def _read_passphrase(self) -> str: """Retrieve and read the vault passphrase""" if file_is_not_empty(self.configs.vault_file()): confirm_flag = False else: sysout("%ORANGE%### Your Vault '{}' file is empty.".format( self.configs.vault_file())) sysout("%ORANGE%>>> Enter the new passphrase for this Vault") confirm_flag = True touch_file(self.configs.vault_file()) passphrase = self.configs.passphrase() if passphrase: return "{}:{}".format(self.configs.vault_user(), base64.b64decode(passphrase).decode("utf-8")) while not passphrase and not confirm_flag: passphrase = getpass.getpass("Enter passphrase:").strip() confirm = None if passphrase and confirm_flag: while not confirm: confirm = getpass.getpass("Repeat passphrase:").strip() if confirm != passphrase: syserr("### Passphrase and confirmation mismatch") safe_del_file(self.configs.vault_file()) else: sysout("%GREEN%Passphrase successfully stored") log.debug("Vault passphrase created for user={}".format( self.configs.vault_user())) touch_file(self.configs.vault_file()) self.is_open = True return "{}:{}".format(self.configs.vault_user(), passphrase)
def shell_poll(cmd_line: str, **kwargs) -> None: """TODO""" if 'stdout' in kwargs: del kwargs['stdout'] # Deleted since we use our own if 'stderr' in kwargs: del kwargs['stderr'] # Deleted since we use our own try: log.info(f"Polling shell command: {cmd_line}") cmd_args = list(filter(None, shlex.split(cmd_line))) with (subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)) as file: process = select.poll() process.register(file.stdout) while True: line = bytes( file.stdout.readline()).decode('utf-8').strip() print('.' + line) except (InterruptedError, KeyboardInterrupt): log.warning( f"Polling process has been interrupted command='{cmd_line}'") except subprocess.CalledProcessError as err: log.debug(f'Failed => {str(err)}') syserr(str(err))
def tearDown(self): try: self.repository.execute(f"DROP TABLE {self.table}", True) self.repository.disconnect() self.assertFalse(self.repository.is_connected()) except (InternalError, OperationalError) as err: syserr(str(err))
def print_error(message: str, argument: Any = None, wait_interval: int = 2) -> None: """TODO""" syserr(f"### Error: {message} \"{argument or ''}\"") time.sleep(wait_interval) sysout('%CUU(2)%%ED0%', end='')
def promote(self) -> Version: """ Promote the current version in the order: DEVELOPMENT->SNAPSHOT->STABLE->RELEASE """ self._assert_extension() if self._version.state and self._version.state != Extension.RELEASE: self._version.state = Extension.of_value( min(Extension.RELEASE.value, self._version.state.value << 1)) sysout(f"Version has been promoted to {self._version}") else: syserr(f"Version {self._version} can't be promoted") return self._version
def demote(self) -> Version: """ Demote the current version in the order: RELEASE->STABLE->SNAPSHOT->DEVELOPMENT """ self._assert_extension() if self._version.state and self._version.state != Extension.DEVELOPMENT: self._version.state = Extension.of_value( max(Extension.DEVELOPMENT.value, self._version.state.value >> 1)) sysout(f"Version has been demoted to {self._version}") else: syserr(f"Version {self._version} can't be demoted") return self._version
def get(self, key) -> None: """Display the vault entry specified by name :param key: The vault entry name to get """ entry = self.service.get_by_key(key) if entry: sysout("\n{}".format(entry.to_string(True, True))) else: log.error( "Attempt to get from Vault failed for name={}".format(key)) syserr("### No entry specified by '{}' was found in vault".format( key)) log.debug("Vault get issued. User={}".format(getpass.getuser()))
def shell_exec(cmd_line: str, **kwargs) -> Optional[str]: """TODO""" try: log.info(f"Executing shell command: {cmd_line}") cmd_args = list(filter(None, shlex.split(cmd_line))) result = subprocess.check_output(cmd_args, **kwargs).decode("utf-8") log.info(f"Execution result: {result}") return result.strip() if result else None except subprocess.CalledProcessError as err: log.error(f'Failed => {str(err)}') syserr(str(err)) return None
def _exec_application(self) -> None: """Execute the application""" if self.getarg('part'): caller = getattr(self.versioner, self.getarg('part')) else: caller = getattr(self.versioner, self.getarg('state')) caller() if self.versioner.save(self.getopt('backup')): sysout( f"%GREEN%Successfully updated version to {self.versioner.version()}" ) else: syserr( f"Failed to update version. No matches found for version {self.getarg('version')}" )
def remove(self, key: str) -> None: """Remove a vault entry :param key: The vault entry name to be removed """ entry = self.service.get_by_key(key) if entry: self.service.remove(entry) sysout("%GREEN%\n=== Entry removed ===\n\n%NC%{}".format( entry.to_string())) else: log.error( "Attempt to remove to Vault failed for name={}".format(key)) syserr("### No entry specified by '{}' was found in vault".format( key)) log.debug("Vault remove issued. User={}".format(getpass.getuser()))
def emit(self, event_name: str, **kwargs) -> None: """TODO""" self._events.append(Event(event_name, **kwargs)) while len(self._events) > 0: event = self._events.pop() cache_key = f"{self.name}.{event.name}" subscribers = self._subscribers[ cache_key] if cache_key in self._subscribers else None if subscribers and len(subscribers['callbacks']) > 0: for callback in subscribers['callbacks']: try: callback(event) except TypeError as err: syserr( f"{self.__class__.__name__}::emit failed => {str(err)}" )
def create(self, app_name: str, app_type: AppType, app_ext: List[AppExtension], dest_dir: str) -> None: """Create the application based on the parameters""" sysout(f'Creating app: {app_name} -> {dest_dir} ...') try: assert os.path.exists(dest_dir), f'Destination not found: {dest_dir}' self._app_name = app_name if app_type == AppType.APP: self._app_dir = f'{dest_dir}/{app_name}' self._create_app(app_name, app_ext) elif app_type == AppType.WIDGET: self._app_dir = f'{dest_dir}' self._create_widget(app_name) elif app_type == AppType.QT_APP: self._app_dir = f'{dest_dir}/{app_name}' self._create_qt_app(app_name, app_ext) except OSError as err: syserr(f"Creation of the application {dest_dir}/{app_name} failed") syserr(str(err)) else: sysout(f"Successfully created the {app_type.value} {app_name}")
def _exec_application(self) -> None: """Execute the specified firebase operation""" op = self.getarg('operation') if op == 'setup' or not self.firebase.is_configured(): self.firebase.setup() # Already handled above if op == 'setup': pass elif op == 'upload': self.firebase.upload( self.getarg('db_alias'), self.getarg('files').split(',') ) elif op == 'download': self.firebase.download( self.getarg('db_alias'), self.getopt('dest-dir') ) else: syserr('### Unhandled operation: {}'.format(op)) self.usage(1)
def add(self, key: str, hint: str, password: str) -> None: """Add a vault entry :param key: The vault entry name to be added :param hint: The vault entry hint to be added :param password: The vault entry password to be added """ entry = self.service.get_by_key(key) if not entry: while not password: password = getpass.getpass( "Type the password for '{}': ".format(key)).strip() entry = VaultEntry(uuid.uuid4(), key, key, password, hint) self.service.save(entry) sysout("%GREEN%\n=== Entry added ===\n\n%NC%{}".format( entry.to_string())) else: log.error("Attempt to add to Vault failed for name={}".format(key)) syserr( "### Entry specified by '{}' already exists in vault".format( key)) log.debug("Vault add issued. User={}".format(getpass.getuser()))
def _exec_application(self) -> None: """Execute the application""" op = self.getarg('operation') if op == 'create': manager = AppManager(self) app_type = AppType.of_value(self.getarg('app-type')) extensions = self.getarg('app-ext').split(',') if self.getarg( 'app-ext') else [] manager.create(self.getarg('app-name'), app_type, list(map(AppExtension.value_of, extensions)), self.getopt('dest-dir') or run_dir()) elif op == 'widgets': manager = WidgetManager(self) widget_name = self.getarg('widget-name') if widget_name: widget_args = str(self.getarg('widget-args')).split(',') manager.execute(widget_name, widget_args) else: manager.dashboard() else: syserr('### Invalid operation: {}'.format(op)) self.usage(1)
def _exec_application(self, ) -> None: """Execute the specified vault operation""" op = self.getarg('operation') try: self.vault.open() if op == 'add': self.vault.add(self.getarg('name'), self.getarg('hint'), self.getarg('password')) elif op == 'get': self.vault.get(self.getarg('name')) elif op == 'del': self.vault.remove(self.getarg('name')) elif op == 'upd': self.vault.update(self.getarg('name'), self.getarg('hint'), self.getarg('password')) elif op == 'list': self.vault.list(self.getarg('filter')) else: syserr('### Invalid operation: {}'.format(op)) self.usage(1) finally: self.vault.close()
def update(self, key, hint, password) -> None: """Update a vault entry :param key: The vault entry name to be updated :param hint: The vault entry hint to be updated :param password: The vault entry password to be updated """ entry = self.service.get_by_key(key) if entry: if not password: passphrase = getpass.getpass( "Type a password for '{}': ".format(key)).strip() else: passphrase = password upd_entry = VaultEntry(entry.uuid, key, key, passphrase, hint) self.service.save(upd_entry) sysout("%GREEN%\n=== Entry updated ===\n\n%NC%{}".format( entry.to_string())) else: log.error("Attempt to update Vault failed for name={}".format(key)) syserr("### No entry specified by '{}' was found in vault".format( key)) log.debug("Vault update issued. User={}".format(getpass.getuser()))
def _select_endpoint(self) -> None: """Select the PCF endpoint to connect to""" with open(f'{self.configs.resource_dir()}/api_endpoints.txt', 'r+') as f_hosts: endpoints = list( map(lambda x: CFEndpoint(x.split(',')), f_hosts.readlines())) selected = mselect(endpoints, title='Please select an endpoint') if not selected: sys.exit(0) sysout(f'%GREEN%Connecting to endpoint: {selected}...') try: response = head(selected.host) if response.status_code and HttpCode.OK: self.api = selected.host else: syserr( f'Failed to connect to API ({response.status_code}): {selected}' ) sys.exit(0) except Exception as err: raise CFConnectionError( f'Failed to connect to API => {selected.host}') from err