def ListServices(self, namespace_ref): messages = self._messages_module request = messages.RunNamespacesServicesListRequest( parent=namespace_ref.RelativeName()) with metrics.record_duration(metrics.LIST_SERVICES): response = self._client.namespaces_services.List(request) return [service.Service(item, messages) for item in response.items]
def ListRoutes(self, namespace_ref): messages = self._messages_module request = messages.RunNamespacesRoutesListRequest( parent=namespace_ref.RelativeName()) with metrics.record_duration(metrics.LIST_ROUTES): response = self._client.namespaces_routes.List(request) return [route.Route(item, messages) for item in response.items]
def ListConfigurations(self, namespace_ref): messages = self._messages_module request = messages.RunNamespacesConfigurationsListRequest( parent=namespace_ref.RelativeName()) with metrics.record_duration(metrics.LIST_CONFIGURATIONS): response = self._client.namespaces_configurations.List(request) return [configuration.Configuration(item, messages) for item in response.items]
def DeleteDomainMapping(self, domain_mapping_ref): """Delete a domain mapping. Args: domain_mapping_ref: Resource, domainmapping resource. """ messages = self._messages_module request = messages.RunNamespacesDomainmappingsDeleteRequest( name=domain_mapping_ref.RelativeName()) with metrics.record_duration(metrics.DELETE_DOMAIN_MAPPING): self._client.namespaces_domainmappings.Delete(request)
def DeleteDomainMapping(self, domain): """Delete a domain mapping. Args: domain: str, domain name of the domainmapping to be deleted. """ messages = self._messages_module request = messages.RunNamespacesDomainmappingsDeleteRequest( name=domain) with metrics.record_duration(metrics.DELETE_DOMAIN_MAPPING): self._client.namespaces_domainmappings.Delete(request)
def GetService(self, service_ref): """Return the relevant Service from the server, or None if 404.""" messages = self._messages_module service_get_request = messages.RunNamespacesServicesGetRequest( name=service_ref.RelativeName()) try: with metrics.record_duration(metrics.GET_SERVICE): service_get_response = self._client.namespaces_services.Get( service_get_request) return service.Service(service_get_response, messages) except api_exceptions.HttpNotFoundError: return None
def GetDomainMapping(self, domain_name): """Get a domain mapping. Args: domain_name: str, domain name. Returns: A domain_mapping.DomainMapping object. """ messages = self._messages_module request = messages.RunNamespacesDomainmappingsGetRequest( name=domain_name) with metrics.record_duration(metrics.GET_DOMAIN_MAPPING): response = self._client.namespaces_domainmappings.Get(request) return domain_mapping.DomainMapping(response)
def ListDomainMappings(self, namespace_ref): """List all domain mappings. Args: namespace_ref: Resource, namespace to list domain mappings in. Returns: A list of domain mappings. """ messages = self._messages_module request = messages.RunNamespacesDomainmappingsListRequest( parent=namespace_ref.RelativeName()) with metrics.record_duration(metrics.LIST_DOMAIN_MAPPINGS): response = self._client.namespaces_domainmappings.List(request) return [domain_mapping.DomainMapping(item, messages) for item in response.items]
def GetRevision(self, revision_ref): """Get the revision. Args: revision_ref: Resource, revision to get. Returns: A revision.Revision object. """ messages = self._messages_module revision_name = revision_ref.RelativeName() request = messages.RunNamespacesRevisionsGetRequest(name=revision_name) try: with metrics.record_duration(metrics.GET_REVISION): response = self._client.namespaces_revisions.Get(request) return revision.Revision(response, messages) except api_exceptions.HttpNotFoundError: return None
def DeleteRevision(self, revision_ref): """Delete the provided Revision. Args: revision_ref: Resource, a reference to the Revision to delete Raises: RevisionNotFoundError: if provided revision is not found. """ messages = self._messages_module revision_name = revision_ref.RelativeName() request = messages.RunNamespacesRevisionsDeleteRequest( name=revision_name) try: with metrics.record_duration(metrics.DELETE_REVISION): self._client.namespaces_revisions.Delete(request) except api_exceptions.HttpNotFoundError: raise serverless_exceptions.RevisionNotFoundError( 'Revision [{}] could not be found.'.format(revision_ref.revisionsId))
def _GetRoute(self, service_ref): """Return the relevant Route from the server, or None if 404.""" messages = self._messages_module # GET the Route route_name = self._registry.Parse( service_ref.servicesId, params={ 'namespacesId': service_ref.namespacesId, }, collection='serverless.namespaces.routes').RelativeName() route_get_request = messages.ServerlessNamespacesRoutesGetRequest( name=route_name, ) try: with metrics.record_duration(metrics.GET_ROUTE): route_get_response = self._client.namespaces_routes.Get( route_get_request) return route.Route(route_get_response, messages) except api_exceptions.HttpNotFoundError: return None
def DeleteService(self, service_ref): """Delete the provided Service. Args: service_ref: Resource, a reference to the Service to delete Raises: ServiceNotFoundError: if provided service is not found. """ messages = self._messages_module service_name = service_ref.RelativeName() service_delete_request = messages.RunNamespacesServicesDeleteRequest( name=service_name, ) try: with metrics.record_duration(metrics.DELETE_SERVICE): self._client.namespaces_services.Delete(service_delete_request) except api_exceptions.HttpNotFoundError: raise serverless_exceptions.ServiceNotFoundError( 'Service [{}] could not be found.'.format(service_ref.servicesId))
def GetRoute(self, service_or_route_ref): """Return the relevant Route from the server, or None if 404.""" messages = self._messages_module if hasattr(service_or_route_ref, 'servicesId'): name = self._registry.Parse( service_or_route_ref.servicesId, params={ 'namespacesId': service_or_route_ref.namespacesId, }, collection='run.namespaces.routes').RelativeName() else: name = service_or_route_ref.RelativeName() route_get_request = (messages.RunNamespacesRoutesGetRequest(name=name)) try: with metrics.record_duration(metrics.GET_ROUTE): route_get_response = self._client.namespaces_routes.Get( route_get_request) return route.Route(route_get_response, messages) except api_exceptions.HttpNotFoundError: return None
def ListRevisions(self, namespace_ref, service_name): """List all revisions for the given service. Args: namespace_ref: Resource, namespace to list revisions in service_name: str, The service for which to list revisions. Returns: A list of revisions for the given service. """ messages = self._messages_module request = messages.ServerlessNamespacesRevisionsListRequest( parent=namespace_ref.RelativeName(), ) if service_name is not None: # For now, same as the service name, and keeping compatible with # 'service-less' operation. request.labelSelector = 'serving.knative.dev/service = {}'.format( service_name) with metrics.record_duration(metrics.LIST_REVISIONS): response = self._client.namespaces_revisions.List(request) return [revision.Revision(item, messages) for item in response.items]
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.RelativeName()) with metrics.record_duration(metrics.CREATE_DOMAIN_MAPPING): response = self._client.namespaces_domainmappings.Create(request) return domain_mapping.DomainMapping(response)
def GetConfiguration(self, service_or_configuration_ref): """Return the relevant Configuration from the server, or None if 404.""" messages = self._messages_module if hasattr(service_or_configuration_ref, 'servicesId'): name = self._registry.Parse( service_or_configuration_ref.servicesId, params={ 'namespacesId': service_or_configuration_ref.namespacesId, }, collection='run.namespaces.configurations').RelativeName() else: name = service_or_configuration_ref.RelativeName() configuration_get_request = ( messages.RunNamespacesConfigurationsGetRequest( name=name)) try: with metrics.record_duration(metrics.GET_CONFIGURATION): configuration_get_response = self._client.namespaces_configurations.Get( configuration_get_request) return configuration.Configuration(configuration_get_response, messages) except api_exceptions.HttpNotFoundError: return None
def _UpdateOrCreateService(self, service_ref, config_changes, with_code, private_endpoint=None): """Apply config_changes to the service. Create it if necessary. Arguments: service_ref: Reference to the service to create or update config_changes: list of ConfigChanger to modify the service with with_code: bool, True if the config_changes contains code to deploy. We can't create the service if we're not deploying code. private_endpoint: bool, True if creating a new Service for Cloud Run on GKE that should only be addressable from within the cluster. False if it should be publicly addressable. None if its existing visibility should remain unchanged. Returns: The Service object we created or modified. """ nonce = _Nonce() config_changes = [_NewRevisionForcingChange(nonce)] + config_changes messages = self._messages_module # GET the Service serv = self.GetService(service_ref) try: if serv: if not with_code: # Avoid changing the running code by making the new revision by digest self._EnsureImageDigest(serv, config_changes) if private_endpoint is None: # Don't change the existing service visibility pass elif private_endpoint: serv.labels[service.ENDPOINT_VISIBILITY] = service.CLUSTER_LOCAL else: del serv.labels[service.ENDPOINT_VISIBILITY] # PUT the changed Service for config_change in config_changes: config_change.AdjustConfiguration(serv.configuration, serv.metadata) serv_name = service_ref.RelativeName() serv_update_req = ( messages.RunNamespacesServicesReplaceServiceRequest( service=serv.Message(), name=serv_name)) with metrics.record_duration(metrics.UPDATE_SERVICE): updated = self._client.namespaces_services.ReplaceService( serv_update_req) return service.Service(updated, messages) else: if not with_code: raise serverless_exceptions.ServiceNotFoundError( 'Service [{}] could not be found.'.format(service_ref.servicesId)) # POST a new Service new_serv = service.Service.New(self._client, service_ref.namespacesId, private_endpoint) new_serv.name = service_ref.servicesId pretty_print.Info('Creating new service [{bold}{service}{reset}]', service=new_serv.name) parent = service_ref.Parent().RelativeName() for config_change in config_changes: config_change.AdjustConfiguration(new_serv.configuration, new_serv.metadata) serv_create_req = ( messages.RunNamespacesServicesCreateRequest( service=new_serv.Message(), parent=parent)) with metrics.record_duration(metrics.CREATE_SERVICE): raw_service = self._client.namespaces_services.Create( serv_create_req) return service.Service(raw_service, messages) except api_exceptions.HttpBadRequestError as e: error_payload = exceptions_util.HttpErrorPayload(e) if error_payload.field_violations: if (serverless_exceptions.BadImageError.IMAGE_ERROR_FIELD in error_payload.field_violations): exceptions.reraise(serverless_exceptions.BadImageError(e)) exceptions.reraise(e) except api_exceptions.HttpNotFoundError as e: # TODO(b/118339293): List available regions to check whether provided # region is invalid or not. raise serverless_exceptions.DeploymentFailedError( 'Deployment endpoint was not found. Perhaps the provided ' 'region was invalid. Set the `run/region` property to a valid ' 'region and retry. Ex: `gcloud config set run/region us-central1`')
def _UpdateOrCreateService(self, service_ref, config_changes, with_code): """Apply config_changes to the service. Create it if necessary. Arguments: service_ref: Reference to the service to create or update config_changes: list of ConfigChanger to modify the service with with_code: boolean, True if the config_changes contains code to deploy. We can't create the service if we're not deploying code. Returns: The Service object we created or modified. """ nonce = _Nonce() config_changes = [_NewRevisionForcingChange(nonce)] + config_changes messages = self._messages_module # GET the Service serv = self.GetService(service_ref) try: if serv: if not with_code: # Avoid changing the running code by making the new revision by digest self._EnsureImageDigest(serv, config_changes) # PUT the changed Service for config_change in config_changes: config_change.AdjustConfiguration(serv.configuration, serv.metadata) serv_name = service_ref.RelativeName() serv_update_req = ( messages.ServerlessNamespacesServicesReplaceServiceRequest( service=serv.Message(), name=serv_name)) with metrics.record_duration(metrics.UPDATE_SERVICE): updated = self._client.namespaces_services.ReplaceService( serv_update_req) return service.Service(updated, messages) else: if not with_code: raise serverless_exceptions.ServiceNotFoundError( 'Service [{}] could not be found.'.format( service_ref.servicesId)) # POST a new Service new_serv = service.Service.New(self._client, service_ref.namespacesId) new_serv.name = service_ref.servicesId pretty_print.Info( 'Creating new service [{bold}{service}{reset}]', service=new_serv.name) parent = service_ref.Parent().RelativeName() for config_change in config_changes: config_change.AdjustConfiguration(new_serv.configuration, new_serv.metadata) serv_create_req = ( messages.ServerlessNamespacesServicesCreateRequest( service=new_serv.Message(), parent=parent)) with metrics.record_duration(metrics.CREATE_SERVICE): raw_service = self._client.namespaces_services.Create( serv_create_req) return service.Service(raw_service, messages) except api_exceptions.HttpBadRequestError as e: error_payload = exceptions_util.HttpErrorPayload(e) if error_payload.field_violations: if (serverless_exceptions.BadImageError.IMAGE_ERROR_FIELD in error_payload.field_violations): exceptions.reraise(serverless_exceptions.BadImageError(e)) exceptions.reraise(e)