Exemple #1
0
def find_latest_release_version(ctx, param, value):
    if not value:
        return
    current_version = re.search(r'^(\d+(?:\.\d+)+)*', __version__).group(1)
    exit_code = 0
    try:
        response = requests.get(cli_constants.OCI_CLI_PYPI_URL)
        # Raises stored HTTPError, if one occurred.
        response.raise_for_status()
        latest_version = response.json()['info']['version']
    except requests.exceptions.HTTPError as errh:
        click.echo(click.style("Unable to access Pypi. HTTP Error : {}").format(errh))
        exit_code = 2
    except requests.exceptions.ConnectionError as errc:
        click.echo(click.style("Unable to access Pypi. Error Connecting: {}").format(errc))
        exit_code = 2
    except requests.exceptions.Timeout as errt:
        click.echo(click.style("Unable to access Pypi. Timeout Error: {}").format(errt))
        exit_code = 2
    except requests.exceptions.RequestException as err:
        click.echo(click.style("Unable to access Pypi. {}").format(err))
        exit_code = 2
    except Exception as e:
        click.echo(click.style("Unexpected Error. {}").format(e))
        exit_code = 2
    else:
        click.echo(latest_version)
        current_version_list = [int(x) for x in current_version.split(".")]
        latest_version_list = [int(x) for x in latest_version.split(".")]
        if current_version_list < latest_version_list:
            click.echo(click.style("You are using OCI CLI version {}, however version {} is available. You should consider upgrading using"
                                   " https://docs.cloud.oracle.com/en-us/iaas/Content/API/SDKDocs/cliupgrading.htm".format(current_version, latest_version), fg='red'))
            exit_code = 1

    ctx.exit(exit_code)
def get_instance_id_from_imds():
    # Get the instance id from the metadata service
    # TODO add error checks to ensure instance_id was retrieved.
    endpoint = '{}/instance/id'.format(InstancePrincipalsSecurityTokenSigner.METADATA_URL_BASE)
    # Set the connect time out to 10 seconds and the read time out to 60 seconds.
    timeout = (10, 60)
    response = requests.get(endpoint, timeout=timeout, headers=METADATA_AUTH_HEADERS)
    return response.text.strip().lower()
 def get_tenancy_id(self):
     # Get the instance metadata using the HTTP endpoint.
     GET_TENANCY_ID_URL = 'http://169.254.169.254/opc/v1/instance/compartmentId'
     response = requests.get(GET_TENANCY_ID_URL)
     compartment_id = response.text
     # In case of nested compartments, the immediate compartment may not be the root compartment.
     tenancy_id = call_with_backoff(self.identity_client.get_compartment,
                                    compartment_id=compartment_id).data.compartment_id
     return tenancy_id
Exemple #4
0
    def initialize_and_return_region(self):
        if hasattr(self, 'region'):
            return self.region

        response = requests.get(self.GET_REGION_URL)
        region_raw = response.text.strip().lower()

        # The region can be something like "phx" but internally we expect "us-phoenix-1", "us-ashburn-1" etc.
        if region_raw in oci.regions.REGIONS_SHORT_NAMES:
            self.region = oci.regions.REGIONS_SHORT_NAMES[region_raw]
        else:
            self.region = region_raw

        return self.region
Exemple #5
0
def find_latest_release_info(ctx, param, value):
    if not value:
        return
    od = OrderedDict()
    version = re.search(r'^(\d+(?:\.\d+)+)*', __version__).group(1)
    try:
        response = requests.get(cli_constants.CHANGE_LOG_URL)
        # Raises stored HTTPError, if one occurred.
        response.raise_for_status()
    except requests.exceptions.HTTPError as errh:
        click.echo(
            click.style("Unable to access Github. HTTP Error : {}").format(
                errh))
    except requests.exceptions.ConnectionError as errc:
        click.echo(
            click.style(
                "Unable to access Github. Error Connecting: {}").format(errc))
    except requests.exceptions.Timeout as errt:
        click.echo(
            click.style("Unable to access Github. Timeout Error: {}").format(
                errt))
    except requests.exceptions.RequestException as err:
        click.echo(click.style("Unable to access Github. {}").format(err))
    except Exception as e:
        click.echo(click.style("Unexpected error. {}").format(e))
    else:
        matches = re.findall(
            r'^(\d+(?:\.\d+)+) +- +\d{4}-\d{2}-\d{2}\r?\n((?:(?!\d+\.\d).*(?:\r?\n|$))*)',
            response.content.decode("utf-8"), re.M)
        for match in matches:
            od[match[0].strip()] = match[1]
        if version not in od:
            click.echo(click.style("Version {} not found".format(version),
                                   fg='red'),
                       file=sys.stderr)
        else:
            version_up_to_date = True
            for key in od.keys():
                if key == version:
                    if version_up_to_date:
                        click.echo(
                            click.style(
                                "Version {} is up to date with latest release".
                                format(version)))
                    ctx.exit()
                version_up_to_date = False
                click.echo(key)
                click.echo(od[key])
    ctx.exit()
    def get_endpoint(self, service_name, client_name):
        # standardize service name to convention for Java SDK model namespaces (all lower case one word)
        service_name = service_name.replace('_', '').lower()

        url = '{service_root_url}/endpoint'.format(
            service_root_url=SERVICE_ROOT_URL)
        params = {
            'sessionId': self.session_id,
            'serviceName': service_name,
            'clientName': client_name
        }

        response = requests.get(url, params=params)
        assert response.status_code == 200, response.content
        return response.content.decode('UTF-8')
    def is_api_enabled(self, service_name, api_name):
        """
        Checks if a given service_name / api_name is supported by the testing service and enabled for this client / language.

        :param str service_name
            The name of the service to request input parameters for. The testing service uses the following template to
            construct the Java SDK request object:
            String.format("com.oracle.bmc.%s.requests.%sRequest", serviceName, apiName);

        :param str api_name
            The name of the API to request input parameters for. The testing service uses the following template to
            construct the Java SDK request object:
            String.format("com.oracle.bmc.%s.requests.%sRequest", serviceName, apiName);

        :return: Whether or not this API is enabled in the testing service.

        """
        # standardize service name to convention for Java SDK model namespaces (all lower case one word)
        service_name = service_name.replace('_', '').lower()

        url = '{service_root_url}/request/enable'.format(
            service_root_url=SERVICE_ROOT_URL)
        params = {
            'lang': SERVICE_LANGUAGE,
            'serviceName': service_name,
            'apiName': api_name
        }

        response = requests.get(url, params=params)
        assert response.status_code == 200, response.content

        response_content = response.content.decode('UTF-8')
        try:
            api_enabled_response = json.loads(response_content)
        except ValueError as e:
            print(
                'Failed to parse testing service response as valid JSON. Response: {}'
                .format(response_content))
            raise e

        assert api_enabled_response is True or api_enabled_response is False, 'Received invalid response from testing service, should be true or false. Response: {}'.format(
            api_enabled_response)
        return api_enabled_response
Exemple #8
0
    def initialize_and_return_region(self):
        if hasattr(self, 'region'):
            return self.region

        self.logger.debug("Requesting region information from : %s " %
                          (self.GET_REGION_URL))
        response = requests.get(self.GET_REGION_URL,
                                timeout=(10, 60),
                                headers=self.METADATA_AUTH_HEADERS)
        region_raw = response.text.strip().lower()

        # The region can be something like "phx" but internally we expect "us-phoenix-1", "us-ashburn-1" etc.
        if region_raw in oci.regions.REGIONS_SHORT_NAMES:
            self.region = oci.regions.REGIONS_SHORT_NAMES[region_raw]
        else:
            self.region = region_raw

        self.logger.debug("Region is set to : %s " % (self.region))
        return self.region
    def get_requests(self, service_name, api_name):
        """
        Gets a list of requests from the testing service to be used in calling the API specified by service_name and api_name.

        :param str service_name
            The name of the service to request input parameters for. The testing service uses the following template to
            construct the Java SDK request object:
            String.format("com.oracle.bmc.%s.requests.%sRequest", serviceName, apiName);

        :param str api_name
            The name of the API to request input parameters for. The testing service uses the following template to
            construct the Java SDK request object:
            String.format("com.oracle.bmc.%s.requests.%sRequest", serviceName, apiName);

        :return: A list of dicts containing parameters to call the API specified by service_name and api_name

        """
        if not self.session_id:
            raise RuntimeError(
                'Must call create_session before calling get_requests.')

        # standardize service name to convention for Java SDK model namespaces (all lower case one word)
        service_name = service_name.replace('_', '').lower()

        params = {
            'serviceName': service_name,
            'apiName': api_name,
            'lang': SERVICE_LANGUAGE,
            'sessionId': self.session_id
        }

        url = '{service_root_url}/request'.format(
            service_root_url=SERVICE_ROOT_URL)
        response = requests.get(url, params=params)
        response_content = response.content.decode('UTF-8')
        try:
            return json.loads(response_content)
        except ValueError as e:
            print(
                'Failed to parse testing service response as valid JSON. Response: '
                + response_content)
            raise e
Exemple #10
0
    def _refresh_inner(self):
        """
        Refreshes the certificate and its corresponding private key (if there is one defined for this retriever).
        This method represents the unit of retrying for the certificate retriever. It is intentionally coarse
        grained (e.g. if we retrieve the certificate but fail to retrieve the private key then we'll retry and
        retrieve both the certificate and private key again) to try and best maintain consistency in the data.

        For example, if we had separate retries for the certificate and the private key, in the scenario where
        a certificate was successfully retrieved but the private key failed, the private key we successfully
        retrieved upon retry may not relate to the certificate that we retrieved (e.g. because of rotation). This
        is still a risk in coarse grained retries, but hopefully a smaller one.
        """
        import oci.signer

        downloaded_certificate = six.BytesIO()
        response = requests.get(self.cert_url, stream=True)

        response.raise_for_status()

        for chunk in response.raw.stream(self.READ_CHUNK_BYTES,
                                         decode_content=False):
            downloaded_certificate.write(chunk)

        self.certificate_and_private_key[
            'certificate'] = downloaded_certificate.getvalue().strip()
        downloaded_certificate.close()
        if isinstance(self.certificate_and_private_key['certificate'],
                      six.text_type):
            self.certificate_and_private_key[
                'certificate'] = self.certificate_and_private_key[
                    'certificate'].encode('ascii')

        self._check_valid_certificate_string(
            self.certificate_and_private_key['certificate'])

        if self.private_key_url:
            downloaded_private_key_raw = six.BytesIO()
            response = requests.get(self.private_key_url, stream=True)

            response.raise_for_status()

            for chunk in response.raw.stream(self.READ_CHUNK_BYTES,
                                             decode_content=False):
                downloaded_private_key_raw.write(chunk)

            self.certificate_and_private_key[
                'private_key_pem'] = downloaded_private_key_raw.getvalue(
                ).strip()
            downloaded_private_key_raw.close()

            if isinstance(self.certificate_and_private_key['private_key_pem'],
                          six.text_type):
                self.certificate_and_private_key[
                    'private_key_pem'] = self.certificate_and_private_key[
                        'private_key_pem'].encode('ascii')

            try:
                self.certificate_and_private_key[
                    'private_key'] = oci.signer.load_private_key(
                        self.certificate_and_private_key['private_key_pem'],
                        self.passphrase)
            except oci.exceptions.InvalidPrivateKey:
                raise InvalidCertificateFromInstanceMetadataError(
                    certificate_type='private_key',
                    certificate_raw=self.
                    certificate_and_private_key['private_key_pem'])