-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaasterblaster.py
executable file
·3571 lines (3266 loc) · 149 KB
/
maasterblaster.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
## This file is part of Maasterblaster.
#
# Copyright Datto, Inc.
# Author: David Andruczyk <[email protected]>
#
# Licensed under the GNU General Public License Version 3
# Fedora-License-Identifier: GPLv3+
# SPDX-2.0-License-Identifier: GPL-3.0+
# SPDX-3.0-License-Identifier: GPL-3.0-or-later
#
# Maasterblaster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Maasterblaster is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maasterblaster. If not, see <https://www.gnu.org/licenses/>.
##
""" MaasterBlaster tries to provide a way to build machines en-mass with MaaS """
import configargparse
import asyncio
import base64
import calendar
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
import copy
import csv
import json
import ipaddress
import time
import logging
import os
import pprint
import re
import requests
import string
import sys
import time
import traceback
import typing
import yaml
import maas.client
from maas.client.enum import NodeStatus
from maas.client.enum import InterfaceType
from maas.client.enum import PowerState
from maas.client.utils.maas_async import asynchronous
from typing import Tuple
BLOCK_SIZE = 4*1024**2 # 4 Meg
# Maas Seems to have a size related error for MD/LVM
# volumes, this ia fudge factor to spare a little space to get around the bug
DISK_FUDGE = 1.0/3000.0
CONFIGFILE = "config.yml"
LOGGER = logging.getLogger('maasterblaster')
DEFAULT_MAAS_SERVER = "maas.example.com"
DEFAULT_RUNDECK_SERVER = "rundeck.example.com"
DEFAULT_FOREMAN_SERVER = "puppet.example.com"
BOND_PREFIX = "96:EF:8F"
PP = pprint.PrettyPrinter(indent=4)
MD_COUNT = {}
ESP_COUNT = {}
# Classes: (custom foreman client class)
class ForemanClient:
""" Foreman API orchestrator class """
def __init__(self, args):
self.config = args
self.foreman_user = self.config.foreman_user
self.foreman_pass = self.config.foreman_pass
if not self.foreman_user:
LOGGER.critical("Foreman user is unset, cannot continue")
exit(1)
if not self.foreman_pass:
LOGGER.critical("Foreman password is unset, cannot continue")
exit(1)
self.foreman_api_url = "https://" + self.config.foreman_server + "/api/"
self.headers = {
"Authorization": "Basic {}".format(
base64.b64encode(
"{user}:{pw}".format(user=self.foreman_user,
pw=self.foreman_pass).encode("ascii")
).decode()
)
}
def _request(self, method, url, params=None, data=None, additional_headers=None):
"""Templated function that orchestrates the requests being made to the
Foreman API"""
# pylint: disable-msg=too-many-arguments
headers = self.headers
if additional_headers:
headers.update(additional_headers)
kwargs = {"headers": headers}
if params:
kwargs["params"] = params
if data:
kwargs["data"] = data
response = requests.request(method, url, **kwargs)
LOGGER.info(method+ " " + url)
return response
def _get_arch(self, architecture="x86_64"):
"""
Retrieve the architecture of the host. Example:
Search result:
{
"total": 3,
"subtotal": 1,
"page": 1,
"per_page": 50,
"search": "name = x86_64",
"sort": {
"by": null,
"order": null
},
"results": [{"created_at":"2017-06-22T22:10:11.000Z","updated_at":"2017-06-22T22:10:11.000Z","name":"x86_64","id":1}]
}
"""
method = "GET"
url = self.foreman_api_url + "architectures"
search_param = "name = {}".format(architecture)
params = {"search": search_param}
response = self._request(method, url, params)
search_results = response.json()
found_architectures = search_results["results"]
if not found_architectures:
raise Exception("Architecture " + architecture + " not found")
if len(found_architectures) > 1:
raise Exception("Multiple architectures found for " + architecture)
return found_architectures[0]
def _get_os(self, operatingsystem="Ubuntu 18.04 LTS"):
"""
Retrieve the OS of the host. Example:
Search result:
{
"total": 12,
"subtotal": 1,
"page": 1,
"per_page": 50,
"search": "name = Ubuntu 18.04 LTS",
"sort": {
"by": null,
"order": null
},
"results": [{"description":"Ubuntu 18.04 LTS","major":"18","minor":"04","family":"Debian","release_name":"bionic","password_hash":"SHA256","created_at":"2018-05-10T21:08:04.000Z","updated_at":"2018-05-10T21:08:04.000Z","id":4,"name":"Ubuntu","title":"Ubuntu 18.04 LTS"}]
}
"""
method = "GET"
url = self.foreman_api_url + "operatingsystems"
search_param = "name = {}".format(operatingsystem)
params = {"search": search_param}
response = self._request(method, url, params)
search_results = response.json()
found_oses = search_results["results"]
if not found_oses:
raise Exception("OS " + operatingsystem + " not found")
if len(found_oses) > 1:
raise Exception("Multiple OS types found for " + operatingsystem)
return found_oses[0]
def get_host(self, fqdn="somehost.example.com"):
"""
Search result:
{
"total": 9805,
"subtotal": 1,
"page": 1,
"per_page": 50,
"search": "name = somehost.example.com",
"sort": {
"by": null,
"order": null
},
"results": [{"ip":null,"ip6":null,"environment_id":1,"environment_name":"example_environment","last_report":null,"mac":"00:00:00:00:00:00","realm_id":null,"realm_name":null,"sp_mac":null,"sp_ip":null,"sp_name":null,"domain_id":1,"domain_name":"somehost.example.com","architecture_id":1,"architecture_name":"x86_64","operatingsystem_id":4,"operatingsystem_name":"Ubuntu 18.04 LTS","subnet_id":null,"subnet_name":null,"subnet6_id":null,"subnet6_name":null,"sp_subnet_id":null,"ptable_id":null,"ptable_name":null,"medium_id":null,"medium_name":null,"pxe_loader":"PXELinux BIOS","build":false,"comment":null,"disk":null,"installed_at":null,"model_id":null,"hostgroup_id":1,"owner_id":1,"owner_type":"User","enabled":true,"managed":true,"use_image":null,"image_file":"","uuid":null,"compute_resource_id":null,"compute_resource_name":null,"compute_profile_id":null,"compute_profile_name":null,"capabilities":["build"],"provision_method":"build","certname":"somehost.example.com","image_id":null,"image_name":null,"created_at":"2020-12-15T23:15:16.000Z","updated_at":"2020-12-15T23:15:16.000Z","last_compile":null,"global_status":0,"global_status_label":"OK","puppet_status":0,"model_name":null,"build_status":0,"build_status_label":"Installed","name":"somehost.example.com","id":14231,"puppet_proxy_id":null,"puppet_proxy_name":null,"puppet_ca_proxy_id":null,"puppet_ca_proxy_name":null,"puppet_proxy":null,"puppet_ca_proxy":null,"hostgroup_name":"example","hostgroup_title":"example_namespace/example"}]
}
"""
method = "GET"
url = self.foreman_api_url + "hosts"
search_param = "name = {}".format(fqdn)
params = {"search": search_param}
response = self._request(method, url, params)
search_results = response.json()
found_hosts = search_results["results"]
if not found_hosts:
LOGGER.warning("Host %s not found", fqdn)
return None, False
if len(found_hosts) > 1:
raise Exception("Multiple hosts found for " + fqdn)
return found_hosts[0], True
def delete_host(self, fqdn):
""" Delete the host in forman """
LOGGER.debug("delete_host FQDN: %s", fqdn)
host_data, result = self.get_host(fqdn)
method = "DELETE"
host_id = str(host_data['id'])
url = self.foreman_api_url + "hosts" + "/" + host_id
try_count = 0
response = self._request(
method, url
)
if response.ok:
return json.loads(response.text)
else:
LOGGER.debug("Error deleting host: %s", response.text)
LOGGER.debug("Failed to delete Host.\n")
def pair_host(self, fqdn, hostgroup_id):
""" Pair the host in foreman """
LOGGER.debug("FQDN %s. hostgroup_id %s", fqdn, hostgroup_id)
# pylint: disable-msg=no-else-return
arch = self._get_arch()
arch_id = arch["id"]
operatingsystem = self._get_os()
os_id = operatingsystem["id"]
method = "POST"
data = {
"host": {
"name": fqdn,
"mac": "00:00:00:00:00:00",
"architecture_id": arch_id,
"operatingsystem_id": os_id,
"hostgroup_id": hostgroup_id,
"build": "false",
"compute_attributes": {"volumes_attributes": {}},
"managed": "true",
"enabled": "true",
"overwrite": "true",
"interfaces_attributes": [],
}
}
data = json.dumps(data)
url = self.foreman_api_url + "hosts"
try_count = 0
response = self._request(
method, url, data=data, additional_headers={"Content-Type": "application/json"}
)
if response.ok:
return json.loads(response.text)
else:
LOGGER.debug("Error creating host %s", response.text)
LOGGER.debug("Failed to create Host.\n")
def update_host_hostgroup(self, fqdn, hostgroup_id):
"""Pair the host in foreman """
LOGGER.debug("fqdn %s. hostgroup_id %s", fqdn, hostgroup_id)
# pylint: disable-msg=no-else-return
host_data, result = self.get_host(fqdn)
method = "PUT"
data = {
"host": {
"hostgroup_id": hostgroup_id,
}
}
host_id = str(host_data['id'])
data = json.dumps(data)
url = self.foreman_api_url + "hosts" + "/" + host_id
try_count = 0
response = self._request(
method, url, data=data, additional_headers={"Content-Type": "application/json"}
)
if response.ok:
return json.loads(response.text)
else:
LOGGER.debug("Error updating host hostgroup %s", response.text)
LOGGER.debug("Failed to update Host.\n")
# Functions:
def LINE() -> str:
""" Print the line number for debugging """
return sys._getframe(1).f_lineno
class ThreadPoolExecutorStackTraced(ThreadPoolExecutor):
def submit(self, fn, *args, **kwargs):
"""Submits the wrapped function instead of `fn`"""
return super(ThreadPoolExecutorStackTraced, self).submit(
self._function_wrapper, fn, *args, **kwargs)
def _function_wrapper(self, fn, *args, **kwargs):
"""Wraps `fn` in order to preserve the traceback of any kind of
raised exception
"""
try:
return fn(*args, **kwargs)
except Exception:
raise sys.exc_info()[0](traceback.format_exc()) # Creates an
# exception of the
# same type with the
# traceback as
# message
def build_user_data(host_config: dict) -> str:
""" Spits out a bas64 endoded version of the user_data section """
user_data = {}
if 'user_data' in host_config:
user_data = host_config['user_data']
user_data = b"#cloud-config\n" + yaml.dump(user_data).encode("utf-8")
return user_data
def setup_logger(args: dict) -> None:
""" Sets up the logger with seemingly sane defaults """
LOGGER.setLevel(args.debug_level)
# Setup handling output to the console at lowest level
log_to_console = logging.StreamHandler()
log_to_console.setLevel(logging.DEBUG)
#
# Default format
#
if args.timestamp:
formatter = logging.Formatter("%(asctime)s - %(levelname).4s - %(message)s")
else:
formatter = logging.Formatter("%(levelname)s = %(message)s")
#
# Set the console output format
#
log_to_console.setFormatter(formatter)
#
# If the --logfile param is specified, check if target is writable and
# if so, start logging to it, it not error out
#
try:
if args.logfile:
log_to_file = logging.FileHandler(args.logfile)
log_to_file.setLevel(logging.DEBUG)
log_to_file.setFormatter(formatter)
LOGGER.addHandler(log_to_file)
if args.debug_level != "NOTSET":
LOGGER.info("Startup")
else:
LOGGER.addHandler(log_to_console)
if args.debug_level != "NOTSET":
LOGGER.info("Startup")
except IOError as err:
LOGGER.critical("Error trying to open %s, error(%i): %s",
args.logfile,
err.errno,
err.strerror)
def load_csv(config: dict, file: str, limit: list) -> list:
""" Parses Input CSV, validates for blank fields, the stores into an array of
dictionaries for future use """
csvfile = open(file, newline='')
csvreader = csv.DictReader(
filter(lambda row: row[0] != '#', csvfile),
dialect="unix",
delimiter=",",
quotechar='"')
hosts = []
# Validate that the fields aren't blank
for row in csvreader:
# Input Validation
# shortname Required
# domain Required
# profile Required
# macs Required
# power Required
# poweruser Required
# powerpass Required
# powerip Required
# netcfg Required
# foreman_hostgroup_id Optional
assert(row['shortname']),\
"Shortname missing on row %i" % csvreader.line_num
if limit and row['shortname'] not in limit:
LOGGER.info("limiting in use, filtering out %s", row['shortname'])
continue
assert(row['domain']),\
"Domain name missing on row %i" % csvreader.line_num
assert(row['machine_profile']),\
"maasterblaster machine_profile to use is missing on row" % csvreader.line_num
assert(row['macs']),\
"No MAC addresses present (space separated) on row " % csvreader.line_num
assert(row['power']),\
"Power Type not specified, expected IPMI or similar on row " % csvreader.line_num
assert(row['poweruser']),\
"NO Power Username specified on row" % csvreader.line_num
assert(row['powerpass']),\
"NO Power Password specified on row" % csvreader.line_num
assert(row['powerip']),\
"NO Power IP address specified on row" % csvreader.line_num
assert(row['netcfg']),\
"NO Networking configuration present on row" % csvreader.line_num
if 'foreman_hostgroup_id' not in row:
LOGGER.info("NO foreman_hostgroup_id configuration present on row")
# assert(row['foreman_hostgroup_id']),\
# "NO Foreman_hostgroup_id configuration present on row" % csvreader.line_num
# If we got here, basic validation passed
hosts.append(row)
return hosts
def parse_args() -> dict:
""" Handle ye mighty arguments """
parser = configargparse.ArgParser(
default_config_files=["/etc/maasterblaster.conf",
"~/.config/maasterblaster.conf"],
args_for_setting_config_path=['--defaults'],
description='Two Sysadmins Enter, One Sysadmin Leaves.... '
'Batch machine Imager, Beta quality at best, use at your own risk!')
group = parser.add_argument_group('MaaS options')
group.add_argument('--maas-api-key',
env_var='MAAS_API_KEY',
help="MaaS API key to use")
group.add_argument('--maas-proto',
default='https',
choices=['http', 'https'],
env_var='MAAS_PROTO',
help="Maas URL protocol (http, https)")
group.add_argument('--maas-port',
default=443,
type=int,
env_var='MAAS_PORT',
help="Maas URL port (443)")
group.add_argument('--maas-server',
env_var='MAAS_SERVER',
default=DEFAULT_MAAS_SERVER,
help="Maas server hostname")
group.add_argument('--rundeck-server',
env_var="RUNDECK_SERVER",
default=DEFAULT_RUNDECK_SERVER,
help="rundeck server hostname")
group.add_argument('--rundeck-api-key',
env_var="RUNDECK_API_KEY",
help="rundeck api key")
group.add_argument('--rundeck-clear-puppet-key-jobid',
env_var="RUNDECK_CLEAR_PUPPET_KEY_JOB_ID",
help="rundeck clear puppet key job id")
group.add_argument('--rundeck-clear-salt-key-jobid',
env_var="RUNDECK_CLEAR_SALT_KEY_JOB_ID",
help="rundeck clear salt key job id")
group.add_argument('--foreman-server',
env_var='FOREMAN_SERVER',
default=DEFAULT_FOREMAN_SERVER,
help="foreman server hostname")
group.add_argument('--foreman-user',
env_var='FOREMAN_USER',
help="foreman user")
group.add_argument('--foreman-pass',
env_var='FOREMAN_PASS',
help="foreman password")
group = parser.add_argument_group('Debugging')
group.add_argument('-l', '--logfile',
help='path to log file to use, otherwise errors come out the console')
group.add_argument('--timestamp', action='store_true',
help='Use timestamped logs')
group.add_argument('-d', '--debug-level',
default='NOTSET',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Debug Level')
group = parser.add_argument_group('Configuration')
parser.add_argument('--internal-config', default='config.yml',
help='path to config file to use')
group.add_argument('-i', '--input-csv',
help='Input CSV')
lockgroup = parser.add_argument_group('Locking')
lockgroup.add_argument('-L',
'--lock',
action='store_true',
help='Lock machine to prevent modification')
lockgroup.add_argument('-U',
'--unlock',
action='store_true',
help='Unlock machines requires --force')
cd_group = group.add_argument_group('Commissioning and Deployment')
cd_group.add_argument('-C',
'--commission',
action='store_true',
help='Commission machines')
cd_group.add_argument('-D',
'--deploy',
action='store_true',
help='Deploy machines')
group.add_argument('-R',
'--release',
action='store_true',
help='Release machines requires --force to be set')
group.add_argument('-A',
'--abort',
action='store_true',
help='Abort machines requires --force to be set')
group.add_argument('--delete',
action='store_true',
help='Delete machines requires --force to be set')
parser.add_argument('--force',
action='store_true',
help='force (to override prompts)')
parser.add_argument('--skip-custom',
env_var='MAAS_SKIP_CUSTOM',
action='store_true',
help='Skips the custom commission firmware upgrade of'
' sas controller and the array drive smart tests')
parser.add_argument('-P', '--parallelism',
default=5,
type=int,
env_var='MAAS_PARALLELISM',
help='How many commission or deploy operations to do in '
'parallel. NOTE: if you have machine profiles with drive '
'exclusions, parallel deployments are DISABLED as it requires '
'interactive responses unless --force is used')
parser.add_argument('--limit', nargs='+',
help='List of entries from the CSV to limit this run to'
)
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--list-profiles',
action='store_true',
help='List Available machine profiles')
group.add_argument('-S',
'--show-profile',
help='Show machine profile <>')
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args()
setup_logger(args)
print(parser.format_values())
if args.debug_level != 'NOTSET':
LOGGER.debug('Debugging enabled')
if args.internal_config:
LOGGER.debug('internal_config file set to %s', args.internal_config)
if args.debug_level:
LOGGER.debug('debug level set to %s', args.debug_level)
if args.list_profiles:
LOGGER.debug('List profiles')
if args.show_profile:
LOGGER.debug('Show profile %s', args.show_profile)
if args.input_csv:
LOGGER.debug('Input CSV file %s', args.input_csv)
if args.commission:
LOGGER.debug('Told to Commission')
if args.deploy:
LOGGER.debug('Told to Deploy')
if args.release:
LOGGER.debug('Told to Release')
if args.delete:
LOGGER.debug('Told to Delete')
if args.lock:
LOGGER.debug('Told to Lock')
if args.unlock:
LOGGER.debug('Told to Unlock')
if args.force:
LOGGER.debug('force is set to true')
if args.limit:
LOGGER.debug('Limiting was selected')
if args.maas_proto:
LOGGER.debug('MaaS protocol to use %s', args.maas_proto)
if args.maas_port:
LOGGER.debug("MaaS port to use %i", args.maas_port)
if args.maas_server:
LOGGER.debug("MaaS server to use %s", args.maas_server)
if args.foreman_server:
LOGGER.debug("Foreman server to use %s", args.foreman_server)
if args.foreman_user:
LOGGER.debug("Foreman user to use %s", args.foreman_user)
#if args.foreman_pass:
# LOGGER.debug("Foreman password to use %s", args.foreman_pass)
if args.maas_api_key:
LOGGER.debug("MaaS API key to use %s", args.maas_api_key)
return args
def maas_authenticate(args: dict) -> object:
""" Authenticate to maas using passed profile, if nothing passed prompt """
if args.maas_api_key is None:
LOGGER.critical("Password auth doesn't work, possible API problem, "
"get an api key and use --maas-api-key instead")
exit(1)
else:
url = "%s://%s:%i/MAAS" % (args.maas_proto,
args.maas_server,
args.maas_port)
client = maas.client.connect(url, apikey=args.maas_api_key)
if not client:
LOGGER.critical("Unable to authenticate to MaaS at %s", url)
exit(1)
# Get a reference to self.
myself = client.users.whoami()
assert myself.is_admin, "%s is not an admin" % myself.username
# Check for a MAAS server capability.
version = client.version.get()
assert "devices-management" in version.capabilities
LOGGER.info("Authentication to MaaS successfull")
return client
def colonify_mac_address(mac: str) -> str:
""" Takes a non-colon delimited mac and returns a colon delimited one """
mac = re.sub('[.:-]', '', mac).lower() # remove delimiters and convert to lower case
mac = ''.join(mac.split()) # remove whitespaces
assert len(mac) == 12 # length should be now exactly 12 (eg. 00005e005300)
assert mac.isalnum() # should only contain letters and numbers
# convert mac in canonical form (eg. 00:00:5e:00:53:00)
mac = ":".join(["%s" % (mac[i:i+2]) for i in range(0, 12, 2)])
return mac
def add_machine(client: object, row: dict, skip_custom_commission: bool = False) -> object:
""" add and commisssion machines """
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Parse out the mac addresses from the encoded field
mac_addys = []
bond_macs = row['macs'].split(' ')
if ';' in row['macs']:
LOGGER.debug("Using mac addresses linked to bonds")
LOGGER.debug("Bond_macs is %s", bond_macs)
for interface in bond_macs:
LOGGER.debug("Interface %s", interface)
bmac = interface.split(';')
LOGGER.debug("Bond name %s, mac: %s", bmac[0], colonify_mac_address(bmac[1]))
mac_addys.append(bmac[1])
else:
for mac in bond_macs:
mac_addys.append(colonify_mac_address(mac))
LOGGER.info("Adding new machine %s.%s", row['shortname'], row['domain'])
nodes = client.nodes.read(hostnames=[row['shortname']])
if nodes:
LOGGER.info("%s: Is already known to maas, initiating custom commissioning",
row['shortname'])
for node in nodes:
machine = node.as_machine()
custom_commission(machine=machine, skip_custom_commission=skip_custom_commission)
return machine
LOGGER.info("%s: Didn't find it by name, trying to add it",
row['shortname'])
try:
machine = client.machines.create(
architecture="amd64",
mac_addresses=mac_addys[0],
power_type=row['power'],
power_parameters={
"power_address": row['powerip'],
"power_user": row['poweruser'],
"power_pass": row['powerpass'],
},
hostname=row['shortname'],
domain=row['domain'])
except maas.client.bones.CallError as err:
if "No rack controllers can acess the BMC" in str(err.content):
LOGGER.info("%s: Possible IPMI Credentials or firmware issue, aborting",
row['shortname'])
exit(1)
if "Hostname already exists" in str(err.content):
LOGGER.info("%s: is already known to maas",
row['shortname'])
if "already in use on" in str(err.content):
machine_name = str(err.content).partition("already in use on")[2].split()[0].rstrip('.')
LOGGER.info("%s: Found pre-existing machine %s as %s",
row['shortname'],
row['shortname'],
machine_name)
nodes = client.nodes.read(hostnames=[machine_name])
if not nodes:
LOGGER.error("%s: Unable to find machine %s", row['shortname'], machine_name)
else:
for node in nodes:
machine = node.as_machine()
dom = get_domain_object(client=client, domain=row['domain'])
LOGGER.info("%s: Renaming %s to %s.%s",
row['shortname'],
machine_name,
row['shortname'],
row['domain'])
machine.hostname = row['shortname']
machine.domain = dom
try:
machine.save()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: machine save error %s",
machine.hostname,
err.content)
return false
custom_commission(machine=machine,
skip_custom_commission=skip_custom_commission)
return machine
else:
LOGGER.error("%s: Error on line %i, trying to add machine %s, error %s",
LINE(),
row['shortname'],
err.content)
# Possible cases here:
# 1. Machine was previously on, so when commission was initiated
# it needs to power cycle it first
# 2. Machine was previously off, so when commission is initiated
# it powers it on
LOGGER.info("%s: Make sure machine is on", machine.hostname)
last_pwr_state = PowerState.UNKNOWN
while True:
time.sleep(1)
try:
machine.refresh()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: machine refresh error %s, continuing",
machine.hostname,
err.content)
continue
try:
pwr_state = machine.query_power_state()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: machine query_power_state error %s, continuing",
machine.hostname,
err.content)
continue
if last_pwr_state == PowerState.ON and pwr_state == PowerState.OFF:
LOGGER.info("%s: Last state on, currently off")
last_pwr_state = pwr_state
continue
if pwr_state == PowerState.OFF:
LOGGER.info("%s: Currently off", machine.hostname)
last_pwr_state = pwr_state
continue
elif pwr_state == PowerState.ON and last_pwr_state == PowerState.OFF:
LOGGER.info("%s: Last state off, Currently on", machine.hostname)
last_pwr_state = pwr_state
continue
elif pwr_state == PowerState.ON and last_pwr_state == PowerState.ON:
LOGGER.info("%s: is now powered ON", machine.hostname)
break
LOGGER.info("%s: Initiating Abort of auto-commmission", machine.hostname)
while True:
try:
machine.refresh()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: machine refresh error %s, continuing",
machine.hostname,
err.content)
continue
if machine.status == NodeStatus.COMMISSIONING:
try:
machine.abort()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: Abort failed (%s)",
machine.hostname,
err.content)
time.sleep(3)
continue
elif machine.status == NodeStatus.DEFAULT:
pwr_state = machine.query_power_state()
if pwr_state == PowerState.OFF:
LOGGER.info("%s: is now in NEW/OFF state", machine.hostname)
break
else:
continue
LOGGER.info("%s: Running commission with custom scripts", machine.hostname)
custom_commission(machine=machine, skip_custom_commission=skip_custom_commission)
return machine
def get_domain_object(client: object = None, domain: str = None,) -> object:
""" Get domains list from maas, match str and return object """
try:
doms = client.domains.list()
except maas.client.bones.CallError as err:
LOGGER.warning("Failed to retrieve domain list, %s",
err.content)
for dom in doms:
if dom.name == domain:
return dom
return None
def custom_commission(machine: object = None, skip_custom_commission: bool = False) -> None:
""" Initiate custom commissioning """
while True:
try:
machine.refresh()
except maas.client.bones.CallError as err:
LOGGER.warning("%s: machine refresh error %s, continuing",
machine.hostname,
err.content)
continue
if machine.status != NodeStatus.COMMISSIONING:
LOGGER.info("%s: Attempting to start custom commissioning", machine.hostname)
try:
if skip_custom_commission:
# disabling testing scripts and custom commissioning
# sas controller firmware upgrade
machine.commission(testing_scripts=[])
else:
machine.commission(commissioning_scripts=["update_firmware"])
except maas.client.bones.CallError as err:
#LOGGER.error("Error on line %i, trying to add machine %s, error %s",
# LINE(),
# row['shortname'],
# err.content)
LOGGER.info("%s: Custom Commission Failed, retrying...", machine.hostname)
else:
LOGGER.info("%s: Custom commission initiated successfully", machine.hostname)
return
def get_list_of_machines_from_maas(client: object, machines: list) -> typing.Tuple[list, list]:
""" Search for machines and return a list of found and not found """
found = []
not_found = machines.copy()
hostnames = []
for machine in machines:
hostnames.append(machine['shortname'])
nodes = client.nodes.read(hostnames=hostnames)
for node in nodes:
for machine in machines:
if machine['shortname'] == node.hostname:
machine['system_id'] = node.system_id
machine['node'] = node
machine['status'] = node.as_machine().status
found.append(machine)
not_found.remove(machine)
return found, not_found
def get_commissionable_machines(client: object, machines: list) -> list:
""" Get commissionable machines
Query maas for known machines
Figure out which ones are commissionable by their state
and add them """
found, not_found = get_list_of_machines_from_maas(client=client, machines=machines)
LOGGER.info("Maas knows about %i machines", len(found))
LOGGER.info("%i machines were't found in maas", len(not_found))
commissionable_machines = not_found.copy()
for machine in found:
if machine['status'] in [
NodeStatus.NEW,
NodeStatus.READY,
NodeStatus.FAILED_COMMISSIONING]:
LOGGER.info("%s: Is commissionable", machine['shortname'])
commissionable_machines.append(machine)
else:
LOGGER.info("%s: Is NOT commissionable (%s)",
machine['shortname'],
machine['status'])
return commissionable_machines
def get_deployable_machines(client: object, machines: list, config: dict) -> list:
""" Get deployable machines """
found = []
hostnames = []
for machine in machines:
hostnames.append(machine['shortname'])
nodes = client.nodes.read(hostnames=hostnames)
count = 0
for node in nodes:
count += 1
for machine in machines:
if machine['shortname'] == node.hostname:
machine['system_id'] = node.system_id
machine['node'] = node
machine['status'] = node.as_machine().status
found.append(machine)
LOGGER.info("Maas knows about %i machines", count)
deployable_machines = []
for machine in found:
if machine['status'] in [
NodeStatus.READY]:
if machine['machine_profile'] not in config['machine_profiles']:
LOGGER.error("Error on line %i, Machine profile (%s) "
"isn't found, skipping host",
LINE(),
machine['machine_profile'])
else:
LOGGER.info("%s: Is deployable", machine['shortname'])
deployable_machines.append(machine)
else:
LOGGER.info("%s: Is NOT deployable (%s)",
machine['shortname'],
machine['status'])
return deployable_machines
def delete_machines(client: object, machines_to_delete: list, parallelism: int) -> None:
""" Delete's machines in maas """
with ThreadPoolExecutorStackTraced(max_workers=(parallelism)) as executor:
future_to_machine = {executor.submit(delete_machine,
client,
name['shortname']): \
name for name in machines_to_delete}
for future in concurrent.futures.as_completed(future_to_machine):
row = future_to_machine[future]
try:
data = future.result()
except Exception as exc:
LOGGER.error("%r generated an exception: %s", row, exc)
def delete_machine(client: object, name: str) -> None:
""" Threaded deleter Delete's machines in maas """
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
nodes = client.nodes.read(hostnames=[name])
if not nodes:
LOGGER.warning("%s: Is not known to maas", name)
for node in nodes:
if node.hostname == name:
machine = node.as_machine()
try:
LOGGER.info("%s: Deleting", machine.hostname)
machine.delete()
except maas.client.bones.CallError as err:
LOGGER.error("Error on line %i, trying to delete machine %s, error %s",
LINE(),
machine.hostname,
err.content)
def unlock_machines(client: object, machines_to_unlock: list, parallelism: int) -> None:
""" Unlock's machines in maas """
with ThreadPoolExecutorStackTraced(max_workers=(parallelism)) as executor:
future_to_machine = {executor.submit(unlock_machine,
client,
name['shortname']): \
name for name in machines_to_unlock}
for future in concurrent.futures.as_completed(future_to_machine):
row = future_to_machine[future]
try:
data = future.result()
except Exception as exc:
LOGGER.error("%r generated an exception: %s", row, exc)
def unlock_machine(client: object, name: str) -> object:
""" Threaded unlocker """
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
nodes = client.nodes.read(hostnames=[name])
if not nodes:
LOGGER.warning("%s: Is not known to maas", name)
for node in nodes:
if node.hostname == name:
machine = node.as_machine()
if machine.locked:
try:
LOGGER.info("%s: Unlocking", machine.hostname)
machine.unlock(
comment="Unlocked by Maasterblaster user: " + os.environ["USER"])
except maas.client.bones.CallError as err:
LOGGER.error("Error on line %i, trying to unlock machine %s, error %s",
LINE(),
machine.hostname,
err.content)
else:
LOGGER.info("%s: isn't locked", machine.hostname)
def lock_machines(client: object, machines_to_lock: list, parallelism: int) -> None:
""" lock's machines in maas """
with ThreadPoolExecutorStackTraced(max_workers=(parallelism)) as executor:
future_to_machine = {executor.submit(lock_machine,