コード例 #1
0
  def Run(self, args):
    """Create or Update service from YAML."""
    conn_context = connection_context.GetConnectionContext(
        args, self.ReleaseTrack())

    with serverless_operations.Connect(conn_context) as client:
      new_service = service.Service(
          messages_util.DictToMessageWithErrorCheck(
              args.FILE, client.messages_module.Service),
          client.messages_module)

      # If managed, namespace must match project (or will default to project if
      # not specified).
      # If not managed, namespace simply must not conflict if specified in
      # multiple places (or will default to "default" if not specified).
      namespace = args.CONCEPTS.namespace.Parse().Name()  # From flag or default
      if new_service.metadata.namespace is not None:
        if (args.IsSpecified('namespace') and
            namespace != new_service.metadata.namespace):
          raise exceptions.ConfigurationError(
              'Namespace specified in file does not match passed flag.')
        namespace = new_service.metadata.namespace
        project = properties.VALUES.core.project.Get()
        if flags.IsManaged(args) and namespace != project:
          raise exceptions.ConfigurationError(
              'Namespace must be [{}] for Cloud Run (fully managed).'.format(
                  project))
      new_service.metadata.namespace = namespace

      changes = [config_changes.ReplaceServiceChange(new_service)]
      service_ref = resources.REGISTRY.Parse(
          new_service.metadata.name,
          params={'namespacesId': namespace},
          collection='run.namespaces.services')
      original_service = client.GetService(service_ref)

      pretty_print.Info(deploy.GetStartDeployMessage(conn_context, service_ref))

      deployment_stages = stages.ServiceStages()
      header = (
          'Deploying...' if original_service else 'Deploying new service...')
      with progress_tracker.StagedProgressTracker(
          header,
          deployment_stages,
          failure_message='Deployment failed',
          suppress_output=args.async_) as tracker:
        client.ReleaseService(
            service_ref,
            changes,
            tracker,
            asyn=args.async_,
            allow_unauthenticated=None,
            for_replace=True)
      if args.async_:
        pretty_print.Success(
            'Service [{{bold}}{serv}{{reset}}] is deploying '
            'asynchronously.'.format(serv=service_ref.servicesId))
      else:
        pretty_print.Success(deploy.GetSuccessMessageForSynchronousDeploy(
            client, service_ref))
コード例 #2
0
    def CreateDomainMapping(self, domain_mapping_ref, service_name):
        """Create a domain mapping.

    Args:
      domain_mapping_ref: Resource, domainmapping resource.
      service_name: str, the service to which to map domain.

    Returns:
      A domain_mapping.DomainMapping object.
    """
        messages = self._messages_module
        new_mapping = domain_mapping.DomainMapping.New(
            self._client, domain_mapping_ref.namespacesId)
        new_mapping.name = domain_mapping_ref.domainmappingsId
        new_mapping.route_name = service_name

        request = messages.RunNamespacesDomainmappingsCreateRequest(
            domainMapping=new_mapping.Message(),
            parent=domain_mapping_ref.Parent().RelativeName())
        with metrics.RecordDuration(metric_names.CREATE_DOMAIN_MAPPING):
            response = self._client.namespaces_domainmappings.Create(request)

        # 'run domain-mappings create' is synchronous. Poll for its completion.
        getter = functools.partial(self.GetDomainMapping, domain_mapping_ref)
        with progress_tracker.StagedProgressTracker(
                'Creating...',
                stages.DomainMappingStages(),
                failure_message='Domain mapping failed') as tracker:
            self.WaitForCondition(DomainMappingConditionPoller(
                getter, tracker))
        return domain_mapping.DomainMapping(response, messages)
コード例 #3
0
  def Run(self, args):
    """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
    # TODO(b/143898356) Begin code that should be in Args
    resource_printer.RegisterFormatter(
        traffic_printer.TRAFFIC_PRINTER_FORMAT,
        traffic_printer.TrafficPrinter)
    args.GetDisplayInfo().AddFormat('traffic')
    # End code that should be in Args

    conn_context = connection_context.GetConnectionContext(
        args, flags.Product.RUN, self.ReleaseTrack())
    service_ref = flags.GetService(args)

    changes = flags.GetConfigurationChanges(args)
    if not changes:
      raise exceptions.NoConfigurationChangeError(
          'No traffic configuration change requested.')

    is_managed = flags.GetPlatform() == flags.PLATFORM_MANAGED
    with serverless_operations.Connect(conn_context) as client:
      deployment_stages = stages.UpdateTrafficStages()
      try:
        with progress_tracker.StagedProgressTracker(
            'Updating traffic...',
            deployment_stages,
            failure_message='Updating traffic failed',
            suppress_output=args.async_) as tracker:
          client.UpdateTraffic(service_ref, changes, tracker, args.async_)
      except:
        serv = client.GetService(service_ref)
        if serv:
          resources = traffic_pair.GetTrafficTargetPairs(
              serv.spec_traffic,
              serv.status_traffic,
              is_managed,
              serv.status.latestReadyRevisionName,
              serv.status.url)
          display.Displayer(
              self, args, resources,
              display_info=args.GetDisplayInfo()).Display()
        raise

    if args.async_:
      pretty_print.Success('Updating traffic asynchronously.')
    else:
      serv = client.GetService(service_ref)
      resources = traffic_pair.GetTrafficTargetPairs(
          serv.spec_traffic,
          serv.status_traffic,
          is_managed,
          serv.status.latestReadyRevisionName,
          serv.status.url)
      return resources
コード例 #4
0
    def Run(self, args):
        """Delete a Cloud Run Integration."""
        integration_name = args.name

        conn_context = connection_context.GetConnectionContext(
            args, run_flags.Product.RUN_APPS, self.ReleaseTrack())
        with run_apps_operations.Connect(conn_context) as client:
            with progress_tracker.StagedProgressTracker(
                    'Deleting Integration...',
                    stages.IntegrationDeleteStages(),
                    failure_message='Failed to delete integration.'
            ) as tracker:
                try:
                    integration_type = client.DeleteIntegration(
                        name=integration_name, tracker=tracker)
                except exceptions.IntegrationsOperationError as err:
                    pretty_print.Info(
                        messages_util.GetDeleteErrorMessage(integration_name))
                    raise err
                else:
                    pretty_print.Info('')
                    pretty_print.Success(
                        messages_util.GetSuccessMessage(
                            integration_type=integration_type,
                            integration_name=integration_name,
                            action='deleted'))
コード例 #5
0
    def Run(self, args):
        """Execute a Job on Cloud Run."""
        job_ref = args.CONCEPTS.job.Parse()
        flags.ValidateResource(job_ref)
        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        with serverless_operations.Connect(conn_context) as operations:
            with progress_tracker.StagedProgressTracker(
                    'Creating execution...',
                    stages.ExecutionStages(include_completion=args.wait),
                    failure_message='Executing job failed',
                    suppress_output=args.async_) as tracker:
                e = operations.RunJob(job_ref,
                                      args.wait,
                                      tracker,
                                      asyn=args.async_)

            if args.async_:
                pretty_print.Success(
                    'Execution [{{bold}}{execution}{{reset}}] is being'
                    ' started asynchronously.'.format(execution=e.name))
            else:
                operation = 'completed' if args.wait else 'started running'

                pretty_print.Success(
                    'Execution [{{bold}}{execution}{{reset}}] has '
                    'successfully {operation}.'.format(execution=e.name,
                                                       operation=operation))

            log.status.Print(
                messages_util.GetExecutionCreatedMessage(
                    self.ReleaseTrack(), e))
            return e
コード例 #6
0
    def Run(self, args):
        """Update the service resource.

       Different from `deploy` in that it can only update the service spec but
       no IAM or Cloud build changes.

    Args:
      args: Args!
    Returns:
      googlecloudsdk.api_lib.run.Service, the updated service
    """
        changes = flags.GetServiceConfigurationChanges(args)
        if not changes or (len(changes) == 1 and isinstance(
                changes[0],
                config_changes.SetClientNameAndVersionAnnotationChange)):
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`, '
                '`--image`?')
        changes.insert(
            0,
            config_changes.DeleteAnnotationChange(
                k8s_object.BINAUTHZ_BREAKGLASS_ANNOTATION))
        changes.append(
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack()))

        conn_context = connection_context.GetConnectionContext(
            args, flags.Product.RUN, self.ReleaseTrack())
        service_ref = args.CONCEPTS.service.Parse()
        flags.ValidateResource(service_ref)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            resource_change_validators.ValidateClearVpcConnector(service, args)
            has_latest = (service is None or traffic.LATEST_REVISION_KEY
                          in service.spec_traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                service = client.ReleaseService(service_ref,
                                                changes,
                                                tracker,
                                                asyn=args.async_,
                                                prefetch=service)

            if args.async_:
                pretty_print.Success(
                    'Service [{{bold}}{serv}{{reset}}] is deploying '
                    'asynchronously.'.format(serv=service.name))
            else:
                service = client.GetService(service_ref)
                pretty_print.Success(
                    messages_util.GetSuccessMessageForSynchronousDeploy(
                        service))
            return service
コード例 #7
0
  def Run(self, args):
    """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
    conn_context = connection_context.GetConnectionContext(
        args, flags.Product.RUN, self.ReleaseTrack())
    service_ref = args.CONCEPTS.service.Parse()
    flags.ValidateResource(service_ref)

    changes = flags.GetServiceConfigurationChanges(args)
    if not changes:
      raise exceptions.NoConfigurationChangeError(
          'No traffic configuration change requested.')
    changes.insert(
        0,
        config_changes.DeleteAnnotationChange(
            k8s_object.BINAUTHZ_BREAKGLASS_ANNOTATION))
    changes.append(
        config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack()))

    is_managed = platforms.GetPlatform() == platforms.PLATFORM_MANAGED
    with serverless_operations.Connect(conn_context) as client:
      deployment_stages = stages.UpdateTrafficStages()
      try:
        with progress_tracker.StagedProgressTracker(
            'Updating traffic...',
            deployment_stages,
            failure_message='Updating traffic failed',
            suppress_output=args.async_) as tracker:
          client.UpdateTraffic(service_ref, changes, tracker, args.async_)
      except:
        serv = client.GetService(service_ref)
        if serv:
          resources = traffic_pair.GetTrafficTargetPairs(
              serv.spec_traffic,
              serv.status_traffic,
              is_managed,
              serv.status.latestReadyRevisionName,
              serv.status.url)
          display.Displayer(
              self, args, resources,
              display_info=args.GetDisplayInfo()).Display()
        raise

      if args.async_:
        pretty_print.Success('Updating traffic asynchronously.')
      else:
        serv = client.GetService(service_ref)
        resources = traffic_pair.GetTrafficTargetPairs(
            serv.spec_traffic,
            serv.status_traffic,
            is_managed,
            serv.status.latestReadyRevisionName,
            serv.status.url)
        return resources
コード例 #8
0
 def testNoOp(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.OFF.name)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False):
     pass
   self.AssertErrEquals('')
コード例 #9
0
 def WaitForCondition(self, getter):
   """Wait for a configuration to be ready in latest revision."""
   stages = _ServiceStages()
   with progress_tracker.StagedProgressTracker(
       'Deploying...',
       stages.values(),
       failure_message='Deployment failed') as tracker:
     config_poller = ConditionPoller(getter, tracker, stages, dependencies={
         'RoutesReady': {'ConfigurationsReady'},
     })
     try:
       conditions = waiter.PollUntilDone(
           config_poller, None,
           wait_ceiling_ms=1000)
     except retry.RetryException as err:
       conditions = config_poller.GetConditions()
       # err.message already indicates timeout. Check ready_cond_type for more
       # information.
       msg = conditions.DescriptiveMessage() if conditions else None
       if msg:
         log.error('Still waiting: {}'.format(msg))
       raise err
     if not conditions.IsReady():
       raise serverless_exceptions.ConfigurationError(
           conditions.DescriptiveMessage())
コード例 #10
0
 def testProgressTracker(self):
   clear_width = self.SetConsoleSize(30) - 1
   with progress_tracker.StagedProgressTracker(
       'tracker',
       self.stages,
       success_message='Goodbye.',
       autotick=False) as spt:
     spt.StartStage(self.keys[0])
     spt.Tick()
     self.AssertErrContains(
         '\r' + ' ' * clear_width + '\r'
         'tracker'
         '\r' + ' ' * clear_width + '\r'
         'tracker\n'
         '\r' + ' ' * clear_width + '\r'
         '  Hello World.../')
     spt.CompleteStage(self.keys[0])
   self.AssertErrEquals(
       '\r' + ' ' * clear_width + '\r'
       'tracker'
       '\r' + ' ' * clear_width + '\r'
       'tracker\n'
       '\r' + ' ' * clear_width + '\r'
       '  Hello World.../'
       '\r' + ' ' * clear_width + '\r'
       '  Hello World...-'
       '\r' + ' ' * clear_width + '\r'
       '  Hello World...done'
       '\r' + ' ' * clear_width + '\r'
       '  Hello World...done\n'
       '\r' + ' ' * clear_width + '\r'
       'Goodbye.\n')
コード例 #11
0
ファイル: operator.py プロジェクト: saranraju90/multik8s
def install_eventing_via_operator(client, track):
  """Install eventing cluster by enabling it via the KubeRun operator.

  Attempt to determine whether KubeRun or CloudRun operator is installed by
    presence of the corresponding operator resource or namespace.

  Args:
    client: An api_tools client.
    track: base.ReleaseTrack, the release (ga, beta, alpha) the command is in.
  """
  namespaces_list = client.ListNamespaces()

  # If not found, then None.
  operator_obj = client.GetKubeRun()

  if operator_obj is not None and track == base.ReleaseTrack.ALPHA:
    # KubeRun operator resource is cluster-scoped so must directly fetch.
    operator_type = events_constants.Operator.KUBERUN
  elif 'cloud-run-system' in namespaces_list:
    # CloudRun operator installed inferred by presence of CR operator namespace.
    operator_obj = client.GetCloudRun()
    operator_type = events_constants.Operator.CLOUDRUN
  else:
    # Neither operator installed.
    operator_type = events_constants.Operator.NONE
    init_shared.prompt_if_can_prompt(
        'Unable to find the CloudRun resource to install Eventing. '
        'Eventing will not be installed. '
        'Would you like to continue anyway?')
    if ('cloud-run-events' in namespaces_list or
        'events-system' in namespaces_list):
      # Neither operator installed, but OSS knative eventing found.
      log.status.Print('OSS eventing already installed.')
    else:
      # Neither operator installed, nor is OSS knative eventing installed.
      raise exceptions.EventingInstallError('Eventing not installed.')

  if operator_obj is None:
    return

  tracker_stages = stages.EventingStages()

  # Enable eventing or wait for operator to finish installing eventing.
  with progress_tracker.StagedProgressTracker(
      'Waiting on eventing installation...'
      if operator_obj.eventing_enabled else 'Enabling eventing...',
      tracker_stages,
      failure_message='Failed to enable eventing') as tracker:

    if not operator_obj.eventing_enabled:
      _update_operator_with_eventing_enabled(client, operator_type)

    # Wait for Operator to enable eventing
    _poll_operator_resource(client, operator_type, tracker)

    if operator_obj.eventing_enabled:
      log.status.Print('Eventing already enabled.')
    else:
      log.status.Print('Enabled eventing successfully.')
コード例 #12
0
  def Run(self, args):
    """Deploy a container to Cloud Run."""
    service_ref = flags.GetService(args)
    image = args.image
    # Build an image from source if source specified.
    if flags.FlagIsExplicitlySet(args, 'source'):
      # Create a tag for the image creation
      if image is None and not args.IsSpecified('config'):
        image = 'gcr.io/{projectID}/cloud-run-source-deploy/{service}:{tag}'.format(
            projectID=properties.VALUES.core.project.Get(required=True),
            service=service_ref.servicesId,
            tag=uuid.uuid4().hex)
      messages = cloudbuild_util.GetMessagesModule()
      build_config = submit_util.CreateBuildConfig(
          image, args.no_cache, messages, args.substitutions, args.config,
          args.IsSpecified('source'), False, args.source,
          args.gcs_source_staging_dir, args.ignore_file, args.gcs_log_dir,
          args.machine_type, args.disk_size)
      submit_util.Build(messages, args.async_, build_config)

    # Deploy a container with an image
    conn_context = connection_context.GetConnectionContext(
        args, flags.Product.RUN, self.ReleaseTrack())
    config_changes = flags.GetConfigurationChanges(args)

    with serverless_operations.Connect(conn_context) as operations:
      image_change = config_changes_mod.ImageChange(image)
      changes = [image_change]
      if config_changes:
        changes.extend(config_changes)
      service = operations.GetService(service_ref)
      allow_unauth = GetAllowUnauth(args, operations, service_ref, service)

      pretty_print.Info(GetStartDeployMessage(conn_context, service_ref))
      has_latest = (service is None or
                    traffic.LATEST_REVISION_KEY in service.spec_traffic)
      deployment_stages = stages.ServiceStages(
          include_iam_policy_set=allow_unauth is not None,
          include_route=has_latest)
      header = 'Deploying...' if service else 'Deploying new service...'
      with progress_tracker.StagedProgressTracker(
          header,
          deployment_stages,
          failure_message='Deployment failed',
          suppress_output=args.async_) as tracker:
        operations.ReleaseService(
            service_ref,
            changes,
            tracker,
            asyn=args.async_,
            allow_unauthenticated=allow_unauth,
            prefetch=service)
      if args.async_:
        pretty_print.Success(
            'Service [{{bold}}{serv}{{reset}}] is deploying '
            'asynchronously.'.format(serv=service_ref.servicesId))
      else:
        pretty_print.Success(GetSuccessMessageForSynchronousDeploy(
            operations, service_ref))
コード例 #13
0
ファイル: update.py プロジェクト: superina5/first_app
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        if conn_context.supports_one_platform:
            flags.VerifyOnePlatformFlags(args)
        else:
            flags.VerifyGKEFlags(args)

        with serverless_operations.Connect(conn_context) as client:
            changes = flags.GetConfigurationChanges(args)
            endpoint_visibility = flags.GetEndpointVisibility(args)
            allow_unauth = None
            if conn_context.supports_one_platform:
                allow_unauth = flags.GetAllowUnauthenticated(
                    args, client, service_ref)
            if not changes and endpoint_visibility is None and allow_unauth is None:
                raise exceptions.NoConfigurationChangeError(
                    'No configuration change requested. '
                    'Did you mean to include the flags `--update-env-vars`, '
                    '`--memory`, `--concurrency`, `--timeout`, `--connectivity`, '
                    'or `--allow-unauthenticated`?')
            deployment_stages = stages.ServiceStages(allow_unauth is not None)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args. async) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args. async,
                                      private_endpoint=endpoint_visibility,
                                      allow_unauthenticated=allow_unauth)
            if args. async:
                pretty_print.Success('Deploying asynchronously.')
            else:
                url = client.GetServiceUrl(service_ref)
                active_revs = client.GetActiveRevisions(service_ref)

                msg = (
                    '{{bold}}Service [{serv}] revision{plural} {rev_msg} is active'
                    ' and serving traffic at{{reset}} {url}')

                rev_msg = ' '.join(['[{}]'.format(rev) for rev in active_revs])

                msg = msg.format(serv=service_ref.servicesId,
                                 plural='s' if len(active_revs) > 1 else '',
                                 rev_msg=rev_msg,
                                 url=url)

                pretty_print.Success(msg)
コード例 #14
0
 def testMapNature(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.OFF.name)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False) as tracker:
     self.assertEqual(tracker[self.keys[0]], self.stages[0])
     self.assertEqual(list(tracker.keys()), self.keys)
   self.AssertErrEquals('')
コード例 #15
0
 def testStubNoStages(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.TESTING.name)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False):
     pass
   self.AssertErrEquals('{"ux": "STAGED_PROGRESS_TRACKER", "message": '
                        '"tracker", "status": "SUCCESS"}\n')
コード例 #16
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`?')

        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.RUN)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            has_latest = (service is None
                          or traffic.LATEST_REVISION_KEY in service.traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args.async_,
                                      prefetch=service)
            if args.async_:
                pretty_print.Success('Deploying asynchronously.')
            else:
                service = client.GetService(service_ref)
                latest_ready = service.status.latestReadyRevisionName
                latest_percent_traffic = sum(
                    target.percent for target in service.status.traffic
                    if target.latestRevision or (
                        latest_ready and target.revisionName == latest_ready))
                msg = (
                    'Service [{{bold}}{serv}{{reset}}] '
                    'revision [{{bold}}{rev}{{reset}}] '
                    'has been deployed and is serving '
                    '{{bold}}{latest_percent_traffic}{{reset}} percent of traffic'
                )
                if latest_percent_traffic:
                    msg += (' at {{bold}}{url}{{reset}}')
                msg = msg.format(serv=service_ref.servicesId,
                                 rev=latest_ready,
                                 url=service.domain
                                 if 'domain' in dir(service) else service.url,
                                 latest_percent_traffic=latest_percent_traffic)
                pretty_print.Success(msg)
コード例 #17
0
 def testProgressTrackerUpdatingCompletedStage(self):
   self.console_size_mock.return_value = (0, 'unused size')
   with self.assertRaisesRegex(
       ValueError, 'This stage has already completed.'):
     with progress_tracker.StagedProgressTracker(
         'tracker', self.stages, autotick=False) as spt:
       spt.StartStage(self.keys[0])
       spt.CompleteStage(self.keys[0])
       spt.StartStage(self.keys[0])
コード例 #18
0
def _GetProgressTracker(patch_job_name):
  stages = [
      progress_tracker.Stage(
          'Generating instance details...', key='pre-summary'),
      progress_tracker.Stage(
          'Reporting instance details...', key='with-summary')
  ]
  return progress_tracker.StagedProgressTracker(
      message='Executing patch job [{0}]'.format(patch_job_name), stages=stages)
コード例 #19
0
    def Run(self, args):
        """Update configuration information about the service.

    Does not change the running code.

    Args:
      args: Args!
    """
        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No configuration change requested. '
                'Did you mean to include the flags `--update-env-vars`, '
                '`--memory`, `--concurrency`, `--timeout`, `--connectivity`?')

        conn_context = connection_context.GetConnectionContext(
            args, product=connection_context.Product.RUN)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            service = client.GetService(service_ref)
            has_latest = (service is None
                          or traffic.LATEST_REVISION_KEY in service.traffic)
            deployment_stages = stages.ServiceStages(
                include_iam_policy_set=False, include_route=has_latest)
            with progress_tracker.StagedProgressTracker(
                    'Deploying...',
                    deployment_stages,
                    failure_message='Deployment failed',
                    suppress_output=args.async_) as tracker:
                client.ReleaseService(service_ref,
                                      changes,
                                      tracker,
                                      asyn=args.async_,
                                      prefetch=service)
            if args.async_:
                pretty_print.Success('Deploying asynchronously.')
            else:
                service = client.GetService(service_ref)
                active_revs = client.GetActiveRevisions(service_ref)

                msg = (
                    'Service [{{bold}}{serv}{{reset}}] revision{plural} {rev_msg} '
                    'is active and serving traffic at {{bold}}{url}{{reset}}')

                rev_msg = ' '.join([
                    '[{{bold}}{}{{reset}}]'.format(rev) for rev in active_revs
                ])

                msg = msg.format(serv=service_ref.servicesId,
                                 plural='s' if len(active_revs) > 1 else '',
                                 rev_msg=rev_msg,
                                 url=service.domain
                                 if 'domain' in dir(service) else service.url)

                pretty_print.Success(msg)
コード例 #20
0
 def testProgressTrackerStageDoesNotBelong(self, start_stage, update_stage,
                                           complete_stage):
   self.console_size_mock.return_value = (0, 'unused size')
   with self.assertRaisesRegex(
       ValueError, 'This stage does not belong to this progress tracker.'):
     with progress_tracker.StagedProgressTracker(
         'tracker', [self.stages[0]], autotick=False) as spt:
       spt.StartStage(self.keys[start_stage])
       spt.UpdateStage(self.keys[update_stage], 'new message')
       spt.CompleteStage(self.keys[complete_stage])
コード例 #21
0
 def testProgressTrackerZeroWidth(self):
   # To simulate pseudo-TTY
   self.console_size_mock.return_value = (0, 'unused size')
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False) as spt:
     spt.StartStage(self.keys[0])
     spt.CompleteStage(self.keys[0])
     spt.Tick()
     spt.Tick()
   self.AssertErrEquals('')
コード例 #22
0
 def testProgressTrackerSpinnersByEncoding(self, encoding, spinners):
   self.SetConsoleSize(30)
   self.SetEncoding(encoding)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False) as spt:
     spt.StartStage(self.keys[0])
     for _ in range(len(spinners)):
       spt.Tick()
   for tick_mark in spinners:
     self.AssertErrContains('  Hello World...' + tick_mark)
コード例 #23
0
 def testStub(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.TESTING.name)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False) as spt:
     spt.StartStage(self.keys[0])
     spt.CompleteStage(self.keys[0])
   self.AssertErrEquals(
       '{"ux": "STAGED_PROGRESS_TRACKER", "message": "tracker", "status": '
       '"SUCCESS", "succeeded_stages": ["Hello World..."]}\n')
コード例 #24
0
def _CreateProgressTracker(patch_job_name):
  """Creates a progress tracker to display patch status synchronously."""
  stages = [
      progress_tracker.Stage(
          'Generating instance details...', key='pre-summary'),
      progress_tracker.Stage(
          'Reporting instance details...', key='with-summary')
  ]
  return progress_tracker.StagedProgressTracker(
      message='Executing patch job [{0}]'.format(patch_job_name), stages=stages)
コード例 #25
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)
    if conn_context.supports_one_platform:
      raise exceptions.UnsupportedArgumentError(
          'Events are only available with Cloud Run for Anthos.')

    trigger_ref = args.CONCEPTS.trigger.Parse()
    namespace_ref = trigger_ref.Parent()
    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      event_type = util.EventTypeFromTypeString(source_crds, args.type)
      source_obj = source.Source.New(client.client, namespace_ref.Name(),
                                     event_type.crd.source_kind,
                                     event_type.crd.source_api_category)
      source_obj.name = _SOURCE_NAME_PATTERN.format(
          trigger=trigger_ref.Name())

      trigger_obj = client.GetTrigger(trigger_ref)
      if trigger_obj is not None:
        # If trigger already exists, validate it has the attributes we're trying
        # to set right now.
        try:
          util.ValidateTrigger(trigger_obj, source_obj, event_type)
        except AssertionError:
          raise exceptions.TriggerCreationError(
              'Trigger [{}] already exists with attributes not '
              'matching this event type.'.format(trigger_obj.name))
        # If the trigger has the right attributes, check if there's already
        # a source that matches the attributes as well.
        source_ref = util.GetSourceRef(
            source_obj.name, source_obj.namespace, event_type.crd)
        if client.GetSource(source_ref, event_type.crd) is not None:
          raise exceptions.TriggerCreationError(
              'Trigger [{}] already exists.'.format(trigger_obj.name))

      parameters = events_flags.GetAndValidateParameters(args, event_type)

      # Create the trigger and source
      with progress_tracker.StagedProgressTracker(
          'Initializing trigger...',
          stages.TriggerSourceStages(),
          failure_message='Trigger creation failed') as tracker:
        client.CreateTriggerAndSource(
            trigger_obj,
            trigger_ref,
            namespace_ref,
            source_obj,
            event_type,
            parameters,
            args.broker,
            args.target_service,
            tracker
        )
コード例 #26
0
 def testStubCompletedWithWarningStage(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.TESTING.name)
   with progress_tracker.StagedProgressTracker(
       'tracker', self.stages, autotick=False) as spt:
     spt.StartStage(self.keys[0])
     spt.StartStage(self.keys[1])
     spt.CompleteStageWithWarning(self.keys[0], 'Nooooooo')
     spt.CompleteStage(self.keys[1])
   self.AssertErrEquals(
       '{"ux": "STAGED_PROGRESS_TRACKER", "message": "tracker", '
       '"status": "WARNING", "succeeded_stages": ["Ahhhhhhhhhhhhhhh..."]}\n')
コード例 #27
0
 def testProgressTrackerDoneMessageCallback(self, interactive):
   self._interactive_mock.return_value = interactive
   self.SetConsoleSize(30)
   msg = ''
   done_message_callback = lambda: msg
   with progress_tracker.StagedProgressTracker(
       'tracker',
       self.stages,
       done_message_callback=done_message_callback,
       autotick=False):
     msg = 'For more information...'
   self.AssertErrContains('Done. For more information...\n')
コード例 #28
0
    def Run(self, args):
        """Update the traffic split for the service.

    Args:
      args: Args!

    Returns:
      List of traffic.TrafficTargetStatus instances reflecting the change.
    """
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        if conn_context.supports_one_platform:
            flags.VerifyOnePlatformFlags(args)
        else:
            flags.VerifyGKEFlags(args)

        changes = flags.GetConfigurationChanges(args)
        if not changes:
            raise exceptions.NoConfigurationChangeError(
                'No traffic configuration change requested.')

        self._SetFormat(args)

        with serverless_operations.Connect(conn_context) as client:
            deployment_stages = stages.UpdateTrafficStages()
            try:
                with progress_tracker.StagedProgressTracker(
                        'Updating traffic...',
                        deployment_stages,
                        failure_message='Updating traffic failed',
                        suppress_output=args.async_) as tracker:
                    client.UpdateTraffic(service_ref, changes, tracker,
                                         args.async_)
            except:
                serv = client.GetService(service_ref)
                resources = traffic.GetTrafficTargetPairs(
                    serv.spec.traffic, serv.status.traffic,
                    flags.IsManaged(args), serv.status.latestReadyRevisionName)
                display.Displayer(
                    self, args, resources,
                    display_info=args.GetDisplayInfo()).Display()
                raise

        if args.async_:
            pretty_print.Success('Updating traffic asynchronously.')
        else:
            serv = client.GetService(service_ref)
            resources = traffic.GetTrafficTargetPairs(
                serv.spec.traffic, serv.status.traffic, flags.IsManaged(args),
                serv.status.latestReadyRevisionName)
            return resources
コード例 #29
0
 def testStubFailedStage(self):
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.TESTING.name)
   with self.assertRaises(ValueError):
     with progress_tracker.StagedProgressTracker(
         'tracker', self.stages, autotick=False) as spt:
       spt.StartStage(self.keys[0])
       spt.StartStage(self.keys[1])
       spt.CompleteStage(self.keys[1])
       spt.FailStage(self.keys[0], ValueError())
   self.AssertErrEquals(
       '{"ux": "STAGED_PROGRESS_TRACKER", "message": "tracker", "status": '
       '"FAILURE", "succeeded_stages": ["Ahhhhhhhhhhhhhhh..."], '
       '"failed_stage": "Hello World..."}\n')
コード例 #30
0
ファイル: init.py プロジェクト: piotradamczyk5/gcloud_cli
    def Run(self, args):
        """Executes when the user runs the delete command."""
        if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
            raise exceptions.UnsupportedArgumentError(
                'This command is only available with Cloud Run for Anthos.')
        project = properties.VALUES.core.project.Get(required=True)
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        with eventflow_operations.Connect(conn_context) as client:
            cloud_run_obj = client.GetCloudRun()
            if cloud_run_obj is None:
                pass
            elif cloud_run_obj.eventing_enabled:
                log.status.Print('Eventing already enabled.')
            else:
                tracker_stages = stages.EventingStages()

                # Enable eventing
                with progress_tracker.StagedProgressTracker(
                        'Enabling eventing...',
                        tracker_stages,
                        failure_message='Failed to enable eventing'
                ) as tracker:
                    response = client.UpdateCloudRunWithEventingEnabled()

                    # Wait for Operator to enable eventing
                    client.PollCloudRunResource(tracker)
                    log.status.Print('Enabled eventing successfully.')

            if client.IsClusterInitialized():
                console_io.PromptContinue(
                    message='This cluster has already been initialized.',
                    prompt_string='Would you like to re-run initialization?',
                    cancel_on_no=True)

            _EnableMissingServices(project)

            for sa_config in [
                    _CONTROL_PLANE_SERVICE_ACCOUNT_CONFIG,
                    _BROKER_SERVICE_ACCOUNT_CONFIG,
                    _SOURCES_SERVICE_ACCOUNT_CONFIG
            ]:
                _ConfigureServiceAccount(sa_config, client, args)

            client.MarkClusterInitialized()

        log.status.Print(
            _InitializedMessage(self.ReleaseTrack(),
                                conn_context.cluster_name))