1 # Copyright 2015 The Chromium 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.
5 """Defines the task controller library."""
18 #pylint: disable=relative-import
21 ISOLATE_PY
= os
.path
.join(common_lib
.SWARMING_DIR
, 'isolate.py')
22 SWARMING_PY
= os
.path
.join(common_lib
.SWARMING_DIR
, 'swarming.py')
25 class Error(Exception):
29 class ConnectionTimeoutError(Error
):
33 class TaskController(object):
34 """Provisions, configures, and controls a task machine.
36 This class is an abstraction of a physical task machine. It provides an
37 end to end API for controlling a task machine. Operations on the task machine
38 are performed using the instance's "rpc" property. A simple end to end
39 scenario is as follows:
41 task = TaskController(...)
43 task.WaitForConnection()
44 proc = task.rpc.subprocess.Popen(['ls'])
45 print task.rpc.subprocess.GetStdout(proc)
52 def __init__(self
, isolated_hash
, dimensions
, priority
=100,
53 idle_timeout_secs
=common_lib
.DEFAULT_TIMEOUT_SECS
,
54 connection_timeout_secs
=common_lib
.DEFAULT_TIMEOUT_SECS
,
55 verbosity
='ERROR', name
=None, run_id
=None):
56 assert isinstance(dimensions
, dict)
57 type(self
)._tasks
.append(self
)
58 type(self
)._task
_count
+= 1
59 self
.verbosity
= verbosity
60 self
._name
= name
or 'Task%d' % type(self
)._task
_count
61 self
._priority
= priority
62 self
._isolated
_hash
= isolated_hash
63 self
._idle
_timeout
_secs
= idle_timeout_secs
64 self
._dimensions
= dimensions
65 self
._connect
_event
= threading
.Event()
66 self
._connected
= False
67 self
._ip
_address
= None
68 self
._otp
= self
._CreateOTP
()
71 run_id
= run_id
or datetime
.datetime
.now().strftime('%Y-%m-%d-%H-%M-%S')
72 self
._task
_name
= '%s/%s/%s' % (
73 os
.path
.splitext(sys
.argv
[0])[0], self
._name
, run_id
)
75 parser
= argparse
.ArgumentParser()
76 parser
.add_argument('--isolate-server')
77 parser
.add_argument('--swarming-server')
78 parser
.add_argument('--task-connection-timeout-secs',
79 default
=common_lib
.DEFAULT_TIMEOUT_SECS
)
80 args
, _
= parser
.parse_known_args()
82 self
._isolate
_server
= args
.isolate_server
83 self
._swarming
_server
= args
.swarming_server
84 self
._connection
_timeout
_secs
= (connection_timeout_secs
or
85 args
.task_connection_timeout_secs
)
97 return self
._connected
100 def connect_event(self
):
101 return self
._connect
_event
109 return self
._verbosity
112 def verbosity(self
, level
):
113 """Sets the verbosity level as a string.
115 Either a string ('INFO', 'DEBUG', etc) or a logging level (logging.INFO,
116 logging.DEBUG, etc) is allowed.
118 assert isinstance(level
, (str, int))
119 if isinstance(level
, int):
120 level
= logging
.getLevelName(level
)
121 self
._verbosity
= level
#pylint: disable=attribute-defined-outside-init
124 def ReleaseAllTasks(cls
):
125 for task
in cls
._tasks
:
128 def _CreateOTP(self
):
129 """Creates the OTP."""
130 controller_name
= socket
.gethostname()
131 test_name
= os
.path
.basename(sys
.argv
[0])
132 creation_time
= datetime
.datetime
.utcnow()
133 otp
= 'task:%s controller:%s test:%s creation:%s' % (
134 self
._name
, controller_name
, test_name
, creation_time
)
138 """Creates the task machine."""
139 logging
.info('Creating %s', self
.name
)
140 self
._connect
_event
.clear()
141 self
._ExecuteSwarming
()
143 def WaitForConnection(self
):
144 """Waits for the task machine to connect.
147 ConnectionTimeoutError if the task doesn't connect in time.
149 logging
.info('Waiting for %s to connect with a timeout of %d seconds',
150 self
._name
, self
._connection
_timeout
_secs
)
151 self
._connect
_event
.wait(self
._connection
_timeout
_secs
)
152 if not self
._connect
_event
.is_set():
153 raise ConnectionTimeoutError('%s failed to connect' % self
.name
)
156 """Quits the task's RPC server so it can release the machine."""
157 if self
._rpc
is not None and self
._connected
:
158 logging
.info('Releasing %s', self
._name
)
161 except (socket
.error
, xmlrpclib
.Fault
):
162 logging
.error('Unable to connect to %s to call Quit', self
.name
)
164 self
._connected
= False
166 def _ExecuteSwarming(self
):
167 """Executes swarming.py."""
173 '--priority', str(self
._priority
),
174 '--task-name', self
._task
_name
,
177 if self
._isolate
_server
:
178 cmd
.extend(['--isolate-server', self
._isolate
_server
])
179 if self
._swarming
_server
:
180 cmd
.extend(['--swarming', self
._swarming
_server
])
181 for key
, value
in self
._dimensions
.iteritems():
182 cmd
.extend(['--dimension', key
, value
])
186 '--controller', common_lib
.MY_IP
,
188 '--verbosity', self
._verbosity
,
189 '--idle-timeout', str(self
._idle
_timeout
_secs
),
192 self
._ExecuteProcess
(cmd
)
194 def _ExecuteProcess(self
, cmd
):
195 """Executes a process, waits for it to complete, and checks for success."""
196 logging
.debug('Running %s', ' '.join(cmd
))
197 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
198 _
, stderr
= p
.communicate()
199 if p
.returncode
!= 0:
202 def OnConnect(self
, ip_address
):
203 """Receives task ip address on connection."""
204 self
._ip
_address
= ip_address
205 self
._connected
= True
206 self
._rpc
= common_lib
.ConnectToServer(self
._ip
_address
)
207 logging
.info('%s connected from %s', self
._name
, ip_address
)
208 self
._connect
_event
.set()