コード例 #1
0
def LogSurveyAnswers(survey_instance):
  """Sends survey response to clearcut table."""
  http_client = requests.GetSession()
  headers = {'user-agent': metrics.GetUserAgent()}
  body = json.dumps(_ClearcutRequest(survey_instance), sort_keys=True)
  response = http_client.request(
      'POST', _CLEARCUT_ENDPOINT, data=body, headers=headers)
  if response.status_code != httplib.OK:
    raise SurveyNotRecordedError(
        'We cannot record your feedback at this time, please try again later.')
  _UpdateSurveyCache()
  log.err.Print('Your response is submitted.')
コード例 #2
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]
コード例 #3
0
    def Run(self, args):
        tfplan_to_cai_operation = TerraformToolsTfplanToCaiOperation()
        validate_cai_operation = TerraformToolsValidateOperation()
        validate_tfplan_operation = TerraformToolsValidateOperation()

        env_vars = {
            'GOOGLE_OAUTH_ACCESS_TOKEN':
            GetFreshAccessToken(account=properties.VALUES.core.account.Get()),
            'USE_STRUCTURED_LOGGING':
            'true',
            'GOOGLE_TERRAFORM_VALIDATOR_USERAGENT_EXTENSION':
            metrics.GetUserAgent(),
        }

        with files.TemporaryDirectory() as tempdir:
            cai_assets = os.path.join(tempdir, 'cai_assets.json')

            response = tfplan_to_cai_operation(
                command='tfplan-to-cai',
                project=args.project or properties.VALUES.core.project.Get(),
                terraform_plan_json=args.terraform_plan_json,
                verbosity=args.verbosity,
                output_path=cai_assets,
                env=env_vars)
            self.exit_code = response.exit_code
            if self.exit_code > 0:
                # The streaming binary backed operation handles its own writing to
                # stdout and stderr, so there's nothing left to do here.
                return None

            with progress_tracker.ProgressTracker(
                    message='Validating resources',
                    aborted_message='Aborted validation.'):
                cai_response = validate_cai_operation(
                    command='validate-cai',
                    policy_library=args.policy_library,
                    input_file=cai_assets,
                    verbosity=args.verbosity,
                    env=env_vars)
                tfplan_response = validate_tfplan_operation(
                    command='validate-tfplan',
                    policy_library=args.policy_library,
                    input_file=args.terraform_plan_json,
                    verbosity=args.verbosity,
                    env=env_vars)

        # exit code 2 from a validate_* command indicates violations; we need to
        # pass that through to users so they can detect this case. However, if
        # either command errors out (exit code 1) return that instead.
        if cai_response.exit_code == 1 or tfplan_response.exit_code == 1:
            self.exit_code = 1
        elif cai_response.exit_code == 2 or tfplan_response.exit_code == 2:
            self.exit_code = 2

        # Output from validate commands uses "structured output", same as the
        # streaming output from conversion. The final output should be a combined
        # list of violations.
        violations = []

        for policy_type, response in (('CAI', cai_response),
                                      ('Terraform', tfplan_response)):
            if response.stdout:
                try:
                    msg = binary_operations.ReadStructuredOutput(
                        response.stdout, as_json=True)
                except binary_operations.StructuredOutputError:
                    log.warning(
                        'Could not parse {} policy validation output.'.format(
                            policy_type))
                else:
                    violations += msg.resource_body
            if response.stderr:
                handler = binary_operations.DefaultStreamStructuredErrHandler(
                    None)
                for line in response.stderr.split('\n'):
                    handler(line)

        return violations