예제 #1
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/{0}'
            ' command/{1}'
            ' invocation-id/{2}'
            ' environment/{3}'
            ' environment-version/{4}'
            ' interactive/{5}'
            ' python/{6}'
            ' {7}').format(
                config.CLOUD_SDK_VERSION.replace(' ', '_'), cmd_path
                or properties.VALUES.metrics.command_name.Get(),
                uuid.uuid4().hex, properties.GetMetricsEnvironment(),
                properties.VALUES.metrics.environment_version.Get(),
                console_io.IsInteractive(error=True, heuristic=True),
                platform.python_version(),
                platforms.Platform.Current().UserAgentFragment())
예제 #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())
예제 #3
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 = 'CloudSDK/{version} {fragment}'.format(
            version=config.CLOUD_SDK_VERSION,
            fragment=current_platform.UserAgentFragment())
        self._async_popen_args = current_platform.AsyncPopenArgs()
        self._project_ids = {}

        hostname = socket.getfqdn()
        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()),
            # cd8 passed as argument to _GAEvent - cd8 = Error
            # cd9 passed as argument to _GAEvent - cd9 = Error Extra Info
        ]

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

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

        self.StartTimer(_GetTimeMillis())
        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...')
예제 #4
0
def _SurveyEnvironment():
  """Gets user's environment."""

  install_type = ('Google' if socket.gethostname().endswith('.google.com') else
                  'External')

  env = {
      'install_type': install_type,
      'cid': metrics.GetCID(),
      'user_agent': metrics.GetUserAgent(),
      'release_channel': config.INSTALLATION_CONFIG.release_channel,
      'python_version': platform.python_version(),
      'environment': properties.GetMetricsEnvironment(),
      'environment_version': properties.VALUES.metrics.environment_version.Get()
  }
  return [{'key': k, 'value': v} for k, v in env.items() if v is not None]
  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()
예제 #6
0
 def UserAgent(self,
               cmd_path,
               invocation_id,
               python_version,
               interactive,
               fromscript=False):
     template = ('gcloud/{0} command/{1} invocation-id/{2} environment/{3} '
                 'environment-version/{4} interactive/{5} from-script/{8} '
                 'python/{6} term/xterm {7}')
     # Mocking the platform fragment doesn't seem to work all the time.
     # Use the real platform we are on.
     platform = platforms.Platform.Current().UserAgentFragment()
     environment = properties.GetMetricsEnvironment()
     environment_version = properties.VALUES.metrics.environment_version.Get(
     )
     user_agent = template.format(config.CLOUD_SDK_VERSION, cmd_path,
                                  invocation_id, environment,
                                  environment_version, interactive,
                                  python_version, platform, fromscript)
     return user_agent
예제 #7
0
 def UserAgent(self,
               version,
               cmd_path,
               invocation_id,
               python_version,
               interactive,
               fromscript=False,
               include_cloudsdk_prefix=True):
   template = ('gcloud/{0} command/{1} invocation-id/{2} environment/{3} '
               'environment-version/{4} interactive/{5} from-script/{8} '
               'python/{6} term/xterm {7}')
   # Mocking the platform fragment doesn't seem to work all the time.
   # Use the real platform we are on.
   platform = platforms.Platform.Current().UserAgentFragment()
   environment = properties.GetMetricsEnvironment()
   environment_version = properties.VALUES.metrics.environment_version.Get()
   user_agent = template.format(
       version, cmd_path, invocation_id, environment, environment_version,
       interactive, python_version, platform, fromscript)
   if include_cloudsdk_prefix:
     user_agent = config.CLOUDSDK_USER_AGENT + ' ' + user_agent
   return user_agent.encode('utf-8')
예제 #8
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...')