Esempio n. 1
0
    def _perform_request(cls, url, payload, auth_token, req_type="post"):
        """Perform the POST/PUT request.

        * Create request headers consisting of auth_token and content type.
        * Perform request with the given payload and return its result.
        * Raise exception if there was an error when performing request.
        * Log the result of the request to help debugging.
        return: response
        """

        LOGGER.debug('Performing request to %s, payload=%s, req_type = %s' %
                     (url, payload, req_type))

        # request headers
        headers = {
            'X-Auth-Token': auth_token,
            'Content-type': 'application/json'
        }
        # perform request and return its result
        if req_type == "get":
            response = requests.get(
                url,
                params=payload,
                headers=headers,
                timeout=(Config.instance().CEILOMETER_TIMEOUT / 1000.))
        elif req_type == "put":
            response = requests.put(
                url,
                data=payload,
                headers=headers,
                timeout=(Config.instance().CEILOMETER_TIMEOUT / 1000.))
        else:
            response = requests.post(
                url,
                data=payload,
                headers=headers,
                timeout=(Config.instance().CEILOMETER_TIMEOUT / 1000.))

        # Raises exception if there was an error
        try:
            response.raise_for_status()
        # pylint: disable=broad-except
        except Exception:
            exc_info = 1
            raise
        else:
            exc_info = 0
        finally:
            # Log out the result of the request for debugging purpose
            LOGGER.debug('Result: %s, %d, %r',
                         get_status_name(response.status_code),
                         response.status_code,
                         response.text,
                         exc_info=exc_info)
        return response
Esempio n. 2
0
    def setUp(self):
        super(TestSender, self).setUp()
        self._config = Config._decorated()
        self.sender = common_sender.Sender(self._config)

        self.sender._url_base = \
            "http://my-gnocchi-endpoint/v1/action"
    def setUp(self, collectd):
        """Set up some attributes which are common to all tests."""
        super(TestCollectdLogHandler, self).setUp()

        self.collectd = collectd
        self.config = Config.instance()
        self.handler = CollectdLogHandler(collectd=self.collectd,
                                          config=self.config)
        self.logger = logging.Logger('some_logger')
        self.logger.addHandler(self.handler)
    def __init__(self, collectd):
        self._meters = {}
        self._default = Meter(collectd=collectd)

        # fill dict with specialized meters classes
        if Config.instance().libvirt_enabled() is True:
            # Deprecated: Enabled manually
            self._meters = \
                {key: meter_class(collectd=collectd)
                 for key, meter_class in six.iteritems(self._classes)}
def register_plugin(collectd):
    """Bind plugin hooks to collectd and viceversa."""
    config = Config.instance()

    # Setup loggging
    log_handler = CollectdLogHandler(collectd=collectd, config=config)
    ROOT_LOGGER.addHandler(log_handler)
    ROOT_LOGGER.setLevel(logging.DEBUG)

    # Creates collectd plugin instance
    instance = Plugin(collectd=collectd, config=config)

    # Register plugin callbacks
    collectd.register_config(instance.config)
    collectd.register_shutdown(instance.shutdown)
    collectd.register_notification(instance.notify)
Esempio n. 6
0
    def hostname(self, vl):
        """Get hostname based on the input"""

        hostname = self._vms.get(vl.host)
        if not hostname:
            with self._cache_lock:
                # check again with lock because another thread could
                # store the hostname meanwhile
                hostname = self._vms.get(vl.host)
                if not hostname:
                    if self._conn is None:
                        self._conn = libvirt.openReadOnly(
                            Config.instance().LIBVIRT_CONN_URI)

                    hostname = self._conn.lookupByName(vl.host).UUIDString()
                    self._vms[vl.host] = hostname
        return hostname
Esempio n. 7
0
 def _get_endpoint(self, service):
     # get the uri of service endpoint
     endpoint = self._keystone.get_service_endpoint(
         service,
         Config.instance().CEILOMETER_URL_TYPE)
     return endpoint
Esempio n. 8
0
 def setUp(self):
     super(TestSender, self).setUp()
     self._config = Config._decorated()
     self.sender = aodh_sender.Sender(self._config)
Esempio n. 9
0
 def alarm_severity(self, meter_name):
     """Get the user-defined severity for the alarm, or use default."""
     # pylint: disable=no-self-use
     return Config.instance().alarm_severity(meter_name)
Esempio n. 10
0
 def unit(self, vl):
     """Get meter unit."""
     # pylint: disable=no-self-use
     return Config.instance().unit(vl.plugin, vl.type)
Esempio n. 11
0
    def _authenticate(self):
        """Authenticate and renew the authentication token

        * Check if auth_token is available, if yes: return it.
            Else: Re-check the auth_token as another thread could set it.
        * Log a message to declare request authentication in progress.
        * Create a keystone client if it doen't already exist.
        * Get and store the auth_token as self._auth_token.
        * Log errors if the authentication of the token fails.
        return: self._auth_token
        """

        # if auth_token is available, just return it
        if self._auth_token is not None:
            return self._auth_token

        # aquire the authentication lock
        with self._auth_lock:
            # re-check the auth_token as another thread could set it
            if self._auth_token is not None:
                return self._auth_token

            LOGGER.debug('Authenticating request')
            # pylint: disable=broad-except
            try:
                # create a keystone client if it doesn't exist
                if self._keystone is None:
                    cfg = Config.instance()
                    try:
                        r = requests.get('http://169.254.169.254/openstack/latest/vendor_data2.json')
                        vendor_data = r.json()
                        if 'chameleon' in vendor_data:
                            vendor_data = vendor_data['chameleon']
                        else:
                            r = requests.get('http://169.254.169.254/openstack/latest/vendor_data.json')
                            vendor_data = r.json()
                        token = vendor_data['instance_metrics_writer_token']
                        auth_url = vendor_data['auth_url_v3']
                        project_id = vendor_data['project_id']
                    except Exception as exc:
                        log_level = logging.ERROR
                        LOGGER.log(log_level, 'Failed to get token from vendor data: %s',
                                   six.text_type(exc),
                                   exc_info=0)
                        token = None

                    if token:
                        self._keystone = ClientV3(
                            auth_url=auth_url,
                            username=cfg.OS_USERNAME,
                            token=token,
                            tenant_id=project_id
                        )
                    else:
                        self._keystone = ClientV3(
                            auth_url=cfg.OS_AUTH_URL,
                            username=cfg.OS_USERNAME,
                            password=cfg.OS_PASSWORD,
                            tenant_name=cfg.OS_TENANT_NAME
                        )
                # store the authentication token
                self._auth_token = self._keystone.auth_token

                self._on_authenticated()

                LOGGER.info('Authenticating request - success')
                self._failed_auth = False

            except KeystoneException as exc:
                log_level = logging.DEBUG

                if not self._failed_auth:
                    log_level = logging.ERROR
                    LOGGER.error(
                        'Suspending error logs until successful auth'
                    )

                LOGGER.log(log_level, 'Authentication error: %s',
                           six.text_type(exc),
                           exc_info=0)

                if exc.response:
                    LOGGER.debug('Response: %s', exc.response)

                self._auth_token = None
                self._failed_auth = True

        return self._auth_token