Esempio n. 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))
Esempio n. 2
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
Esempio n. 3
0
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)

    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      return [crd for crd in source_crds if crd.event_types]
Esempio n. 4
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
    def Run(self, args):
        self._CheckPlatform()

        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:
            serv = client.GetService(service_ref)
        if not serv:
            raise exceptions.ArgumentError('Cannot find service [{}]'.format(
                service_ref.servicesId))

        bind = '127.0.0.1:' + (args.port if args.port else '8080')
        host = self._GetUrl(serv, args.tag, service_ref.servicesId)

        command_executor = proxy.ProxyWrapper()
        log.Print('Proxying service [{}] in region [{}] locally...'.format(
            service_ref.servicesId, serv.region))
        log.Print('http://{} proxies to {}'.format(bind, host))

        if args.token:
            response = command_executor(host=host, token=args.token, bind=bind)
        else:
            # Keep restarting the proxy with fresh token before the token expires (1h)
            # until hitting a failure.
            while True:
                response = command_executor(host=host,
                                            token=_GetFreshIdToken(),
                                            bind=bind,
                                            duration='55m')
                if response.failed:
                    break

        return self._DefaultOperationResponseHandler(response)
Esempio n. 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
Esempio n. 7
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        trigger_ref = args.CONCEPTS.trigger.Parse()
        with eventflow_operations.Connect(conn_context) as client:
            if client.IsCluster():
                trigger_ref = resources.REGISTRY.Parse(
                    trigger_ref.RelativeName(),
                    collection=util.ANTHOS_TRIGGER_COLLECTION_NAME,
                    api_version=client.api_version)

            trigger_obj = client.GetTrigger(trigger_ref)
            source_obj = None
            if trigger_obj is not None:
                source_crds = client.ListSourceCustomResourceDefinitions()
                source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
                    trigger_obj, source_crds, client.IsCluster())
                if source_ref and source_crd:
                    source_obj = client.GetSource(source_ref, source_crd)

        if not trigger_obj:
            raise exceptions.TriggerNotFound('Trigger [{}] not found.'.format(
                trigger_ref.Name()))
        if not source_obj:
            log.warning('No matching event source for trigger [{}].'.format(
                trigger_ref.Name()))
        return SerializedTriggerAndSource(
            trigger_obj.MakeSerializable(),
            source_obj.MakeSerializable() if source_obj else None)
Esempio n. 8
0
 def Run(self, args):
     """List available configurations."""
     conn_context = connection_context.GetConnectionContext(args)
     namespace_ref = args.CONCEPTS.namespace.Parse()
     with serverless_operations.Connect(conn_context) as client:
         self.SetCompleteApiEndpoint(conn_context.endpoint)
         return client.ListConfigurations(namespace_ref)
Esempio n. 9
0
 def Run(self, args):
   """List available domain mappings."""
   conn_context = connection_context.GetConnectionContext(args)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     self.SetCompleteApiEndpoint(conn_context.endpoint)
     return commands.SortByName(client.ListDomainMappings(namespace_ref))
Esempio n. 10
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
Esempio n. 11
0
 def Run(self, args):
     """List available services."""
     is_managed = flags.GetPlatform() == flags.PLATFORM_MANAGED
     if is_managed and not args.IsSpecified('region'):
         self._SetFormat(args, show_region=True)
         client = global_methods.GetServerlessClientInstance()
         self.SetPartialApiEndpoint(client.url)
         args.CONCEPTS.namespace.Parse()  # Error if no proj.
         # Don't consider region property here, we'll default to all regions
         return commands.SortByName(global_methods.ListServices(client))
     else:
         conn_context = connection_context.GetConnectionContext(
             args, product=flags.Product.RUN)
         self._SetFormat(args,
                         show_region=is_managed,
                         show_namespace=(not is_managed))
         namespace_ref = args.CONCEPTS.namespace.Parse()
         with serverless_operations.Connect(conn_context) as client:
             self.SetCompleteApiEndpoint(conn_context.endpoint)
             if not is_managed:
                 location_msg = ' in [{}]'.format(
                     conn_context.cluster_location)
                 log.status.Print('For cluster [{cluster}]{zone}:'.format(
                     cluster=conn_context.cluster_name,
                     zone=location_msg
                     if conn_context.cluster_location else ''))
             return commands.SortByName(client.ListServices(namespace_ref))
Esempio n. 12
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return [crd for crd in source_crds if crd.event_types]
Esempio n. 13
0
    def Run(self, args):
        """Executes when user runs the init command."""
        if platforms.GetPlatform() == platforms.PLATFORM_MANAGED:
            raise exceptions.UnsupportedArgumentError(
                'This command is only available with Cloud Run for Anthos.')

        kuberun_events_flags.ValidateAuthenticationFlags(args)

        conn_context = connection_context.GetConnectionContext(
            args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

        namespace_ref = args.CONCEPTS.namespace.Parse()

        with eventflow_operations.Connect(conn_context) as client:
            product_type = init_shared.determine_product_type(
                client, args.authentication)

            if not client.GetNamespace(namespace_ref):
                client.CreateNamespace(namespace_ref)

            if args.authentication == events_constants.AUTH_SECRETS:
                client.CreateOrReplaceSourcesSecret(namespace_ref,
                                                    product_type)

        log.status.Print(
            'Initialized namespace [{}] for Cloud Run eventing with '
            'secret {}'.format(namespace_ref.Name(),
                               anthosevents_operations.SOURCES_KEY))
Esempio n. 14
0
  def Run(self, args):
    """Executes when the user runs the delete command."""
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

    trigger_ref = args.CONCEPTS.trigger.Parse()
    console_io.PromptContinue(
        message='Trigger [{}] will be deleted.'.format(trigger_ref.Name()),
        throw_if_unattended=True,
        cancel_on_no=True)

    with eventflow_operations.Connect(conn_context) as client:
      # TODO(b/147308604): Don't delete source when Odin supports ownerRefs
      if serverless_flags.GetPlatform() == serverless_flags.PLATFORM_MANAGED:
        trigger_obj = client.GetTrigger(trigger_ref)
        if trigger_obj is not None:
          source_crds = client.ListSourceCustomResourceDefinitions()
          source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
              trigger_obj, source_crds)
          if source_ref and source_crd:
            # Delete the source before the trigger because we need the trigger
            # to exist to be able to find the source. Otherwise, we could end up
            # losing a reference to the source if trigger deletion succeeds but
            # source deletion fails.
            try:
              client.DeleteSource(source_ref, source_crd)
            except exceptions.SourceNotFound:
              # Source could have been deleted but trigger deletion failed
              # and this command was re-run, which is fine.
              pass
      client.DeleteTrigger(trigger_ref)

    log.DeletedResource(trigger_ref.Name(), 'trigger')
Esempio n. 15
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'))
Esempio n. 16
0
    def Run(self, args):
        """Create a domain mapping."""
        conn_context = connection_context.GetConnectionContext(
            args, product=flags.Product.RUN)
        domain_mapping_ref = args.CONCEPTS.domain.Parse()

        # Check if the provided domain has already been verified
        # if mapping to a non-CRoGKE service
        if flags.GetPlatform() == flags.PLATFORM_MANAGED:
            client = global_methods.GetServerlessClientInstance()
            all_domains = global_methods.ListVerifiedDomains(
                client, flags.GetRegion(args))
            # If not already verified, explain and error out
            if all(d.id not in domain_mapping_ref.Name() for d in all_domains):
                if not all_domains:
                    domains_text = 'You currently have no verified domains.'
                else:
                    domains = ['* {}'.format(d.id) for d in all_domains]
                    domains_text = ('Currently verified domains:\n{}'.format(
                        '\n'.join(domains)))
                raise exceptions.DomainMappingCreationError(
                    'The provided domain does not appear to be verified '
                    'for the current account so a domain mapping '
                    'cannot be created. Visit [{help}] for more information.'
                    '\n{domains}'.format(help=DOMAIN_MAPPINGS_HELP_DOCS_URL,
                                         domains=domains_text))

        with serverless_operations.Connect(conn_context) as client:
            mapping = client.CreateDomainMapping(domain_mapping_ref,
                                                 args.service,
                                                 args.force_override)
            for record in mapping.records:
                record.name = record.name or mapping.route_name
            return mapping.records
Esempio n. 17
0
 def Run(self, args):
   """List available revisions."""
   service_name = args.service
   conn_context = connection_context.GetConnectionContext(args)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     return client.ListRevisions(namespace_ref, service_name)
Esempio n. 18
0
    def Run(self, args):
        """Update environment variables."""
        conn_context = connection_context.GetConnectionContext(args)
        service_ref = flags.GetService(args)

        with serverless_operations.Connect(conn_context) as client:
            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, or --concurrency?')
            client.ReleaseService(service_ref, changes, args. async)
            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)
Esempio n. 19
0
 def Run(self, args):
     """List available services."""
     is_managed = flags.IsManaged(args)
     if is_managed and not getattr(args, 'region', None):
         self._SetFormat(args, show_region=True)
         client = global_methods.GetServerlessClientInstance()
         self.SetPartialApiEndpoint(client.url)
         args.CONCEPTS.namespace.Parse()  # Error if no proj.
         locations_ref = args.CONCEPTS.region.Parse()
         return commands.SortByName(
             global_methods.ListServices(client,
                                         locations_ref.RelativeName()))
     else:
         conn_context = connection_context.GetConnectionContext(args)
         self._SetFormat(args,
                         show_region=is_managed,
                         show_namespace=(not is_managed))
         namespace_ref = args.CONCEPTS.namespace.Parse()
         with serverless_operations.Connect(conn_context) as client:
             self.SetCompleteApiEndpoint(conn_context.endpoint)
             if not is_managed:
                 location_msg = ' in [{}]'.format(
                     conn_context.cluster_location)
                 log.status.Print('For cluster [{cluster}]{zone}:'.format(
                     cluster=conn_context.cluster_name,
                     zone=location_msg
                     if conn_context.cluster_location else ''))
             return commands.SortByName(client.ListServices(namespace_ref))
Esempio n. 20
0
  def Run(self, args):
    """Executes when the user runs the describe command."""
    conn_context = connection_context.GetConnectionContext(
        args, product=connection_context.Product.EVENTS)

    trigger_ref = args.CONCEPTS.trigger.Parse()
    with eventflow_operations.Connect(conn_context) as client:
      trigger_obj = client.GetTrigger(trigger_ref)
      source_obj = None
      if trigger_obj is not None:
        source_crds = client.ListSourceCustomResourceDefinitions()
        source_ref, source_crd = util.GetSourceRefAndCrdForTrigger(
            trigger_obj, source_crds)
        if source_ref and source_crd:
          source_obj = client.GetSource(source_ref, source_crd)

    if not trigger_obj:
      raise exceptions.TriggerNotFound(
          'Trigger [{}] not found.'.format(trigger_ref.Name()))
    if not source_obj:
      log.warning('No matching event source for trigger [{}].'.format(
          trigger_ref.Name()))
    return SerializedTriggerAndSource(
        trigger_obj.MakeSerializable(),
        source_obj.MakeSerializable() if source_obj else None)
Esempio n. 21
0
    def Run(self, args):
        """Executes when the user runs the describe command."""
        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()
        with eventflow_operations.Connect(conn_context) as client:
            trigger_obj = client.GetTrigger(trigger_ref)
            source_obj = None
            if trigger_obj is not None:
                source_crds = client.ListSourceCustomResourceDefinitions()
                source_obj_ref = trigger_obj.dependency
                source_crd = next((s for s in source_crds
                                   if s.source_kind == source_obj_ref.kind),
                                  None)
                if source_crd is not None:
                    source_ref = util.GetSourceRef(source_obj_ref.name,
                                                   source_obj_ref.namespace,
                                                   source_crd)
                    source_obj = client.GetSource(source_ref, source_crd)
        if not trigger_obj:
            raise exceptions.TriggerNotFound('Trigger [{}] not found.'.format(
                trigger_ref.Name()))
        if not source_obj:
            log.warning('No matching event source for trigger [{}].'.format(
                trigger_ref.Name()))
        return SerializedTriggerAndSource(
            trigger_obj.MakeSerializable(),
            source_obj.MakeSerializable() if source_obj else None)
Esempio n. 22
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))
Esempio n. 23
0
    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)
Esempio n. 24
0
 def Run(self, args):
   """List available routes."""
   if args.uri:
     raise flags.ArgumentError('--uri flag is not supported for this resource')
   conn_context = connection_context.GetConnectionContext(args)
   namespace_ref = args.CONCEPTS.namespace.Parse()
   with serverless_operations.Connect(conn_context) as client:
     return client.ListRoutes(namespace_ref)
Esempio n. 25
0
 def Run(self, args):
     """List available routes."""
     conn_context = connection_context.GetConnectionContext(
         args, product=flags.Product.RUN)
     namespace_ref = args.CONCEPTS.namespace.Parse()
     with serverless_operations.Connect(conn_context) as client:
         self.SetCompleteApiEndpoint(conn_context.endpoint)
         return commands.SortByName(client.ListRoutes(namespace_ref))
  def Run(self, args):
    conn_context = connection_context.GetConnectionContext(
        args, serverless_flags.Product.EVENTS, self.ReleaseTrack())

    with eventflow_operations.Connect(conn_context) as client:
      source_crds = client.ListSourceCustomResourceDefinitions()
      return util.EventTypeFromTypeString(
          source_crds, args.event_type, args.source)
Esempio n. 27
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)
Esempio n. 28
0
    def Run(self, args):
        """Create a domain mapping."""
        # domains.cloudrun.com api group only supports v1alpha1 on clusters.
        conn_context = connection_context.GetConnectionContext(
            args,
            flags.Product.RUN,
            self.ReleaseTrack(),
            version_override=('v1alpha1' if platforms.GetPlatform() !=
                              platforms.PLATFORM_MANAGED else None))
        domain_mapping_ref = args.CONCEPTS.domain.Parse()
        changes = [
            config_changes.SetLaunchStageAnnotationChange(self.ReleaseTrack())
        ]

        # Check if the provided domain has already been verified
        # if mapping to a non-CRoGKE service
        if platforms.GetPlatform() == platforms.PLATFORM_MANAGED:
            client = global_methods.GetServerlessClientInstance()
            all_domains = global_methods.ListVerifiedDomains(client)
            # If not already verified, explain and error out
            if all(d.id not in domain_mapping_ref.Name() for d in all_domains):
                if not all_domains:
                    domains_text = 'You currently have no verified domains.'
                else:
                    domains = ['* {}'.format(d.id) for d in all_domains]
                    domains_text = ('Currently verified domains:\n{}'.format(
                        '\n'.join(domains)))
                raise exceptions.DomainMappingCreationError(
                    'The provided domain does not appear to be verified '
                    'for the current account so a domain mapping '
                    'cannot be created. Visit [{help}] for more information.'
                    '\n{domains}'.format(help=DOMAIN_MAPPINGS_HELP_DOCS_URL,
                                         domains=domains_text))

        with serverless_operations.Connect(conn_context) as client:
            try:
                mapping = client.CreateDomainMapping(domain_mapping_ref,
                                                     args.service, changes,
                                                     args.force_override)
            except exceptions.DomainMappingAlreadyExistsError as e:
                if console_io.CanPrompt() and console_io.PromptContinue(
                    ('This domain is already being used as a mapping elsewhere. '
                     'The existing mapping can be overriden by passing '
                     '`--force-override` or by continuing at the prompt below.'
                     ),
                        prompt_string='Override the existing mapping'):
                    deletion.Delete(domain_mapping_ref,
                                    client.GetDomainMapping,
                                    client.DeleteDomainMapping,
                                    async_=False)
                    mapping = client.CreateDomainMapping(
                        domain_mapping_ref, args.service, changes, True)
                else:
                    raise e

            for record in mapping.records:
                record.name = record.name or mapping.route_name
            return mapping.records
Esempio n. 29
0
    def Run(self, args):
        conn_context = connection_context.GetConnectionContext(args)
        if conn_context.supports_one_platform:
            raise exceptions.UnsupportedArgumentError(
                'Events are only available with Cloud Run for Anthos.')

        with eventflow_operations.Connect(conn_context) as client:
            source_crds = client.ListSourceCustomResourceDefinitions()
            return util.EventTypeFromTypeString(source_crds, args.event_type)
Esempio n. 30
0
 def Run(self, args):
   """Create a domain mapping."""
   conn_context = connection_context.GetConnectionContext(args)
   domain_mapping_ref = args.CONCEPTS.domain.Parse()
   with serverless_operations.Connect(conn_context) as client:
     client.CreateDomainMapping(domain_mapping_ref, args.service)
     msg = """{domain} now maps to service [{serv}]""".format(
         domain=domain_mapping_ref.domainmappingsId, serv=args.service)
     pretty_print.Success(msg)