1# -*- coding: utf-8 -*- 2# 3# Copyright 2019 The ChromiumOS Authors 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6 7"""Utilities for locking machines.""" 8 9 10import time 11 12from cros_utils import logger 13import lock_machine 14 15 16def AcquireLock(machines, chromeos_root, timeout=1200): 17 """Acquire lock for machine(s) with timeout.""" 18 start_time = time.time() 19 locked = True 20 sleep_time = min(10, timeout / 10.0) 21 while True: 22 try: 23 lock_machine.LockManager( 24 machines, False, chromeos_root 25 ).UpdateMachines(True) 26 break 27 except Exception as e: 28 if time.time() - start_time > timeout: 29 locked = False 30 logger.GetLogger().LogWarning( 31 "Could not acquire lock on {0} within {1} seconds: {2}".format( 32 repr(machines), timeout, str(e) 33 ) 34 ) 35 break 36 time.sleep(sleep_time) 37 return locked 38 39 40def ReleaseLock(machines, chromeos_root): 41 """Release locked machine(s).""" 42 unlocked = True 43 try: 44 lock_machine.LockManager(machines, False, chromeos_root).UpdateMachines( 45 False 46 ) 47 except Exception as e: 48 unlocked = False 49 logger.GetLogger().LogWarning( 50 "Could not unlock %s. %s" % (repr(machines), str(e)) 51 ) 52 return unlocked 53