def ConnectEventManaged(conn_context):
    """Provides an EventflowOperations instance to use, for managed events."""

    # pylint: disable=protected-access
    client = apis_internal._GetClientInstance(
        conn_context.api_name,
        conn_context.api_version,
        # Only check response if not connecting to GKE
        check_response_func=apis.CheckResponseForApiEnablement()
        if conn_context.supports_one_platform else None,
        http_client=conn_context.HttpClient())
    # This client is used for working with core resources (e.g. Secrets) in
    # Cloud Run for Anthos.
    core_client = None
    if not conn_context.supports_one_platform:
        core_client = apis_internal._GetClientInstance(
            conn_context.api_name,
            _CORE_CLIENT_VERSION,
            http_client=conn_context.HttpClient())
    # This client is only used to get CRDs because the api group they are
    # under uses different versioning in k8s
    crd_client = apis_internal._GetClientInstance(
        conn_context.api_name,
        _CRD_CLIENT_VERSION,
        http_client=conn_context.HttpClient())
    # pylint: enable=protected-access
    return EventflowOperations(client, conn_context.api_version,
                               conn_context.region, core_client, crd_client)
def Connect(conn_context):
    """Provide a ServerlessOperations instance to use.

  If we're using the GKE Serverless Add-on, connect to the relevant cluster.
  Otherwise, connect to the right region of GSE.

  Arguments:
    conn_context: a context manager that yields a ConnectionInfo and manages a
      dynamic context that makes connecting to serverless possible.

  Yields:
    A ServerlessOperations instance.
  """

    # The One Platform client is required for making requests against
    # endpoints that do not supported Kubernetes-style resource naming
    # conventions. The One Platform client must be initialized outside of a
    # connection context so that it does not pick up the api_endpoint_overrides
    # values from the connection context.
    # pylint: disable=protected-access
    op_client = apis_internal._GetClientInstance(
        conn_context.api_name,
        conn_context.api_version,
        ca_certs=conn_context.ca_certs)
    # pylint: enable=protected-access

    with conn_context as conn_info:
        # pylint: disable=protected-access
        client = apis_internal._GetClientInstance(conn_info.api_name,
                                                  conn_info.api_version,
                                                  ca_certs=conn_info.ca_certs)
        # pylint: enable=protected-access
        yield ServerlessOperations(client, conn_info.api_name,
                                   conn_info.api_version, conn_info.region,
                                   op_client)
def Connect(conn_context):
    """Provide a EventflowOperations instance to use.

  If we're using the GKE Serverless Add-on, connect to the relevant cluster.
  Otherwise, connect to the right region of GSE.

  Arguments:
    conn_context: a context manager that yields a ConnectionInfo and manages a
      dynamic context that makes connecting to serverless possible.

  Yields:
    A EventflowOperations instance.
  """

    # The One Platform client is required for making requests against
    # endpoints that do not supported Kubernetes-style resource naming
    # conventions. The One Platform client must be initialized outside of a
    # connection context so that it does not pick up the api_endpoint_overrides
    # values from the connection context.
    op_client = apis.GetClientInstance(conn_context.api_name,
                                       conn_context.api_version)

    with conn_context as conn_info:
        # pylint: disable=protected-access
        client = apis_internal._GetClientInstance(
            conn_info.api_name,
            conn_info.api_version,
            # Only check response if not connecting to GKE
            check_response_func=apis.CheckResponseForApiEnablement()
            if conn_context.supports_one_platform else None,
            http_client=conn_context.HttpClient())
        # This client is used for working with core resources (e.g. Secrets) in
        # Cloud Run for Anthos.
        core_client = None
        if not conn_context.supports_one_platform:
            core_client = apis_internal._GetClientInstance(
                conn_context.api_name,
                _CORE_CLIENT_VERSION,
                http_client=conn_context.HttpClient())
        # This client is only used to get CRDs because the api group they are
        # under uses different versioning in k8s
        crd_client = apis_internal._GetClientInstance(
            conn_context.api_name,
            _CRD_CLIENT_VERSION,
            http_client=conn_context.HttpClient())
        # pylint: enable=protected-access
        yield EventflowOperations(client, conn_info.region, core_client,
                                  crd_client, op_client)
Exemple #4
0
def GetMethods(full_collection_name, api_version=None, no_http=True):
  """Gets all the methods available on the given collection.

  Args:
    full_collection_name: str, The collection including the api name.
    api_version: str, The version string of the API or None to use the default
      for this API.
    no_http: bool, True to not create an authenticated http object for this
      API Client.

  Returns:
    [APIMethod], The method specifications.
  """
  api_name, collection = _SplitFullCollectionName(full_collection_name)
  api_version = api_version or _GetDefaultVersion(api_name)
  # pylint:disable=protected-access
  client = apis_internal._GetClientInstance(api_name, api_version,
                                            no_http=no_http)
  api_collection = GetAPICollection(full_collection_name,
                                    api_version=api_version)
  service = getattr(client, collection.replace(NAME_SEPARATOR, '_'))

  method_names = service.GetMethodsList()
  method_configs = [(name, service.GetMethodConfig(name))
                    for name in method_names]
  return [APIMethod(service, name, api_collection, config)
          for name, config in method_configs]
Exemple #5
0
def GenerateIdToken(service_account_id, audience, include_email=False):
    """Generates an id token for the given service account."""
    service_account_ref = resources.REGISTRY.Parse(
        service_account_id,
        collection='iamcredentials.serviceAccounts',
        params={
            'projectsId': '-',
            'serviceAccountsId': service_account_id
        })

    # pylint: disable=protected-access
    http_client = http_creds.Http(enable_resource_quota=False,
                                  response_encoding=http_creds.ENCODING,
                                  allow_account_impersonation=False)
    iam_client = apis_internal._GetClientInstance('iamcredentials',
                                                  'v1',
                                                  http_client=http_client)
    response = iam_client.projects_serviceAccounts.GenerateIdToken(
        iam_client.MESSAGES_MODULE.
        IamcredentialsProjectsServiceAccountsGenerateIdTokenRequest(
            name=service_account_ref.RelativeName(),
            generateIdTokenRequest=iam_client.MESSAGES_MODULE.
            GenerateIdTokenRequest(audience=audience,
                                   includeEmail=include_email)))
    return response.token
def GetClientInstance():
    # pylint:disable=protected-access
    # Specifically disable resource quota in all cases for service management.
    # We need to use this API to turn on APIs and sometimes the user doesn't have
    # this API turned on. We should always used the shared project to do this
    # so we can bootstrap users getting the appropriate APIs enabled. If the user
    # has explicitly set the quota project, then respect that.
    enable_resource_quota = (
        properties.VALUES.billing.quota_project.IsExplicitlySet())
    return apis_internal._GetClientInstance(
        'servicemanagement', 'v1', enable_resource_quota=enable_resource_quota)
Exemple #7
0
def GetClientInstance(api_name, api_version, no_http=False):
    """Returns an instance of the API client specified in the args.

  Args:
    api_name: str, The API name (or the command surface name, if different).
    api_version: str, The version of the API.
    no_http: bool, True to not create an http object for this client.

  Returns:
    base_api.BaseApiClient, An instance of the specified API client.
  """
    # pylint:disable=protected-access
    return apis_internal._GetClientInstance(api_name, api_version, no_http,
                                            _CheckResponse)
Exemple #8
0
def Connect(conn_info):
    """Provide a AnthosEventsOperations instance to use.

  If we're using the GKE Serverless Add-on, connect to the relevant cluster.
  Otherwise, connect to the right region of GSE.

  Arguments:
    conn_info: a ConnectionInfo

  Returns:
    An AnthosEventsOperation instance.
  """
    # pylint: disable=protected-access
    v1beta1_client = apis_internal._GetClientInstance(
        _ANTHOS_EVENTS_CLIENT_NAME,
        _ANTHOS_EVENTS_CLIENT_VERSION,

        # Only check response if not connecting to GKE
        check_response_func=apis.CheckResponseForApiEnablement()
        if conn_info.supports_one_platform else None,
        http_client=conn_info.HttpClient())

    # This client is used for working with core resources (e.g. Secrets) in
    # Cloud Run for Anthos.
    v1_client = apis_internal._GetClientInstance(
        _ANTHOS_EVENTS_CLIENT_NAME,
        _CORE_CLIENT_VERSION,
        http_client=conn_info.HttpClient())

    v1alpha1_client = apis_internal._GetClientInstance(
        _ANTHOS_EVENTS_CLIENT_NAME,
        _OPERATOR_CLIENT_VERSION,
        http_client=conn_info.HttpClient())

    # pylint: enable=protected-access
    return AnthosEventsOperations(conn_info.api_version, conn_info.region,
                                  v1_client, v1alpha1_client, v1beta1_client)
Exemple #9
0
def _GetClientInstance(version='v1'):
    """Get a client instance for service usage."""
    # pylint:disable=protected-access
    # Specifically disable resource quota in all cases for service management.
    # We need to use this API to turn on APIs and sometimes the user doesn't have
    # this API turned on. We should always use the shared project to do this
    # so we can bootstrap users getting the appropriate APIs enabled. If the user
    # has explicitly set the quota project, then respect that.
    enable_resource_quota = (
        properties.VALUES.billing.quota_project.IsExplicitlySet())
    http_client = http_creds.Http(response_encoding=http_creds.ENCODING,
                                  enable_resource_quota=enable_resource_quota)
    return apis_internal._GetClientInstance('serviceusage',
                                            version,
                                            http_client=http_client)
Exemple #10
0
def GetClientInstance(api_name, api_version, no_http=False,
                      enable_resource_quota=True):
  """Returns an instance of the API client specified in the args.

  Args:
    api_name: str, The API name (or the command surface name, if different).
    api_version: str, The version of the API.
    no_http: bool, True to not create an http object for this client.
    enable_resource_quota: bool, By default, we are going to tell APIs to use
      the quota of the project being operated on. For some APIs we want to use
      gcloud's quota, so you can explicitly disable that behavior by passing
      False here.

  Returns:
    base_api.BaseApiClient, An instance of the specified API client.
  """
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance(
      api_name, api_version, no_http, _CheckResponse, enable_resource_quota)
Exemple #11
0
def GenerateAccessToken(service_account_id, scopes):
  """Generates an access token for the given service account."""
  service_account_ref = resources.REGISTRY.Parse(
      service_account_id, collection='iamcredentials.serviceAccounts',
      params={'projectsId': '-', 'serviceAccountsId': service_account_id})

  # pylint: disable=protected-access
  iam_client = apis_internal._GetClientInstance(
      'iamcredentials', 'v1', allow_account_impersonation=False,
      force_resource_quota=True)
  response = iam_client.projects_serviceAccounts.GenerateAccessToken(
      iam_client.MESSAGES_MODULE
      .IamcredentialsProjectsServiceAccountsGenerateAccessTokenRequest(
          name=service_account_ref.RelativeName(),
          generateAccessTokenRequest=iam_client.MESSAGES_MODULE
          .GenerateAccessTokenRequest(scope=scopes)
      )
  )
  return response
Exemple #12
0
def GetClientInstance(api_name, api_version, no_http=False,
                      enable_resource_quota=True):
  """Returns an instance of the API client specified in the args.

  Args:
    api_name: str, The API name (or the command surface name, if different).
    api_version: str, The version of the API.
    no_http: bool, True to not create an http object for this client.
    enable_resource_quota: bool, By default, we are going to tell APIs to use
      the quota of the project being operated on. For some APIs we want to use
      gcloud's quota, so you can explicitly disable that behavior by passing
      False here.

  Returns:
    base_api.BaseApiClient, An instance of the specified API client.
  """
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance(
      api_name, api_version, no_http, _CheckResponse, enable_resource_quota)
Exemple #13
0
def Connect(conn_context):
  """Provide a ServerlessOperations instance to use.

  If we're using the GKE Serverless Add-on, connect to the relevant cluster.
  Otherwise, connect to the right region of GSE.

  Arguments:
    conn_context: a context manager that yields a ConnectionInfo and manages a
      dynamic context that makes connecting to serverless possible.

  Yields:
    A ServerlessOperations instance.
  """
  with conn_context as conn_info:
    yield ServerlessOperations(
        apis_internal._GetClientInstance(  # pylint: disable=protected-access
            conn_info.api_name, conn_info.api_version,
            ca_certs=conn_info.ca_certs),
        conn_info.api_name, conn_info.api_version)
Exemple #14
0
def Connect(cluster_ref):
    """Provide a ServerlessOperations instance to use.

  Arguments:
    cluster_ref: Resource, the gke cluster to connect to if present. Otherwise,
      connect to Hosted Serverless.

  Yields:
    A ServerlessOperations instance.
  """
    if cluster_ref:
        if not hasattr(ssl, 'PROTOCOL_TLSv1_2'):
            raise serverless_exceptions.NoTLSError(
                'Your Python {}.{}.{} installation does not support TLS 1.2, which is'
                ' required to connect to the GKE Serverless add-on. Please upgrade to'
                ' Python 2.7.9 or greater.'.format(sys.version_info.major,
                                                   sys.version_info.minor,
                                                   sys.version_info.micro))
        with gke.ClusterConnectionInfo(cluster_ref) as (endpoint, ca_certs):

            k8s_apiserver = 'https://kubernetes.default/'
            with gke.MonkeypatchGetaddrinfo('kubernetes.default', endpoint):
                prev_endpoint = (
                    properties.VALUES.api_endpoint_overrides.serverless.Get())
                properties.VALUES.api_endpoint_overrides.serverless.Set(
                    k8s_apiserver)
                # Since we weirdly have to provide ca_certs directly, allow this
                # protected access internal method.
                try:
                    yield ServerlessOperations(
                        apis_internal._GetClientInstance(  # pylint: disable=protected-access
                            _SERVERLESS_API_NAME,
                            _SERVERLESS_API_VERSION,
                            ca_certs=ca_certs))
                finally:
                    properties.VALUES.api_endpoint_overrides.serverless.Set(
                        prev_endpoint)

    else:
        yield ServerlessOperations(
            apis.GetClientInstance(_SERVERLESS_API_NAME,
                                   _SERVERLESS_API_VERSION))
Exemple #15
0
def GetClientInstance(api_name,
                      api_version,
                      no_http=False,
                      use_google_auth=False):
    """Returns an instance of the API client specified in the args.

  Args:
    api_name: str, The API name (or the command surface name, if different).
    api_version: str, The version of the API.
    no_http: bool, True to not create an http object for this client.
    use_google_auth: bool, True if the calling command indicates to use
      google-auth library for authentication. If False, authentication will
      fallback to using the oauth2client library.

  Returns:
    base_api.BaseApiClient, An instance of the specified API client.
  """
    # pylint:disable=protected-access
    return apis_internal._GetClientInstance(api_name, api_version, no_http,
                                            None,
                                            CheckResponseForApiEnablement(),
                                            use_google_auth)
Exemple #16
0
def Connect(conn_context):
    """Provide a EventflowOperations instance to use.

  If we're using the GKE Serverless Add-on, connect to the relevant cluster.
  Otherwise, connect to the right region of GSE.

  Arguments:
    conn_context: a context manager that yields a ConnectionInfo and manages a
      dynamic context that makes connecting to serverless possible.

  Yields:
    A EventflowOperations instance.
  """

    # The One Platform client is required for making requests against
    # endpoints that do not supported Kubernetes-style resource naming
    # conventions. The One Platform client must be initialized outside of a
    # connection context so that it does not pick up the api_endpoint_overrides
    # values from the connection context.
    # pylint: disable=protected-access
    op_client = apis.GetClientInstance(conn_context.api_name,
                                       conn_context.api_version)
    # pylint: enable=protected-access

    with conn_context as conn_info:
        # pylint: disable=protected-access
        client = apis_internal._GetClientInstance(
            conn_info.api_name,
            conn_info.api_version,
            # Only check response if not connecting to GKE
            check_response_func=apis.CheckResponseForApiEnablement()
            if conn_context.supports_one_platform else None,
            http_client=conn_context.HttpClient())
        # pylint: enable=protected-access
        yield EventflowOperations(client, conn_info.api_name,
                                  conn_info.api_version, conn_info.region,
                                  op_client)
Exemple #17
0
def GenerateAccessToken(service_account_id, scopes):
    """Generates an access token for the given service account."""
    service_account_ref = resources.REGISTRY.Parse(
        service_account_id,
        collection='iamcredentials.serviceAccounts',
        params={
            'projectsId': '-',
            'serviceAccountsId': service_account_id
        })

    http_client = transports.GetApitoolsTransport(
        enable_resource_quota=False,
        response_encoding=transport.ENCODING,
        allow_account_impersonation=False)
    # pylint: disable=protected-access
    iam_client = apis_internal._GetClientInstance('iamcredentials',
                                                  'v1',
                                                  http_client=http_client)

    try:
        response = iam_client.projects_serviceAccounts.GenerateAccessToken(
            iam_client.MESSAGES_MODULE.
            IamcredentialsProjectsServiceAccountsGenerateAccessTokenRequest(
                name=service_account_ref.RelativeName(),
                generateAccessTokenRequest=iam_client.MESSAGES_MODULE.
                GenerateAccessTokenRequest(scope=scopes)))
        return response
    except apitools_exceptions.HttpForbiddenError as e:
        raise exceptions.HttpException(
            e,
            error_format='Error {code} (Forbidden) - failed to impersonate '
            '[{service_acc}]. Make sure the account that\'s trying '
            'to impersonate it has access to the service account '
            'itself and the "roles/iam.serviceAccountTokenCreator" '
            'role.'.format(code=e.status_code, service_acc=service_account_id))
    except apitools_exceptions.HttpError as e:
        raise exceptions.HttpException(e)
Exemple #18
0
def Connect(cluster_ref):
    """Provide a ServerlessOperations instance to use.

  Arguments:
    cluster_ref: Resource, the gke cluster to connect to if present. Otherwise,
      connect to Hosted Serverless.

  Yields:
    A ServerlessOperations instance.
  """
    if cluster_ref:
        _CheckTLSSupport()
        with gke.ClusterConnectionInfo(cluster_ref) as (ip, ca_certs):
            with gke.MonkeypatchAddressChecking('kubernetes.default',
                                                ip) as endpoint:
                k8s_apiserver = 'https://{}/'.format(endpoint)
                prev_endpoint = (
                    properties.VALUES.api_endpoint_overrides.serverless.Get())
                properties.VALUES.api_endpoint_overrides.serverless.Set(
                    k8s_apiserver)
                # Since we weirdly have to provide ca_certs directly, allow this
                # protected access internal method.
                try:
                    yield ServerlessOperations(
                        apis_internal._GetClientInstance(  # pylint: disable=protected-access
                            _SERVERLESS_API_NAME,
                            _SERVERLESS_API_VERSION,
                            ca_certs=ca_certs))
                finally:
                    properties.VALUES.api_endpoint_overrides.serverless.Set(
                        prev_endpoint)

    else:
        yield ServerlessOperations(
            apis.GetClientInstance(_SERVERLESS_API_NAME,
                                   _SERVERLESS_API_VERSION))
Exemple #19
0
def GetApiKeysClientInstance():
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance('apikeys', 'v1')
Exemple #20
0
def GetClientInstance():
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance('servicemanagement', 'v1')
Exemple #21
0
  messages = GetMessagesModule()

  RaiseIfResultNotTypeOf(result, messages.Operation)

  result_dict = encoding.MessageToDict(result)

  if not async:
    op_name = result_dict['name']
    op_ref = resources.REGISTRY.Parse(
        op_name,
        collection='servicemanagement.operations')
    log.status.Print(
        'Waiting for async operation {0} to complete...'.format(op_name))
    result_dict = encoding.MessageToDict(WaitForOperation(
        # pylint:disable=protected-access
        op_ref, apis_internal._GetClientInstance('servicemanagement', 'v1')))

  return result_dict


def RaiseIfResultNotTypeOf(test_object, expected_type, nonetype_ok=False):
  if nonetype_ok and test_object is None:
    return
  if not isinstance(test_object, expected_type):
    raise TypeError('result must be of type %s' % expected_type)


def GetCallerViews():
  messages = GetMessagesModule()
  get_request = messages.ServicemanagementServicesProjectSettingsGetRequest
  return {
Exemple #22
0
  messages = GetMessagesModule()

  RaiseIfResultNotTypeOf(result, messages.Operation)

  result_dict = encoding.MessageToDict(result)

  if not async:
    op_name = result_dict['name']
    op_ref = resources.REGISTRY.Parse(
        op_name,
        collection='servicemanagement.operations')
    log.status.Print(
        'Waiting for async operation {0} to complete...'.format(op_name))
    result_dict = encoding.MessageToDict(WaitForOperation(
        # pylint:disable=protected-access
        op_ref, apis_internal._GetClientInstance('servicemanagement', 'v1')))

  return result_dict


def RaiseIfResultNotTypeOf(test_object, expected_type, nonetype_ok=False):
  if nonetype_ok and test_object is None:
    return
  if not isinstance(test_object, expected_type):
    raise TypeError('result must be of type %s' % expected_type)


def GetCallerViews():
  messages = GetMessagesModule()
  get_request = messages.ServicemanagementServicesProjectSettingsGetRequest
  return {
Exemple #23
0
def GetClientInstance():
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance('servicemanagement', 'v1')
Exemple #24
0
def GetApiKeysClientInstance():
  # pylint:disable=protected-access
  return apis_internal._GetClientInstance('apikeys', 'v1')