1# Copyright 2015 The Chromium OS Authors. All rights reserved.
2"""Utilities for locking machines."""
3
4from __future__ import print_function
5
6import time
7
8import afe_lock_machine
9
10import logger
11
12
13def AcquireLock(machines, chromeos_root, timeout=1200):
14  """Acquire lock for machine(s) with timeout, using AFE server for locking."""
15  start_time = time.time()
16  locked = True
17  sleep_time = min(10, timeout / 10.0)
18  while True:
19    try:
20      afe_lock_machine.AFELockManager(machines, False, chromeos_root,
21                                      None).UpdateMachines(True)
22      break
23    except Exception as e:
24      if time.time() - start_time > timeout:
25        locked = False
26        logger.GetLogger().LogWarning(
27            'Could not acquire lock on {0} within {1} seconds: {2}'.format(
28                repr(machines), timeout, str(e)))
29        break
30      time.sleep(sleep_time)
31  return locked
32
33
34def ReleaseLock(machines, chromeos_root):
35  """Release locked machine(s), using AFE server for locking."""
36  unlocked = True
37  try:
38    afe_lock_machine.AFELockManager(machines, False, chromeos_root,
39                                    None).UpdateMachines(False)
40  except Exception as e:
41    unlocked = False
42    logger.GetLogger().LogWarning('Could not unlock %s. %s' %
43                                  (repr(machines), str(e)))
44  return unlocked
45