Exemple #1
0
def TektonYamlDataToTaskRun(data):
  """Convert Tekton yaml file into TaskRun message."""
  _VersionCheck(data)
  metadata = _MetadataTransform(data)
  spec = data["spec"]
  if "taskSpec" in spec:
    _TaskSpecTransform(spec["taskSpec"])
    managed_sidecars = _MetadataToSidecar(metadata)
    if managed_sidecars:
      spec["taskSpec"]["managedSidecars"] = managed_sidecars
  elif "taskRef" not in spec:
    raise cloudbuild_exceptions.InvalidYamlError(
        "TaskSpec or TaskRef is required.")

  for workspace in spec.get("workspaces", []):
    _WorkspaceTransform(workspace)
  _ServiceAccountTransform(spec)
  input_util.ParamDictTransform(spec.get("params", []))

  discarded_fields = _CheckUnsupportedFields(spec, _TASKRUN_UNSUPPORTED_FIELDS)
  messages = client_util.GetMessagesModule()
  schema_message = encoding.DictToMessage(spec, messages.TaskRun)

  input_util.UnrecognizedFields(schema_message)
  return schema_message, discarded_fields
Exemple #2
0
def TektonYamlDataToPipelineRun(data):
  """Convert Tekton yaml file into PipelineRun message."""
  _VersionCheck(data)
  _MetadataTransform(data)
  spec = data["spec"]
  if "pipelineSpec" in spec:
    _PipelineSpecTransform(spec["pipelineSpec"])
  elif "pipelineRef" not in spec:
    raise cloudbuild_exceptions.InvalidYamlError(
        "PipelineSpec or PipelineRef is required.")

  if "resources" in spec:
    spec.pop("resources")
    log.warning(
        "PipelineResources are dropped because they are deprecated: "
        "https://github.com/tektoncd/pipeline/blob/main/docs/resources.md")

  for workspace in spec.get("workspaces", []):
    _WorkspaceTransform(workspace)
  _ServiceAccountTransform(spec)
  input_util.ParamDictTransform(spec.get("params", []))

  discarded_fields = _CheckUnsupportedFields(spec,
                                             _PIPELINERUN_UNSUPPORTED_FIELDS)
  messages = client_util.GetMessagesModule()
  schema_message = encoding.DictToMessage(spec, messages.PipelineRun)

  input_util.UnrecognizedFields(schema_message)
  return schema_message, discarded_fields
    def Run(self, args):
        """This is what gets called when the user runs this command."""
        client = client_util.GetClientInstance()
        messages = client_util.GetMessagesModule()

        project = properties.VALUES.core.project.Get(required=True)
        parent = 'projects/%s/locations/%s' % (project, args.region)
        workflow_name = '%s/workflows/%s' % (parent, args.WORKFLOW_ID)
        run_workflow_req = messages.RunWorkflowRequest()

        # Add params ('key1=val1,key2=val2') to RunWorkflow request.
        if args.params:
            params = []
            for key, value in args.params.items():
                param = messages.Param(
                    name=key,
                    value=messages.ParamValue(
                        type=messages.ParamValue.TypeValueValuesEnum('STRING'),
                        stringVal=value,
                    ))
                params.append(param)
            run_workflow_req.params = params

        # Call RunWorkflow. Initial not-Done LRO immediately returned.
        run_workflow_operation = client.projects_locations_workflows.Run(
            messages.CloudbuildProjectsLocationsWorkflowsRunRequest(
                name=workflow_name,
                runWorkflowRequest=run_workflow_req,
            ))
        run_workflow_operation_name = run_workflow_operation.name
        run_workflow_operation_ref = resources.REGISTRY.ParseRelativeName(
            run_workflow_operation_name,
            collection='cloudbuild.projects.locations.operations')

        # Wait for RunWorkflow LRO to be marked as Done.
        # Underlying, this also waits for the CreatePipelineRun LRO to be Done.
        waiter.WaitFor(
            waiter.CloudOperationPoller(client.projects_locations_workflows,
                                        client.projects_locations_operations),
            run_workflow_operation_ref,
            'Running Workflow and Creating PipelineRun')

        # Re-fetch the RunWorkflow LRO now that it is done.
        run_workflow_operation_done = client.projects_locations_operations.Get(
            messages.CloudbuildProjectsLocationsOperationsGetRequest(
                name=run_workflow_operation_name))

        # Extract the PipelineRunId from the RunWorkflowCustomOperationMetadata.
        pipeline_run_id = ''
        for additional_property in run_workflow_operation_done.metadata.additionalProperties:
            if additional_property.key == 'pipelineRunId':
                pipeline_run_id = additional_property.value.string_value
        pipeline_run_name = parent + '/pipelineRuns/' + pipeline_run_id

        # Log ran/created resources and return Done RunWorkflow LRO.
        log.status.Print('Ran workflow: {}'.format(workflow_name))
        log.status.Print('Created pipeline run: {}'.format(pipeline_run_name))
        return run_workflow_operation_done
Exemple #4
0
def CloudBuildYamlDataToWorkflow(workflow):
    """Convert cloudbuild.yaml file into Workflow message."""
    _VersionCheck(workflow)
    _WorkflowTransform(workflow)

    messages = client_util.GetMessagesModule()
    schema_message = encoding.DictToMessage(workflow, messages.Workflow)
    input_util.UnrecognizedFields(schema_message)
    return schema_message
    def Run(self, args):
        """This is what gets called when the user runs this command."""
        client = client_util.GetClientInstance()
        messages = client_util.GetMessagesModule()

        project = properties.VALUES.core.project.Get(required=True)
        parent = 'projects/%s/locations/%s' % (project, args.region)
        workflow_name = '%s/workflows/%s' % (parent, args.WORKFLOW_ID)

        workflow = client.projects_locations_workflows.Get(
            messages.CloudbuildProjectsLocationsWorkflowsGetRequest(
                name=workflow_name))
        return workflow
    def Run(self, args):
        """This is what gets called when the user runs this command."""
        client = client_util.GetClientInstance()
        messages = client_util.GetMessagesModule()

        region_ref = args.CONCEPTS.region.Parse()
        return list_pager.YieldFromList(
            client.projects_locations_results,
            messages.CloudbuildProjectsLocationsResultsListRequest(
                parent=region_ref.RelativeName(), filter=args.filter),
            field='results',
            batch_size=args.page_size,
            batch_size_attribute='pageSize',
            limit=args.limit)
Exemple #7
0
    def Run(self, args):
        """This is what gets called when the user runs this command."""
        client = client_util.GetClientInstance()
        messages = client_util.GetMessagesModule()

        yaml_data = input_util.LoadYamlFromPath(args.file)
        workflow = workflow_input_util.CloudBuildYamlDataToWorkflow(yaml_data)

        project = properties.VALUES.core.project.Get(required=True)
        parent = 'projects/%s/locations/%s' % (project, args.region)
        name = '%s/workflows/%s' % (parent, args.WORKFLOW_ID)

        # Update workflow (or create if missing).
        workflow.name = name
        update_operation = client.projects_locations_workflows.Patch(
            messages.CloudbuildProjectsLocationsWorkflowsPatchRequest(
                name=name, workflow=workflow, allowMissing=True))

        update_operation_ref = resources.REGISTRY.ParseRelativeName(
            update_operation.name,
            collection='cloudbuild.projects.locations.operations')

        updated_workflow = waiter.WaitFor(
            waiter.CloudOperationPoller(client.projects_locations_workflows,
                                        client.projects_locations_operations),
            update_operation_ref, 'Updating Workflow')

        updated_workflow_ref = resources.REGISTRY.Parse(
            updated_workflow.name,
            collection='cloudbuild.projects.locations.workflows',
            api_version=client_util.RELEASE_TRACK_TO_API_VERSION[
                self.ReleaseTrack()],
        )

        log.status.Print('Apply result: {}'.format(updated_workflow_ref))
        return updated_workflow
Exemple #8
0
  def Run(self, args):
    """This is what gets called when the user runs this command."""
    client = client_util.GetClientInstance()
    messages = client_util.GetMessagesModule()

    project = properties.VALUES.core.project.Get(required=True)
    parent = 'projects/%s/locations/%s' % (project, args.region)
    resource_name = '%s/workflows/%s' % (parent, args.WORKFLOW_ID)

    # Delete workflow.
    delete_operation = client.projects_locations_workflows.Delete(
        messages.CloudbuildProjectsLocationsWorkflowsDeleteRequest(
            name=resource_name))

    delete_operation_ref = resources.REGISTRY.ParseRelativeName(
        delete_operation.name,
        collection='cloudbuild.projects.locations.operations')

    waiter.WaitFor(
        waiter.CloudOperationPollerNoResources(
            client.projects_locations_operations), delete_operation_ref,
        'Deleting Workflow')

    log.DeletedResource(resource_name)
    def Run(self, args):
        """This is what gets called when the user runs this command."""
        region_ref = args.CONCEPTS.region.Parse()
        region = region_ref.AsDict()['locationsId']
        project = region_ref.AsDict()['projectsId']
        run_id = args.RUN_ID

        if args.type == 'pipelinerun':
            client = v2_client_util.GetClientInstance()
            messages = v2_client_util.GetMessagesModule()
            pipeline_run_resource = resources.REGISTRY.Parse(
                run_id,
                collection='cloudbuild.projects.locations.pipelineRuns',
                api_version='v2',
                params={
                    'projectsId': project,
                    'locationsId': region,
                    'pipelineRunsId': run_id,
                })
            pipeline_run = messages.PipelineRun(
                pipelineRunStatus=messages.PipelineRun.
                PipelineRunStatusValueValuesEnum.PIPELINE_RUN_CANCELLED, )
            update_mask = 'pipelineRunStatus'
            operation = client.projects_locations_pipelineRuns.Patch(
                messages.CloudbuildProjectsLocationsPipelineRunsPatchRequest(
                    name=pipeline_run_resource.RelativeName(),
                    pipelineRun=pipeline_run,
                    updateMask=update_mask,
                ))
            operation_ref = resources.REGISTRY.ParseRelativeName(
                operation.name,
                collection='cloudbuild.projects.locations.operations')
            updated_pipeline_run = waiter.WaitFor(
                waiter.CloudOperationPoller(
                    client.projects_locations_pipelineRuns,
                    client.projects_locations_operations), operation_ref,
                'Cancelling PipelineRun')
            log.status.Print('Cancelled PipelineRun {0}'.format(run_id))
            return updated_pipeline_run
        elif args.type == 'taskrun':
            client = v2_client_util.GetClientInstance()
            messages = v2_client_util.GetMessagesModule()
            task_run_resource = resources.REGISTRY.Parse(
                run_id,
                collection='cloudbuild.projects.locations.taskRuns',
                api_version='v2',
                params={
                    'projectsId': project,
                    'locationsId': region,
                    'taskRunsId': run_id,
                })
            task_run = messages.TaskRun(
                taskRunStatus=messages.TaskRun.TaskRunStatusValueValuesEnum.
                TASK_RUN_CANCELLED, )
            update_mask = 'taskRunStatus'
            operation = client.projects_locations_taskRuns.Patch(
                messages.CloudbuildProjectsLocationsTaskRunsPatchRequest(
                    name=task_run_resource.RelativeName(),
                    taskRun=task_run,
                    updateMask=update_mask,
                ))
            operation_ref = resources.REGISTRY.ParseRelativeName(
                operation.name,
                collection='cloudbuild.projects.locations.operations')
            updated_task_run = waiter.WaitFor(
                waiter.CloudOperationPoller(
                    client.projects_locations_taskRuns,
                    client.projects_locations_operations), operation_ref,
                'Cancelling TaskRun')
            log.status.Print('Cancelled TaskRun {0}'.format(run_id))
            return updated_task_run
        elif args.type == 'build':
            client = v1_client_util.GetClientInstance()
            messages = v1_client_util.GetMessagesModule()
            build_ref = resources.REGISTRY.Parse(
                run_id,
                api_version='v1',
                params={
                    'projectsId': project,
                    'locationsId': region,
                    'buildsId': run_id,
                },
                collection='cloudbuild.projects.locations.builds')
            cancelled_build = client.projects_locations_builds.Cancel(
                messages.CancelBuildRequest(
                    name=build_ref.RelativeName(),
                    projectId=build_ref.projectsId,
                    id=build_ref.buildsId,
                ))
            log.status.Print('Cancelled Build {0}'.format(run_id))
            return cancelled_build
Exemple #10
0
  def Run(self, args):
    """This is what gets called when the user runs this command."""
    client = client_util.GetClientInstance()
    messages = client_util.GetMessagesModule()

    yaml_data = input_util.LoadYamlFromPath(args.file)
    run_type = yaml_data['kind']
    run_id = yaml_data['metadata']['name']

    parent = args.CONCEPTS.region.Parse().RelativeName()

    if run_type == 'PipelineRun':
      pipeline_run, discarded_fields = pipeline_input_util.TektonYamlDataToPipelineRun(
          yaml_data)
      self._CheckDiscardedFields(discarded_fields)
      operation = client.projects_locations_pipelineRuns.Create(
          messages.CloudbuildProjectsLocationsPipelineRunsCreateRequest(
              parent=parent,
              pipelineRun=pipeline_run,
              pipelineRunId=run_id,
          ))
      operation_ref = resources.REGISTRY.ParseRelativeName(
          operation.name, collection='cloudbuild.projects.locations.operations')
      created_pipeline_run = waiter.WaitFor(
          waiter.CloudOperationPoller(client.projects_locations_pipelineRuns,
                                      client.projects_locations_operations),
          operation_ref, 'Creating PipelineRun')

      pipeline_run_ref = resources.REGISTRY.Parse(
          created_pipeline_run.name,
          collection='cloudbuild.projects.locations.pipelineRuns',
          api_version=client_util.RELEASE_TRACK_TO_API_VERSION[
              self.ReleaseTrack()],
      )

      log.CreatedResource(pipeline_run_ref)
      return created_pipeline_run
    elif run_type == 'TaskRun':
      task_run, discarded_fields = pipeline_input_util.TektonYamlDataToTaskRun(
          yaml_data)
      self._CheckDiscardedFields(discarded_fields)
      operation = client.projects_locations_taskRuns.Create(
          messages.CloudbuildProjectsLocationsTaskRunsCreateRequest(
              parent=parent,
              taskRun=task_run,
              taskRunId=run_id,
          ))
      operation_ref = resources.REGISTRY.ParseRelativeName(
          operation.name, collection='cloudbuild.projects.locations.operations')
      created_task_run = waiter.WaitFor(
          waiter.CloudOperationPoller(client.projects_locations_taskRuns,
                                      client.projects_locations_operations),
          operation_ref, 'Creating TaskRun')

      task_run_ref = resources.REGISTRY.Parse(
          created_task_run.name,
          collection='cloudbuild.projects.locations.taskRuns',
          api_version=client_util.RELEASE_TRACK_TO_API_VERSION[
              self.ReleaseTrack()],
      )

      log.CreatedResource(task_run_ref)
      return created_task_run
    else:
      raise cloudbuild_exceptions.InvalidYamlError(
          'Requested resource type {r} not supported'.format(r=run_type))