def getVolumeDetails():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request
    volumeURL = server + "/v2/projects/" + str(
        project_number
    ) + "/locations/" + location + "/Volumes/" + volumeIDdetails
    payload = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("GET",
                                volumeURL,
                                data=payload,
                                headers=headers)
    # Load the json response into a dict
    r_dict = response.json()
    #Print out all service levels
    print("Response to GET request: " + volumeURL)
    # Get volume attributes
    volumeName = (r_dict.get('name'))
    volumeID = (r_dict.get('volumeId'))
    serviceLevcel = (r_dict.get('serviceLevel'))
    print("\tvolumeName: " + volumeName + ", serviceLevel: " + serviceLevcel,
          "volumeID: " + volumeID)
    def classify_by_api_call(self, query):

        proxies = {
            'http': HTTP_PROXY,
            'https': HTTPS_PROXY,
        }

        url = QUESTION_CLASSIFIER_URL

        headers = {
            'content-type': "application/json",
            'authorization': GOOGLE_API_KEY
        }
        payload = {
            "document": {
                "type": "PLAIN_TEXT",
                "content": query
            },
            "classificationConfig": {
                "model": "question_classification_v2_0"
            }
        }

        response = requests.request("POST",
                                    url,
                                    data=json.dumps(payload),
                                    headers=headers,
                                    proxies=proxies)
        answer_type = json.loads(
            response.text)["categories"][0]["name"].replace("_", ":")
        return answer_type
示例#3
0
    def delete(self, path):
        """Deletes the given study, series or instance from the server.
        :param path: Positional argument, specifies a path (studies/[<uid>/series/\
[<uid>/instances/]]) to delete.
        """
        try:
            response_text = self.requests.delete_dicom(path)
            response_json = json.loads(response_text)
            if "name" in response_json:
                operation_name = response_json["name"]
                base_url = re.match('^.+//([^/]+/){2}',
                                    self.requests.host).group()
                requests = requests_util.Requests(base_url,
                                                  self.requests.authenticator)
                is_done = False
                while not is_done:
                    time.sleep(1)
                    try:
                        operation_json = json.loads(requests.request(operation_name,\
                         "", {}).text)
                        is_done = operation_json.get("done", False)
                    except requests_util.NetworkError:
                        return operation_name  # we assume user uses custom endpoint e.g reverse proxy
                    logging.info('In progress\x1b[1A\x1b[\x1b[80D')
            logging.info('Deletion is done            ')
        except requests_util.NetworkError as exception:
            logging.error('Delete failure: %s', exception)
        return ""
示例#4
0
def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Code copied from https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iap/make_iap_request.py

    Args:
        url: The Identity-Aware Proxy-protected URL to fetch.
        client_id: The client ID used by Identity-Aware Proxy.
        method: The request method to use
                ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
        **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                If no timeout is provided, it is set to 90 by default.

    Returns:
        The page body, or raises an exception if the page couldn't be retrieved.

    """
    # Set the default timeout, if missing
    if 'timeout' not in kwargs:
        kwargs['timeout'] = 90

    # Obtain an OpenID Connect (OIDC) token from metadata server or using service account.
    google_open_id_connect_token = id_token.fetch_id_token(
        google.auth.transport.requests.Request(), client_id)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    logger.info("Attempting iap auth")
    resp = requests.request(
        method,
        url,
        headers={'Authorization': f'Bearer {google_open_id_connect_token}'},
        **kwargs)
    logger.info("Past auth")
    if resp.status_code == 403:
        raise Exception('Service account does not have permission to '
                        'access the IAP-protected application.')
    elif resp.status_code != 200:
        raise Exception(
            'Bad response from application: {!r} / {!r} / {!r}'.format(
                resp.status_code, resp.headers, resp.text))
    else:
        return resp.text
def deleteVol():
    id_token1 = get_token()
    # Construct delete request
    deletevolumeURL = server + "/v2/projects/" + str(
        project_number
    ) + "/locations/" + location + "/Volumes/" + volumeIDdetails
    payload = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    # delete request to create the volume
    response = requests.request("DELETE",
                                deletevolumeURL,
                                headers=headers,
                                data=payload)
    print(response.text)
def updateServiceLevel():
    id_token1 = get_token()
    # Get all volumes from all regions
    # Construct GET request
    volumeURL = server + "/v2/projects/" + str(
        project_number
    ) + "/locations/" + location + "/Volumes/" + volumeIDdetails
    payload = "{\n    \"serviceLevel\": \"basic\"\n}"
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("PUT",
                                volumeURL,
                                data=payload,
                                headers=headers)
    # Load the json response into a dict
    #Print out all service levels
    time.sleep(10)
    print("Response to GET request: " + volumeURL)
    print(response.text)
示例#7
0
def getServiceLevel():
    id_token1 = get_token()
    # Get all volumes from all regions
    url = server + "/v2/projects/" + str(
        project_number) + "/locations/" + location + "/Storage/ServiceLevels"
    # Construct GET request
    #url = "https://cloudvolumesgcp-api.netapp.com/v2/projects/779740114201/locations/us-central1/Storage/ServiceLevels"
    payload = ""
    headers = {
        'Content-Type': "application/json",
        'Authorization': "Bearer " + id_token1.decode('utf-8'),
        'cache-control': "no-cache",
    }
    response = requests.request("GET", url, data=payload, headers=headers)
    # Load the json response into a dict
    r_dict = response.json()
    # Print out all service levels
    print("Response to GET request: " + url)
    for serviceLevel in r_dict:
        # Get volume attributes
        serviceLevelName = serviceLevel["name"]
        serviceLevelPerformance = serviceLevel["performance"]
        print("\tserviceLevelName: " + serviceLevelName +
              ", \tserviceLevelPerformance: " + serviceLevelPerformance)
示例#8
0
def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.

    Args:
      url: The Identity-Aware Proxy-protected URL to fetch.
      client_id: The client ID used by Identity-Aware Proxy.
      method: The request method to use
              ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                If no timeout is provided, it is set to 90 by default.

    Returns:
      The page body, or raises an exception if the page couldn't be retrieved.
    """
    # Set the default timeout, if missing
    if 'timeout' not in kwargs:
        kwargs['timeout'] = 90

    # Figure out what environment we're running in and get some preliminary
    # information about the service account.
    bootstrap_credentials, _ = google.auth.default(scopes=[IAM_SCOPE])

    # For service account's using the Compute Engine metadata service,
    # service_account_email isn't available until refresh is called.
    bootstrap_credentials.refresh(Request())

    signer_email = bootstrap_credentials.service_account_email
    if isinstance(bootstrap_credentials,
                  google.auth.compute_engine.credentials.Credentials):
        # Since the Compute Engine metadata service doesn't expose the service
        # account key, we use the IAM signBlob API to sign instead.
        # In order for this to work:
        # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
        #    You can specify this specific scope when creating a VM
        #    through the API or gcloud. When using Cloud Console,
        #    you'll need to specify the "full access to all Cloud APIs"
        #    scope. A VM's scopes can only be specified at creation time.
        # 2. The VM's default service account needs the "Service Account Actor"
        #    role. This can be found under the "Project" category in Cloud
        #    Console, or roles/iam.serviceAccountActor in gcloud.
        signer = google.auth.iam.Signer(Request(), bootstrap_credentials,
                                        signer_email)
    else:
        # A Signer object can sign a JWT using the service account's key.
        signer = bootstrap_credentials.signer

    # Construct OAuth 2.0 service account credentials using the signer
    # and email acquired from the bootstrap credentials.
    service_account_credentials = google.oauth2.service_account.Credentials(
        signer,
        signer_email,
        token_uri=OAUTH_TOKEN_URI,
        additional_claims={'target_audience': client_id})
    # service_account_credentials gives us a JWT signed by the service
    # account. Next, we use that to obtain an OpenID Connect token,
    # which is a JWT signed by Google.
    google_open_id_connect_token = get_google_open_id_connect_token(
        service_account_credentials)

    # Fetch the Identity-Aware Proxy-protected URL, including an
    # Authorization header containing "Bearer " followed by a
    # Google-issued OpenID Connect token for the service account.
    resp = requests.request(
        method,
        url,
        headers={
            'Authorization': 'Bearer {}'.format(google_open_id_connect_token)
        },
        **kwargs)
    if resp.status_code == 403:
        raise Exception(
            'Service account {} does not have permission to '
            'access the IAP-protected application.'.format(signer_email))
    elif resp.status_code != 200:
        raise Exception(
            'Bad response from application: {!r} / {!r} / {!r}'.format(
                resp.status_code, resp.headers, resp.text))
    else:
        return resp.text