예제 #1
0
    def load_json_file(self, json_file):
        """Open file as read, load json, returns dict."""
        self.called_tools.append('load_json_file')
        try:
            with open(json_file, 'r') as file:
                dict_result = json.load(file)
        except FileNotFoundError as error:
            self.safe_create_folder(CONSTANTS.CONF_FOLDER)
            raise RbkcliException.ToolsError(error)
        except json.decoder.JSONDecodeError as error:
            raise RbkcliException.ToolsError(error)

        return dict_result
예제 #2
0
파일: api.py 프로젝트: powershellvb/rbkcli
    def _create_auth_header(self):
        """Create the auth header based on auth type (user/token)."""
        user_agent = "RubrikRbkcli--{}--{}".format(self.rbkcli_version,
                                                   self.python_version)
        try:
            auth = 'Bearer ' + self.auth.token
            self.auth_prpt.type_ = 'token'
            if self.auth_prpt.primary_exception != '':
                raise RbkcliException.ToolsError(
                    self.auth_prpt.primary_exception)
        except KeyError as bad_key:
            msg = ('Authorization key not found ' + str(bad_key))
            auth = self._create_username_header(msg)
        # Fix or cleanup needed.
        except AttributeError as bad_key:
            msg = ('Authorization key not found ' + str(bad_key))
            auth = self._create_username_header(msg)
        # Until here
        except RbkcliException.ToolsError as error:
            auth = self._create_username_header(error)

        self.auth_prpt.header = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': user_agent,
            'Authorization': auth,
        }
예제 #3
0
 def load_conf_file(self, file='', conf_dict=None):
     """Load configuration data from json file."""
     self.called_tools.append('load_conf_file')
     if conf_dict is None:
         conf_dict = {}
     try:
         if file == '':
             file = CONSTANTS.CONF_FOLDER + '/rbkcli.conf'
         msg = '%s [%s]' % ('IOTools # Successfully loaded configuration'
                            ' file: ', file)
         if conf_dict == {} and self.conf_dict == {}:
             self.conf_dict = self.load_json_file(file)
             self.logger.debug(msg)
         elif isinstance(conf_dict, dict) and self.conf_dict == {}:
             self.conf_dict = conf_dict
             self.logger.debug(msg)
         else:
             msg = 'IOTools # Configuration file already loaded.'
             self.logger.debug(msg)
         CONSTANTS.CONF_DICT = self.conf_dict
     except RbkcliException.ToolsError:
         try:
             self.create_vanila_conf()
             self.load_conf_file()
         except RbkcliException.ToolsError:
             msg = 'Unable to load configuration file'
             self.logger.error('IOToolsError # ' + msg)
             raise RbkcliException.ToolsError(msg)
     return self.conf_dict
예제 #4
0
    def load_env_auth(self):
        """Load authentication data from environment variables."""
        self.called_tools.append('load_env_auth')
        try:
            self.auth.server = os.environ['rubrik_cdm_node_ip']
            self.auth.username = os.environ['rubrik_cdm_username']
            self.auth.password = os.environ['rubrik_cdm_password']
            self.auth.token = os.environ['rubrik_cdm_token']

        except KeyError as bad_key:
            if str(bad_key) != "\'rubrik_cdm_token\'" and str(
                    bad_key) != "\'RUBRIK_CDM_TOKEN\'":
                msg = '%s%s%s' % ('Unable to load environmental variable for'
                                  ' authentication: ', bad_key,
                                  '. Are they defined?')
                self.logger.error('IOToolsError # ' + msg)
                raise RbkcliException.ToolsError(msg)
            else:
                # Log successful actions
                keys = ''
                for line in self.auth.keys():
                    keys = keys + ',' + line
                msg = '%s [%s]' % ('IOTools # Successfully loaded'
                                   ' environmental vars', keys.strip(','))
                self.logger.debug(msg)

        return self.auth
예제 #5
0
    def load_yaml_file(self, yaml_file):
        """Open file as read, load yaml, returns dict."""
        self.called_tools.append('load_yaml_file')

        try:
            with open(yaml_file, 'r') as file:
                dict_result = yaml.safe_load(file.read())
        except FileNotFoundError as error:
            raise RbkcliException.ToolsError(error)

        return dict_result
예제 #6
0
    def load_auth_key(self, key):
        """Load key by key confirming if consistency is kept."""
        try:
            self.auth[key] = self.auth_dict[key]

        except KeyError as bad_key:
            if str(bad_key) == "\'token\'":
                if ('username' not in self.auth_dict.keys()
                        and 'password' not in self.auth_dict.keys()):
                    msg = '%s%s%s' % ('Unable to load authentication data from'
                                      ' configuration file: ', bad_key,
                                      '. Are all keys defined correctly?')
                    self.logger.error('IOToolsError # ' + msg)
                    raise RbkcliException.ToolsError(msg)

            elif (str(bad_key) != "\'password\'"
                  or str(bad_key) != "\'username\'"):
                msg = '%s%s%s' % ('Unable to load authentication data from '
                                  'configuration file: ', bad_key,
                                  '. Are all keys defined correctly?')
                self.logger.error('IOToolsError # ' + msg)
                raise RbkcliException.ToolsError(msg)
예제 #7
0
    def download_file(self, url):
        """Download file from provided url."""
        self.called_tools.append('download_file')
        pool = urllib3.PoolManager(cert_reqs='CERT_NONE')
        try:
            with pool.request('GET', url, preload_content=False) as file:
                content = file.read()
            if content == b'Route not defined.':
                error = str('Wrong or nonexistent URL [' + url + '], route is '
                            'not defined')
                msg = 'IOToolsError # ' + error
                self.logger.error(msg)
                raise RbkcliException.ToolsError(error)
            else:
                msg = str('IOTools # Successfully downloaded file [%s]' % url)
                self.logger.debug(msg)

        except urllib3.exceptions.MaxRetryError as error:
            msg = 'IOToolsError # ' + str(error)
            self.logger.error(msg)
            raise RbkcliException.ToolsError(str(error))

        return content
예제 #8
0
 def load_auth_file(self):
     """Load authentication data from json file."""
     self.called_tools.append('load_auth_file')
     file = 'rbkcli.conf'
     try:
         if self.conf_dict == {}:
             self.load_conf_file()
         file = self.conf_dict['config']['credentialsFile']['value']
         file = CONSTANTS.CONF_FOLDER + '/' + file
         self.auth_dict = self.load_json_file(file)
     except RbkcliException.ToolsError:
         msg = 'Unable to load auth file, [' + file + ']'
         self.logger.error('IOToolsError # ' + msg)
         raise RbkcliException.ToolsError(msg)
예제 #9
0
    def _resolve_target(self, target_name):
        """Resolve target fqdn to IP."""
        # Split port and fqdn
        if ':' in target_name:
            target_name = target_name.split(':')
            target_ip = target_name[0]
            port = ':' + target_name[1]
        else:
            port = ''
            target_ip = target_name
        try:
            target_ip = str(socket.gethostbyname(target_ip))
        except socket.gaierror:
            msg = 'Unable to resolve FQDN [%s].' % target_ip
            self.logger.error('ToolsError # ' + msg)
            raise RbkcliException.ToolsError(msg)

        return target_ip + port
예제 #10
0
    def create_json_file(self, json_dict, json_file):
        """Open file as write, dump json dict to file."""
        self.called_tools.append('create_json_file')
        try:
            with open(json_file, 'w') as file:
                file.write(json.dumps(json_dict, indent=2, sort_keys=True))
            self.logger.debug('IOTools # File created successfully: ' +
                              json_file)
            return True
        except FileNotFoundError as error:
            error = str(error) + '\n'
            msg = 'Exception is ' + error
            self.logger.error('IOToolsError # ' + msg)
            return False

        except Exception as error:
            error = str(error) + '\n'
            msg = 'Exception is ' + str(error)
            self.logger.error('IOToolsError # ' + msg)
            raise RbkcliException.ToolsError(error)
예제 #11
0
    def create_yaml_file(self, yml_dict, yml_file):
        """Open file as write, dump yaml dict to file."""
        self.called_tools.append('create_yaml_file')
        try:
            with open(yml_file, 'w') as file:
                yaml.dump(yml_dict, file, default_flow_style=False)
            self.logger.debug('File created successfully: ' + yml_file)

            return True
        except FileNotFoundError as error:
            error = str(error) + '\n'
            msg = 'Exception is ' + error
            self.logger.error('IOToolsError # ' + msg)
            return False

        except Exception as error:
            error = str(error) + '\n'
            msg = 'Exception is ' + error
            self.logger.error('IOToolsError # ' + msg)
            raise RbkcliException.ToolsError(error)
예제 #12
0
    def load_file_auth(self):
        """Load authentication data from json file."""
        self.called_tools.append('load_file_auth')

        if self.conf_dict['config']['useCredentialsFile']['value'] == 'False':
            msg = 'CredentialsFile is disable, unable to read from file.'
            raise RbkcliException.ToolsError(msg)

        self.load_auth_file()
        auth_keys = ['server', 'token', 'username', 'password']
        for key in auth_keys:
            self.load_auth_key(key)
        # Log successful actions
        keys = ''
        for line in self.auth.keys():
            keys = keys + ',' + line
        msg = '%s [%s]' % ('IOTools # Successfully loaded file auth data',
                           keys.strip(','))
        self.logger.debug(msg)

        return self.auth
예제 #13
0
    def natural_simple_dictstr(natural_str):
        """Convert natural values into simple dictionary."""
        simple_dictstr = []

        if isinstance(natural_str, list):
            natural_str = natural_str[0]
        natural_str = natural_str.split(',')

        for item in natural_str:
            try:
                key, value = item.split('=')
                if value[0] == '[' and value[-1] == ']':
                    value = value[1:-1]
                    simple_dictstr.append('"%s": ["%s"]' % (key, value))
                else:
                    simple_dictstr.append('"%s": "%s"' % (key, value))
            except ValueError as e:
                raise RbkcliException.ToolsError('jsops error: ' + str(e) +
                                                 '\n')

        return str('{%s}' % ', '.join(simple_dictstr))
예제 #14
0
 def create_vanila_conf(self):
     """Create a default configuration file."""
     self.called_tools.append('create_vanila_conf')
     conf_dict = {
         "config": {
             "storeToken": {
                 "value":
                 "False",
                 "description":
                 str("Caches the last successful token "
                     "with environment data.")
             },
             "logLevel": {
                 "value":
                 "debug",
                 "description":
                 str("Verbosity of the logs written to the"
                     " file logs/rbkcli.log.")
             },
             "useCredentialsFile": {
                 "value":
                 "False",
                 "description":
                 str("Tries to load credentials from auth"
                     " file before looking for env vars.")
             },
             "credentialsFile": {
                 "value":
                 "target.conf",
                 "description":
                 str("File where to load credentials from, "
                     "before looking for env vars.")
             },
             "whiteList": {
                 "description":
                 "",
                 "value": [
                     'v1:/session:post:NA',
                     'internal:/report/{id}/table:post:NA',
                     'internal:/managed_volume/{id}/begin_snapshot:post:NA',
                     'internal:/managed_volume/{id}/end_snapshot:post:NA',
                     'internal:/support/support_bundle:post:NA',
                     'rbkcli:/cmdlet/profile:get:NA',
                     'rbkcli:/cmdlet/profile:post:NA',
                     'rbkcli:/cmdlet/sync:post:NA',
                     'rbkcli:/cmdlet:delete:NA', 'rbkcli:/cmdlet:get:NA',
                     'rbkcli:/cmdlet:post:NA', 'rbkcli:/commands:get:NA',
                     'rbkcli:/jsonfy:get:NA', 'rbkcli:/script/sync:post:NA',
                     'rbkcli:/script:get:NA', 'scripts:/log/bundle:post:NA'
                 ]
             },
             "blackList": {
                 "description": "",
                 "value": []
             },
             "userProfile": {
                 "description":
                 str("String value which can be admin or "
                     "support. A profile is a set of API"
                     " endpoints that is available in the"
                     " command line."),
                 "value":
                 "admin"
             }
         }
     }
     file = CONSTANTS.CONF_FOLDER + '/rbkcli.conf'
     try:
         self.safe_create_folder(CONSTANTS.CONF_FOLDER)
         self.create_json_file(conf_dict, file)
         msg = 'Successfully created new configuration file'
         self.logger.debug('IOTools # ' + msg)
     except Exception:
         msg = 'Unable to create new configuration file'
         self.logger.error('IOToolsError # ' + msg)
         raise RbkcliException.ToolsError(msg)