-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprof.py
More file actions
executable file
·1184 lines (1003 loc) · 39 KB
/
prof.py
File metadata and controls
executable file
·1184 lines (1003 loc) · 39 KB
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
#!/usr/bin/python
import argparse
import datetime
import json
import logging
import os
import os
import re
import signal
import sys
import time
import shlex
import random
import math
import traceback
import resource
from collections import namedtuple
from subprocess import Popen, PIPE, check_output
from threading import Thread, Lock, Condition, local
import keystoneclient.v2_0.client
import novaclient
import novaclient.shell
class Stats(object):
max = 0
total = 0
n = 0
max_where = ''
def update(self, start):
current = time.time() - start
assert current >= 0
if current > self.max:
self.max = current
self.max_where = traceback.format_stack()
self.n += 1
self.total += current
class ProfiledLock(object):
all_locks = []
def __init__(self, name, lock_cls=None):
if lock_cls is None:
lock_cls = Lock
self._lock = lock_cls()
self.__stats = {}
self.name = name
self.all_locks.append(self)
def _update_stat(self, name, start):
try:
stat = self.__stats[name]
except KeyError:
stat = Stats()
self.__stats[name] = stat
stat.update(start)
def report(self, out):
out.write(' max total avg n')
for name, stats in self.__stats.items():
out.write('\n%-9s%-9.1e%-9.1e%-9.1e%d' %
(name, stats.max, stats.total,
stats.total / stats.n, stats.n))
@classmethod
def report_all(cls, out):
for lock in cls.all_locks:
out.write('\x1b[1m%s:\x1b[0m\n' % lock.name)
lock.report(out)
out.write('\n')
def __enter__(self):
start = time.time()
self._lock.acquire()
self._update_stat('acquire', start)
self._hold_start = time.time()
def __exit__(self, type, value, traceback):
self._update_stat('held', self._hold_start)
self._lock.release()
class ProfiledCondition(ProfiledLock):
def __init__(self, name, lock_cls=None):
if lock_cls is None:
lock_cls = Condition
ProfiledLock.__init__(self, name, lock_cls)
def notify(self):
self._lock.notify()
def notify_all(self):
self._lock.notify_all()
def wait(self, timeout=None):
start = time.time()
self._update_stat('held', self._hold_start)
self._lock.wait(timeout)
self._hold_start = time.time()
self._update_stat('wait', start)
DEV_NULL = open('/dev/null', 'w+')
print_lock = ProfiledLock('print')
last_status_len = 0
def status_line(msg):
global last_status_len
with print_lock:
print '\r', msg, ' ' * (last_status_len - len(msg)), '\r',
sys.stdout.flush()
last_status_len = len(msg)
def timestamp():
return str(datetime.datetime.now())
class Timer(object):
def __init__(self, name):
self.start()
self.name = name
def start(self):
self.start_time = time.time()
def elapsed(self):
return time.time() - self.start_time
class InstanceDoesNotExistError(Exception):
def __init__(self, instance_id):
Exception.__init__(self, 'Instance with id %s does not exist.' %
instance_id)
class InstanceHasNoIpError(Exception):
def __init__(self, instance_id):
Exception.__init__(self, 'Instance with id %s has no ip address.' %
instance_id)
NetworkPort = namedtuple('NetworkPort', 'network ip mac type')
class Instance(object):
def __init__(self, nova, id):
self.__nova = nova
self.__server_data = None
self.id = id
@property
def __path(self):
return os.path.join(self.__nova.instances_path, self.id)
@property
def console_log_path(self):
return os.path.join(self.__path, 'console.log')
def delete(self):
self.__nova.delete(self.id)
@property
def __server(self):
if self.__server_data == None:
self.__server_data = self.__nova.show(self.id)
return self.__server_data
def refetch(self):
self.__server_data = None
@property
def net2ports(self):
net2ports = {}
for network, addresses in self.__server.addresses.iteritems():
ports = []
net2ports[network] = ports
for address in addresses:
ports.append(NetworkPort(network, address['addr'],
address['OS-EXT-IPS-MAC:mac_addr'],
type=address['OS-EXT-IPS:type']))
return net2ports
@property
def ports(self):
ports = []
for netports in self.net2ports.itervalues():
ports.extend(netports)
return ports
@property
def status(self):
return self.__server.status
@property
def task_state(self):
return getattr(self.__server, 'OS-EXT-STS:task_state')
def get_port(self, network):
if network is None:
ports = self.ports
else:
ports = self.net2ports[network]
if len(ports) == 0:
raise InstanceHasNoIpError(self.id)
return ports[0]
def get_mac(self, network):
return self.get_port(network).mac
def get_ip(self, network):
return self.get_port(network).ip
INTERFACE_ID_RE=re.compile('<parameters interfaceid=\'([a-z0-9-]*)\'/>')
def fetch_port_uuid(self, network):
out = check_output(['virsh', 'dumpxml', self.id])
match = self.INTERFACE_ID_RE.search(out)
return match.groups()[0]
def fetch_status(self):
self.refetch()
return self.status
def __repr__(self):
return 'Instance(%r, %r)' % (self.__nova, self.id)
class SharedTokenClientFactory(object):
def __init__(self, username, password, tenant_name, tenant_id, auth_url):
self.username = username
self.password = password
self.tenant_name = tenant_name
self.tenant_id = tenant_id
self.auth_url = auth_url
self.auth_ref = self.create_keystone().auth_ref
self.nova_api_url = self.auth_ref.\
service_catalog.\
url_for(attr='region',
service_type='compute',
endpoint_type='publicURL')
self.nova_extensions = novaclient.shell.\
OpenStackComputeShell().\
_discover_extensions('1.1')
def create_nova(self):
client = novaclient.v1_1.Client(username=self.username,
api_key=self.password,
project_id=self.tenant_name,
tenant_id=self.auth_ref.tenant_id,
auth_url='shared-token-did-not-work!',
extensions=self.nova_extensions)
client.client.management_url = self.nova_api_url
client.client.auth_token = self.auth_ref.auth_token
return client
def create_keystone(self):
return keystoneclient.v2_0.client.Client(username=self.username,
password=self.password,
tenant_name=self.tenant_name,
tenant_id=self.tenant_id,
auth_url=self.auth_url)
class MockClientFactory(object):
class Server(object):
def __init__(self, name, id):
self.name = name
self.id = id
self.__timer = Timer('server')
self.__states = [(random.random() * 2.0, 'BUILD', None),
(random.random() * 2.0, 'BUILD', 'scheduling'),
(random.random() * 2.0, 'BUILD', 'block_device_mapping'),
(random.random() * 2.0, 'BUILD', 'networking'),
(random.random() * 2.0, 'BUILD', 'spawning'),
(random.random() * 2.0, 'ACTIVE', None)]
setattr(self, 'OS-EXT-STS:task_state', None)
def __getattribute__(self, name):
if name == 'OS-EXT-STS:task_state':
return getattr(self, 'task_state')
return object.__getattribute__(self, name)
def __getattr__(self, name):
elapsed = self.__timer.elapsed()
cumulative = 0
for timeout, status, task_state in self.__states:
if timeout + cumulative > elapsed:
break
cumulative += timeout
with print_lock:
print '\n', timeout, cumulative, elapsed
if name == 'task_state':
return task_state
if name == 'status':
return status
return object.__getattr__(self, name)
class Namespace(object):
pass
def __init__(self):
self.__servers = {}
self.__lock = ProfiledLock('mock client factory')
self.__id = 0
self.servers = self.Namespace()
self.cobalt = self.Namespace()
setattr(self.servers, 'create', self.__servers_create)
setattr(self.servers, 'delete', self.__servers_delete)
setattr(self.servers, 'list', self.__servers_list)
setattr(self.cobalt, 'start_live_image', self.__cobalt_start_live_image)
def create_nova(self):
return self
def __create_next(self, name):
with self.__lock:
server = self.Server(name, str(self.__id))
self.__servers[server.id] = server
self.__id += 1
return server
def __servers_create(self, name, image, flavor, key_name, min_count):
return self.__create_next(name)
def __servers_delete(self, id):
with self.__lock:
del self.__servers[id]
def __servers_list(self):
time.sleep(random.random() * 4)
with self.__lock:
return self.__servers.values()
def __cobalt_start_live_image(self, server, name, key_name, num_instances):
return self.__create_next(name)
class Nova(object):
def __init__(self, client_factory, simple_list, instances_path):
self.__list = {}
self.__list_cond = ProfiledCondition('nova list')
self.__list_status = 'IDLE'
self.__tls = local()
self.__client_factory = client_factory
self.__simple_show = simple_list
self.instances_path = instances_path
@property
def __client(self):
try:
return self.__tls.client
except AttributeError:
self.__tls.client = self.__client_factory.create_nova()
return self.__tls.client
def show(self, instance_id):
if not self.__simple_show:
for i in range(2):
instances = self.coalesced_list()
try:
return instances[instance_id]
except KeyError:
pass
else:
for instance in self.simple_list():
if instance.id == instance_id:
return instance
raise InstanceDoesNotExistError(instance_id)
def list(self):
if self.__simple_show:
return self.simple_list()
else:
return self.coalesced_list().values()
def simple_list(self):
return self.__client.servers.list()
def coalesced_list(self):
with self.__list_cond:
if self.__list_status == 'IDLE':
self.__list_status = 'ACTIVE'
else:
while True:
self.__list_cond.wait()
if self.__list_status == 'ERROR':
raise Exception('Error in list, aborting.')
elif self.__list_status == 'IDLE':
return self.__list
else:
assert self.__list_status == 'ACTIVE'
while True:
try:
new_list = self.__client.servers.list()
break
except Exception, e:
with print_lock:
print 'error retrieving list (%s), retrying in 1s' % e
time.sleep(1)
except:
with self.__list_cond:
self.__list_status = 'ERROR'
self.__list_cond.notify()
raise
with self.__list_cond:
self.__list = {}
for server in new_list:
assert server.id not in self.__list
self.__list[server.id] = server
self.__list_status = 'IDLE'
self.__list_cond.notify_all()
return self.__list
def boot(self, name, image, flavor, key_name, num_instances=1):
instance = self.__client.servers.create(name=name,
image=image,
flavor=flavor,
key_name=key_name,
min_count=num_instances)
return Instance(self, instance.id)
def live_image_start(self, name, image, flavor, key_name, num_instances=1):
instances =\
self.__client.cobalt.start_live_image(server=image,
name=name,
key_name=key_name,
num_instances=num_instances)
assert len(instances) == 1
return Instance(self, instances[0].id)
def delete(self, id):
self.__client.servers.delete(id)
class Atop(object):
def __init__(self, title, interval, output_path):
self.title = title
self.process = None
self.interval = interval
self.output_path = output_path
def start(self):
assert self.process == None
self.process = Popen(
['sudo', 'atop', '-w', '%s/%s.atop' % (self.output_path,
self.title),
str(self.interval)],
close_fds=True)
def stop(self):
# Wow, this is weird. In Ubuntu 13.10, you can't send signals to sudo
# processes. Strange how the shell can though.
os.system('sudo kill -INT %d' % self.process.pid)
#self.process.send_signal(signal.SIGINT)
self.process.wait()
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
class NullAtop(object):
def start(self):
pass
def stop(self):
pass
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
class PhaseLog(object):
def __init__(self, timer, title, output_path, order, total):
if order is None:
order = []
self.order = order
self.in_phase = dict([(phase, 0) for phase in self.order])
self.last_phase = {}
self.timer = timer
self.lock = ProfiledCondition('phase')
self.last_in_phase = {}
self.data = open('%s/%s.phases' % (output_path, title), 'w')
self.total = total
def __enter__(self):
self.start()
return self
def __exit__(self, type, value, traceback):
self.stop()
def start(self):
pass
def stop(self):
self.data.close()
def event(self, experiment, *args):
t = self.timer.elapsed()
with self.lock:
phase = experiment.phase
if phase not in self.in_phase:
self.order.append(phase)
try:
last_phase = self.last_phase[experiment]
except KeyError:
last_phase = None
else:
# No change.
if last_phase == phase:
return
self.in_phase[last_phase] -= 1
if self.in_phase[last_phase] == 0:
self.last_in_phase[last_phase] = experiment
self.data.write('%s\tin-%s\t%s\n' % (t, last_phase, self.in_phase[last_phase]))
self.data.write('%s\tend-%s\n' % (t, last_phase))
self.in_phase.setdefault(phase, 0)
self.in_phase[phase] += 1
self.data.write('%s\tstart-%s\n' % (t, phase))
self.data.write('%s\tin-%s\t%s\n' % (t, phase, self.in_phase[phase]))
self.last_in_phase.pop(phase, None)
self.last_phase[experiment] = phase
#self.print_progress()
def print_progress(self):
width = int(math.ceil(math.log(max(1, self.total), 10))) + 1
fmt = ' %%-%dd ' % width
with self.lock:
parts = [' RUNNING: %-9s '
% ('t+%.1fs' % self.timer.elapsed())]
for phase in self.order:
parts.extend([phase.replace('create:', ''),
fmt % self.in_phase[phase]])
status_line(''.join(parts))
def report(self):
self.print_progress()
with print_lock:
# One newline to clear the status line .
print
return
fmtstr = '%%-%ds %%-10s' % (max([len('PHASE')] + map(len, self.order)))
print fmtstr % ('PHASE', 'LAST')
for phase in self.order:
try:
last = self.last_in_phase[phase]
except KeyError:
last_id = '<still active or none exited>'
else:
if last.instance == None:
last_id = '-'
else:
last_id = last.instance.id
print fmtstr % (phase, last_id)
class PeriodicCaller(Thread):
def __init__(self, period, func, *args, **kwargs):
super(PeriodicCaller, self).__init__(name='Periodic Caller')
self.__period = period
self.__callee = lambda: func(*args, **kwargs)
self.__stopped = False
self.__cond = ProfiledCondition('periodic')
def run(self):
with self.__cond:
while True:
self.__cond.wait(timeout=self.__period)
if self.__stopped:
break
self.__callee()
def stop(self):
with self.__cond:
self.__stopped = True
self.__cond.notify()
class Phase(object):
def __init__(self, timer):
self.name = timer.name
self.start = timer.start_time
self.duration = timer.elapsed()
self.end = self.start + self.duration
class PhaseError(Exception):
pass
class Tail(object):
def __init__(self, path, from_beginning=False):
self.path = path
args = ['tail']
if from_beginning:
args.extend(['-c', '+0'])
args.extend(['-f', path])
self.__p = Popen(args, stdout=PIPE, close_fds=True)
def readline(self):
return self.__p.stdout.readline()
def stop(self):
self.__p.kill()
self.__p.wait()
self.__p.stdout.close()
self.__p = None
class InstanceCreator(object):
def __init__(self, nova, nova_op, total, name_prefix,
image, key_name, flavor):
self.nova = nova
self.total = total
self.name_prefix = name_prefix
self.nova_op = nova_op
self.image = image
self.key_name = key_name
self.flavor = flavor
self.__created = 0
self._cond = ProfiledCondition('creator')
@staticmethod
def create(nova, args):
if args.multi:
cls = MultiInstanceCreator
else:
cls = SingleInstanceCreator
if args.op == 'boot':
func = nova.boot
image = args.image
elif args.op == 'launch':
func = nova.live_image_start
image = args.live_image
else:
raise ValueError(args.op)
return cls(nova, func, args.n, '%s-%s' % (args.name_prefix, args.op),
image, args.key_name, args.flavor)
def _do_nova_op(self, name, num_instances):
return self.nova_op(name, self.image, self.flavor, self.key_name,
num_instances)
def next_instance(self):
with self._cond:
self.__created += 1
id = self.__created
assert id <= self.total
return self._next_instance(id)
class SingleInstanceCreator(InstanceCreator):
def _next_instance(self, id):
name = '%s-%d-of-%d' % (self.name_prefix, id, self.total)
return self._do_nova_op(name, num_instances=1)
class MultiInstanceCreator(InstanceCreator):
__state = 'init'
def _next_instance(self, id):
with self._cond:
if self.__state == 'init':
try:
self.__state = 'waiting'
self.__seen = set()
self.__available = set()
self.__multi_prefix = 'multi-%d' % random.randint(0, 10000)
i = self._do_nova_op(self.__multi_prefix, num_instances=self.total)
self.__seen = set([i.id])
self.__available = set([i.id])
self.__state = 'done'
except:
self.__state = 'error'
raise
finally:
self._cond.notify_all()
while self.__state is 'waiting':
self._cond.wait()
if self.__state is 'error':
raise Exception()
while not self.__available:
for instance in self.nova.list():
if instance.id not in self.__seen:
self.__seen.add(instance.id)
self.__available.add(instance.id)
return Instance(self.nova, self.__available.pop())
class Experiment(object):
def __init__(self, args, nova, creator):
self.args = args
self.creator = creator
self.timer = Timer('total')
self.phase = 'setup'
self.listeners = []
self.nova = nova
self.phases = []
self.instance = None
self.console_tail = None
self.__instance_port = None
for name in vars(self.args):
if name.startswith('check_syslog') and getattr(self.args, name):
self.syslog_tail = Tail('/var/log/syslog', False)
break
else:
self.syslog_tail = None
if args.netns is not None:
self.netns_exec = ['sudo', 'ip', 'netns', 'exec', args.netns]
else:
self.netns_exec = []
@classmethod
def phase_order(self, args):
arg2phases = [
(True, ['create:api',
'create:none',
'create:scheduling',
'create:networking',
'create:block_device_mapping',
'create:spawning']),
(args.check_dhcp_hosts, ['dhcp_hosts']),
(args.check_syslog_ovsvsctl, ['syslog_ovsvsctl']),
(args.check_console_boot, ['console_boot']),
(args.check_iptables, ['iptables']),
(args.check_syslog_dhcp, ['syslog_dhcp']),
(args.check_console_dhcp, ['console_dhcp']),
(args.check_ping, ['ping']),
(args.check_nmap, ['nmap']),
(args.check_ssh, ['ssh']),
(args.delete, ['delete_api', 'delete']),
(True, ['fin']),
]
r = []
for arg, phases in arg2phases:
if arg:
r.extend(phases)
return r
def add_listener(self, listener):
self.listeners.append(listener)
def remove_listener(self, listener):
i = list(reversed(self.listeners)).index(listener)
self.listeners.pop(len(self.listeners) - i - 1)
def event(self, *args):
for listener in self.listeners:
listener(self, *args)
def start_phase(self, name):
self.phase = name
self.event()
def phase_error(self, msg):
raise PhaseError('Error during phase %s for instance %s: %s' %
(self.phase, self.instance.id, msg))
def run(self):
try:
self.__create()
if self.args.check_dhcp_hosts:
self.__check_dhcp_hosts()
if self.args.check_syslog_ovsvsctl:
self.__check_syslog_ovsvsctl()
if self.args.check_console_boot:
self.__check_console_boot()
if self.args.check_iptables:
self.__check_iptables()
if self.args.check_syslog_dhcp:
self.__check_syslog_dhcp()
if self.args.check_console_dhcp:
self.__check_console_dhcp()
if self.args.check_ping:
self.__check_ping()
if self.args.check_nmap:
self.__check_nmap()
if self.args.check_ssh:
self.__check_ssh()
if self.args.delete:
self.__delete()
self.start_phase('fin')
finally:
if self.console_tail != None:
self.console_tail.stop()
if self.syslog_tail != None:
self.syslog_tail.stop()
def boot_op(self, name):
return self.nova.boot(name, self.args.image,
self.args.flavor, self.args.key_name)
def launch_op(self, name):
return self.nova.live_image_start(name, self.args.live_image,
self.args.key_name)
def __create(self):
self.start_phase('create:api')
self.instance = self.creator.next_instance()
self.start_phase('create:none')
last_task_state = None
while True:
self.instance.refetch()
task_state = self.instance.task_state
if task_state != last_task_state and task_state is not None:
self.start_phase('create:%s' % task_state)
last_task_state = task_state
status = self.instance.status
assert status != 'ERROR'
if status == 'ACTIVE':
break
def __delete(self):
self.start_phase('delete_api')
self.instance.delete()
self.start_phase('delete')
while True:
try:
assert self.instance.fetch_status() != 'ERROR'
except InstanceDoesNotExistError:
break
def __check_dhcp_hosts(self):
self.start_phase('dhcp_hosts')
ip = self.__instance_ip()
while True:
with open(self.args.check_dhcp_hosts) as f:
if ip in f.read():
break
time.sleep(1)
def __check_iptables(self):
self.start_phase('iptables')
prefix = self.__instance_port_uuid_prefix()
regex = re.compile('%s.*--[ds]port 6[78]' % re.escape(prefix))
while True:
out = check_output(['sudo', 'iptables-save'])
if regex.search(out):
break
time.sleep(1)
def __check_tail(self, tail, regex):
if isinstance(regex, basestring):
regex = re.compile(regex)
while True:
line = tail.readline()
if line == '':
self.phase_error('%s not in %s' % (regex.pattern, tail.path))
if regex.search(line):
break
def __check_console(self, regex):
if self.console_tail == None:
self.console_tail =\
Tail(os.path.join(self.instance.console_log_path), True)
self.__check_tail(self.console_tail, regex)
def __check_syslog(self, regex):
self.__check_tail(self.syslog_tail, regex)
def __check_syslog_dhcp(self):
self.start_phase('syslog_dhcp')
self.__check_syslog('DHCPDISCOVER.*%s' %
re.escape(self.__instance_mac()))
def __check_syslog_ovsvsctl(self):
self.start_phase('syslog_ovsvsctl')
self.__check_syslog('ovs-vsctl.*%s' % re.escape(self.__instance_mac()))
def __check_console_boot(self):
self.start_phase('console_boot')
self.__check_console('Sending discover...')
def __check_console_dhcp(self):
self.start_phase('console_dhcp')
self.__check_console(re.escape(self.__instance_ip()))
def __check_nmap(self):
self.start_phase('nmap')
def __get_instance_port(self):
if self.__instance_port is None:
get = lambda: self.instance.get_port(self.args.network)
try:
self.__instance_port = get()
except InstanceHasNoIpError:
self.instance.refetch()
self.__instance_port = get()
return self.__instance_port
def __instance_ip(self):
return self.__get_instance_port().ip
def __instance_mac(self):
return self.__get_instance_port().mac
def __instance_port_uuid_prefix(self):
uuid = self.instance.fetch_port_uuid(self.args.network)
return uuid.partition('-')[0]
def __check_ping(self):
self.start_phase('ping')
while True:
p = Popen(self.netns_exec +
['ping', '-c', '1', '-w', '1', self.__instance_ip()],
stderr=DEV_NULL,
stdout=DEV_NULL,
stdin=DEV_NULL,
close_fds=True)
if p.wait() == 0:
break
def __check_ssh(self):
self.start_phase('ssh')
args = list(self.netns_exec)
args.extend([
'ssh',
'-l', self.args.check_ssh_user,
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'StrictHostKeyChecking=no',
'-o', 'PasswordAuthentication=no',
])
if self.args.check_ssh_key is not None:
args.extend(['-i', self.args.check_ssh_key])
args.extend([
self.__instance_ip(),
self.args.check_ssh_command,
])
while True:
p = Popen(args, stdout=DEV_NULL, stderr=DEV_NULL, stdin=DEV_NULL,
close_fds=True)
if p.wait() == 0:
break
time.sleep(1)
class ParallelExperiment(object):
def __init__(self, args, atop, nova, title, creator, output_path):
self.creator = creator
self.args = args
self.atop = atop
self.nova = nova
self.title = title
self.output_path = output_path
def run(self):
status_line(' RUNNING: ...')
threads = []
timer = Timer('total')
log = PhaseLog(timer, self.title, self.output_path,
Experiment.phase_order(self.args), self.args.n)
progress_thread = PeriodicCaller(1, log.print_progress)
timer.start()
with self.atop, log:
for i in range(self.args.n):
experiment = Experiment(self.args, self.nova, self.creator)
experiment.add_listener(log.event)
thread = Thread(target=experiment.run,
name='experiment %d' % (i + 1))
thread.daemon = True
thread.start()
threads.append(thread)
log.print_progress()
progress_thread.start()
# Join all of the threads. Wakeup every 1s so we can check for
# keyboard interrupts.
while True:
for thread in threads:
if thread.is_alive():
thread.join(1)
break
else:
break
progress_thread.stop()
progress_thread.join()
log.report()
class ArgumentParser(argparse.ArgumentParser):
def add_bool_arg(self, yes_arg, default=False, help=None):
assert yes_arg[:2] == '--'
arg_name = yes_arg[2:]
no_arg = '--no-%s' % arg_name
dest = arg_name.replace('-', '_')
self.add_argument(yes_arg, dest=dest, action='store_true',
help=help)