/
quads-cli
executable file
·570 lines (504 loc) · 25.5 KB
/
quads-cli
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
#!/usr/bin/env python3
# This file is part of QUADs.
#
# QUADS 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.
#
# QUADS 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 QUADs. If not, see <http://www.gnu.org/licenses/>.
import argparse
import asyncio
import datetime
import functools
import logging
from collections import defaultdict
import requests
import signal
import subprocess
import sys
import os
from json import JSONDecodeError
from quads.config import conf, API_URL
from quads.quads import Api as QuadsApi
from quads.tools.move_and_rebuild_hosts import move_and_rebuild, switch_config
from quads.model import Cloud, Schedule, Host
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.propagate = False
logging.basicConfig(level=logging.INFO, format="%(message)s")
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def output_json_result(request, data):
try:
if request.status_code == 204:
logger.info('Removed: %s' % data)
else:
js = request.json()
logger.debug('%s %s: %s' % (request.status_code, request.reason, data))
for result in js['result']:
if type(result) == list:
for line in result:
logger.info(line)
else:
logger.info(result)
except JSONDecodeError:
logger.error('Could not parse json reply.')
logger.debug(request.text)
exit(1)
def exception_handler(loop, context):
logger.error(f"Caught exception: {context['message']}")
def main(_args):
# List all common call
quads = QuadsApi(API_URL)
if _args.action:
_kwargs = {}
if _args.cloudonly:
_kwargs["cloud"] = _args.cloudonly
if _args.host:
_kwargs["host"] = _args.host
if _args.datearg:
_kwargs["date"] = datetime.datetime.strptime(_args.datearg, '%Y-%m-%d %H:%M').isoformat()
if _args.action in ['owner', 'ticket', 'qinq', 'wipe', 'ccuser']:
data = quads.get(_args.action)
if data:
for k in data:
if isinstance(k[_args.action], list):
logger.info(str(k['name']) + ": " + str(", ".join(k[_args.action])))
else:
logger.info(str(k['name']) + ": " + str(k[_args.action]))
exit(0)
if _args.action == 'interface':
if _args.host is None:
logger.error('Missing option. --host option is required for --ls-interface:')
exit(1)
_host = Host.objects(name=_args.host).first()
if not _host:
logger.error('Host %s does not exist' % _args.host)
exit(1)
data = quads.get_interfaces(**_kwargs)
if data:
for interface in data["result"]:
logger.info(interface)
exit(0)
if _args.action == 'schedule':
if _args.host:
_host = Host.objects(name=_args.host).first()
if not _host:
logger.error('Host %s does not exist' % _args.host)
exit(1)
_kwargs["host"] = _host
logger.info("Default cloud: %s" % _host.default_cloud.name)
_current_schedule = Schedule.current_schedule(**_kwargs)
if _current_schedule:
_current_cloud = _current_schedule[0].cloud.name
if _current_cloud != _host.default_cloud.name:
logger.info("Current cloud: %s" % _current_cloud)
logger.info("Current schedule: %s" % _current_schedule[0].index)
else:
logger.info("Current cloud: %s" % _host.default_cloud.name)
else:
logger.info("Current cloud: %s" % _host.default_cloud.name)
if "date" in _kwargs:
_kwargs.pop("date")
_host_schedules = Schedule.objects(**_kwargs)
if _host_schedules:
for schedule in _host_schedules:
_cloud_name = schedule.cloud.name
start = str(schedule.start)[:-3]
end = str(schedule.end)[:-3]
logger.info(
"%s| start=%s, end=%s, cloud=%s" % (
schedule["index"],
start,
end,
_cloud_name)
)
else:
_clouds = Cloud.objects()
for cloud in _clouds:
logger.info("%s:" % cloud.name)
_kwargs["cloud"] = cloud.name
if cloud.name == "cloud01":
if _kwargs.get("date"):
data = {
"start": _kwargs["date"],
"end": _kwargs["date"],
}
available_hosts = quads.get_available(**data)
for host in available_hosts:
logger.info(host)
else:
_hosts = Host.objects(cloud=cloud)
for host in _hosts:
logger.info(host.name)
else:
_schedules = quads.get_current_schedule(**_kwargs)
if _schedules and "result" not in _schedules:
if type(_schedules) == list:
for entry in _schedules:
host = quads.get_hosts(id=entry["host"]["$oid"])
logger.info("- %s" % str(host['name']))
else:
host = quads.get_hosts(id=_schedules["host"]["$oid"])
logger.info("- %s" % str(host['name']))
exit(0)
elif _args.action in ['host', 'cloud']:
entries = quads.get(_args.action)
if entries and "result" not in entries:
for entry in sorted(entries, key=lambda k: k['name']):
logger.info(entry['name'])
elif "result" in entries:
logger.info(entries['result'])
exit(0)
elif _args.action == "available":
if _args.schedstart and _args.schedend is None:
_args.schedend = _args.schedstart
if _args.schedstart is None and _args.schedend:
_args.schedstart = str(datetime.datetime.now())[:-10]
if _args.schedstart is None and _args.schedend is None:
_args.schedstart = _args.schedend = str(datetime.datetime.now())[:-10]
_start = datetime.datetime.strptime(_args.schedstart, '%Y-%m-%d %H:%M').isoformat()
_end = datetime.datetime.strptime(_args.schedend, '%Y-%m-%d %H:%M').isoformat()
data = {
"start": _start,
"end": _end,
}
available_hosts = quads.get_available(**data)
for host in available_hosts:
logger.info(host)
exit(0)
elif _args.action == "free_cloud":
_clouds = Cloud.objects(name__ne="cloud01")
for cloud in _clouds:
cloud_count = Schedule.objects(end__gte=datetime.datetime.now(), cloud=cloud).count()
if cloud_count > 0:
continue
else:
logger.info(cloud.name)
exit(0)
# Cloud Add / Modify
elif _args.cloudresource:
data = {'name': _args.cloudresource,
'description': _args.description,
'owner': _args.cloudowner,
'ccuser': _args.ccusers,
'qinq': _args.qinq,
'wipe': _args.wipe,
'ticket': _args.cloudticket,
'vlan': _args.vlan,
'force': _args.force}
logger.info(quads.insert_cloud(data)["result"])
exit(0)
# Cloud Remove
elif _args.rmcloud is not None:
url = os.path.join(API_URL, 'cloud', _args.rmcloud)
_response = requests.delete(url)
output_json_result(_response, {'cloud': _args.rmcloud})
exit(0)
# Host Add / Modify
elif _args.hostresource:
if not _args.hostcloud:
logger.error('Missing option --default-cloud')
exit(1)
if _args.cloudresource:
logger.error('--define-cloud and --define-host are mutually exclusive.')
exit(1)
url = os.path.join(API_URL, 'host')
data = {'name': _args.hostresource,
'default_cloud': _args.hostcloud,
'host_type': _args.hosttype,
'force': _args.force}
_response = requests.post(url, data)
output_json_result(_response, data)
exit(0)
# Host Remove
elif _args.rmhost is not None:
_host = Host.objects(name=_args.rmhost).first()
future_schedules = Schedule.future_schedules(host=_host)
if future_schedules:
logger.error("Can't remove host with future schedule.")
exit(1)
url = os.path.join(API_URL, 'host', _args.rmhost)
_response = requests.delete(url)
output_json_result(_response, {'host': _args.rmhost})
exit(0)
# Add Interface
elif _args.addinterface:
if _args.ifmac is None \
or _args.ifip is None or _args.ifport is None \
or _args.host is None:
logger.error('Missing option. All these options are required for --add-interface:')
logger.error(' --host')
logger.error(' --interface-mac')
logger.error(' --interface-ip')
logger.error(' --interface-port')
url = os.path.join(API_URL, 'interfaces')
data = {
'name': _args.addinterface,
'mac_address': _args.ifmac,
'ip_address': _args.ifip,
'switch_port': _args.ifport,
'host': _args.host,
'force': _args.force
}
_response = requests.post(url, data)
output_json_result(_response, data)
exit(0)
elif _args.rminterface is not None:
if _args.host is None:
logger.error('Missing option. --host option is required for --rm-interface:')
exit(1)
data = {'host': _args.host, 'name': _args.rminterface}
logger.info(quads.remove_interface(**data))
exit(0)
# Add Schedule
elif _args.addschedule:
if _args.schedstart is None or _args.schedend is None \
or _args.schedcloud is None or _args.host is None:
logger.error('Missing option. All these options are required for --add-schedule:')
logger.error(' --host')
logger.error(' --schedule-start')
logger.error(' --schedule-end')
logger.error(' --schedule-cloud')
exit(1)
data = {'cloud': _args.schedcloud,
'host': _args.host,
'start': _args.schedstart,
'end': _args.schedend}
logger.info(quads.insert_schedule(data)['result'])
exit(0)
elif _args.rmschedule is not None:
if _args.host:
data = {"host": _args.host, "index": str(_args.rmschedule)}
logger.info(quads.remove_schedule(**data))
exit(0)
else:
logger.error('Missing option. Need --host when using --rm-schedule')
exit(1)
elif _args.modschedule is not None:
if _args.host is None:
logger.error('Missing option. Need --host when using --mod-schedule')
exit(1)
if _args.schedstart is None and _args.schedend is None and _args.schedcloud is None:
logger.error('Missing option. At least one these options are required for --mod-schedule:')
logger.error(' --schedule-start')
logger.error(' --schedule-end')
logger.error(' --schedule-cloud')
exit(1)
data = {'index': _args.modschedule,
'start': _args.schedstart,
'end': _args.schedend,
'cloud': _args.schedcloud,
'host': _args.host}
logger.info(quads.insert_schedule(data)["result"])
exit(0)
elif _args.movehosts:
if _args.datearg is not None and not _args.dryrun:
logger.error('--move-hosts and --date are mutually exclusive unless using --dry-run.')
exit(1)
url = os.path.join(API_URL, 'moves')
data = {}
if _args.datearg is not None:
data['date'] = datetime.datetime.strptime(_args.datearg, '%Y-%m-%d %H:%M').isoformat()
_response = requests.get(url, data)
js = _response.json()
if 'result' in js:
if len(js['result']) == 0:
logger.info('Nothing to do.')
exit(0)
_clouds = defaultdict(list)
for result in js['result']:
_clouds[result['new']].append(result)
# TODO:
# raise the number of semaphores after this is resolved
# https://projects.theforeman.org/issues/27953#change-127120
semaphore = asyncio.Semaphore(1)
for _cloud, results in _clouds.items():
provisioned = True
tasks = []
switch_tasks = []
for result in results:
host = result['host']
current = result['current']
new = result['new']
cloud = Cloud.objects(name=new).first()
logger.info('Moving %s from %s to %s, wipe = %s' % (host, current, new, cloud.wipe))
if not _args.dryrun:
try:
if _args.movecommand == default_move_command:
fn = functools.partial(move_and_rebuild, host, current, new, semaphore, cloud.wipe)
tasks.append(fn)
switch_tasks.append(functools.partial(switch_config, host, current, new))
else:
if cloud.wipe:
subprocess.check_call([args.movecommand, host, current, new])
else:
subprocess.check_call([args.movecommand, host, current, new, "nowipe"])
except:
logger.exception('Move command failed for host: %s' % host)
provisioned = False
if not _args.dryrun:
done = None
loop = asyncio.get_event_loop()
loop.set_exception_handler(exception_handler)
try:
done = loop.run_until_complete(
asyncio.gather(*[task(loop) for task in tasks])
)
except (asyncio.CancelledError, SystemExit, Exception, TimeoutError):
logger.exception('Move command failed')
provisioned = False
for task in switch_tasks:
try:
logger.info(f"Running switch config for {task.args[0]}")
task()
except Exception:
logger.exception("There was something wrong configuring the switch.")
provisioned = False
# TODO: Add logic here for setting host to validated=false
# if result["new"]==default_cloud
if done:
for future in done:
if isinstance(future, Exception):
provisioned = False
else:
provisioned = provisioned and future
if provisioned:
_new_cloud_obj = Cloud.objects(name=_cloud).first()
_new_cloud_obj.update(provisioned=True)
_old_cloud_obj = Cloud.objects(name=results[0]["current"]).first()
_old_cloud_obj.update(provisioned=False, validated=False, vlan=None, wipe=True)
exit(0)
elif _args.host:
_host = Host.objects(name=_args.host).first()
if _host:
_kwargs = {"host": _host}
if _args.datearg:
_kwargs["date"] = datetime.datetime.strptime(_args.datearg, '%Y-%m-%d %H:%M').isoformat()
schedules = Schedule.current_schedule(**_kwargs)
if schedules:
for schedule in schedules:
logger.info(schedule.cloud.name)
else:
logger.info(_host.default_cloud.name)
else:
logger.info('Unknown host: %s' % _args.host)
exit(1)
exit(0)
elif _args.cloudonly:
_cloud = Cloud.objects(name=_args.cloudonly).first()
_kwargs = {"cloud": _cloud}
if _args.datearg:
_kwargs["date"] = datetime.datetime.strptime(_args.datearg, '%Y-%m-%d %H:%M').isoformat()
schedules = Schedule.current_schedule(**_kwargs)
if schedules:
for schedule in sorted(schedules, key=lambda k: k['host']['name']):
logger.info(schedule.host.name)
else:
if _kwargs.get("date") and _args.cloudonly == "cloud01":
data = {
"start": _kwargs["date"],
"end": _kwargs["date"],
}
available_hosts = quads.get_available(**data)
for host in sorted(available_hosts):
logger.info(host)
else:
_hosts = Host.objects(cloud=_cloud)
for host in sorted(_hosts, key=lambda k: k['name']):
logger.info(host.name)
exit(0)
elif _args.summary or _args.fullsummary:
_kwargs = {}
if _args.datearg:
_kwargs["date"] = datetime.datetime.strptime(_args.datearg, '%Y-%m-%d %H:%M').isoformat()
summary = quads.get_summary()
for cloud in summary:
if _args.fullsummary or cloud["count"] > 0:
logger.info("%s: %s (%s)" % (cloud["name"], cloud["count"], cloud["description"]))
exit(0)
elif _args.version:
version = quads.get_version()
if "result" in version:
logger.info(version["result"])
exit(0)
logger.info('No result received')
exit(0)
if __name__ == '__main__':
sys.path.append(conf['install_dir'])
sys.path.append(os.path.dirname(__file__) + '/../')
default_move_command = '/opt/quads/quads/tools/move_and_rebuild_hosts.py'
parser = argparse.ArgumentParser(description='Query current cloud for a given host')
group = parser.add_mutually_exclusive_group()
group.add_argument('--ls-owner', dest='action', action='store_const', const='owner', help='List owners')
group.add_argument('--ls-cc-users', dest='action', action='store_const', const='ccuser', help='List CC list')
group.add_argument('--ls-ticket', dest='action', action='store_const', const='ticket', help='List request ticket')
group.add_argument('--ls-qinq', dest='action', action='store_const', const='qinq', help='List cloud qinq state')
group.add_argument('--ls-wipe', dest='action', action='store_const', const='wipe', help='List cloud wipe state')
group.add_argument('--define-host', dest='hostresource', type=str, default=None, help='Define a host resource')
group.add_argument('--define-cloud', dest='cloudresource', type=str, default=None,
help='Define a cloud environment')
group.add_argument('--add-schedule', dest='addschedule', action='store_true', help='Define a host reservation')
group.add_argument('--mod-schedule', dest='modschedule', type=str, default=None, help='Modify a host reservation')
group.add_argument('--add-interface', dest='addinterface', type=str, default=None, help='Define a host interface')
group.add_argument('--rm-schedule', dest='rmschedule', type=str, default=None, help='Remove a host reservation')
group.add_argument('--rm-interface', dest='rminterface', type=str, default=None, help='Remove a host interface')
group.add_argument('--ls-hosts', dest='action', action='store_const', const='host', help='List all hosts')
group.add_argument('--ls-clouds', dest='action', action='store_const', const='cloud', help='List all clouds')
group.add_argument('--rm-host', dest='rmhost', type=str, default=None, help='Remove a host')
group.add_argument('--rm-cloud', dest='rmcloud', type=str, default=None, help='Remove a cloud')
group.add_argument('--ls-available', dest='action', action='store_const', const='available',
help='List available hosts on a specific time frame')
group.add_argument('--ls-schedule', dest='action', action='store_const', const='schedule',
help='List the host reservations')
group.add_argument('--ls-interface', dest='action', action='store_const', const='interface',
help='List the host interfaces')
group.add_argument('--find-free-cloud', dest='action', action='store_const', const='free_cloud',
help='List available hosts on a specific time frame')
parser.add_argument('--host', dest='host', type=str, default=None, help='Specify the host to query')
parser.add_argument('--cloud-only', dest='cloudonly', type=str, default=None,
help='Limit full report to hosts only in this cloud')
parser.add_argument('-d', '--datetime', dest='datearg', type=str, default=None,
help='date and time to query; e.g. "2016-06-01 08:00"')
parser.add_argument('--cloud-owner', dest='cloudowner', type=str, default=None, help='Define environment owner')
parser.add_argument('--cc-users', dest='ccusers', type=str, default=None, help='Define environment CC list')
parser.add_argument('--qinq', dest='qinq', type=str, default=None, help='Define environment qinq state')
parser.add_argument('--no-wipe', dest='wipe', action='store_false',
help='Define no wipe for safeguarding data after assignment')
parser.add_argument('--cloud-ticket', dest='cloudticket', type=str, default=None, help='Define environment ticket')
parser.add_argument('--description', dest='description', type=str, default=None,
help='Defined description of cloud')
parser.add_argument('--default-cloud', dest='hostcloud', type=str, default=None,
help='Defined default cloud for a host')
parser.add_argument('--force', dest='force', action='store_true',
help='Force host or cloud update when already defined')
parser.add_argument('--summary', dest='summary', action='store_true', help='Generate a summary report')
parser.add_argument('--full-summary', dest='fullsummary', action='store_true', help='Generate a summary report')
parser.add_argument('--schedule-start', dest='schedstart', type=str, default=None, help='Schedule start date/time')
parser.add_argument('--schedule-end', dest='schedend', type=str, default=None, help='Schedule end date/time')
parser.add_argument('--schedule-cloud', dest='schedcloud', type=str, default=None, help='Schedule cloud')
parser.add_argument('--interface-mac', dest='ifmac', type=str, default=None, help='MAC address for --add-interface')
parser.add_argument('--interface-ip', dest='ifip', type=str, default=None, help='IP address for --add-interface')
parser.add_argument('--interface-port', dest='ifport', type=str, default=None,
help='Switch port for --add-interface')
parser.add_argument('--move-hosts', dest='movehosts', action='store_true', default=None,
help='Move hosts if schedule has changed')
parser.add_argument('--move-command', dest='movecommand', type=str, default=default_move_command,
help='External command to move a host')
parser.add_argument('--dry-run', dest='dryrun', action='store_true', default=None,
help="Don't update state when used with --move-hosts")
parser.add_argument('--log-path', dest='logpath', type=str, default=None, help='Path to quads log file')
parser.add_argument('--host-type', dest='hosttype', type=str, default=None,
help='Open-ended identifier for host: util, baremetal, aws, openstack, libvirt, etc.')
parser.add_argument('--vlan', dest='vlan', type=int, default=None,
help='VLAN id number for public routable network')
parser.add_argument('--debug', action='store_true', default=False, help='Show debugging information.')
parser.add_argument('--version', dest='version', action='store_true', help='Display version of QUADS')
args = parser.parse_args()
main(args)