forked from mozilla/autophone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autophone.py
executable file
·1516 lines (1392 loc) · 66.3 KB
/
autophone.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import ConfigParser
import Queue
import SocketServer
import datetime
import errno
import inspect
import json
import logging
import logging.handlers
import multiprocessing
import os
import re
import signal
import socket
import subprocess
import sys
import threading
import traceback
import pytz
from manifestparser import TestManifest
import builds
import buildserver
import jobs
import utils
from adb import ADBHost
from adb_android import ADBAndroid
from autophonepulsemonitor import AutophonePulseMonitor
from autophonetreeherder import AutophoneTreeherder
from mailer import Mailer
from options import AutophoneOptions
from phonestatus import PhoneStatus
from phonetest import PhoneTest
from process_states import ProcessStates
from sensitivedatafilter import SensitiveDataFilter
from worker import PhoneWorker
LOGGER = None
CONSOLE_LOGGER = None
class PhoneData(object):
def __init__(self, phoneid, serial, machinetype, osver, abi, sdk, supported_sdks, ipaddr):
self.id = phoneid
self.serial = serial
self.machinetype = machinetype
self.osver = osver
self.abi = abi
self.sdk = sdk
self.supported_sdks = supported_sdks
self.host_ip = ipaddr
@property
def os(self):
return 'android-%s' % '-'.join(self.osver.split('.')[:2])
def __str__(self):
return '%s' % self.__dict__
class AutoPhone(object):
class CmdTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
allow_reuse_address = True
daemon_threads = True
cmd_cb = None
class CmdTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
buff = ''
self.request.send('Hello? Yes this is Autophone.\n')
while True:
try:
data = self.request.recv(1024)
except socket.error, e:
if e.errno == errno.ECONNRESET:
break
raise e
if not data:
break
buff += data
while buff:
line, nl, rest = buff.partition('\n')
if not nl:
break
buff = rest
line = line.strip()
if not line:
continue
if line == 'quit' or line == 'exit':
return
response = self.server.cmd_cb(line)
self.request.send(response + '\n')
def __init__(self, loglevel, options):
self.state = ProcessStates.STARTING
self.unrecoverable_error = False
self.options = options
self.loglevel = loglevel
self.mailer = Mailer(options.emailcfg, '[autophone] ')
self._next_worker_num = 0
self.jobs = jobs.Jobs(self.mailer,
allow_duplicates=options.allow_duplicate_jobs)
self.phone_workers = {} # indexed by phone id
self.lock = threading.RLock()
self.shared_lock = multiprocessing.Lock()
self._tests = []
self._devices = {} # dict indexed by device names found in devices ini file
self.server = None
self.server_thread = None
self.treeherder_thread = None
self.pulse_monitor = None
self.restart_workers = {}
self.treeherder = AutophoneTreeherder(None,
self.options,
self.jobs,
mailer=self.mailer,
shared_lock=self.shared_lock)
CONSOLE_LOGGER.info('Starting autophone.')
# Queue for listening to status updates from
# PhoneWorkerSubProcess workers.
self.queue = multiprocessing.Queue()
CONSOLE_LOGGER.info('Loading tests.')
self.read_tests()
CONSOLE_LOGGER.info('Initializing devices.')
self.read_devices()
self.state = ProcessStates.RUNNING
for worker in self.phone_workers.values():
worker.start()
# We must wait to start the pulse monitor until after the
# workers have started in order to make certain that the
# shared_lock is passed to the worker subprocesses in an
# unlocked state.
if options.enable_pulse:
self.pulse_monitor = AutophonePulseMonitor(
userid=options.pulse_user,
password=options.pulse_password,
jobaction_exchange_name=options.pulse_jobactions_exchange,
build_callback=self.on_build,
jobaction_callback=self.on_jobaction,
treeherder_url=self.options.treeherder_url,
trees=options.repos,
platforms=['android',
'android-api-9',
'android-api-10',
'android-api-11',
'android-api-15',
'android-x86'],
buildtypes=options.buildtypes,
durable_queues=self.options.pulse_durable_queue,
shared_lock=self.shared_lock,
verbose=options.verbose)
self.pulse_monitor.start()
LOGGER.debug('autophone_options: %s', self.options)
CONSOLE_LOGGER.info('Autophone started.')
if self.options.reboot_on_error:
msg_subj = 'Starting %s' % utils.host()
msg_body = ('Hello, this is Autophone. '
'Just to let you know, I have started running. '
'Wish me luck and check on me from time to time. '
'I will send you emails if I have any problems.\n\n')
self.mailer.send(msg_subj, msg_body)
def _get_frames(self):
"""Return the stack to the current location"""
frames = traceback.format_list(traceback.extract_stack())
return ''.join(frames[:-2])
def lock_acquire(self, data=None):
if LOGGER.getEffectiveLevel() == logging.DEBUG:
if self.options.verbose:
LOGGER.debug('lock_acquire: %s\n%s', data, self._get_frames())
self.lock.acquire()
def lock_release(self, data=None):
if LOGGER.getEffectiveLevel() == logging.DEBUG:
if self.options.verbose:
LOGGER.debug('lock_release: %s\n%s', data, self._get_frames())
self.lock.release()
@property
def next_worker_num(self):
n = self._next_worker_num
self._next_worker_num += 1
return n
def run(self):
self.server = self.CmdTCPServer(('0.0.0.0', self.options.port),
self.CmdTCPHandler)
self.server.cmd_cb = self.route_cmd
self.server_thread = threading.Thread(target=self.server.serve_forever,
name='CmdTCPThread')
self.server_thread.daemon = True
self.server_thread.start()
if self.options.treeherder_url:
self.treeherder_thread = threading.Thread(
target=self.treeherder.serve_forever,
name='TreeherderThread')
self.treeherder_thread.daemon = True
self.treeherder_thread.start()
self.worker_msg_loop()
def check_for_dead_workers(self):
if self.state != ProcessStates.RUNNING:
return
workers = self.phone_workers.values()
for worker in workers:
if not worker.is_alive():
phoneid = worker.phone.id
LOGGER.debug('Worker %s %s is not alive', phoneid, worker.state)
if phoneid in self.restart_workers:
initial_state = PhoneStatus.IDLE
LOGGER.info('Worker %s exited; restarting with new values.', phoneid)
elif worker.state == ProcessStates.STOPPING:
# The device will be removed and not restarted.
initial_state = None
elif worker.state == ProcessStates.RESTARTING:
initial_state = PhoneStatus.IDLE
else:
CONSOLE_LOGGER.error('Worker %s died!', phoneid)
msg_subj = '%s worker %s died' % (utils.host(), phoneid)
msg_body = ('Hello, this is Autophone. '
'Just to let you know, '
'the worker process '
'for phone %s died.\n' %
phoneid)
if worker.crashes.too_many_crashes():
initial_state = PhoneStatus.DISABLED
msg_subj += ' and was disabled'
msg_body += (
'It looks really crashy, so I disabled it. '
'Sorry about that.\n\n')
else:
initial_state = PhoneStatus.DISCONNECTED
LOGGER.info('Sending notification...')
self.mailer.send(msg_subj, msg_body)
# Have to remove the tests for the worker prior to
# removing or recreating it in order to remove it from
# the PhoneTest.instances.
while worker.tests:
t = worker.tests.pop()
t.remove()
# Do we need to worry about a race between the pulse
# monitor locking the shared lock?
if worker.state == ProcessStates.STOPPING:
CONSOLE_LOGGER.info('Worker %s stopped', phoneid)
del self.phone_workers[phoneid]
else:
if worker.state == ProcessStates.RESTARTING:
# The device is being restarted with a
# potentially changed test manifest and
# changed test configurations. The changes to
# the test configuration files will be
# automatically picked up when the tests are
# recreated for the worker, but we must
# reparse the test manifest in order for the
# worker to pick up test manifest changes. We
# re-read the tests here, to update
# self._tests which will be incorporated into
# the new worker instance. If a worker dies
# and is restarted, it will automatically pick
# up these changes as well.
self.read_tests()
# We can not re-use the original worker instance
# since we need to recreate the
# multiprocessing.Process object before we can
# call start on it again.
CONSOLE_LOGGER.info('Worker %s restarting', phoneid)
# Save the record of crashes before recreating the
# Worker, then restore it afterwards.
crashes = worker.crashes
try:
new_worker = self.create_worker(worker.phone)
new_worker.crashes = crashes
new_worker.start(initial_state)
except Exception, e:
CONSOLE_LOGGER.info('Worker %s failed to restart',
phoneid)
msg_subj = ('%s worker %s failed to restart' %
(utils.host(), phoneid))
msg_body = ('Hello, this is Autophone. '
'Just to let you know, '
'the worker process '
'for phone %s '
'failed to restart due to %s.\n' %
(phoneid, e))
self.mailer.send(msg_subj, msg_body)
self.purge_worker(phoneid)
def check_for_unrecoverable_errors(self):
"""Set the property unrecoverable_error to True if any devices have
lost usb connectivity or not updated their status within the
maximum allowed heartbeat time period. Forcefully stop any
workers which have exceeded the maximum heartbeat time.
"""
for worker in self.phone_workers.values():
if not worker.last_status_msg:
continue
if worker.last_status_msg.phone_status == PhoneStatus.DISCONNECTED:
self.unrecoverable_error = True
# Do not check the last timestamp of a worker that
# is currently downloading a build due to the size
# of the downloads and the unknown network speed.
elapsed = datetime.datetime.now(tz=pytz.utc) - worker.last_status_msg.timestamp
if worker.last_status_msg.phone_status != PhoneStatus.FETCHING and \
elapsed > datetime.timedelta(seconds=self.options.maximum_heartbeat):
self.unrecoverable_error = True
worker.stop()
def worker_msg_loop(self):
self.lock_acquire()
try:
while self.phone_workers and self.state != ProcessStates.STOPPING:
if self.options.reboot_on_error:
self.check_for_unrecoverable_errors()
if self.unrecoverable_error and self.state != ProcessStates.SHUTTINGDOWN:
self.shutdown()
self.check_for_dead_workers()
if self.state == ProcessStates.RUNNING and self.pulse_monitor and \
not self.pulse_monitor.is_alive():
self.pulse_monitor.start()
# Temporarily release the lock while we are waiting
# for a message from the workers.
self.lock_release()
try:
msg = self.queue.get(timeout=5)
except Queue.Empty:
continue
except IOError, e:
if e.errno == errno.EINTR:
continue
finally:
# Reacquire the lock.
self.lock_acquire()
if msg.phone.id not in self.phone_workers:
LOGGER.warning('Received message %s '
'from Non-existent worker', msg)
continue
self.phone_workers[msg.phone.id].process_msg(msg)
if msg.phone_status == PhoneStatus.SHUTDOWN:
# Have to remove the tests for the worker prior to
# removing it in order to remove it from the
# PhoneTest.instances so that it will not appear
# in future PhoneTest.match results.
worker = self.phone_workers[msg.phone.id]
while worker.tests:
t = worker.tests.pop()
t.remove()
if worker.state == ProcessStates.SHUTTINGDOWN:
# We are completely shutting down the device
# so we delete it from the phone_workers
# dictionary. Otherwise, the phone will be
# detected as dead and will be restarted.
del self.phone_workers[msg.phone.id]
CONSOLE_LOGGER.info('Worker %s shutdown', msg.phone.id)
except KeyboardInterrupt:
pass
finally:
if self.pulse_monitor:
self.pulse_monitor.stop()
self.pulse_monitor = None
if self.server:
self.server.shutdown()
if self.server_thread:
self.server_thread.join()
if self.options.treeherder_url:
self.treeherder.shutdown()
if self.treeherder_thread:
self.treeherder_thread.join()
for p in self.phone_workers.values():
p.stop()
self.lock_release()
if self.unrecoverable_error and self.options.reboot_on_error:
CONSOLE_LOGGER.info('Rebooting due to unrecoverable errors')
msg_subj = 'Rebooting %s due to unrecoverable errors' % utils.host()
msg_body = ('Hello, this is Autophone. '
'Just to let you know, I have experienced '
'unrecoverable device errors and am rebooting in '
'the hope of resolving them.\n\n'
'Please check on me.\n')
self.mailer.send(msg_subj, msg_body)
subprocess.call('sudo reboot', shell=True)
if self.state == ProcessStates.RESTARTING:
# Lifted from Sisyphus/Bughunter...
newargv = sys.argv
newargv.insert(0, sys.executable)
# Set all open file handlers to close on exec. Use 64K as
# the limit to check as that is the max on Windows XP. The
# performance issue of doing this is negligible since it
# is only run during a program reload.
from fcntl import fcntl, F_GETFD, F_SETFD, FD_CLOEXEC
for fd in xrange(0x3, 0x10000):
try:
fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC)
except KeyboardInterrupt:
raise
except:
pass
while True:
try:
(pid, status, resource) = os.wait3(os.WNOHANG)
LOGGER.debug('Reaped %s %s', pid, status)
except OSError:
break
os.execvp(sys.executable, newargv)
# Start the phones for testing
def new_job(self, job_data):
LOGGER.debug('new_job: %s', job_data)
build_url = job_data['build']
tests = job_data['tests']
phoneids = set([test.phone.id for test in tests])
for phoneid in phoneids:
p = self.phone_workers[phoneid]
LOGGER.debug('new_job: worker phoneid %s', phoneid)
# Determine if we will test this build, which tests to run and if we
# need to enable unittests.
runnable_tests = PhoneTest.match(tests=tests,
phoneid=phoneid,
repo=job_data['repo'],
build_type=job_data['build_type'],
build_abi=job_data['abi'],
build_sdk=job_data['sdk'])
if not runnable_tests:
LOGGER.debug('new_job: Ignoring build %s for phone %s', build_url, phoneid)
continue
enable_unittests = False
for t in runnable_tests:
enable_unittests = enable_unittests or t.enable_unittests
new_tests = self.jobs.new_job(build_url,
build_id=job_data['build_id'],
build_type=job_data['build_type'],
build_platform=job_data['platform'],
build_abi=job_data['abi'],
build_sdk=job_data['sdk'],
tree=job_data['repo'],
changeset=job_data['changeset'],
changeset_dirs=job_data['changeset_dirs'],
revision=job_data['revision'],
builder_type=job_data['builder_type'],
tests=runnable_tests,
enable_unittests=enable_unittests,
device=phoneid)
if new_tests:
self.treeherder.submit_pending(phoneid,
build_url,
job_data['repo'],
job_data['revision'],
job_data['build_type'],
job_data['platform'],
job_data['abi'],
job_data['sdk'],
job_data['builder_type'],
tests=new_tests)
LOGGER.info('new_job: Notifying device %s of new job '
'%s for tests %s, enable_unittests=%s.',
phoneid, build_url, runnable_tests,
enable_unittests)
p.new_job()
def route_cmd(self, data):
response = ''
self.lock_acquire(data=data)
try:
response = self._route_cmd(data)
finally:
self.lock_release(data=data)
return response
def _route_cmd(self, data):
# There is not currently any way to get proper responses for commands
# that interact with workers, since communication between the main
# process and the worker processes is asynchronous.
# It would be possible but nontrivial for the workers to put responses
# onto a queue and have them routed to the proper connection by using
# request IDs or something like that.
LOGGER.debug('route_cmd: %s', data)
data = data.strip()
cmd, space, params = data.partition(' ')
cmd = cmd.lower()
response = 'ok'
if cmd.startswith('device-'):
# Device commands have prefix device- and are mapped into
# PhoneWorker methods by stripping the leading 'device-'
# from the command. The device id is the first parameter.
valid_cmds = ('is_alive', 'stop', 'shutdown', 'reboot', 'disable',
'enable', 'ping', 'status', 'restart')
cmd = cmd.replace('device-', '').replace('-', '_')
if cmd not in valid_cmds:
response = 'Unknown command device-%s' % cmd
else:
phoneid, space, params = params.partition(' ')
response = 'error: phone not found'
for worker in self.phone_workers.values():
if phoneid.lower() == 'all' or worker.phone.serial == phoneid or \
worker.phone.id == phoneid:
f = getattr(worker, cmd)
if params:
value = f(params)
else:
value = f()
if value is not None:
response = '%s\n' % value
else:
response = ''
response += 'ok'
elif cmd == 'autophone-add-device':
phoneid, space, serialno = params.partition(' ')
if phoneid in self.phone_workers:
response = 'device %s already exists' % phoneid
CONSOLE_LOGGER.warning(response)
else:
self.read_devices(new_device_name=phoneid)
self.phone_workers[phoneid].start()
elif cmd == 'autophone-restart':
self.state = ProcessStates.RESTARTING
CONSOLE_LOGGER.info('Restarting Autophone...')
for worker in self.phone_workers.values():
worker.shutdown()
elif cmd == 'autophone-stop':
CONSOLE_LOGGER.info('Stopping Autophone...')
self.stop()
elif cmd == 'autophone-shutdown':
CONSOLE_LOGGER.info('Shutting down Autophone...')
self.shutdown()
elif cmd == 'autophone-log':
LOGGER.info(params)
elif cmd == 'autophone-triggerjobs':
response = self.trigger_jobs(params)
elif cmd == 'autophone-status':
response = 'state: %s\n' % self.state
phoneids = self.phone_workers.keys()
phoneids.sort()
for i in phoneids:
response += self.phone_workers[i].status()
response += 'ok'
elif cmd == 'autophone-help':
response = '''
Autophone command help:
autophone-help
Generate this message.
autophone-add-device <devicename> <serialno>
Adds a new device to the active workers. <devicename> refers to
the name given to the device in the devices.ini file while
<serialno> is its adb serial number.
autophone-restart
Shutdown each worker after its current test, then restart
autophone.
autophone-shutdown
Shutdown each worker after its current test, then
shutdown autophone.
autophone-status
Generate a status report for each device.
autophone-stop
Immediately stop autophone and all worker processes; may be
delayed by pending download.
device-disable <devicename>
Disable the device's worker and cancel its pending jobs.
device-enable <devicename>
Enable a disabled device's worker.
device-is-alive <devicename>
Check if the device's worker process is alive, report to log.
device-ping <devicename>
Issue a ping command to the device's worker which checks the sdcard
availability.
device-reboot <devicename>
Reboot the device.
device-restart <devicename>
Shutdown the device's worker process after the current test, then
restart the worker picking up test manifest and test configuration
changes.
device-status <devicename>
Generate a status report for the device's worker.
device-shutdown <devicename>
Shutdown the device's worker process after the current test. The
device's worker process will not be restarted and will be removed
from the active list of workers.
device-stop <devicename>
Immediately stop the device's worker process and remove it from the
list of active workers.
ok
'''
else:
response = 'Unknown command "%s"\n' % cmd
return response
def create_worker(self, phone):
LOGGER.info('Creating worker for %s: %s.', phone, self.options)
dm = self._devices[phone.id]['dm']
tests = []
for test_class, config_file, test_devices_repos in self._tests:
LOGGER.debug('create_worker: %s %s %s',
test_class, config_file, test_devices_repos)
skip_test = True
if not test_devices_repos:
# There is no restriction on this test being run by
# specific devices.
repos = []
skip_test = False
elif phone.id in test_devices_repos:
# This test is to be run by this device on
# the repos test_devices_repos[phone.id]
repos = test_devices_repos[phone.id]
skip_test = False
if not skip_test:
test = test_class(dm=dm,
phone=phone,
options=self.options,
config_file=config_file,
repos=repos)
tests.append(test)
for chunk in range(2, test.chunks+1):
LOGGER.debug('Creating chunk %d/%d', chunk, test.chunks)
tests.append(test_class(dm=dm,
phone=phone,
options=self.options,
config_file=config_file,
chunk=chunk,
repos=repos))
if not tests:
LOGGER.warning('Not creating worker: No tests defined for '
'worker for %s: %s.',
phone, self.options)
return
logfile_prefix = os.path.splitext(self.options.logfile)[0]
worker = PhoneWorker(dm, self.next_worker_num,
tests, phone, self.options,
self.queue,
'%s-%s' % (logfile_prefix, phone.id),
self.loglevel, self.mailer, self.shared_lock)
self.phone_workers[phone.id] = worker
return worker
def purge_worker(self, phoneid):
"""Remove worker and its tests from cached locations."""
if phoneid in self.phone_workers:
del self.phone_workers[phoneid]
if phoneid in self.restart_workers:
del self.restart_workers[phoneid]
for t in PhoneTest.match(phoneid=phoneid):
t.remove()
def register_cmd(self, data):
# Map MAC Address to ip and user name for phone
# The configparser does odd things with the :'s so remove them.
phoneid = data['device_name']
phone = PhoneData(
phoneid,
data['serialno'],
data['hardware'],
data['osver'],
data['abi'],
data['sdk'],
data['supported_sdks'],
self.options.ipaddr) # XXX IPADDR no longer needed?
if LOGGER.getEffectiveLevel() == logging.DEBUG:
LOGGER.debug('register_cmd: phone: %s', phone)
if phoneid in self.phone_workers:
LOGGER.debug('Received registration message for known phone %s.', phoneid)
worker = self.phone_workers[phoneid]
if worker.phone.__dict__ != phone.__dict__:
# This won't update the subprocess, but it will allow
# us to write out the updated values right away.
worker.phone = phone
LOGGER.info('Registration info has changed; restarting worker.')
if phoneid in self.restart_workers:
LOGGER.info('Phone worker is already scheduled to be restarted!')
else:
self.restart_workers[phoneid] = phone
worker.stop()
else:
try:
self.create_worker(phone)
LOGGER.info('Registered phone %s.', phone.id)
except Exception:
CONSOLE_LOGGER.info('Worker %s failed to register', phoneid)
self.purge_worker(phoneid)
raise
def read_devices(self, new_device_name=None):
"""Read the devices.ini file and create a corresponding ADBAndroid dm
instance to manage each of the devices listed.
When called without a new_device_name argument, read_devices()
will register all devices currently specified in the
devices.ini file.
When called with a new_device_name argument specifying the
name of a device, read_devices(new_device_name="devicename")
will register only that device and will reload the tests from
the test manifest in order to pick up the tests for the newly
added device.
"""
cfg = ConfigParser.RawConfigParser()
cfg.read(self.options.devicescfg)
if new_device_name:
devices = [new_device_name]
else:
devices = cfg.sections()
for device_name in devices:
# failure for a device to have a serialno option is fatal.
serialno = cfg.get(device_name, 'serialno')
if cfg.has_option(device_name, 'test_root'):
test_root = cfg.get(device_name, 'test_root')
else:
test_root = self.options.device_test_root
CONSOLE_LOGGER.info("Initializing device name=%s, serialno=%s", device_name, serialno)
try:
dm = ADBAndroid(
device=serialno,
device_ready_retry_wait=self.options.device_ready_retry_wait,
device_ready_retry_attempts=self.options.device_ready_retry_attempts,
verbose=self.options.verbose,
test_root=test_root)
device = {"device_name": device_name,
"serialno": serialno,
"dm" : dm}
device['osver'] = dm.get_prop('ro.build.version.release')
device['hardware'] = dm.get_prop('ro.product.model')
device['abi'] = dm.get_prop('ro.product.cpu.abi')
try:
sdk = int(dm.get_prop('ro.build.version.sdk'))
device['sdk'] = 'api-%s' % sdk
if sdk <= 10:
device['supported_sdks'] = 'api-9,api-10'
elif sdk < 15:
device['supported_sdks'] = 'api-11'
else:
device['supported_sdks'] = 'api-11,api-15'
except ValueError:
device['supported_sdks'] = 'api-9'
self._devices[device_name] = device
if new_device_name:
self.read_tests()
self.register_cmd(device)
except Exception, e:
CONSOLE_LOGGER.error('Unable to initialize device %s due to %s.',
device_name, e)
msg_subj = '%s unable to initialize device %s' % (utils.host(),
device_name)
msg_body = ('Hello, this is Autophone. '
'Just to let you know, '
'phone %s '
'failed to initialize due to %s.\n' %
(device_name, e))
self.mailer.send(msg_subj, msg_body)
self.purge_worker(device_name)
def read_tests(self):
self._tests = []
manifest = TestManifest()
manifest.read(self.options.test_path)
tests_info = manifest.get()
for t in tests_info:
# Remove test section suffix.
t['name'] = t['name'].split()[0]
if not t['here'] in sys.path:
sys.path.append(t['here'])
if t['name'].endswith('.py'):
t['name'] = t['name'][:-3]
# add all classes in module that are derived from PhoneTest to
# the test list
tests = []
for member_name, member_value in inspect.getmembers(__import__(t['name']),
inspect.isclass):
if member_name != 'PhoneTest' and member_name != 'PerfTest' and \
issubclass(member_value, PhoneTest):
config = t.get('config', '')
# config is a space separated list of config
# files. The test will be instantiated for each
# of the config files allowing tests such as the
# runremotetests.py to handle more than one unit
# test at a time.
#
# Each config file can contain additional options
# for a test.
#
# Other options are:
#
# <device> = <repo-list>
#
# which determines the devices which should
# run the test. If no devices are listed, then
# all devices will run the test.
devices = [device for device in t if device not in
('name', 'here', 'manifest', 'path', 'config',
'relpath', 'unittests', 'subsuite')]
LOGGER.debug('read_tests: test: %s, class: %s, '
'config: %s, devices: %s',
member_name,
member_value,
config,
devices)
test_devices_repos = {}
for device in devices:
test_devices_repos[device] = t[device].split()
configs = config.split()
for config_file in configs:
config_file = os.path.normpath(
os.path.join(t['here'], config_file))
tests.append((member_value,
config_file, test_devices_repos))
self._tests.extend(tests)
def trigger_jobs(self, data):
LOGGER.info('Received user-specified job: %s', data)
trigger_data = json.loads(data)
if 'build_data' not in trigger_data:
return 'invalid args'
build_data = trigger_data['build_data']
build_url = build_data['url']
changeset_dirs = build_data['changeset_dirs']
repo = build_data['repo']
build_type = build_data['build_type']
abi = build_data['abi']
sdk = build_data['sdk']
test_names = trigger_data['test_names']
# If we can not determine the sdk, default to all, abi to arm.
if not sdk:
sdk = 'api-9,api-10,api-11,api-15'
LOGGER.warning('trigger_jobs: default sdks: %s', sdk)
if not abi:
abi = 'arm'
LOGGER.warning('trigger_jobs: default abi: %s', abi)
LOGGER.info('trigger_jobs: using repo %s, build_type %s, abi %s, sdk %s',
repo, build_type, abi, sdk)
tests = []
if not test_names:
# No test names specified, force PhoneTest.match
# to return tests with any name.
test_names = [None]
devices = trigger_data['devices']
if not devices:
# No devices specified, force PhoneTest.match
# to return tests for any device.
devices = [None]
for test_name in test_names:
for device in devices:
tests.extend(PhoneTest.match(test_name=test_name,
phoneid=device,
repo=repo,
build_type=build_type,
build_abi=abi,
build_sdk=sdk,
changeset_dirs=changeset_dirs))
if tests:
job_data = {
'build': build_url,
'build_id': build_data['id'],
'build_type': build_data['build_type'],
'platform': build_data['platform'],
'abi': abi,
'sdk': sdk,
'repo': repo,
'changeset': build_data['changeset'],
'changeset_dirs': build_data['changeset_dirs'],
'revision': build_data['revision'],
'builder_type': build_data['builder_type'],
'tests': tests,
}
self.new_job(job_data)
return 'ok'
def reset_phones(self):
LOGGER.info('Resetting phones...')
for phoneid, phone in self.phone_workers.iteritems():
phone.reboot()
def on_build(self, build_data):
if self.pulse_monitor._stopping.is_set():
LOGGER.debug('on_build: shutting down: ignoring %s', build_data)
return
self.lock_acquire()
try:
if self.state != ProcessStates.RUNNING:
return
LOGGER.debug('PULSE BUILD FOUND %s', build_data)
build_url = build_data['url']
platform = build_data['platform']
repo = build_data['repo']
build_id = build_data['id']
build_type = build_data['build_type']
changeset = build_data['changeset']
changeset_dirs = build_data['changeset_dirs']
revision = build_data['revision']
builder_type = build_data['builder_type']
abi = build_data['abi']
sdk = build_data['sdk']
comments = build_data['comments']
if repo != 'try':
tests = PhoneTest.match(repo=repo, build_type=build_type, build_abi=abi,
build_sdk=sdk, changeset_dirs=changeset_dirs)
else:
# Autophone try builds will have a comment of the form:
# try: -b o -p android-api-9,android-api-15 -u autophone-smoke,autophone-s1s2 -t none
# Do not allow global selection of tests
# since Autophone can not handle the load.
tests = []
reTests = re.compile('try:.* (?:-u|--unittests) (.*) -t.*')
match = reTests.match(comments)
if match:
test_names = [t for t in match.group(1).split(',')
if t.startswith('autophone-') and
t != 'autophone-tests']
for test_name in test_names:
tests.extend(PhoneTest.match(test_name=test_name,
repo=repo,
build_type=build_type,
build_abi=abi,
build_sdk=sdk))
job_data = {
'build': build_url,
'build_id': build_id,
'build_type': build_type,
'changeset': changeset,
'changeset_dirs': changeset_dirs,
'revision': revision,
'builder_type': builder_type,
'platform': platform,
'repo': repo,
'abi': abi,
'sdk': sdk,
'tests': tests,
}
self.new_job(job_data)
finally:
self.lock_release()
def on_jobaction(self, job_action):
if self.pulse_monitor._stopping.is_set():
LOGGER.debug('on_jobaction: shutting down: ignoring %s', job_action)
return
self.lock_acquire()
try:
if self.state != ProcessStates.RUNNING or job_action['job_group_name'] != 'Autophone':
return
machine_name = job_action['machine_name']
if machine_name not in self.phone_workers:
LOGGER.warning('on_jobaction: unknown device %s', machine_name)
return
LOGGER.debug('on_jobaction: found %s', job_action)
p = self.phone_workers[machine_name]
if job_action['action'] == 'cancel':