def _StartNewWebSocket(self):
        """Start a new WebSocket and thread to listen for incoming data."""
        headers = ['User-Agent: ' + transport.MakeUserAgentString()]
        request_reason = properties.VALUES.core.request_reason.Get()
        if request_reason:
            headers += ['X-Goog-Request-Reason: ' + request_reason]

        if self._get_access_token_callback:
            headers += [
                'Authorization: Bearer ' + self._get_access_token_callback()
            ]

        if self._connection_sid:
            url = utils.CreateWebSocketReconnectUrl(self._tunnel_target,
                                                    self._connection_sid,
                                                    self._total_bytes_received)
            log.info('Reconnecting with URL [%r]', url)
        else:
            url = utils.CreateWebSocketConnectUrl(self._tunnel_target)
            log.info('Connecting with URL [%r]', url)

        self._connect_msg_received = False
        self._websocket_helper = helper.IapTunnelWebSocketHelper(
            url, headers, self._ignore_certs, self._tunnel_target.proxy_info,
            self._OnData, self._OnClose)
        self._websocket_helper.StartReceivingThread()
Exemple #2
0
def Http(timeout='unset', response_encoding=None, ca_certs=None):
    """Get an httplib2.Http client that is properly configured for use by gcloud.

  This method does not add credentials to the client.  For an Http client that
  has been authenticated, use core.credentials.http.Http().

  Args:
    timeout: double, The timeout in seconds to pass to httplib2.  This is the
        socket level timeout.  If timeout is None, timeout is infinite.  If
        default argument 'unset' is given, a sensible default is selected.
    response_encoding: str, the encoding to use to decode the response.
    ca_certs: str, absolute filename of a ca_certs file that overrides the
        default. The gcloud config property for ca_certs, in turn, overrides
        this argument.

  Returns:
    An httplib2.Http client object configured with all the required settings
    for gcloud.
  """
    # Wrap the request method to put in our own user-agent, and trace reporting.
    command_name = properties.VALUES.metrics.command_name.Get()
    gcloud_ua = transport.MakeUserAgentString(command_name)
    http_client = _CreateRawHttpClient(timeout, ca_certs)
    http_client = _Wrap(http_client,
                        properties.VALUES.core.request_reason.Get(), gcloud_ua,
                        properties.VALUES.core.log_http.GetBool(),
                        properties.VALUES.core.log_http_redact_token.GetBool(),
                        response_encoding)

    return http_client
Exemple #3
0
 def _HandleNewConnection(self, conn, socket_address):
     try:
         user_agent = transport.MakeUserAgentString()
         self._RunReceiveLocalData(conn, repr(socket_address), user_agent)
     except EnvironmentError as e:
         log.info('Socket error [%s] while receiving from client.',
                  six.text_type(e))
     except:  # pylint: disable=bare-except
         log.exception('Error while receiving from client.')
Exemple #4
0
 def _TestConnection(self):
     log.status.Print('Testing if tunnel connection works.')
     user_agent = transport.MakeUserAgentString()
     websocket_conn = self._InitiateWebSocketConnection(
         None,
         functools.partial(_GetAccessTokenCallback,
                           store.LoadIfEnabled(use_google_auth=True)),
         user_agent)
     websocket_conn.Close()
    def Run(self, args):
        enable_experimental = (
            properties.VALUES.kuberun.enable_experimental_commands.GetBool())
        if not enable_experimental:
            # This prompt is here because our commands are not yet public and marking
            # them as hidden doesn't proclude a customer from using the command if
            # they know about it.
            console_io.PromptContinue(
                message=
                'This command is currently under construction and not supported.',
                throw_if_unattended=True,
                cancel_on_no=True,
                default=False)

        project = properties.VALUES.core.project.Get()
        command = self.Command()
        command.extend(self.BuildKubeRunArgs(args))

        devkit_dir = ''  # '' to force Go binary to use the fdk-dir for gcloud_lite
        if config.Paths().sdk_root:
            devkit_dir = os.path.join(config.Paths().sdk_root, 'lib',
                                      'kuberun', 'kuberun_devkits')
        env_vars = {
            'CLOUDSDK_AUTH_TOKEN':
                auth.GetAuthToken(account=properties.VALUES.core.account.Get()),
            'CLOUDSDK_PROJECT':
                project,
            'CLOUDSDK_USER_AGENT':  # Cloud SDK prefix + user agent string
                '{} {}'.format(config.CLOUDSDK_USER_AGENT,
                               transport.MakeUserAgentString()),
            'KUBERUN_DEVKIT_DIRECTORY':
                devkit_dir,
        }

        region = properties.VALUES.compute.region.Get(required=False,
                                                      validate=False)
        if region:
            env_vars['CLOUDSDK_COMPUTE_REGION'] = region

        zone = properties.VALUES.compute.zone.Get(required=False,
                                                  validate=False)
        if zone:
            env_vars['CLOUDSDK_COMPUTE_ZONE'] = zone

        response = self.command_executor(
            command=command,
            env=kuberuncli.GetEnvArgsForCommand(extra_vars=env_vars),
            show_exec_error=args.show_exec_error)
        log.debug('Response: %s' % response.stdout)
        log.debug('ErrResponse: %s' % response.stderr)

        if response.failed:
            return self.FailureResult(response.stdout)

        return self.SuccessResult(response.stdout, args)
Exemple #6
0
    def Run(self):
        """Executes the tunneling of data."""
        try:
            with execution_utils.RaisesKeyboardInterrupt():

                # Fetching user agent before we start the read loop, because the agent
                # fetch will call sys.stdin.isatty, which is blocking if there is a read
                # waiting for data in the stdin. This only affects MacOs + python 2.7.
                user_agent = transport.MakeUserAgentString()

                self._RunReceiveLocalData(_StdinSocket(), 'stdin', user_agent)
        except KeyboardInterrupt:
            log.info('Keyboard interrupt received.')
    def Run(self, args):
        enable_experimental = (
            properties.VALUES.kuberun.enable_experimental_commands.GetBool())
        if not enable_experimental:
            # This prompt is here because our commands are not yet public and marking
            # them as hidden doesn't proclude a customer from using the command if
            # they know about it.
            console_io.PromptContinue(
                message=
                'This command is currently under construction and not supported.',
                throw_if_unattended=True,
                cancel_on_no=True,
                default=False)

        command_executor = self.CommandExecutor()
        project = properties.VALUES.core.project.Get()
        command = self.Command()
        command.extend(self.BuildKubeRunArgs(args))
        response = command_executor(
            command=command,
            env=kuberuncli.GetEnvArgsForCommand(
                extra_vars={
                    'CLOUDSDK_AUTH_TOKEN':
                    auth.GetAuthToken(
                        account=properties.VALUES.core.account.Get()),
                    'CLOUDSDK_PROJECT':
                    project,
                    'CLOUDSDK_USER_AGENT':
                    # Cloud SDK prefix + user agent string
                    '{} {}'.format(config.CLOUDSDK_USER_AGENT,
                                   transport.MakeUserAgentString()),
                }),
            show_exec_error=args.show_exec_error)
        log.debug('Response: %s' % response.stdout)
        log.debug('ErrResponse: %s' % response.stderr)
        return self.OperationResponseHandler(response, args)
Exemple #8
0
def MakeSecureChannel(target):
    """Creates grpc secure channel.

  Args:
    target: str, The server address, for example:
      bigtableadmin.googleapis.com:443.

  Returns:
    grpc.secure channel.
  """

    access_token = cred_store.GetFreshAccessToken()
    # ssl_channel_credentials() loads root certificates from
    # `grpc/_adapter/credentials/roots.pem`.
    transport_creds = grpc.ssl_channel_credentials()
    custom_metadata_plugin = _MetadataPlugin(access_token)
    auth_creds = grpc.metadata_call_credentials(custom_metadata_plugin,
                                                name='google_creds')
    channel_creds = grpc.composite_channel_credentials(transport_creds,
                                                       auth_creds)
    command_name = properties.VALUES.metrics.command_name.Get()
    channel_args = (('grpc.primary_user_agent',
                     transport.MakeUserAgentString(command_name)), )
    return grpc.secure_channel(target, channel_creds, options=channel_args)
def _GetUserAgentHeader():
    """Returns the user agent headers to be used."""
    user_agent = core_transport.MakeUserAgentString()
    return [('user-agent', config.CLOUDSDK_USER_AGENT + ' ' + user_agent)]
Exemple #10
0
def MakeRequest(url, command_path):
    """Gets the request object for the given URL using the requests library.

  If the URL is for cloud storage and we get a 403, this will try to load the
  active credentials and use them to authenticate the download.

  Args:
    url: str, the URL to download.
    command_path: str, the command path to include in the User-Agent header if
      the URL is HTTP.

  Raises:
    AuthenticationError: If this download requires authentication and there
      are no credentials or the credentials do not have access.

  Returns:
    requests.Response object
  """
    if url.startswith(ComponentInstaller.GCS_BROWSER_DL_URL):
        url = url.replace(ComponentInstaller.GCS_BROWSER_DL_URL,
                          ComponentInstaller.GCS_API_DL_URL, 1)
    headers = {
        b'Cache-Control':
        b'no-cache',
        b'User-Agent':
        http_encoding.Encode(transport.MakeUserAgentString(command_path))
    }
    timeout = TIMEOUT_IN_SEC
    if command_path == UPDATE_MANAGER_COMMAND_PATH:
        timeout = UPDATE_MANAGER_TIMEOUT_IN_SEC

    try:
        return _RawRequest(url, headers=headers, timeout=timeout)
    except requests.exceptions.HTTPError as e:
        if e.response.status_code != 403 or not e.response.url.startswith(
                ComponentInstaller.GCS_API_DL_URL):
            raise e
        try:
            creds = store.LoadFreshCredential(use_google_auth=True)
            creds.apply(headers)
        except creds_exceptions.Error as e:
            # If we fail here, it is because there are no active credentials or the
            # credentials are bad.
            raise AuthenticationError(
                'This component requires valid credentials to install.', e)
        try:
            # Retry the download using the credentials.
            return _RawRequest(url, headers=headers, timeout=timeout)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code != 403:
                raise e
            # If we fail again with a 403, that means we used the credentials, but
            # they didn't have access to the resource.
            raise AuthenticationError(
                """\
Account [{account}] does not have permission to install this component.  Please
ensure that this account should have access or run:

$ gcloud config set account `ACCOUNT`

to choose another account.""".format(
                    account=properties.VALUES.core.account.Get()), e)