def __init__(self, *args, **keywords): """ Initialize tool form objects """ self.logger = Logger(__name__) self.api_action = System() self.tools_inst = Tools() action = {'api_action': self.tools_inst} self.tools_tc = {} self.repo_widgets = {} if keywords['action_dict']: action.update(keywords['action_dict']) if keywords['names']: i = 1 for name in keywords['names']: try: action['action_object' + str(i)] = getattr( self.tools_inst, name) except AttributeError: action['action_object' + str(i)] = getattr( self.api_action, name) i += 1 self.action = action # get list of all possible group views to display self.views = deque() possible_groups = set() manifest = Template(self.api_action.manifest) tools = self.tools_inst.inventory(choices=['tools'])[1]['tools'] for tool in tools: groups = manifest.option(tool, 'groups')[1].split(',') for group in groups: # don't do core because that's the purpose of all in views if group != '' and group != 'core': possible_groups.add(group) self.manifest = manifest self.views += possible_groups self.views.append('all groups') self.no_instance = ['remove'] super(ToolForm, self).__init__(*args, **keywords)
def on_ok(self): """ Add the repository """ def popup(thr, add_type, title): """ Start the thread and display a popup of the plugin being cloned until the thread is finished """ thr.start() tool_str = 'Cloning repository...' if add_type == 'image': tool_str = 'Pulling image...' npyscreen.notify_wait(tool_str, title=title) while thr.is_alive(): time.sleep(1) return if self.image.value and self.link_name.value: api_action = Tools() api_image = Image(System().manifest) api_system = System() thr = threading.Thread(target=api_image.add, args=(), kwargs={ 'image': self.image.value, 'link_name': self.link_name.value, 'tag': self.tag.value, 'registry': self.registry.value, 'groups': self.groups.value }) popup(thr, 'image', 'Please wait, adding image...') npyscreen.notify_confirm('Done adding image.', title='Added image') editor_args = { 'tool_name': self.image.value, 'version': self.tag.value, 'get_configure': api_system.get_configure, 'save_configure': api_system.save_configure, 'restart_tools': api_system.restart_tools, 'start_tools': api_action.start, 'from_registry': True, 'just_downloaded': True, 'link_name': self.link_name.value, 'groups': self.groups.value } self.parentApp.addForm('CONFIGUREIMAGE', EditorForm, name='Specify vent.template settings for ' 'image pulled (optional)', **editor_args) self.parentApp.change_form('CONFIGUREIMAGE') elif self.image.value: npyscreen.notify_confirm( 'A name needs to be supplied for ' 'the image being added!', title='Specify a name for the image', form_color='CAUTION') elif self.repo.value: self.parentApp.repo_value['repo'] = self.repo.value.lower() api_repo = Repository(System().manifest) api_repo.repo = self.repo.value.lower() thr = threading.Thread(target=api_repo._clone, args=(), kwargs={ 'user': self.user.value, 'pw': self.pw.value }) popup(thr, 'repository', 'Please wait, adding repository...') self.parentApp.addForm('ADDOPTIONS', AddOptionsForm, name='Set options for new plugin' '\t\t\t\t\t\t^Q to quit', color='CONTROL') self.parentApp.change_form('ADDOPTIONS') else: npyscreen.notify_confirm( 'Either a repository or an image ' 'name must be specified!', title='Specify plugin to add', form_color='CAUTION') return
def on_ok(self): """ Save changes made to vent.template """ # ensure user didn't have any syntactical errors input_is_good, trimmed_input = self.valid_input(self.edit_space.value) if not input_is_good: return self.edit_space.value = trimmed_input # get the number of instances and ensure user didn't malform that if re.search(r'instances\ *=', self.edit_space.value): try: # split out spaces instances_val = re.split(r'instances\ *=\ *', self.edit_space.value)[1] instances_val = instances_val.split('\n')[0] new_instances = int(re.match(r'\d+$', instances_val).group()) except AttributeError: npyscreen.notify_confirm( "You didn't specify a valid number" ' for instances.', title='Invalid' ' instance number') return # user can't change instances when configuring new instnaces if (self.instance_cfg and self.settings['new_instances'] != new_instances): npyscreen.notify_confirm( "You can't change the number of" ' instnaces while configuring new' ' instances!', title='Illegal change') return # get old number of instances try: if 'old_instances' in self.settings: old_instances = self.settings['old_instances'] else: settings_dict = json.loads( self.manifest.option(self.section, 'settings')[1]) old_instances = int(settings_dict['instances']) except Exception: old_instances = 1 else: new_instances = 1 old_instances = 1 # save changes and update manifest we're looking at with changes if self.vent_cfg: save_args = {'main_cfg': True, 'config_val': self.edit_space.value} self.manifest = self.settings['save_configure'](**save_args)[1] else: save_args = copy.deepcopy(self.tool_identifier) save_args.update({'config_val': self.edit_space.value}) if self.registry_tool: save_args.update({'from_registry': True}) if self.instance_cfg: save_args.update({'instances': new_instances}) self.manifest = self.settings['save_configure'](**save_args)[1] # restart tools, if necessary if not self.just_downloaded and not self.instance_cfg: restart_kargs = { 'main_cfg': self.vent_cfg, 'old_val': self.config_val, 'new_val': self.edit_space.value } if self.vent_cfg: wait_str = 'Restarting tools affected by changes...' else: wait_str = 'Restarting this tool with new settings...' restart_kargs.update(self.tool_identifier) npyscreen.notify_wait(wait_str, title='Restarting with changes') self.settings['restart_tools'](**restart_kargs) # start new instances if user wanted to if self.instance_cfg and self.settings['start_new']: npyscreen.notify_wait('Starting new instances...', title='Start') tool_d = {} for i in range(self.settings['old_instances'] + 1, self.settings['new_instances'] + 1): # create section by scrubbing instance number out of names # and adding new instance number i_section = self.section.rsplit(':', 2) i_section[0] = re.sub(r'[0-9]', '', i_section[0]) + str(i) i_section = ':'.join(i_section) t_name = self.manifest.option(i_section, 'name')[1] t_id = {'name': t_name} tool_d.update(self.settings['prep_start'](**t_id)[1]) if tool_d: self.settings['start_tools'](tool_d) # prompt user for instance changes, as necessary if not self.instance_cfg and not self.vent_cfg: if new_instances > old_instances: try: diff = str(new_instances - old_instances) res = npyscreen.notify_yes_no('You will be creating ' + diff + ' additional' ' instance(s) is that okay?', title='Confirm new' ' instance(s)') if res: if self.manifest.option(self.section, 'built')[1] == 'yes': run = npyscreen.notify_yes_no( 'Do you want to' ' start these new' ' tools upon' ' creation?', title='Run new' ' instance(s)') else: run = False # get clean name (no instance numbers in it) new_name = self.settings['tool_name'] new_name = re.sub(r'[0-9]+$', '', new_name) self.settings['tool_name'] = new_name npyscreen.notify_wait( 'Pulling up default settings' ' for ' + self.settings['tool_name'] + '...', title='Gathering settings') Repository(System().manifest)._clone( self.settings['repo']) self.settings['new_instances'] = new_instances self.settings['old_instances'] = old_instances self.settings['start_new'] = run self.settings['new_instance'] = True self.settings['name'] = 'Configure new instance(s)' + \ ' for ' + self.settings['tool_name'] self.parentApp.addForm( 'INSTANCEEDITOR' + self.settings['tool_name'], EditorForm, **self.settings) self.parentApp.change_form('INSTANCEEDITOR' + self.settings['tool_name']) else: return except Exception: npyscreen.notify_confirm( 'Trouble finding tools to add,' ' exiting', title='Error') self.on_cancel() elif new_instances < old_instances: try: diff = str(old_instances - new_instances) res = npyscreen.notify_yes_no('You will be deleting ' + diff + ' instance(s), is' ' that okay?', title='Confirm delete' ' instance(s)') if res: form_name = 'Delete instances for ' + \ re.sub(r'\d+$', '', self.settings['tool_name']) + '\t'*8 + \ '^E to exit configuration process' clean_section = self.section.rsplit(':', 2) clean_section[0] = re.sub(r'\d+$', '', clean_section[0]) clean_section = ':'.join(clean_section) d_args = { 'name': form_name, 'new_instances': new_instances, 'old_instances': old_instances, 'next_tool': self.settings['next_tool'], 'manifest': self.manifest, 'section': clean_section, 'clean': self.settings['clean'], 'prep_start': self.settings['prep_start'], 'start_tools': self.settings['start_tools'] } self.parentApp.addForm( 'DELETER' + self.settings['tool_name'], DeleteForm, **d_args) self.parentApp.change_form('DELETER' + self.settings['tool_name']) except Exception: npyscreen.notify_confirm( 'Trouble finding instances to' ' delete, exiting', title='Error') self.on_cancel() if (new_instances == old_instances or self.instance_cfg or self.vent_cfg): npyscreen.notify_confirm('Done configuring ' + self.settings['tool_name'], title='Configurations saved') self.change_screens()
def __init__(self, repo='', tool_name='', next_tool=None, just_downloaded=False, vent_cfg=False, from_registry=False, new_instance=False, *args, **keywords): """ Initialize EditorForm objects """ # default for any editor self.settings = locals() self.settings.update(keywords) del self.settings['self'] del self.settings['args'] del self.settings['keywords'] del self.settings['parentApp'] self.tool_identifier = {'name': tool_name} self.settings.update(self.tool_identifier) del self.settings['name'] self.settings['tool_name'] = tool_name self.settings['next_tool'] = next_tool self.settings['repo'] = repo # setup checks self.just_downloaded = ('just_downloaded' in self.settings and self.settings['just_downloaded']) self.vent_cfg = ('vent_cfg' in self.settings and self.settings['vent_cfg']) self.registry_tool = ('from_registry' in self.settings and self.settings['from_registry']) self.instance_cfg = ('new_instance' in self.settings and self.settings['new_instance']) # get manifest info for tool that will be used throughout if not self.just_downloaded and not self.vent_cfg: result = Template(System().manifest).constrain_opts( self.tool_identifier, []) tool, self.manifest = result self.section = list(tool.keys())[0] # get configuration information depending on type if self.just_downloaded: self.config_val = '[info]\n' self.config_val += 'name = ' + keywords['link_name'] + '\n' self.config_val += 'groups = ' + keywords['groups'] + '\n' elif self.vent_cfg: self.config_val = keywords['get_configure'](main_cfg=True)[1] self.settings['tool_name'] = 'vent configuration' elif self.instance_cfg: path = self.manifest.option(self.section, 'path')[1] multi_tool = self.manifest.option(self.section, 'multi_tool') if multi_tool[0] and multi_tool[1] == 'yes': name = self.manifest.option(self.section, 'name')[1] if name == 'unspecified': name = 'vent' template_path = os.path.join(path, name + '.template') else: template_path = os.path.join(path, 'vent.template') # ensure instances is in the editor and that it is the right number template = Template(template_path) template.add_section('settings') template.set_option('settings', 'instances', str(self.settings['new_instances'])) template.write_config() with open(template_path, 'r') as vent_template: self.config_val = vent_template.read() else: self.config_val = keywords['get_configure']( **self.tool_identifier)[1] super(EditorForm, self).__init__(*args, **keywords)
def test_gpu(): """ Test the gpu function """ system = System() system.gpu()
def test_upgrade(): """ Test the upgrade function """ system = System() system.upgrade()
def test_stop(): """ Test the stop function """ system = System() system.stop()
def test_configure(): """ Test the configure function """ system = System() system.configure()
def test_rollback(): """ Test the rollback function """ system = System() system.rollback()
def test_restore(): """ Test the restore function """ system = System() system.restore('foo')
def test_history(): """ Test the history function """ system = System() system.history()
def test_add(): """ Test the add function """ repo = Repository(System().manifest) repo.add('https://github.com/cyberreboot/poseidon')
def test_update(): """ Test the update function """ repo = Repository(System().manifest) repo.update('foo')
def test_update(): """ Test the update class """ image = Image(System().manifest) image.update('foo')
def create(self): """ Override method for creating FormBaseNewWithMenu form """ try: self.api_action = System() except DockerException as de: # pragma: no cover notify_confirm(str(de), title='Docker Error', form_color='DANGER', wrap=True) MainForm.exit() self.add_handlers({'^T': self.help_form, '^Q': MainForm.exit}) # all forms that can toggle view by group self.view_togglable = ['inventory', 'remove'] ####################### # MAIN SCREEN WIDGETS # ####################### self.addfield = self.add(npyscreen.TitleFixedText, name='Date:', labelColor='DEFAULT', value=Timestamp()) self.addfield2 = self.add(npyscreen.TitleFixedText, name='Uptime:', labelColor='DEFAULT', value=Uptime()) self.cpufield = self.add(npyscreen.TitleFixedText, name='Logical CPUs:', labelColor='DEFAULT', value=Cpu()) self.gpufield = self.add(npyscreen.TitleFixedText, name='GPUs:', labelColor='DEFAULT', value=Gpu()[1]) self.location = self.add(npyscreen.TitleFixedText, name='User Data:', value=PathDirs().meta_dir, labelColor='DEFAULT') self.file_drop = self.add(npyscreen.TitleFixedText, name='File Drop:', value=DropLocation()[1], labelColor='DEFAULT') self.addfield3 = self.add(npyscreen.TitleFixedText, name='Containers:', labelColor='DEFAULT', value='0 ' + ' running') self.multifield1 = self.add(npyscreen.MultiLineEdit, max_height=22, editable=False, value=""" '., 'b * '$ #. $: #: *# @): :@,@): ,.**:' , :@@*: ..**' '#o. .:(@'.@*"' 'bq,..:,@@*' ,* ,p$q8,:@)' .p*' ' '@@Pp@@*' Y7'.' :@):. .:@:'. .::(@:. _ __ _____ _ __ | |_ \ \ / / _ \ '_ \| __| \ V / __/ | | | |_ \_/ \___|_| |_|\__| """) ################ # MENU OPTIONS # ################ # Tool Menu Items self.m3 = self.add_menu(name='Tools', shortcut='p') self.m3.addItem(text='Add New Tool', onSelect=self.perform_action, arguments=['add'], shortcut='a') self.m3.addItem(text='Configure Tools', onSelect=self.perform_action, arguments=['configure'], shortcut='t') self.m3.addItem(text='Inventory', onSelect=self.perform_action, arguments=['inventory'], shortcut='i') self.m3.addItem(text='Remove Tools', onSelect=self.perform_action, arguments=['remove'], shortcut='r') self.m3.addItem(text='Start Tools', onSelect=self.perform_action, arguments=['start'], shortcut='s') self.m3.addItem(text='Stop Tools', onSelect=self.perform_action, arguments=['stop'], shortcut='p') # Services Menu Items self.m5 = self.add_menu(name='Services Running', shortcut='s') self.m5.addItem(text='External Services', onSelect=self.perform_action, arguments=['services_external'], shortcut='e') self.m5.addItem(text='Tool Services', onSelect=self.perform_action, arguments=['services'], shortcut='t') # System Commands Menu Items self.m6 = self.add_menu(name='System Commands', shortcut='y') self.m6.addItem(text='Backup', onSelect=self.system_commands, arguments=['backup'], shortcut='b') self.m6.addItem(text='Change Vent Configuration', onSelect=self.system_commands, arguments=['configure'], shortcut='c') self.m6.addItem(text='Detect GPUs', onSelect=self.system_commands, arguments=['gpu'], shortcut='g') self.m6.addItem(text='Factory Reset', onSelect=self.system_commands, arguments=['reset'], shortcut='r') self.m6.addItem(text='Restore (To Be Implemented...', onSelect=self.system_commands, arguments=['restore'], shortcut='t') # TODO this should be either or depending on whether or not it's running already self.m6.addItem(text='Start', onSelect=self.system_commands, arguments=['start'], shortcut='s') self.m6.addItem(text='Stop', onSelect=self.system_commands, arguments=['stop'], shortcut='o') self.m6.addItem(text='Upgrade (To Be Implemented...)', onSelect=self.system_commands, arguments=['upgrade'], shortcut='u') # Tutorial Menu Items self.m7 = self.add_menu(name='Tutorials', shortcut='t') self.s1 = self.m7.addNewSubmenu(name='About Vent', shortcut='v') self.s1.addItem(text='Background', onSelect=self.switch_tutorial, arguments=['background'], shortcut='b') self.s1.addItem(text='Terminology', onSelect=self.switch_tutorial, arguments=['terminology'], shortcut='t') self.s1.addItem(text='Getting Setup', onSelect=self.switch_tutorial, arguments=['setup'], shortcut='s') self.s2 = self.m7.addNewSubmenu(name='Working with Tools', shortcut='c') self.s2.addItem(text='Starting Tools', onSelect=self.switch_tutorial, arguments=['starting_tools'], shortcut='s') self.s3 = self.m7.addNewSubmenu(name='Working with Plugins', shortcut='p') self.s3.addItem(text='Adding Tools', onSelect=self.switch_tutorial, arguments=['adding_tools'], shortcut='a') self.s4 = self.m7.addNewSubmenu(name='Files', shortcut='f') self.s4.addItem(text='Adding Files', onSelect=self.switch_tutorial, arguments=['adding_files'], shortcut='a') self.s5 = self.m7.addNewSubmenu(name='Help', shortcut='s') self.s5.addItem(text='Basic Troubleshooting', onSelect=self.switch_tutorial, arguments=['basic_troubleshooting'], shortcut='t')
def onStart(self): """ Override onStart method for npyscreen """ curses.mousemask(0) self.paths.host_config() version = Version() # setup initial runtime stuff if self.first_time[0] and self.first_time[1] != 'exists': system = System() thr = Thread(target=system.start, args=(), kwargs={}) thr.start() countdown = 60 while thr.is_alive(): npyscreen.notify_wait('Completing initialization:...' + str(countdown), title='Setting up things...') time.sleep(1) countdown -= 1 thr.join() quit_s = '\t' * 4 + '^Q to quit' tab_esc = '\t' * 4 + 'ESC to close menu popup' self.addForm('MAIN', MainForm, name='Vent ' + version + '\t\t\t\t\t^T for help' + quit_s + tab_esc, color='IMPORTANT') self.addForm('HELP', HelpForm, name='Help\t\t\t\t\t\t\t\t^T to toggle previous' + quit_s, color='DANGER') self.addForm('TUTORIALINTRO', TutorialIntroForm, name='Vent Tutorial' + quit_s, color='DANGER') self.addForm('TUTORIALBACKGROUND', TutorialBackgroundForm, name='About Vent' + quit_s, color='DANGER') self.addForm('TUTORIALTERMINOLOGY', TutorialTerminologyForm, name='About Vent' + quit_s, color='DANGER') self.addForm('TUTORIALGETTINGSETUP', TutorialGettingSetupForm, name='About Vent' + quit_s, color='DANGER') self.addForm('TUTORIALSTARTINGCORES', TutorialStartingCoresForm, name='Working with Cores' + quit_s, color='DANGER') self.addForm('TUTORIALADDINGPLUGINS', TutorialAddingPluginsForm, name='Working with Plugins' + quit_s, color='DANGER') self.addForm('TUTORIALADDINGFILES', TutorialAddingFilesForm, name='Files' + quit_s, color='DANGER') self.addForm('TUTORIALTROUBLESHOOTING', TutorialTroubleshootingForm, name='Troubleshooting' + quit_s, color='DANGER')