This repository has been archived by the owner on Dec 31, 2019. It is now read-only.
/
actions.py
1523 lines (1443 loc) · 69.9 KB
/
actions.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
import ast
import docker
import getpass
import json
import os
import queue
import re
import shutil
import tempfile
import urllib
import yaml
from vent.api.plugins import Plugin
from vent.api.templates import Template
from vent.helpers.logs import Logger
from vent.helpers.meta import Containers
from vent.helpers.meta import Dependencies
from vent.helpers.meta import Images
from vent.helpers.meta import ParsedSections
from vent.helpers.meta import Timestamp
from vent.helpers.paths import PathDirs
class Action:
""" Handle actions in menu """
def __init__(self, **kargs):
self.plugin = Plugin(**kargs)
self.d_client = self.plugin.d_client
self.vent_config = self.plugin.path_dirs.cfg_file
self.startup_file = self.plugin.path_dirs.startup_file
self.p_helper = self.plugin.p_helper
self.queue = queue.Queue()
self.logger = Logger(__name__)
def add(self, repo, tools=None, overrides=None, version="HEAD",
branch="master", build=True, user=None, pw=None, groups=None,
version_alias=None, wild=None, remove_old=True, disable_old=True):
""" Add a new set of tool(s) """
self.logger.info("Starting: add")
status = (True, None)
try:
# remove tools that are already installed from being added
if isinstance(tools, list):
i = len(tools) - 1
while i >= 0:
tool = tools[i]
if tool[0].find('@') >= 0:
tool_name = tool[0].split('@')[-1]
else:
tool_name = tool[0].rsplit('/', 1)[-1]
constraints = {'name': tool_name,
'repo': repo.split('.git')[0]}
prev_installed, _ = self.p_helper. \
constraint_options(constraints, [])
# don't reinstall
if prev_installed:
tools.remove(tool)
i -= 1
if tools is None or len(tools) > 0:
is_core = repo == 'https://github.com/cyberreboot/vent'
status = self.plugin.add(repo,
tools=tools,
overrides=overrides,
version=version,
branch=branch,
build=build,
user=user,
pw=pw,
groups=groups,
version_alias=version_alias,
wild=wild,
remove_old=remove_old,
disable_old=disable_old,
core=is_core)
else:
self.logger.info("no new tools to add, exiting")
status = (True, "previously installed")
except Exception as e: # pragma: no cover
self.logger.error("add failed with error: " + str(e))
status = (False, str(e))
self.logger.info("Status of add: " + str(status[0]))
self.logger.info("Finished: add")
return status
def add_image(self,
image,
link_name,
tag=None,
registry=None,
groups=None):
""" Add a new image from a Docker registry """
self.logger.info("Starting: add image")
status = (True, None)
try:
status = self.plugin.add_image(image,
link_name,
tag=tag,
registry=registry,
groups=groups)
except Exception as e: # pragma: no cover
self.logger.error("add image failed with error: " + str(e))
status = (False, str(e))
self.logger.info("Status of add image: " + str(status[0]))
self.logger.info("Finished: add image")
return status
def remove(self, repo=None, namespace=None, name=None, groups=None,
enabled="yes", branch="master", version="HEAD", built="yes"):
""" Remove tools or a repo """
self.logger.info("Starting: remove")
status = (True, None)
try:
# don't want to include groups because constrained_sections will
# return everything that matches that group, possibly removing
# things we don't want to remove
if groups:
groups = None
status = self.plugin.remove(name=name,
repo=repo,
namespace=namespace,
groups=groups,
enabled=enabled,
branch=branch,
version=version,
built=built)
# remove any dependant/child of the current container
child_name = str(name) + '_child'
for container in self.d_client.containers.list():
if ('vent.groups' in container.attrs['Config']['Labels'] and
child_name in container.attrs['Config']['Labels']['vent.groups']):
container.remove(force=True)
except Exception as e: # pragma: no cover
self.logger.error("remove failed with error: " + str(e))
status = (False, e)
self.logger.info("Status of remove: " + str(status[0]))
self.logger.info("Finished: remove")
return status
def prep_start(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD"):
""" Prep a bunch of containers to be started to they can be ordered """
args = locals()
del args['self']
self.logger.info("Starting: prep_start")
status = self.p_helper.prep_start(**args)
self.logger.info("Status of prep_start: " + str(status[0]))
self.logger.info("Finished: prep_start")
return status
def start(self, tool_d):
"""
Start a set of tools that match the parameters given, if no parameters
are given, start all installed tools on the master branch at verison
HEAD that are enabled
"""
self.logger.info("Starting: start")
status = (True, None)
try:
# check start priorities (priority of groups alphabetical for now)
group_orders = {}
groups = []
containers_remaining = []
username = getpass.getuser()
for container in tool_d:
containers_remaining.append(container)
self.logger.info(
"User: " + username +
" starting container: " + str(container)
)
if 'labels' in tool_d[container]:
if 'vent.groups' in tool_d[container]['labels']:
groups += tool_d[container]['labels']['vent.groups'].split(',')
if 'vent.priority' in tool_d[container]['labels']:
priorities = tool_d[container]['labels']['vent.priority'].split(',')
container_groups = tool_d[container]['labels']['vent.groups'].split(',')
for i, priority in enumerate(priorities):
if container_groups[i] not in group_orders:
group_orders[container_groups[i]] = []
group_orders[container_groups[i]].append((int(priority), container))
containers_remaining.remove(container)
tool_d[container]['labels'].update(
{"started-by": username}
)
else:
tool_d[container].update(
{'labels': {"started-by": username}}
)
self.logger.info("group orders: " + str(group_orders))
self.logger.info("containers remaining: " +
str(containers_remaining))
# start containers based on priorities
p_results = self.p_helper.start_priority_containers(groups,
group_orders,
tool_d)
# start the rest of the containers that didn't have any priorities
r_results = self.p_helper.start_remaining_containers(containers_remaining, tool_d)
results = (p_results[0] + r_results[0],
p_results[1] + r_results[1])
if len(results[1]) > 0:
status = (False, results)
else:
status = (True, results)
except Exception as e: # pragma: no cover
self.logger.error("start failed with error: " + str(e))
status = (False, str(e))
self.logger.info("Status of start: " + str(status[0]))
self.logger.info("Finished: start")
self.queue.put(status)
return status
def update(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD",
new_version="HEAD"):
"""
Update a set of tools that match the parameters given, if no parameters
are given, updated all installed tools on the master branch at verison
HEAD that are enabled
"""
args = locals()
del args['new_version']
self.logger.info("Starting: update")
self.logger.info(args)
status = (True, None)
try:
options = ['path', 'image_name', 'image_id', 'running',
'multi_tool', 'name', 'link_name']
s, template = self.p_helper.constraint_options(args, options)
# get existing containers and images and states
running_containers = Containers()
built_images = Images()
self.logger.info("running docker containers: " +
str(running_containers))
self.logger.info("built docker images: " + str(built_images))
# if repo, pull and build
# if registry image, pull
for section in s:
try:
cwd = os.getcwd()
self.logger.info("current working directory: " + str(cwd))
os.chdir(s[section]['path'])
c_status = self.p_helper.checkout(branch=branch,
version=new_version)
self.logger.info(c_status)
os.chdir(cwd)
self.plugin.builder(template,
s[section]['path'],
s[section]['image_name'],
section,
build=True,
branch=branch,
version=new_version)
# exit if no changes were made
if (template.option(section, 'image_id')[1] ==
s[section]['image_id']):
self.logger.info("No changes made through update")
self.logger.info("Status of update: True")
self.logger.info("Finished: update")
return (True, "no changes made")
# update any new vent.template settings that may have been set
vent_template_path = s[section]['path']
if s[section]['multi_tool'] == 'yes':
name = s[section]['name']
if name == 'unspecified':
name = 'vent'
vent_template_path = os.path.join(vent_template_path,
name+'.template')
else:
vent_template_path = os.path.join(vent_template_path,
'vent.template')
if os.path.exists(vent_template_path):
vent_template = Template(vent_template_path)
for setting in vent_template.sections()[1]:
# perserve customizations
prev_dict = template.option(section, setting)
if prev_dict[0]:
prev_dict = json.loads(prev_dict[1])
else:
prev_dict = {}
self.logger.info('old settings for option ' +
setting + ' are: ' +
str(prev_dict))
opt_vals = vent_template.section(setting)[1]
self.logger.info('new settings:')
for opt_val in opt_vals:
name = opt_val[0]
val = opt_val[1]
if name == 'name':
name = 'link_name'
self.logger.info(name + ' = ' + val)
# set groups and link_name individually
if name in ['link_name', 'groups']:
template.set_option(section, name, val)
if name not in prev_dict:
prev_dict.update({name: val})
# check to see if a list variable has been updated
elif prev_dict[name] != val:
prev_dict.update({name: val})
template.set_option(section, setting,
json.dumps(prev_dict))
# reset containers that may be affected by changes,
# including dependencies
tool_d = {}
if (s[section]['running'] == 'yes'):
# find dependencies that will need to be restarted
# once this tool is reset
prev_dependencies = []
for t_sect in template.sections()[1]:
self.logger.info("Testing check tool: " + t_sect)
t_name = template.option(t_sect, 'name')[1]
t_branch = template.option(t_sect, 'branch')[1]
t_version = template.option(t_sect, 'version')[1]
self.logger.info(t_name + ', ' + t_branch + ', ' + t_version)
t_identifier = {'name': t_name,
'branch': t_branch,
'version': t_version}
# don't worry about dealing with tool if it's not
# running
running = template.option(t_sect, 'running')
if (not running[0] or running[1] != 'yes' or
t_name == s[section]['name']):
self.logger.info("tool not dependency," +
" skipping to next")
continue
options = template.options(t_sect)[1]
self.logger.info(options)
if 'docker' in options:
d_settings = json.loads(template.option(t_sect,
'docker')[1])
self.logger.info(d_settings)
if 'links' in d_settings:
for link in json.loads(d_settings['links']):
if link == s[section]['link_name']:
prev_dependencies.append(t_identifier)
# remove old containers, start new
self.logger.info("running tools to be restarted: " +
str(prev_dependencies))
for tool in prev_dependencies:
self.clean(**tool)
tool_d.update(self.prep_start(**tool)[1])
# clean tool before new manifest entry to get rid of
# old tool
self.clean(name=s[section]['name'], branch=branch,
version=version)
# finish writing new manifest entry, including creating new
# section name and deleting old image
template.set_option(section, 'version', new_version)
template.set_option(section, 'running', s[section]['running'])
old_image = template.option(section, 'image_name')[1]
self.logger.info("Testing old.... " + old_image)
new_image = old_image.rsplit(':', 1)[0]+':'+new_version
template.set_option(section, 'image_name', new_image)
# create new section
new_section = section.rsplit(':', 1)[0]+':'+new_version
template.add_section(new_section)
old_section = template.section(section)[1]
for val in old_section:
template.set_option(new_section, val[0], val[1])
# remove old section and image
self.d_client.images.remove(old_image, force=True)
template.del_section(section)
template.write_config()
# now we can start new tool with correct info in manifest
tool_d.update(self.prep_start(name=s[section]['name'],
branch=branch,
version=new_version)[1])
self.start(tool_d)
except Exception as e: # pragma: no cover
self.logger.error("unable to update: " + str(section) +
" because: " + str(e))
except Exception as e: # pragma: no cover
self.logger.error("update failed with error: " + str(e))
status = (False, e)
self.logger.info("Status of update: " + str(status[0]))
self.logger.info("Finished: update")
return status
def stop(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD"):
"""
Stop a set of tools that match the parameters given, if no parameters
are given, stop all installed tools on the master branch at verison
HEAD that are enabled
"""
args = locals()
self.logger.info("Starting: stop")
self.logger.info(args)
status = (True, None)
try:
# !! TODO need to account for plugin containers that have random
# names, use labels perhaps
options = ['name',
'namespace',
'built',
'groups',
'path',
'image_name',
'branch',
'version']
s, _ = self.p_helper.constraint_options(args, options)
self.logger.info(s)
for section in s:
container_name = s[section]['image_name'].replace(':', '-')
container_name = container_name.replace('/', '-')
try:
container = self.d_client.containers.get(container_name)
container.stop()
self.logger.info("stopped " + str(container_name))
except Exception as e: # pragma: no cover
self.logger.error("failed to stop " + str(container_name) +
" because: " + str(e))
except Exception as e: # pragma: no cover
self.logger.error("stop failed with error: " + str(e))
status = (False, e)
self.logger.info("Status of stop: " + str(status[0]))
self.logger.info("Finished: stop")
return status
def clean(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD"):
"""
Clean (stop and remove) a set of tools that match the parameters given,
if no parameters are given, clean all installed tools on the master
branch at verison HEAD that are enabled
"""
args = locals()
self.logger.info("Starting: clean")
self.logger.info(args)
status = (True, None)
try:
# !! TODO need to account for plugin containers that have random
# names, use labels perhaps
options = ['name',
'namespace',
'built',
'groups',
'path',
'image_name',
'branch',
'version']
s, manifest = self.p_helper.constraint_options(args, options)
self.logger.info(s)
for section in s:
container_name = s[section]['image_name'].replace(':', '-')
container_name = container_name.replace('/', '-')
instance_num = re.search(r'\d+$', s[section]['name'])
if instance_num:
container_name += instance_num.group()
try:
container = self.d_client.containers.get(container_name)
container.remove(force=True)
manifest.set_option(section, 'running', 'no')
self.logger.info("cleaned " + str(container_name))
except Exception as e: # pragma: no cover
self.logger.error("failed to clean " +
str(container_name) +
" because: " + str(e))
manifest.write_config()
except Exception as e: # pragma: no cover
self.logger.error("clean failed with error: " + str(e))
status = (False, e)
self.logger.info("Status of clean: " + str(status[0]))
self.logger.info("Finished: clean")
return status
def build(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD"):
""" Build a set of tools that match the parameters given """
args = locals()
self.logger.info("Starting: build")
self.logger.info(args)
status = (True, None)
try:
options = ['image_name', 'path']
s, template = self.p_helper.constraint_options(args, options)
self.logger.info(s)
for section in s:
self.logger.info("Building " + str(section) + " ...")
template = self.plugin.builder(template,
s[section]['path'],
s[section]['image_name'],
section,
build=True,
branch=branch,
version=version)
if len(s) > 0:
template.write_config()
except Exception as e: # pragma: no cover
self.logger.error("build failed with error: " + str(e))
status = (False, e)
self.logger.info("Status of build: " + str(status[0]))
self.logger.info("Finished: build")
return status
def backup(self):
"""
Saves the configuration information of the current running vent
instance to be used for restoring at a later time
"""
self.logger.info("Starting: backup")
status = (True, None)
# initialize all needed variables (names for backup files, etc.)
backup_name = ('.vent-backup-' + '-'.join(Timestamp().split(' ')))
backup_dir = os.path.join(os.path.expanduser('~'), backup_name)
backup_manifest = os.path.join(backup_dir, 'backup_manifest.cfg')
backup_vcfg = os.path.join(backup_dir, 'backup_vcfg.cfg')
manifest = self.p_helper.manifest
# create new backup directory
try:
os.mkdir(backup_dir)
except Exception as e: # pragma: no cover
self.logger.error(str(e))
return (False, str(e))
# create new files in backup directory
try:
# backup manifest
with open(backup_manifest, 'w') as bmanifest:
with open(manifest) as manifest_file:
bmanifest.write(manifest_file.read())
# backup vent.cfg
with open(backup_vcfg, 'w') as bvcfg:
with open(self.vent_config) as vcfg_file:
bvcfg.write(vcfg_file.read())
self.logger.info("Backup information written to " + backup_dir)
status = (True, backup_dir)
except Exception as e: # pragma: no cover
self.logger.error("Couldn't backup vent: " + str(e))
status = (False, str(e))
self.logger.info("Status of backup: " + str(status[0]))
self.logger.info("Finished: backup")
return status
def restore(self, backup_dir):
"""
Restores a vent configuration from a previously backed up version
"""
self.logger.info("Starting: restore")
self.logger.info("Directory given: " + backup_dir)
status = (True, None)
# initialize needed variables
added_str = ''
failed_str = ''
template_options = ['service', 'settings', 'docker', 'info', 'gpu']
backup_dir = os.path.join(os.path.expanduser('~'), backup_dir)
if os.path.exists(backup_dir):
# restore backed up manifest file
backup_manifest = os.path.join(backup_dir, 'backup_manifest.cfg')
bmanifest = Template(backup_manifest)
tools = bmanifest.sections()[1]
for tool in tools:
constraints = {}
options = bmanifest.options(tool)[1]
for vals in bmanifest.section(tool)[1]:
constraints[vals[0]] = vals[1]
backedup_tool = bmanifest.constrained_sections(constraints,
options)
t_info = backedup_tool[tool]
if t_info['type'] == 'repository':
# for purposes of the add method (only adding a sepcific
# tool each time, and the add method expects a tuple with
# relative path to tool for that)
rel_path = t_info['path'].split(t_info['namespace'])[-1]
t_tuple = (rel_path, '')
if t_info['built'] == 'yes':
build = True
else:
build = False
if 'groups' in t_info and 'core' in t_info['groups']:
core = True
else:
core = False
add_kargs = {'tools': [t_tuple],
'branch': t_info['branch'],
'version': t_info['version'],
'build': build,
'core': core}
try:
self.plugin.add(t_info['repo'], **add_kargs)
# update manifest with customizations
new_manifest = Template(self.plugin.manifest)
for option in template_options:
if option in t_info:
new_manifest.set_option(tool, option,
t_info[option])
new_manifest.write_config()
added_str += 'Restored: ' + t_info['name'] + '\n'
except Exception as e: # pragma: no cover
self.logger.error("Problem restoring tool " + t_info['name'] +
" because " + str(e))
failed_str += 'Failed: ' + t_info['name'] + '\n'
elif t_info['type'] == 'registry':
add_kargs = {'image': t_info['pull_name'],
'link_name': t_info['link_name'],
'tag': t_info['version'],
'registry': t_info['repo'].split('/')[0],
'groups': t_info['groups']}
try:
self.add_image(**add_kargs)
# update manifest with customizations
new_manifest = Template(self.plugin.manifest)
for option in template_options:
if option in t_info:
new_manifest.set_option(tool, option,
t_info[option])
new_manifest.write_config()
added_str += 'Restored: ' + t_info['name'] + '\n'
except Exception as e: # pragma: no cover
self.logger.error("Problem restoring tool " + t_info['name'] +
" because " + str(e))
failed_str += 'Failed: ' + t_info['name'] + '\n'
# restore backed up vent.cfg file
backup_vcfg = os.path.join(backup_dir, 'backup_vcfg.cfg')
bvcfg = Template(backup_vcfg)
try:
vcfg_template = Template(self.vent_config)
for section in bvcfg.sections()[1]:
for vals in bvcfg.section(section)[1]:
# add section to new template in case it doesn't exist
try:
vcfg_template.add_section(section)
except Exception as e: # pragma: no cover
# okay if error because of already existing
self.logger.error("Failed adding section " +
str(e))
vcfg_template.set_option(vals[0], vals[1])
vcfg_template.write_config()
added_str += 'Restored: vent configuration file'
except Exception as e: # pragma: no cover
self.logger.error("Couldn't restore vent.cfg"
"because: " + str(e))
failed_str += 'Failed: vent configuration file'
else:
status = (False, "No backup directory found at specified path")
if status[0]:
status = (True, failed_str + added_str)
self.logger.info("Status of restore: " + str(status[0]))
self.logger.info("Finished: restore")
return status
@staticmethod
def configure():
# TODO
# tools, core, etc.
return
@staticmethod
def upgrade():
# TODO
return
def reset(self):
""" Factory reset all of Vent's user data, containers, and images """
status = (True, None)
error_message = ''
# remove containers
try:
c_list = set(self.d_client.containers.list(
filters={'label': 'vent'}, all=True))
for c in c_list:
c.remove(force=True)
except Exception as e: # pragma: no cover
error_message += "Error removing Vent containers: " + str(e) + "\n"
# remove images
try:
i_list = set(self.d_client.images.list(filters={'label': 'vent'},
all=True))
for i in i_list:
# delete tagged images only because they are the parents for
# the untagged images. Remove the parents and the children get
# removed automatically
if i.attrs['RepoTags']:
self.d_client.images.remove(image=i.id, force=True)
except Exception as e: # pragma: no cover
error_message += "Error deleting Vent images: " + str(e) + "\n"
# remove .vent folder
try:
cwd = os.getcwd()
if cwd.startswith(os.path.join(os.path.expanduser('~'), '.vent')):
os.chdir(os.path.expanduser('~'))
shutil.rmtree(os.path.join(os.path.expanduser('~'), '.vent'))
except Exception as e: # pragma: no cover
error_message += "Error deleting Vent data: " + str(e) + "\n"
if error_message:
status = (False, error_message)
return status
def logs(self, c_type=None, grep_list=None):
""" Generically filter logs stored in log containers """
def get_logs(logs, log_entries):
try:
for log in logs:
if str(container.name) in log_entries:
log_entries[str(container.name)].append(log)
else:
log_entries[str(container.name)] = [log]
except Exception as e: # pragma: no cover
self.logger.error("Unable to get logs for " +
str(container.name) +
" because: " + str(e))
return log_entries
self.logger.info("Starting: logs")
status = (True, None)
log_entries = {}
containers = self.d_client.containers.list(all=True,
filters={'label': 'vent'})
self.logger.info("containers found: " + str(containers))
comp_c = containers
if c_type:
try:
comp_c = [c for c in containers
if (c_type
in c.attrs['Config']['Labels']['vent.groups'])]
except Exception as e: # pragma: no cover
self.logger.error("Unable to limit containers by: " +
str(c_type) + " because: " +
str(e))
if grep_list:
for expression in grep_list:
for container in comp_c:
try:
# 'logs' stores each line containing the expression
logs = [log for log in container.logs().split("\n")
if expression in log]
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
self.logger.info("Unable to get logs for " +
str(container) +
" because: " + str(e))
else:
for container in comp_c:
try:
logs = container.logs().split("\n")
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
self.logger.info("Unabled to get logs for " +
str(container) +
" because: " + str(e))
status = (True, log_entries)
self.logger.info("Status of logs: " + str(status[0]))
self.logger.info("Finished: logs")
return status
@staticmethod
def help():
# TODO
return
def inventory(self, choices=None):
""" Return a dictionary of the inventory items and status """
self.logger.info("Starting: inventory")
status = (True, None)
self.logger.info("choices specified: " + str(choices))
if not choices:
return (False, "No choices made")
try:
# choices: repos, core, tools, images, built, running, enabled
items = {'repos': [], 'core': {}, 'tools': {}, 'images': {},
'built': {}, 'running': {}, 'enabled': {}}
tools = self.plugin.list_tools()
self.logger.info("found tools: " + str(tools))
for choice in choices:
for tool in tools:
try:
if choice == 'repos':
if 'repo' in tool:
if (tool['repo'] and
tool['repo'] not in items[choice]):
items[choice].append(tool['repo'])
elif choice == 'core':
if 'groups' in tool and 'core' in tool['groups']:
items[choice][tool['section']] = tool['name']
elif choice == 'tools':
if (('groups' in tool and
'core' not in tool['groups']) or
'groups' not in tool):
items[choice][tool['section']] = tool['name']
elif choice == 'images':
# TODO also check against docker
items[choice][tool['section']] = tool['image_name']
elif choice == 'built':
items[choice][tool['section']] = tool['built']
elif choice == 'running':
containers = Containers()
status = 'not running'
for container in containers:
image_name = tool['image_name'] \
.rsplit(":" +
tool['version'], 1)[0]
image_name = image_name.replace(':', '-')
image_name = image_name.replace('/', '-')
self.logger.info("image_name: " + image_name)
if container[0] == image_name:
status = container[1]
# cores need to not have version, plugins need
# to have version in order to match
elif container[0] == image_name + \
'-' + tool['version']:
status = container[1]
items[choice][tool['section']] = status
elif choice == 'enabled':
items[choice][tool['section']] = tool['enabled']
else:
# unknown choice
pass
except Exception as e: # pragma: no cover
self.logger.error("unable to grab info about tool: " +
str(tool) + " because: " + str(e))
status = (True, items)
except Exception as e: # pragma: no cover
self.logger.error("inventory failed with error: " + str(e))
status = (False, str(e))
self.logger.info("Status of inventory: " + str(status[0]))
self.logger.info("Finished: inventory")
return status
def get_configure(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD",
main_cfg=False):
"""
Get the vent.template settings for a given tool by looking at the
plugin_manifest
"""
self.logger.info("Starting: get_configure")
constraints = locals()
del constraints['main_cfg']
status = (True, None)
template_dict = {}
return_str = ""
if main_cfg:
vent_cfg = Template(self.vent_config)
for section in vent_cfg.sections()[1]:
template_dict[section] = {}
for vals in vent_cfg.section(section)[1]:
template_dict[section][vals[0]] = vals[1]
else:
# all possible vent.template options stored in plugin_manifest
options = ['info', 'service', 'settings', 'docker', 'gpu']
tools = self.p_helper.constraint_options(constraints, options)[0]
if tools:
# should only be one tool
tool = tools.keys()[0]
# load all vent.template options into dict
for section in tools[tool]:
template_dict[section] = json.loads(tools[tool][section])
else:
status = (False, "Couldn't get vent.template information")
if status[0]:
# display all those options as they would in the file
for section in template_dict:
return_str += "[" + section + "]\n"
# ensure instances shows up in configuration
for option in template_dict[section]:
if option.startswith('#'):
return_str += option + "\n"
else:
return_str += option + " = "
return_str += template_dict[section][option] + "\n"
return_str += "\n"
# only one newline at end of file
status = (True, return_str[:-1])
self.logger.info("Status of get_configure: " + str(status[0]))
self.logger.info("Finished: get_configure")
return status
def save_configure(self,
repo=None,
name=None,
groups=None,
enabled="yes",
branch="master",
version="HEAD",
config_val="",
from_registry=False,
main_cfg=False,
instances=1):
"""
Save changes made to vent.template through npyscreen to the template
and to plugin_manifest
"""
def template_to_manifest(vent_template, manifest, tool, instances):
"""
Helper function to transfer information from vent.template
to plugin_manifest
"""
sections = vent_template.sections()
if sections[0]:
for section in sections[1]:
section_dict = {}
if section == 'settings':
section_dict.update({'instances': str(instances)})
options = vent_template.options(section)
if options[0]:
for option in options[1]:
option_name = option
if option == 'name':
option_name = 'link_name'
opt_val = vent_template.option(section,
option)[1]
section_dict[option_name] = opt_val
if section_dict:
manifest.set_option(tool, section,
json.dumps(section_dict))
elif manifest.option(tool, section)[0]:
manifest.del_option(tool, section)
self.logger.info("Starting: save_configure")
constraints = locals()
del constraints['config_val']
del constraints['from_registry']
del constraints['main_cfg']
del constraints['instances']
del constraints['template_to_manifest']
status = (True, None)
fd = None
# ensure instances is an int and remove instances from config_val to
# ensure correct info
instances = int(instances)
config_val = re.sub(r'instances\ *=\ *\d+\n', '', config_val)
if not main_cfg:
if not from_registry:
# creating new instances
if instances > 1:
fd, template_path = tempfile.mkstemp(suffix='.template')
# scrub name for clean section name
if re.search(r'\d+$', name):
name = re.sub(r'\d+$', '', name)
t_identifier = {'name': name,
'branch': branch,
'version': version}
result = self.p_helper.constraint_options(t_identifier, [])
tools = result[0]
manifest = result[1]
tool = tools.keys()[0]
else:
options = ['path', 'multi_tool', 'name']
self.logger.info(constraints)
tools, manifest = self.p_helper. \
constraint_options(constraints, options)
self.logger.info(tools)
# only one tool in tools because perform this function for
# every tool
if tools:
tool = tools.keys()[0]
if ('multi_tool' in tools[tool] and