def Run(self, args):
        """Exports a build trigger.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.
    """
        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        project = properties.VALUES.core.project.Get(required=True)
        location = args.region or cloudbuild_util.DEFAULT_REGION
        trigger = args.TRIGGER

        name = resources.REGISTRY.Parse(
            trigger,
            params={
                'projectsId': project,
                'locationsId': location,
                'triggersId': trigger,
            },
            collection='cloudbuild.projects.locations.triggers').RelativeName(
            )

        got_trigger = client.projects_locations_triggers.Get(
            messages.CloudbuildProjectsLocationsTriggersGetRequest(
                name=name, triggerId=trigger))
        with files.FileWriter(args.destination) as out:
            yaml.dump(encoding.MessageToDict(got_trigger), stream=out)
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        parent = properties.VALUES.core.project.Get(required=True)
        config_id = args.CONFIG
        # Get the GitLab Enterprise config ref
        gitlab_config_resource = resources.REGISTRY.Parse(
            None,
            collection='cloudbuild.projects.locations.gitLabConfigs',
            api_version='v1',
            params={
                'projectsId': parent,
                'locationsId': args.region,
                'gitLabConfigsId': config_id,
            })

        # Send the Get request
        gitlab_config = client.projects_locations_gitLabConfigs.Get(
            messages.CloudbuildProjectsLocationsGitLabConfigsGetRequest(
                name=gitlab_config_resource.RelativeName()))
        return gitlab_config
 def SetUp(self):
     self.messages = cloudbuild_util.GetMessagesModule()
     self.object_ref = storage_util.ObjectReference.FromUrl(
         'gs://bucket/path/object.tgz')
     for prop in (properties.VALUES.app.container_builder_image,
                  properties.VALUES.app.cloud_build_timeout):
         self.addCleanup(prop.Set, prop.Get())
Esempio n. 4
0
  def ParseTriggerFromFlags(self, args):
    """Parses command line arguments into a build trigger.

    Args:
      args: An argparse arguments object.

    Returns:
      A build trigger object.
    """
    messages = cloudbuild_util.GetMessagesModule()

    trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
    if done:
      return trigger

    repo_ref = args.CONCEPTS.repo.Parse()
    repo = repo_ref.reposId
    trigger = messages.BuildTrigger(
        name=args.name,
        description=args.description,
        triggerTemplate=messages.RepoSource(
            repoName=repo,
            branchName=args.branch_pattern,
            tagName=args.tag_pattern,
        ),
    )

    # Build Config
    project = properties.VALUES.core.project.Get(required=True)
    default_image = 'gcr.io/%s/%s:$COMMIT_SHA' % (project, repo)
    trigger_utils.ParseBuildConfigArgs(trigger, args, messages, default_image)
    trigger_utils.ParseRepoEventArgs(trigger, args)

    return trigger
Esempio n. 5
0
    def BuildAndStoreFlexTemplateImage(image_gcr_path,
                                       flex_template_base_image, jar_paths,
                                       py_paths, env, sdk_language,
                                       gcs_log_dir):
        """Builds the flex template docker container image and stores it in GCR.

    Args:
      image_gcr_path: GCR location to store the flex template container image.
      flex_template_base_image: SDK version or base image to use.
      jar_paths: List of jar paths to pipelines and dependencies.
      py_paths: List of python paths to pipelines and dependencies.
      env: Dictionary of env variables to set in the container image.
      sdk_language: SDK language of the flex template.
      gcs_log_dir: Path to Google Cloud Storage directory to store build logs.

    Returns:
      True if container is built and store successfully.

    Raises:
      ValueError: If the parameters values are invalid.
    """
        Templates.__ValidateFlexTemplateEnv(env, sdk_language)
        with files.TemporaryDirectory() as temp_dir:
            log.status.Print(
                'Copying files to a temp directory {}'.format(temp_dir))

            pipeline_files = []
            paths = jar_paths
            if py_paths:
                paths = py_paths
            for path in paths:
                absl_path = os.path.abspath(path)
                if os.path.isfile(absl_path):
                    shutil.copy2(absl_path, temp_dir)
                else:
                    shutil.copytree(
                        absl_path, '{}/{}'.format(temp_dir,
                                                  os.path.basename(absl_path)))
                pipeline_files.append(os.path.split(absl_path)[1])

            log.status.Print(
                'Generating dockerfile to build the flex template container image...'
            )
            dockerfile_contents = Templates.BuildDockerfile(
                flex_template_base_image, pipeline_files, env, sdk_language)

            dockerfile_path = os.path.join(temp_dir, 'Dockerfile')
            files.WriteFileContents(dockerfile_path, dockerfile_contents)
            log.status.Print('Generated Dockerfile. Contents: {}'.format(
                dockerfile_contents))

            messages = cloudbuild_util.GetMessagesModule()
            build_config = submit_util.CreateBuildConfig(
                image_gcr_path, False, messages, None, 'cloudbuild.yaml', True,
                False, temp_dir, None, None, gcs_log_dir, None, None, None,
                None)
            log.status.Print('Pushing flex template container image to GCR...')

            submit_util.Build(messages, False, build_config)
            return True
 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 = properties.VALUES.core.project.Get(required=True)
     run_id = args.RUN_ID
     if args.type == 'build':
         client = v1_client_util.GetClientInstance()
         messages = v1_client_util.GetMessagesModule()
         build_ref = resources.REGISTRY.Parse(
             run_id,
             params={
                 'projectsId': project,
                 'locationsId': region,
                 'buildsId': run_id,
             },
             collection='cloudbuild.projects.locations.builds')
         logger = v1_logs.CloudBuildClient(client, messages, True)
         if args.stream:
             logger.Stream(build_ref)
             return
         logger.PrintLog(build_ref)
         return
     else:
         logger = v2_logs.CloudBuildLogClient()
         if args.stream:
             logger.Stream(project, region, run_id, args.type)
             return
         logger.PrintLog(project, region, run_id, args.type)
         return
Esempio n. 7
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        parent = properties.VALUES.core.project.Get(required=True)
        # Get the parent project ref
        parent_resource = resources.REGISTRY.Create(
            collection='cloudbuild.projects', projectId=parent)

        # Send the List request
        ghe_list = client.projects_githubEnterpriseConfigs.List(
            messages.CloudbuildProjectsGithubEnterpriseConfigsListRequest(
                parent=parent_resource.RelativeName())).configs

        return ghe_list
Esempio n. 8
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

    client = cloudbuild_util.GetClientInstance()
    messages = cloudbuild_util.GetMessagesModule()

    parent = properties.VALUES.core.project.Get(required=True)
    # Get the parent project ref
    parent_resource = resources.REGISTRY.Create(
        collection='cloudbuild.projects.locations',
        projectsId=parent,
        # Use default region global until Proctor is fully regionalized.
        locationsId=cloudbuild_util.DEFAULT_REGION)

    # Send the List request
    bbs_list = client.projects_locations_bitbucketServerConfigs.List(
        messages.CloudbuildProjectsLocationsBitbucketServerConfigsListRequest(
            parent=parent_resource.RelativeName())).bitbucketServerConfigs

    return bbs_list
Esempio n. 9
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        release_track = self.ReleaseTrack()
        client = cloudbuild_util.GetClientInstance(release_track)
        messages = cloudbuild_util.GetMessagesModule(release_track)

        parent = properties.VALUES.core.project.Get(required=True)

        # Get the parent project ref
        parent_resource = resources.REGISTRY.Create(
            collection='cloudbuild.projects', projectId=parent)

        # Send the List request
        wp_list = client.projects_workerPools.List(
            messages.CloudbuildProjectsWorkerPoolsListRequest(
                parent=parent_resource.RelativeName())).workerPools

        # Format the workerpool names for display
        for wp in wp_list:
            try:
                wp.name = cloudbuild_util.GlobalWorkerPoolShortName(wp.name)
            except ValueError:
                pass  # Must be an old version.

        return wp_list
Esempio n. 10
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

    release_track = self.ReleaseTrack()
    client = cloudbuild_util.GetClientInstance(release_track)
    messages = cloudbuild_util.GetMessagesModule(release_track)

    parent = properties.VALUES.core.project.Get(required=True)

    wp_name = args.WORKER_POOL

    # Get the workerpool ref
    wp_resource = resources.REGISTRY.Parse(
        None,
        collection='cloudbuild.projects.workerPools',
        api_version=cloudbuild_util.RELEASE_TRACK_TO_API_VERSION[release_track],
        params={
            'projectsId': parent,
            'workerPoolsId': wp_name,
        })

    # Send the Delete request
    client.projects_workerPools.Delete(
        messages.CloudbuildProjectsWorkerPoolsDeleteRequest(
            name=wp_resource.RelativeName()))

    log.DeletedResource(wp_resource)
Esempio n. 11
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()
        registry = self.context['registry']

        build_ref = registry.Parse(
            args.build,
            params={
                'projectId': properties.VALUES.core.project.GetOrFail,
            },
            collection='cloudbuild.projects.builds')

        logger = cb_logs.CloudBuildClient(client, messages)
        if args.stream:
            logger.Stream(build_ref)
            return

        # Just print out what's available now.
        logger.PrintLog(build_ref)
Esempio n. 12
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        build_region = args.region or cloudbuild_util.DEFAULT_REGION

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        cancelled = []
        for build in args.builds:
            build_ref = resources.REGISTRY.Parse(
                build,
                params={
                    'projectsId': properties.VALUES.core.project.GetOrFail,
                    'locationsId': build_region,
                    'buildsId': build,
                },
                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.write(
                'Cancelled [{r}].\n'.format(r=six.text_type(build_ref)))
            cancelled.append(cancelled_build)
        return cancelled
Esempio n. 13
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        parent = properties.VALUES.core.project.Get(required=True)
        config_id = args.CONFIG
        # Get the bitbucket server config ref
        bbs_resource = resources.REGISTRY.Parse(
            None,
            collection='cloudbuild.projects.locations.bitbucketServerConfigs',
            api_version='v1',
            params={
                'projectsId': parent,
                # Use default region global until Proctor is fully regionalized.
                'locationsId': cloudbuild_util.DEFAULT_REGION,
                'bitbucketServerConfigsId': config_id,
            })

        # Send the Get request
        bbs = client.projects_locations_bitbucketServerConfigs.Get(
            messages.
            CloudbuildProjectsLocationsBitbucketServerConfigsGetRequest(
                name=bbs_resource.RelativeName()))
        return bbs
    def LoadCloudBuild(self, params):
        """Loads the Cloud Build configuration file for this builder reference.

    Args:
      params: dict, a dictionary of values to be substituted in to the
        Cloud Build configuration template corresponding to this runtime
        version.

    Returns:
      Build message, the parsed and parameterized Cloud Build configuration
        file.

    Raises:
      CloudBuildLoadError: If the Cloud Build configuration file is unknown.
      FileReadError: If reading the configuration file fails.
      InvalidRuntimeBuilderPath: If the path of the configuration file is
        invalid.
    """
        if not self.build_file_uri:
            raise CloudBuildLoadError(
                'There is no build file associated with runtime [{runtime}]'.
                format(runtime=self.runtime))
        messages = cloudbuild_util.GetMessagesModule()
        with _Read(self.build_file_uri) as data:
            return cloudbuild_config.LoadCloudbuildConfigFromStream(
                data, messages=messages, params=params)
Esempio n. 15
0
    def LoadCloudBuild(self, params):
        """Loads the Cloud Build configuration file for this runtime version.

    Pulls the file from the app/runtime_builders_root value. Supported protocols
    are Cloud Storage ('gs://') and local filesystem ('file://').

    Args:
      params: dict, a dictionary of values to be substituted in to the
        Cloud Build configuration template corresponding to this runtime
        version.

    Returns:
      Build message, the parsed and parameterized Cloud Build configuration
        file.

    Raises:
      CloudBuildLoadError: if the Cloud Build configuration file could not be
        loaded.
    """
        messages = cloudbuild_util.GetMessagesModule()
        build_file_path = os.path.join(self.source_dir, self.CLOUDBUILD_FILE)
        try:
            with open(build_file_path) as data:
                return cloudbuild_config.LoadCloudbuildConfigFromStream(
                    data, messages=messages, params=params)
        except (IOError, OSError, calliope_exceptions.BadFileException):
            raise self._CreateCloudBuildNotFoundException()
Esempio n. 16
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        cancelled = []
        for build in args.builds:
            build_ref = resources.REGISTRY.Parse(
                build,
                params={'projectId': properties.VALUES.core.project.GetOrFail},
                collection='cloudbuild.projects.builds')
            cancelled_build = client.projects_builds.Cancel(
                messages.CloudbuildProjectsBuildsCancelRequest(
                    projectId=build_ref.projectId, id=build_ref.id))
            log.status.write('Cancelled [{r}].\n'.format(r=str(build_ref)))
            cancelled.append(cancelled_build)
        return cancelled
Esempio n. 17
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        build_region = args.region or cloudbuild_util.DEFAULT_REGION

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        build_ref = resources.REGISTRY.Parse(
            args.build,
            params={
                'projectsId': properties.VALUES.core.project.GetOrFail,
                'locationsId': build_region,
            },
            collection='cloudbuild.projects.locations.builds')

        logger = cb_logs.CloudBuildClient(client, messages, self._support_gcl)
        if args.stream:
            if not self._support_gcl:
                log.status.Print(
                    '\ngcloud builds log --stream only displays logs from Cloud'
                    ' Storage. To view logs from Cloud Logging, run:\ngcloud beta'
                    ' builds log --stream\n')
            logger.Stream(build_ref)
            return

        # Just print out what's available now.
        logger.PrintLog(build_ref)
Esempio n. 18
0
    def Run(self, args):
        """Imports a build trigger.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        project = properties.VALUES.core.project.Get(required=True)
        location = args.region or cloudbuild_util.DEFAULT_REGION
        triggers = cloudbuild_util.LoadMessagesFromPath(
            args.source,
            messages.BuildTrigger,
            'BuildTrigger',
            skip_camel_case=['substitutions'])

        return [
            self._CreateOrUpdateTrigger(client, messages, project, location,
                                        trigger) for trigger in triggers
        ]
Esempio n. 19
0
  def _UpdateBuildTriggerWithSchedulerJobTags(
      self, build_trigger, job_location, job_id):
    job_location_tag = 'cloudscheduler-job-location_' + job_location
    job_id_tag = 'cloudscheduler-job-id_' + job_id

    build_trigger_tags = [x for x in build_trigger.tags
                          if not x.startswith('cloudscheduler-job-')]
    build_trigger_tags.append(job_location_tag)
    build_trigger_tags.append(job_id_tag)
    build_trigger.tags = build_trigger_tags

    build_tags = [x for x in build_trigger.build.tags
                  if not x.startswith('cloudscheduler-job-')]
    build_tags.append(job_location_tag)
    build_tags.append(job_id_tag)
    build_trigger.build.tags = build_tags

    client = cloudbuild_util.GetClientInstance()
    messages = cloudbuild_util.GetMessagesModule()
    project = properties.VALUES.core.project.Get(required=True)

    updated_trigger = client.projects_triggers.Patch(
        messages.CloudbuildProjectsTriggersPatchRequest(
            buildTrigger=build_trigger,
            projectId=project,
            triggerId=build_trigger.id
        )
    )

    log.debug('added job id to trigger: ' + six.text_type(updated_trigger))
Esempio n. 20
0
  def _ConfigureCleanPreviewBuildTrigger(
      self, repo_name, repo_owner, pull_request_pattern, cluster, location,
      app_name):

    # Generate deterministic trigger name
    name = self._FixBuildTriggerName(self._GenerateResourceName(
        function_code='cp',  # Clean Preview
        repo_type='github',  # Only supports github for now.
        full_repo_name=repo_owner + '-' + repo_name,
        branch_pattern=pull_request_pattern))
    description = ('Clean expired preview deployments for pull requests '
                   'against branch pattern "{}"').format(
                       pull_request_pattern)

    build_trigger = build_util.CreateCleanPreviewBuildTrigger(
        messages=cloudbuild_util.GetMessagesModule(),
        name=name,
        description=description,
        github_repo_owner=repo_owner,
        github_repo_name=repo_name,
        cluster=cluster,
        location=location,
        build_tags=[app_name],
        build_trigger_tags=[app_name]
    )

    log.status.Print('Upserting Cloud Build trigger to clean expired preview '
                     'deployments of your application.')
    return self._UpsertBuildTrigger(build_trigger, False)
Esempio n. 21
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Nothing on success.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        parent = properties.VALUES.core.project.Get(required=True)

        config_id = args.CONFIG

        # Get the github enterprise config ref
        ghe_resource = resources.REGISTRY.Parse(
            None,
            collection='cloudbuild.projects.githubEnterpriseConfigs',
            api_version='v1',
            params={
                'projectsId': parent,
                'githubEnterpriseConfigsId': config_id,
            })

        # Send the Delete request
        client.projects_githubEnterpriseConfigs.Delete(
            messages.CloudbuildProjectsGithubEnterpriseConfigsDeleteRequest(
                name=ghe_resource.RelativeName()))
        log.DeletedResource(ghe_resource)
Esempio n. 22
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

    client = cloudbuild_util.GetClientInstance()
    messages = cloudbuild_util.GetMessagesModule()

    trigger = self.ParseTriggerFromFlags(args)

    # Send the Create request
    project = properties.VALUES.core.project.Get(required=True)
    created_trigger = client.projects_triggers.Create(
        messages.CloudbuildProjectsTriggersCreateRequest(
            buildTrigger=trigger, projectId=project))

    trigger_resource = resources.REGISTRY.Parse(
        None,
        collection='cloudbuild.projects.triggers',
        api_version='v1',
        params={
            'projectId': project,
            'triggerId': created_trigger.id,
        })
    log.CreatedResource(trigger_resource)

    return created_trigger
Esempio n. 23
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.

    Raises:
      FailedBuildException: If the build is completed and not 'SUCCESS'.
    """

    messages = cloudbuild_util.GetMessagesModule()

    # Create the build request.
    build_config = submit_util.CreateBuildConfig(
        args.tag, args.no_cache, messages, args.substitutions, args.config,
        args.IsSpecified('source'), args.no_source, args.source,
        args.gcs_source_staging_dir, args.ignore_file, args.gcs_log_dir,
        args.machine_type, args.disk_size)

    # Start the build.
    return submit_util.Build(messages, args.async_, build_config)
Esempio n. 24
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        ongoing_filter = None
        if args.ongoing:
            ongoing_filter = 'status="WORKING" OR status="QUEUED"'

        return list_pager.YieldFromList(
            client.projects_builds,
            messages.CloudbuildProjectsBuildsListRequest(
                pageSize=args.page_size,
                projectId=properties.VALUES.core.project.Get(),
                filter=ongoing_filter),
            field='builds',
            batch_size=args.page_size,
            batch_size_attribute='pageSize')
def ParseTriggerFromFlags(args):
    """Parse arguments into a BuildTrigger proto.

  Args:
    args: An argparse.Namespace. All the arguments that were provided to this
      command invocation.

  Returns:
    A BuildTrigger proto object.
  """
    messages = cloudbuild_util.GetMessagesModule()

    trigger, done = trigger_utils.ParseTriggerArgs(args, messages)
    if done:
        return trigger

    trigger.name = args.name
    trigger.pubsubConfig = messages.PubsubConfig(topic=args.topic)

    # Build Config
    project = properties.VALUES.core.project.Get(required=True)
    default_image = 'gcr.io/%s/gcb-%s:$COMMIT_SHA' % (project, args.name)
    trigger_utils.ParseBuildConfigArgs(trigger,
                                       args,
                                       messages,
                                       default_image,
                                       need_repo=True)

    trigger.filter = args.filter

    return trigger
Esempio n. 26
0
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
    build_region = args.region or cloudbuild_util.DEFAULT_REGION

    client = cloudbuild_util.GetClientInstance()
    messages = cloudbuild_util.GetMessagesModule()

    project_id = properties.VALUES.core.project.GetOrFail()
    parent_resource = resources.REGISTRY.Create(
        collection='cloudbuild.projects.locations',
        projectsId=project_id,
        locationsId=build_region)

    args.filter, server_filter = filter_rewrite.Backend(args.ongoing).Rewrite(
        args.filter)

    return list_pager.YieldFromList(
        client.projects_locations_builds,
        messages.CloudbuildProjectsLocationsBuildsListRequest(
            parent=parent_resource.RelativeName(),
            pageSize=args.page_size,
            filter=server_filter),
        field='builds',
        batch_size=args.page_size,
        limit=args.limit,
        batch_size_attribute='pageSize')
Esempio n. 27
0
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """

        client = cloudbuild_util.GetClientInstance()
        messages = cloudbuild_util.GetMessagesModule()

        args.filter, server_filter = filter_rewrite.Backend(
            args.ongoing).Rewrite(args.filter)

        return list_pager.YieldFromList(
            client.projects_builds,
            messages.CloudbuildProjectsBuildsListRequest(
                pageSize=args.page_size,
                projectId=properties.VALUES.core.project.GetOrFail(),
                filter=server_filter),
            field='builds',
            batch_size=args.page_size,
            limit=args.limit,
            batch_size_attribute='pageSize')
Esempio n. 28
0
  def _ConfigureGitPushBuildTrigger(
      self, repo_type, csr_repo_name, github_repo_owner, github_repo_name,
      branch_pattern, tag_pattern, dockerfile_path, app_name, config_path,
      namespace, expose_port, gcs_config_staging_path, cluster, location):

    # Generate deterministic trigger name
    if csr_repo_name:
      full_repo_name = csr_repo_name
    else:
      full_repo_name = github_repo_owner + '-' + github_repo_name

    name = self._FixBuildTriggerName(self._GenerateResourceName(
        function_code='gp',  # Git Push
        repo_type=repo_type,
        full_repo_name=full_repo_name,
        branch_pattern=branch_pattern,
        tag_pattern=tag_pattern))

    if branch_pattern:
      description = 'Build and deploy on push to "{}"'.format(branch_pattern)
    elif tag_pattern:
      description = 'Build and deploy on "{}" tag'.format(tag_pattern)

    build_trigger = build_util.CreateGitPushBuildTrigger(
        cloudbuild_util.GetMessagesModule(),
        name=name,
        description=description,
        build_timeout=properties.VALUES.builds.timeout.Get(),
        csr_repo_name=csr_repo_name,
        github_repo_owner=github_repo_owner,
        github_repo_name=github_repo_name,
        branch_pattern=branch_pattern,
        tag_pattern=tag_pattern,
        dockerfile_path=dockerfile_path,
        app_name=app_name,
        config_path=config_path,
        namespace=namespace,
        expose_port=expose_port,
        gcs_config_staging_path=gcs_config_staging_path,
        cluster=cluster,
        location=location,
        build_tags=[app_name],
        build_trigger_tags=[app_name],
    )

    log.status.Print('Upserting Cloud Build trigger to build and deploy your '
                     'application.')
    upserted_trigger = self._UpsertBuildTrigger(build_trigger, True)
    project = properties.VALUES.core.project.Get(required=True)

    log.status.Print(
        '\nSuccessfully created the Cloud Build trigger to build and deploy '
        'your application.\n\n'
        'Visit https://console.cloud.google.com/cloud-build/triggers/edit/{trigger_id}?project={project} '
        'to view the trigger.\n\n'
        'You can visit https://console.cloud.google.com/cloud-build/triggers?project={project} '
        'to view all Cloud Build triggers.'.format(
            trigger_id=upserted_trigger.id, project=project)
    )
Esempio n. 29
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. 30
0
def AddMachineTypeFlag(parser, hidden=False):
    """Add a machine type flag."""
    global _machine_type_flag_map
    _machine_type_flag_map = arg_utils.ChoiceEnumMapper(
        '--machine-type', (cloudbuild_util.GetMessagesModule()
                           ).BuildOptions.MachineTypeValueValuesEnum,
        include_filter=lambda s: six.text_type(s) != 'UNSPECIFIED',
        help_str='Machine type used to run the build.',
        hidden=hidden)
    _machine_type_flag_map.choice_arg.AddToParser(parser)