1# Copyright 2015 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import time
6import uuid
7
8from autotest_lib.client.common_lib import error
9from autotest_lib.client.common_lib.cros import process_watcher
10from autotest_lib.client.common_lib.cros.fake_device_server.client_lib import \
11        meta
12
13
14class FakeGCDHelper(object):
15    """Helper object that knows how to bring up and kill fake GCD instances."""
16
17    def __init__(self, host=None):
18        """Construct an instance.
19
20        @param host: host object if the server should be started on a remote
21                host.
22
23        """
24        self._generation = str(uuid.uuid1())
25        self._process = process_watcher.ProcessWatcher(
26                '/usr/local/autotest/common_lib/cros/'
27                        'fake_device_server/server.py',
28                args=(self._generation,),
29                host=host)
30        self._meta = meta.MetaClient()
31
32
33    def start(self, timeout_seconds=30):
34        """Start this instance and confirm that it is up.
35
36        @param timeout_seconds: number of seconds to wait for server start.
37
38        """
39        self._process.start()
40        start_time = time.time()
41        while time.time() - start_time < timeout_seconds:
42            received_generation = self._meta.get_generation()
43            if self._generation == received_generation:
44                return
45            time.sleep(1)
46
47        raise error.TestError('Failed to start fake GCD server.')
48
49
50    def close(self):
51        """Close this instance."""
52        self._process.close()
53