def _get_options(self, argv, action_name): """ """ # Get option completion. self.option_completion(argv, action_name) # Remove the auto-generated help option. parser.remove_option('--help') # Add custom help options. parser.add_option('--help', dest='help', action='store_true', default=None) attributes = self._get_method_attrs(action_name) if attributes: for option in attributes: parser.add_option('--%s' % option.get('name'), dest=option.get('name'), action=option.get('option_action', 'store'), default=option.get('default', None), help=optparse.SUPPRESS_HELP) else: attributes = [] # Here we go, parse the arg ! try: self.options, args = parser.parse_args(argv) except UnboundLocalError: raise ControllerException("Please specify an argument") # Sets the logger level according to the -v options. level = logging.DEBUG if self.options.debug else logging.INFO syncli_logger = logging.getLogger('syncli') syncli_logger.setLevel(level) if level == 'INFO': for handler in syncli_logger.handlers: formatter = logging.Formatter('%(message)s') handler.setFormatter(formatter) # 1) Transforms OptParse options to dict. # 2) Remove the entry if the value is None. self.options = dict((k, v) for k, v in vars(self.options).iteritems() \ if v is not None) # Display the help for this action ? if self.options.get('help'): self.print_options(action_name) # TODO: Raise an exception ? Are you sure ? raise ControllerException() return self.options, args[0] if len(args) else None
def update_meta(self, argv): """ Updates the meta-data (owner, group, mode) of a file. """ options, path = self._get_options(argv, 'update_meta') if not path: raise ControllerException("Please specify the file name.") if not options: self.print_options('update_meta') raise ControllerException("Please specify an option !") attributes = self._get_attrs('update_meta', options) mon = self.get_mon_value(options) self.do_action('update_meta', path, monitor=mon, **attributes)
def status(self, argv): """ Retrieves the meta data of a file. """ options, path = self._get_options(argv, 'status') if not path: raise ControllerException("Please specify the file name.") kwargs = {'content': options.get('get_content'), 'md5': options.get('md5')} get_content = options.get('get_content') md5 = options.get('md5') if options.get('save'): get_content = True # Build the request request = self.api.infos(path, content=get_content, md5=md5) # When the "save" option is provided, get the responses synchronously, # as we don't have to print the results. if options.get('save'): with self.client: self.ping() self.client.send(request) self._save_files(self.get_responses(), options['save']) else: self.do_action('infos', path, **kwargs)
def dispatch(self, argv): if '--version' in argv: print options.get_version() return # Handle resource completion if '--completion' in argv: self.resource_completion(argv) # Avoid to complete options when no [resource action] are # specified. if '--completion-option' in argv and len(argv) <= 3: return # If there's no arguments or the --help argument without # anything else, print the doc and exit. if len(argv) == 0 or argv[0] == '--help': self.print_resources() sys.stdout.write('\n') parser.parse_args() return # Load the resource module specified in the cmdline. self._load_resource(argv[0]) if self.resource: # Pass the remaining cmdline arguments. self.resource.run(argv[1:]) else: raise ControllerException("Resource '%s' is not loaded" % argv[0])
def set_content(self, argv): """Sets the content of a file.""" options, path = self._get_options(argv, 'set_content') if not path: raise ControllerException("Please specify the file name.") from_file = options.get('from_file') from_url = options.get('from_url') from_string = options.get('from_string') mon = self.get_mon_value(options) content = None if from_file: content = self._get_content_from_file(from_file) self.do_action('set_content', path, content) elif from_url: self.do_action('set_content_from_url', path, from_url) elif from_string: content = base64.b64encode(from_string) self.do_action('set_content', path, content, encoding='base64') else: print "No content specified"
def create(self, argv): """ Creates a group. """ options, name = self._get_options(argv, 'create') if not name: raise ControllerException("Please specify the group name") self.do_action('create', name)
def execute(self, argv): """ Executes a raw command on the remote system. """ options, command = self._get_options(argv, 'execute') if not command: raise ControllerException("Please specify a command") self.do_action('execute', command)
def remove(self, argv): """ Removes a group. """ options, name = self._get_options(argv, 'remove') if not name: raise ControllerException("Please specify the group name") self.do_action('remove', name)
def reload(self, argv): """ Reloads the service. """ options, name = self._get_options(argv, "reload") if not name: raise ControllerException("Please specify the service name.") mon = self.get_mon_value(options) self.do_action('reload', name, monitor=mon)
def stop(self, argv): """ Stops the service. """ options, name = self._get_options(argv, "stop") if not name: raise ControllerException("Please specify the service name.") mon = self.get_mon_value(options) self.do_action('stop', name, monitor=mon)
def status(self, argv): """ Retrieves a user's informations. """ options, name = self._get_options(argv, "status") if not name: raise ControllerException("Please specify the user name.") self.do_action('infos', name)
def delete(self, argv): """Deletes a file.""" options, path = self._get_options(argv, 'delete') mon = self.get_mon_value(options) if not path: raise ControllerException("Please specify the file name.") self.do_action('delete', path, monitor=mon)
def disable(self, argv): """ Disables the service at boot. """ options, name = self._get_options(argv, "disable") if not name: raise ControllerException("Please specify the service name.") mon = self.get_mon_value(options) self.do_action('disable', name, monitor=mon)
def create(self, argv): """ Creates a file on remote hosts. """ options, path = self._get_options(argv, 'create') if not path: raise ControllerException("Please specify the file name.") attributes = self._get_attrs('create', options) mon = self.get_mon_value(options) self.do_action('create', path, monitor=mon, **attributes)
def remove(self, argv): """ Removes a user. """ options, name = self._get_options(argv, "remove") if not name: raise ControllerException("Please specify the user name.") mon = self.get_mon_value(options) self.do_action('remove', name, mon)
def update(self, argv): """ Updates a group. """ options, name = self._get_options(argv, 'update') if not name: raise ControllerException("Please specify the group name") _new_name = options.get('new_name') self.do_action('update', name, _new_name)
def edit(self, argv): """ Edits a file "remotely". It's opened in $EDITOR. """ options, path = self._get_options(argv, 'edit') if not path: raise ControllerException("Please specify the file name.") responses = [] nb_hosts = 0 request = self.api.infos(path, md5=True, content=True) with self.client: self.ping() nb_hosts = len(self.disco_hosts) if nb_hosts: self.client.send(request) responses = self.get_responses() else: return mon = self.get_mon_value(options) if len(responses): # Gets the first md5. md5 = responses[0].get('status').get('md5') can_edit = True for resp in responses: if resp.get('status').get('md5') != md5: print "\nSorry, you can't update because files differ " \ "on hosts." print "You could use the --force, Luke, to bypass this " \ "limitation." can_edit = False if options.get('force') or can_edit: resp = responses[0].get('status') if not resp.get('error'): path = resp.get('name', path) starting_text = resp.get('content', ' ') try: content = editor.edit_text(starting_text) or ' ' self.client.connect() request = self.api.set_content(path, content, monitor=mon) self.client.send(request) self.get_responses() self.client.disconnect() except editor.NotModifiedException: print "File not modified."
def update(self, argv): """ Updates a user. """ options, name = self._get_options(argv, "update") if not name: raise ControllerException("Please specify the user name.") if not options: self.print_options(self.attributes) raise ControllerException("Please specify options.") _password = options.get("password") _login_group = options.get("login_group") _add_to_groups = options.get("add_to_groups") _remove_from_groups = options.get("remove_from_groups") _set_groups = options.get("set_groups") mon = self.get_mon_value(options) self.do_action('update', name, _password, _login_group, _add_to_groups, _remove_from_groups, _set_groups, mon)
def create(self, argv): """ Creates a user. """ options, name = self._get_options(argv, "create") if not name: raise ControllerException("Please specify the user name.") if not options: self.print_options("create") raise ControllerException("Please specify options.") _password = options.get("password") _login_group = options.get("login_group") _groups = options.get("groups") mon = self.get_mon_value(options) self.do_action('create', name, _password, _login_group, _groups, monitor=mon)
def _save_files(self, responses, path): for resp in responses: if not resp.get('error'): filename = os.path.basename(resp['status']['name']) folder = os.path.join(os.path.abspath(path), resp['uuid']) try: os.makedirs(folder, 0755) except OSError: pass filepath = os.path.join(folder, filename) try: with open(filepath, 'w') as fd: fd.write(resp['status']['content']) except IOError as err: raise ControllerException(err) print "File content saved to %s" % filepath else: fmt.pprint(resp)
def run(self, argv): """ """ self.action_completion(argv) if len(argv) == 0: print "Please specify an action.\n" self._print_actions() elif argv[0] == '--help': self._print_actions() else: action = argv[0] if action in self._actions: remaining_args = argv[1:] # Call the resource method associated to this action. self._actions[action](remaining_args) else: raise ControllerException("%s is not a valid action." % action)