Python oslo_utils.encodeutils.to_utf8() Examples

The following are 19 code examples of oslo_utils.encodeutils.to_utf8(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_utils.encodeutils , or try the search function .
Example #1
Source File: alarm_definitions_repository.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def _insert_into_alarm_action(self, conn, alarm_definition_id, actions,
                                  alarm_state):

        if actions is None:
            return

        for action in actions:
            b_id = action.encode('utf8') if six.PY2 else action
            row = conn.execute(self.select_nm_query,
                               b_id=b_id).fetchone()
            if row is None:
                raise exceptions.InvalidUpdateException(
                    "Non-existent notification id {} submitted for {} "
                    "notification action".format(encodeutils.to_utf8(action),
                                                 encodeutils.to_utf8(alarm_state)))
            conn.execute(self.insert_aa_query,
                         b_alarm_definition_id=alarm_definition_id,
                         b_alarm_state=alarm_state.encode('utf8') if six.PY2 else alarm_state,
                         b_action_id=action.encode('utf8') if six.PY2 else action
                         ) 
Example #2
Source File: utils.py    From os-brick with Apache License 2.0 6 votes vote down vote up
def convert_str(text):
    """Convert to native string.

    Convert bytes and Unicode strings to native strings:

    * convert to bytes on Python 2:
      encode Unicode using encodeutils.safe_encode()
    * convert to Unicode on Python 3: decode bytes from UTF-8
    """
    if six.PY2:
        return encodeutils.to_utf8(text)
    else:
        if isinstance(text, bytes):
            return text.decode('utf-8')
        else:
            return text 
Example #3
Source File: test_driver.py    From neutron-dynamic-routing with Apache License 2.0 6 votes vote down vote up
def test_add_bgp_peer_with_unicode_password(self):
        self.os_ken_bgp_driver.add_bgp_speaker(FAKE_LOCAL_AS1)
        self.assertEqual(1,
                self.os_ken_bgp_driver.cache.get_hosted_bgp_speakers_count())
        NEW_FAKE_PEER_PASSWORD = str(FAKE_PEER_PASSWORD)
        self.os_ken_bgp_driver.add_bgp_peer(
            FAKE_LOCAL_AS1,
            FAKE_PEER_IP,
            FAKE_PEER_AS,
            FAKE_AUTH_TYPE,
            NEW_FAKE_PEER_PASSWORD)
        speaker = self.os_ken_bgp_driver.cache.get_bgp_speaker(FAKE_LOCAL_AS1)
        speaker.neighbor_add.assert_called_once_with(
            address=FAKE_PEER_IP,
            remote_as=FAKE_PEER_AS,
            enable_ipv4=True,
            enable_ipv6=True,
            password=encodeutils.to_utf8(NEW_FAKE_PEER_PASSWORD),
            connect_mode=CONNECT_MODE_ACTIVE) 
Example #4
Source File: driver.py    From neutron-dynamic-routing with Apache License 2.0 6 votes vote down vote up
def add_bgp_peer(self, speaker_as, peer_ip, peer_as,
                     auth_type='none', password=None):
        curr_speaker = self.cache.get_bgp_speaker(speaker_as)
        if not curr_speaker:
            raise bgp_driver_exc.BgpSpeakerNotAdded(local_as=speaker_as,
                                                    rtid=self.routerid)

        # Validate peer_ip and peer_as.
        utils.validate_as_num('remote_as', peer_as)
        utils.validate_ip_addr(peer_ip)
        utils.validate_auth(auth_type, password)
        if password is not None:
            password = encodeutils.to_utf8(password)

        curr_speaker.neighbor_add(address=peer_ip,
                                  remote_as=peer_as,
                                  enable_ipv4=True,
                                  enable_ipv6=True,
                                  password=password,
                                  connect_mode=CONNECT_MODE_ACTIVE)
        LOG.info(_LI('Added BGP Peer %(peer)s for remote_as=%(as)d to '
                     'BGP Speaker running for local_as=%(local_as)d.'),
                 {'peer': peer_ip, 'as': peer_as, 'local_as': speaker_as}) 
Example #5
Source File: test_driver.py    From neutron-dynamic-routing with Apache License 2.0 6 votes vote down vote up
def test_add_bgp_peer_with_password(self):
        self.os_ken_bgp_driver.add_bgp_speaker(FAKE_LOCAL_AS1)
        self.assertEqual(1,
                self.os_ken_bgp_driver.cache.get_hosted_bgp_speakers_count())
        self.os_ken_bgp_driver.add_bgp_peer(FAKE_LOCAL_AS1,
                                         FAKE_PEER_IP,
                                         FAKE_PEER_AS,
                                         FAKE_AUTH_TYPE,
                                         FAKE_PEER_PASSWORD)
        speaker = self.os_ken_bgp_driver.cache.get_bgp_speaker(FAKE_LOCAL_AS1)
        speaker.neighbor_add.assert_called_once_with(
            address=FAKE_PEER_IP,
            remote_as=FAKE_PEER_AS,
            enable_ipv4=True,
            enable_ipv6=True,
            password=encodeutils.to_utf8(FAKE_PEER_PASSWORD),
            connect_mode=CONNECT_MODE_ACTIVE) 
Example #6
Source File: utils.py    From neutron-lib with Apache License 2.0 5 votes vote down vote up
def get_interface_name(name, prefix='', max_len=constants.DEVICE_NAME_MAX_LEN):
    """Construct an interface name based on the prefix and name.

    The interface name can not exceed the maximum length passed in. Longer
    names are hashed to help ensure uniqueness.
    """
    requested_name = prefix + name

    if len(requested_name) <= max_len:
        return requested_name

    # We can't just truncate because interfaces may be distinguished
    # by an ident at the end. A hash over the name should be unique.
    # Leave part of the interface name on for easier identification
    if (len(prefix) + INTERFACE_HASH_LEN) > max_len:
        raise ValueError(_("Too long prefix provided. New name would exceed "
                           "given length for an interface name."))

    namelen = max_len - len(prefix) - INTERFACE_HASH_LEN
    hashed_name = hashlib.sha1(encodeutils.to_utf8(name))
    new_name = ('%(prefix)s%(truncated)s%(hash)s' %
                {'prefix': prefix, 'truncated': name[0:namelen],
                 'hash': hashed_name.hexdigest()[0:INTERFACE_HASH_LEN]})
    LOG.info("The requested interface name %(requested_name)s exceeds the "
             "%(limit)d character limitation. It was shortened to "
             "%(new_name)s to fit.",
             {'requested_name': requested_name,
              'limit': max_len, 'new_name': new_name})
    return new_name 
Example #7
Source File: utils.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def generate_identifier(result):
    """
    Returns a fixed length identifier based on a hash of a combined set of
    playbook/task values which are as close as we can guess to unique for each
    task.
    """
    # Determine the playbook file path to use for the ID
    if result.task.playbook and result.task.playbook.path:
        playbook_file = result.task.playbook.path
    else:
        playbook_file = ''
    play_path = u'%s.%s' % (playbook_file, result.task.play.name)

    # Determine the task file path to use for the ID
    if result.task.file and result.task.file.path:
        task_file = result.task.file.path
    else:
        task_file = ''
    task_path = u'%s.%s' % (task_file, result.task.name)

    # Combine both of the above for a full path
    identifier_path = u'%s.%s' % (play_path, task_path)

    # Assign the identifier as a hash of the fully unique path.
    identifier = hashlib.sha1(encodeutils.to_utf8(identifier_path)).hexdigest()

    return identifier 
Example #8
Source File: tests_encodeutils.py    From oslo.utils with Apache License 2.0 5 votes vote down vote up
def test_to_utf8(self):
        self.assertEqual(encodeutils.to_utf8(b'a\xe9\xff'),        # bytes
                         b'a\xe9\xff')
        self.assertEqual(encodeutils.to_utf8(u'a\xe9\xff\u20ac'),  # Unicode
                         b'a\xc3\xa9\xc3\xbf\xe2\x82\xac')
        self.assertRaises(TypeError, encodeutils.to_utf8, 123)     # invalid

        # oslo.i18n Message objects should also be accepted for convenience.
        # It works because Message is a subclass of six.text_type. Use the
        # lazy translation to get a Message instance of oslo_i18n.
        msg = oslo_i18n_fixture.Translation().lazy("test")
        self.assertEqual(encodeutils.to_utf8(msg),
                         b'test') 
Example #9
Source File: fingerprint.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def _get_schema_sha1(schema_raw):
        return hashlib.sha1(encodeutils.to_utf8(schema_raw)).hexdigest() 
Example #10
Source File: wsgi.py    From tacker with Apache License 2.0 5 votes vote down vote up
def encode_body(body):
    """Encode unicode body.

    WebOb requires to encode unicode body used to update response body.
    """
    return encodeutils.to_utf8(body) 
Example #11
Source File: metadata_service.py    From dragonflow with Apache License 2.0 5 votes vote down vote up
def _sign_instance_id(self, instance_id):
        secret = self.conf.metadata_proxy_shared_secret
        secret = encodeutils.to_utf8(secret)
        instance_id = encodeutils.to_utf8(instance_id)
        return hmac.new(secret, instance_id, hashlib.sha256).hexdigest() 
Example #12
Source File: barbican.py    From octavia with Apache License 2.0 5 votes vote down vote up
def get_private_key_passphrase(self):
        if self._cert_container.private_key_passphrase:
            return encodeutils.to_utf8(
                self._cert_container.private_key_passphrase.payload)
        return None 
Example #13
Source File: barbican.py    From octavia with Apache License 2.0 5 votes vote down vote up
def get_private_key(self):
        if self._cert_container.private_key:
            return encodeutils.to_utf8(
                self._cert_container.private_key.payload)
        return None 
Example #14
Source File: barbican.py    From octavia with Apache License 2.0 5 votes vote down vote up
def get_intermediates(self):
        if self._cert_container.intermediates:
            intermediates = encodeutils.to_utf8(
                self._cert_container.intermediates.payload)
            return list(cert_parser.get_intermediates_pems(intermediates))
        return None 
Example #15
Source File: barbican.py    From octavia with Apache License 2.0 5 votes vote down vote up
def get_certificate(self):
        if self._cert_container.certificate:
            return encodeutils.to_utf8(
                self._cert_container.certificate.payload)
        return None 
Example #16
Source File: models.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def process_bind_param(self, value, dialect):
        return zlib.compress(encodeutils.to_utf8(value)) 
Example #17
Source File: models.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def process_bind_param(self, value, dialect):
        return zlib.compress(encodeutils.to_utf8(jsonutils.dumps(value))) 
Example #18
Source File: models.py    From ara-archive with GNU General Public License v3.0 5 votes vote down vote up
def content_sha1(context):
    """
    Used by the FileContent model to automatically compute the sha1
    hash of content before storing it to the database.
    """
    try:
        content = context.current_parameters['content']
    except AttributeError:
        content = context
    return hashlib.sha1(encodeutils.to_utf8(content)).hexdigest()


# Primary key columns are of these type. 
Example #19
Source File: barbican.py    From octavia with Apache License 2.0 4 votes vote down vote up
def store_cert(self, context, certificate, private_key, intermediates=None,
                   private_key_passphrase=None, expiration=None,
                   name="PKCS12 Certificate Bundle"):
        """Stores a certificate in the certificate manager.

        :param context: Oslo context of the request
        :param certificate: PEM encoded TLS certificate
        :param private_key: private key for the supplied certificate
        :param intermediates: ordered and concatenated intermediate certs
        :param private_key_passphrase: optional passphrase for the supplied key
        :param expiration: the expiration time of the cert in ISO 8601 format
        :param name: a friendly name for the cert

        :returns: the container_ref of the stored cert
        :raises Exception: if certificate storage fails
        """
        connection = self.auth.get_barbican_client(context.project_id)

        LOG.info("Storing certificate secret '%s' in Barbican.", name)
        p12 = crypto.PKCS12()
        p12.set_friendlyname(encodeutils.to_utf8(name))
        x509_cert = crypto.load_certificate(crypto.FILETYPE_PEM, certificate)
        p12.set_certificate(x509_cert)
        x509_pk = crypto.load_privatekey(crypto.FILETYPE_PEM, private_key)
        p12.set_privatekey(x509_pk)
        if intermediates:
            cert_ints = list(cert_parser.get_intermediates_pems(intermediates))
            x509_ints = [
                crypto.load_certificate(crypto.FILETYPE_PEM, ci)
                for ci in cert_ints]
            p12.set_ca_certificates(x509_ints)
        if private_key_passphrase:
            raise exceptions.CertificateStorageException(
                "Passphrase protected PKCS12 certificates are not supported.")

        try:
            certificate_secret = connection.secrets.create(
                payload=p12.export(),
                expiration=expiration,
                name=name
            )
            certificate_secret.store()
            return certificate_secret.secret_ref
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error('Error storing certificate data: %s', e)