yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 1 | #!/usr/bin/python |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 2 | # |
| 3 | # Copyright 2010 Google Inc. All Rights Reserved. |
| 4 | |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 5 | """Script to lock/unlock machines.""" |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 6 | |
| 7 | __author__ = "asharif@google.com (Ahmad Sharif)" |
| 8 | |
| 9 | import datetime |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 10 | import fcntl |
asharif | da8e93b | 2013-02-15 22:49:27 +0000 | [diff] [blame] | 11 | import getpass |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 12 | import glob |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 13 | import json |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 14 | import optparse |
| 15 | import os |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 16 | import socket |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 17 | import sys |
| 18 | import time |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 19 | |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 20 | from utils import logger |
| 21 | |
| 22 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 23 | class FileCreationMask(object): |
| 24 | def __init__(self, mask): |
| 25 | self._mask = mask |
| 26 | |
| 27 | def __enter__(self): |
| 28 | self._old_mask = os.umask(self._mask) |
| 29 | |
| 30 | def __exit__(self, type, value, traceback): |
| 31 | os.umask(self._old_mask) |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 32 | |
| 33 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 34 | class LockDescription(object): |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 35 | """The description of the lock.""" |
| 36 | |
| 37 | def __init__(self, desc): |
| 38 | try: |
| 39 | self.owner = desc["owner"] |
| 40 | self.exclusive = desc["exclusive"] |
| 41 | self.counter = desc["counter"] |
| 42 | self.time = desc["time"] |
| 43 | self.reason = desc["reason"] |
| 44 | except (KeyError, TypeError): |
| 45 | self.owner = "" |
| 46 | self.exclusive = False |
| 47 | self.counter = 0 |
| 48 | self.time = 0 |
| 49 | self.reason = "" |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 50 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 51 | def IsLocked(self): |
| 52 | return self.counter or self.exclusive |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 53 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 54 | def __str__(self): |
| 55 | return " ".join(["Owner: %s" % self.owner, |
| 56 | "Exclusive: %s" % self.exclusive, |
| 57 | "Counter: %s" % self.counter, |
| 58 | "Time: %s" % self.time, |
| 59 | "Reason: %s" % self.reason]) |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 60 | |
| 61 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 62 | class FileLock(object): |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 63 | """File lock operation class.""" |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 64 | |
| 65 | def __init__(self, lock_filename): |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 66 | self._filepath = lock_filename |
| 67 | lock_dir = os.path.dirname(lock_filename) |
| 68 | assert os.path.isdir(lock_dir), ( |
| 69 | "Locks dir: %s doesn't exist!" % lock_dir) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 70 | self._file = None |
| 71 | |
| 72 | @classmethod |
| 73 | def AsString(cls, file_locks): |
| 74 | stringify_fmt = "%-30s %-15s %-4s %-4s %-15s %-40s" |
| 75 | header = stringify_fmt % ("machine", "owner", "excl", "ctr", |
| 76 | "elapsed", "reason") |
| 77 | lock_strings = [] |
| 78 | for file_lock in file_locks: |
| 79 | |
| 80 | elapsed_time = datetime.timedelta( |
| 81 | seconds=int(time.time() - file_lock._description.time)) |
| 82 | elapsed_time = "%s ago" % elapsed_time |
| 83 | lock_strings.append(stringify_fmt % |
| 84 | (os.path.basename(file_lock._filepath), |
| 85 | file_lock._description.owner, |
| 86 | file_lock._description.exclusive, |
| 87 | file_lock._description.counter, |
| 88 | elapsed_time, |
| 89 | file_lock._description.reason)) |
| 90 | table = "\n".join(lock_strings) |
| 91 | return "\n".join([header, table]) |
| 92 | |
| 93 | @classmethod |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 94 | def ListLock(cls, pattern, locks_dir): |
| 95 | if not locks_dir: |
| 96 | locks_dir = Machine.LOCKS_DIR |
| 97 | full_pattern = os.path.join(locks_dir, pattern) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 98 | file_locks = [] |
| 99 | for lock_filename in glob.glob(full_pattern): |
| 100 | file_lock = FileLock(lock_filename) |
| 101 | with file_lock as lock: |
| 102 | if lock.IsLocked(): |
| 103 | file_locks.append(file_lock) |
| 104 | logger.GetLogger().LogOutput("\n%s" % cls.AsString(file_locks)) |
| 105 | |
| 106 | def __enter__(self): |
| 107 | with FileCreationMask(0000): |
| 108 | try: |
| 109 | self._file = open(self._filepath, "a+") |
| 110 | self._file.seek(0, os.SEEK_SET) |
| 111 | |
| 112 | if fcntl.flock(self._file.fileno(), fcntl.LOCK_EX) == -1: |
| 113 | raise IOError("flock(%s, LOCK_EX) failed!" % self._filepath) |
| 114 | |
| 115 | try: |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 116 | desc = json.load(self._file) |
| 117 | except (EOFError, ValueError): |
| 118 | desc = None |
| 119 | self._description = LockDescription(desc) |
| 120 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 121 | return self._description |
| 122 | # Check this differently? |
| 123 | except IOError as ex: |
| 124 | logger.GetLogger().LogError(ex) |
| 125 | return None |
| 126 | |
| 127 | def __exit__(self, type, value, traceback): |
| 128 | self._file.truncate(0) |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 129 | self._file.write(json.dumps(self._description.__dict__, skipkeys=True)) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 130 | self._file.close() |
| 131 | |
| 132 | def __str__(self): |
| 133 | return self.AsString([self]) |
| 134 | |
| 135 | |
| 136 | class Lock(object): |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 137 | def __init__(self, lock_file): |
| 138 | self._to_lock = os.path.basename(lock_file) |
| 139 | self._lock_file = lock_file |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 140 | self._logger = logger.GetLogger() |
| 141 | |
| 142 | def NonBlockingLock(self, exclusive, reason=""): |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 143 | with FileLock(self._lock_file) as lock: |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 144 | if lock.exclusive: |
| 145 | self._logger.LogError( |
| 146 | "Exclusive lock already acquired by %s. Reason: %s" % |
| 147 | (lock.owner, lock.reason)) |
| 148 | return False |
| 149 | |
| 150 | if exclusive: |
| 151 | if lock.counter: |
| 152 | self._logger.LogError("Shared lock already acquired") |
| 153 | return False |
| 154 | lock.exclusive = True |
| 155 | lock.reason = reason |
asharif | da8e93b | 2013-02-15 22:49:27 +0000 | [diff] [blame] | 156 | lock.owner = getpass.getuser() |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 157 | lock.time = time.time() |
| 158 | else: |
| 159 | lock.counter += 1 |
| 160 | self._logger.LogOutput("Successfully locked: %s" % self._to_lock) |
| 161 | return True |
| 162 | |
| 163 | def Unlock(self, exclusive, force=False): |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 164 | with FileLock(self._lock_file) as lock: |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 165 | if not lock.IsLocked(): |
| 166 | self._logger.LogError("Can't unlock unlocked machine!") |
| 167 | return False |
| 168 | |
| 169 | if lock.exclusive != exclusive: |
| 170 | self._logger.LogError("shared locks must be unlocked with --shared") |
| 171 | return False |
| 172 | |
| 173 | if lock.exclusive: |
asharif | da8e93b | 2013-02-15 22:49:27 +0000 | [diff] [blame] | 174 | if lock.owner != getpass.getuser() and not force: |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 175 | self._logger.LogError("%s can't unlock lock owned by: %s" % |
asharif | da8e93b | 2013-02-15 22:49:27 +0000 | [diff] [blame] | 176 | (getpass.getuser(), lock.owner)) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 177 | return False |
| 178 | lock.exclusive = False |
| 179 | lock.reason = "" |
| 180 | lock.owner = "" |
| 181 | else: |
| 182 | lock.counter -= 1 |
| 183 | return True |
| 184 | |
| 185 | |
| 186 | class Machine(object): |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 187 | LOCKS_DIR = "/home/mobiletc-prebuild/locks" |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 188 | |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 189 | def __init__(self, name, locks_dir=LOCKS_DIR): |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 190 | self._name = name |
| 191 | try: |
| 192 | self._full_name = socket.gethostbyaddr(name)[0] |
| 193 | except socket.error: |
| 194 | self._full_name = self._name |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 195 | self._full_name = os.path.join(locks_dir, self._full_name) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 196 | |
| 197 | def Lock(self, exclusive=False, reason=""): |
| 198 | lock = Lock(self._full_name) |
| 199 | return lock.NonBlockingLock(exclusive, reason) |
| 200 | |
shenhan | e0a6d8a | 2013-02-19 20:42:29 +0000 | [diff] [blame] | 201 | def TryLock(self, timeout=300, exclusive=False, reason=""): |
| 202 | locked = False |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 203 | sleep = timeout / 10 |
shenhan | e0a6d8a | 2013-02-19 20:42:29 +0000 | [diff] [blame] | 204 | while True: |
| 205 | locked = self.Lock(exclusive, reason) |
| 206 | if locked or not timeout >= 0: |
| 207 | break |
| 208 | print "Lock not acquired for {0}, wait {1} seconds ...".format( |
yunlian | 8a3bdcb | 2013-02-19 20:42:48 +0000 | [diff] [blame^] | 209 | self._name, sleep) |
shenhan | e0a6d8a | 2013-02-19 20:42:29 +0000 | [diff] [blame] | 210 | time.sleep(sleep) |
| 211 | timeout -= sleep |
| 212 | return locked |
| 213 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 214 | def Unlock(self, exclusive=False, ignore_ownership=False): |
| 215 | lock = Lock(self._full_name) |
| 216 | return lock.Unlock(exclusive, ignore_ownership) |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 217 | |
| 218 | |
| 219 | def Main(argv): |
| 220 | """The main function.""" |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 221 | parser = optparse.OptionParser() |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 222 | parser.add_option("-r", |
| 223 | "--reason", |
| 224 | dest="reason", |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 225 | default="", |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 226 | help="The lock reason.") |
| 227 | parser.add_option("-u", |
| 228 | "--unlock", |
| 229 | dest="unlock", |
| 230 | action="store_true", |
| 231 | default=False, |
| 232 | help="Use this to unlock.") |
| 233 | parser.add_option("-l", |
| 234 | "--list_locks", |
| 235 | dest="list_locks", |
| 236 | action="store_true", |
| 237 | default=False, |
| 238 | help="Use this to list locks.") |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 239 | parser.add_option("-f", |
| 240 | "--ignore_ownership", |
| 241 | dest="ignore_ownership", |
| 242 | action="store_true", |
| 243 | default=False, |
| 244 | help="Use this to force unlock on a lock you don't own.") |
| 245 | parser.add_option("-s", |
| 246 | "--shared", |
| 247 | dest="shared", |
| 248 | action="store_true", |
| 249 | default=False, |
| 250 | help="Use this for a shared (non-exclusive) lock.") |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 251 | parser.add_option("-d", |
| 252 | "--dir", |
| 253 | dest="locks_dir", |
| 254 | action="store", |
| 255 | default=Machine.LOCKS_DIR, |
| 256 | help="Use this to set different locks_dir") |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 257 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 258 | options, args = parser.parse_args(argv) |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 259 | |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 260 | options.locks_dir = os.path.abspath(options.locks_dir) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 261 | exclusive = not options.shared |
| 262 | |
| 263 | if not options.list_locks and len(args) != 2: |
| 264 | logger.GetLogger().LogError( |
| 265 | "Either --list_locks or a machine arg is needed.") |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 266 | return 1 |
| 267 | |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 268 | if len(args) > 1: |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 269 | machine = Machine(args[1], options.locks_dir) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 270 | else: |
| 271 | machine = None |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 272 | |
| 273 | if options.list_locks: |
yunlian | 52a6c57 | 2013-02-19 20:42:07 +0000 | [diff] [blame] | 274 | FileLock.ListLock("*", options.locks_dir) |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 275 | retval = True |
| 276 | elif options.unlock: |
| 277 | retval = machine.Unlock(exclusive, options.ignore_ownership) |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 278 | else: |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 279 | retval = machine.Lock(exclusive, options.reason) |
| 280 | |
| 281 | if retval: |
| 282 | return 0 |
| 283 | else: |
| 284 | return 1 |
asharif | b237bca | 2013-02-15 20:54:57 +0000 | [diff] [blame] | 285 | |
| 286 | if __name__ == "__main__": |
asharif | 455157b | 2013-02-15 21:15:05 +0000 | [diff] [blame] | 287 | sys.exit(Main(sys.argv)) |