forked from open-power/op-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpTestUtil.py
2709 lines (2513 loc) · 127 KB
/
OpTestUtil.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
#!/usr/bin/env python3
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: op-test-framework/common/OpTestUtil.py $
#
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2015
# [+] International Business Machines Corp.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
# IBM_PROLOG_END_TAG
import sys
import os
import datetime
import time
import pwd
import string
import subprocess
import random
import re
import telnetlib
import socket
import select
import time
import pty
import pexpect
import subprocess
import requests
import traceback
from requests.adapters import HTTPAdapter
#from requests.packages.urllib3.util import Retry
from http.client import HTTPConnection
# HTTPConnection.debuglevel = 1 # this will print some additional info to stdout
import urllib3 # setUpChildLogger enables integrated logging with op-test
import json
import tempfile
from .OpTestConstants import OpTestConstants as BMC_CONST
from .OpTestError import OpTestError
from .Exceptions import CommandFailed, RecoverFailed, ConsoleSettings
from .Exceptions import HostLocker, AES, ParameterCheck, HTTPCheck, UnexpectedCase
from .OpTestVIOS import OpTestVIOS
import logging
import OpTestLogger
log = OpTestLogger.optest_logger_glob.get_logger(__name__)
sudo_responses = ["not in the sudoers",
"incorrect password"]
class OpTestUtil():
def __init__(self, conf=None):
self.conf = conf
def setup(self, config='HostLocker'):
# we need this called AFTER the proper configuration values have been seeded
if config == 'AES':
self.conf.util_server = Server(url=self.conf.args.aes_server,
base_url=self.conf.args.aes_base_url,
minutes=None,
proxy=self.build_proxy(self.conf.args.aes_proxy,
self.conf.args.aes_no_proxy_ips))
elif config == 'REST':
rest_server = "https://{}".format(self.conf.args.bmc_ip)
self.conf.util_bmc_server = Server(url=rest_server,
username=self.conf.args.bmc_username,
password=self.conf.args.bmc_password)
else:
self.conf.util_server = Server(url=self.conf.args.hostlocker_server,
base_url=self.conf.args.hostlocker_base_url,
minutes=None,
proxy=self.build_proxy(self.conf.args.hostlocker_proxy,
self.conf.args.hostlocker_no_proxy_ips))
def is_signed(self, output):
if "Module signature appended" in output[0]:
return True
return False
def check_kernel_signature(self):
'''
Check whether the kernel is signed or unsigned.
If, string - "Module signature appended" is found,
then the kernel is signed, else, the kernel is unsigned.
'''
vmlinux = "vmlinuz" # RHEL
if self.distro_name() == 'sles' or self.distro_name() == "suse":
vmlinux = "vmlinux"
cmd = "strings /boot/%s-$(uname -r) | tail -1" % vmlinux
output = self.conf.host().host_run_command(cmd)
if self.is_signed(output):
return True
return False
def get_grub_file(self):
'''
Fetch the grub-file based on the distro
'''
if self.distro_name() == 'rhel':
rpm_name = "grub2-ppc64le"
filename = "core.elf"
elif self.distro_name() == 'suse' or self.distro_name() == 'sles':
rpm_name = "grub2-powerpc-ieee1275"
filename = "grub.elf"
else:
raise self.skipTest("Test currently supported on SLES and RHEL releases only.")
cmd = ("rpm -ql %s" % (rpm_name))
output = self.conf.host().host_run_command(cmd)
for line in output:
if filename in line:
grub_filename = line
if not grub_filename:
self.fail("%s: Failed to get grub file" % (self.distro_name()))
return grub_filename
def check_grub_signature(self, grub_filename):
'''
Check whether the GRUB is signed or unsigned.
'''
cmd = "strings %s | tail -1" % grub_filename
output = self.conf.host().host_run_command(cmd)
if self.is_signed(output):
return True
else:
self.fail("Grub is not signed.")
def check_os_level_secureboot_state(self):
'''
Check whether the secure-boot is enabled at os level.
To do this, check the entry of "00000002" in "/proc/device-tree/ibm,secure-boot" file.
If found, then secure-boot is enabled.
'''
cmd = "lsprop /proc/device-tree/ibm,secure-boot"
output = self.conf.host().host_run_command(cmd)
for line in output:
if '00000002' in line:
return True
return False
def getPRePDisk(self):
'''
Identify the PReP partition, this disk name is required to copy
signed grub. This manual step required for RHEL OS only.
'''
out = self.conf.host().host_run_command('df /boot')
for line in out:
if "/dev" in line:
self.prepDisk = line.split(" ")[0].replace('2', '1')
break
if not self.prepDisk:
return False
return True
def backup_restore_PRepDisk(self, action):
if action == "backup":
out = self.conf.host().host_run_command("dd if=%s of=%s" % (self.prepDisk, self.backup_prep_filename))
if action == "restore":
out = self.conf.host().host_run_command("dd if=%s of=%s" % (self.backup_prep_filename, self.prepDisk))
for line in out:
if "No" in line:
return False
return True
def os_secureboot_enable(self, enable=True):
'''
To enable/disable the Secure Boot at Operating System level.
Parameter enable=True for enabling Secure Boot
Parameter enable=False for disabling Secure Boot
'''
self.prepDisk = ""
self.backup_prep_filename = "/root/save-prep"
self.distro_version = self.get_distro_version()
self.kernel_signature = self.check_kernel_signature()
self.grub_filename = self.get_grub_file()
self.grub_signature = self.check_grub_signature(self.grub_filename)
if self.kernel_signature == True:
if 'rhel' in self.distro_name() and enable:
# Get the PReP disk file
if not self.getPRePDisk():
return False
if not self.backup_restore_PRepDisk(action="backup"):
return False
#Proceed ahead only if the grub is signed
if self.grub_signature == True:
# Running grub2-install on PReP disk
out = self.conf.host().host_run_command("grub2-install %s" % self.prepDisk)
for line in out:
if "Installation finished. No error reported." not in out:
# Restore the PRep partition back to its original state
self.backup_restore_PRepDisk(action="restore")
return False
out = self.conf.host().host_run_command("dd if=%s of=%s; echo $?" %
(self.grub_filename, self.prepDisk))
if "0" not in out[3]:
# Restore the PRep partition back to its original state
self.backup_restore_PRepDisk(action="restore")
self.fail("RHEL: Failed to copy to PReP partition")
elif 'rhel' in self.distro_name() and not enable:
# Nothing to do for Secure Boot disable for RHEL at OS level
pass
else:
return False
return True
def check_lockers(self):
if self.conf.args.hostlocker is not None:
self.conf.util.hostlocker_lock(self.conf.args)
if self.conf.args.aes is not None:
query = False
lock = False
unlock = False
for i in range(len(self.conf.args.aes)):
if self.conf.args.aes[i].lower() == 'q':
query = True
# remove the q flag in case env name is also q
del self.conf.args.aes[i]
break
if self.conf.args.aes[i].lower() == 'l':
lock = True
# remove the l flag in case env name is also l
del self.conf.args.aes[i]
break
if self.conf.args.aes[i].lower() == 'u':
unlock = True
# remove the u flag in case env name is also u
del self.conf.args.aes[i]
break
# removes any duplicates
self.conf.args.aes = list(set(self.conf.args.aes))
if query:
envs, search_criteria = self.conf.util.aes_get_environments(
self.conf.args)
if envs is not None:
self.conf.util.aes_print_environments(envs)
else:
print(("NO environments found, (if Environment_Name added its "
"probably a syntax problem with --aes q, look at "
"--aes-search-args), we used --aes-search-args {}\n"
.format(' '.join(search_criteria))))
self.conf.util.cleanup()
exit(0)
if lock:
envs, search_criteria = self.conf.util.aes_get_environments(
self.conf.args)
if envs is not None and len(envs) > 0:
if len(envs) <= 1:
for env in envs:
# working_id should NOT be kept to release upon exit
working_id = self.conf.util.aes_lock_env(env=env)
if working_id is None:
print(("AES shows NOT available to LOCK, "
"Environment_EnvId={} Environment_Name='{}' "
"Environment_State={} res_id={} res_email={}"
.format(env['env_id'], env['name'], env['state'],
env['res_id'], env['res_email'])))
else:
print(("AES LOCKED Environment_EnvId={} "
"Environment_Name='{}' res_id={} aes-add-locktime "
"(in hours, zero is Never Expires) = '{}'"
.format(env['env_id'], env['name'], working_id,
self.conf.args.aes_add_locktime)))
else:
print(("AES LOCK limit imposed, we found {} environments "
"using --aes-search-args {} and we must find only "
"one to lock here, use --aes q with your "
"--aes-search-args to view what we found"
.format(len(envs), ' '.join(search_criteria))))
else:
print(("Found NO environments using --aes-search-args {}, "
"use --aes q with your --aes-search-args to view "
"what we found".format(' '.join(search_criteria))))
self.conf.util.cleanup()
exit(0) # exit lock branch
if unlock:
envs, search_criteria = self.conf.util.aes_get_environments(
self.conf.args)
if envs is not None:
if len(envs) <= 1:
for env in envs:
res_id = self.conf.util.aes_release_reservation(
env=env)
if res_id is None:
print(("AES shows NO LOCK, so skipped UNLOCK "
"Environment_EnvId={} Environment_Name='{}' "
"Environment_State={} res_id={} res_email={}"
.format(env['env_id'], env['name'], env['state'],
env['res_id'], env['res_email'])))
else:
print(("AES UNLOCKed Environment_EnvId={} "
"Environment_Name='{}' res_id={} res_email={}"
.format(env['env_id'], env['name'],
env['res_id'], env['res_email'])))
else:
print(("AES UNLOCK limit imposed, we found {} "
"environments and we must only find one to unlock "
"here, use --aes-search-args to limit "
"serach criteria".format(len(envs))))
else:
print(("NO AES environments found using --aes-search-args {}"
.format(' '.join(search_criteria))))
self.conf.util.cleanup()
exit(0) # exit unlock branch
else: # we filtered out all else so now find an env and lock it
self.conf.lock_dict = self.conf.util.aes_lock(self.conf.args,
self.conf.lock_dict)
environments = self.conf.lock_dict.get('envs')
if self.conf.lock_dict.get('res_id') is None:
if self.conf.aes_print_helpers is True:
self.conf.util.aes_print_environments(environments)
# MESSAGE 'unable to lock' must be kept in same line to be filtered
raise AES(message="OpTestSystem AES unable to lock environment "
"requested, try --aes q with options for --aes-search-args "
"to view availability")
else:
log.info("OpTestSystem AES Reservation for Environment_Name '{}' "
"Group_Name={} Reservation id={}"
.format(self.conf.lock_dict.get('name'),
self.conf.lock_dict.get('Group_Name'),
self.conf.lock_dict.get('res_id')))
elif self.conf.args.aes_search_args is not None:
self.conf.lock_dict = self.conf.util.aes_lock(self.conf.args,
self.conf.lock_dict)
environments = self.conf.lock_dict.get('envs')
if self.conf.lock_dict.get('res_id') is None:
if self.conf.aes_print_helpers is True:
self.conf.util.aes_print_environments(environments)
# MESSAGE 'unable to lock' must be kept in same line to be filtered
raise AES(message="OpTestSystem AES NO available environments matching "
"criteria (see output earlier), unable to lock,"
"try running op-test with --aes q "
"--aes-search-args Environment_State=A "
"to query system availability, if trying to use "
"existing reservation the query must be exactly one")
else:
log.info("OpTestSystem AES Reservation for Environment_Name '{}' "
"Group_Name={} Reservation id={}"
.format(self.conf.lock_dict.get('name'),
self.conf.lock_dict.get('Group_Name'),
self.conf.lock_dict.get('res_id')))
def cleanup(self):
if self.conf.args.hostlocker is not None:
if self.conf.args.hostlocker_keep_lock is False:
try:
self.hostlocker_unlock()
except Exception as e:
log.warning("OpTestSystem HostLocker attempted to release "
"host '{}' hostlocker-user '{}', please manually "
"verify and release".format(self.conf.args.hostlocker,
self.conf.args.hostlocker_user))
rc, lockers = self.hostlocker_locked()
if rc == 0:
# there can be cases during signal handler cleanup
# where we get interrupted before the actual lock hit
# so this message can be output even though no lock was
# actually released, no two phase commits here :0
# other cases exist where we confirm no locks held, but
# the info message may say released, due to exceptions thrown
insert_message = ", host is locked by '{}'".format(lockers)
if len(lockers) == 0:
insert_message = ""
log.info("OpTestSystem HostLocker cleanup for host '{}' "
"hostlocker-user '{}' confirms you do not hold the lock{}"
.format(self.conf.args.hostlocker,
self.conf.args.hostlocker_user, insert_message))
else: # we only care if user held the lock
log.warning("OpTestSystem HostLocker attempted to cleanup "
"and release the host '{}' and we were unable to verify, "
"please manually verify and release"
.format(self.conf.args.hostlocker))
# clear since signal handler may call and exit path
self.conf.args.hostlocker = None
if self.conf.args.aes is not None or self.conf.args.aes_search_args is not None:
if self.conf.args.aes_keep_lock is False:
if self.conf.lock_dict.get('res_id') is not None:
temp_res_id = self.aes_release_reservation(
res_id=self.conf.lock_dict.get('res_id'))
if temp_res_id is not None:
log.info("OpTestSystem AES releasing reservation {} "
"Environment_Name '{}' Group_Name {}"
.format(self.conf.lock_dict.get('res_id'),
self.conf.lock_dict.get('name'),
self.conf.lock_dict.get('Group_Name')))
# clear signal handler may call and exit path
self.conf.lock_dict['res_id'] = None
else:
log.info("OpTestSystem AES attempted to cleanup and release "
"reservation {} Environment_Name '{}' Group_Name {}"
" and we were unable to verify, please manually verify "
"and release".format(self.conf.lock_dict.get('res_id'),
self.conf.lock_dict.get(
'name'),
self.conf.lock_dict.get('Group_Name')))
if self.conf.util_server is not None:
# AES and Hostlocker skip logout
log.debug("Closing util_server")
self.conf.util_server.close()
if self.conf.util_bmc_server is not None:
log.debug("Logging out of util_bmc_server")
self.conf.util_bmc_server.logout()
log.debug("Closing util_bmc_server")
self.conf.util_bmc_server.close()
if self.conf.dump:
self.conf.dump = False # possible for multiple passes here
# currently only pulling OpenBMC logs
marker_time = (time.asctime(time.localtime())).replace(" ", "_")
if self.conf.args.bmc_type in ['OpenBMC']:
try:
self.PingMTUCheck(
self.conf.args.bmc_ip, totalSleepTime=BMC_CONST.PING_RETRY_FOR_STABILITY)
except Exception as e:
log.warning(
"Check that the BMC is healthy, maybe the Broadcom bug, Exception={}".format(e))
log.info("OpTestSystem Starting to Gather BMC logs")
try:
journal_dmesg_outfile = "op-test-openbmc-journal-dmesg.{}".format(
marker_time)
journal_dmesg_entries = self.conf.bmc().run_command(
"journalctl -k --no-pager >/tmp/{}".format(journal_dmesg_outfile))
journal_outfile = "op-test-openbmc-journal.{}".format(
marker_time)
journal_entries = self.conf.bmc().run_command(
"journalctl --no-pager >/tmp/{}".format(journal_outfile))
top_outfile = "op-test-openbmc-top.{}".format(marker_time)
top_entries = self.conf.bmc().run_command(
"top -b -n 1 >/tmp/{}".format(top_outfile))
df_outfile = "op-test-openbmc-df.{}".format(marker_time)
df_entries = self.conf.bmc().run_command("df -h >/tmp/{}".format(df_outfile))
uptime_outfile = "op-test-openbmc-uptime.{}".format(
marker_time)
uptime_entries = self.conf.bmc().run_command(
"uptime >/tmp/{}".format(uptime_outfile))
console_outfile = "op-test-openbmc-console-log.{}".format(
marker_time)
# obmc-console.log will exist even if empty
console_entries = self.conf.bmc().run_command("cp /var/log/obmc-console.log /tmp/{}"
.format(console_outfile))
self.copyFilesFromDest(self.conf.args.bmc_username,
self.conf.args.bmc_ip,
"/tmp/op-test*",
self.conf.args.bmc_password,
self.conf.logdir)
except Exception as e:
log.debug(
"OpTestSystem encountered a problem trying to gather the BMC logs, Exception={}".format(e))
# remove temp files
try:
self.conf.bmc().run_command("rm /tmp/op-test*")
except Exception as e:
log.warning(
"OpTestSystem encountered a problem cleaning up BMC /tmp files, you may want to check.")
log.info(
"OpTestSystem Completed Gathering BMC logs, find them in the Log Location")
# this will get esels for all
log.info("OpTestSystem Starting to Gather ESEL's")
try:
esel_entries = self.conf.op_system.sys_sel_elist()
esel_outfile = "{}/op-test-esel.{}".format(
self.conf.logdir, marker_time)
self.dump_list(entries=esel_entries, outfile=esel_outfile)
log.info(
"OpTestSystem Completed Gathering ESEL's, find them in the Log Location")
except Exception as e:
log.debug(
"OpTestSystem encountered a problem trying to gather ESEL's, Exception={}".format(e))
self.dump_versions()
self.dump_nvram_opts()
# leave closing the qemu scratch disk until last
# no known reasons at this point, document in future
try:
log.debug("self.conf.args.qemu_scratch_disk={}"
.format(self.conf.args.qemu_scratch_disk))
if self.conf.args.qemu_scratch_disk is not None:
self.conf.args.qemu_scratch_disk.close()
log.debug("Successfully closed qemu_scratch_disk")
self.conf.args.qemu_scratch_disk = None # in case we pass here again
except Exception as e:
log.debug("self.conf.args.qemu_scratch_disk={} "
"closing Exception={}"
.format(self.conf.args.qemu_scratch_disk, e))
def dump_list(self, entries=None, outfile=None):
'''
Purpose of this function is to dump a list object to the
file system to be used by other methods, etc.
'''
if entries is None or outfile is None:
raise ParameterCheck(message="Check your call to dump_list, entries"
" and outfile need valid values")
if type(entries) == str:
list_obj = entries.splitlines()
else:
list_obj = entries
list_obj.insert(0, "From BMC {} Host {}".format(
self.conf.args.bmc_ip, self.conf.args.host_ip))
with open(outfile, 'w') as f:
for line in list_obj:
f.write("{}\n".format(line))
def dump_versions(self):
log.info("Log Location: {}/*debug*".format(self.conf.output))
log.info("\n----------------------------------------------------------\n"
"OpTestSystem Firmware Versions Tested\n"
"(if flashed things like skiboot.lid, may not be accurate)\n"
"----------------------------------------------------------\n"
"{}\n"
"----------------------------------------------------------\n"
"----------------------------------------------------------\n"
.format(
(None if self.conf.firmware_versions is None
else ('\n'.join(f for f in self.conf.firmware_versions)))
))
def check_nvram_options(self, console):
try:
console.run_command("which nvram")
except:
log.info("No NVRAM utility available to check options")
return
try:
result = console.run_command("nvram -p ibm,skiboot --print-config")
except CommandFailed as cf:
if 'There is no Open Firmware "ibm,skiboot" partition!' in ''.join(cf.output):
result = []
pass
else:
raise cf
self.conf.nvram_debug_opts = [o for o in result if "=" in o]
if len(self.conf.nvram_debug_opts) == 0:
log.info("No NVRAM debugging options set")
return
log.warning("{} NVRAM debugging options set".format(
len(self.conf.nvram_debug_opts)))
def dump_nvram_opts(self):
if self.conf.nvram_debug_opts is None or len(self.conf.nvram_debug_opts) == 0:
return
log.warning("\n{} NVRAM debugging options set\n"
"These may adversely affect test results; verify these are appropriate if a failure occurs:\n"
"----------------------------------------------------------\n"
"{}\n"
"----------------------------------------------------------\n"
.format(len(self.conf.nvram_debug_opts), '\n'.join(f for f in self.conf.nvram_debug_opts)))
def build_proxy(self, proxy, no_proxy_ips):
if no_proxy_ips is None:
return proxy
for ip in no_proxy_ips:
cmd = 'ip addr show to %s' % ip
try:
output = subprocess.check_output(cmd.split())
except (subprocess.CalledProcessError, OSError) as e:
raise HostLocker(
message="Could not run 'ip' to check for no proxy?")
if len(output):
proxy = None
break
return proxy
def get_env_name(self, x):
return x['name']
def aes_print_environments(self, environments):
if environments is None:
return
sorted_env_list = sorted(environments, key=self.get_env_name)
print("--------------------------------------------------------------------------------")
for env in sorted_env_list:
print(("--aes-search-args Environment_Name='{}' Environment_EnvId={} "
"Group_Name='{}' Group_GroupId={} Environment_State={} <res_id={} "
"res_email={} aes-add-locktime={}>"
.format(env['name'], env['env_id'], env['group']['name'],
env['group']['group_id'], env['state'], env['res_id'],
env['res_email'], env['res_length'], )))
print("--------------------------------------------------------------------------------")
print("\nHELPERS --aes-search-args Server_VersionName=witherspoon|boston|habanero|zz|tuleta"
"|palmetto|brazos|fleetwood|p8dtu|p9dsu|zaius|stratton|firestone|garrison|romulus|alpine")
print(" --aes-search-args Server_HardwarePlatform=POWER8|POWER9|openpower")
print(" --aes-search-args Group_Name=op-test")
print(" --aes-search-args Environment_State=A|R|M|X|H|E")
print("A=Available R=Reserved M=Maintenance X=Offline H=HealthCheck E=Exclusive")
print(("AES Environments found = {}".format(len(sorted_env_list))))
def aes_release_reservation(self, res_id=None, env=None):
release_dict = {'result': None,
'status': None,
'message': None,
}
if res_id is None:
if env is not None:
res_id = env.get('res_id')
if res_id is None:
return None # nothing to do
res_payload = {'res_id': res_id}
uri = "/release-reservation.php"
try:
r = self.conf.util_server.get(uri=uri, params=res_payload)
if r.status_code != requests.codes.ok:
raise AES(message="OpTestSystem AES attempted to release "
"reservation '{}' but it was NOT found in AES, "
"please update and retry".format(res_id))
except Exception as e:
raise AES(message="OpTestSystem AES attempted to releasing "
"reservation '{}' but encountered an Exception='{}', "
"please manually verify and release".format(res_id, e))
try:
json_data = r.json()
release_dict['status'] = json_data.get('status')
release_dict['result'] = json_data.get('result')
if json_data.get('result').get('res_id') != res_id:
log.warning("OpTestSystem AES UNABLE to confirm the release "
"of the reservation '{}' in AES, please manually "
"verify and release if needed, see details: {}"
.format(res_id, release_dict))
except Exception as e:
# this seems to be the typical path from AES, not sure what's up
log.debug(
"NO JSON object from aes_release_reservation, r.text={}".format(r.text))
release_dict['message'] = r.text
log.debug("OpTestSystem AES UNABLE to confirm the release "
"of the reservation '{}' in AES, please manually "
"verify and release if needed, see details: {}"
.format(res_id, release_dict))
return res_id
def aes_get_environments(self, args):
# this method initializes the Server request session
get_dict = {'result': None,
'status': None,
'message': None,
}
args_dict = vars(args)
if self.conf.util_server is None:
self.setup(config='AES')
if self.conf.args.aes_search_args is None:
self.conf.args.aes_search_args = []
if self.conf.args.aes is not None:
for i in range(len(self.conf.args.aes)):
# add the single env to the list of search
self.conf.args.aes_search_args += ("Environment_Name={}"
.format(self.conf.args.aes[i]).splitlines())
else:
return None, None # we should NOT have gotten here
else:
if self.conf.args.aes is not None:
for i in range(len(self.conf.args.aes)):
self.conf.args.aes_search_args += ("Environment_Name={}"
.format(self.conf.args.aes[i]).splitlines())
uri = "/get-environments.php"
payload = {'query_params[]': self.conf.args.aes_search_args}
r = self.conf.util_server.get(uri=uri, params=payload)
if r.status_code != requests.codes.ok:
raise AES(message="OpTestSystem AES UNABLE to find the environment '{}' "
"in AES, please update and retry".format(self.conf.args.aes))
# SQL issues can cause various problems which come back as ok=200
filter_list = ["have an error"]
matching = [xs for xs in filter_list if xs in r.text]
if len(matching):
raise AES(message="OpTestSystem AES encountered an error,"
" check the syntax of your query and retry, Exception={}"
.format(r.text))
# we need this here to set the aes_user for subsequent calls
if self.conf.args.aes_user is None:
self.conf.args.aes_user = pwd.getpwuid(os.getuid()).pw_name
aes_response_json = r.json()
get_dict['status'] = aes_response_json.get('status')
if aes_response_json.get('status') == 0:
get_dict['result'] = aes_response_json.get('result')
else:
get_dict['message'] = aes_response_json.get('message')
raise AES(message="Something unexpected happened, "
"see details: {}".format(get_dict))
return get_dict.get('result'), self.conf.args.aes_search_args
def aes_get_env(self, env):
uri = "/get-environment-info.php"
env_payload = {'env_id': env['env_id']}
r = self.conf.util_server.get(uri=uri, params=env_payload)
if r.status_code != requests.codes.ok:
raise AES(message="OpTestSystem AES UNABLE to find the environment '{}' "
"in AES, please update and retry".format(env['env_id']))
aes_response_json = r.json()
if aes_response_json.get('status') == 0:
return aes_response_json['result'][0]
def aes_add_time(self, env=None, locktime=24):
# Sept 10, 2018 - seems to be some issue with add-res-time.php
# even in Web UI the Add an Hour is not working
# locktime number of hours to add
# if aes_add_time called when AES reservation is
# in expiration window this fails
# not sure how that calculation is done yet
time_dict = {'result': None,
'status': None,
'message': None,
}
if locktime == 0:
# if default, add some time
# allows user to specify command line override
locktime = 24
uri = "/add-res-time.php"
res_payload = {'res_id': env.get('res_id'),
'hours': float(locktime),
}
r = self.conf.util_server.get(uri=uri, params=res_payload)
if r.status_code != requests.codes.ok:
raise AES(message="OpTestSystem AES UNABLE to find the reservation "
"res_id '{}' in AES, please update and retry".format(env['res_id']))
aes_response_json = r.json()
time_dict['status'] = aes_response_json.get('status')
if aes_response_json.get('status') == 0:
time_dict['result'] = aes_response_json.get('result')
else:
time_dict['message'] = aes_response_json.get('message')
raise AES(message="OpTestSystem AES UNABLE to add time to existing "
"reservation, the reservation may be about to expire or "
"conflict exists, see details: {}".format(time_dict))
return time_dict
def aes_get_creds(self, env, args):
# version_mappings used for bmc_type
# AES op-test
version_mappings = {'witherspoon': 'OpenBMC',
'zaius': 'OpenBMC',
'boston': 'SMC',
'stratton': 'SMC',
'p9dsu': 'SMC',
'p8dtu': 'SMC',
'firestone': 'AMI',
'garrison': 'AMI',
'habanero': 'AMI',
'palmetto': 'AMI',
'romulus': 'AMI',
'alpine': 'FSP',
'brazos': 'FSP',
'fleetwood': 'FSP',
'tuleta': 'FSP',
'zz': 'FSP',
'unknown': 'unknown',
'qemu': 'qemu',
}
# aes_mappings used for configuration parameters
# AES op-test
aes_mappings = {'os_password': 'host_password',
'os_username': 'host_user',
'os_host': 'host_ip',
'net_mask': 'host_submask',
'os_mac_address': 'host_mac',
'def_gateway': 'host_gateway',
'mac_address': 'bmc_mac',
'password': 'bmc_password',
'username': 'bmc_username',
'host_name': 'bmc_ip',
'ipmi_username': 'bmc_usernameipmi',
'ipmi_password': 'bmc_passwordipmi',
'version_name': 'bmc_type',
'hardware_platform': 'platform',
'attached_disk': 'host_scratch_disk',
}
args_dict = vars(args) # we store credentials to the args
if len(env['servers']) != 1:
# we may not yet have output a message about reservation
# but we will get the release message
self.cleanup()
raise AES(message="AES credential problem, check AES definitions "
"for server record, we either have no server record or more "
"than one, check FSPs and BMCs")
for key, value in list(aes_mappings.items()):
if env['servers'][0].get(key) is not None and env['servers'][0].get(key) != '':
if key == 'version_name':
args_dict[aes_mappings[key]] = version_mappings.get(
env['servers'][0][key].lower())
else:
args_dict[aes_mappings[key]] = env['servers'][0][key]
def aes_lock_env(self, env=None):
if env is None:
return
new_res_id = None
res_payload = {'email': self.conf.args.aes_user,
'query_params[]': None,
'needs_claim': False,
'length': float(self.conf.args.aes_add_locktime),
'rel_on_expire': self.conf.args.aes_rel_on_expire,
}
if env.get('state') == 'A':
uri = "/enqueue-reservation.php"
res_payload['query_params[]'] = 'Environment_EnvId={}'.format(
env.get('env_id'))
r = self.conf.util_server.get(uri=uri, params=res_payload)
if r.status_code != requests.codes.ok:
raise AES(message="Problem with AES trying to enqueue a reservation "
"for environment '{}', please retry".format(env.get('env_id')))
# SQL issues can cause various problems which come back as ok=200
filter_list = ["have an error"]
matching = [xs for xs in filter_list if xs in r.text]
if len(matching):
raise AES(message="OpTestSystem AES encountered an error,"
" check the syntax of your query and retry, Exception={}"
.format(r.text))
aes_response_json = r.json()
if aes_response_json['status'] == 0:
new_res_id = aes_response_json['result']
return new_res_id # None if status not zero
else:
if env.get('state') == 'R' and \
env.get('res_email') == self.conf.args.aes_user and \
self.conf.args.aes_add_locktime != 0:
time_dict = self.aes_add_time(env=env,
locktime=self.conf.args.aes_add_locktime)
return env.get('res_id')
return new_res_id # return None, nothing works
def aes_lock(self, args, lock_dict):
environments, search_criteria = self.aes_get_environments(args)
for env in environments:
# store the new reservation id in the callers instance
# since we need to cleanup if aes_get_creds fails
lock_dict['res_id'] = self.aes_lock_env(env=env)
if lock_dict['res_id'] is not None:
# get the database join info for the env
creds_env = self.aes_get_env(env)
# we need lock_dict filled in here
# in case exception thrown in aes_get_creds
lock_dict['name'] = env.get('name')
lock_dict['Group_Name'] = env.get('group').get('name')
lock_dict['envs'] = environments
self.aes_get_creds(creds_env, args)
return lock_dict
else: # it was not Available
# if only one environment, was it us ?
# if so extend the reservation
if len(environments) == 1:
if env.get('res_email') == self.conf.args.aes_user:
if env.get('state') == 'R':
if env.get('res_length') != 0:
lock_dict['res_id'] = env.get('res_id')
# aes_add_time can fail if reservation
# about to expire or conflicts
time_dict = self.aes_add_time(env=env,
locktime=self.conf.args.aes_add_locktime)
creds_env = self.aes_get_env(env)
# we need lock_dict filled in here
# in case exception thrown in aes_get_creds
lock_dict['res_id'] = env.get('res_id')
lock_dict['name'] = env.get('name')
lock_dict['Group_Name'] = env.get(
'group').get('name')
lock_dict['envs'] = environments
self.aes_get_creds(creds_env, args)
return lock_dict
lock_dict['res_id'] = None
lock_dict['name'] = None
lock_dict['Group_Name'] = None
lock_dict['envs'] = environments
# we did not find anything able to be reserved
# return the list we looked thru
return lock_dict
def hostlocker_lock(self, args):
args_dict = vars(args)
# we need hostlocker_user first thing in case exceptions
if self.conf.args.hostlocker_user is None:
self.conf.args.hostlocker_user = pwd.getpwuid(os.getuid()).pw_name
if self.conf.util_server is None:
self.setup()
uri = "/host/{}/".format(self.conf.args.hostlocker)
try:
r = self.conf.util_server.get(uri=uri)
except Exception as e:
log.debug("hostlocker_lock unable to query Exception={}".format(e))
raise HostLocker(message="OpTestSystem HostLocker unable to query "
"HostLocker, check that your VPN/SSH tunnel is properly"
" configured and open, proxy configured as '{}' Exception={}"
.format(self.conf.args.hostlocker_proxy, e))
if r.status_code != requests.codes.ok:
raise HostLocker(message="OpTestSystem did NOT find the host '{}' "
"in HostLocker, please update and retry"
.format(self.conf.args.hostlocker))
# parse the hostlocker comment for op-test settings
host = r.json()[0]
hostlocker_comment = []
hostlocker_comment = host['comment'].splitlines()
# Ignore anything before the [op-test] marker, as a fallback we try
# to parse everything if there's no marker.
offset = 0
for i, line in enumerate(hostlocker_comment):
if line.find("[op-test]") == 0:
offset = i
break
for key in list(args_dict.keys()):
for l in hostlocker_comment[offset:]:
line = l.strip()
if line.startswith(key + ":"):
value = re.sub(key + ':', "", line).strip()
args_dict[key] = value
if "password" in key:
log_value = "<hidden>"
else:
log_value = value
log.debug(
"Hostlocker config: {} = {}".format(key, log_value))
break
uri = "/lock/"
payload = {'host': self.conf.args.hostlocker,
'user': self.conf.args.hostlocker_user,
'expiry_time': self.conf.args.hostlocker_locktime}
try:
r = self.conf.util_server.post(uri=uri, data=payload)
except Exception as e:
raise HostLocker(message="OpTestSystem HostLocker unable to "
"acquire lock from HostLocker, see Exception={}".format(e))
if r.status_code == requests.codes.locked: # 423
rc, lockers = self.hostlocker_locked()
# MESSAGE 'unable to lock' string must be kept in same line to be filtered
raise HostLocker(message="OpTestSystem HostLocker unable to lock"
" Host '{}' is locked by '{}', please unlock and retry"
.format(self.conf.args.hostlocker, lockers))
elif r.status_code == requests.codes.conflict: # 409
raise HostLocker(message="OpTestSystem HostLocker Host '{}' is "
"unusable, please pick another host and retry"
.format(self.conf.args.hostlocker))
elif r.status_code == requests.codes.bad_request: # 400
raise HostLocker(message=r.text)
elif r.status_code == requests.codes.not_found: # 404
msg = ("OpTestSystem HostLocker unknown hostlocker_user '{}', "
"you need to have logged in to HostLocker via the web"
" at least once prior, please log in to HostLocker via the web"
" and then retry or check configuration."
.format(self.conf.args.hostlocker_user))
raise HostLocker(message=msg)