Beispiel #1
0
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items() if k not in exclude)
     if not env.get('auth_plugin'):
         with mock.patch('ceilometerclient.client.AuthPlugin.'
                         'redirect_to_aodh_endpoint'):
             return client.get_client(api_version, **env)
     else:
         env['auth_plugin'].redirect_to_aodh_endpoint = mock.MagicMock()
         return client.get_client(api_version, **env)
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items()
                if k not in exclude)
     if not env.get('auth_plugin'):
         with mock.patch('ceilometerclient.client.AuthPlugin.'
                         'redirect_to_aodh_endpoint'):
             return client.get_client(api_version, **env)
     else:
         env['auth_plugin'].redirect_to_aodh_endpoint = mock.MagicMock()
         return client.get_client(api_version, **env)
Beispiel #3
0
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items() if k not in exclude)
     if not env.get('auth_plugin'):
         with mock.patch('ceilometerclient.client.AuthPlugin.'
                         'redirect_to_aodh_endpoint') as redirect_aodh:
             redirect_aodh.side_effect = ks_exc.EndpointNotFound
             return client.get_client(api_version, **env)
     else:
         env['auth_plugin'].redirect_to_aodh_endpoint.side_effect = \
             ks_exc.EndpointNotFound
         return client.get_client(api_version, **env)
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items()
                if k not in exclude)
     if not env.get('auth_plugin'):
         with mock.patch('ceilometerclient.client.AuthPlugin.'
                         'redirect_to_aodh_endpoint') as redirect_aodh:
             redirect_aodh.side_effect = ks_exc.EndpointNotFound
             return client.get_client(api_version, **env)
     else:
         env['auth_plugin'].redirect_to_aodh_endpoint.side_effect = \
             ks_exc.EndpointNotFound
         return client.get_client(api_version, **env)
def setup_tasks():
    key_cli = keystoneclient.v2_0.client.Client(**KEY_CREDS)
    endpoint = key_cli.service_catalog.url_for(**CEILO_CREDS)
    cl = client.get_client(2, ceilometer_url=endpoint,
                           os_auth_token=lambda: key_cli.auth_token,
                           timeout=600)
    resources = cl.resources.list()
    resource = random.choice(resources)
    while not resource.project_id or not resource.user_id:
        resource = random.choice(resources)

    TASKS["TASK 1"] = {}
    TASKS["TASK 2"] = dict(period=80)
    TASKS["TASK 3"] = dict(period=5000)
    TASKS["TASK 4"] = dict(period=180, q=[dict(field="project_id",
                                               value=resource.project_id),
                                          dict(field="user_id",
                                               value=resource.user_id)],
                           groupby=["resource_id"],)
    TASKS["TASK 5"] = dict(period=3600*24,
                           q=[dict(field="project_id",
                                   value=resource.project_id),
                              dict(field="user_id",
                                   value=resource.user_id)],
                           groupby=["resource_id"])
    TASKS["TASK 6"] = dict(groupby=["resource_id", "project_id", "user_id"])
Beispiel #6
0
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items()
                if k not in exclude)
     with mock.patch(
             'ceilometerclient.v2.client.Client._get_redirect_client',
             return_value=None):
         return client.get_client(api_version, **env)
Beispiel #7
0
 def get_client(self):
     keystone = dict(os_username=self._user,
                     os_password=self._passw,
                     os_auth_url=self._auth_url,
                     os_tenant_name=self._tenant)
     ceilometer = client.get_client(2, **keystone)
     return ceilometer
def get_meter_client():
    cred=dict(os_username='******',
              os_password=admin_pass,
              os_tenant_name='admin',
              os_auth_url=auth_url)
    n_client = meter_client.get_client('2', **cred)
    return n_client
 def __init__(self, name='', keys='', inbox=None, datapath=None, args=None):
     super(CeilometerDriver, self).__init__(name, keys, inbox, datapath,
                                            args)
     self.creds = self.get_ceilometer_credentials_v2(args)
     self.ceilometer_client = cc.get_client(**self.creds)
     self.raw_state = {}
     self.initialized = True
Beispiel #10
0
def get_latest_network_flow(timestamp):
    ceilometer = ceilometerclient.get_client(
        "2", os_auth_url=OS_ENDPOINT, os_username=OS_USERNAME, os_password=OS_PASSWORD, os_tenant_name=OS_TENANT
    )
    packet = {}
    if not timestamp:
        t = ceilometer.samples.list(meter_name="network.flow.bytes", limit=1)
        # print t
        timestamp = t[0].timestamp
        ts = iso8601.parse_date(timestamp) - datetime.timedelta(0, 5)
        timestamp = isotime(ts)
        # nowoff = datetime.datetime.now() - datetime.timedelta(3, 10)
        # timestamp = nowoff.isoformat()
        # print timestamp
        # timestamp = str(nowoff.year) + "-" + str(nowoff.month) + "-" + str(nowoff.day - 2) + "T" + str(nowoff.hour) + ":" + str(nowoff.minute) + ":" + str(nowoff.second) + "Z"
    # print timestamp
    u = ceilometer.samples.list(
        meter_name="network.flow.bytes", q=[{"field": "timestamp", "op": "ge", "value": timestamp}]
    )
    # u = ceilometer.samples.list(meter_name="network.flow.bytes",  limit=1000)
    for i in u:
        # packet[]
        # print i
        if not i.resource_metadata["instance_id"] in packet:
            packet[i.resource_metadata["instance_id"]] = {}
        packet[i.resource_metadata["instance_id"]][i.timestamp] = json.dumps(i.resource_metadata)
    return json.dumps(packet)
Beispiel #11
0
def get_latest_network_flow(timestamp):
    ceilometer = ceilometerclient.get_client("2",
                                             os_auth_url=OS_ENDPOINT,
                                             os_username=OS_USERNAME,
                                             os_password=OS_PASSWORD,
                                             os_tenant_name=OS_TENANT)
    packet = {}
    if not timestamp:
        t = ceilometer.samples.list(meter_name="network.flow.bytes", limit=1)
        #print t
        timestamp = t[0].timestamp
        ts = iso8601.parse_date(timestamp) - datetime.timedelta(0, 5)
        timestamp = isotime(ts)
        #nowoff = datetime.datetime.now() - datetime.timedelta(3, 10)
        #timestamp = nowoff.isoformat()
        #print timestamp
        #timestamp = str(nowoff.year) + "-" + str(nowoff.month) + "-" + str(nowoff.day - 2) + "T" + str(nowoff.hour) + ":" + str(nowoff.minute) + ":" + str(nowoff.second) + "Z"

#print timestamp
    u = ceilometer.samples.list(meter_name="network.flow.bytes",
                                q=[{
                                    "field": "timestamp",
                                    "op": "ge",
                                    "value": timestamp
                                }])
    #u = ceilometer.samples.list(meter_name="network.flow.bytes",  limit=1000)
    for i in u:
        #packet[]
        #print i
        if not i.resource_metadata["instance_id"] in packet:
            packet[i.resource_metadata["instance_id"]] = {}
        packet[i.resource_metadata["instance_id"]][i.timestamp] = json.dumps(
            i.resource_metadata)
    return json.dumps(packet)
Beispiel #12
0
def get_latest_feature_list():
    nova = novaclient.Client("1.1",
                             username=OS_USERNAME,
                             api_key=OS_PASSWORD,
                             auth_url=OS_ENDPOINT,
                             project_id=OS_TENANT)
    servers = nova.servers.list(detailed=True)
    ceilometer = ceilometerclient.get_client("2",
                                             os_auth_url=OS_ENDPOINT,
                                             os_username=OS_USERNAME,
                                             os_password=OS_PASSWORD,
                                             os_tenant_name=OS_TENANT)
    packet = {}
    meters = ["cpu_util", "disk.write.requests.rate"]
    for i in servers:
        packet[i.id] = {}
        for j in meters:
            packet[i.id][j] = {}
            u = ceilometer.samples.list(meter_name=j,
                                        q=[{
                                            "field": "resource_id",
                                            "value": i.id
                                        }],
                                        limit=1)
            #print u
            if not u:
                #print u
                packet[i.id][j]["value"] = 0
                packet[i.id][j]["timestamp"] = 0
            else:
                packet[i.id][j]["value"] = u[0].counter_volume
                packet[i.id][j]["timestamp"] = u[0].timestamp
    return json.dumps(packet)
Beispiel #13
0
def get_cpu_util_list():
    nova = novaclient.Client("1.1",
                             username=OS_USERNAME,
                             api_key=OS_PASSWORD,
                             auth_url=OS_ENDPOINT,
                             project_id=OS_TENANT)
    servers = nova.servers.list(detailed=True)
    ceilometer = ceilometerclient.get_client("2",
                                             os_auth_url=OS_ENDPOINT,
                                             os_username=OS_USERNAME,
                                             os_password=OS_PASSWORD,
                                             os_tenant_name=OS_TENANT)
    packet = {}
    for i in servers:
        u = ceilometer.samples.list(meter_name="cpu_util",
                                    q=[{
                                        "field": "resource_id",
                                        "value": i.id
                                    }],
                                    limit=1)
        if not u:
            packet[i.id] = 0
        else:
            packet[i.id] = u[0].counter_volume
            #print u[0].timestamp
    #print packet
    return json.dumps(packet)
Beispiel #14
0
 def __init__(self):
     CONF = cfg.CONF
     CONF.import_group('ceilometer_collector','cloudkitty.collector.ceilometer')
     CONF.import_opt('billing_month_start', 'cloudkitty.collector', 'collect')
     CONF.import_opt('backend', 'cloudkitty.tenant_fetcher', 'tenant_fetcher')
     
     # Tenant fetcher
     self.fetcher = driver.DriverManager(
         FETCHERS_NAMESPACE,
         CONF.tenant_fetcher.backend,
         invoke_on_load=True).driver
     
     self.user = cfg.CONF.ceilometer_collector.username
     self.password = cfg.CONF.ceilometer_collector.password
     self.tenant = cfg.CONF.ceilometer_collector.tenant
     self.region = cfg.CONF.ceilometer_collector.region
     self.keystone_url = cfg.CONF.ceilometer_collector.url
     
     self._conn = cclient.get_client('2',
                                     os_username=self.user,
                                     os_password=self.password,
                                     os_auth_url=self.keystone_url,
                                     os_tenant_name=self.tenant,
                                     os_region_name=self.region)
     
     self.t_ceilometer = ceilometer.CeilometerTransformer()
Beispiel #15
0
 def __init__(self, name="", keys="", inbox=None, datapath=None, args=None):
     super(CeilometerDriver, self).__init__(name, keys, inbox, datapath, args)
     datasource_driver.ExecutionDriver.__init__(self)
     session = ds_utils.get_keystone_session(args)
     self.ceilometer_client = cc.get_client(version="2", session=session)
     self.add_executable_client_methods(self.ceilometer_client, "ceilometerclient.v2.")
     self._init_end_start_poll()
Beispiel #16
0
    def _check_ceilometer_sample_api(cls):
        # Check it only once
        if cls.ceilometer_sample_api_is_supported is None:

            auth_config = pecan.request.cfg.service_credentials
            client = ceiloclient.get_client(
                version=2,
                session=keystone_client.get_session(pecan.request.cfg),
                # ceiloclient adapter options
                region_name=auth_config.region_name,
                interface=auth_config.interface,
            )
            try:
                client.statistics.list(
                    meter_name="idontthinkthatexistsbutwhatever")
            except Exception as e:
                if isinstance(e, ceiloexc.HTTPException):
                    if e.code == 410:
                        cls.ceilometer_sample_api_is_supported = False
                    elif e.code < 500:
                        cls.ceilometer_sample_api_is_supported = True
                    else:
                        raise
                else:
                    raise
            else:
                # I don't think this meter can exists but how known
                cls.ceilometer_sample_api_is_supported = True

        if cls.ceilometer_sample_api_is_supported is False:
            raise base.ClientSideError(
                "This telemetry installation is not configured to support"
                "alarm of type 'threshold")
 def __init__(self, name='', keys='', inbox=None, datapath=None, args=None):
     super(CeilometerDriver, self).__init__(name, keys, inbox,
                                            datapath, args)
     self.creds = self.get_ceilometer_credentials_v2(args)
     self.ceilometer_client = cc.get_client(**self.creds)
     self.raw_state = {}
     self.initialized = True
Beispiel #18
0
 def __init__(self):
     self.ceil_client = client.get_client(
         "2",
         os_username=api_settings.OS_AUTH.get("username"),
         os_password=api_settings.OS_AUTH.get("password"),
         os_tenant_name=api_settings.OS_AUTH.get("project_name"),
         os_auth_url=api_settings.OS_AUTH.get("auth_url"))
Beispiel #19
0
    def _create(self):

        con = self.context
        endpoint_type = self._get_client_option(CLIENT_NAME, 'endpoint_type')
        endpoint = self.url_for(service_type=self.METERING,
                                endpoint_type=endpoint_type)
        aodh_endpoint = self.url_for(service_type=self.ALARMING,
                                     endpoint_type=endpoint_type)
        args = {
            'auth_url': con.auth_url,
            'service_type': self.METERING,
            'project_name': con.tenant,
            'token': lambda: self.auth_token,
            'user_domain_id': con.user_domain,
            'project_domain_id': con.project_domain,
            'endpoint_type': endpoint_type,
            'os_endpoint': endpoint,
            'cacert': self._get_client_option(CLIENT_NAME, 'ca_file'),
            'cert_file': self._get_client_option(CLIENT_NAME, 'cert_file'),
            'key_file': self._get_client_option(CLIENT_NAME, 'key_file'),
            'insecure': self._get_client_option(CLIENT_NAME, 'insecure'),
            'aodh_endpoint': aodh_endpoint,
            'timeout': self._get_client_option(CLIENT_NAME, 'timeout')
        }

        return cc.get_client('2', **args)
Beispiel #20
0
    def get_meter(self, meter, obj, pk, keystone=None):
        if (not keystone):
                keystone={}
                keystone['os_username']=env['OS_USERNAME']
                keystone['os_password']=env['OS_PASSWORD']
                keystone['os_auth_url']=env['OS_AUTH_URL']
                keystone['os_tenant_name']=env['OS_TENANT_NAME']
                keystone['os_cacert']=env['OS_CACERT']
                keystone['os_region_name']=env['OS_REGION_NAME']

                keystone['username']=env['OS_USERNAME']
                keystone['password']=env['OS_PASSWORD']
                keystone['auth_url']=env['OS_AUTH_URL']
                keystone['tenant_name']=env['OS_TENANT_NAME']
                keystone['cacert']=env['OS_CACERT']
                keystone['region_name']=env['OS_REGION_NAME']

        keystone['auth_plugin']=client.AuthPlugin(**keystone)

        ceilometer = client.get_client(2,**keystone)
        
        cur_ts = datetime.datetime.fromtimestamp(time.time()-86400)
        str_ts = cur_ts.strftime('%Y-%m-%dT%H:%M:%S')

        object_filter = object_to_filter(obj, pk)
        filter=';'.join([object_filter,'timestamp>%s'%str_ts])
        #query = cli_to_array("project_id=124de34266b24f57957345cdb43cc9ff;timestamp>2014-12-11T00:00:00")
        query = cli_to_array(filter)

        meters = ceilometer.statistics.list(meter,q=query,period=3600)

        stats = meters_to_stats(meters)
        return stats
Beispiel #21
0
    def _check_ceilometer_sample_api(cls):
        # Check it only once
        if cls.ceilometer_sample_api_is_supported is None:

            auth_config = pecan.request.cfg.service_credentials
            client = ceiloclient.get_client(
                version=2,
                session=keystone_client.get_session(pecan.request.cfg),
                # ceiloclient adapter options
                region_name=auth_config.region_name,
                interface=auth_config.interface,
            )
            try:
                client.statistics.list(
                    meter_name="idontthinkthatexistsbutwhatever")
            except Exception as e:
                if isinstance(e, ceiloexc.HTTPException):
                    if e.code == 410:
                        cls.ceilometer_sample_api_is_supported = False
                    elif e.code < 500:
                        cls.ceilometer_sample_api_is_supported = True
                    else:
                        raise
                else:
                    raise
            else:
                # I don't think this meter can exist but how known
                cls.ceilometer_sample_api_is_supported = True

        if cls.ceilometer_sample_api_is_supported is False:
            raise base.ClientSideError(
                "This telemetry installation is not configured to support"
                "alarm of type 'threshold")
Beispiel #22
0
 def client_ceilometer(self):
     if not self.__client_ceilometer:
         self.__client_ceilometer = cclient.get_client(version=2,
                                                       timeout=self.ceilometer_timeout,
                                                       connect_retries=self.connect_retries,
                                                       **self.__auth)
     return self.__client_ceilometer
Beispiel #23
0
 def _connect(self):
     """Initialize connection to the Ceilometer endpoint."""
     self._conn = cclient.get_client('2', os_username=self.user,
                                     os_password=self.password,
                                     os_auth_url=self.keystone_url,
                                     os_tenant_name=self.tenant,
                                     os_region_name=self.region)
 def __init__(self, args):
     version = '2'
     self.ceilo_connect = client.get_client(version,
                                            os_username=args.username,
                                            os_password=args.password,
                                            os_tenant_name=args.tenant_name,
                                            os_auth_url=args.auth_url)
 def __init__(self, args):
     version = '2'
     self.ceilo_connect = client.get_client(version,
                                            os_username=args.username,
                                            os_password=args.password,
                                            os_tenant_name=args.tenant_name,
                                            os_auth_url=args.auth_url)
Beispiel #26
0
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items()
                if k not in exclude)
     with mock.patch('ceilometerclient.openstack.common.apiclient.client.'
                     'HTTPClient.client_request',
                     return_value=mock.MagicMock()):
         return client.get_client(api_version, **env)
 def create_client(env, api_version=2, endpoint=None, exclude=[]):
     env = dict((k, v) for k, v in env.items()
                if k not in exclude)
     with mock.patch('ceilometerclient.openstack.common.apiclient.client.'
                     'HTTPClient.client_request',
                     return_value=mock.MagicMock()):
         return client.get_client(api_version, **env)
Beispiel #28
0
    def _create(self):

        con = self.context
        endpoint_type = self._get_client_option(CLIENT_NAME, 'endpoint_type')
        endpoint = self.url_for(service_type=self.METERING,
                                endpoint_type=endpoint_type)
        aodh_endpoint = self.url_for(service_type=self.ALARMING,
                                     endpoint_type=endpoint_type)
        args = {
            'auth_url': con.auth_url,
            'service_type': self.METERING,
            'project_name': con.project_name,
            'token': lambda: self.auth_token,
            'user_domain_id': con.user_domain,
            'project_domain_id': con.project_domain,
            'endpoint_type': endpoint_type,
            'os_endpoint': endpoint,
            'cacert': self._get_client_option(CLIENT_NAME, 'ca_file'),
            'cert_file': self._get_client_option(CLIENT_NAME, 'cert_file'),
            'key_file': self._get_client_option(CLIENT_NAME, 'key_file'),
            'insecure': self._get_client_option(CLIENT_NAME, 'insecure'),
            'aodh_endpoint': aodh_endpoint
        }

        return cc.get_client('2', **args)
Beispiel #29
0
 def __init__(self):
     self._q_client = q_client.Client(**credentials.get_q_creds())
     self._n_client = n_client.Client(**credentials.get_n_creds())
     self._c_client = c_client.get_client('2', **credentials.get_c_creds())
     self._context = {'q_client' : self._q_client,
                      'n_client' : self._n_client,
                      'c_client' : self._c_client,}
    def main(self, argv):
        parsed = self.parse_args(argv)
        if parsed == 0:
            return 0
        api_version, args = parsed

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not ((self.auth_plugin.opts.get('token')
                 or self.auth_plugin.opts.get('auth_token'))
                and self.auth_plugin.opts['endpoint']):
            if not self.auth_plugin.opts['username']:
                raise exc.CommandError("You must provide a username via "
                                       "either --os-username or via "
                                       "env[OS_USERNAME]")

            if not self.auth_plugin.opts['password']:
                raise exc.CommandError("You must provide a password via "
                                       "either --os-password or via "
                                       "env[OS_PASSWORD]")

            if self.no_project_and_domain_set(args):
                # steer users towards Keystone V3 API
                raise exc.CommandError("You must provide a project_id via "
                                       "either --os-project-id or via "
                                       "env[OS_PROJECT_ID] and "
                                       "a domain_name via either "
                                       "--os-user-domain-name or via "
                                       "env[OS_USER_DOMAIN_NAME] or "
                                       "a domain_id via either "
                                       "--os-user-domain-id or via "
                                       "env[OS_USER_DOMAIN_ID]")

            if not (self.auth_plugin.opts['tenant_id']
                    or self.auth_plugin.opts['tenant_name']):
                raise exc.CommandError("You must provide a tenant_id via "
                                       "either --os-tenant-id or via "
                                       "env[OS_TENANT_ID]")

            if not self.auth_plugin.opts['auth_url']:
                raise exc.CommandError("You must provide an auth url via "
                                       "either --os-auth-url or via "
                                       "env[OS_AUTH_URL]")

        client_kwargs = vars(args)
        client_kwargs.update(self.auth_plugin.opts)
        client_kwargs['auth_plugin'] = self.auth_plugin
        client = ceiloclient.get_client(api_version, **client_kwargs)
        # call whatever callback was selected
        try:
            args.func(client, args)
        except exc.HTTPUnauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
    def main(self, argv):
        parsed = self.parse_args(argv)
        if parsed == 0:
            return 0
        api_version, args = parsed

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not ((self.auth_plugin.opts.get('token')
                 or self.auth_plugin.opts.get('auth_token'))
                and self.auth_plugin.opts['endpoint']):
            if not self.auth_plugin.opts['username']:
                raise exc.CommandError("You must provide a username via "
                                       "either --os-username or via "
                                       "env[OS_USERNAME]")

            if not self.auth_plugin.opts['password']:
                raise exc.CommandError("You must provide a password via "
                                       "either --os-password or via "
                                       "env[OS_PASSWORD]")

            if self.no_project_and_domain_set(args):
                # steer users towards Keystone V3 API
                raise exc.CommandError("You must provide a project_id via "
                                       "either --os-project-id or via "
                                       "env[OS_PROJECT_ID] and "
                                       "a domain_name via either "
                                       "--os-user-domain-name or via "
                                       "env[OS_USER_DOMAIN_NAME] or "
                                       "a domain_id via either "
                                       "--os-user-domain-id or via "
                                       "env[OS_USER_DOMAIN_ID]")

            if not (self.auth_plugin.opts['tenant_id']
                    or self.auth_plugin.opts['tenant_name']):
                raise exc.CommandError("You must provide a tenant_id via "
                                       "either --os-tenant-id or via "
                                       "env[OS_TENANT_ID]")

            if not self.auth_plugin.opts['auth_url']:
                raise exc.CommandError("You must provide an auth url via "
                                       "either --os-auth-url or via "
                                       "env[OS_AUTH_URL]")

        client_kwargs = vars(args)
        client_kwargs.update(self.auth_plugin.opts)
        client_kwargs['auth_plugin'] = self.auth_plugin
        client = ceiloclient.get_client(api_version, **client_kwargs)
        # call whatever callback was selected
        try:
            args.func(client, args)
        except exc.HTTPUnauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
 def test_ceilometerclient_available_without_aodh_services_running(self):
     env = FAKE_ENV.copy()
     env.pop('auth_plugin', None)
     with mock.patch('ceilometerclient.openstack.common.apiclient.client.'
                     'HTTPClient.client_request') as mocked_request:
         mocked_request.side_effect = requests.exceptions.ConnectionError
         ceiloclient = client.get_client(2, **env)
         self.assertIsInstance(ceiloclient, v2client.Client)
Beispiel #33
0
 def __new__(cls, *args, **kwargs):
     if not cls._cm_client:
         cls._cm_client = object.__new__(cls)
         try:
             cls._cm_client = client.get_client(settings.CEILOMETER_API_VERSION, **settings.CEILOMETER_AUTH_DATA)
         except ks_exceptions.AuthorizationFailure:
             raise Exception("failed to connect/authenticate to ceilometer")
     return cls._cm_client
Beispiel #34
0
def get_ceilometer_client():
    sess = _get_keystone_session()

    return ceilometerclient.get_client(
        '2',
        session=sess,
        region_name=CONF.keystone_authtoken.region_name
    )
    def getCeilometerClient(self):

        cclient = cl.get_client( '2',
							username=env['OS_USERNAME'],
							password=env['OS_PASSWORD'],
							tenant_name=env['OS_TENANT_NAME'],
							auth_url=env['OS_AUTH_URL'])
        return cclient
def get_credentials():
    keystone = {}
    keystone['os_username']=env['OS_USERNAME']
    keystone['os_password']=env['OS_PASSWORD']
    keystone['os_auth_url']=env['OS_AUTH_URL']
    keystone['os_tenant_name']=env['OS_TENANT_NAME']

    return client.get_client(2, **keystone)
Beispiel #37
0
 def test_ceilometerclient_available_without_aodh_services_running(self):
     env = FAKE_ENV.copy()
     env.pop('auth_plugin', None)
     with mock.patch('ceilometerclient.openstack.common.apiclient.client.'
                     'HTTPClient.client_request') as mocked_request:
         mocked_request.side_effect = requests.exceptions.ConnectionError
         ceiloclient = client.get_client(2, **env)
         self.assertIsInstance(ceiloclient, v2client.Client)
Beispiel #38
0
 def get_ceilometer_client(self):
     return ceiloclient.get_client(
         Ceiloplot.API_VERSION,
         os_username=self.args.os_username,
         os_password=self.args.os_password,
         os_auth_url=self.args.os_auth_url,
         os_tenant_id=self.args.os_tenant_id
     )
Beispiel #39
0
 def _connect(self):
     """Initialize connection to the Ceilometer endpoint."""
     self._conn = cclient.get_client('2',
                                     os_username=self.user,
                                     os_password=self.password,
                                     os_auth_url=self.keystone_url,
                                     os_tenant_name=self.tenant,
                                     os_region_name=self.region)
 def client_ceilometer(self):
     if not self.__client_ceilometer:
         self.__client_ceilometer = cclient.get_client(
             version=2,
             timeout=self.ceilometer_timeout,
             connect_retries=self.connect_retries,
             **self.__auth)
     return self.__client_ceilometer
 def test_client_v2_with_session(self):
     resp = mock.Mock(status_code=200, text=b'')
     resp.json.return_value = []
     session = mock.Mock()
     session.request.return_value = resp
     c = client.get_client(2, session=session)
     c.resources.list()
     self.assertTrue(session.request.called)
     self.assertTrue(resp.json.called)
 def __init__(self, name='', args=None):
     super(CeilometerDriver, self).__init__(name, args=args)
     datasource_driver.ExecutionDriver.__init__(self)
     session = ds_utils.get_keystone_session(args)
     self.ceilometer_client = cc.get_client(version='2', session=session)
     self.add_executable_client_methods(self.ceilometer_client,
                                        'ceilometerclient.v2.')
     self.initialize_update_method()
     self._init_end_start_poll()
Beispiel #43
0
    def ceilometer(self):
        if self._ceilometer:
            return self._ceilometer

        ceilometerclient_version = self._get_client_option(
            'ceilometer', 'api_version')
        self._ceilometer = ceclient.get_client(ceilometerclient_version,
                                               session=self.session)
        return self._ceilometer
def get_ceilometer_api_client(args):
    
    s = CeilometerShell()
    ret_value = s.parse_args(args)
    if isinstance(ret_value, tuple):
        api_version, parsed_args = s.parse_args(args)

        return parsed_args, ceiloclient.get_client(api_version, **(parsed_args.__dict__))
    return None, None
def main():
    try:
        os.makedirs(OUTDIR)
    except:
        pass
    kargs = build_keystone_args()
    LOG.debug("keystone args: %s" % (str(kargs)))
    
    cclient = client.get_client(2,**kargs)
    
    if USE_PRELOAD_RESOURCES:
        preload_resources(cclient)
        pass
    
    iteration = 0
    outfile = "%s/%s" % (OUTDIR,OUTBASENAME)
    tmpoutfile = outfile + ".NEW"
    while True:
        iteration += 1
        try:
            reload_hostnames()
            newdatadict = fetchall(cclient)
            f = file(tmpoutfile,'w')
            #,cls=FlatteningJSONEncoder)
            f.write(json.dumps(newdatadict,sort_keys=True,indent=None) + '\n')
            f.close()
            shutil.move(tmpoutfile,outfile)
        except:
            LOG.exception("failure during iteration %d; nothing new generated"
                          % (iteration,))
            pass
        
        LOG.debug("Sleeping for 5 minutes...")
        time.sleep(5 * MINUTE)
        pass

    #meters = client.meters.list(limit=LIMIT)
    #pp.pprint("Meters: ")
    #pp.pprint(meters)
    
    # Ceilometer meter.list command only allows filtering on
    # ['project', 'resource', 'source', 'user'].
    # q=[{'field':'meter.name','value':'cpu_util','op':'eq','type':'string'}]
    #cpu_util_meters = []
    #for m in meters:
    #    if m.name == 'cpu_util':
    #        cpu_util_meters.append(m)
    #    pass
    #pp.pprint("cpu_util Meters:")
    #pp.pprint(cpu_util_meters)
    
    #for m in cpu_util_meters:
    #    pp.pprint("Resource %s for cpu_util meter %s:" % (m.resource_id,m.meter_id))
    #    pp.pprint(resources[m.resource_id])
    #    pass
    
    return -1
Beispiel #46
0
 def _client():
     auth_config = cfg.CONF.service_credentials
     creds = dict(
         os_auth_url=auth_config.os_auth_url,
         os_tenant_name=auth_config.os_tenant_name,
         os_password=auth_config.os_password,
         os_username=auth_config.os_username
     )
     return ceiloclient.get_client(2, **creds)
Beispiel #47
0
    def create_client(self, version=None, service_type=None):
        """Return ceilometer client."""
        from ceilometerclient import client as ceilometer

        client = ceilometer.get_client(
            self.choose_version(version),
            session=self.keystone.get_session()[0],
            endpoint_override=self._get_endpoint(service_type))
        return client
Beispiel #48
0
    def ceilometer(self):
        if self._ceilometer:
            return self._ceilometer

        ceilometerclient_version = self._get_client_option('ceilometer',
                                                           'api_version')
        self._ceilometer = ceclient.get_client(ceilometerclient_version,
                                               session=self.session)
        return self._ceilometer
Beispiel #49
0
    def create_client(self, version=None, service_type=None):
        """Return ceilometer client."""
        from ceilometerclient import client as ceilometer

        client = ceilometer.get_client(
            self.choose_version(version),
            session=self.keystone.get_session()[0],
            endpoint_override=self._get_endpoint(service_type))
        return client
 def __init__(self, name='', keys='', inbox=None, datapath=None, args=None):
     super(CeilometerDriver, self).__init__(name, keys, inbox,
                                            datapath, args)
     datasource_driver.ExecutionDriver.__init__(self)
     self.creds = self.get_ceilometer_credentials_v2(args)
     self.ceilometer_client = cc.get_client(**self.creds)
     self.add_executable_client_methods(self.ceilometer_client,
                                        'ceilometerclient.v2.')
     self._init_end_start_poll()
    def _admin_credentials(self):
        """

        :rtype : ceilometer_client
        :type self: User
        """
        keystone = dict(os_username=self._user, os_password=self._passw, os_auth_url=self._auth_url,
                        os_tenant_name=self._tenant)
        return clients.get_client(2, **keystone)
Beispiel #52
0
 def __init__(self, name='', args=None):
     super(CeilometerDriver, self).__init__(name, args=args)
     datasource_driver.ExecutionDriver.__init__(self)
     session = ds_utils.get_keystone_session(args)
     self.ceilometer_client = cc.get_client(version='2', session=session)
     self.add_executable_client_methods(self.ceilometer_client,
                                        'ceilometerclient.v2.')
     self.initialize_update_method()
     self._init_end_start_poll()
Beispiel #53
0
 def test_client_v2_with_session(self):
     resp = mock.Mock(status_code=200, text=b'')
     resp.json.return_value = []
     session = mock.Mock()
     session.request.return_value = resp
     c = client.get_client(2, session=session)
     c.resources.list()
     self.assertTrue(session.request.called)
     self.assertTrue(resp.json.called)
Beispiel #54
0
 def __new__(cls, *args, **kwargs):
     if not cls._cm_client:
         cls._cm_client = object.__new__(cls)
         try:
             cls._cm_client = client.get_client(
                 settings.CEILOMETER_API_VERSION,
                 **settings.CEILOMETER_AUTH_DATA)
         except ks_exceptions.AuthorizationFailure:
             raise Exception('failed to connect/authenticate to ceilometer')
     return cls._cm_client
Beispiel #55
0
    def get_ceilometer(self, version='2'):
        """Get a ceilometer client instance.

        :param version: String api version
        :return: ceilometerclient.client
        """
        if self.ceilometer is None:
            self.ceilometer = ceilometerclient.get_client(
                version, **self.auth_kwargs)
        return self.ceilometer
def get_ceilometer_api_client(args):

    s = CeilometerShell()
    ret_value = s.parse_args(args)
    if isinstance(ret_value, tuple):
        api_version, parsed_args = s.parse_args(args)

        return parsed_args, ceiloclient.get_client(api_version,
                                                   **(parsed_args.__dict__))
    return None, None
Beispiel #57
0
 def setup(self, api_version=2):
     from ceilometerclient import client
     (options, args) = self.ceilometer.parser.parse_known_args(
         self.base_argv)
     if options.help:
         options.command = None
         self.do_help(options)
         sys.exit(2)
     client_kwargs = vars(options)
     return options, client.get_client(api_version, **client_kwargs)
Beispiel #58
0
    def _admin_credentials(self):
        """

        :rtype : ceilometer_client
        :type self: User
        """
        keystone = dict(os_username=self._user,
                        os_password=self._passw,
                        os_auth_url=self._auth_url,
                        os_tenant_name=self._tenant)
        return clients.get_client(2, **keystone)
 def __init__(self, name='', keys='', inbox=None, datapath=None, args=None):
     super(CeilometerDriver, self).__init__(name, keys, inbox, datapath,
                                            args)
     self.creds = self.get_ceilometer_credentials_v2(name, args)
     self.ceilometer_client = cc.get_client(**self.creds)
     self.raw_state = {}
     self.register_translator(CeilometerDriver.meters_translator)
     self.register_translator(CeilometerDriver.alarms_translator)
     self.register_translator(CeilometerDriver.events_translator)
     self.register_translator(CeilometerDriver.statistics_translator)
     self.initialized = True