Exemplo n.º 1
0
 def testIsFromShellScript(self):
     self.StartObjectPatch(
         platforms.OperatingSystem,
         'Current').return_value = platforms.OperatingSystem.LINUX
     self.StartObjectPatch(os, 'getppid').return_value = 12345
     self.StartObjectPatch(os, 'getpgrp').return_value = 12345
     self.assertTrue(console_io.IsRunFromShellScript())
     self.StartObjectPatch(os, 'getpgrp').return_value = 12346
     self.assertFalse(console_io.IsRunFromShellScript())
     self.StartObjectPatch(
         platforms.OperatingSystem,
         'Current').return_value = platforms.OperatingSystem.WINDOWS
     self.assertFalse(console_io.IsRunFromShellScript())
Exemplo n.º 2
0
def MakeUserAgentString(cmd_path=None):
    """Return a user-agent string for this request.

  Contains 'gcloud' in addition to several other product IDs used for tracing in
  metrics reporting.

  Args:
    cmd_path: str representing the current command for tracing.

  Returns:
    str, User Agent string.
  """
    return (
        'gcloud/{version}'
        ' command/{cmd}'
        ' invocation-id/{inv_id}'
        ' environment/{environment}'
        ' environment-version/{env_version}'
        ' interactive/{is_interactive}'
        ' from-script/{from_script}'
        ' python/{py_version}'
        ' term/{term}'
        ' {ua_fragment}').format(
            version=config.CLOUD_SDK_VERSION.replace(' ', '_'),
            cmd=(cmd_path or properties.VALUES.metrics.command_name.Get()),
            inv_id=uuid.uuid4().hex,
            environment=properties.GetMetricsEnvironment(),
            env_version=properties.VALUES.metrics.environment_version.Get(),
            is_interactive=console_io.IsInteractive(error=True,
                                                    heuristic=True),
            py_version=platform.python_version(),
            ua_fragment=platforms.Platform.Current().UserAgentFragment(),
            from_script=console_io.IsRunFromShellScript(),
            term=console_attr.GetConsoleAttr().GetTermIdentifier())
Exemplo n.º 3
0
def MaybePrintSttUiLink(request):
  """Print Url to the Speech-to-text UI console for given recognize request."""
  if (console_io.IsRunFromShellScript() or
      properties.VALUES.core.disable_prompts.GetBool()):
    return
  audio_uri = request.audio.uri
  if not audio_uri:
    return
  payload = {
      'audio':
          urllib.parse.quote_plus(
              audio_uri[5:] if audio_uri.startswith('gs://') else audio_uri),
      'encoding':
          request.config.encoding,
      'model':
          request.config.model,
      'locale':
          request.config.languageCode,
      'sampling':
          request.config.sampleRateHertz,
      'channels':
          request.config.audioChannelCount,
      'enhanced':
          request.config.useEnhanced,
  }

  params = ';'.join('{}={}'.format(key, value)
                    for (key, value) in sorted(payload.items())
                    if value and ('unspecified' not in str(value).lower()))
  url_tuple = ('https', 'console.cloud.google.com',
               '/speech/transcriptions/create', params, '', '')
  target_url = urllib.parse.urlunparse(url_tuple)
  log.status.Print(
      'Try this using the Speech-to-Text UI at {}'.format(target_url))
  def __init__(self):
    hostname = socket.gethostname()
    install_type = 'Google' if hostname.endswith('.google.com') else 'External'

    current_platform = platforms.Platform.Current()

    self.client_id = config.GetCID()
    self.current_platform = current_platform
    self.user_agent = GetUserAgent(current_platform)
    self.release_channel = config.INSTALLATION_CONFIG.release_channel
    self.install_type = install_type
    self.metrics_environment = properties.GetMetricsEnvironment()
    self.is_interactive = console_io.IsInteractive(error=True, heuristic=True)
    self.python_version = platform.python_version()
    self.metrics_environment_version = (properties.VALUES
                                        .metrics.environment_version.Get())
    self.is_run_from_shell_script = console_io.IsRunFromShellScript()
    self.term_identifier = console_attr.GetConsoleAttr().GetTermIdentifier()
Exemplo n.º 5
0
  def __init__(self, ga_tid=_GA_TID):
    """Initialize a new MetricsCollector.

    This should only be invoked through the static GetCollector() function or
    the static ResetCollectorInstance() function.

    Args:
      ga_tid: The Google Analytics tracking ID to use for metrics collection.
              Defaults to _GA_TID.
    """
    current_platform = platforms.Platform.Current()
    self._user_agent = _MetricsCollector._GetUserAgent(current_platform)
    self._async_popen_args = current_platform.AsyncPopenArgs()
    self._project_ids = {}

    hostname = socket.gethostname()
    install_type = 'Google' if hostname.endswith('.google.com') else 'External'
    cid = _MetricsCollector._GetCID()

    # Table of common params to send to both GA and CSI.
    # First column is GA name, second column is CSI name, third is the value.
    common_params = [
        ('cd1', 'release_channel', config.INSTALLATION_CONFIG.release_channel),
        ('cd2', 'install_type', install_type),
        ('cd3', 'environment', properties.GetMetricsEnvironment()),
        ('cd4', 'interactive', console_io.IsInteractive(error=True,
                                                        heuristic=True)),
        ('cd5', 'python_version', platform.python_version()),
        # cd6 passed as argument to _GAEvent - cd6 = Flag Names
        ('cd7', 'environment_version',
         properties.VALUES.metrics.environment_version.Get()),
        ('cd12', 'from_script', console_io.IsRunFromShellScript()),
        # cd8 passed as argument to _GAEvent - cd8 = Error
        # cd9 passed as argument to _GAEvent - cd9 = Error Extra Info
    ]

    self._ga_event_params = [
        ('v', '1'),
        ('tid', ga_tid),
        ('cid', cid),
        ('t', 'event')]
    self._ga_event_params.extend(
        [(param[0], param[2]) for param in common_params])
    self._ga_events = []

    self._ga_timing_params = [
        ('v', '1'),
        ('tid', ga_tid),
        ('cid', cid),
        ('t', 'timing')]
    self._ga_timing_params.extend(
        [(param[0], param[2]) for param in common_params])

    cloud_sdk_version = config.CLOUD_SDK_VERSION
    self._csi_params = [('s', _CSI_ID),
                        ('v', '2'),
                        ('rls', cloud_sdk_version),
                        ('c', cid)]
    self._csi_params.extend([(param[1], param[2]) for param in common_params])
    self._timer = _CommandTimer()

    self._clearcut_request_params = {
        'client_info': {
            'client_type': 'DESKTOP',
            'desktop_client_info': {
                'os': current_platform.operating_system.id
            }
        },
        'log_source_name': 'CONCORD',
        'zwieback_cookie': cid,
    }
    self._clearcut_concord_event_params = {
        'release_version': cloud_sdk_version,
        'console_type': 'CloudSDK',
    }
    self._clearcut_concord_event_metadata = [
        {'key': param[1], 'value': str(param[2])} for param in common_params]
    self._clearcut_concord_timed_events = []

    self._metrics = []

    # Tracking the level so we can only report metrics for the top level action
    # (and not other actions executed within an action). Zero is the top level.
    self._action_level = 0

    log.debug('Metrics collector initialized...')