示例#1
0
def _ValidateAndGetDockerVersion(version_or_tag):
    """Validates a version_or_tag and returns the validated DockerVersion object.

  Args:
    version_or_tag: a docker version or a docker tag.

  Returns:
    a DockerVersion object.

  Raises:
    ar_exceptions.InvalidInputValueError if version_or_tag is not valid.
  """
    try:
        if isinstance(version_or_tag, DockerVersion):
            # We have all the information about the docker digest.
            # Call the API to make sure it exists.
            ar_requests.GetVersion(ar_requests.GetClient(),
                                   ar_requests.GetMessages(),
                                   version_or_tag.GetVersionName())
            return version_or_tag
        elif isinstance(version_or_tag, DockerTag):
            digest = ar_requests.GetVersionFromTag(ar_requests.GetClient(),
                                                   ar_requests.GetMessages(),
                                                   version_or_tag.GetTagName())
            docker_version = DockerVersion(version_or_tag.image, digest)
            return docker_version
        else:
            raise ar_exceptions.InvalidInputValueError(
                _INVALID_DOCKER_IMAGE_ERROR)
    except api_exceptions.HttpNotFoundError:
        raise ar_exceptions.InvalidInputValueError(_DOCKER_IMAGE_NOT_FOUND)
示例#2
0
def DisableUpgradeRedirection(unused_ref, args):
    """Disables upgrade redirection for the active project."""
    project = GetProject(args)
    messages = ar_requests.GetMessages()
    con = console_attr.GetConsoleAttr()

    log.status.Print("Disabling upgrade redirection...\n")
    if not CheckRedirectionPermission(project):
        return None

    # If the current state is finalized, then disabling is not possible
    log.status.Print("Checking current redirection status...\n")
    settings = ar_requests.GetProjectSettings(GetProject(args))
    current_status = settings.legacyRedirectionState

    if (current_status ==
            messages.ProjectSettings.LegacyRedirectionStateValueValuesEnum.
            REDIRECTION_FROM_GCR_IO_FINALIZED):
        log.status.Print(
            con.Colorize("FAIL:", "red") + " Redirection has already "
            "been finalized for project {}. Disabling redirection is not possible "
            "once it has been finalized.".format(project))
        return None

    update = console_io.PromptContinue(
        "This action will disable the redirection of Container Registry traffic to Artifact Registry for project {}"
        .format(project),
        default=False)
    if not update:
        log.status.Print("No changes made.")
        return None
    return ar_requests.DisableUpgradeRedirection(project)
def GetMavenSnippet(args):
  """Forms a maven snippet to add to the pom.xml file.

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

  Returns:
    A maven snippet.
  """
  messages = ar_requests.GetMessages()
  location, repo_path = _GetLocationAndRepoPath(
      args, messages.Repository.FormatValueValuesEnum.MAVEN)
  data = {
      "scheme": "artifactregistry",
      "location": location,
      "server_id": "artifact-registry",
      "repo_path": repo_path,
  }
  mvn_template = mvn.NO_SERVICE_ACCOUNT_TEMPLATE

  sa_creds = _GetServiceAccountCreds(args)
  if sa_creds:
    mvn_template = mvn.SERVICE_ACCOUNT_TEMPLATE
    data["scheme"] = "https"
    data["username"] = "******"
    data["password"] = sa_creds

  return mvn_template.format(**data)
def _ValidateDockerRepo(repo_name):
    repo = ar_requests.GetRepository(repo_name)
    messages = ar_requests.GetMessages()
    if repo.format != messages.Repository.FormatValueValuesEnum.DOCKER:
        raise ar_exceptions.InvalidInputValueError(
            "Invalid repository type {}. The `artifacts docker` command group can "
            "only be used on Docker repositories.".format(repo.format))
示例#5
0
def GetMavenSnippet(args):
  """Forms a maven snippet to add to the pom.xml file.

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

  Returns:
    str, a maven snippet to add to the pom.xml file.
  """
  messages = ar_requests.GetMessages()
  location, repo_path, maven_cfg = _GetLocationRepoPathAndMavenConfig(
      args, messages.Repository.FormatValueValuesEnum.MAVEN)
  data = {
      "scheme": "artifactregistry",
      "location": location,
      "server_id": "artifact-registry",
      "repo_path": repo_path,
  }
  sa_creds = _GetServiceAccountCreds(args)
  mvn_template = GetMavenTemplate(messages, maven_cfg, sa_creds)

  if sa_creds:
    data["scheme"] = "https"
    data["username"] = "******"
    data["password"] = sa_creds

  return mvn_template.format(**data)
def GetGradleSnippet(args):
  """Forms a gradle snippet to add to the build.gradle file.

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

  Returns:
    A gradle snippet.
  """
  messages = ar_requests.GetMessages()
  location, repo_path = _GetLocationAndRepoPath(
      args, messages.Repository.FormatValueValuesEnum.MAVEN)
  data = {"location": location, "repo_path": repo_path}

  sa_creds = _GetServiceAccountCreds(args)
  if sa_creds:
    gradle_template = gradle.SERVICE_ACCOUNT_TEMPLATE
    data["username"] = "******"
    data["password"] = sa_creds

  else:
    gradle_template = gradle.NO_SERVICE_ACCOUNT_TEMPLATE
    data["extension_version"] = "2.1.0"
  return gradle_template.format(**data)
示例#7
0
def _GetDockerVersions(docker_img, include_tags, is_nested=False):
  """Gets a list of versions for a Docker image."""
  client = ar_requests.GetClient()
  messages = ar_requests.GetMessages()
  ver_view = (
      messages
      .ArtifactregistryProjectsLocationsRepositoriesPackagesVersionsListRequest
      .ViewValueValuesEnum.BASIC)
  if include_tags:
    ver_view = (
        messages.
        ArtifactregistryProjectsLocationsRepositoriesPackagesVersionsListRequest
        .ViewValueValuesEnum.FULL)
  ver_list = ar_requests.ListVersions(client, messages,
                                      docker_img.GetPackageName(), ver_view)

  # If there's no result, the package name might be part of a nested package.
  # E.g. us-west1-docker.pkg.dev/fake-project/docker-repo/nested1 in
  # us-west1-docker.pkg.dev/fake-project/docker-repo/nested1/nested2/test-image
  # Try to get the list of versions through the list of all packages.
  if not ver_list and not is_nested:
    return _GetDockerNestedVersions(docker_img, include_tags, is_nested=True)

  img_list = []
  for ver in ver_list:
    img_list.append({
        "package": docker_img.GetDockerString(),
        "tags": ", ".join([tag.name.split("/")[-1] for tag in ver.relatedTags]),
        "version": ver.name,
        "createTime": ver.createTime,
        "updateTime": ver.updateTime
    })
  return img_list
示例#8
0
def GetAptSettingsSnippet(args):
  """Forms an apt settings snippet to add to the sources.list.d directory.

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

  Returns:
    An apt settings snippet.
  """
  messages = ar_requests.GetMessages()
  location, repo_path = _GetLocationAndRepoPath(
      args, messages.Repository.FormatValueValuesEnum.APT)
  repo = _GetRequiredRepoValue(args)
  project = _GetRequiredProjectValue(args)

  data = {
      "location": location,
      "project": project,
      "repo": repo,
      "repo_path": repo_path
  }

  if IsPublicRepo(project, location, repo):
    apt_setting_template = apt.PUBLIC_TEMPLATE
  else:
    apt_setting_template = apt.DEFAULT_TEMPLATE
  return apt_setting_template.format(**data)
示例#9
0
def AddDockerTag(args):
    """Adds a Docker tag."""
    src_image, version_or_tag = _ParseDockerImage(args.DOCKER_IMAGE,
                                                  _INVALID_DOCKER_IMAGE_ERROR)
    if version_or_tag is None:
        raise ar_exceptions.InvalidInputValueError(_INVALID_DOCKER_IMAGE_ERROR)

    dest_image, tag = _ParseDockerTag(args.DOCKER_TAG)

    if src_image.GetPackageName() != dest_image.GetPackageName():
        raise ar_exceptions.InvalidInputValueError(
            "Image {}\ndoes not match image {}".format(
                src_image.GetDockerString(), dest_image.GetDockerString()))

    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    docker_version = version_or_tag
    if isinstance(version_or_tag, DockerTag):
        docker_version = DockerVersion(
            version_or_tag.image,
            ar_requests.GetVersionFromTag(client, messages,
                                          version_or_tag.GetTagName()))

    try:
        ar_requests.GetTag(client, messages, tag.GetTagName())
    except api_exceptions.HttpNotFoundError:
        ar_requests.CreateDockerTag(client, messages, tag, docker_version)
    else:
        ar_requests.DeleteTag(client, messages, tag.GetTagName())
        ar_requests.CreateDockerTag(client, messages, tag, docker_version)

    log.status.Print("Added tag [{}] to image [{}].".format(
        tag.GetDockerString(), args.DOCKER_IMAGE))
示例#10
0
def ListDockerTags(args):
    """Lists Docker tags."""
    resource = _ParseDockerImagePath(args.IMAGE_PATH)

    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    img_list = []
    if isinstance(resource, DockerRepo):
        log.status.Print(
            "Listing items under project {}, location {}, repository {}.\n".
            format(resource.project, resource.location, resource.repo))
        for pkg in ar_requests.ListPackages(client, messages,
                                            resource.GetRepositoryName()):
            img_list.append(DockerImage(resource, pkg.name.split("/")[-1]))
    elif isinstance(resource, DockerImage):
        log.status.Print(
            "Listing items under project {}, location {}, repository {}.\n".
            format(resource.docker_repo.project, resource.docker_repo.location,
                   resource.docker_repo.repo))
        img_list.append(resource)

    tag_list = []
    for img in img_list:
        for tag in ar_requests.ListTags(client, messages,
                                        img.GetPackageName()):
            tag_list.append({
                "tag": tag.name,
                "image": img.GetDockerString(),
                "version": tag.version,
            })
    return tag_list
def DeleteDockerImage(args):
    """Deletes a Docker digest or image.

  If input is an image, delete the image along with its resources.

  If input is an image identified by digest, delete the digest.
  If input is an image identified by tag, delete the digest and the tag.
  If --delete-tags is specified, delete all tags associated with the image
  digest.

  Args:
    args: user input arguments.

  Returns:
    The long-running operation from DeletePackage API call.
  """
    image, version_or_tag = _ParseDockerImage(args.IMAGE, _INVALID_IMAGE_ERROR)
    _ValidateDockerRepo(image.docker_repo.GetRepositoryName())
    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    if not version_or_tag:
        console_io.PromptContinue(
            message="\nThis operation will delete all tags and images for " +
            image.GetDockerString() + ".",
            cancel_on_no=True)
        return ar_requests.DeletePackage(client, messages,
                                         image.GetPackageName())

    else:
        tags_to_delete = []
        docker_version = version_or_tag
        if isinstance(version_or_tag, DockerTag):
            docker_version = DockerVersion(
                version_or_tag.image,
                ar_requests.GetVersionFromTag(client, messages,
                                              version_or_tag.GetTagName()))
            tags_to_delete.append(version_or_tag)
        existing_tags = _GetDockerVersionTags(client, messages, docker_version)
        if args.delete_tags:
            tags_to_delete.extend(existing_tags)

        if len(existing_tags) != len(tags_to_delete):
            raise ar_exceptions.ArtifactRegistryError(
                "Cannot delete image {} because it is tagged. "
                "Existing tags are:\n- {}".format(
                    args.IMAGE, "\n- ".join(tag.GetDockerString()
                                            for tag in existing_tags)))

        _LogResourcesToDelete(docker_version, tags_to_delete)
        console_io.PromptContinue(
            message="\nThis operation will delete the above resources.",
            cancel_on_no=True)

        for tag in tags_to_delete:
            ar_requests.DeleteTag(client, messages, tag.GetTagName())
        return ar_requests.DeleteVersion(client, messages,
                                         docker_version.GetVersionName())
示例#12
0
def GetNpmSettingsSnippet(args):
    """Forms an npm settings snippet to add to the .npmrc file.

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

  Returns:
    An npm settings snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.NPM)
    registry_path = "{location}-npm.pkg.dev/{repo_path}/".format(
        **{
            "location": location,
            "repo_path": repo_path
        })
    configured_registry = "registry"
    if args.scope:
        if not args.scope.startswith("@") or len(args.scope) <= 1:
            raise ar_exceptions.InvalidInputValueError(
                "Scope name must start with \"@\" and be longer than 1 character."
            )
        configured_registry = args.scope + ":" + configured_registry

    data = {
        "configured_registry": configured_registry,
        "registry_path": registry_path,
        "repo_path": repo_path
    }

    sa_creds = _GetServiceAccountCreds(args)
    if sa_creds:
        npm_setting_template = """\
# Insert following snippet into your .npmrc

{configured_registry}=https://{registry_path}
//{registry_path}:_password="******"
//{registry_path}:username=_json_key_base64
//{registry_path}:[email protected]
//{registry_path}:always-auth=true
"""
        data["password"] = base64.b64encode(
            sa_creds.encode("utf-8")).decode("utf-8")
    else:
        npm_setting_template = """\
# Insert following snippet into your .npmrc

{configured_registry}=https://{registry_path}
//{registry_path}:_authToken=""
//{registry_path}:always-auth=true
"""

    return npm_setting_template.format(**data)
示例#13
0
def DeleteDockerTag(args):
    """Deletes a Docker tag."""
    _, tag = _ParseDockerTag(args.DOCKER_TAG)

    console_io.PromptContinue(
        message="You are about to delete tag [{}]".format(
            tag.GetDockerString()),
        cancel_on_no=True)
    ar_requests.DeleteTag(ar_requests.GetClient(), ar_requests.GetMessages(),
                          tag.GetTagName())
    log.status.Print("Deleted tag [{}].".format(tag.GetDockerString()))
示例#14
0
def GetGCRRepos(buckets, project):
    """Gets a list of GCR repositories given a list of GCR bucket names."""
    messages = ar_requests.GetMessages()
    existing_buckets = GetExistingGCRBuckets(buckets, project)

    def RepoMsg(bucket):
        return messages.Repository(
            name="projects/{}/locations/{}/repositories/{}".format(
                project, bucket["location"], bucket["repository"]),
            format=messages.Repository.FormatValueValuesEnum.DOCKER),

    return map(RepoMsg, existing_buckets)
示例#15
0
def DeleteDockerTag(args):
  """Deletes a Docker tag."""
  img, tag = _ParseDockerTag(args.DOCKER_TAG)

  ar_util.ValidateLocation(img.docker_repo.location, img.docker_repo.project)
  _ValidateDockerRepo(img.docker_repo.GetRepositoryName())

  console_io.PromptContinue(
      message="You are about to delete tag [{}]".format(tag.GetDockerString()),
      cancel_on_no=True)
  ar_requests.DeleteTag(ar_requests.GetClient(), ar_requests.GetMessages(),
                        tag.GetTagName())
  log.status.Print("Deleted tag [{}].".format(tag.GetDockerString()))
示例#16
0
def _GetDockerPackagesAndVersions(docker_repo, include_tags, is_nested=False):
    """Gets a list of packages with versions for a Docker repository."""
    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    img_list = []
    for pkg in ar_requests.ListPackages(client, messages,
                                        docker_repo.GetRepositoryName()):
        parts = pkg.name.split("/")
        if len(parts) != 8:
            raise ar_exceptions.ArtifactRegistryError(
                "Internal error. Corrupted package name: {}".format(pkg.name))
        img = DockerImage(DockerRepo(parts[1], parts[3], parts[5]), parts[7])
        img_list.extend(_GetDockerVersions(img, include_tags, is_nested))
    return img_list
示例#17
0
def _GetDockerDigest(version_or_tag):
    """Retrieves the docker digest information.

  Args:
    version_or_tag: an object of DockerVersion or DockerTag

  Returns:
    A dictionary of information about the given docker image.
  """
    docker_version = version_or_tag
    try:
        if isinstance(version_or_tag, DockerVersion):
            # We have all the information about the docker digest.
            # Call the API to make sure it exists.
            ar_requests.GetVersion(ar_requests.GetClient(),
                                   ar_requests.GetMessages(),
                                   version_or_tag.GetVersionName())
        elif isinstance(version_or_tag, DockerTag):
            digest = ar_requests.GetVersionFromTag(ar_requests.GetClient(),
                                                   ar_requests.GetMessages(),
                                                   version_or_tag.GetTagName())
            docker_version = DockerVersion(version_or_tag.image, digest)
        else:
            raise ar_exceptions.InvalidInputValueError(
                _INVALID_DOCKER_IMAGE_ERROR)
    except api_exceptions.HttpNotFoundError:
        raise ar_exceptions.InvalidInputValueError(_DOCKER_IMAGE_NOT_FOUND)
    return {
        "digest":
        docker_version.digest,
        "fully_qualified_digest":
        docker_version.GetDockerString(),
        "registry":
        "{}-docker.pkg.dev".format(docker_version.image.docker_repo.location),
        "repository":
        docker_version.image.docker_repo.repo,
    }
示例#18
0
def ListRepositories(args):
    """List repositories in a given project.

  If no location value is specified, list repositories across all locations.

  Args:
    args: User input arguments.

  Returns:
    List of repositories.
  """
    project = GetProject(args)
    location = args.location or properties.VALUES.artifacts.location.Get()
    if location and not IsValidLocation(location) and location != "all":
        raise ar_exceptions.UnsupportedLocationError(
            "{} is not a valid location. Valid locations are [{}].".format(
                location, ", ".join(_VALID_LOCATIONS)))

    loc_paths = []
    if location and location != "all":
        log.status.Print(
            "Listing items under project {}, location {}.\n".format(
                project, location))
        loc_paths.append("projects/{}/locations/{}".format(project, location))
        buckets = [_GCR_BUCKETS[location]] if location in _GCR_BUCKETS else []
    else:
        log.status.Print(
            "Listing items under project {}, across all locations.\n".format(
                project))
        loc_paths.extend([
            "projects/{}/locations/{}".format(project, loc)
            for loc in _VALID_LOCATIONS
        ])
        buckets = _GCR_BUCKETS.values()

    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    repos = []
    for loc in loc_paths:
        repos.extend(ar_requests.ListRepositories(client, messages, loc))
    gcr_repos = _GetGCRRepos(buckets, project)
    if gcr_repos:
        repos.extend(gcr_repos)
        log.status.Print(
            "Note: To perform actions on the Container Registry repositories "
            "listed below please use 'gcloud container images'.\n")

    return repos
def FinalizeUpgradeRedirection(unused_ref, args):
    """Finalizes upgrade redirection for the active project."""
    con = console_attr.GetConsoleAttr()
    project = GetProject(args)
    messages = ar_requests.GetMessages()

    log.status.Print("Finalizing upgrade redirection...\n")
    if not CheckRedirectionPermission(project):
        return None

    # Check the current status is enabled first.
    log.status.Print("Checking current redirection status...\n")
    settings = ar_requests.GetProjectSettings(GetProject(args))
    current_status = settings.legacyRedirectionState
    if (current_status ==
            messages.ProjectSettings.LegacyRedirectionStateValueValuesEnum.
            REDIRECTION_FROM_GCR_IO_FINALIZED):
        log.status.Print(
            "Redirection is already finalized for project {}.".format(project))
        return None
    if (current_status !=
            messages.ProjectSettings.LegacyRedirectionStateValueValuesEnum.
            REDIRECTION_FROM_GCR_IO_ENABLED):
        log.status.Print(
            "Redirection is not currently enabled for project {}.".format(
                project))
        log.status.Print(
            "Enable redirection using 'gcloud artifacts settings enable-upgrade-redirection'"
        )
        return None

    # Run the same report as enabling in case new repos have been added since.
    failed_repos = GetRedirectionEnablementReport(project)
    if failed_repos:
        log.status.Print(
            con.Colorize("FAIL: ", "red") +
            "Redirection cannot be enabled until all Container Registry repos have equivalent Artifact Registry repositories to redirect to:"
        )
        return None

    update = console_io.PromptContinue(
        "This action permanently redirects gcr.io traffic to Artifact Registry "
        "for project {}.".format(con.Emphasize(project, bold=True)),
        default=False)
    if not update:
        log.status.Print("No changes made.")
        return None
    return ar_requests.FinalizeUpgradeRedirection(GetProject(args))
示例#20
0
def DeleteDockerImage(args):
    """Deletes a Docker digest or image.

  If input is an image, delete the image along with its resources.

  If input is an image identified by digest, delete the digest.
  If input is an image identified by tag, delete the digest and the tag.
  If --delete-tags is specified, delete all tags associated with the image
  digest.

  Args:
    args: user input arguments.

  Returns:
    The long-running operation from DeletePackage API call.
  """
    image, version_or_tag = _ParseDockerImage(args.IMAGE, _INVALID_IMAGE_ERROR)
    client = ar_requests.GetClient()
    messages = ar_requests.GetMessages()
    if not version_or_tag:
        console_io.PromptContinue(
            message="\nThis operation will delete all tags and images for " +
            image.GetDockerString() + ".",
            cancel_on_no=True)
        return ar_requests.DeletePackage(client, messages,
                                         image.GetPackageName())

    else:
        tags_to_delete = []
        docker_version = version_or_tag
        if isinstance(version_or_tag, DockerTag):
            docker_version = DockerVersion(
                version_or_tag.image,
                ar_requests.GetVersionFromTag(client, messages,
                                              version_or_tag.GetTagName()))
            tags_to_delete.append(version_or_tag)
        if args.delete_tags:
            tags_to_delete.extend(
                _GetDockerVersionTags(client, messages, docker_version))

        _LogResourcesToDelete(docker_version, tags_to_delete)
        console_io.PromptContinue(
            message="\nThis operation will delete the above resources.",
            cancel_on_no=True)
        for tag in tags_to_delete:
            ar_requests.DeleteTag(client, messages, tag.GetTagName())
        return ar_requests.DeleteVersion(client, messages,
                                         docker_version.GetVersionName())
示例#21
0
def GetGradleSnippet(args):
    """Forms a gradle snippet to add to the build.gradle file.

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

  Returns:
    A gradle snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.MAVEN)

    gradle_template = """\
Please insert following snippet into your build.gradle
see docs.gradle.org/current/userguide/publishing_maven.html

======================================================
plugins {{
  id "maven-publish"
  id "com.google.cloud.artifactregistry.gradle-plugin" version "{extension_version}"
}}

publishing {{
  repositories {{
    maven {{
      url "artifactregistry://{location}-maven.pkg.dev/{repo_path}"
    }}
  }}
}}

repositories {{
  maven {{
    url "artifactregistry://{location}-maven.pkg.dev/{repo_path}"
  }}
}}
======================================================
"""

    data = {
        "location": location,
        "repo_path": repo_path,
        "extension_version": "2.0.0",
    }
    return gradle_template.format(**data)
示例#22
0
def GetNpmSettingsSnippet(args):
    """Forms an npm settings snippet to add to the .npmrc file.

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

  Returns:
    An npm settings snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.NPM)
    registry_path = "{location}-npm.pkg.dev/{repo_path}/".format(
        **{
            "location": location,
            "repo_path": repo_path
        })
    configured_registry = "registry"
    if args.scope:
        if not args.scope.startswith("@") or len(args.scope) <= 1:
            raise ar_exceptions.InvalidInputValueError(
                "Scope name must start with '@' and be longer than 1 character."
            )
        configured_registry = args.scope + ":" + configured_registry

    npm_setting_template = """\
Please insert following snippet into your .npmrc

======================================================
{configured_registry}=https://{registry_path}
//{registry_path}:_password=""
//{registry_path}:username=oauth2accesstoken
//{registry_path}:[email protected]
//{registry_path}:always-auth=true
======================================================
"""

    data = {
        "configured_registry": configured_registry,
        "registry_path": registry_path,
        "repo_path": repo_path,
    }
    return npm_setting_template.format(**data)
示例#23
0
def GetGCRRepos(buckets, project):
    """Gets a list of GCR repositories given a list of GCR bucket names."""
    messages = ar_requests.GetMessages()
    repos = []

    project_id_for_bucket = project
    if ":" in project:
        domain, project_id = project.split(":")
        project_id_for_bucket = "{}.{}.a".format(project_id, domain)
    for bucket in buckets:
        try:
            ar_requests.TestStorageIAMPermission(
                bucket["bucket"].format(project_id_for_bucket), project)
            repo = messages.Repository(
                name="projects/{}/locations/{}/repositories/{}".format(
                    project, bucket["location"], bucket["repository"]),
                format=messages.Repository.FormatValueValuesEnum.DOCKER)
            repos.append(repo)
        except api_exceptions.HttpNotFoundError:
            continue
    return repos
def GetNpmSettingsSnippet(args):
  """Forms an npm settings snippet to add to the .npmrc file.

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

  Returns:
    An npm settings snippet.
  """
  messages = ar_requests.GetMessages()
  location, repo_path = _GetLocationAndRepoPath(
      args, messages.Repository.FormatValueValuesEnum.NPM)
  registry_path = "{location}-npm.pkg.dev/{repo_path}/".format(**{
      "location": location,
      "repo_path": repo_path
  })
  configured_registry = "registry"
  if args.scope:
    if not args.scope.startswith("@") or len(args.scope) <= 1:
      raise ar_exceptions.InvalidInputValueError(
          "Scope name must start with \"@\" and be longer than 1 character.")
    configured_registry = args.scope + ":" + configured_registry

  data = {
      "configured_registry": configured_registry,
      "registry_path": registry_path,
      "repo_path": repo_path
  }

  sa_creds = _GetServiceAccountCreds(args)
  if sa_creds:
    npm_setting_template = npm.SERVICE_ACCOUNT_TEMPLATE
    data["password"] = base64.b64encode(
        sa_creds.encode("utf-8")).decode("utf-8")
  else:
    npm_setting_template = npm.NO_SERVICE_ACCOUNT_TEMPLATE
  return npm_setting_template.format(**data)
def GetPythonSettingsSnippet(args):
  """Forms a Python snippet for .pypirc file (twine) and pip.conf file.

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

  Returns:
    A python snippet.
  """
  messages = ar_requests.GetMessages()
  location, repo_path = _GetLocationAndRepoPath(
      args, messages.Repository.FormatValueValuesEnum.PYPI)
  repo = _GetRequiredRepoValue(args)
  data = {"location": location, "repo_path": repo_path, "repo": repo}

  sa_creds = _GetServiceAccountCreds(args)

  if sa_creds:
    data["password"] = sa_creds
    return python.SERVICE_ACCOUNT_SETTING_TEMPLATE.format(**data)
  else:
    return python.NO_SERVICE_ACCOUNT_SETTING_TEMPLATE.format(**data)
示例#26
0
def GetGradleSnippet(args):
  """Forms a gradle snippet to add to the build.gradle file.

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

  Returns:
    str, a gradle snippet to add to build.gradle.
  """
  messages = ar_requests.GetMessages()
  location, repo_path, maven_cfg = _GetLocationRepoPathAndMavenConfig(
      args, messages.Repository.FormatValueValuesEnum.MAVEN)
  sa_creds = _GetServiceAccountCreds(args)
  gradle_template = GetGradleTemplate(messages, maven_cfg, sa_creds)
  data = {"location": location, "repo_path": repo_path}

  if sa_creds:
    data["username"] = "******"
    data["password"] = sa_creds

  else:
    data["extension_version"] = _EXT_VERSION
  return gradle_template.format(**data)
示例#27
0
def GetPypiSettingsSnippet(args):
    """Forms a PyPI snippet to add to the .pypirc file (twine) and pip.conf file.

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

  Returns:
    A pypi snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.PYPI)
    repo = _GetRequiredRepoValue(args)
    data = {"location": location, "repo_path": repo_path, "repo": repo}

    sa_creds = _GetServiceAccountCreds(args)

    if sa_creds:
        data["password"] = base64.b64encode(
            sa_creds.encode("utf-8")).decode("utf-8")
        return SA_SETTING_TEMPLATE.format(**data)
    else:
        return UNAUTHENTICATED_SETTING_TEMPLATE.format(**data)
示例#28
0
def CreateRepository(repo):
    """Creates an Artifact Registry repostiory and waits for the operation.

  Args:
    repo: googlecloudsdk.command_lib.artifacts.docker_util.DockerRepo defining
      the repository to be created.
  """
    messages = requests.GetMessages()
    repository_message = messages.Repository(
        name=repo.GetRepositoryName(),
        description='Cloud Run Source Deployments',
        format=messages.Repository.FormatValueValuesEnum.DOCKER,
    )

    op = requests.CreateRepository(repo.project, repo.location,
                                   repository_message)
    op_resource = resources.REGISTRY.ParseRelativeName(
        op.name, collection='artifactregistry.projects.locations.operations')

    client = requests.GetClient()
    waiter.WaitFor(
        waiter.CloudOperationPoller(client.projects_locations_repositories,
                                    client.projects_locations_operations),
        op_resource)
示例#29
0
def GetGradleSnippet(args):
    """Forms a gradle snippet to add to the build.gradle file.

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

  Returns:
    A gradle snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.MAVEN)
    data = {"location": location, "repo_path": repo_path}

    sa_creds = _GetServiceAccountCreds(args)
    if sa_creds:
        gradle_template = """\
// Move the secret to ~/.gradle.properties
def artifactRegistryMavenSecret = "{password}"

// Insert following snippet into your build.gradle
// see docs.gradle.org/current/userguide/publishing_maven.html

plugins {{
  id "maven-publish"
}}

publishing {{
  repositories {{
    maven {{
      url "https://{location}-maven.pkg.dev/{repo_path}"
      credentials {{
        username = "******"
        password = "******"
      }}
    }}
  }}
}}

repositories {{
  maven {{
    url "https://{location}-maven.pkg.dev/{repo_path}"
    credentials {{
      username = "******"
      password = "******"
    }}
    authentication {{
      basic(BasicAuthentication)
    }}
  }}
}}
"""

        data["username"] = "******"
        data["password"] = sa_creds

    else:
        gradle_template = """\
// Insert following snippet into your build.gradle
// see docs.gradle.org/current/userguide/publishing_maven.html

plugins {{
  id "maven-publish"
  id "com.google.cloud.artifactregistry.gradle-plugin" version "{extension_version}"
}}

publishing {{
  repositories {{
    maven {{
      url "artifactregistry://{location}-maven.pkg.dev/{repo_path}"
    }}
  }}
}}

repositories {{
  maven {{
    url "artifactregistry://{location}-maven.pkg.dev/{repo_path}"
  }}
}}
"""

        data["extension_version"] = "2.1.0"
    return gradle_template.format(**data)
示例#30
0
def GetMavenSnippet(args):
    """Forms a maven snippet to add to the pom.xml file.

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

  Returns:
    A maven snippet.
  """
    messages = ar_requests.GetMessages()
    location, repo_path = _GetLocationAndRepoPath(
        args, messages.Repository.FormatValueValuesEnum.MAVEN)
    data = {
        "scheme": "artifactregistry",
        "build_ext": """\n
<build>
<extensions>
  <extension>
    <groupId>com.google.cloud.artifactregistry</groupId>
    <artifactId>artifactregistry-maven-wagon</artifactId>
    <version>2.1.0</version>
  </extension>
</extensions>
</build>""",
        "location": location,
        "server_id": "artifact-registry",
        "repo_path": repo_path,
    }
    mvn_template = """\
<!-- Insert following snippet into your pom.xml -->

<project>
  <distributionManagement>
    <snapshotRepository>
      <id>{server_id}</id>
      <url>{scheme}://{location}-maven.pkg.dev/{repo_path}</url>
    </snapshotRepository>
    <repository>
      <id>{server_id}</id>
      <url>{scheme}://{location}-maven.pkg.dev/{repo_path}</url>
    </repository>
  </distributionManagement>

  <repositories>
    <repository>
      <id>{server_id}</id>
      <url>{scheme}://{location}-maven.pkg.dev/{repo_path}</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>{build_ext}
</project>
"""

    sa_creds = _GetServiceAccountCreds(args)
    if sa_creds:
        mvn_template += """
<!-- Insert following snippet into your settings.xml -->

<settings>
  <servers>
    <server>
      <id>{server_id}</id>
      <configuration>
        <httpConfiguration>
          <get>
            <usePreemptive>true</usePreemptive>
          </get>
          <put>
            <params>
              <property>
                <name>http.protocol.expect-continue</name>
                <value>false</value>
              </property>
            </params>
          </put>
        </httpConfiguration>
      </configuration>
      <username>{username}</username>
      <password>{password}</password>
    </server>
  </servers>
</settings>
"""

        data["scheme"] = "https"
        data["build_ext"] = ""
        data["username"] = "******"
        data["password"] = sa_creds

    return mvn_template.format(**data)