示例#1
0
文件: shell.py 项目: agilee/st2
    def get_client(self, args, debug=False):
        ST2_CLI_SKIP_CONFIG = os.environ.get('ST2_CLI_SKIP_CONFIG', 0)
        ST2_CLI_SKIP_CONFIG = int(ST2_CLI_SKIP_CONFIG)

        skip_config = args.skip_config
        skip_config = skip_config or ST2_CLI_SKIP_CONFIG

        # Note: Options provided as the CLI argument have the highest precedence
        # Precedence order: cli arguments > environment variables > rc file variables
        cli_options = ['base_url', 'auth_url', 'api_url', 'api_version', 'cacert']
        cli_options = {opt: getattr(args, opt) for opt in cli_options}
        config_file_options = self._get_config_file_options(args=args)

        kwargs = {}

        if not skip_config:
            # Config parsing is skipped
            kwargs = merge_dicts(kwargs, config_file_options)

        kwargs = merge_dicts(kwargs, cli_options)
        kwargs['debug'] = debug

        client = Client(**kwargs)

        if ST2_CLI_SKIP_CONFIG:
            # Config parsing is skipped
            LOG.info('Skipping parsing CLI config')
            return client

        # If credentials are provided in the CLI config use them and try to authenticate
        rc_config = self._parse_config_file(args=args)

        credentials = rc_config.get('credentials', {})
        username = credentials.get('username', None)
        password = credentials.get('password', None)
        cache_token = rc_config.get('cli', {}).get('cache_token', False)

        if username and password:
            # Credentials are provided, try to authenticate agaist the API
            try:
                token = self._get_auth_token(client=client, username=username, password=password,
                                             cache_token=cache_token)
            except requests.exceptions.ConnectionError as e:
                LOG.warn('Auth API server is not available, skipping authentication.')
                LOG.exception(e)
                return client
            except Exception as e:
                print('Failed to authenticate with credentials provided in the config.')
                raise e

            client.token = token
            # TODO: Hack, refactor when splitting out the client
            os.environ['ST2_AUTH_TOKEN'] = token

        return client
示例#2
0
    def test_args(self):
        base_url = 'http://www.stackstorm.com'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'

        client = Client(base_url=base_url,
                        api_url=api_url,
                        stream_url=stream_url)
        endpoints = client.endpoints
        self.assertEqual(endpoints['base'], base_url)
        self.assertEqual(endpoints['api'], api_url)
        self.assertEqual(endpoints['stream'], stream_url)
示例#3
0
    def run(self, deviceIP, cmd_path, subnet, nextHop):

        cmd_path = cmd_path[:26]
        subnet = subnet.replace("/", "%2F")

        # Fetching device credentials based on keys derived from deviceIP
        #################################################################
        user_key_name = deviceIP + "_user"
        pswd_key_name = deviceIP + "_pswd"
        print("\n")
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        print("Looking for credentials in KV store")
        client = Client()
        try:
            user = (client.keys.get_by_name(user_key_name)).value
            pswd = (client.keys.get_by_name(pswd_key_name)).value
            print("     Obtained from KV store: user = "******"     Obtained from KV store: pswd = " + pswd)
        except Exception:
            return (False, "No credentials for : " + deviceIP)

        # Preapring the URL request(s)
        #################################################################
        h = {
            "accept": "application/json",
            "content-length": "0"
        }

        url_0 = "https://" + deviceIP + "/" + cmd_path
        url_1 = "/set/protocols/static/route/" + subnet
        url_2 = "/next-hop/" + nextHop
        url = url_0 + url_1 + url_2

        # Sending the URL call(s)
        #################################################################
        print("Sending REST call(s):")
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            print("     PUT            " + url)
            r = requests.put(url, auth=(user, pswd), headers=h, verify=False)
            r_code = str(r.status_code)
            print("     Response code:   " + r_code)
            cmd_response_code = int(r.status_code)
            if cmd_response_code != 200:
                return (False, cmd_response_code)
            else:
                try:
                    data = json.loads(r.text)
                    print("     Response body: ")
                    print(json.dumps(data, sort_keys=True, indent=4))
                except Exception:
                    print("     Response body: empty")
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
示例#4
0
    def test_env_base_only(self):
        base_url = 'http://www.stackstorm.com'
        api_url = 'http://www.stackstorm.com:9101'

        os.environ['ST2_BASE_URL'] = base_url
        self.assertEqual(os.environ.get('ST2_BASE_URL'), base_url)
        self.assertEqual(os.environ.get('ST2_API_URL'), None)

        client = Client()
        endpoints = client.endpoints
        self.assertEqual(endpoints['base'], base_url)
        self.assertEqual(endpoints['api'], api_url)
示例#5
0
文件: datastore.py 项目: tzmvp/st2
    def get_api_client(self):
        """
        Retrieve API client instance.
        """
        if not self._client:
            self._logger.debug('Creating new Client object.')

            api_url = get_full_public_api_url()
            client = Client(api_url=api_url, token=self._auth_token)
            self._client = client

        return self._client
    def test_managers(self):
        property_names = [
            k for k, v in six.iteritems(Client.__dict__)
            if isinstance(v, property)
        ]

        client = Client()

        for property_name in property_names:
            manager = getattr(client, property_name, None)
            self.assertIsNotNone(manager)
            self.assertIsInstance(manager, models.ResourceManager)
示例#7
0
    def __init__(self, config=None, action_service=None):
        super(FormatResultAction, self).__init__(config=config,
                                                 action_service=action_service)
        api_url = os.environ.get('ST2_ACTION_API_URL', None)
        token = os.environ.get('ST2_ACTION_AUTH_TOKEN', None)
        self.client = Client(api_url=api_url, token=token)
        self.jinja = jinja_utils.get_jinja_environment(allow_undefined=True)
        self.jinja.tests['in'] = lambda item, list: item in list

        path = os.path.dirname(os.path.realpath(__file__))
        with open(os.path.join(path, 'templates/default.j2'), 'r') as f:
            self.default_template = f.read()
示例#8
0
    def run(self, deviceIP, targetIP):

        # Fetching device credentials based on keys derived from deviceIP
        #################################################################
        user_key_name = deviceIP + "_user"
        pswd_key_name = deviceIP + "_pswd"
        print "\n"
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        print "Looking for credentials in KV store"
        client = Client()
        try:
            user = (client.keys.get_by_name(user_key_name)).value
            pswd = (client.keys.get_by_name(pswd_key_name)).value
            print "     Obtained from KV store: user = "******"     Obtained from KV store: pswd = " + pswd
        except:
            return (False, "No credentials for : " + deviceIP)

        # Preapring the URL request(s)
        #################################################################
        h = {
            "accept": "application/json",
            "content-length": "0"
        }

        url_base = "https://" + deviceIP + "/rest/op/"
        url = url_base + "ping/" + targetIP

        # Sending the URL call(s)
        #################################################################
        print "Sending REST call(s):"
        print "     POST            " + url
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = requests.post(url, auth=(user, pswd), headers=h, verify=False)
            r_code = str(r.status_code)
            print "     Response code:   " + r_code
            if r.status_code == 201:
                cmd_path = r.headers["Location"]
                url = "https://" + deviceIP + "/" + cmd_path
                time.sleep(2)
                print "     GET             " + url
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    r2 = requests.get(url, auth=(user, pswd),
                                      headers=h, verify=False)
                    output_response_code = str(r2.status_code)
                    print "     Response code:   " + output_response_code
                    print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
                    print"\n"
                if r2.status_code == 200:
                    print r2.text
                    print("\n")
示例#9
0
    def test_args(self):
        base_url = "http://www.stackstorm.com"
        api_url = "http://www.st2.com:9101/v1"
        stream_url = "http://www.st2.com:9102/v1"

        client = Client(base_url=base_url,
                        api_url=api_url,
                        stream_url=stream_url)
        endpoints = client.endpoints
        self.assertEqual(endpoints["base"], base_url)
        self.assertEqual(endpoints["api"], api_url)
        self.assertEqual(endpoints["stream"], stream_url)
示例#10
0
    def _get_api_client(self):
        """
        Retrieve API client instance.
        """
        if not self._client:
            ttl = (24 * 60 * 60)
            temporary_token = create_token(username=self._api_username,
                                           ttl=ttl)
            api_url = get_full_public_api_url()
            self._client = Client(api_url=api_url, token=temporary_token.token)

        return self._client
    def run(self, deviceIP, cmd_path, fw_instance_name, intfNum, direction):

        cmd_path = cmd_path[:26]

        # Fetching device credentials based on keys derived from deviceIP
        #################################################################
        user_key_name = deviceIP + "_user"
        pswd_key_name = deviceIP + "_pswd"
        print "\n"
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        print "Looking for credentials in KV store"
        client = Client()
        try:
            user = (client.keys.get_by_name(user_key_name)).value
            pswd = (client.keys.get_by_name(pswd_key_name)).value
            print "     Obtained from KV store: user = "******"     Obtained from KV store: pswd = " + pswd
        except:
            return (False, "No credentials for : " + deviceIP)

        # Preapring the URL request(s)
        #################################################################
        h = {
            "accept": "application/json",
            "content-length": "0"
        }

        url_0 = "https://" + deviceIP + "/" + cmd_path
        url_1 = "/set/interfaces/dataplane/" + intfNum
        url_2 = "/firewall/" + direction + "/" + fw_instance_name
        url = url_0 + url_1 + url_2

        # Sending the URL call(s)
        #################################################################
        print "Sending REST call(s):"
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            print "     PUT            " + url
            r = requests.put(url, auth=(user, pswd), headers=h, verify=False)
            r_code = str(r.status_code)
            print "     Response code:   " + r_code
            cmd_response_code = int(r.status_code)
            if cmd_response_code != 200:
                return (False, cmd_response_code)
            else:
                try:
                    data = json.loads(r.text)
                    print "     Response body: "
                    print json.dumps(data, sort_keys=True, indent=4)
                except:
                    print "     Response body: empty"
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
示例#12
0
    def run(self, deviceIP, cmd_path):

        cmd_path = cmd_path[:26]

        # Fetching device credentials based on keys derived from deviceIP
        #################################################################
        user_key_name = deviceIP + "_user"
        pswd_key_name = deviceIP + "_pswd"
        print("\n")
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        print("Looking for credentials in KV store")
        client = Client()
        try:
            user = (client.keys.get_by_name(user_key_name)).value
            pswd = (client.keys.get_by_name(pswd_key_name)).value
            print("     Obtained from KV store: user = "******"     Obtained from KV store: pswd = " + pswd)
        except Exception:
            return (False, "No credentials for : " + deviceIP)

        # Preapring the URL request(s)
        #################################################################
        h = {
            "accept": "application/json",
            "content-length": "0"
        }

        url_base = "https://" + deviceIP + "/" + cmd_path
        url = url_base + "/commit"

        # Sending the URL call(s)
        #################################################################
        print("Sending REST call(s):")
        print("     POST            " + url)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = requests.post(url, auth=(user, pswd), headers=h, verify=False)
            r_code = str(r.status_code)
            print("     Response code:   " + r_code)

            if r.status_code == 200:
                try:
                    data = json.loads(r.text)
                    print("     Response body: ")
                    print(json.dumps(data, sort_keys=True, indent=4))
                    return True, data
                    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                except Exception:
                    print("     Response body is empty")
                    print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
            else:
                return (False, "Failed!")
示例#13
0
    def test_get_cached_auth_token_corrupted_token_cache_file(self):
        client = Client()
        shell = Shell()
        username = '******'
        password = '******'

        cached_token_path = shell._get_cached_token_path_for_user(username=username)
        with open(cached_token_path, 'w') as fp:
            fp.write('CORRRRRUPTED!')

        expected_msg = 'File (.+) with cached token is corrupted or invalid'
        self.assertRaisesRegexp(ValueError, expected_msg, shell._get_cached_auth_token,
                                client=client, username=username, password=password)
示例#14
0
    def run(self, deviceIP, cmd_path):

        cmd_path = cmd_path[:26]

        # Fetching device credentials based on keys derived from deviceIP
        #################################################################
        user_key_name = deviceIP + "_user"
        pswd_key_name = deviceIP + "_pswd"
        print "\n"
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
        print "Looking for credentials in KV store"
        client = Client()
        try:
            user = (client.keys.get_by_name(user_key_name)).value
            pswd = (client.keys.get_by_name(pswd_key_name)).value
            print "     Obtained from KV store: user = "******"     Obtained from KV store: pswd = " + pswd
        except:
            return (False, "No credentials for : " + deviceIP)

        # Preapring the URL request(s)
        #################################################################
        h = {"accept": "application/json", "content-length": "0"}

        url_list = list()

        url_base = "https://" + deviceIP + "/" + cmd_path
        url = url_base + "/delete/protocols/bgp/"
        url_list.append(url)

        # Sending the URL call(s)
        #################################################################
        print "Sending REST call(s):"
        for u in url_list:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                print "     PUT            " + u
                r = requests.put(u, auth=(user, pswd), headers=h, verify=False)
                r_code = str(r.status_code)
                print "     Response code:   " + r_code
                cmd_response_code = int(r.status_code)
                if cmd_response_code != 200:
                    return (False, cmd_response_code)
                else:
                    try:
                        data = json.loads(r.text)
                        print "     Response body: "
                        print json.dumps(data, sort_keys=True, indent=4)
                    except:
                        print "     Response body: empty"
        print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
示例#15
0
    def run(self, repo, user, homepage, description, pack_yaml_data):
        self.client = Client(base_url='http://localhost')

        self.templates_folder = 'pack_template'
        self.templates_dir = '/opt/stackstorm/bitovi-stackstorm-exchange/bitovi_packs/actions/' + self.templates_folder
        self.temp_templates_root = "/opt/stackstorm/tmp_create_{repo}".format(
            repo=repo)
        self.temp_templates_dir = "{a}/{b}".format(a=self.temp_templates_root,
                                                   b=self.templates_folder)

        # Prep he tmp directory template files
        os.system("rm -rf {dir}".format(dir=self.temp_templates_root))
        self.makedirs(self.temp_templates_dir)

        # Copy template files from {templates_dir} to {temp_templates_root}
        os.system("cp -rf {a} {b}".format(a=self.templates_dir,
                                          b=self.temp_templates_root))

        self._save_obj_to_yaml_file(self.temp_templates_root, 'pack.yaml',
                                    pack_yaml_data)
        self._save_obj_to_yaml_file(self.temp_templates_root + '/rules',
                                    'watch_pack_commit.yaml',
                                    self.get_watch_pack_commit_rule(repo))
        self._save_file_contents(self.temp_templates_root, 'README.md',
                                 self.get_readme(repo, user, description))

        commit_message = "Bootstrap a Bitovi StackStorm Exchange pack repository for pack {repo}".format(
            repo=repo)
        os.chdir(self.temp_templates_root)
        os.system("git init")
        os.system(
            "git config user.email '{email}'".format(email="*****@*****.**"))
        os.system(
            "git config user.name '{name}'".format(name=self.github_user))
        os.system("git add .")
        os.system("git commit -m '{message}'".format(message=commit_message))
        os.system(
            "git remote add origin https://{gu}:{gt}@github.com/{user}/{repo}.git"
            .format(gu=self.github_user,
                    gt=self.github_token,
                    user=user,
                    repo=repo))
        os.system("git push -u origin master")
        os.system("git checkout -b dev")
        os.system("git push -u origin HEAD")

        # Remove the template files
        os.system("rm -rf {dir}".format(dir=self.temp_templates_root))

        return True
示例#16
0
    def run(self):

        self.client = Client(base_url='http://localhost')
        queryresult = self.client.keys.query(prefix="NPING")
        iplist = []

        for key in queryresult:
            _name = key.name
            _ip = _name.split(':')[1]
            iplist.append(_ip)

        if iplist:
            return (True, iplist)
        return (False)
示例#17
0
    def test_basic_auth_option_success_password_with_colon(self):
        client = Client(basic_auth="username:password:with:colon")
        self.assertEqual(client.basic_auth,
                         ("username", "password:with:colon"))

        self.assertEqual(requests.get.call_count, 0)
        client.actions.get_all()
        self.assertEqual(requests.get.call_count, 1)

        requests.get.assert_called_with(
            "http://127.0.0.1:9101/v1/actions",
            auth=("username", "password:with:colon"),
            params={},
        )
示例#18
0
    def run(self):

        self.client = Client(base_url='http://localhost')
        queryresult = self.client.keys.query(prefix="NDEV")
        nbgplist = []

        for key in queryresult:
            _name = key.name
            _nname = _name.split(':')[1]
            nbgplist.append(_nname)

        if nbgplist:
            return (True, nbgplist)
        return (False)
示例#19
0
    def run(self, count=100):
        pool = GreenPool(count)
        client = Client()
        rule_ids = []

        name_patterns = ['key1', 'key2', 'key3', 'key4', 'key5']

        def create_rule(rule):
            try:
                rule = client.rules.create(rule)
            except Exception as e:
                # Rule already exists, ignore the error
                print(e)
                return

            rule_ids.append(rule.id)

        start_timestamp = time.time()

        index_name_pattern = 0
        for index in range(0, count):
            rule = Rule()
            rule.name = 'rule_%s' % (index)
            rule.pack = 'default'
            rule.trigger = {'type': 'core.st2.key_value_pair.create'}

            # Use uniform distribution of names so if COUNT is 100, each key
            # will be used COUNT / len(KEYS)
            if index_name_pattern >= len(name_patterns):
                index_name_pattern = 0

            pattern = name_patterns[index_name_pattern]
            rule.criteria = {
                'trigger.object.name': {
                    'pattern': (pattern),
                    'type': 'equals'
                }
            }
            rule.action = {'ref': 'core.noop'}
            index_name_pattern += 1

            pool.spawn(create_rule, rule)

        pool.waitall()

        end_timestamp = time.time()
        delta = (end_timestamp - start_timestamp)

        print('Created %d rules in %ss.' % (count, delta))
示例#20
0
    def _get_api_client(self):
        """
        Retrieve API client instance.
        """
        token_expire = self._token_expire <= get_datetime_utc_now()

        if not self._client or token_expire:
            self._logger.audit('Creating new Client object.')
            ttl = cfg.CONF.auth.service_token_ttl
            self._token_expire = get_datetime_utc_now() + timedelta(seconds=ttl)
            temporary_token = create_token(username=self._api_username, ttl=ttl, service=True)
            api_url = get_full_public_api_url()
            self._client = Client(api_url=api_url, token=temporary_token.token)

        return self._client
示例#21
0
    def test_env_base_only(self):
        base_url = "http://www.stackstorm.com"
        api_url = "http://www.stackstorm.com:9101/v1"
        stream_url = "http://www.stackstorm.com:9102/v1"

        os.environ["ST2_BASE_URL"] = base_url
        self.assertEqual(os.environ.get("ST2_BASE_URL"), base_url)
        self.assertEqual(os.environ.get("ST2_API_URL"), None)
        self.assertEqual(os.environ.get("ST2_STREAM_URL"), None)

        client = Client()
        endpoints = client.endpoints
        self.assertEqual(endpoints["base"], base_url)
        self.assertEqual(endpoints["api"], api_url)
        self.assertEqual(endpoints["stream"], stream_url)
示例#22
0
def runAction(action_ref, params):

    client = Client()
    action_exec_mgr = client.managers['LiveAction']

    execution = models.LiveAction()
    execution.action = action_ref
    execution.parameters = param_parser(params)
    actionexec = action_exec_mgr.create(execution)

    while actionexec.status not in END_STATES:
        time.sleep(2)
        actionexec = action_exec_mgr.get_by_id(actionexec.id)

    return actionexec
示例#23
0
    def test_get_cached_auth_token_valid_token_in_cache_file(self):
        client = Client()
        shell = Shell()
        username = "******"
        password = "******"

        cached_token_path = shell._get_cached_token_path_for_user(username=username)
        data = {"token": "yayvalid", "expire_timestamp": (int(time.time()) + 20)}
        with open(cached_token_path, "w") as fp:
            fp.write(json.dumps(data))

        result = shell._get_cached_auth_token(
            client=client, username=username, password=password
        )
        self.assertEqual(result, "yayvalid")
示例#24
0
    def execute_actionalias(self, action_alias, representation, msg):
        """
        @action_alias: the st2client action_alias object.
        @representation: the st2client representation for the action_alias.
        @msg: errbot message.
        """
        auth_kwargs = self.st2auth.auth_method("st2client")
        LOG.info("Create st2 client with {} {} {}".format(self.st2config.base_url,
                                                          self.st2config.api_url,
                                                          auth_kwargs))

        st2_client = Client(base_url=self.st2config.base_url,
                            api_url=self.st2config.api_url,
                            debug=True,
                            **auth_kwargs)

        execution = ActionAliasExecution()
        execution.name = action_alias.name
        execution.format = representation
        execution.command = msg.body
        if msg.is_direct == False:
            execution.notification_channel = str(msg.to)
            execution.source_channel = str(msg.to)
        else:
            execution.notification_channel = str(msg.frm)
            execution.source_channel = str(msg.frm)

        execution.notification_route = 'errbot'
        execution.user = str(msg.frm)

        LOG.info("Execution: {}".format([execution.command,
                                         execution.format,
                                         execution.name,
                                         execution.notification_channel,
                                         execution.notification_route,
                                         execution.source_channel,
                                         execution.user]))

        action_exec_mgr = st2_client.managers['ActionAliasExecution']
        execution = action_exec_mgr.create(execution)

        LOG.info("AFTER {}{}".format(type(execution), dir(execution)))
        try:
            ret_msg = execution.message
            LOG.info("AFTER {}{}".format(execution.execution, execution.message))
        except AttributeError as e:
            ret_msg = "Something is happening ... "
        return ret_msg # " ".join([execution.message])
示例#25
0
    def _generate_actionaliases(self):
        """
        generate pattern and help for action alias
        """
        self.help = ''
        self.pattern_action = {}

        base_url = self.st2config.base_url
        api_url = self.st2config.api_url

        auth_kwargs = self.st2auth.auth_method("st2client")
        LOG.info("\u001b[35m Create st2 client with {} {} {} \u001b[0m".format(base_url,
                                                                               api_url,
                                                                               auth_kwargs))
        st2_client = Client(base_url=base_url, api_url=api_url, **auth_kwargs)
        self.parser.process_actionaliases(st2_client.managers['ActionAlias'].get_all())
示例#26
0
    def __init__(self, config=None):
        super(BaseAction, self).__init__(config)

        if config is None:
            raise ValueError(
                "No connection configuration details found for san")

        if FIREWALLS in config:
            self.client = Client(base_url='http://localhost')
            self.list_fws = config[FIREWALLS]
            if self.list_fws is None:
                raise ValueError(FIREWALLS + " config defined but empty.")
            else:
                pass
        else:
            raise ValueError("No connection configuration details found")
示例#27
0
    def test_cache_auth_token_success(self):
        client = Client()
        shell = Shell()
        username = '******'
        password = '******'
        expiry = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)

        result = shell._get_cached_auth_token(client=client, username=username,
                                              password=password)
        self.assertEqual(result, None)

        token_db = TokenDB(user=username, token='fyeah', expiry=expiry)
        shell._cache_auth_token(token_obj=token_db)

        result = shell._get_cached_auth_token(client=client, username=username,
                                              password=password)
        self.assertEqual(result, 'fyeah')
示例#28
0
    def test_get_cached_auth_token_valid_token_in_cache_file(self):
        client = Client()
        shell = Shell()
        username = '******'
        password = '******'

        cached_token_path = shell._get_cached_token_path_for_user(username=username)
        data = {
            'token': 'yayvalid',
            'expire_timestamp': (int(time.time()) + 20)
        }
        with open(cached_token_path, 'w') as fp:
            fp.write(json.dumps(data))

        result = shell._get_cached_auth_token(client=client, username=username,
                                              password=password)
        self.assertEqual(result, 'yayvalid')
示例#29
0
文件: test_client.py 项目: zwunix/st2
    def test_env(self):
        base_url = 'http://www.stackstorm.com'
        api_url = 'http://www.st2.com:9101/v1'
        stream_url = 'http://www.st2.com:9102/v1'

        os.environ['ST2_BASE_URL'] = base_url
        os.environ['ST2_API_URL'] = api_url
        os.environ['ST2_STREAM_URL'] = stream_url
        self.assertEqual(os.environ.get('ST2_BASE_URL'), base_url)
        self.assertEqual(os.environ.get('ST2_API_URL'), api_url)
        self.assertEqual(os.environ.get('ST2_STREAM_URL'), stream_url)

        client = Client()
        endpoints = client.endpoints
        self.assertEqual(endpoints['base'], base_url)
        self.assertEqual(endpoints['api'], api_url)
        self.assertEqual(endpoints['stream'], stream_url)
示例#30
0
    def _get_api_client(self):
        """
        Retrieve API client instance.
        """
        # TODO: API client is really unfriendly and needs to be re-designed and
        # improved
        api_url = os.environ.get(API_URL_ENV_VARIABLE_NAME, None)
        auth_token = os.environ.get(AUTH_TOKEN_ENV_VARIABLE_NAME, None)

        if not api_url or not auth_token:
            raise ValueError('%s and %s environment variable must be set' %
                             (API_URL_ENV_VARIABLE_NAME, AUTH_TOKEN_ENV_VARIABLE_NAME))

        if not self._client:
            self._client = Client(api_url=api_url)

        return self._client
示例#31
0
    def select(self, query, data, key):
        q = query
        if data:
            values = self._list_to_string(data)
            q = q.format(values)

        c = self.db.cursor()
        try:
            c.execute(q)
            output = self._format_results(c)
            if key is not None:
                client = Client(base_url='http://localhost')
                client.keys.update(KeyValuePair(name=key, value=str(output)))
                return key
            else:
                return output
        except MySQLdb.Error as e:  # pylint: disable=no-member
            raise Exception(e)
示例#32
0
文件: shell.py 项目: Bala96/st2
    def get_client(self, args, debug=False):
        ST2_CLI_SKIP_CONFIG = os.environ.get('ST2_CLI_SKIP_CONFIG', 0)
        ST2_CLI_SKIP_CONFIG = int(ST2_CLI_SKIP_CONFIG)

        skip_config = args.skip_config
        skip_config = skip_config or ST2_CLI_SKIP_CONFIG

        # Note: Options provided as the CLI argument have the highest precedence
        # Precedence order: cli arguments > environment variables > rc file variables
        cli_options = ['base_url', 'auth_url', 'api_url', 'api_version', 'cacert']
        cli_options = {opt: getattr(args, opt) for opt in cli_options}
        config_file_options = self._get_config_file_options(args=args)

        kwargs = {}

        if not skip_config:
            # Config parsing is not skipped
            kwargs = merge_dicts(kwargs, config_file_options)

        kwargs = merge_dicts(kwargs, cli_options)
        kwargs['debug'] = debug

        client = Client(**kwargs)

        if skip_config:
            # Config parsing is skipped
            LOG.info('Skipping parsing CLI config')
            return client

        # Ok to use config at this point
        rc_config = get_config()

        # Silence SSL warnings
        silence_ssl_warnings = rc_config.get('general', {}).get('silence_ssl_warnings', False)
        if silence_ssl_warnings:
            requests.packages.urllib3.disable_warnings()

        # We skip automatic authentication for some commands such as auth
        try:
            command_class_name = args.func.im_class.__name__
        except Exception:
            command_class_name = None

        if command_class_name in SKIP_AUTH_CLASSES:
            return client

        # We also skip automatic authentication if token is provided via the environment variable
        # or as a command line argument
        env_var_token = os.environ.get('ST2_AUTH_TOKEN', None)
        cli_argument_token = getattr(args, 'token', None)
        env_var_api_key = os.environ.get('ST2_API_KEY', None)
        cli_argument_api_key = getattr(args, 'api_key', None)
        if env_var_token or cli_argument_token or env_var_api_key or cli_argument_api_key:
            return client

        # If credentials are provided in the CLI config use them and try to authenticate
        credentials = rc_config.get('credentials', {})
        username = credentials.get('username', None)
        password = credentials.get('password', None)
        cache_token = rc_config.get('cli', {}).get('cache_token', False)

        if username and password:
            # Credentials are provided, try to authenticate agaist the API
            try:
                token = self._get_auth_token(client=client, username=username, password=password,
                                             cache_token=cache_token)
            except requests.exceptions.ConnectionError as e:
                LOG.warn('Auth API server is not available, skipping authentication.')
                LOG.exception(e)
                return client
            except Exception as e:
                print('Failed to authenticate with credentials provided in the config.')
                raise e

            client.token = token
            # TODO: Hack, refactor when splitting out the client
            os.environ['ST2_AUTH_TOKEN'] = token

        return client