예제 #1
0
    def test_oci_metadata__get(self):
        """
        Test metadata class get.

        Returns
        -------
            No return value.
        """
        regionlist = list()
        for region in oci_regions.values():
            regionlist += re.split(' - | \(', region.replace(')',''))
        metadata = InstanceMetadata().get()
        self.assertNotEqual(metadata, [], 'Instanciated metadata is empty')
        self.assertTrue('instance' in metadata, 'instance key should be in metadata')
        self.assertIn('region', metadata['instance'], 'metadata does not contain region information')
        self.assertIn(metadata['instance']['region'], regionlist,
                      'instance region [%s] not part of possible values [%s]'
                      % (metadata['instance']['region'], regionlist))
        self.assertIn('state', metadata['instance'], 'Returned instance metadata do not contain any \'state\' key')
        self.assertEqual(metadata['instance']['state'], 'Running',
                         'execute state of OCI instance should  be running. [%s]'
                         % metadata['instance']['state'])
        self.assertIn('displayName' , metadata['instance'], 'displayname key should be in metadata')
        self.assertIn('availabilityDomain', metadata['instance'],
                        'availability domain key should be in metadata')
        self.assertIn('id' , metadata['instance'], 'OCID key should be in metadata')
        self.assertIn('compartmentId', metadata['instance'], 'compartment OCID key should be in metadata')
예제 #2
0
    def test_oci_metadata__filter(self):
        """
        Test metadata filter.

        Returns
        -------
            No return value.
        """
        metadata = InstanceMetadata().filter(['macaddr', 'instance'])
        self.assertTrue(metadata, 'empty filtered metadata returned')
        self.assertIn('instance', metadata,
                      '\'instance\' not part of filtered metadata')
        self.assertIn(
            'compartmentId', metadata['instance'],
            '\'compartmentId\' not part of filtered instance metadata')
        self.assertIn(
            'ocid1.compartment.oc1..', metadata['instance']['compartmentId'],
            'Not expected value of \'compartmentId\'  of filtered instance metadata'
        )
        self.assertIn('vnics', metadata,
                      '\vnics\' not part of filtered instance metadata')
        self.assertIn('macAddr', metadata['vnics'][0],
                      'first VNIC of metatada do not contain \'macAddr\' key')
        self.assertNotIn(
            'vnicId', metadata['vnics'][0],
            'first VNIC of metatada do not contain \'vnicId\' key')
예제 #3
0
    def test_oci_metadata__get(self):
        """
        Test metadata class get.

        Returns
        -------
            No return value.
        """
        metadata = InstanceMetadata().get()
        self.assertNotEqual(metadata, [], 'Instanciated metatde is empty')
        self.assertTrue(metadata['instance'],
                        'instance key of metadata should be True')
        self.assertIn('region', metadata['instance'],
                      'metadata do not contain region information')
        self.assertIn(
            metadata['instance']['region'],
            ['phx', 'iad', 'fra', 'lhr', 'uk-london-1'],
            'instance region [%s] not part of possible values [%s]' %
            (metadata['instance']['region'], ['phx', 'iad', 'fra', 'lhr']))
        self.assertIn(
            'state', metadata['instance'],
            'Returned instance metadata do not contain any '
            '\'state\' key')
        self.assertEqual(
            metadata['instance']['state'], 'Running',
            'exepcetd statte of OCI instance to be running. ['
            '%s]' % metadata['instance']['state'])
예제 #4
0
def needsOCICLI():
    """
    Skip test if the OCI CLI is not installed and configured:
    * checks that oci command line is present;
    * checks that we are running on OCI instance by check a call to OCI SDK;
    * checks that we can call oci instance;

    Returns
    -------
    lambda function
        Decorator
    """
    global __needsOCICLI_msg

    if __needsOCICLI_msg == '':
        # we've been here already and everything is fine
        return lambda func: func

    if __needsOCICLI_msg is not None:
        # we've been here already and something is wrong
        return unittest.skip(__needsOCICLI_msg)

    # first time here: let's do some checks.

    if not os.path.exists('/usr/bin/oci'):
        __needsOCICLI_msg = "OCI CLI client must be installed for this " \
                            "test (missing /usr/bin/oci)"
        return unittest.skip(__needsOCICLI_msg)

    # we expect metadata to host 'instance' key with 'id' information in it
    _instance_id = None
    try:
        _instance_id = InstanceMetadata().get()['instance'].get('id')
    except Exception:
        pass

    if _instance_id is None:
        __needsOCICLI_msg = "must be run on an OCI instance " \
                            "(get_instance_id() failed)"
        return unittest.skip(__needsOCICLI_msg)

    # now check that the oci client is configured
    sp = subprocess.Popen([
        '/usr/bin/oci', 'compute', 'instance', 'get', '--instance-id',
        _instance_id
    ],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    (_, _) = sp.communicate()
    if sp.returncode != 0:
        __needsOCICLI_msg = "OCI CLI client must be configured for this " \
                            "test (oci command execution failed)"
        return unittest.skip(__needsOCICLI_msg)

    # empty means OK
    __needsOCICLI_msg = ''

    return lambda func: func
예제 #5
0
    def test_oci_metadata_refresh(self):
        """
        Test metadata refresh.

        Returns
        -------
            No return value.
        """
        self.assertTrue(InstanceMetadata().refresh(), 'Metadata refresh failed.')
예제 #6
0
def get_instance_ocid():
    """
    Gets the instance OCID; fetch in the instance InstanceMetadata the
    ID of the current instance

    Returns
    -------
        str
            The instance id or '<instance OCID>' if not found.
    """
    return InstanceMetadata().refresh()['instance']['id']
예제 #7
0
def get_phys_device():
    """
    Find the primary ethernet device interface name.

    Returns
    -------
    str
        The primary ethernet device name.
    """
    try:
        # TODO : it seesm that it is private_ip now
        private_ip = InstanceMetadata()['vnics'][0]['privateIp']
    except Exception, e:
        _logger.debug('error checking metadata: %s' % str(e))
        return None
예제 #8
0
    def __init__(self, topic=None, config_file=OCI_CONFIG_FILE):
        """
        Initialisation of the oci-notification configuration.

        Parameters
        ----------
        topic: str
            The oci-notification topic.
        config_file: str
            The full path to the oci-notify config file.
        """
        self._topic = topic
        self._config_file = config_file
        self._instance_name = InstanceMetadata().refresh(
        )['instance']['displayName']
def get_instance_ocid():
    """
    Gets the instance OCID; fetch in the instance InstanceMetadata the
    ID of the current instance

    Returns
    -------
        str
            The instance id or '<instance OCID>' if not found.
    """
    md = InstanceMetadata().filter('instance')
    if 'instance' in md and 'id' in md['instance']:
        return md['instance']['id']
    else:
        # TODO : What the purpose of this ?
        #        How user supposed to handle this ?
        return '<instance OCID>'
예제 #10
0
    def __init__(self,
                 title,
                 message,
                 oci_config_file='~/.oci/config',
                 oci_config_profile='DEFAULT',
                 authentication_method=None):
        """
        Initialisation sending the message.

        Parameters
        ----------
        title: str
            The message subject.
        message: str
            The file or url containing the message.
        oci_config_file: str
            The full or relative path to the oci config file, for direct authentication.
        oci_config_profile: str
            The profile used for direct authentication.
        authentication_method: str
            The authentication method: NONE, DIRECT, IP, PROXY, AUTO
        """
        self._title = title
        if len(title) > MAX_MESSAGE_TITLE_LEN:
            self._title = title[:MAX_MESSAGE_TITLE_LEN]
            _logger.info("Cutting title to '[%s]'", self._title)
        self._message = message
        self._subject = ''
        # self._topic = self.get_notification_topic()
        self._topic = None
        self._oci_config_file = oci_config_file
        self._oci_config_profile = oci_config_profile
        self._oci_authentication = authentication_method
        self._message_type_str = False
        self._signer = None
        self._ons_client = None
        self._identity_client = None
        self._oci_config = None
        self._instance_name = InstanceMetadata().refresh(
        )['instance']['displayName']
        self._auth_method = self.get_auth_method()
예제 #11
0
def get_phys_device():
    """
    Find the primary ethernet device interface name.

    Returns
    -------
    str
        The primary ethernet device name.
    """
    try:
        # TODO : it seesm that it is private_ip now
        private_ip = InstanceMetadata().refresh()['vnics'][0]['privateIp']
    except Exception as e:
        _logger.debug('error checking metadata: %s', str(e))
        return None
    phys_dev = None
    output = sudo_utils.call_output([IP_CMD, '-o', '-4', 'addr', 'show'])
    lines = output.splitlines()
    for line in lines:
        _l = line.decode().strip()
        if private_ip in _l:
            phys_dev = _l.split()[1]
    _logger.debug('%s physical devices found', len(phys_dev))
    return phys_dev
예제 #12
0
def main():
    """
    Visualize the metadata.

    Returns
    -------
        0 on success, 1 on failure.
    """
    args = parse_args()

    inst_id = None
    if args.instance_id:
        inst_id = args.instance_id

    if args.export and not args.keys:
        _logger.error("--export only works with --get or -g.")
        return 1

    if args.trim and not args.keys:
        _logger.error("--trim only works with --get or -g. ")
        return 1

    if args.setkeys:
        # set
        if args.keys:
            _logger.error("-g or --get option conflicts with -u or --update.")
            return 1

        k_v = parse_vars(args.setkeys)
        if not verify_setkeys(k_v):
            return 1

        try:
            # meta = oci_utils.oci_api.OCISession().update_instance_metadata(
            # instance_id=inst_id, **k_v)
            meta = OCISession().update_instance_metadata(instance_id=inst_id,
                                                         **k_v)
            if meta is None:
                #
                # if meta is None, the session failed to update the metadata; the session is writing the error message;
                # this should change...
                return 1
            metadata = meta.filter(list(k_v.keys()))
        except Exception as e:
            _logger.error("%s", str(e), exc_info=True)
            return 1
    else:
        # get
        if args.value_only:
            if len(args.keys) != 1:
                _logger.error(
                    "Error: --value-only option works only with one -g or --get option."
                )
                return 1

        try:
            # if we have an ID, use the session.
            if inst_id is not None:
                meta = OCISession().get_instance(
                    instance_id=inst_id).get_metadata()
            else:
                meta = InstanceMetadata().refresh()
            metadata = meta.filter(args.keys)
        except Exception as e:
            _logger.debug('Failed to get metadata for %s',
                          inst_id,
                          exc_info=True)
            _logger.error("%s", str(e))
            return 1

    if metadata is None:
        if args.keys:
            _logger.error("No matching metadata for '%s' found.",
                          str(args.keys))
        elif args.setkeys:
            _logger.error("No matching metadata for '%s' found.",
                          str(args.setkeys))
        else:
            _logger.error("No metadata found for instance (%s).", inst_id)
        return 1

    if args.value_only:
        print_value_only(args.keys, metadata)
        return 0

    if args.export:
        export_keys(args.keys, metadata)
        return 0

    if args.trim:
        print_trimed_key_values(args.keys, metadata)
        return 0

    if args.json:
        print(json.dumps(metadata, default=dumper, indent=2))
        return 0

    pretty_print(metadata)
    return 0
예제 #13
0
def main():
    """
    Visualize the metadata.

    Returns
    -------
        0 on success, 1 on failure.
    """
    args = parse_args()

    inst_id = None
    if args.instance_id:
        inst_id = args.instance_id

    if args.export and not args.keys:
        _logger.error("--export only works with --get or -g.")
        return 1

    if args.trim and not args.keys:
        _logger.error("--trim only works with --get or -g. ")
        return 1

    if args.setkeys:
        if args.keys:
            _logger.error("-g or --get option conflicts with -u or --update.")
            return 1

        k_v = parse_vars(args.setkeys)
        if not verify_setkeys(k_v):
            return 1

        try:
            # meta = oci_utils.oci_api.OCISession().update_instance_metadata(
            # instance_id=inst_id, **k_v)
            meta = OCISession().update_instance_metadata(instance_id=inst_id,
                                                         **k_v)
            metadata = meta.filter(k_v.keys())
        except Exception as e:
            _logger.error("%s" % str(e))
            return 1
    else:
        # get
        if args.value_only:
            if len(args.keys) != 1:
                sys.stderr.write(
                    "Error: --value-only option works only with one -g or --get option."
                )
                return 1

        try:
            # if we have an ID, use the session.
            if inst_id is not None:
                meta = OCISession().get_instance(
                    instance_id=inst_id).get_metadata()
            else:
                meta = InstanceMetadata()
            metadata = meta.filter(args.keys)
        except Exception as e:
            _logger.error("%s" % str(e))
            return 1

    if metadata is None:
        if args.keys:
            _logger.error("No matching metadata for '%s' found." %
                          str(args.keys))
        elif args.setkeys:
            _logger.error("No matching metadata for '%s' found." %
                          str(args.setkeys))
        else:
            _logger.error("No metadata found for instance (%s)." % inst_id)
        return 1

    if args.value_only:
        print_value_only(args.keys, metadata)
        return 0

    if args.export:
        export_keys(args.keys, metadata)
        return 0

    if args.trim:
        print_trimed_key_values(args.keys, metadata)
        return 0
    if args.json:
        print json.dumps(metadata, default=dumper, indent=2)
        return 0
    else:
        pretty_print(metadata)
        return 0