diff --git a/packages/google-cloud-os-login/.coveragerc b/packages/google-cloud-os-login/.coveragerc
index dd39c8546c41..c742b31ae8cd 100644
--- a/packages/google-cloud-os-login/.coveragerc
+++ b/packages/google-cloud-os-login/.coveragerc
@@ -21,15 +21,14 @@ branch = True
[report]
fail_under = 100
show_missing = True
+omit = google/cloud/oslogin/__init__.py
exclude_lines =
# Re-enable the standard pragma
pragma: NO COVER
# Ignore debug-only repr
def __repr__
- # Ignore abstract methods
- raise NotImplementedError
-omit =
- */gapic/*.py
- */proto/*.py
- */core/*.py
- */site-packages/*.py
\ No newline at end of file
+ # Ignore pkg_resources exceptions.
+ # This is added at the module level as a safeguard for if someone
+ # generates the code and tries to run it without pip installing. This
+ # makes it virtually impossible to test properly.
+ except pkg_resources.DistributionNotFound
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/__init__.py b/packages/google-cloud-os-login/.github/snippet-bot.yml
similarity index 100%
rename from packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/__init__.py
rename to packages/google-cloud-os-login/.github/snippet-bot.yml
diff --git a/packages/google-cloud-os-login/.gitignore b/packages/google-cloud-os-login/.gitignore
index b87e1ed580d9..b9daa52f118d 100644
--- a/packages/google-cloud-os-login/.gitignore
+++ b/packages/google-cloud-os-login/.gitignore
@@ -46,6 +46,7 @@ pip-log.txt
# Built documentation
docs/_build
bigquery/docs/generated
+docs.metadata
# Virtual environment
env/
@@ -57,4 +58,4 @@ system_tests/local_test_setup
# Make sure a generated file isn't accidentally committed.
pylintrc
-pylintrc.test
\ No newline at end of file
+pylintrc.test
diff --git a/packages/google-cloud-os-login/.kokoro/build.sh b/packages/google-cloud-os-login/.kokoro/build.sh
index e62eed1cc715..fcd96b1a140d 100755
--- a/packages/google-cloud-os-login/.kokoro/build.sh
+++ b/packages/google-cloud-os-login/.kokoro/build.sh
@@ -36,4 +36,10 @@ python3.6 -m pip uninstall --yes --quiet nox-automation
python3.6 -m pip install --upgrade --quiet nox
python3.6 -m nox --version
-python3.6 -m nox
+# If NOX_SESSION is set, it only runs the specified session,
+# otherwise run all the sessions.
+if [[ -n "${NOX_SESSION:-}" ]]; then
+ python3.6 -m nox -s "${NOX_SESSION:-}"
+else
+ python3.6 -m nox
+fi
diff --git a/packages/google-cloud-os-login/.kokoro/docker/docs/Dockerfile b/packages/google-cloud-os-login/.kokoro/docker/docs/Dockerfile
new file mode 100644
index 000000000000..412b0b56a921
--- /dev/null
+++ b/packages/google-cloud-os-login/.kokoro/docker/docs/Dockerfile
@@ -0,0 +1,98 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from ubuntu:20.04
+
+ENV DEBIAN_FRONTEND noninteractive
+
+# Ensure local Python is preferred over distribution Python.
+ENV PATH /usr/local/bin:$PATH
+
+# Install dependencies.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends \
+ apt-transport-https \
+ build-essential \
+ ca-certificates \
+ curl \
+ dirmngr \
+ git \
+ gpg-agent \
+ graphviz \
+ libbz2-dev \
+ libdb5.3-dev \
+ libexpat1-dev \
+ libffi-dev \
+ liblzma-dev \
+ libreadline-dev \
+ libsnappy-dev \
+ libssl-dev \
+ libsqlite3-dev \
+ portaudio19-dev \
+ redis-server \
+ software-properties-common \
+ ssh \
+ sudo \
+ tcl \
+ tcl-dev \
+ tk \
+ tk-dev \
+ uuid-dev \
+ wget \
+ zlib1g-dev \
+ && add-apt-repository universe \
+ && apt-get update \
+ && apt-get -y install jq \
+ && apt-get clean autoclean \
+ && apt-get autoremove -y \
+ && rm -rf /var/lib/apt/lists/* \
+ && rm -f /var/cache/apt/archives/*.deb
+
+
+COPY fetch_gpg_keys.sh /tmp
+# Install the desired versions of Python.
+RUN set -ex \
+ && export GNUPGHOME="$(mktemp -d)" \
+ && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \
+ && /tmp/fetch_gpg_keys.sh \
+ && for PYTHON_VERSION in 3.7.8 3.8.5; do \
+ wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \
+ && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \
+ && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \
+ && rm -r python-${PYTHON_VERSION}.tar.xz.asc \
+ && mkdir -p /usr/src/python-${PYTHON_VERSION} \
+ && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \
+ && rm python-${PYTHON_VERSION}.tar.xz \
+ && cd /usr/src/python-${PYTHON_VERSION} \
+ && ./configure \
+ --enable-shared \
+ # This works only on Python 2.7 and throws a warning on every other
+ # version, but seems otherwise harmless.
+ --enable-unicode=ucs4 \
+ --with-system-ffi \
+ --without-ensurepip \
+ && make -j$(nproc) \
+ && make install \
+ && ldconfig \
+ ; done \
+ && rm -rf "${GNUPGHOME}" \
+ && rm -rf /usr/src/python* \
+ && rm -rf ~/.cache/
+
+RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \
+ && python3.7 /tmp/get-pip.py \
+ && python3.8 /tmp/get-pip.py \
+ && rm /tmp/get-pip.py
+
+CMD ["python3.7"]
diff --git a/packages/google-cloud-os-login/.kokoro/docker/docs/fetch_gpg_keys.sh b/packages/google-cloud-os-login/.kokoro/docker/docs/fetch_gpg_keys.sh
new file mode 100755
index 000000000000..d653dd868e4b
--- /dev/null
+++ b/packages/google-cloud-os-login/.kokoro/docker/docs/fetch_gpg_keys.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# A script to fetch gpg keys with retry.
+# Avoid jinja parsing the file.
+#
+
+function retry {
+ if [[ "${#}" -le 1 ]]; then
+ echo "Usage: ${0} retry_count commands.."
+ exit 1
+ fi
+ local retries=${1}
+ local command="${@:2}"
+ until [[ "${retries}" -le 0 ]]; do
+ $command && return 0
+ if [[ $? -ne 0 ]]; then
+ echo "command failed, retrying"
+ ((retries--))
+ fi
+ done
+ return 1
+}
+
+# 3.6.9, 3.7.5 (Ned Deily)
+retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \
+ 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D
+
+# 3.8.0 (Ćukasz Langa)
+retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \
+ E3FF2839C048B25C084DEBE9B26995E310250568
+
+#
diff --git a/packages/google-cloud-os-login/.kokoro/docs/common.cfg b/packages/google-cloud-os-login/.kokoro/docs/common.cfg
index c8dcdc242375..4f186ed20cf2 100644
--- a/packages/google-cloud-os-login/.kokoro/docs/common.cfg
+++ b/packages/google-cloud-os-login/.kokoro/docs/common.cfg
@@ -11,12 +11,12 @@ action {
gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline"
# Use the trampoline script to run in docker.
-build_file: "python-oslogin/.kokoro/trampoline.sh"
+build_file: "python-oslogin/.kokoro/trampoline_v2.sh"
# Configure the docker image for kokoro-trampoline.
env_vars: {
key: "TRAMPOLINE_IMAGE"
- value: "gcr.io/cloud-devrel-kokoro-resources/python-multi"
+ value: "gcr.io/cloud-devrel-kokoro-resources/python-lib-docs"
}
env_vars: {
key: "TRAMPOLINE_BUILD_FILE"
@@ -28,6 +28,23 @@ env_vars: {
value: "docs-staging"
}
+env_vars: {
+ key: "V2_STAGING_BUCKET"
+ value: "docs-staging-v2-staging"
+}
+
+# It will upload the docker image after successful builds.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE_UPLOAD"
+ value: "true"
+}
+
+# It will always build the docker image.
+env_vars: {
+ key: "TRAMPOLINE_DOCKERFILE"
+ value: ".kokoro/docker/docs/Dockerfile"
+}
+
# Fetch the token needed for reporting release status to GitHub
before_action {
fetch_keystore {
diff --git a/packages/google-cloud-os-login/.kokoro/docs/docs-presubmit.cfg b/packages/google-cloud-os-login/.kokoro/docs/docs-presubmit.cfg
new file mode 100644
index 000000000000..1118107829b7
--- /dev/null
+++ b/packages/google-cloud-os-login/.kokoro/docs/docs-presubmit.cfg
@@ -0,0 +1,17 @@
+# Format: //devtools/kokoro/config/proto/build.proto
+
+env_vars: {
+ key: "STAGING_BUCKET"
+ value: "gcloud-python-test"
+}
+
+env_vars: {
+ key: "V2_STAGING_BUCKET"
+ value: "gcloud-python-test"
+}
+
+# We only upload the image in the main `docs` build.
+env_vars: {
+ key: "TRAMPOLINE_IMAGE_UPLOAD"
+ value: "false"
+}
diff --git a/packages/google-cloud-os-login/.kokoro/populate-secrets.sh b/packages/google-cloud-os-login/.kokoro/populate-secrets.sh
new file mode 100755
index 000000000000..f52514257ef0
--- /dev/null
+++ b/packages/google-cloud-os-login/.kokoro/populate-secrets.sh
@@ -0,0 +1,43 @@
+#!/bin/bash
+# Copyright 2020 Google LLC.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+set -eo pipefail
+
+function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;}
+function msg { println "$*" >&2 ;}
+function println { printf '%s\n' "$(now) $*" ;}
+
+
+# Populates requested secrets set in SECRET_MANAGER_KEYS from service account:
+# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com
+SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager"
+msg "Creating folder on disk for secrets: ${SECRET_LOCATION}"
+mkdir -p ${SECRET_LOCATION}
+for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g")
+do
+ msg "Retrieving secret ${key}"
+ docker run --entrypoint=gcloud \
+ --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \
+ gcr.io/google.com/cloudsdktool/cloud-sdk \
+ secrets versions access latest \
+ --project cloud-devrel-kokoro-resources \
+ --secret ${key} > \
+ "${SECRET_LOCATION}/${key}"
+ if [[ $? == 0 ]]; then
+ msg "Secret written to ${SECRET_LOCATION}/${key}"
+ else
+ msg "Error retrieving secret ${key}"
+ fi
+done
diff --git a/packages/google-cloud-os-login/.kokoro/publish-docs.sh b/packages/google-cloud-os-login/.kokoro/publish-docs.sh
index 7a8b82b2524d..8acb14e802b0 100755
--- a/packages/google-cloud-os-login/.kokoro/publish-docs.sh
+++ b/packages/google-cloud-os-login/.kokoro/publish-docs.sh
@@ -18,26 +18,16 @@ set -eo pipefail
# Disable buffering, so that the logs stream through.
export PYTHONUNBUFFERED=1
-cd github/python-oslogin
-
-# Remove old nox
-python3.6 -m pip uninstall --yes --quiet nox-automation
+export PATH="${HOME}/.local/bin:${PATH}"
# Install nox
-python3.6 -m pip install --upgrade --quiet nox
-python3.6 -m nox --version
+python3 -m pip install --user --upgrade --quiet nox
+python3 -m nox --version
# build docs
nox -s docs
-python3 -m pip install gcp-docuploader
-
-# install a json parser
-sudo apt-get update
-sudo apt-get -y install software-properties-common
-sudo add-apt-repository universe
-sudo apt-get update
-sudo apt-get -y install jq
+python3 -m pip install --user gcp-docuploader
# create metadata
python3 -m docuploader create-metadata \
@@ -52,4 +42,23 @@ python3 -m docuploader create-metadata \
cat docs.metadata
# upload docs
-python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket docs-staging
+python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket "${STAGING_BUCKET}"
+
+
+# docfx yaml files
+nox -s docfx
+
+# create metadata.
+python3 -m docuploader create-metadata \
+ --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \
+ --version=$(python3 setup.py --version) \
+ --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \
+ --distribution-name=$(python3 setup.py --name) \
+ --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \
+ --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \
+ --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json)
+
+cat docs.metadata
+
+# upload docs
+python3 -m docuploader upload docs/_build/html/docfx_yaml --metadata-file docs.metadata --destination-prefix docfx --staging-bucket "${V2_STAGING_BUCKET}"
diff --git a/packages/google-cloud-os-login/.kokoro/release/common.cfg b/packages/google-cloud-os-login/.kokoro/release/common.cfg
index 63ecf1746ed0..e472c13e4988 100644
--- a/packages/google-cloud-os-login/.kokoro/release/common.cfg
+++ b/packages/google-cloud-os-login/.kokoro/release/common.cfg
@@ -23,42 +23,18 @@ env_vars: {
value: "github/python-oslogin/.kokoro/release.sh"
}
-# Fetch the token needed for reporting release status to GitHub
-before_action {
- fetch_keystore {
- keystore_resource {
- keystore_config_id: 73713
- keyname: "yoshi-automation-github-key"
- }
- }
-}
-
-# Fetch PyPI password
-before_action {
- fetch_keystore {
- keystore_resource {
- keystore_config_id: 73713
- keyname: "google_cloud_pypi_password"
- }
- }
-}
-
-# Fetch magictoken to use with Magic Github Proxy
-before_action {
- fetch_keystore {
- keystore_resource {
- keystore_config_id: 73713
- keyname: "releasetool-magictoken"
- }
- }
+# Fetch PyPI password
+before_action {
+ fetch_keystore {
+ keystore_resource {
+ keystore_config_id: 73713
+ keyname: "google_cloud_pypi_password"
+ }
+ }
}
-# Fetch api key to use with Magic Github Proxy
-before_action {
- fetch_keystore {
- keystore_resource {
- keystore_config_id: 73713
- keyname: "magic-github-proxy-api-key"
- }
- }
-}
+# Tokens needed to report release status back to GitHub
+env_vars: {
+ key: "SECRET_MANAGER_KEYS"
+ value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem"
+}
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/.kokoro/samples/python3.6/common.cfg b/packages/google-cloud-os-login/.kokoro/samples/python3.6/common.cfg
index c647069053f8..67208789cf9d 100644
--- a/packages/google-cloud-os-login/.kokoro/samples/python3.6/common.cfg
+++ b/packages/google-cloud-os-login/.kokoro/samples/python3.6/common.cfg
@@ -13,6 +13,12 @@ env_vars: {
value: "py-3.6"
}
+# Declare build specific Cloud project.
+env_vars: {
+ key: "BUILD_SPECIFIC_GCLOUD_PROJECT"
+ value: "python-docs-samples-tests-py36"
+}
+
env_vars: {
key: "TRAMPOLINE_BUILD_FILE"
value: "github/python-oslogin/.kokoro/test-samples.sh"
diff --git a/packages/google-cloud-os-login/.kokoro/samples/python3.7/common.cfg b/packages/google-cloud-os-login/.kokoro/samples/python3.7/common.cfg
index 7de55cd6cf5a..35fcd8492aa1 100644
--- a/packages/google-cloud-os-login/.kokoro/samples/python3.7/common.cfg
+++ b/packages/google-cloud-os-login/.kokoro/samples/python3.7/common.cfg
@@ -13,6 +13,12 @@ env_vars: {
value: "py-3.7"
}
+# Declare build specific Cloud project.
+env_vars: {
+ key: "BUILD_SPECIFIC_GCLOUD_PROJECT"
+ value: "python-docs-samples-tests-py37"
+}
+
env_vars: {
key: "TRAMPOLINE_BUILD_FILE"
value: "github/python-oslogin/.kokoro/test-samples.sh"
diff --git a/packages/google-cloud-os-login/.kokoro/samples/python3.8/common.cfg b/packages/google-cloud-os-login/.kokoro/samples/python3.8/common.cfg
index ef192852ab18..5dcebe51dead 100644
--- a/packages/google-cloud-os-login/.kokoro/samples/python3.8/common.cfg
+++ b/packages/google-cloud-os-login/.kokoro/samples/python3.8/common.cfg
@@ -13,6 +13,12 @@ env_vars: {
value: "py-3.8"
}
+# Declare build specific Cloud project.
+env_vars: {
+ key: "BUILD_SPECIFIC_GCLOUD_PROJECT"
+ value: "python-docs-samples-tests-py38"
+}
+
env_vars: {
key: "TRAMPOLINE_BUILD_FILE"
value: "github/python-oslogin/.kokoro/test-samples.sh"
diff --git a/packages/google-cloud-os-login/.kokoro/trampoline.sh b/packages/google-cloud-os-login/.kokoro/trampoline.sh
index e8c4251f3ed4..f39236e943a8 100755
--- a/packages/google-cloud-os-login/.kokoro/trampoline.sh
+++ b/packages/google-cloud-os-login/.kokoro/trampoline.sh
@@ -15,9 +15,14 @@
set -eo pipefail
-python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" || ret_code=$?
+# Always run the cleanup script, regardless of the success of bouncing into
+# the container.
+function cleanup() {
+ chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh
+ ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh
+ echo "cleanup";
+}
+trap cleanup EXIT
-chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh
-${KOKORO_GFILE_DIR}/trampoline_cleanup.sh || true
-
-exit ${ret_code}
+$(dirname $0)/populate-secrets.sh # Secret Manager secrets.
+python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py"
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/.kokoro/trampoline_v2.sh b/packages/google-cloud-os-login/.kokoro/trampoline_v2.sh
new file mode 100755
index 000000000000..719bcd5ba84d
--- /dev/null
+++ b/packages/google-cloud-os-login/.kokoro/trampoline_v2.sh
@@ -0,0 +1,487 @@
+#!/usr/bin/env bash
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# trampoline_v2.sh
+#
+# This script does 3 things.
+#
+# 1. Prepare the Docker image for the test
+# 2. Run the Docker with appropriate flags to run the test
+# 3. Upload the newly built Docker image
+#
+# in a way that is somewhat compatible with trampoline_v1.
+#
+# To run this script, first download few files from gcs to /dev/shm.
+# (/dev/shm is passed into the container as KOKORO_GFILE_DIR).
+#
+# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/secrets_viewer_service_account.json /dev/shm
+# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/automl_secrets.txt /dev/shm
+#
+# Then run the script.
+# .kokoro/trampoline_v2.sh
+#
+# These environment variables are required:
+# TRAMPOLINE_IMAGE: The docker image to use.
+# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile.
+#
+# You can optionally change these environment variables:
+# TRAMPOLINE_IMAGE_UPLOAD:
+# (true|false): Whether to upload the Docker image after the
+# successful builds.
+# TRAMPOLINE_BUILD_FILE: The script to run in the docker container.
+# TRAMPOLINE_WORKSPACE: The workspace path in the docker container.
+# Defaults to /workspace.
+# Potentially there are some repo specific envvars in .trampolinerc in
+# the project root.
+
+
+set -euo pipefail
+
+TRAMPOLINE_VERSION="2.0.5"
+
+if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then
+ readonly IO_COLOR_RED="$(tput setaf 1)"
+ readonly IO_COLOR_GREEN="$(tput setaf 2)"
+ readonly IO_COLOR_YELLOW="$(tput setaf 3)"
+ readonly IO_COLOR_RESET="$(tput sgr0)"
+else
+ readonly IO_COLOR_RED=""
+ readonly IO_COLOR_GREEN=""
+ readonly IO_COLOR_YELLOW=""
+ readonly IO_COLOR_RESET=""
+fi
+
+function function_exists {
+ [ $(LC_ALL=C type -t $1)"" == "function" ]
+}
+
+# Logs a message using the given color. The first argument must be one
+# of the IO_COLOR_* variables defined above, such as
+# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the
+# given color. The log message will also have an RFC-3339 timestamp
+# prepended (in UTC). You can disable the color output by setting
+# TERM=vt100.
+function log_impl() {
+ local color="$1"
+ shift
+ local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")"
+ echo "================================================================"
+ echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}"
+ echo "================================================================"
+}
+
+# Logs the given message with normal coloring and a timestamp.
+function log() {
+ log_impl "${IO_COLOR_RESET}" "$@"
+}
+
+# Logs the given message in green with a timestamp.
+function log_green() {
+ log_impl "${IO_COLOR_GREEN}" "$@"
+}
+
+# Logs the given message in yellow with a timestamp.
+function log_yellow() {
+ log_impl "${IO_COLOR_YELLOW}" "$@"
+}
+
+# Logs the given message in red with a timestamp.
+function log_red() {
+ log_impl "${IO_COLOR_RED}" "$@"
+}
+
+readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX)
+readonly tmphome="${tmpdir}/h"
+mkdir -p "${tmphome}"
+
+function cleanup() {
+ rm -rf "${tmpdir}"
+}
+trap cleanup EXIT
+
+RUNNING_IN_CI="${RUNNING_IN_CI:-false}"
+
+# The workspace in the container, defaults to /workspace.
+TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}"
+
+pass_down_envvars=(
+ # TRAMPOLINE_V2 variables.
+ # Tells scripts whether they are running as part of CI or not.
+ "RUNNING_IN_CI"
+ # Indicates which CI system we're in.
+ "TRAMPOLINE_CI"
+ # Indicates the version of the script.
+ "TRAMPOLINE_VERSION"
+)
+
+log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}"
+
+# Detect which CI systems we're in. If we're in any of the CI systems
+# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be
+# the name of the CI system. Both envvars will be passing down to the
+# container for telling which CI system we're in.
+if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then
+ # descriptive env var for indicating it's on CI.
+ RUNNING_IN_CI="true"
+ TRAMPOLINE_CI="kokoro"
+ if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then
+ if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then
+ log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting."
+ exit 1
+ fi
+ # This service account will be activated later.
+ TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json"
+ else
+ if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then
+ gcloud auth list
+ fi
+ log_yellow "Configuring Container Registry access"
+ gcloud auth configure-docker --quiet
+ fi
+ pass_down_envvars+=(
+ # KOKORO dynamic variables.
+ "KOKORO_BUILD_NUMBER"
+ "KOKORO_BUILD_ID"
+ "KOKORO_JOB_NAME"
+ "KOKORO_GIT_COMMIT"
+ "KOKORO_GITHUB_COMMIT"
+ "KOKORO_GITHUB_PULL_REQUEST_NUMBER"
+ "KOKORO_GITHUB_PULL_REQUEST_COMMIT"
+ # For Build Cop Bot
+ "KOKORO_GITHUB_COMMIT_URL"
+ "KOKORO_GITHUB_PULL_REQUEST_URL"
+ )
+elif [[ "${TRAVIS:-}" == "true" ]]; then
+ RUNNING_IN_CI="true"
+ TRAMPOLINE_CI="travis"
+ pass_down_envvars+=(
+ "TRAVIS_BRANCH"
+ "TRAVIS_BUILD_ID"
+ "TRAVIS_BUILD_NUMBER"
+ "TRAVIS_BUILD_WEB_URL"
+ "TRAVIS_COMMIT"
+ "TRAVIS_COMMIT_MESSAGE"
+ "TRAVIS_COMMIT_RANGE"
+ "TRAVIS_JOB_NAME"
+ "TRAVIS_JOB_NUMBER"
+ "TRAVIS_JOB_WEB_URL"
+ "TRAVIS_PULL_REQUEST"
+ "TRAVIS_PULL_REQUEST_BRANCH"
+ "TRAVIS_PULL_REQUEST_SHA"
+ "TRAVIS_PULL_REQUEST_SLUG"
+ "TRAVIS_REPO_SLUG"
+ "TRAVIS_SECURE_ENV_VARS"
+ "TRAVIS_TAG"
+ )
+elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then
+ RUNNING_IN_CI="true"
+ TRAMPOLINE_CI="github-workflow"
+ pass_down_envvars+=(
+ "GITHUB_WORKFLOW"
+ "GITHUB_RUN_ID"
+ "GITHUB_RUN_NUMBER"
+ "GITHUB_ACTION"
+ "GITHUB_ACTIONS"
+ "GITHUB_ACTOR"
+ "GITHUB_REPOSITORY"
+ "GITHUB_EVENT_NAME"
+ "GITHUB_EVENT_PATH"
+ "GITHUB_SHA"
+ "GITHUB_REF"
+ "GITHUB_HEAD_REF"
+ "GITHUB_BASE_REF"
+ )
+elif [[ "${CIRCLECI:-}" == "true" ]]; then
+ RUNNING_IN_CI="true"
+ TRAMPOLINE_CI="circleci"
+ pass_down_envvars+=(
+ "CIRCLE_BRANCH"
+ "CIRCLE_BUILD_NUM"
+ "CIRCLE_BUILD_URL"
+ "CIRCLE_COMPARE_URL"
+ "CIRCLE_JOB"
+ "CIRCLE_NODE_INDEX"
+ "CIRCLE_NODE_TOTAL"
+ "CIRCLE_PREVIOUS_BUILD_NUM"
+ "CIRCLE_PROJECT_REPONAME"
+ "CIRCLE_PROJECT_USERNAME"
+ "CIRCLE_REPOSITORY_URL"
+ "CIRCLE_SHA1"
+ "CIRCLE_STAGE"
+ "CIRCLE_USERNAME"
+ "CIRCLE_WORKFLOW_ID"
+ "CIRCLE_WORKFLOW_JOB_ID"
+ "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS"
+ "CIRCLE_WORKFLOW_WORKSPACE_ID"
+ )
+fi
+
+# Configure the service account for pulling the docker image.
+function repo_root() {
+ local dir="$1"
+ while [[ ! -d "${dir}/.git" ]]; do
+ dir="$(dirname "$dir")"
+ done
+ echo "${dir}"
+}
+
+# Detect the project root. In CI builds, we assume the script is in
+# the git tree and traverse from there, otherwise, traverse from `pwd`
+# to find `.git` directory.
+if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then
+ PROGRAM_PATH="$(realpath "$0")"
+ PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")"
+ PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")"
+else
+ PROJECT_ROOT="$(repo_root $(pwd))"
+fi
+
+log_yellow "Changing to the project root: ${PROJECT_ROOT}."
+cd "${PROJECT_ROOT}"
+
+# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need
+# to use this environment variable in `PROJECT_ROOT`.
+if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then
+
+ mkdir -p "${tmpdir}/gcloud"
+ gcloud_config_dir="${tmpdir}/gcloud"
+
+ log_yellow "Using isolated gcloud config: ${gcloud_config_dir}."
+ export CLOUDSDK_CONFIG="${gcloud_config_dir}"
+
+ log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication."
+ gcloud auth activate-service-account \
+ --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}"
+ log_yellow "Configuring Container Registry access"
+ gcloud auth configure-docker --quiet
+fi
+
+required_envvars=(
+ # The basic trampoline configurations.
+ "TRAMPOLINE_IMAGE"
+ "TRAMPOLINE_BUILD_FILE"
+)
+
+if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then
+ source "${PROJECT_ROOT}/.trampolinerc"
+fi
+
+log_yellow "Checking environment variables."
+for e in "${required_envvars[@]}"
+do
+ if [[ -z "${!e:-}" ]]; then
+ log "Missing ${e} env var. Aborting."
+ exit 1
+ fi
+done
+
+# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1
+# script: e.g. "github/repo-name/.kokoro/run_tests.sh"
+TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}"
+log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}"
+
+# ignore error on docker operations and test execution
+set +e
+
+log_yellow "Preparing Docker image."
+# We only download the docker image in CI builds.
+if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then
+ # Download the docker image specified by `TRAMPOLINE_IMAGE`
+
+ # We may want to add --max-concurrent-downloads flag.
+
+ log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}."
+ if docker pull "${TRAMPOLINE_IMAGE}"; then
+ log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}."
+ has_image="true"
+ else
+ log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}."
+ has_image="false"
+ fi
+else
+ # For local run, check if we have the image.
+ if docker images "${TRAMPOLINE_IMAGE}:latest" | grep "${TRAMPOLINE_IMAGE}"; then
+ has_image="true"
+ else
+ has_image="false"
+ fi
+fi
+
+
+# The default user for a Docker container has uid 0 (root). To avoid
+# creating root-owned files in the build directory we tell docker to
+# use the current user ID.
+user_uid="$(id -u)"
+user_gid="$(id -g)"
+user_name="$(id -un)"
+
+# To allow docker in docker, we add the user to the docker group in
+# the host os.
+docker_gid=$(cut -d: -f3 < <(getent group docker))
+
+update_cache="false"
+if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then
+ # Build the Docker image from the source.
+ context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}")
+ docker_build_flags=(
+ "-f" "${TRAMPOLINE_DOCKERFILE}"
+ "-t" "${TRAMPOLINE_IMAGE}"
+ "--build-arg" "UID=${user_uid}"
+ "--build-arg" "USERNAME=${user_name}"
+ )
+ if [[ "${has_image}" == "true" ]]; then
+ docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}")
+ fi
+
+ log_yellow "Start building the docker image."
+ if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then
+ echo "docker build" "${docker_build_flags[@]}" "${context_dir}"
+ fi
+
+ # ON CI systems, we want to suppress docker build logs, only
+ # output the logs when it fails.
+ if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then
+ if docker build "${docker_build_flags[@]}" "${context_dir}" \
+ > "${tmpdir}/docker_build.log" 2>&1; then
+ if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then
+ cat "${tmpdir}/docker_build.log"
+ fi
+
+ log_green "Finished building the docker image."
+ update_cache="true"
+ else
+ log_red "Failed to build the Docker image, aborting."
+ log_yellow "Dumping the build logs:"
+ cat "${tmpdir}/docker_build.log"
+ exit 1
+ fi
+ else
+ if docker build "${docker_build_flags[@]}" "${context_dir}"; then
+ log_green "Finished building the docker image."
+ update_cache="true"
+ else
+ log_red "Failed to build the Docker image, aborting."
+ exit 1
+ fi
+ fi
+else
+ if [[ "${has_image}" != "true" ]]; then
+ log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting."
+ exit 1
+ fi
+fi
+
+# We use an array for the flags so they are easier to document.
+docker_flags=(
+ # Remove the container after it exists.
+ "--rm"
+
+ # Use the host network.
+ "--network=host"
+
+ # Run in priviledged mode. We are not using docker for sandboxing or
+ # isolation, just for packaging our dev tools.
+ "--privileged"
+
+ # Run the docker script with the user id. Because the docker image gets to
+ # write in ${PWD} you typically want this to be your user id.
+ # To allow docker in docker, we need to use docker gid on the host.
+ "--user" "${user_uid}:${docker_gid}"
+
+ # Pass down the USER.
+ "--env" "USER=${user_name}"
+
+ # Mount the project directory inside the Docker container.
+ "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}"
+ "--workdir" "${TRAMPOLINE_WORKSPACE}"
+ "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}"
+
+ # Mount the temporary home directory.
+ "--volume" "${tmphome}:/h"
+ "--env" "HOME=/h"
+
+ # Allow docker in docker.
+ "--volume" "/var/run/docker.sock:/var/run/docker.sock"
+
+ # Mount the /tmp so that docker in docker can mount the files
+ # there correctly.
+ "--volume" "/tmp:/tmp"
+ # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR
+ # TODO(tmatsuo): This part is not portable.
+ "--env" "TRAMPOLINE_SECRET_DIR=/secrets"
+ "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile"
+ "--env" "KOKORO_GFILE_DIR=/secrets/gfile"
+ "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore"
+ "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore"
+)
+
+# Add an option for nicer output if the build gets a tty.
+if [[ -t 0 ]]; then
+ docker_flags+=("-it")
+fi
+
+# Passing down env vars
+for e in "${pass_down_envvars[@]}"
+do
+ if [[ -n "${!e:-}" ]]; then
+ docker_flags+=("--env" "${e}=${!e}")
+ fi
+done
+
+# If arguments are given, all arguments will become the commands run
+# in the container, otherwise run TRAMPOLINE_BUILD_FILE.
+if [[ $# -ge 1 ]]; then
+ log_yellow "Running the given commands '" "${@:1}" "' in the container."
+ readonly commands=("${@:1}")
+ if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then
+ echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}"
+ fi
+ docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}"
+else
+ log_yellow "Running the tests in a Docker container."
+ docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}")
+ if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then
+ echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}"
+ fi
+ docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}"
+fi
+
+
+test_retval=$?
+
+if [[ ${test_retval} -eq 0 ]]; then
+ log_green "Build finished with ${test_retval}"
+else
+ log_red "Build finished with ${test_retval}"
+fi
+
+# Only upload it when the test passes.
+if [[ "${update_cache}" == "true" ]] && \
+ [[ $test_retval == 0 ]] && \
+ [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then
+ log_yellow "Uploading the Docker image."
+ if docker push "${TRAMPOLINE_IMAGE}"; then
+ log_green "Finished uploading the Docker image."
+ else
+ log_red "Failed uploading the Docker image."
+ fi
+ # Call trampoline_after_upload_hook if it's defined.
+ if function_exists trampoline_after_upload_hook; then
+ trampoline_after_upload_hook
+ fi
+
+fi
+
+exit "${test_retval}"
diff --git a/packages/google-cloud-os-login/.trampolinerc b/packages/google-cloud-os-login/.trampolinerc
new file mode 100644
index 000000000000..995ee29111e1
--- /dev/null
+++ b/packages/google-cloud-os-login/.trampolinerc
@@ -0,0 +1,51 @@
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Template for .trampolinerc
+
+# Add required env vars here.
+required_envvars+=(
+ "STAGING_BUCKET"
+ "V2_STAGING_BUCKET"
+)
+
+# Add env vars which are passed down into the container here.
+pass_down_envvars+=(
+ "STAGING_BUCKET"
+ "V2_STAGING_BUCKET"
+)
+
+# Prevent unintentional override on the default image.
+if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \
+ [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then
+ echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image."
+ exit 1
+fi
+
+# Define the default value if it makes sense.
+if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then
+ TRAMPOLINE_IMAGE_UPLOAD=""
+fi
+
+if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then
+ TRAMPOLINE_IMAGE=""
+fi
+
+if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then
+ TRAMPOLINE_DOCKERFILE=""
+fi
+
+if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then
+ TRAMPOLINE_BUILD_FILE=""
+fi
diff --git a/packages/google-cloud-os-login/CONTRIBUTING.rst b/packages/google-cloud-os-login/CONTRIBUTING.rst
index 5af97fbffae3..20b8128d8b43 100644
--- a/packages/google-cloud-os-login/CONTRIBUTING.rst
+++ b/packages/google-cloud-os-login/CONTRIBUTING.rst
@@ -80,25 +80,6 @@ We use `nox `__ to instrument our tests.
.. nox: https://pypi.org/project/nox/
-Note on Editable Installs / Develop Mode
-========================================
-
-- As mentioned previously, using ``setuptools`` in `develop mode`_
- or a ``pip`` `editable install`_ is not possible with this
- library. This is because this library uses `namespace packages`_.
- For context see `Issue #2316`_ and the relevant `PyPA issue`_.
-
- Since ``editable`` / ``develop`` mode can't be used, packages
- need to be installed directly. Hence your changes to the source
- tree don't get incorporated into the **already installed**
- package.
-
-.. _namespace packages: https://www.python.org/dev/peps/pep-0420/
-.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316
-.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12
-.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode
-.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs
-
*****************************************
I'm getting weird errors... Can you help?
*****************************************
diff --git a/packages/google-cloud-os-login/README.rst b/packages/google-cloud-os-login/README.rst
index 189de820fc18..4bd7e0dc7361 100644
--- a/packages/google-cloud-os-login/README.rst
+++ b/packages/google-cloud-os-login/README.rst
@@ -49,11 +49,13 @@ dependencies.
Supported Python Versions
^^^^^^^^^^^^^^^^^^^^^^^^^
-Python >= 3.5
+Python >= 3.6
-Deprecated Python Versions
-^^^^^^^^^^^^^^^^^^^^^^^^^^
-Python == 2.7. Python 2.7 support will be removed on January 1, 2020.
+Unsupported Python Versions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Python == 2.7.
+
+The last version of this library compatible with Python 2.7 is google-cloud-os-login==1.0.0.
Mac/Linux
diff --git a/packages/google-cloud-os-login/UPGRADING.md b/packages/google-cloud-os-login/UPGRADING.md
new file mode 100644
index 000000000000..38abfa0c28da
--- /dev/null
+++ b/packages/google-cloud-os-login/UPGRADING.md
@@ -0,0 +1,162 @@
+# 2.0.0 Migration Guide
+
+The 2.0 release of the `google-cloud-os-login` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage.
+
+If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-oslogin/issues).
+
+## Supported Python Versions
+
+> **WARNING**: Breaking change
+
+The 2.0.0 release requires Python 3.6+.
+
+
+## Method Calls
+
+> **WARNING**: Breaking change
+
+Methods expect request objects. We provide a script that will convert most common use cases.
+
+* Install the library
+
+```py
+python3 -m pip install google-cloud-os-login
+```
+
+* The script `fixup_oslogin_v1_keywords.py` is shipped with the library. It expects
+an input directory (with the code to convert) and an empty destination directory.
+
+```sh
+$ fixup_oslogin_v1_keywords.py --input-directory .samples/ --output-directory samples/
+```
+
+**Before:**
+```py
+from google.cloud import oslogin_v1
+
+client = oslogin_v1.OsLoginServiceClient()
+
+login_profile = client.get_login_profile("login_profile_name")
+```
+
+
+**After:**
+```py
+from google.cloud import oslogin_v1
+
+client = oslogin_v1.OsLoginServiceClient()
+
+login_profile = client.get_login_profile(request={'name': "login_profile_name"})
+```
+
+### More Details
+
+In `google-cloud-os-login<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters.
+
+**Before:**
+```py
+ def update_ssh_public_key(
+ self,
+ name,
+ ssh_public_key,
+ update_mask=None,
+ retry=google.api_core.gapic_v1.method.DEFAULT,
+ timeout=google.api_core.gapic_v1.method.DEFAULT,
+ metadata=None,
+ ):
+```
+
+In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional.
+
+Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer.
+
+
+**After:**
+```py
+ def update_ssh_public_key(
+ self,
+ request: oslogin.UpdateSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ ssh_public_key: common.SshPublicKey = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> common.SshPublicKey:
+```
+
+> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive.
+> Passing both will result in an error.
+
+
+Both of these calls are valid:
+
+```py
+response = client.update_ssh_public_key(
+ request={
+ "name": name,
+ "ssh_public_key": ssh_public_key,
+ "update_mask": update_mask,
+ }
+)
+```
+
+```py
+response = client.update_ssh_public_key(
+ name=name,
+ ssh_public_key=ssh_public_key,
+ update_mask=update_mask,
+)
+```
+
+This call is invalid because it mixes `request` with a keyword argument `update_mask`. Executing this code
+will result in an error.
+
+```py
+response = client.update_ssh_public_key(
+ request={
+ "name": name,
+ "ssh_public_key": ssh_public_key
+ },
+ update_mask=update_mask,
+)
+```
+
+
+
+## Enums and Types
+
+
+> **WARNING**: Breaking change
+
+The submodules `enums` and `types` have been removed.
+
+**Before:**
+```py
+from google.cloud import oslogin_v1
+
+system_type = oslogin_v1.enums.OperatingSystemType.LINUX
+login_profile = oslogin_v1.types.LoginProfile(name="name")
+```
+
+
+**After:**
+```py
+from google.cloud import oslogin_v1
+
+system_type = oslogin_v1.OperatingSystemType.LINUX
+login_profile = oslogin_v1.LoginProfile(name="name")
+```
+
+## Path Helper Methods
+
+The following path helper methods have been removed. Please construct these paths manually.
+
+```py
+project = 'my-project'
+user = 'user'
+
+posix_account_path = f'users/{user}/projects/{project}'
+user_path = f'users/{user}'
+```
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/docs/UPGRADING.md b/packages/google-cloud-os-login/docs/UPGRADING.md
new file mode 120000
index 000000000000..01097c8c0fb8
--- /dev/null
+++ b/packages/google-cloud-os-login/docs/UPGRADING.md
@@ -0,0 +1 @@
+../UPGRADING.md
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/docs/_templates/layout.html b/packages/google-cloud-os-login/docs/_templates/layout.html
index 228529efe2d2..6316a537f72b 100644
--- a/packages/google-cloud-os-login/docs/_templates/layout.html
+++ b/packages/google-cloud-os-login/docs/_templates/layout.html
@@ -21,8 +21,8 @@
- On January 1, 2020 this library will no longer support Python 2 on the latest released version.
- Previously released library versions will continue to be available. For more information please
+ As of January 1, 2020 this library no longer supports Python 2 on the latest released version.
+ Library versions released prior to that date will continue to be available. For more information please
visit
Python 2 support on Google Cloud.
{% block body %} {% endblock %}
diff --git a/packages/google-cloud-os-login/docs/conf.py b/packages/google-cloud-os-login/docs/conf.py
index f82a1562e07c..6829b2da0afe 100644
--- a/packages/google-cloud-os-login/docs/conf.py
+++ b/packages/google-cloud-os-login/docs/conf.py
@@ -20,12 +20,16 @@
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(".."))
+# For plugins that can not read conf.py.
+# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85
+sys.path.insert(0, os.path.abspath("."))
+
__version__ = ""
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
-needs_sphinx = "1.6.3"
+needs_sphinx = "1.5.5"
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@@ -35,6 +39,7 @@
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
+ "sphinx.ext.doctest",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
@@ -90,7 +95,12 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
-exclude_patterns = ["_build"]
+exclude_patterns = [
+ "_build",
+ "samples/AUTHORING_GUIDE.md",
+ "samples/CONTRIBUTING.md",
+ "samples/snippets/README.rst",
+]
# The reST default role (used for this markup: `text`) to use for all
# documents.
diff --git a/packages/google-cloud-os-login/docs/gapic/v1/api.rst b/packages/google-cloud-os-login/docs/gapic/v1/api.rst
deleted file mode 100644
index 25108a16994c..000000000000
--- a/packages/google-cloud-os-login/docs/gapic/v1/api.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-Client for Cloud OS Login API
-=============================
-
-.. automodule:: google.cloud.oslogin_v1
- :members:
- :inherited-members:
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/docs/gapic/v1/types.rst b/packages/google-cloud-os-login/docs/gapic/v1/types.rst
deleted file mode 100644
index 9694a7e3719f..000000000000
--- a/packages/google-cloud-os-login/docs/gapic/v1/types.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-Types for Cloud OS Login API Client
-===================================
-
-.. automodule:: google.cloud.oslogin_v1.types
- :members:
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/docs/index.rst b/packages/google-cloud-os-login/docs/index.rst
index 719f4f9f0092..442c5c6518f6 100644
--- a/packages/google-cloud-os-login/docs/index.rst
+++ b/packages/google-cloud-os-login/docs/index.rst
@@ -7,10 +7,22 @@ Api Reference
.. toctree::
:maxdepth: 2
- gapic/v1/api
- gapic/v1/types
+ oslogin_v1/services
+ oslogin_v1/types
+ oslogin_v1/common/types
+
changelog
+Migration Guide
+---------------
+
+See the guide below for instructions on migrating to the 2.x release of this library.
+
+.. toctree::
+ :maxdepth: 2
+
+ UPGRADING
+
Changelog
---------
diff --git a/packages/google-cloud-os-login/docs/oslogin_v1/common/types.rst b/packages/google-cloud-os-login/docs/oslogin_v1/common/types.rst
new file mode 100644
index 000000000000..c9c3df7a97b1
--- /dev/null
+++ b/packages/google-cloud-os-login/docs/oslogin_v1/common/types.rst
@@ -0,0 +1,5 @@
+Types for Google Cloud Oslogin Common API
+==========================================
+
+.. automodule:: google.cloud.oslogin_v1.common
+ :members:
diff --git a/packages/google-cloud-os-login/docs/oslogin_v1/services.rst b/packages/google-cloud-os-login/docs/oslogin_v1/services.rst
new file mode 100644
index 000000000000..dbdb8bf26aa6
--- /dev/null
+++ b/packages/google-cloud-os-login/docs/oslogin_v1/services.rst
@@ -0,0 +1,6 @@
+Services for Google Cloud Oslogin v1 API
+========================================
+
+.. automodule:: google.cloud.oslogin_v1.services.os_login_service
+ :members:
+ :inherited-members:
diff --git a/packages/google-cloud-os-login/docs/oslogin_v1/types.rst b/packages/google-cloud-os-login/docs/oslogin_v1/types.rst
new file mode 100644
index 000000000000..759411d524f5
--- /dev/null
+++ b/packages/google-cloud-os-login/docs/oslogin_v1/types.rst
@@ -0,0 +1,5 @@
+Types for Google Cloud Oslogin v1 API
+=====================================
+
+.. automodule:: google.cloud.oslogin_v1.types
+ :members:
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin/__init__.py
new file mode 100644
index 000000000000..57af9830ad75
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin/__init__.py
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from google.cloud.oslogin_v1.services.os_login_service.async_client import (
+ OsLoginServiceAsyncClient,
+)
+from google.cloud.oslogin_v1.services.os_login_service.client import (
+ OsLoginServiceClient,
+)
+from google.cloud.oslogin_v1.types.oslogin import DeletePosixAccountRequest
+from google.cloud.oslogin_v1.types.oslogin import DeleteSshPublicKeyRequest
+from google.cloud.oslogin_v1.types.oslogin import GetLoginProfileRequest
+from google.cloud.oslogin_v1.types.oslogin import GetSshPublicKeyRequest
+from google.cloud.oslogin_v1.types.oslogin import ImportSshPublicKeyRequest
+from google.cloud.oslogin_v1.types.oslogin import ImportSshPublicKeyResponse
+from google.cloud.oslogin_v1.types.oslogin import LoginProfile
+from google.cloud.oslogin_v1.types.oslogin import UpdateSshPublicKeyRequest
+
+__all__ = (
+ "DeletePosixAccountRequest",
+ "DeleteSshPublicKeyRequest",
+ "GetLoginProfileRequest",
+ "GetSshPublicKeyRequest",
+ "ImportSshPublicKeyRequest",
+ "ImportSshPublicKeyResponse",
+ "LoginProfile",
+ "OsLoginServiceAsyncClient",
+ "OsLoginServiceClient",
+ "UpdateSshPublicKeyRequest",
+)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin/py.typed b/packages/google-cloud-os-login/google/cloud/oslogin/py.typed
new file mode 100644
index 000000000000..825d05f7f103
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin/py.typed
@@ -0,0 +1,2 @@
+# Marker file for PEP 561.
+# The google-cloud-oslogin package uses inline types.
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/__init__.py
index 08f98e4b6b8f..41e41bfae6df 100644
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/__init__.py
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/__init__.py
@@ -1,45 +1,39 @@
# -*- coding: utf-8 -*-
-#
+
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
-# https://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+#
-
-from __future__ import absolute_import
-import sys
-import warnings
-
-from google.cloud.oslogin_v1 import types
-from google.cloud.oslogin_v1.gapic import enums
-from google.cloud.oslogin_v1.gapic import os_login_service_client
-
-
-if sys.version_info[:2] == (2, 7):
- message = (
- "A future version of this library will drop support for Python 2.7. "
- "More details about Python 2 support for Google Cloud Client Libraries "
- "can be found at https://cloud.google.com/python/docs/python2-sunset/"
- )
- warnings.warn(message, DeprecationWarning)
-
-
-class OsLoginServiceClient(os_login_service_client.OsLoginServiceClient):
- __doc__ = os_login_service_client.OsLoginServiceClient.__doc__
- enums = enums
+from .services.os_login_service import OsLoginServiceClient
+from .types.oslogin import DeletePosixAccountRequest
+from .types.oslogin import DeleteSshPublicKeyRequest
+from .types.oslogin import GetLoginProfileRequest
+from .types.oslogin import GetSshPublicKeyRequest
+from .types.oslogin import ImportSshPublicKeyRequest
+from .types.oslogin import ImportSshPublicKeyResponse
+from .types.oslogin import LoginProfile
+from .types.oslogin import UpdateSshPublicKeyRequest
__all__ = (
- "enums",
- "types",
+ "DeletePosixAccountRequest",
+ "DeleteSshPublicKeyRequest",
+ "GetLoginProfileRequest",
+ "GetSshPublicKeyRequest",
+ "ImportSshPublicKeyRequest",
+ "ImportSshPublicKeyResponse",
+ "LoginProfile",
+ "UpdateSshPublicKeyRequest",
"OsLoginServiceClient",
)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/__init__.py
similarity index 66%
rename from packages/google-cloud-os-login/google/cloud/oslogin.py
rename to packages/google-cloud-os-login/google/cloud/oslogin_v1/common/__init__.py
index 022d27d3f90d..6ac5dc142ba7 100644
--- a/packages/google-cloud-os-login/google/cloud/oslogin.py
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/__init__.py
@@ -1,29 +1,27 @@
# -*- coding: utf-8 -*-
-#
+
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
-# https://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+#
-
-from __future__ import absolute_import
-
-from google.cloud.oslogin_v1 import OsLoginServiceClient
-from google.cloud.oslogin_v1 import enums
-from google.cloud.oslogin_v1 import types
+from .types.common import OperatingSystemType
+from .types.common import PosixAccount
+from .types.common import SshPublicKey
__all__ = (
- "enums",
- "types",
- "OsLoginServiceClient",
+ "OperatingSystemType",
+ "SshPublicKey",
+ "PosixAccount",
)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/py.typed b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/py.typed
new file mode 100644
index 000000000000..5f0cbe7c69cd
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/py.typed
@@ -0,0 +1,2 @@
+# Marker file for PEP 561.
+# The google-cloud-oslogin-common package uses inline types.
diff --git a/packages/google-cloud-os-login/google/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/__init__.py
similarity index 71%
rename from packages/google-cloud-os-login/google/__init__.py
rename to packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/__init__.py
index 9a1b64a6d586..1f648d32af93 100644
--- a/packages/google-cloud-os-login/google/__init__.py
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/__init__.py
@@ -1,24 +1,27 @@
# -*- coding: utf-8 -*-
-#
+
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
-# https://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+#
-try:
- import pkg_resources
+from .common import (
+ PosixAccount,
+ SshPublicKey,
+)
- pkg_resources.declare_namespace(__name__)
-except ImportError:
- import pkgutil
- __path__ = pkgutil.extend_path(__path__, __name__)
+__all__ = (
+ "PosixAccount",
+ "SshPublicKey",
+)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/common.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/common.py
new file mode 100644
index 000000000000..52dc2e0bf6e9
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/common/types/common.py
@@ -0,0 +1,121 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.cloud.oslogin.v1",
+ manifest={"OperatingSystemType", "PosixAccount", "SshPublicKey",},
+)
+
+
+class OperatingSystemType(proto.Enum):
+ r"""The operating system options for account entries."""
+ OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0
+ LINUX = 1
+ WINDOWS = 2
+
+
+class PosixAccount(proto.Message):
+ r"""The POSIX account information associated with a Google
+ account.
+
+ Attributes:
+ primary (bool):
+ Only one POSIX account can be marked as
+ primary.
+ username (str):
+ The username of the POSIX account.
+ uid (int):
+ The user ID.
+ gid (int):
+ The default group ID.
+ home_directory (str):
+ The path to the home directory for this
+ account.
+ shell (str):
+ The path to the logic shell for this account.
+ gecos (str):
+ The GECOS (user information) entry for this
+ account.
+ system_id (str):
+ System identifier for which account the
+ username or uid applies to. By default, the
+ empty value is used.
+ account_id (str):
+ Output only. A POSIX account identifier.
+ operating_system_type (~.common.OperatingSystemType):
+ The operating system type where this account
+ applies.
+ name (str):
+ Output only. The canonical resource name.
+ """
+
+ primary = proto.Field(proto.BOOL, number=1)
+
+ username = proto.Field(proto.STRING, number=2)
+
+ uid = proto.Field(proto.INT64, number=3)
+
+ gid = proto.Field(proto.INT64, number=4)
+
+ home_directory = proto.Field(proto.STRING, number=5)
+
+ shell = proto.Field(proto.STRING, number=6)
+
+ gecos = proto.Field(proto.STRING, number=7)
+
+ system_id = proto.Field(proto.STRING, number=8)
+
+ account_id = proto.Field(proto.STRING, number=9)
+
+ operating_system_type = proto.Field(
+ proto.ENUM, number=10, enum="OperatingSystemType",
+ )
+
+ name = proto.Field(proto.STRING, number=11)
+
+
+class SshPublicKey(proto.Message):
+ r"""The SSH public key information associated with a Google
+ account.
+
+ Attributes:
+ key (str):
+ Public key text in SSH format, defined by RFC4253 section
+ 6.6.
+ expiration_time_usec (int):
+ An expiration time in microseconds since
+ epoch.
+ fingerprint (str):
+ Output only. The SHA-256 fingerprint of the
+ SSH public key.
+ name (str):
+ Output only. The canonical resource name.
+ """
+
+ key = proto.Field(proto.STRING, number=1)
+
+ expiration_time_usec = proto.Field(proto.INT64, number=2)
+
+ fingerprint = proto.Field(proto.STRING, number=3)
+
+ name = proto.Field(proto.STRING, number=4)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/enums.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/enums.py
deleted file mode 100644
index 48c48da09224..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/enums.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Wrappers for protocol buffer enum types."""
-
-import enum
-
-
-class OperatingSystemType(enum.IntEnum):
- """
- The operating system options for account entries.
-
- Attributes:
- OPERATING_SYSTEM_TYPE_UNSPECIFIED (int): The operating system type associated with the user account information is
- unspecified.
- LINUX (int): Linux user account information.
- WINDOWS (int): Windows user account information.
- """
-
- OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0
- LINUX = 1
- WINDOWS = 2
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client.py
deleted file mode 100644
index 2f8e11efba14..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client.py
+++ /dev/null
@@ -1,664 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Accesses the google.cloud.oslogin.v1 OsLoginService API."""
-
-import pkg_resources
-import warnings
-
-from google.oauth2 import service_account
-import google.api_core.client_options
-import google.api_core.gapic_v1.client_info
-import google.api_core.gapic_v1.config
-import google.api_core.gapic_v1.method
-import google.api_core.gapic_v1.routing_header
-import google.api_core.grpc_helpers
-import google.api_core.path_template
-import grpc
-
-from google.cloud.oslogin_v1.gapic import enums
-from google.cloud.oslogin_v1.gapic import os_login_service_client_config
-from google.cloud.oslogin_v1.gapic.transports import os_login_service_grpc_transport
-from google.cloud.oslogin_v1.proto import common_pb2
-from google.cloud.oslogin_v1.proto import oslogin_pb2
-from google.cloud.oslogin_v1.proto import oslogin_pb2_grpc
-from google.protobuf import empty_pb2
-from google.protobuf import field_mask_pb2
-
-
-_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
- "google-cloud-os-login",
-).version
-
-
-class OsLoginServiceClient(object):
- """
- Cloud OS Login API
-
- The Cloud OS Login API allows you to manage users and their associated SSH
- public keys for logging into virtual machines on Google Cloud Platform.
- """
-
- SERVICE_ADDRESS = "oslogin.googleapis.com:443"
- """The default address of the service."""
-
- # The name of the interface for this client. This is the key used to
- # find the method configuration in the client_config dictionary.
- _INTERFACE_NAME = "google.cloud.oslogin.v1.OsLoginService"
-
- @classmethod
- def from_service_account_file(cls, filename, *args, **kwargs):
- """Creates an instance of this client using the provided credentials
- file.
-
- Args:
- filename (str): The path to the service account private key json
- file.
- args: Additional arguments to pass to the constructor.
- kwargs: Additional arguments to pass to the constructor.
-
- Returns:
- OsLoginServiceClient: The constructed client.
- """
- credentials = service_account.Credentials.from_service_account_file(filename)
- kwargs["credentials"] = credentials
- return cls(*args, **kwargs)
-
- from_service_account_json = from_service_account_file
-
- @classmethod
- def posix_account_path(cls, user, project):
- """Return a fully-qualified posix_account string."""
- return google.api_core.path_template.expand(
- "users/{user}/projects/{project}", user=user, project=project,
- )
-
- @classmethod
- def ssh_public_key_path(cls, user, fingerprint):
- """Return a fully-qualified ssh_public_key string."""
- return google.api_core.path_template.expand(
- "users/{user}/sshPublicKeys/{fingerprint}",
- user=user,
- fingerprint=fingerprint,
- )
-
- @classmethod
- def user_path(cls, user):
- """Return a fully-qualified user string."""
- return google.api_core.path_template.expand("users/{user}", user=user,)
-
- def __init__(
- self,
- transport=None,
- channel=None,
- credentials=None,
- client_config=None,
- client_info=None,
- client_options=None,
- ):
- """Constructor.
-
- Args:
- transport (Union[~.OsLoginServiceGrpcTransport,
- Callable[[~.Credentials, type], ~.OsLoginServiceGrpcTransport]): A transport
- instance, responsible for actually making the API calls.
- The default transport uses the gRPC protocol.
- This argument may also be a callable which returns a
- transport instance. Callables will be sent the credentials
- as the first argument and the default transport class as
- the second argument.
- channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
- through which to make calls. This argument is mutually exclusive
- with ``credentials``; providing both will raise an exception.
- credentials (google.auth.credentials.Credentials): The
- authorization credentials to attach to requests. These
- credentials identify this application to the service. If none
- are specified, the client will attempt to ascertain the
- credentials from the environment.
- This argument is mutually exclusive with providing a
- transport instance to ``transport``; doing so will raise
- an exception.
- client_config (dict): DEPRECATED. A dictionary of call options for
- each method. If not specified, the default configuration is used.
- client_info (google.api_core.gapic_v1.client_info.ClientInfo):
- The client info used to send a user-agent string along with
- API requests. If ``None``, then default info will be used.
- Generally, you only need to set this if you're developing
- your own client library.
- client_options (Union[dict, google.api_core.client_options.ClientOptions]):
- Client options used to set user options on the client. API Endpoint
- should be set through client_options.
- """
- # Raise deprecation warnings for things we want to go away.
- if client_config is not None:
- warnings.warn(
- "The `client_config` argument is deprecated.",
- PendingDeprecationWarning,
- stacklevel=2,
- )
- else:
- client_config = os_login_service_client_config.config
-
- if channel:
- warnings.warn(
- "The `channel` argument is deprecated; use " "`transport` instead.",
- PendingDeprecationWarning,
- stacklevel=2,
- )
-
- api_endpoint = self.SERVICE_ADDRESS
- if client_options:
- if type(client_options) == dict:
- client_options = google.api_core.client_options.from_dict(
- client_options
- )
- if client_options.api_endpoint:
- api_endpoint = client_options.api_endpoint
-
- # Instantiate the transport.
- # The transport is responsible for handling serialization and
- # deserialization and actually sending data to the service.
- if transport:
- if callable(transport):
- self.transport = transport(
- credentials=credentials,
- default_class=os_login_service_grpc_transport.OsLoginServiceGrpcTransport,
- address=api_endpoint,
- )
- else:
- if credentials:
- raise ValueError(
- "Received both a transport instance and "
- "credentials; these are mutually exclusive."
- )
- self.transport = transport
- else:
- self.transport = os_login_service_grpc_transport.OsLoginServiceGrpcTransport(
- address=api_endpoint, channel=channel, credentials=credentials,
- )
-
- if client_info is None:
- client_info = google.api_core.gapic_v1.client_info.ClientInfo(
- gapic_version=_GAPIC_LIBRARY_VERSION,
- )
- else:
- client_info.gapic_version = _GAPIC_LIBRARY_VERSION
- self._client_info = client_info
-
- # Parse out the default settings for retry and timeout for each RPC
- # from the client configuration.
- # (Ordinarily, these are the defaults specified in the `*_config.py`
- # file next to this one.)
- self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
- client_config["interfaces"][self._INTERFACE_NAME],
- )
-
- # Save a dictionary of cached API call functions.
- # These are the actual callables which invoke the proper
- # transport methods, wrapped with `wrap_method` to add retry,
- # timeout, and the like.
- self._inner_api_calls = {}
-
- # Service calls
- def delete_posix_account(
- self,
- name,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Deletes a POSIX account.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> name = client.posix_account_path('[USER]', '[PROJECT]')
- >>>
- >>> client.delete_posix_account(name)
-
- Args:
- name (str): Required. A reference to the POSIX account to update. POSIX accounts
- are identified by the project ID they are associated with. A reference
- to the POSIX account is in format ``users/{user}/projects/{project}``.
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "delete_posix_account" not in self._inner_api_calls:
- self._inner_api_calls[
- "delete_posix_account"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.delete_posix_account,
- default_retry=self._method_configs["DeletePosixAccount"].retry,
- default_timeout=self._method_configs["DeletePosixAccount"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.DeletePosixAccountRequest(name=name,)
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("name", name)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- self._inner_api_calls["delete_posix_account"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
-
- def delete_ssh_public_key(
- self,
- name,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Deletes an SSH public key.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]')
- >>>
- >>> client.delete_ssh_public_key(name)
-
- Args:
- name (str): Required. The fingerprint of the public key to update. Public keys
- are identified by their SHA-256 fingerprint. The fingerprint of the
- public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``.
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "delete_ssh_public_key" not in self._inner_api_calls:
- self._inner_api_calls[
- "delete_ssh_public_key"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.delete_ssh_public_key,
- default_retry=self._method_configs["DeleteSshPublicKey"].retry,
- default_timeout=self._method_configs["DeleteSshPublicKey"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.DeleteSshPublicKeyRequest(name=name,)
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("name", name)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- self._inner_api_calls["delete_ssh_public_key"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
-
- def get_login_profile(
- self,
- name,
- project_id=None,
- system_id=None,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Retrieves the profile information used for logging in to a virtual machine
- on Google Compute Engine.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> name = client.user_path('[USER]')
- >>>
- >>> response = client.get_login_profile(name)
-
- Args:
- name (str): Required. The unique ID for the user in format ``users/{user}``.
- project_id (str): The project ID of the Google Cloud Platform project.
- system_id (str): A system ID for filtering the results of the request.
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Returns:
- A :class:`~google.cloud.oslogin_v1.types.LoginProfile` instance.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "get_login_profile" not in self._inner_api_calls:
- self._inner_api_calls[
- "get_login_profile"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.get_login_profile,
- default_retry=self._method_configs["GetLoginProfile"].retry,
- default_timeout=self._method_configs["GetLoginProfile"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.GetLoginProfileRequest(
- name=name, project_id=project_id, system_id=system_id,
- )
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("name", name)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- return self._inner_api_calls["get_login_profile"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
-
- def get_ssh_public_key(
- self,
- name,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Retrieves an SSH public key.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]')
- >>>
- >>> response = client.get_ssh_public_key(name)
-
- Args:
- name (str): Required. The fingerprint of the public key to retrieve. Public keys
- are identified by their SHA-256 fingerprint. The fingerprint of the
- public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``.
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Returns:
- A :class:`~google.cloud.oslogin_v1.types.SshPublicKey` instance.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "get_ssh_public_key" not in self._inner_api_calls:
- self._inner_api_calls[
- "get_ssh_public_key"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.get_ssh_public_key,
- default_retry=self._method_configs["GetSshPublicKey"].retry,
- default_timeout=self._method_configs["GetSshPublicKey"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.GetSshPublicKeyRequest(name=name,)
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("name", name)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- return self._inner_api_calls["get_ssh_public_key"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
-
- def import_ssh_public_key(
- self,
- parent,
- ssh_public_key=None,
- project_id=None,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Adds an SSH public key and returns the profile information. Default POSIX
- account information is set when no username and UID exist as part of the
- login profile.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> parent = client.user_path('[USER]')
- >>>
- >>> response = client.import_ssh_public_key(parent)
-
- Args:
- parent (str): Required. The unique ID for the user in format ``users/{user}``.
- ssh_public_key (Union[dict, ~google.cloud.oslogin_v1.types.SshPublicKey]): Optional. The SSH public key and expiration time.
-
- If a dict is provided, it must be of the same form as the protobuf
- message :class:`~google.cloud.oslogin_v1.types.SshPublicKey`
- project_id (str): The project ID of the Google Cloud Platform project.
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Returns:
- A :class:`~google.cloud.oslogin_v1.types.ImportSshPublicKeyResponse` instance.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "import_ssh_public_key" not in self._inner_api_calls:
- self._inner_api_calls[
- "import_ssh_public_key"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.import_ssh_public_key,
- default_retry=self._method_configs["ImportSshPublicKey"].retry,
- default_timeout=self._method_configs["ImportSshPublicKey"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.ImportSshPublicKeyRequest(
- parent=parent, ssh_public_key=ssh_public_key, project_id=project_id,
- )
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("parent", parent)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- return self._inner_api_calls["import_ssh_public_key"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
-
- def update_ssh_public_key(
- self,
- name,
- ssh_public_key,
- update_mask=None,
- retry=google.api_core.gapic_v1.method.DEFAULT,
- timeout=google.api_core.gapic_v1.method.DEFAULT,
- metadata=None,
- ):
- """
- Updates an SSH public key and returns the profile information. This method
- supports patch semantics.
-
- Example:
- >>> from google.cloud import oslogin_v1
- >>>
- >>> client = oslogin_v1.OsLoginServiceClient()
- >>>
- >>> name = client.ssh_public_key_path('[USER]', '[FINGERPRINT]')
- >>>
- >>> # TODO: Initialize `ssh_public_key`:
- >>> ssh_public_key = {}
- >>>
- >>> response = client.update_ssh_public_key(name, ssh_public_key)
-
- Args:
- name (str): Required. The fingerprint of the public key to update. Public keys
- are identified by their SHA-256 fingerprint. The fingerprint of the
- public key is in format ``users/{user}/sshPublicKeys/{fingerprint}``.
- ssh_public_key (Union[dict, ~google.cloud.oslogin_v1.types.SshPublicKey]): Required. The SSH public key and expiration time.
-
- If a dict is provided, it must be of the same form as the protobuf
- message :class:`~google.cloud.oslogin_v1.types.SshPublicKey`
- update_mask (Union[dict, ~google.cloud.oslogin_v1.types.FieldMask]): Mask to control which fields get updated. Updates all if not present.
-
- If a dict is provided, it must be of the same form as the protobuf
- message :class:`~google.cloud.oslogin_v1.types.FieldMask`
- retry (Optional[google.api_core.retry.Retry]): A retry object used
- to retry requests. If ``None`` is specified, requests will
- be retried using a default configuration.
- timeout (Optional[float]): The amount of time, in seconds, to wait
- for the request to complete. Note that if ``retry`` is
- specified, the timeout applies to each individual attempt.
- metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
- that is provided to the method.
-
- Returns:
- A :class:`~google.cloud.oslogin_v1.types.SshPublicKey` instance.
-
- Raises:
- google.api_core.exceptions.GoogleAPICallError: If the request
- failed for any reason.
- google.api_core.exceptions.RetryError: If the request failed due
- to a retryable error and retry attempts failed.
- ValueError: If the parameters are invalid.
- """
- # Wrap the transport method to add retry and timeout logic.
- if "update_ssh_public_key" not in self._inner_api_calls:
- self._inner_api_calls[
- "update_ssh_public_key"
- ] = google.api_core.gapic_v1.method.wrap_method(
- self.transport.update_ssh_public_key,
- default_retry=self._method_configs["UpdateSshPublicKey"].retry,
- default_timeout=self._method_configs["UpdateSshPublicKey"].timeout,
- client_info=self._client_info,
- )
-
- request = oslogin_pb2.UpdateSshPublicKeyRequest(
- name=name, ssh_public_key=ssh_public_key, update_mask=update_mask,
- )
- if metadata is None:
- metadata = []
- metadata = list(metadata)
- try:
- routing_header = [("name", name)]
- except AttributeError:
- pass
- else:
- routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
- routing_header
- )
- metadata.append(routing_metadata)
-
- return self._inner_api_calls["update_ssh_public_key"](
- request, retry=retry, timeout=timeout, metadata=metadata
- )
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py
deleted file mode 100644
index cc3bb692e009..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/os_login_service_client_config.py
+++ /dev/null
@@ -1,62 +0,0 @@
-config = {
- "interfaces": {
- "google.cloud.oslogin.v1.OsLoginService": {
- "retry_codes": {
- "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"],
- "no_retry_codes": [],
- },
- "retry_params": {
- "retry_policy_1_params": {
- "initial_retry_delay_millis": 100,
- "retry_delay_multiplier": 1.3,
- "max_retry_delay_millis": 60000,
- "initial_rpc_timeout_millis": 10000,
- "rpc_timeout_multiplier": 1.0,
- "max_rpc_timeout_millis": 10000,
- "total_timeout_millis": 10000,
- },
- "no_retry_params": {
- "initial_retry_delay_millis": 0,
- "retry_delay_multiplier": 0.0,
- "max_retry_delay_millis": 0,
- "initial_rpc_timeout_millis": 0,
- "rpc_timeout_multiplier": 1.0,
- "max_rpc_timeout_millis": 0,
- "total_timeout_millis": 0,
- },
- },
- "methods": {
- "DeletePosixAccount": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- "DeleteSshPublicKey": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- "GetLoginProfile": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- "GetSshPublicKey": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- "ImportSshPublicKey": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- "UpdateSshPublicKey": {
- "timeout_millis": 10000,
- "retry_codes_name": "retry_policy_1_codes",
- "retry_params_name": "retry_policy_1_params",
- },
- },
- }
- }
-}
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/transports/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/transports/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py
deleted file mode 100644
index 1ee7295d9f9a..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/gapic/transports/os_login_service_grpc_transport.py
+++ /dev/null
@@ -1,193 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-import google.api_core.grpc_helpers
-
-from google.cloud.oslogin_v1.proto import oslogin_pb2_grpc
-
-
-class OsLoginServiceGrpcTransport(object):
- """gRPC transport class providing stubs for
- google.cloud.oslogin.v1 OsLoginService API.
-
- The transport provides access to the raw gRPC stubs,
- which can be used to take advantage of advanced
- features of gRPC.
- """
-
- # The scopes needed to make gRPC calls to all of the methods defined
- # in this service.
- _OAUTH_SCOPES = (
- "https://www.googleapis.com/auth/cloud-platform",
- "https://www.googleapis.com/auth/compute",
- )
-
- def __init__(
- self, channel=None, credentials=None, address="oslogin.googleapis.com:443"
- ):
- """Instantiate the transport class.
-
- Args:
- channel (grpc.Channel): A ``Channel`` instance through
- which to make calls. This argument is mutually exclusive
- with ``credentials``; providing both will raise an exception.
- credentials (google.auth.credentials.Credentials): The
- authorization credentials to attach to requests. These
- credentials identify this application to the service. If none
- are specified, the client will attempt to ascertain the
- credentials from the environment.
- address (str): The address where the service is hosted.
- """
- # If both `channel` and `credentials` are specified, raise an
- # exception (channels come with credentials baked in already).
- if channel is not None and credentials is not None:
- raise ValueError(
- "The `channel` and `credentials` arguments are mutually " "exclusive.",
- )
-
- # Create the channel.
- if channel is None:
- channel = self.create_channel(
- address=address,
- credentials=credentials,
- options={
- "grpc.max_send_message_length": -1,
- "grpc.max_receive_message_length": -1,
- }.items(),
- )
-
- self._channel = channel
-
- # gRPC uses objects called "stubs" that are bound to the
- # channel and provide a basic method for each RPC.
- self._stubs = {
- "os_login_service_stub": oslogin_pb2_grpc.OsLoginServiceStub(channel),
- }
-
- @classmethod
- def create_channel(
- cls, address="oslogin.googleapis.com:443", credentials=None, **kwargs
- ):
- """Create and return a gRPC channel object.
-
- Args:
- address (str): The host for the channel to use.
- credentials (~.Credentials): The
- authorization credentials to attach to requests. These
- credentials identify this application to the service. If
- none are specified, the client will attempt to ascertain
- the credentials from the environment.
- kwargs (dict): Keyword arguments, which are passed to the
- channel creation.
-
- Returns:
- grpc.Channel: A gRPC channel object.
- """
- return google.api_core.grpc_helpers.create_channel(
- address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs
- )
-
- @property
- def channel(self):
- """The gRPC channel used by the transport.
-
- Returns:
- grpc.Channel: A gRPC channel object.
- """
- return self._channel
-
- @property
- def delete_posix_account(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.delete_posix_account`.
-
- Deletes a POSIX account.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].DeletePosixAccount
-
- @property
- def delete_ssh_public_key(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.delete_ssh_public_key`.
-
- Deletes an SSH public key.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].DeleteSshPublicKey
-
- @property
- def get_login_profile(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.get_login_profile`.
-
- Retrieves the profile information used for logging in to a virtual machine
- on Google Compute Engine.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].GetLoginProfile
-
- @property
- def get_ssh_public_key(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.get_ssh_public_key`.
-
- Retrieves an SSH public key.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].GetSshPublicKey
-
- @property
- def import_ssh_public_key(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.import_ssh_public_key`.
-
- Adds an SSH public key and returns the profile information. Default POSIX
- account information is set when no username and UID exist as part of the
- login profile.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].ImportSshPublicKey
-
- @property
- def update_ssh_public_key(self):
- """Return the gRPC stub for :meth:`OsLoginServiceClient.update_ssh_public_key`.
-
- Updates an SSH public key and returns the profile information. This method
- supports patch semantics.
-
- Returns:
- Callable: A callable which accepts the appropriate
- deserialized request object and returns a
- deserialized response object.
- """
- return self._stubs["os_login_service_stub"].UpdateSshPublicKey
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2.py
deleted file mode 100644
index cfc12d195f17..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2.py
+++ /dev/null
@@ -1,481 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: google/cloud/oslogin/common/common.proto
-
-from google.protobuf.internal import enum_type_wrapper
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from google.protobuf import reflection as _reflection
-from google.protobuf import symbol_database as _symbol_database
-
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2
-from google.api import resource_pb2 as google_dot_api_dot_resource__pb2
-
-
-DESCRIPTOR = _descriptor.FileDescriptor(
- name="google/cloud/oslogin/common/common.proto",
- package="google.cloud.oslogin.common",
- syntax="proto3",
- serialized_options=b"\n\037com.google.cloud.oslogin.commonB\014OsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\252\002\033Google.Cloud.OsLogin.Common\312\002\033Google\\Cloud\\OsLogin\\Common\352\002\036Google::Cloud::OsLogin::Common\352A+\n\033oslogin.googleapis.com/User\022\014users/{user}",
- create_key=_descriptor._internal_create_key,
- serialized_pb=b'\n(google/cloud/oslogin/common/common.proto\x12\x1bgoogle.cloud.oslogin.common\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto"\xdc\x02\n\x0cPosixAccount\x12\x0f\n\x07primary\x18\x01 \x01(\x08\x12\x10\n\x08username\x18\x02 \x01(\t\x12\x0b\n\x03uid\x18\x03 \x01(\x03\x12\x0b\n\x03gid\x18\x04 \x01(\x03\x12\x16\n\x0ehome_directory\x18\x05 \x01(\t\x12\r\n\x05shell\x18\x06 \x01(\t\x12\r\n\x05gecos\x18\x07 \x01(\t\x12\x11\n\tsystem_id\x18\x08 \x01(\t\x12\x17\n\naccount_id\x18\t \x01(\tB\x03\xe0\x41\x03\x12O\n\x15operating_system_type\x18\n \x01(\x0e\x32\x30.google.cloud.oslogin.common.OperatingSystemType\x12\x11\n\x04name\x18\x0b \x01(\tB\x03\xe0\x41\x03:I\xea\x41\x46\n#oslogin.googleapis.com/PosixAccount\x12\x1fusers/{user}/projects/{project}"\xba\x01\n\x0cSshPublicKey\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x1c\n\x14\x65xpiration_time_usec\x18\x02 \x01(\x03\x12\x18\n\x0b\x66ingerprint\x18\x03 \x01(\tB\x03\xe0\x41\x03\x12\x11\n\x04name\x18\x04 \x01(\tB\x03\xe0\x41\x03:R\xea\x41O\n#oslogin.googleapis.com/SshPublicKey\x12(users/{user}/sshPublicKeys/{fingerprint}*T\n\x13OperatingSystemType\x12%\n!OPERATING_SYSTEM_TYPE_UNSPECIFIED\x10\x00\x12\t\n\x05LINUX\x10\x01\x12\x0b\n\x07WINDOWS\x10\x02\x42\xfd\x01\n\x1f\x63om.google.cloud.oslogin.commonB\x0cOsLoginProtoZAgoogle.golang.org/genproto/googleapis/cloud/oslogin/common;common\xaa\x02\x1bGoogle.Cloud.OsLogin.Common\xca\x02\x1bGoogle\\Cloud\\OsLogin\\Common\xea\x02\x1eGoogle::Cloud::OsLogin::Common\xea\x41+\n\x1boslogin.googleapis.com/User\x12\x0cusers/{user}b\x06proto3',
- dependencies=[
- google_dot_api_dot_field__behavior__pb2.DESCRIPTOR,
- google_dot_api_dot_resource__pb2.DESCRIPTOR,
- ],
-)
-
-_OPERATINGSYSTEMTYPE = _descriptor.EnumDescriptor(
- name="OperatingSystemType",
- full_name="google.cloud.oslogin.common.OperatingSystemType",
- filename=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- values=[
- _descriptor.EnumValueDescriptor(
- name="OPERATING_SYSTEM_TYPE_UNSPECIFIED",
- index=0,
- number=0,
- serialized_options=None,
- type=None,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.EnumValueDescriptor(
- name="LINUX",
- index=1,
- number=1,
- serialized_options=None,
- type=None,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.EnumValueDescriptor(
- name="WINDOWS",
- index=2,
- number=2,
- serialized_options=None,
- type=None,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- containing_type=None,
- serialized_options=None,
- serialized_start=673,
- serialized_end=757,
-)
-_sym_db.RegisterEnumDescriptor(_OPERATINGSYSTEMTYPE)
-
-OperatingSystemType = enum_type_wrapper.EnumTypeWrapper(_OPERATINGSYSTEMTYPE)
-OPERATING_SYSTEM_TYPE_UNSPECIFIED = 0
-LINUX = 1
-WINDOWS = 2
-
-
-_POSIXACCOUNT = _descriptor.Descriptor(
- name="PosixAccount",
- full_name="google.cloud.oslogin.common.PosixAccount",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="primary",
- full_name="google.cloud.oslogin.common.PosixAccount.primary",
- index=0,
- number=1,
- type=8,
- cpp_type=7,
- label=1,
- has_default_value=False,
- default_value=False,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="username",
- full_name="google.cloud.oslogin.common.PosixAccount.username",
- index=1,
- number=2,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="uid",
- full_name="google.cloud.oslogin.common.PosixAccount.uid",
- index=2,
- number=3,
- type=3,
- cpp_type=2,
- label=1,
- has_default_value=False,
- default_value=0,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="gid",
- full_name="google.cloud.oslogin.common.PosixAccount.gid",
- index=3,
- number=4,
- type=3,
- cpp_type=2,
- label=1,
- has_default_value=False,
- default_value=0,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="home_directory",
- full_name="google.cloud.oslogin.common.PosixAccount.home_directory",
- index=4,
- number=5,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="shell",
- full_name="google.cloud.oslogin.common.PosixAccount.shell",
- index=5,
- number=6,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="gecos",
- full_name="google.cloud.oslogin.common.PosixAccount.gecos",
- index=6,
- number=7,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="system_id",
- full_name="google.cloud.oslogin.common.PosixAccount.system_id",
- index=7,
- number=8,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="account_id",
- full_name="google.cloud.oslogin.common.PosixAccount.account_id",
- index=8,
- number=9,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\003",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="operating_system_type",
- full_name="google.cloud.oslogin.common.PosixAccount.operating_system_type",
- index=9,
- number=10,
- type=14,
- cpp_type=8,
- label=1,
- has_default_value=False,
- default_value=0,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.common.PosixAccount.name",
- index=10,
- number=11,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\003",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=b"\352AF\n#oslogin.googleapis.com/PosixAccount\022\037users/{user}/projects/{project}",
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=134,
- serialized_end=482,
-)
-
-
-_SSHPUBLICKEY = _descriptor.Descriptor(
- name="SshPublicKey",
- full_name="google.cloud.oslogin.common.SshPublicKey",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="key",
- full_name="google.cloud.oslogin.common.SshPublicKey.key",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="expiration_time_usec",
- full_name="google.cloud.oslogin.common.SshPublicKey.expiration_time_usec",
- index=1,
- number=2,
- type=3,
- cpp_type=2,
- label=1,
- has_default_value=False,
- default_value=0,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="fingerprint",
- full_name="google.cloud.oslogin.common.SshPublicKey.fingerprint",
- index=2,
- number=3,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\003",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.common.SshPublicKey.name",
- index=3,
- number=4,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\003",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=b"\352AO\n#oslogin.googleapis.com/SshPublicKey\022(users/{user}/sshPublicKeys/{fingerprint}",
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=485,
- serialized_end=671,
-)
-
-_POSIXACCOUNT.fields_by_name["operating_system_type"].enum_type = _OPERATINGSYSTEMTYPE
-DESCRIPTOR.message_types_by_name["PosixAccount"] = _POSIXACCOUNT
-DESCRIPTOR.message_types_by_name["SshPublicKey"] = _SSHPUBLICKEY
-DESCRIPTOR.enum_types_by_name["OperatingSystemType"] = _OPERATINGSYSTEMTYPE
-_sym_db.RegisterFileDescriptor(DESCRIPTOR)
-
-PosixAccount = _reflection.GeneratedProtocolMessageType(
- "PosixAccount",
- (_message.Message,),
- {
- "DESCRIPTOR": _POSIXACCOUNT,
- "__module__": "google.cloud.oslogin.common.common_pb2",
- "__doc__": """The POSIX account information associated with a Google account.
-
- Attributes:
- primary:
- Only one POSIX account can be marked as primary.
- username:
- The username of the POSIX account.
- uid:
- The user ID.
- gid:
- The default group ID.
- home_directory:
- The path to the home directory for this account.
- shell:
- The path to the logic shell for this account.
- gecos:
- The GECOS (user information) entry for this account.
- system_id:
- System identifier for which account the username or uid
- applies to. By default, the empty value is used.
- account_id:
- Output only. A POSIX account identifier.
- operating_system_type:
- The operating system type where this account applies.
- name:
- Output only. The canonical resource name.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.PosixAccount)
- },
-)
-_sym_db.RegisterMessage(PosixAccount)
-
-SshPublicKey = _reflection.GeneratedProtocolMessageType(
- "SshPublicKey",
- (_message.Message,),
- {
- "DESCRIPTOR": _SSHPUBLICKEY,
- "__module__": "google.cloud.oslogin.common.common_pb2",
- "__doc__": """The SSH public key information associated with a Google account.
-
- Attributes:
- key:
- Public key text in SSH format, defined by RFC4253 section 6.6.
- expiration_time_usec:
- An expiration time in microseconds since epoch.
- fingerprint:
- Output only. The SHA-256 fingerprint of the SSH public key.
- name:
- Output only. The canonical resource name.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.common.SshPublicKey)
- },
-)
-_sym_db.RegisterMessage(SshPublicKey)
-
-
-DESCRIPTOR._options = None
-_POSIXACCOUNT.fields_by_name["account_id"]._options = None
-_POSIXACCOUNT.fields_by_name["name"]._options = None
-_POSIXACCOUNT._options = None
-_SSHPUBLICKEY.fields_by_name["fingerprint"]._options = None
-_SSHPUBLICKEY.fields_by_name["name"]._options = None
-_SSHPUBLICKEY._options = None
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2_grpc.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2_grpc.py
deleted file mode 100644
index 07cb78fe03a9..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/common_pb2_grpc.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
-import grpc
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2.py
deleted file mode 100644
index 845a4229cabc..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2.py
+++ /dev/null
@@ -1,892 +0,0 @@
-# -*- coding: utf-8 -*-
-# Generated by the protocol buffer compiler. DO NOT EDIT!
-# source: google/cloud/oslogin_v1/proto/oslogin.proto
-
-from google.protobuf import descriptor as _descriptor
-from google.protobuf import message as _message
-from google.protobuf import reflection as _reflection
-from google.protobuf import symbol_database as _symbol_database
-
-# @@protoc_insertion_point(imports)
-
-_sym_db = _symbol_database.Default()
-
-
-from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2
-from google.api import client_pb2 as google_dot_api_dot_client__pb2
-from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2
-from google.api import resource_pb2 as google_dot_api_dot_resource__pb2
-from google.cloud.oslogin_v1.proto import (
- common_pb2 as google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2,
-)
-from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2
-
-
-DESCRIPTOR = _descriptor.FileDescriptor(
- name="google/cloud/oslogin_v1/proto/oslogin.proto",
- package="google.cloud.oslogin.v1",
- syntax="proto3",
- serialized_options=b"\n\033com.google.cloud.oslogin.v1B\014OsLoginProtoP\001Z>google.golang.org/genproto/googleapis/cloud/oslogin/v1;oslogin\252\002\027Google.Cloud.OsLogin.V1\312\002\027Google\\Cloud\\OsLogin\\V1\352\002\032Google::Cloud::OsLogin::V1",
- create_key=_descriptor._internal_create_key,
- serialized_pb=b'\n+google/cloud/oslogin_v1/proto/oslogin.proto\x12\x17google.cloud.oslogin.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a(google/cloud/oslogin/common/common.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto"\x98\x02\n\x0cLoginProfile\x12\x11\n\x04name\x18\x01 \x01(\tB\x03\xe0\x41\x02\x12\x41\n\x0eposix_accounts\x18\x02 \x03(\x0b\x32).google.cloud.oslogin.common.PosixAccount\x12Q\n\x0fssh_public_keys\x18\x03 \x03(\x0b\x32\x38.google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry\x1a_\n\x12SshPublicKeysEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKey:\x02\x38\x01"V\n\x19\x44\x65letePosixAccountRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/PosixAccount"V\n\x19\x44\x65leteSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey"z\n\x16GetLoginProfileRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\x12#oslogin.googleapis.com/PosixAccount\x12\x12\n\nproject_id\x18\x02 \x01(\t\x12\x11\n\tsystem_id\x18\x03 \x01(\t"S\n\x16GetSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey"\xb4\x01\n\x19ImportSshPublicKeyRequest\x12;\n\x06parent\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\x12#oslogin.googleapis.com/SshPublicKey\x12\x46\n\x0essh_public_key\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKeyB\x03\xe0\x41\x01\x12\x12\n\nproject_id\x18\x03 \x01(\t"Z\n\x1aImportSshPublicKeyResponse\x12<\n\rlogin_profile\x18\x01 \x01(\x0b\x32%.google.cloud.oslogin.v1.LoginProfile"\xcf\x01\n\x19UpdateSshPublicKeyRequest\x12\x39\n\x04name\x18\x01 \x01(\tB+\xe0\x41\x02\xfa\x41%\n#oslogin.googleapis.com/SshPublicKey\x12\x46\n\x0essh_public_key\x18\x02 \x01(\x0b\x32).google.cloud.oslogin.common.SshPublicKeyB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.FieldMask2\xd0\t\n\x0eOsLoginService\x12\x8e\x01\n\x12\x44\x65letePosixAccount\x12\x32.google.cloud.oslogin.v1.DeletePosixAccountRequest\x1a\x16.google.protobuf.Empty",\x82\xd3\xe4\x93\x02\x1f*\x1d/v1/{name=users/*/projects/*}\xda\x41\x04name\x12\x93\x01\n\x12\x44\x65leteSshPublicKey\x12\x32.google.cloud.oslogin.v1.DeleteSshPublicKeyRequest\x1a\x16.google.protobuf.Empty"1\x82\xd3\xe4\x93\x02$*"/v1/{name=users/*/sshPublicKeys/*}\xda\x41\x04name\x12\x99\x01\n\x0fGetLoginProfile\x12/.google.cloud.oslogin.v1.GetLoginProfileRequest\x1a%.google.cloud.oslogin.v1.LoginProfile".\x82\xd3\xe4\x93\x02!\x12\x1f/v1/{name=users/*}/loginProfile\xda\x41\x04name\x12\xa0\x01\n\x0fGetSshPublicKey\x12/.google.cloud.oslogin.v1.GetSshPublicKeyRequest\x1a).google.cloud.oslogin.common.SshPublicKey"1\x82\xd3\xe4\x93\x02$\x12"/v1/{name=users/*/sshPublicKeys/*}\xda\x41\x04name\x12\xf9\x01\n\x12ImportSshPublicKey\x12\x32.google.cloud.oslogin.v1.ImportSshPublicKeyRequest\x1a\x33.google.cloud.oslogin.v1.ImportSshPublicKeyResponse"z\x82\xd3\xe4\x93\x02\x39"\'/v1/{parent=users/*}:importSshPublicKey:\x0essh_public_key\xda\x41\x15parent,ssh_public_key\xda\x41 parent,ssh_public_key,project_id\x12\xe7\x01\n\x12UpdateSshPublicKey\x12\x32.google.cloud.oslogin.v1.UpdateSshPublicKeyRequest\x1a).google.cloud.oslogin.common.SshPublicKey"r\x82\xd3\xe4\x93\x02\x34\x32"/v1/{name=users/*/sshPublicKeys/*}:\x0essh_public_key\xda\x41\x13name,ssh_public_key\xda\x41\x1fname,ssh_public_key,update_mask\x1ar\xca\x41\x16oslogin.googleapis.com\xd2\x41Vhttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/computeB\xbe\x01\n\x1b\x63om.google.cloud.oslogin.v1B\x0cOsLoginProtoP\x01Z>google.golang.org/genproto/googleapis/cloud/oslogin/v1;oslogin\xaa\x02\x17Google.Cloud.OsLogin.V1\xca\x02\x17Google\\Cloud\\OsLogin\\V1\xea\x02\x1aGoogle::Cloud::OsLogin::V1b\x06proto3',
- dependencies=[
- google_dot_api_dot_annotations__pb2.DESCRIPTOR,
- google_dot_api_dot_client__pb2.DESCRIPTOR,
- google_dot_api_dot_field__behavior__pb2.DESCRIPTOR,
- google_dot_api_dot_resource__pb2.DESCRIPTOR,
- google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.DESCRIPTOR,
- google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,
- google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR,
- ],
-)
-
-
-_LOGINPROFILE_SSHPUBLICKEYSENTRY = _descriptor.Descriptor(
- name="SshPublicKeysEntry",
- full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="key",
- full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry.key",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="value",
- full_name="google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry.value",
- index=1,
- number=2,
- type=11,
- cpp_type=10,
- label=1,
- has_default_value=False,
- default_value=None,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=b"8\001",
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=478,
- serialized_end=573,
-)
-
-_LOGINPROFILE = _descriptor.Descriptor(
- name="LoginProfile",
- full_name="google.cloud.oslogin.v1.LoginProfile",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.LoginProfile.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="posix_accounts",
- full_name="google.cloud.oslogin.v1.LoginProfile.posix_accounts",
- index=1,
- number=2,
- type=11,
- cpp_type=10,
- label=3,
- has_default_value=False,
- default_value=[],
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="ssh_public_keys",
- full_name="google.cloud.oslogin.v1.LoginProfile.ssh_public_keys",
- index=2,
- number=3,
- type=11,
- cpp_type=10,
- label=3,
- has_default_value=False,
- default_value=[],
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[_LOGINPROFILE_SSHPUBLICKEYSENTRY,],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=293,
- serialized_end=573,
-)
-
-
-_DELETEPOSIXACCOUNTREQUEST = _descriptor.Descriptor(
- name="DeletePosixAccountRequest",
- full_name="google.cloud.oslogin.v1.DeletePosixAccountRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.DeletePosixAccountRequest.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/PosixAccount",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=575,
- serialized_end=661,
-)
-
-
-_DELETESSHPUBLICKEYREQUEST = _descriptor.Descriptor(
- name="DeleteSshPublicKeyRequest",
- full_name="google.cloud.oslogin.v1.DeleteSshPublicKeyRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.DeleteSshPublicKeyRequest.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=663,
- serialized_end=749,
-)
-
-
-_GETLOGINPROFILEREQUEST = _descriptor.Descriptor(
- name="GetLoginProfileRequest",
- full_name="google.cloud.oslogin.v1.GetLoginProfileRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\022#oslogin.googleapis.com/PosixAccount",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="project_id",
- full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.project_id",
- index=1,
- number=2,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="system_id",
- full_name="google.cloud.oslogin.v1.GetLoginProfileRequest.system_id",
- index=2,
- number=3,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=751,
- serialized_end=873,
-)
-
-
-_GETSSHPUBLICKEYREQUEST = _descriptor.Descriptor(
- name="GetSshPublicKeyRequest",
- full_name="google.cloud.oslogin.v1.GetSshPublicKeyRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.GetSshPublicKeyRequest.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=875,
- serialized_end=958,
-)
-
-
-_IMPORTSSHPUBLICKEYREQUEST = _descriptor.Descriptor(
- name="ImportSshPublicKeyRequest",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="parent",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.parent",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\022#oslogin.googleapis.com/SshPublicKey",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="ssh_public_key",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.ssh_public_key",
- index=1,
- number=2,
- type=11,
- cpp_type=10,
- label=1,
- has_default_value=False,
- default_value=None,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\001",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="project_id",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyRequest.project_id",
- index=2,
- number=3,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=961,
- serialized_end=1141,
-)
-
-
-_IMPORTSSHPUBLICKEYRESPONSE = _descriptor.Descriptor(
- name="ImportSshPublicKeyResponse",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyResponse",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="login_profile",
- full_name="google.cloud.oslogin.v1.ImportSshPublicKeyResponse.login_profile",
- index=0,
- number=1,
- type=11,
- cpp_type=10,
- label=1,
- has_default_value=False,
- default_value=None,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=1143,
- serialized_end=1233,
-)
-
-
-_UPDATESSHPUBLICKEYREQUEST = _descriptor.Descriptor(
- name="UpdateSshPublicKeyRequest",
- full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest",
- filename=None,
- file=DESCRIPTOR,
- containing_type=None,
- create_key=_descriptor._internal_create_key,
- fields=[
- _descriptor.FieldDescriptor(
- name="name",
- full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.name",
- index=0,
- number=1,
- type=9,
- cpp_type=9,
- label=1,
- has_default_value=False,
- default_value=b"".decode("utf-8"),
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002\372A%\n#oslogin.googleapis.com/SshPublicKey",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="ssh_public_key",
- full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.ssh_public_key",
- index=1,
- number=2,
- type=11,
- cpp_type=10,
- label=1,
- has_default_value=False,
- default_value=None,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=b"\340A\002",
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.FieldDescriptor(
- name="update_mask",
- full_name="google.cloud.oslogin.v1.UpdateSshPublicKeyRequest.update_mask",
- index=2,
- number=3,
- type=11,
- cpp_type=10,
- label=1,
- has_default_value=False,
- default_value=None,
- message_type=None,
- enum_type=None,
- containing_type=None,
- is_extension=False,
- extension_scope=None,
- serialized_options=None,
- file=DESCRIPTOR,
- create_key=_descriptor._internal_create_key,
- ),
- ],
- extensions=[],
- nested_types=[],
- enum_types=[],
- serialized_options=None,
- is_extendable=False,
- syntax="proto3",
- extension_ranges=[],
- oneofs=[],
- serialized_start=1236,
- serialized_end=1443,
-)
-
-_LOGINPROFILE_SSHPUBLICKEYSENTRY.fields_by_name[
- "value"
-].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY
-_LOGINPROFILE_SSHPUBLICKEYSENTRY.containing_type = _LOGINPROFILE
-_LOGINPROFILE.fields_by_name[
- "posix_accounts"
-].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._POSIXACCOUNT
-_LOGINPROFILE.fields_by_name[
- "ssh_public_keys"
-].message_type = _LOGINPROFILE_SSHPUBLICKEYSENTRY
-_IMPORTSSHPUBLICKEYREQUEST.fields_by_name[
- "ssh_public_key"
-].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY
-_IMPORTSSHPUBLICKEYRESPONSE.fields_by_name["login_profile"].message_type = _LOGINPROFILE
-_UPDATESSHPUBLICKEYREQUEST.fields_by_name[
- "ssh_public_key"
-].message_type = google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY
-_UPDATESSHPUBLICKEYREQUEST.fields_by_name[
- "update_mask"
-].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK
-DESCRIPTOR.message_types_by_name["LoginProfile"] = _LOGINPROFILE
-DESCRIPTOR.message_types_by_name[
- "DeletePosixAccountRequest"
-] = _DELETEPOSIXACCOUNTREQUEST
-DESCRIPTOR.message_types_by_name[
- "DeleteSshPublicKeyRequest"
-] = _DELETESSHPUBLICKEYREQUEST
-DESCRIPTOR.message_types_by_name["GetLoginProfileRequest"] = _GETLOGINPROFILEREQUEST
-DESCRIPTOR.message_types_by_name["GetSshPublicKeyRequest"] = _GETSSHPUBLICKEYREQUEST
-DESCRIPTOR.message_types_by_name[
- "ImportSshPublicKeyRequest"
-] = _IMPORTSSHPUBLICKEYREQUEST
-DESCRIPTOR.message_types_by_name[
- "ImportSshPublicKeyResponse"
-] = _IMPORTSSHPUBLICKEYRESPONSE
-DESCRIPTOR.message_types_by_name[
- "UpdateSshPublicKeyRequest"
-] = _UPDATESSHPUBLICKEYREQUEST
-_sym_db.RegisterFileDescriptor(DESCRIPTOR)
-
-LoginProfile = _reflection.GeneratedProtocolMessageType(
- "LoginProfile",
- (_message.Message,),
- {
- "SshPublicKeysEntry": _reflection.GeneratedProtocolMessageType(
- "SshPublicKeysEntry",
- (_message.Message,),
- {
- "DESCRIPTOR": _LOGINPROFILE_SSHPUBLICKEYSENTRY,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2"
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.LoginProfile.SshPublicKeysEntry)
- },
- ),
- "DESCRIPTOR": _LOGINPROFILE,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """The user profile information used for logging in to a virtual machine
- on Google Compute Engine.
-
- Attributes:
- name:
- Required. A unique user ID.
- posix_accounts:
- The list of POSIX accounts associated with the user.
- ssh_public_keys:
- A map from SSH public key fingerprint to the associated key
- object.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.LoginProfile)
- },
-)
-_sym_db.RegisterMessage(LoginProfile)
-_sym_db.RegisterMessage(LoginProfile.SshPublicKeysEntry)
-
-DeletePosixAccountRequest = _reflection.GeneratedProtocolMessageType(
- "DeletePosixAccountRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _DELETEPOSIXACCOUNTREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for deleting a POSIX account entry.
-
- Attributes:
- name:
- Required. A reference to the POSIX account to update. POSIX
- accounts are identified by the project ID they are associated
- with. A reference to the POSIX account is in format
- ``users/{user}/projects/{project}``.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.DeletePosixAccountRequest)
- },
-)
-_sym_db.RegisterMessage(DeletePosixAccountRequest)
-
-DeleteSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType(
- "DeleteSshPublicKeyRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _DELETESSHPUBLICKEYREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for deleting an SSH public key.
-
- Attributes:
- name:
- Required. The fingerprint of the public key to update. Public
- keys are identified by their SHA-256 fingerprint. The
- fingerprint of the public key is in format
- ``users/{user}/sshPublicKeys/{fingerprint}``.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.DeleteSshPublicKeyRequest)
- },
-)
-_sym_db.RegisterMessage(DeleteSshPublicKeyRequest)
-
-GetLoginProfileRequest = _reflection.GeneratedProtocolMessageType(
- "GetLoginProfileRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _GETLOGINPROFILEREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for retrieving the login profile information for a
- user.
-
- Attributes:
- name:
- Required. The unique ID for the user in format
- ``users/{user}``.
- project_id:
- The project ID of the Google Cloud Platform project.
- system_id:
- A system ID for filtering the results of the request.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.GetLoginProfileRequest)
- },
-)
-_sym_db.RegisterMessage(GetLoginProfileRequest)
-
-GetSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType(
- "GetSshPublicKeyRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _GETSSHPUBLICKEYREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for retrieving an SSH public key.
-
- Attributes:
- name:
- Required. The fingerprint of the public key to retrieve.
- Public keys are identified by their SHA-256 fingerprint. The
- fingerprint of the public key is in format
- ``users/{user}/sshPublicKeys/{fingerprint}``.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.GetSshPublicKeyRequest)
- },
-)
-_sym_db.RegisterMessage(GetSshPublicKeyRequest)
-
-ImportSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType(
- "ImportSshPublicKeyRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _IMPORTSSHPUBLICKEYREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for importing an SSH public key.
-
- Attributes:
- parent:
- Required. The unique ID for the user in format
- ``users/{user}``.
- ssh_public_key:
- Optional. The SSH public key and expiration time.
- project_id:
- The project ID of the Google Cloud Platform project.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.ImportSshPublicKeyRequest)
- },
-)
-_sym_db.RegisterMessage(ImportSshPublicKeyRequest)
-
-ImportSshPublicKeyResponse = _reflection.GeneratedProtocolMessageType(
- "ImportSshPublicKeyResponse",
- (_message.Message,),
- {
- "DESCRIPTOR": _IMPORTSSHPUBLICKEYRESPONSE,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A response message for importing an SSH public key.
-
- Attributes:
- login_profile:
- The login profile information for the user.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.ImportSshPublicKeyResponse)
- },
-)
-_sym_db.RegisterMessage(ImportSshPublicKeyResponse)
-
-UpdateSshPublicKeyRequest = _reflection.GeneratedProtocolMessageType(
- "UpdateSshPublicKeyRequest",
- (_message.Message,),
- {
- "DESCRIPTOR": _UPDATESSHPUBLICKEYREQUEST,
- "__module__": "google.cloud.oslogin_v1.proto.oslogin_pb2",
- "__doc__": """A request message for updating an SSH public key.
-
- Attributes:
- name:
- Required. The fingerprint of the public key to update. Public
- keys are identified by their SHA-256 fingerprint. The
- fingerprint of the public key is in format
- ``users/{user}/sshPublicKeys/{fingerprint}``.
- ssh_public_key:
- Required. The SSH public key and expiration time.
- update_mask:
- Mask to control which fields get updated. Updates all if not
- present.
- """,
- # @@protoc_insertion_point(class_scope:google.cloud.oslogin.v1.UpdateSshPublicKeyRequest)
- },
-)
-_sym_db.RegisterMessage(UpdateSshPublicKeyRequest)
-
-
-DESCRIPTOR._options = None
-_LOGINPROFILE_SSHPUBLICKEYSENTRY._options = None
-_LOGINPROFILE.fields_by_name["name"]._options = None
-_DELETEPOSIXACCOUNTREQUEST.fields_by_name["name"]._options = None
-_DELETESSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None
-_GETLOGINPROFILEREQUEST.fields_by_name["name"]._options = None
-_GETSSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None
-_IMPORTSSHPUBLICKEYREQUEST.fields_by_name["parent"]._options = None
-_IMPORTSSHPUBLICKEYREQUEST.fields_by_name["ssh_public_key"]._options = None
-_UPDATESSHPUBLICKEYREQUEST.fields_by_name["name"]._options = None
-_UPDATESSHPUBLICKEYREQUEST.fields_by_name["ssh_public_key"]._options = None
-
-_OSLOGINSERVICE = _descriptor.ServiceDescriptor(
- name="OsLoginService",
- full_name="google.cloud.oslogin.v1.OsLoginService",
- file=DESCRIPTOR,
- index=0,
- serialized_options=b"\312A\026oslogin.googleapis.com\322AVhttps://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/compute",
- create_key=_descriptor._internal_create_key,
- serialized_start=1446,
- serialized_end=2678,
- methods=[
- _descriptor.MethodDescriptor(
- name="DeletePosixAccount",
- full_name="google.cloud.oslogin.v1.OsLoginService.DeletePosixAccount",
- index=0,
- containing_service=None,
- input_type=_DELETEPOSIXACCOUNTREQUEST,
- output_type=google_dot_protobuf_dot_empty__pb2._EMPTY,
- serialized_options=b"\202\323\344\223\002\037*\035/v1/{name=users/*/projects/*}\332A\004name",
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.MethodDescriptor(
- name="DeleteSshPublicKey",
- full_name="google.cloud.oslogin.v1.OsLoginService.DeleteSshPublicKey",
- index=1,
- containing_service=None,
- input_type=_DELETESSHPUBLICKEYREQUEST,
- output_type=google_dot_protobuf_dot_empty__pb2._EMPTY,
- serialized_options=b'\202\323\344\223\002$*"/v1/{name=users/*/sshPublicKeys/*}\332A\004name',
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.MethodDescriptor(
- name="GetLoginProfile",
- full_name="google.cloud.oslogin.v1.OsLoginService.GetLoginProfile",
- index=2,
- containing_service=None,
- input_type=_GETLOGINPROFILEREQUEST,
- output_type=_LOGINPROFILE,
- serialized_options=b"\202\323\344\223\002!\022\037/v1/{name=users/*}/loginProfile\332A\004name",
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.MethodDescriptor(
- name="GetSshPublicKey",
- full_name="google.cloud.oslogin.v1.OsLoginService.GetSshPublicKey",
- index=3,
- containing_service=None,
- input_type=_GETSSHPUBLICKEYREQUEST,
- output_type=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY,
- serialized_options=b'\202\323\344\223\002$\022"/v1/{name=users/*/sshPublicKeys/*}\332A\004name',
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.MethodDescriptor(
- name="ImportSshPublicKey",
- full_name="google.cloud.oslogin.v1.OsLoginService.ImportSshPublicKey",
- index=4,
- containing_service=None,
- input_type=_IMPORTSSHPUBLICKEYREQUEST,
- output_type=_IMPORTSSHPUBLICKEYRESPONSE,
- serialized_options=b"\202\323\344\223\0029\"'/v1/{parent=users/*}:importSshPublicKey:\016ssh_public_key\332A\025parent,ssh_public_key\332A parent,ssh_public_key,project_id",
- create_key=_descriptor._internal_create_key,
- ),
- _descriptor.MethodDescriptor(
- name="UpdateSshPublicKey",
- full_name="google.cloud.oslogin.v1.OsLoginService.UpdateSshPublicKey",
- index=5,
- containing_service=None,
- input_type=_UPDATESSHPUBLICKEYREQUEST,
- output_type=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2._SSHPUBLICKEY,
- serialized_options=b'\202\323\344\223\00242"/v1/{name=users/*/sshPublicKeys/*}:\016ssh_public_key\332A\023name,ssh_public_key\332A\037name,ssh_public_key,update_mask',
- create_key=_descriptor._internal_create_key,
- ),
- ],
-)
-_sym_db.RegisterServiceDescriptor(_OSLOGINSERVICE)
-
-DESCRIPTOR.services_by_name["OsLoginService"] = _OSLOGINSERVICE
-
-# @@protoc_insertion_point(module_scope)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py
deleted file mode 100644
index 6b002666a67b..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py
+++ /dev/null
@@ -1,148 +0,0 @@
-# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
-import grpc
-
-from google.cloud.oslogin_v1.proto import (
- common_pb2 as google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2,
-)
-from google.cloud.oslogin_v1.proto import (
- oslogin_pb2 as google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2,
-)
-from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
-
-
-class OsLoginServiceStub(object):
- """Cloud OS Login API
-
- The Cloud OS Login API allows you to manage users and their associated SSH
- public keys for logging into virtual machines on Google Cloud Platform.
- """
-
- def __init__(self, channel):
- """Constructor.
-
- Args:
- channel: A grpc.Channel.
- """
- self.DeletePosixAccount = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeletePosixAccountRequest.SerializeToString,
- response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
- )
- self.DeleteSshPublicKey = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeleteSshPublicKeyRequest.SerializeToString,
- response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
- )
- self.GetLoginProfile = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetLoginProfileRequest.SerializeToString,
- response_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.LoginProfile.FromString,
- )
- self.GetSshPublicKey = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetSshPublicKeyRequest.SerializeToString,
- response_deserializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.FromString,
- )
- self.ImportSshPublicKey = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyRequest.SerializeToString,
- response_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyResponse.FromString,
- )
- self.UpdateSshPublicKey = channel.unary_unary(
- "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey",
- request_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.UpdateSshPublicKeyRequest.SerializeToString,
- response_deserializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.FromString,
- )
-
-
-class OsLoginServiceServicer(object):
- """Cloud OS Login API
-
- The Cloud OS Login API allows you to manage users and their associated SSH
- public keys for logging into virtual machines on Google Cloud Platform.
- """
-
- def DeletePosixAccount(self, request, context):
- """Deletes a POSIX account.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
- def DeleteSshPublicKey(self, request, context):
- """Deletes an SSH public key.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
- def GetLoginProfile(self, request, context):
- """Retrieves the profile information used for logging in to a virtual machine
- on Google Compute Engine.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
- def GetSshPublicKey(self, request, context):
- """Retrieves an SSH public key.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
- def ImportSshPublicKey(self, request, context):
- """Adds an SSH public key and returns the profile information. Default POSIX
- account information is set when no username and UID exist as part of the
- login profile.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
- def UpdateSshPublicKey(self, request, context):
- """Updates an SSH public key and returns the profile information. This method
- supports patch semantics.
- """
- context.set_code(grpc.StatusCode.UNIMPLEMENTED)
- context.set_details("Method not implemented!")
- raise NotImplementedError("Method not implemented!")
-
-
-def add_OsLoginServiceServicer_to_server(servicer, server):
- rpc_method_handlers = {
- "DeletePosixAccount": grpc.unary_unary_rpc_method_handler(
- servicer.DeletePosixAccount,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeletePosixAccountRequest.FromString,
- response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
- ),
- "DeleteSshPublicKey": grpc.unary_unary_rpc_method_handler(
- servicer.DeleteSshPublicKey,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.DeleteSshPublicKeyRequest.FromString,
- response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
- ),
- "GetLoginProfile": grpc.unary_unary_rpc_method_handler(
- servicer.GetLoginProfile,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetLoginProfileRequest.FromString,
- response_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.LoginProfile.SerializeToString,
- ),
- "GetSshPublicKey": grpc.unary_unary_rpc_method_handler(
- servicer.GetSshPublicKey,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.GetSshPublicKeyRequest.FromString,
- response_serializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.SerializeToString,
- ),
- "ImportSshPublicKey": grpc.unary_unary_rpc_method_handler(
- servicer.ImportSshPublicKey,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyRequest.FromString,
- response_serializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.ImportSshPublicKeyResponse.SerializeToString,
- ),
- "UpdateSshPublicKey": grpc.unary_unary_rpc_method_handler(
- servicer.UpdateSshPublicKey,
- request_deserializer=google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogin__pb2.UpdateSshPublicKeyRequest.FromString,
- response_serializer=google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2.SshPublicKey.SerializeToString,
- ),
- }
- generic_handler = grpc.method_handlers_generic_handler(
- "google.cloud.oslogin.v1.OsLoginService", rpc_method_handlers
- )
- server.add_generic_rpc_handlers((generic_handler,))
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/py.typed b/packages/google-cloud-os-login/google/cloud/oslogin_v1/py.typed
new file mode 100644
index 000000000000..825d05f7f103
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/py.typed
@@ -0,0 +1,2 @@
+# Marker file for PEP 561.
+# The google-cloud-oslogin package uses inline types.
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/__init__.py
new file mode 100644
index 000000000000..42ffdf2bc43d
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/packages/google-cloud-os-login/google/cloud/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/__init__.py
similarity index 71%
rename from packages/google-cloud-os-login/google/cloud/__init__.py
rename to packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/__init__.py
index 9a1b64a6d586..4e7ce22bc5c3 100644
--- a/packages/google-cloud-os-login/google/cloud/__init__.py
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/__init__.py
@@ -1,24 +1,24 @@
# -*- coding: utf-8 -*-
-#
+
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
-# https://www.apache.org/licenses/LICENSE-2.0
+# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+#
-try:
- import pkg_resources
-
- pkg_resources.declare_namespace(__name__)
-except ImportError:
- import pkgutil
+from .client import OsLoginServiceClient
+from .async_client import OsLoginServiceAsyncClient
- __path__ = pkgutil.extend_path(__path__, __name__)
+__all__ = (
+ "OsLoginServiceClient",
+ "OsLoginServiceAsyncClient",
+)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/async_client.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/async_client.py
new file mode 100644
index 000000000000..8afce3ad88ec
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/async_client.py
@@ -0,0 +1,631 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+import functools
+import re
+from typing import Dict, Sequence, Tuple, Type, Union
+import pkg_resources
+
+import google.api_core.client_options as ClientOptions # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.types import oslogin
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+from .transports.base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO
+from .transports.grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport
+from .client import OsLoginServiceClient
+
+
+class OsLoginServiceAsyncClient:
+ """Cloud OS Login API
+ The Cloud OS Login API allows you to manage users and their
+ associated SSH public keys for logging into virtual machines on
+ Google Cloud Platform.
+ """
+
+ _client: OsLoginServiceClient
+
+ DEFAULT_ENDPOINT = OsLoginServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = OsLoginServiceClient.DEFAULT_MTLS_ENDPOINT
+
+ ssh_public_key_path = staticmethod(OsLoginServiceClient.ssh_public_key_path)
+ parse_ssh_public_key_path = staticmethod(
+ OsLoginServiceClient.parse_ssh_public_key_path
+ )
+
+ from_service_account_file = OsLoginServiceClient.from_service_account_file
+ from_service_account_json = from_service_account_file
+
+ get_transport_class = functools.partial(
+ type(OsLoginServiceClient).get_transport_class, type(OsLoginServiceClient)
+ )
+
+ def __init__(
+ self,
+ *,
+ credentials: credentials.Credentials = None,
+ transport: Union[str, OsLoginServiceTransport] = "grpc_asyncio",
+ client_options: ClientOptions = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiate the os login service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.OsLoginServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (ClientOptions): Custom options for the client. It
+ won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint) and "auto" (auto switch to the
+ default mTLS endpoint if client certificate is present, this is
+ the default value). However, the ``api_endpoint`` property takes
+ precedence if provided.
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
+ is "true", then the ``client_cert_source`` property can be used
+ to provide client certificate for mutual TLS transport. If
+ not provided, the default SSL client certificate will be used if
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
+ set, no client certificate will be used.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+
+ self._client = OsLoginServiceClient(
+ credentials=credentials,
+ transport=transport,
+ client_options=client_options,
+ client_info=client_info,
+ )
+
+ async def delete_posix_account(
+ self,
+ request: oslogin.DeletePosixAccountRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a POSIX account.
+
+ Args:
+ request (:class:`~.oslogin.DeletePosixAccountRequest`):
+ The request object. A request message for deleting a
+ POSIX account entry.
+ name (:class:`str`):
+ Required. A reference to the POSIX account to update.
+ POSIX accounts are identified by the project ID they are
+ associated with. A reference to the POSIX account is in
+ format ``users/{user}/projects/{project}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.DeletePosixAccountRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_posix_account,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ async def delete_ssh_public_key(
+ self,
+ request: oslogin.DeleteSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes an SSH public key.
+
+ Args:
+ request (:class:`~.oslogin.DeleteSshPublicKeyRequest`):
+ The request object. A request message for deleting an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.DeleteSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.delete_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ await rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ async def get_login_profile(
+ self,
+ request: oslogin.GetLoginProfileRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> oslogin.LoginProfile:
+ r"""Retrieves the profile information used for logging in
+ to a virtual machine on Google Compute Engine.
+
+ Args:
+ request (:class:`~.oslogin.GetLoginProfileRequest`):
+ The request object. A request message for retrieving the
+ login profile information for a user.
+ name (:class:`str`):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.oslogin.LoginProfile:
+ The user profile information used for
+ logging in to a virtual machine on
+ Google Compute Engine.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.GetLoginProfileRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_login_profile,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def get_ssh_public_key(
+ self,
+ request: oslogin.GetSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> common.SshPublicKey:
+ r"""Retrieves an SSH public key.
+
+ Args:
+ request (:class:`~.oslogin.GetSshPublicKeyRequest`):
+ The request object. A request message for retrieving an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to retrieve.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.common.SshPublicKey:
+ The SSH public key information
+ associated with a Google account.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.GetSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.get_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def import_ssh_public_key(
+ self,
+ request: oslogin.ImportSshPublicKeyRequest = None,
+ *,
+ parent: str = None,
+ ssh_public_key: common.SshPublicKey = None,
+ project_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> oslogin.ImportSshPublicKeyResponse:
+ r"""Adds an SSH public key and returns the profile
+ information. Default POSIX account information is set
+ when no username and UID exist as part of the login
+ profile.
+
+ Args:
+ request (:class:`~.oslogin.ImportSshPublicKeyRequest`):
+ The request object. A request message for importing an
+ SSH public key.
+ parent (:class:`str`):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ ssh_public_key (:class:`~.common.SshPublicKey`):
+ Optional. The SSH public key and
+ expiration time.
+ This corresponds to the ``ssh_public_key`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ project_id (:class:`str`):
+ The project ID of the Google Cloud
+ Platform project.
+ This corresponds to the ``project_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.oslogin.ImportSshPublicKeyResponse:
+ A response message for importing an
+ SSH public key.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([parent, ssh_public_key, project_id]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.ImportSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if ssh_public_key is not None:
+ request.ssh_public_key = ssh_public_key
+ if project_id is not None:
+ request.project_id = project_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.import_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ async def update_ssh_public_key(
+ self,
+ request: oslogin.UpdateSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ ssh_public_key: common.SshPublicKey = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> common.SshPublicKey:
+ r"""Updates an SSH public key and returns the profile
+ information. This method supports patch semantics.
+
+ Args:
+ request (:class:`~.oslogin.UpdateSshPublicKeyRequest`):
+ The request object. A request message for updating an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ ssh_public_key (:class:`~.common.SshPublicKey`):
+ Required. The SSH public key and
+ expiration time.
+ This corresponds to the ``ssh_public_key`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Mask to control which fields get
+ updated. Updates all if not present.
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.common.SshPublicKey:
+ The SSH public key information
+ associated with a Google account.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ if request is not None and any([name, ssh_public_key, update_mask]):
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ request = oslogin.UpdateSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+ if ssh_public_key is not None:
+ request.ssh_public_key = ssh_public_key
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = gapic_v1.method_async.wrap_method(
+ self._client._transport.update_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=DEFAULT_CLIENT_INFO,
+ )
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+
+try:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version,
+ )
+except pkg_resources.DistributionNotFound:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("OsLoginServiceAsyncClient",)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/client.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/client.py
new file mode 100644
index 000000000000..ab59bfa47339
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/client.py
@@ -0,0 +1,751 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+from distutils import util
+import os
+import re
+from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union
+import pkg_resources
+
+from google.api_core import client_options as client_options_lib # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.types import oslogin
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+from .transports.base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO
+from .transports.grpc import OsLoginServiceGrpcTransport
+from .transports.grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport
+
+
+class OsLoginServiceClientMeta(type):
+ """Metaclass for the OsLoginService client.
+
+ This provides class-level methods for building and retrieving
+ support objects (e.g. transport) without polluting the client instance
+ objects.
+ """
+
+ _transport_registry = (
+ OrderedDict()
+ ) # type: Dict[str, Type[OsLoginServiceTransport]]
+ _transport_registry["grpc"] = OsLoginServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = OsLoginServiceGrpcAsyncIOTransport
+
+ def get_transport_class(cls, label: str = None,) -> Type[OsLoginServiceTransport]:
+ """Return an appropriate transport class.
+
+ Args:
+ label: The name of the desired transport. If none is
+ provided, then the first transport in the registry is used.
+
+ Returns:
+ The transport class to use.
+ """
+ # If a specific transport is requested, return that one.
+ if label:
+ return cls._transport_registry[label]
+
+ # No transport is requested; return the default (that is, the first one
+ # in the dictionary).
+ return next(iter(cls._transport_registry.values()))
+
+
+class OsLoginServiceClient(metaclass=OsLoginServiceClientMeta):
+ """Cloud OS Login API
+ The Cloud OS Login API allows you to manage users and their
+ associated SSH public keys for logging into virtual machines on
+ Google Cloud Platform.
+ """
+
+ @staticmethod
+ def _get_default_mtls_endpoint(api_endpoint):
+ """Convert api endpoint to mTLS endpoint.
+ Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
+ "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
+ Args:
+ api_endpoint (Optional[str]): the api endpoint to convert.
+ Returns:
+ str: converted mTLS api endpoint.
+ """
+ if not api_endpoint:
+ return api_endpoint
+
+ mtls_endpoint_re = re.compile(
+ r"(?P
[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?"
+ )
+
+ m = mtls_endpoint_re.match(api_endpoint)
+ name, mtls, sandbox, googledomain = m.groups()
+ if mtls or not googledomain:
+ return api_endpoint
+
+ if sandbox:
+ return api_endpoint.replace(
+ "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
+ )
+
+ return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
+
+ DEFAULT_ENDPOINT = "oslogin.googleapis.com"
+ DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
+ DEFAULT_ENDPOINT
+ )
+
+ @classmethod
+ def from_service_account_file(cls, filename: str, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ file.
+
+ Args:
+ filename (str): The path to the service account private key json
+ file.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ {@api.name}: The constructed client.
+ """
+ credentials = service_account.Credentials.from_service_account_file(filename)
+ kwargs["credentials"] = credentials
+ return cls(*args, **kwargs)
+
+ from_service_account_json = from_service_account_file
+
+ @staticmethod
+ def ssh_public_key_path(user: str, fingerprint: str,) -> str:
+ """Return a fully-qualified ssh_public_key string."""
+ return "users/{user}/sshPublicKeys/{fingerprint}".format(
+ user=user, fingerprint=fingerprint,
+ )
+
+ @staticmethod
+ def parse_ssh_public_key_path(path: str) -> Dict[str, str]:
+ """Parse a ssh_public_key path into its component segments."""
+ m = re.match(r"^users/(?P.+?)/sshPublicKeys/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[credentials.Credentials] = None,
+ transport: Union[str, OsLoginServiceTransport, None] = None,
+ client_options: Optional[client_options_lib.ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiate the os login service client.
+
+ Args:
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ transport (Union[str, ~.OsLoginServiceTransport]): The
+ transport to use. If set to None, a transport is chosen
+ automatically.
+ client_options (client_options_lib.ClientOptions): Custom options for the
+ client. It won't take effect if a ``transport`` instance is provided.
+ (1) The ``api_endpoint`` property can be used to override the
+ default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
+ environment variable can also be used to override the endpoint:
+ "always" (always use the default mTLS endpoint), "never" (always
+ use the default regular endpoint) and "auto" (auto switch to the
+ default mTLS endpoint if client certificate is present, this is
+ the default value). However, the ``api_endpoint`` property takes
+ precedence if provided.
+ (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
+ is "true", then the ``client_cert_source`` property can be used
+ to provide client certificate for mutual TLS transport. If
+ not provided, the default SSL client certificate will be used if
+ present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
+ set, no client certificate will be used.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
+ creation failed for any reason.
+ """
+ if isinstance(client_options, dict):
+ client_options = client_options_lib.from_dict(client_options)
+ if client_options is None:
+ client_options = client_options_lib.ClientOptions()
+
+ # Create SSL credentials for mutual TLS if needed.
+ use_client_cert = bool(
+ util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
+ )
+
+ ssl_credentials = None
+ is_mtls = False
+ if use_client_cert:
+ if client_options.client_cert_source:
+ import grpc # type: ignore
+
+ cert, key = client_options.client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ is_mtls = True
+ else:
+ creds = SslCredentials()
+ is_mtls = creds.is_mtls
+ ssl_credentials = creds.ssl_credentials if is_mtls else None
+
+ # Figure out which api endpoint to use.
+ if client_options.api_endpoint is not None:
+ api_endpoint = client_options.api_endpoint
+ else:
+ use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
+ if use_mtls_env == "never":
+ api_endpoint = self.DEFAULT_ENDPOINT
+ elif use_mtls_env == "always":
+ api_endpoint = self.DEFAULT_MTLS_ENDPOINT
+ elif use_mtls_env == "auto":
+ api_endpoint = (
+ self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT
+ )
+ else:
+ raise MutualTLSChannelError(
+ "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always"
+ )
+
+ # Save or instantiate the transport.
+ # Ordinarily, we provide the transport, but allowing a custom transport
+ # instance provides an extensibility point for unusual situations.
+ if isinstance(transport, OsLoginServiceTransport):
+ # transport is a OsLoginServiceTransport instance.
+ if credentials or client_options.credentials_file:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its credentials directly."
+ )
+ if client_options.scopes:
+ raise ValueError(
+ "When providing a transport instance, "
+ "provide its scopes directly."
+ )
+ self._transport = transport
+ else:
+ Transport = type(self).get_transport_class(transport)
+ self._transport = Transport(
+ credentials=credentials,
+ credentials_file=client_options.credentials_file,
+ host=api_endpoint,
+ scopes=client_options.scopes,
+ ssl_channel_credentials=ssl_credentials,
+ quota_project_id=client_options.quota_project_id,
+ client_info=client_info,
+ )
+
+ def delete_posix_account(
+ self,
+ request: oslogin.DeletePosixAccountRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes a POSIX account.
+
+ Args:
+ request (:class:`~.oslogin.DeletePosixAccountRequest`):
+ The request object. A request message for deleting a
+ POSIX account entry.
+ name (:class:`str`):
+ Required. A reference to the POSIX account to update.
+ POSIX accounts are identified by the project ID they are
+ associated with. A reference to the POSIX account is in
+ format ``users/{user}/projects/{project}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([name])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.DeletePosixAccountRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.DeletePosixAccountRequest):
+ request = oslogin.DeletePosixAccountRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.delete_posix_account]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ def delete_ssh_public_key(
+ self,
+ request: oslogin.DeleteSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> None:
+ r"""Deletes an SSH public key.
+
+ Args:
+ request (:class:`~.oslogin.DeleteSshPublicKeyRequest`):
+ The request object. A request message for deleting an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([name])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.DeleteSshPublicKeyRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.DeleteSshPublicKeyRequest):
+ request = oslogin.DeleteSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.delete_ssh_public_key]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ rpc(
+ request, retry=retry, timeout=timeout, metadata=metadata,
+ )
+
+ def get_login_profile(
+ self,
+ request: oslogin.GetLoginProfileRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> oslogin.LoginProfile:
+ r"""Retrieves the profile information used for logging in
+ to a virtual machine on Google Compute Engine.
+
+ Args:
+ request (:class:`~.oslogin.GetLoginProfileRequest`):
+ The request object. A request message for retrieving the
+ login profile information for a user.
+ name (:class:`str`):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.oslogin.LoginProfile:
+ The user profile information used for
+ logging in to a virtual machine on
+ Google Compute Engine.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([name])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.GetLoginProfileRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.GetLoginProfileRequest):
+ request = oslogin.GetLoginProfileRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_login_profile]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ def get_ssh_public_key(
+ self,
+ request: oslogin.GetSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> common.SshPublicKey:
+ r"""Retrieves an SSH public key.
+
+ Args:
+ request (:class:`~.oslogin.GetSshPublicKeyRequest`):
+ The request object. A request message for retrieving an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to retrieve.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.common.SshPublicKey:
+ The SSH public key information
+ associated with a Google account.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([name])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.GetSshPublicKeyRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.GetSshPublicKeyRequest):
+ request = oslogin.GetSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_ssh_public_key]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ def import_ssh_public_key(
+ self,
+ request: oslogin.ImportSshPublicKeyRequest = None,
+ *,
+ parent: str = None,
+ ssh_public_key: common.SshPublicKey = None,
+ project_id: str = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> oslogin.ImportSshPublicKeyResponse:
+ r"""Adds an SSH public key and returns the profile
+ information. Default POSIX account information is set
+ when no username and UID exist as part of the login
+ profile.
+
+ Args:
+ request (:class:`~.oslogin.ImportSshPublicKeyRequest`):
+ The request object. A request message for importing an
+ SSH public key.
+ parent (:class:`str`):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ ssh_public_key (:class:`~.common.SshPublicKey`):
+ Optional. The SSH public key and
+ expiration time.
+ This corresponds to the ``ssh_public_key`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ project_id (:class:`str`):
+ The project ID of the Google Cloud
+ Platform project.
+ This corresponds to the ``project_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.oslogin.ImportSshPublicKeyResponse:
+ A response message for importing an
+ SSH public key.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([parent, ssh_public_key, project_id])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.ImportSshPublicKeyRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.ImportSshPublicKeyRequest):
+ request = oslogin.ImportSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if parent is not None:
+ request.parent = parent
+ if ssh_public_key is not None:
+ request.ssh_public_key = ssh_public_key
+ if project_id is not None:
+ request.project_id = project_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.import_ssh_public_key]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Send the request.
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+ def update_ssh_public_key(
+ self,
+ request: oslogin.UpdateSshPublicKeyRequest = None,
+ *,
+ name: str = None,
+ ssh_public_key: common.SshPublicKey = None,
+ update_mask: field_mask.FieldMask = None,
+ retry: retries.Retry = gapic_v1.method.DEFAULT,
+ timeout: float = None,
+ metadata: Sequence[Tuple[str, str]] = (),
+ ) -> common.SshPublicKey:
+ r"""Updates an SSH public key and returns the profile
+ information. This method supports patch semantics.
+
+ Args:
+ request (:class:`~.oslogin.UpdateSshPublicKeyRequest`):
+ The request object. A request message for updating an
+ SSH public key.
+ name (:class:`str`):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint.
+ The fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ This corresponds to the ``name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ ssh_public_key (:class:`~.common.SshPublicKey`):
+ Required. The SSH public key and
+ expiration time.
+ This corresponds to the ``ssh_public_key`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`~.field_mask.FieldMask`):
+ Mask to control which fields get
+ updated. Updates all if not present.
+ This corresponds to the ``update_mask`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, str]]): Strings which should be
+ sent along with the request as metadata.
+
+ Returns:
+ ~.common.SshPublicKey:
+ The SSH public key information
+ associated with a Google account.
+
+ """
+ # Create or coerce a protobuf request object.
+ # Sanity check: If we got a request object, we should *not* have
+ # gotten any keyword arguments that map to the request.
+ has_flattened_params = any([name, ssh_public_key, update_mask])
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # Minor optimization to avoid making a copy if the user passes
+ # in a oslogin.UpdateSshPublicKeyRequest.
+ # There's no risk of modifying the input as we've already verified
+ # there are no flattened fields.
+ if not isinstance(request, oslogin.UpdateSshPublicKeyRequest):
+ request = oslogin.UpdateSshPublicKeyRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+
+ if name is not None:
+ request.name = name
+ if ssh_public_key is not None:
+ request.ssh_public_key = ssh_public_key
+ if update_mask is not None:
+ request.update_mask = update_mask
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.update_ssh_public_key]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Send the request.
+ response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
+
+ # Done; return the response.
+ return response
+
+
+try:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version,
+ )
+except pkg_resources.DistributionNotFound:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+
+
+__all__ = ("OsLoginServiceClient",)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py
new file mode 100644
index 000000000000..67d67c936901
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/__init__.py
@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from collections import OrderedDict
+from typing import Dict, Type
+
+from .base import OsLoginServiceTransport
+from .grpc import OsLoginServiceGrpcTransport
+from .grpc_asyncio import OsLoginServiceGrpcAsyncIOTransport
+
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[OsLoginServiceTransport]]
+_transport_registry["grpc"] = OsLoginServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = OsLoginServiceGrpcAsyncIOTransport
+
+
+__all__ = (
+ "OsLoginServiceTransport",
+ "OsLoginServiceGrpcTransport",
+ "OsLoginServiceGrpcAsyncIOTransport",
+)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/base.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/base.py
new file mode 100644
index 000000000000..583258212558
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/base.py
@@ -0,0 +1,250 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import abc
+import typing
+import pkg_resources
+
+from google import auth # type: ignore
+from google.api_core import exceptions # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import retry as retries # type: ignore
+from google.auth import credentials # type: ignore
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.types import oslogin
+from google.protobuf import empty_pb2 as empty # type: ignore
+
+
+try:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=pkg_resources.get_distribution("google-cloud-os-login",).version,
+ )
+except pkg_resources.DistributionNotFound:
+ DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
+
+
+class OsLoginServiceTransport(abc.ABC):
+ """Abstract transport class for OsLoginService."""
+
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "oslogin.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: typing.Optional[str] = None,
+ scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
+ quota_project_id: typing.Optional[str] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ **kwargs,
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scope (Optional[Sequence[str]]): A list of scopes.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+ """
+ # Save the hostname. Default to port 443 (HTTPS) if none is specified.
+ if ":" not in host:
+ host += ":443"
+ self._host = host
+
+ # If no credentials are provided, then determine the appropriate
+ # defaults.
+ if credentials and credentials_file:
+ raise exceptions.DuplicateCredentialArgs(
+ "'credentials_file' and 'credentials' are mutually exclusive"
+ )
+
+ if credentials_file is not None:
+ credentials, _ = auth.load_credentials_from_file(
+ credentials_file, scopes=scopes, quota_project_id=quota_project_id
+ )
+
+ elif credentials is None:
+ credentials, _ = auth.default(
+ scopes=scopes, quota_project_id=quota_project_id
+ )
+
+ # Save the credentials.
+ self._credentials = credentials
+
+ # Lifted into its own function so it can be stubbed out during tests.
+ self._prep_wrapped_messages(client_info)
+
+ def _prep_wrapped_messages(self, client_info):
+ # Precompute the wrapped methods.
+ self._wrapped_methods = {
+ self.delete_posix_account: gapic_v1.method.wrap_method(
+ self.delete_posix_account,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ self.delete_ssh_public_key: gapic_v1.method.wrap_method(
+ self.delete_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ self.get_login_profile: gapic_v1.method.wrap_method(
+ self.get_login_profile,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ self.get_ssh_public_key: gapic_v1.method.wrap_method(
+ self.get_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ self.import_ssh_public_key: gapic_v1.method.wrap_method(
+ self.import_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ self.update_ssh_public_key: gapic_v1.method.wrap_method(
+ self.update_ssh_public_key,
+ default_retry=retries.Retry(
+ initial=0.1,
+ maximum=60.0,
+ multiplier=1.3,
+ predicate=retries.if_exception_type(
+ exceptions.ServiceUnavailable, exceptions.DeadlineExceeded,
+ ),
+ ),
+ default_timeout=10.0,
+ client_info=client_info,
+ ),
+ }
+
+ @property
+ def delete_posix_account(
+ self,
+ ) -> typing.Callable[
+ [oslogin.DeletePosixAccountRequest],
+ typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def delete_ssh_public_key(
+ self,
+ ) -> typing.Callable[
+ [oslogin.DeleteSshPublicKeyRequest],
+ typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_login_profile(
+ self,
+ ) -> typing.Callable[
+ [oslogin.GetLoginProfileRequest],
+ typing.Union[oslogin.LoginProfile, typing.Awaitable[oslogin.LoginProfile]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_ssh_public_key(
+ self,
+ ) -> typing.Callable[
+ [oslogin.GetSshPublicKeyRequest],
+ typing.Union[common.SshPublicKey, typing.Awaitable[common.SshPublicKey]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def import_ssh_public_key(
+ self,
+ ) -> typing.Callable[
+ [oslogin.ImportSshPublicKeyRequest],
+ typing.Union[
+ oslogin.ImportSshPublicKeyResponse,
+ typing.Awaitable[oslogin.ImportSshPublicKeyResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_ssh_public_key(
+ self,
+ ) -> typing.Callable[
+ [oslogin.UpdateSshPublicKeyRequest],
+ typing.Union[common.SshPublicKey, typing.Awaitable[common.SshPublicKey]],
+ ]:
+ raise NotImplementedError()
+
+
+__all__ = ("OsLoginServiceTransport",)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py
new file mode 100644
index 000000000000..587a6c4b1405
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc.py
@@ -0,0 +1,401 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import warnings
+from typing import Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import grpc_helpers # type: ignore
+from google.api_core import gapic_v1 # type: ignore
+from google import auth # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.types import oslogin
+from google.protobuf import empty_pb2 as empty # type: ignore
+
+from .base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO
+
+
+class OsLoginServiceGrpcTransport(OsLoginServiceTransport):
+ """gRPC backend transport for OsLoginService.
+
+ Cloud OS Login API
+ The Cloud OS Login API allows you to manage users and their
+ associated SSH public keys for logging into virtual machines on
+ Google Cloud Platform.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _stubs: Dict[str, Callable]
+
+ def __init__(
+ self,
+ *,
+ host: str = "oslogin.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Sequence[str] = None,
+ channel: grpc.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
+ ssl_channel_credentials: grpc.ChannelCredentials = None,
+ quota_project_id: Optional[str] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional(Sequence[str])): A list of scopes. This argument is
+ ignored if ``channel`` is provided.
+ channel (Optional[grpc.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
+ If provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ Deprecated. A callback to provide client SSL certificate bytes and
+ private key bytes, both in PEM format. It is ignored if
+ ``api_mtls_endpoint`` is None.
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
+ for grpc channel. It is ignored if ``channel`` is provided.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ warnings.warn(
+ "api_mtls_endpoint and client_cert_source are deprecated",
+ DeprecationWarning,
+ )
+
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ if credentials is None:
+ credentials, _ = auth.default(
+ scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ )
+ else:
+ host = host if ":" in host else host + ":443"
+
+ if credentials is None:
+ credentials, _ = auth.default(
+ scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
+ )
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_channel_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ )
+
+ self._stubs = {} # type: Dict[str, Callable]
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ )
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "oslogin.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: str = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
+ **kwargs,
+ ) -> grpc.Channel:
+ """Create and return a gRPC channel object.
+ Args:
+ address (Optionsl[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is mutually exclusive with credentials.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ grpc.Channel: A gRPC channel object.
+
+ Raises:
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ **kwargs,
+ )
+
+ @property
+ def grpc_channel(self) -> grpc.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def delete_posix_account(
+ self,
+ ) -> Callable[[oslogin.DeletePosixAccountRequest], empty.Empty]:
+ r"""Return a callable for the delete posix account method over gRPC.
+
+ Deletes a POSIX account.
+
+ Returns:
+ Callable[[~.DeletePosixAccountRequest],
+ ~.Empty]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_posix_account" not in self._stubs:
+ self._stubs["delete_posix_account"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount",
+ request_serializer=oslogin.DeletePosixAccountRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_posix_account"]
+
+ @property
+ def delete_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.DeleteSshPublicKeyRequest], empty.Empty]:
+ r"""Return a callable for the delete ssh public key method over gRPC.
+
+ Deletes an SSH public key.
+
+ Returns:
+ Callable[[~.DeleteSshPublicKeyRequest],
+ ~.Empty]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_ssh_public_key" not in self._stubs:
+ self._stubs["delete_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey",
+ request_serializer=oslogin.DeleteSshPublicKeyRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_ssh_public_key"]
+
+ @property
+ def get_login_profile(
+ self,
+ ) -> Callable[[oslogin.GetLoginProfileRequest], oslogin.LoginProfile]:
+ r"""Return a callable for the get login profile method over gRPC.
+
+ Retrieves the profile information used for logging in
+ to a virtual machine on Google Compute Engine.
+
+ Returns:
+ Callable[[~.GetLoginProfileRequest],
+ ~.LoginProfile]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_login_profile" not in self._stubs:
+ self._stubs["get_login_profile"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile",
+ request_serializer=oslogin.GetLoginProfileRequest.serialize,
+ response_deserializer=oslogin.LoginProfile.deserialize,
+ )
+ return self._stubs["get_login_profile"]
+
+ @property
+ def get_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.GetSshPublicKeyRequest], common.SshPublicKey]:
+ r"""Return a callable for the get ssh public key method over gRPC.
+
+ Retrieves an SSH public key.
+
+ Returns:
+ Callable[[~.GetSshPublicKeyRequest],
+ ~.SshPublicKey]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_ssh_public_key" not in self._stubs:
+ self._stubs["get_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey",
+ request_serializer=oslogin.GetSshPublicKeyRequest.serialize,
+ response_deserializer=common.SshPublicKey.deserialize,
+ )
+ return self._stubs["get_ssh_public_key"]
+
+ @property
+ def import_ssh_public_key(
+ self,
+ ) -> Callable[
+ [oslogin.ImportSshPublicKeyRequest], oslogin.ImportSshPublicKeyResponse
+ ]:
+ r"""Return a callable for the import ssh public key method over gRPC.
+
+ Adds an SSH public key and returns the profile
+ information. Default POSIX account information is set
+ when no username and UID exist as part of the login
+ profile.
+
+ Returns:
+ Callable[[~.ImportSshPublicKeyRequest],
+ ~.ImportSshPublicKeyResponse]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "import_ssh_public_key" not in self._stubs:
+ self._stubs["import_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey",
+ request_serializer=oslogin.ImportSshPublicKeyRequest.serialize,
+ response_deserializer=oslogin.ImportSshPublicKeyResponse.deserialize,
+ )
+ return self._stubs["import_ssh_public_key"]
+
+ @property
+ def update_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.UpdateSshPublicKeyRequest], common.SshPublicKey]:
+ r"""Return a callable for the update ssh public key method over gRPC.
+
+ Updates an SSH public key and returns the profile
+ information. This method supports patch semantics.
+
+ Returns:
+ Callable[[~.UpdateSshPublicKeyRequest],
+ ~.SshPublicKey]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_ssh_public_key" not in self._stubs:
+ self._stubs["update_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey",
+ request_serializer=oslogin.UpdateSshPublicKeyRequest.serialize,
+ response_deserializer=common.SshPublicKey.deserialize,
+ )
+ return self._stubs["update_ssh_public_key"]
+
+
+__all__ = ("OsLoginServiceGrpcTransport",)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..63206d9726af
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/services/os_login_service/transports/grpc_asyncio.py
@@ -0,0 +1,402 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import warnings
+from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple
+
+from google.api_core import gapic_v1 # type: ignore
+from google.api_core import grpc_helpers_async # type: ignore
+from google import auth # type: ignore
+from google.auth import credentials # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+
+import grpc # type: ignore
+from grpc.experimental import aio # type: ignore
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.types import oslogin
+from google.protobuf import empty_pb2 as empty # type: ignore
+
+from .base import OsLoginServiceTransport, DEFAULT_CLIENT_INFO
+from .grpc import OsLoginServiceGrpcTransport
+
+
+class OsLoginServiceGrpcAsyncIOTransport(OsLoginServiceTransport):
+ """gRPC AsyncIO backend transport for OsLoginService.
+
+ Cloud OS Login API
+ The Cloud OS Login API allows you to manage users and their
+ associated SSH public keys for logging into virtual machines on
+ Google Cloud Platform.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends protocol buffers over the wire using gRPC (which is built on
+ top of HTTP/2); the ``grpcio`` package must be installed.
+ """
+
+ _grpc_channel: aio.Channel
+ _stubs: Dict[str, Callable] = {}
+
+ @classmethod
+ def create_channel(
+ cls,
+ host: str = "oslogin.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ quota_project_id: Optional[str] = None,
+ **kwargs,
+ ) -> aio.Channel:
+ """Create and return a gRPC AsyncIO channel object.
+ Args:
+ address (Optional[str]): The host for the channel to use.
+ credentials (Optional[~.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify this application to the service. If
+ none are specified, the client will attempt to ascertain
+ the credentials from the environment.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ kwargs (Optional[dict]): Keyword arguments, which are passed to the
+ channel creation.
+ Returns:
+ aio.Channel: A gRPC AsyncIO channel object.
+ """
+ scopes = scopes or cls.AUTH_SCOPES
+ return grpc_helpers_async.create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes,
+ quota_project_id=quota_project_id,
+ **kwargs,
+ )
+
+ def __init__(
+ self,
+ *,
+ host: str = "oslogin.googleapis.com",
+ credentials: credentials.Credentials = None,
+ credentials_file: Optional[str] = None,
+ scopes: Optional[Sequence[str]] = None,
+ channel: aio.Channel = None,
+ api_mtls_endpoint: str = None,
+ client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
+ ssl_channel_credentials: grpc.ChannelCredentials = None,
+ quota_project_id=None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiate the transport.
+
+ Args:
+ host (Optional[str]): The hostname to connect to.
+ credentials (Optional[google.auth.credentials.Credentials]): The
+ authorization credentials to attach to requests. These
+ credentials identify the application to the service; if none
+ are specified, the client will attempt to ascertain the
+ credentials from the environment.
+ This argument is ignored if ``channel`` is provided.
+ credentials_file (Optional[str]): A file with credentials that can
+ be loaded with :func:`google.auth.load_credentials_from_file`.
+ This argument is ignored if ``channel`` is provided.
+ scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
+ service. These are only used when credentials are not specified and
+ are passed to :func:`google.auth.default`.
+ channel (Optional[aio.Channel]): A ``Channel`` instance through
+ which to make calls.
+ api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
+ If provided, it overrides the ``host`` argument and tries to create
+ a mutual TLS channel with client SSL credentials from
+ ``client_cert_source`` or applicatin default SSL credentials.
+ client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
+ Deprecated. A callback to provide client SSL certificate bytes and
+ private key bytes, both in PEM format. It is ignored if
+ ``api_mtls_endpoint`` is None.
+ ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
+ for grpc channel. It is ignored if ``channel`` is provided.
+ quota_project_id (Optional[str]): An optional project to use for billing
+ and quota.
+ client_info (google.api_core.gapic_v1.client_info.ClientInfo):
+ The client info used to send a user-agent string along with
+ API requests. If ``None``, then default info will be used.
+ Generally, you only need to set this if you're developing
+ your own client library.
+
+ Raises:
+ google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
+ creation failed for any reason.
+ google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
+ and ``credentials_file`` are passed.
+ """
+ if channel:
+ # Sanity check: Ensure that channel and credentials are not both
+ # provided.
+ credentials = False
+
+ # If a channel was explicitly provided, set it.
+ self._grpc_channel = channel
+ elif api_mtls_endpoint:
+ warnings.warn(
+ "api_mtls_endpoint and client_cert_source are deprecated",
+ DeprecationWarning,
+ )
+
+ host = (
+ api_mtls_endpoint
+ if ":" in api_mtls_endpoint
+ else api_mtls_endpoint + ":443"
+ )
+
+ if credentials is None:
+ credentials, _ = auth.default(
+ scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
+ )
+
+ # Create SSL credentials with client_cert_source or application
+ # default SSL credentials.
+ if client_cert_source:
+ cert, key = client_cert_source()
+ ssl_credentials = grpc.ssl_channel_credentials(
+ certificate_chain=cert, private_key=key
+ )
+ else:
+ ssl_credentials = SslCredentials().ssl_credentials
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ )
+ else:
+ host = host if ":" in host else host + ":443"
+
+ if credentials is None:
+ credentials, _ = auth.default(
+ scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
+ )
+
+ # create a new channel. The provided one is ignored.
+ self._grpc_channel = type(self).create_channel(
+ host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ ssl_credentials=ssl_channel_credentials,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ )
+
+ # Run the base constructor.
+ super().__init__(
+ host=host,
+ credentials=credentials,
+ credentials_file=credentials_file,
+ scopes=scopes or self.AUTH_SCOPES,
+ quota_project_id=quota_project_id,
+ client_info=client_info,
+ )
+
+ self._stubs = {}
+
+ @property
+ def grpc_channel(self) -> aio.Channel:
+ """Create the channel designed to connect to this service.
+
+ This property caches on the instance; repeated calls return
+ the same channel.
+ """
+ # Return the channel from cache.
+ return self._grpc_channel
+
+ @property
+ def delete_posix_account(
+ self,
+ ) -> Callable[[oslogin.DeletePosixAccountRequest], Awaitable[empty.Empty]]:
+ r"""Return a callable for the delete posix account method over gRPC.
+
+ Deletes a POSIX account.
+
+ Returns:
+ Callable[[~.DeletePosixAccountRequest],
+ Awaitable[~.Empty]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_posix_account" not in self._stubs:
+ self._stubs["delete_posix_account"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/DeletePosixAccount",
+ request_serializer=oslogin.DeletePosixAccountRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_posix_account"]
+
+ @property
+ def delete_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.DeleteSshPublicKeyRequest], Awaitable[empty.Empty]]:
+ r"""Return a callable for the delete ssh public key method over gRPC.
+
+ Deletes an SSH public key.
+
+ Returns:
+ Callable[[~.DeleteSshPublicKeyRequest],
+ Awaitable[~.Empty]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "delete_ssh_public_key" not in self._stubs:
+ self._stubs["delete_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/DeleteSshPublicKey",
+ request_serializer=oslogin.DeleteSshPublicKeyRequest.serialize,
+ response_deserializer=empty.Empty.FromString,
+ )
+ return self._stubs["delete_ssh_public_key"]
+
+ @property
+ def get_login_profile(
+ self,
+ ) -> Callable[[oslogin.GetLoginProfileRequest], Awaitable[oslogin.LoginProfile]]:
+ r"""Return a callable for the get login profile method over gRPC.
+
+ Retrieves the profile information used for logging in
+ to a virtual machine on Google Compute Engine.
+
+ Returns:
+ Callable[[~.GetLoginProfileRequest],
+ Awaitable[~.LoginProfile]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_login_profile" not in self._stubs:
+ self._stubs["get_login_profile"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/GetLoginProfile",
+ request_serializer=oslogin.GetLoginProfileRequest.serialize,
+ response_deserializer=oslogin.LoginProfile.deserialize,
+ )
+ return self._stubs["get_login_profile"]
+
+ @property
+ def get_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.GetSshPublicKeyRequest], Awaitable[common.SshPublicKey]]:
+ r"""Return a callable for the get ssh public key method over gRPC.
+
+ Retrieves an SSH public key.
+
+ Returns:
+ Callable[[~.GetSshPublicKeyRequest],
+ Awaitable[~.SshPublicKey]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "get_ssh_public_key" not in self._stubs:
+ self._stubs["get_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/GetSshPublicKey",
+ request_serializer=oslogin.GetSshPublicKeyRequest.serialize,
+ response_deserializer=common.SshPublicKey.deserialize,
+ )
+ return self._stubs["get_ssh_public_key"]
+
+ @property
+ def import_ssh_public_key(
+ self,
+ ) -> Callable[
+ [oslogin.ImportSshPublicKeyRequest],
+ Awaitable[oslogin.ImportSshPublicKeyResponse],
+ ]:
+ r"""Return a callable for the import ssh public key method over gRPC.
+
+ Adds an SSH public key and returns the profile
+ information. Default POSIX account information is set
+ when no username and UID exist as part of the login
+ profile.
+
+ Returns:
+ Callable[[~.ImportSshPublicKeyRequest],
+ Awaitable[~.ImportSshPublicKeyResponse]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "import_ssh_public_key" not in self._stubs:
+ self._stubs["import_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/ImportSshPublicKey",
+ request_serializer=oslogin.ImportSshPublicKeyRequest.serialize,
+ response_deserializer=oslogin.ImportSshPublicKeyResponse.deserialize,
+ )
+ return self._stubs["import_ssh_public_key"]
+
+ @property
+ def update_ssh_public_key(
+ self,
+ ) -> Callable[[oslogin.UpdateSshPublicKeyRequest], Awaitable[common.SshPublicKey]]:
+ r"""Return a callable for the update ssh public key method over gRPC.
+
+ Updates an SSH public key and returns the profile
+ information. This method supports patch semantics.
+
+ Returns:
+ Callable[[~.UpdateSshPublicKeyRequest],
+ Awaitable[~.SshPublicKey]]:
+ A function that, when called, will call the underlying RPC
+ on the server.
+ """
+ # Generate a "stub function" on-the-fly which will actually make
+ # the request.
+ # gRPC handles serialization and deserialization, so we just need
+ # to pass in the functions for each.
+ if "update_ssh_public_key" not in self._stubs:
+ self._stubs["update_ssh_public_key"] = self.grpc_channel.unary_unary(
+ "/google.cloud.oslogin.v1.OsLoginService/UpdateSshPublicKey",
+ request_serializer=oslogin.UpdateSshPublicKeyRequest.serialize,
+ response_deserializer=common.SshPublicKey.deserialize,
+ )
+ return self._stubs["update_ssh_public_key"]
+
+
+__all__ = ("OsLoginServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/types.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/types.py
deleted file mode 100644
index 898477688e5a..000000000000
--- a/packages/google-cloud-os-login/google/cloud/oslogin_v1/types.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-from __future__ import absolute_import
-import sys
-
-from google.api_core.protobuf_helpers import get_messages
-
-from google.cloud.oslogin_v1.proto import common_pb2
-from google.cloud.oslogin_v1.proto import oslogin_pb2
-from google.protobuf import empty_pb2
-from google.protobuf import field_mask_pb2
-
-
-_shared_modules = [
- common_pb2,
- empty_pb2,
- field_mask_pb2,
-]
-
-_local_modules = [
- oslogin_pb2,
-]
-
-names = []
-
-for module in _shared_modules: # pragma: NO COVER
- for name, message in get_messages(module).items():
- setattr(sys.modules[__name__], name, message)
- names.append(name)
-for module in _local_modules:
- for name, message in get_messages(module).items():
- message.__module__ = "google.cloud.oslogin_v1.types"
- setattr(sys.modules[__name__], name, message)
- names.append(name)
-
-
-__all__ = tuple(sorted(names))
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/__init__.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/__init__.py
new file mode 100644
index 000000000000..c36dc46a52d8
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/__init__.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from .oslogin import (
+ LoginProfile,
+ DeletePosixAccountRequest,
+ DeleteSshPublicKeyRequest,
+ GetLoginProfileRequest,
+ GetSshPublicKeyRequest,
+ ImportSshPublicKeyRequest,
+ ImportSshPublicKeyResponse,
+ UpdateSshPublicKeyRequest,
+)
+
+
+__all__ = (
+ "LoginProfile",
+ "DeletePosixAccountRequest",
+ "DeleteSshPublicKeyRequest",
+ "GetLoginProfileRequest",
+ "GetSshPublicKeyRequest",
+ "ImportSshPublicKeyRequest",
+ "ImportSshPublicKeyResponse",
+ "UpdateSshPublicKeyRequest",
+)
diff --git a/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/oslogin.py b/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/oslogin.py
new file mode 100644
index 000000000000..f0e5fa37a28b
--- /dev/null
+++ b/packages/google-cloud-os-login/google/cloud/oslogin_v1/types/oslogin.py
@@ -0,0 +1,188 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import proto # type: ignore
+
+
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+__protobuf__ = proto.module(
+ package="google.cloud.oslogin.v1",
+ manifest={
+ "LoginProfile",
+ "DeletePosixAccountRequest",
+ "DeleteSshPublicKeyRequest",
+ "GetLoginProfileRequest",
+ "GetSshPublicKeyRequest",
+ "ImportSshPublicKeyRequest",
+ "ImportSshPublicKeyResponse",
+ "UpdateSshPublicKeyRequest",
+ },
+)
+
+
+class LoginProfile(proto.Message):
+ r"""The user profile information used for logging in to a virtual
+ machine on Google Compute Engine.
+
+ Attributes:
+ name (str):
+ Required. A unique user ID.
+ posix_accounts (Sequence[~.common.PosixAccount]):
+ The list of POSIX accounts associated with
+ the user.
+ ssh_public_keys (Sequence[~.oslogin.LoginProfile.SshPublicKeysEntry]):
+ A map from SSH public key fingerprint to the
+ associated key object.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ posix_accounts = proto.RepeatedField(
+ proto.MESSAGE, number=2, message=common.PosixAccount,
+ )
+
+ ssh_public_keys = proto.MapField(
+ proto.STRING, proto.MESSAGE, number=3, message=common.SshPublicKey,
+ )
+
+
+class DeletePosixAccountRequest(proto.Message):
+ r"""A request message for deleting a POSIX account entry.
+
+ Attributes:
+ name (str):
+ Required. A reference to the POSIX account to update. POSIX
+ accounts are identified by the project ID they are
+ associated with. A reference to the POSIX account is in
+ format ``users/{user}/projects/{project}``.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+
+class DeleteSshPublicKeyRequest(proto.Message):
+ r"""A request message for deleting an SSH public key.
+
+ Attributes:
+ name (str):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint. The
+ fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+
+class GetLoginProfileRequest(proto.Message):
+ r"""A request message for retrieving the login profile
+ information for a user.
+
+ Attributes:
+ name (str):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ project_id (str):
+ The project ID of the Google Cloud Platform
+ project.
+ system_id (str):
+ A system ID for filtering the results of the
+ request.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ project_id = proto.Field(proto.STRING, number=2)
+
+ system_id = proto.Field(proto.STRING, number=3)
+
+
+class GetSshPublicKeyRequest(proto.Message):
+ r"""A request message for retrieving an SSH public key.
+
+ Attributes:
+ name (str):
+ Required. The fingerprint of the public key to retrieve.
+ Public keys are identified by their SHA-256 fingerprint. The
+ fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+
+class ImportSshPublicKeyRequest(proto.Message):
+ r"""A request message for importing an SSH public key.
+
+ Attributes:
+ parent (str):
+ Required. The unique ID for the user in format
+ ``users/{user}``.
+ ssh_public_key (~.common.SshPublicKey):
+ Optional. The SSH public key and expiration
+ time.
+ project_id (str):
+ The project ID of the Google Cloud Platform
+ project.
+ """
+
+ parent = proto.Field(proto.STRING, number=1)
+
+ ssh_public_key = proto.Field(proto.MESSAGE, number=2, message=common.SshPublicKey,)
+
+ project_id = proto.Field(proto.STRING, number=3)
+
+
+class ImportSshPublicKeyResponse(proto.Message):
+ r"""A response message for importing an SSH public key.
+
+ Attributes:
+ login_profile (~.oslogin.LoginProfile):
+ The login profile information for the user.
+ """
+
+ login_profile = proto.Field(proto.MESSAGE, number=1, message=LoginProfile,)
+
+
+class UpdateSshPublicKeyRequest(proto.Message):
+ r"""A request message for updating an SSH public key.
+
+ Attributes:
+ name (str):
+ Required. The fingerprint of the public key to update.
+ Public keys are identified by their SHA-256 fingerprint. The
+ fingerprint of the public key is in format
+ ``users/{user}/sshPublicKeys/{fingerprint}``.
+ ssh_public_key (~.common.SshPublicKey):
+ Required. The SSH public key and expiration
+ time.
+ update_mask (~.field_mask.FieldMask):
+ Mask to control which fields get updated.
+ Updates all if not present.
+ """
+
+ name = proto.Field(proto.STRING, number=1)
+
+ ssh_public_key = proto.Field(proto.MESSAGE, number=2, message=common.SshPublicKey,)
+
+ update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,)
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-os-login/mypy.ini b/packages/google-cloud-os-login/mypy.ini
new file mode 100644
index 000000000000..4505b485436b
--- /dev/null
+++ b/packages/google-cloud-os-login/mypy.ini
@@ -0,0 +1,3 @@
+[mypy]
+python_version = 3.6
+namespace_packages = True
diff --git a/packages/google-cloud-os-login/noxfile.py b/packages/google-cloud-os-login/noxfile.py
index 2981137d7a61..9600c90df0e4 100644
--- a/packages/google-cloud-os-login/noxfile.py
+++ b/packages/google-cloud-os-login/noxfile.py
@@ -27,8 +27,8 @@
BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"]
DEFAULT_PYTHON_VERSION = "3.8"
-SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"]
-UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"]
+SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"]
+UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"]
@nox.session(python=DEFAULT_PYTHON_VERSION)
@@ -70,6 +70,8 @@ def lint_setup_py(session):
def default(session):
# Install all test dependencies, then install this package in-place.
+ session.install("asyncmock", "pytest-asyncio")
+
session.install("mock", "pytest", "pytest-cov")
session.install("-e", ".")
@@ -100,6 +102,10 @@ def system(session):
"""Run the system test suite."""
system_test_path = os.path.join("tests", "system.py")
system_test_folder_path = os.path.join("tests", "system")
+
+ # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true.
+ if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false":
+ session.skip("RUN_SYSTEM_TESTS is set to false, skipping")
# Sanity check: Only run tests if the environment variable is set.
if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""):
session.skip("Credentials must be set via environment variable")
@@ -135,7 +141,7 @@ def cover(session):
test runs (not system test runs), and then erases coverage data.
"""
session.install("coverage", "pytest-cov")
- session.run("coverage", "report", "--show-missing", "--fail-under=70")
+ session.run("coverage", "report", "--show-missing", "--fail-under=100")
session.run("coverage", "erase")
@@ -145,7 +151,7 @@ def docs(session):
"""Build the docs for this library."""
session.install("-e", ".")
- session.install("sphinx<3.0.0", "alabaster", "recommonmark")
+ session.install("sphinx", "alabaster", "recommonmark")
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
@@ -160,3 +166,38 @@ def docs(session):
os.path.join("docs", ""),
os.path.join("docs", "_build", "html", ""),
)
+
+
+@nox.session(python=DEFAULT_PYTHON_VERSION)
+def docfx(session):
+ """Build the docfx yaml files for this library."""
+
+ session.install("-e", ".")
+ # sphinx-docfx-yaml supports up to sphinx version 1.5.5.
+ # https://github.com/docascode/sphinx-docfx-yaml/issues/97
+ session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml")
+
+ shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
+ session.run(
+ "sphinx-build",
+ "-T", # show full traceback on exception
+ "-N", # no colors
+ "-D",
+ (
+ "extensions=sphinx.ext.autodoc,"
+ "sphinx.ext.autosummary,"
+ "docfx_yaml.extension,"
+ "sphinx.ext.intersphinx,"
+ "sphinx.ext.coverage,"
+ "sphinx.ext.napoleon,"
+ "sphinx.ext.todo,"
+ "sphinx.ext.viewcode,"
+ "recommonmark"
+ ),
+ "-b",
+ "html",
+ "-d",
+ os.path.join("docs", "_build", "doctrees", ""),
+ os.path.join("docs", ""),
+ os.path.join("docs", "_build", "html", ""),
+ )
diff --git a/packages/google-cloud-os-login/samples/AUTHORING_GUIDE.md b/packages/google-cloud-os-login/samples/AUTHORING_GUIDE.md
new file mode 100644
index 000000000000..55c97b32f4c1
--- /dev/null
+++ b/packages/google-cloud-os-login/samples/AUTHORING_GUIDE.md
@@ -0,0 +1 @@
+See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/samples/CONTRIBUTING.md b/packages/google-cloud-os-login/samples/CONTRIBUTING.md
new file mode 100644
index 000000000000..34c882b6f1a3
--- /dev/null
+++ b/packages/google-cloud-os-login/samples/CONTRIBUTING.md
@@ -0,0 +1 @@
+See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md
\ No newline at end of file
diff --git a/packages/google-cloud-os-login/scripts/decrypt-secrets.sh b/packages/google-cloud-os-login/scripts/decrypt-secrets.sh
index ff599eb2af25..21f6d2a26d90 100755
--- a/packages/google-cloud-os-login/scripts/decrypt-secrets.sh
+++ b/packages/google-cloud-os-login/scripts/decrypt-secrets.sh
@@ -20,14 +20,27 @@ ROOT=$( dirname "$DIR" )
# Work from the project root.
cd $ROOT
+# Prevent it from overriding files.
+# We recommend that sample authors use their own service account files and cloud project.
+# In that case, they are supposed to prepare these files by themselves.
+if [[ -f "testing/test-env.sh" ]] || \
+ [[ -f "testing/service-account.json" ]] || \
+ [[ -f "testing/client-secrets.json" ]]; then
+ echo "One or more target files exist, aborting."
+ exit 1
+fi
+
# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources.
PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}"
gcloud secrets versions access latest --secret="python-docs-samples-test-env" \
+ --project="${PROJECT_ID}" \
> testing/test-env.sh
gcloud secrets versions access latest \
--secret="python-docs-samples-service-account" \
+ --project="${PROJECT_ID}" \
> testing/service-account.json
gcloud secrets versions access latest \
--secret="python-docs-samples-client-secrets" \
- > testing/client-secrets.json
\ No newline at end of file
+ --project="${PROJECT_ID}" \
+ > testing/client-secrets.json
diff --git a/packages/google-cloud-os-login/scripts/fixup_oslogin_v1_keywords.py b/packages/google-cloud-os-login/scripts/fixup_oslogin_v1_keywords.py
new file mode 100644
index 000000000000..01ff86724ff2
--- /dev/null
+++ b/packages/google-cloud-os-login/scripts/fixup_oslogin_v1_keywords.py
@@ -0,0 +1,183 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import argparse
+import os
+import libcst as cst
+import pathlib
+import sys
+from typing import (Any, Callable, Dict, List, Sequence, Tuple)
+
+
+def partition(
+ predicate: Callable[[Any], bool],
+ iterator: Sequence[Any]
+) -> Tuple[List[Any], List[Any]]:
+ """A stable, out-of-place partition."""
+ results = ([], [])
+
+ for i in iterator:
+ results[int(predicate(i))].append(i)
+
+ # Returns trueList, falseList
+ return results[1], results[0]
+
+
+class osloginCallTransformer(cst.CSTTransformer):
+ CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
+ METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
+ 'delete_posix_account': ('name', ),
+ 'delete_ssh_public_key': ('name', ),
+ 'get_login_profile': ('name', 'project_id', 'system_id', ),
+ 'get_ssh_public_key': ('name', ),
+ 'import_ssh_public_key': ('parent', 'ssh_public_key', 'project_id', ),
+ 'update_ssh_public_key': ('name', 'ssh_public_key', 'update_mask', ),
+
+ }
+
+ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
+ try:
+ key = original.func.attr.value
+ kword_params = self.METHOD_TO_PARAMS[key]
+ except (AttributeError, KeyError):
+ # Either not a method from the API or too convoluted to be sure.
+ return updated
+
+ # If the existing code is valid, keyword args come after positional args.
+ # Therefore, all positional args must map to the first parameters.
+ args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
+ if any(k.keyword.value == "request" for k in kwargs):
+ # We've already fixed this file, don't fix it again.
+ return updated
+
+ kwargs, ctrl_kwargs = partition(
+ lambda a: not a.keyword.value in self.CTRL_PARAMS,
+ kwargs
+ )
+
+ args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
+ ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
+ for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
+
+ request_arg = cst.Arg(
+ value=cst.Dict([
+ cst.DictElement(
+ cst.SimpleString("'{}'".format(name)),
+ cst.Element(value=arg.value)
+ )
+ # Note: the args + kwargs looks silly, but keep in mind that
+ # the control parameters had to be stripped out, and that
+ # those could have been passed positionally or by keyword.
+ for name, arg in zip(kword_params, args + kwargs)]),
+ keyword=cst.Name("request")
+ )
+
+ return updated.with_changes(
+ args=[request_arg] + ctrl_kwargs
+ )
+
+
+def fix_files(
+ in_dir: pathlib.Path,
+ out_dir: pathlib.Path,
+ *,
+ transformer=osloginCallTransformer(),
+):
+ """Duplicate the input dir to the output dir, fixing file method calls.
+
+ Preconditions:
+ * in_dir is a real directory
+ * out_dir is a real, empty directory
+ """
+ pyfile_gen = (
+ pathlib.Path(os.path.join(root, f))
+ for root, _, files in os.walk(in_dir)
+ for f in files if os.path.splitext(f)[1] == ".py"
+ )
+
+ for fpath in pyfile_gen:
+ with open(fpath, 'r') as f:
+ src = f.read()
+
+ # Parse the code and insert method call fixes.
+ tree = cst.parse_module(src)
+ updated = tree.visit(transformer)
+
+ # Create the path and directory structure for the new file.
+ updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
+ updated_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Generate the updated source file at the corresponding path.
+ with open(updated_path, 'w') as f:
+ f.write(updated.code)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(
+ description="""Fix up source that uses the oslogin client library.
+
+The existing sources are NOT overwritten but are copied to output_dir with changes made.
+
+Note: This tool operates at a best-effort level at converting positional
+ parameters in client method calls to keyword based parameters.
+ Cases where it WILL FAIL include
+ A) * or ** expansion in a method call.
+ B) Calls via function or method alias (includes free function calls)
+ C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
+
+ These all constitute false negatives. The tool will also detect false
+ positives when an API method shares a name with another method.
+""")
+ parser.add_argument(
+ '-d',
+ '--input-directory',
+ required=True,
+ dest='input_dir',
+ help='the input directory to walk for python files to fix up',
+ )
+ parser.add_argument(
+ '-o',
+ '--output-directory',
+ required=True,
+ dest='output_dir',
+ help='the directory to output files fixed via un-flattening',
+ )
+ args = parser.parse_args()
+ input_dir = pathlib.Path(args.input_dir)
+ output_dir = pathlib.Path(args.output_dir)
+ if not input_dir.is_dir():
+ print(
+ f"input directory '{input_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if not output_dir.is_dir():
+ print(
+ f"output directory '{output_dir}' does not exist or is not a directory",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ if os.listdir(output_dir):
+ print(
+ f"output directory '{output_dir}' is not empty",
+ file=sys.stderr,
+ )
+ sys.exit(-1)
+
+ fix_files(input_dir, output_dir)
diff --git a/packages/google-cloud-os-login/setup.py b/packages/google-cloud-os-login/setup.py
index f3aafb8a529b..c1533dffb9e8 100644
--- a/packages/google-cloud-os-login/setup.py
+++ b/packages/google-cloud-os-login/setup.py
@@ -28,7 +28,11 @@
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_status = "Development Status :: 5 - Production/Stable"
-dependencies = ["google-api-core[grpc] >= 1.14.0, < 2.0.0dev"]
+dependencies = [
+ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev",
+ "proto-plus >= 1.4.0",
+ "libcst >= 0.2.5",
+]
extras = {}
@@ -43,7 +47,9 @@
# Only include packages under the 'google' namespace. Do not include tests,
# benchmarks, etc.
packages = [
- package for package in setuptools.find_packages() if package.startswith("google")
+ package
+ for package in setuptools.PEP420PackageFinder.find()
+ if package.startswith("google")
]
# Determine which namespaces are needed.
@@ -66,12 +72,10 @@
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
- "Programming Language :: Python :: 2",
- "Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
"Operating System :: OS Independent",
"Topic :: Internet",
],
@@ -80,7 +84,8 @@
namespace_packages=namespaces,
install_requires=dependencies,
extras_require=extras,
- python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",
+ python_requires=">=3.6",
+ scripts=["scripts/fixup_oslogin_v1_keywords.py"],
include_package_data=True,
zip_safe=False,
)
diff --git a/packages/google-cloud-os-login/synth.metadata b/packages/google-cloud-os-login/synth.metadata
index eb99d89278ad..6538a74c264a 100644
--- a/packages/google-cloud-os-login/synth.metadata
+++ b/packages/google-cloud-os-login/synth.metadata
@@ -4,22 +4,14 @@
"git": {
"name": ".",
"remote": "https://github.com/googleapis/python-oslogin.git",
- "sha": "f0254af9a85859f55bf1dbc7608c4a19be270368"
- }
- },
- {
- "git": {
- "name": "googleapis",
- "remote": "https://github.com/googleapis/googleapis.git",
- "sha": "cf41866c6f14f10a07aa1e2a1260fc0a2727d889",
- "internalRef": "317812187"
+ "sha": "98e8b892553dafba3fd1ec10146c8366cd2da4bf"
}
},
{
"git": {
"name": "synthtool",
"remote": "https://github.com/googleapis/synthtool.git",
- "sha": "cf2eff09d0f5319a4dc5cdce2b6356d85af4a798"
+ "sha": "0762e8ee2ec21cdfc4d82020b985a104feb0453b"
}
}
],
diff --git a/packages/google-cloud-os-login/synth.py b/packages/google-cloud-os-login/synth.py
index b5610426350c..e6e941716ffe 100644
--- a/packages/google-cloud-os-login/synth.py
+++ b/packages/google-cloud-os-login/synth.py
@@ -18,6 +18,7 @@
gapic = gcp.GAPICBazel()
common = gcp.CommonTemplates()
+excludes = ["README.rst", "setup.py", "nox*.py", "docs/index.rst"]
# ----------------------------------------------------------------------------
# Generate oslogin GAPIC layer
@@ -28,42 +29,54 @@
bazel_target="//google/cloud/oslogin/v1:oslogin-v1-py",
include_protos=True,
)
-# pb2's are incorrectly generated into deeper directories, so copy separately into proto/
-s.move(
- library,
- excludes=[
- "nox.py",
- "setup.py",
- "README.rst",
- "docs/index.rst",
- library / "google/cloud/oslogin_v1/proto/oslogin/**",
- library / "google/cloud/oslogin_v1/proto/oslogin_v1/**",
- ],
+
+s.move(library / "google/cloud/oslogin_v1")
+
+s.move(library / "google/cloud/oslogin", excludes=[library / "google/cloud/oslogin/common/**/*"])
+s.move(library / "google/cloud/oslogin/common", "google/cloud/oslogin_v1/common", excludes=[library / "google/cloud/oslogin/common/services"])
+
+s.move(library / "tests/unit/gapic/oslogin_v1")
+
+s.move(library / "scripts/fixup_oslogin_v1_keywords.py")
+
+s.move(library / "docs", excludes=[library / "docs/index.rst", library / "docs/common"])
+s.move(library / "docs/common", "docs/oslogin_v1/common", excludes=[library / "docs/common/services.rst"])
+s.replace(
+ "docs/oslogin_v1/common/types.rst",
+ "google.cloud.oslogin.common.types",
+ "google.cloud.oslogin_v1.common"
)
-s.move(library / "google/cloud/oslogin_v1/proto/**/*.py", "google/cloud/oslogin_v1/proto")
-s.move(library / "google/cloud/oslogin/common/**/*.py", "google/cloud/oslogin_v1/proto")
s.replace(
- "google/cloud/oslogin_v1/gapic/os_login_service_client.py",
+ "google/cloud/oslogin_v1/**/*.py",
"google-cloud-oslogin",
"google-cloud-os-login",
)
-# Fix up imports
+for file in ["google/cloud/**/*.py", "tests/**/*.py"]:
+ s.replace(
+ file,
+ "from google.cloud.oslogin.common import common_pb2 as common",
+ "from google.cloud.oslogin_v1 import common"
+ )
s.replace(
- "google/**/proto/*.py",
- "from google.cloud.oslogin.common import common_pb2",
- "from google.cloud.oslogin_v1.proto import common_pb2",
+ "google/cloud/oslogin_v1/**/*.py",
+ "google.cloud.oslogin.common",
+ "google.cloud.oslogin.v1"
+)
+s.replace(
+ "google/cloud/oslogin_v1/**/*.py",
+ "SshPublicKey.FromString",
+ "SshPublicKey.deserialize"
)
# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
-templated_files = common.py_library(cov_level=70)
-s.move(templated_files)
-
-# TODO(busunkim): Use latest sphinx after microgenerator transition
-s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"')
-
+templated_files = common.py_library(
+ samples=False, # set to True only if there are samples
+ microgenerator=True,
+)
+s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file
s.shell.run(["nox", "-s", "blacken"], hide_output=False)
diff --git a/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/__init__.py b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/__init__.py
new file mode 100644
index 000000000000..8b137891791f
--- /dev/null
+++ b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/__init__.py
@@ -0,0 +1 @@
+
diff --git a/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py
new file mode 100644
index 000000000000..bb077d5110fa
--- /dev/null
+++ b/packages/google-cloud-os-login/tests/unit/gapic/oslogin_v1/test_os_login_service.py
@@ -0,0 +1,2016 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2020 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import os
+import mock
+
+import grpc
+from grpc.experimental import aio
+import math
+import pytest
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+
+from google import auth
+from google.api_core import client_options
+from google.api_core import exceptions
+from google.api_core import gapic_v1
+from google.api_core import grpc_helpers
+from google.api_core import grpc_helpers_async
+from google.auth import credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.oslogin_v1 import common # type: ignore
+from google.cloud.oslogin_v1.services.os_login_service import OsLoginServiceAsyncClient
+from google.cloud.oslogin_v1.services.os_login_service import OsLoginServiceClient
+from google.cloud.oslogin_v1.services.os_login_service import transports
+from google.cloud.oslogin_v1.types import oslogin
+from google.oauth2 import service_account
+from google.protobuf import field_mask_pb2 as field_mask # type: ignore
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+def test__get_default_mtls_endpoint():
+ api_endpoint = "example.googleapis.com"
+ api_mtls_endpoint = "example.mtls.googleapis.com"
+ sandbox_endpoint = "example.sandbox.googleapis.com"
+ sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
+ non_googleapi = "api.example.com"
+
+ assert OsLoginServiceClient._get_default_mtls_endpoint(None) is None
+ assert (
+ OsLoginServiceClient._get_default_mtls_endpoint(api_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ OsLoginServiceClient._get_default_mtls_endpoint(api_mtls_endpoint)
+ == api_mtls_endpoint
+ )
+ assert (
+ OsLoginServiceClient._get_default_mtls_endpoint(sandbox_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ OsLoginServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
+ == sandbox_mtls_endpoint
+ )
+ assert (
+ OsLoginServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [OsLoginServiceClient, OsLoginServiceAsyncClient]
+)
+def test_os_login_service_client_from_service_account_file(client_class):
+ creds = credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ client = client_class.from_service_account_json("dummy/file/path.json")
+ assert client._transport._credentials == creds
+
+ assert client._transport._host == "oslogin.googleapis.com:443"
+
+
+def test_os_login_service_client_get_transport_class():
+ transport = OsLoginServiceClient.get_transport_class()
+ assert transport == transports.OsLoginServiceGrpcTransport
+
+ transport = OsLoginServiceClient.get_transport_class("grpc")
+ assert transport == transports.OsLoginServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"),
+ (
+ OsLoginServiceAsyncClient,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+@mock.patch.object(
+ OsLoginServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(OsLoginServiceClient),
+)
+@mock.patch.object(
+ OsLoginServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(OsLoginServiceAsyncClient),
+)
+def test_os_login_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(OsLoginServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(OsLoginServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError):
+ client = client_class()
+
+ # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ with pytest.raises(ValueError):
+ client = client_class()
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc", "true"),
+ (
+ OsLoginServiceAsyncClient,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc", "false"),
+ (
+ OsLoginServiceAsyncClient,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ OsLoginServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(OsLoginServiceClient),
+)
+@mock.patch.object(
+ OsLoginServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(OsLoginServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_os_login_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ ssl_channel_creds = mock.Mock()
+ with mock.patch(
+ "grpc.ssl_channel_credentials", return_value=ssl_channel_creds
+ ):
+ patched.return_value = None
+ client = client_class(client_options=options)
+
+ if use_client_cert_env == "false":
+ expected_ssl_channel_creds = None
+ expected_host = client.DEFAULT_ENDPOINT
+ else:
+ expected_ssl_channel_creds = ssl_channel_creds
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ ssl_channel_credentials=expected_ssl_channel_creds,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ ):
+ with mock.patch(
+ "google.auth.transport.grpc.SslCredentials.is_mtls",
+ new_callable=mock.PropertyMock,
+ ) as is_mtls_mock:
+ with mock.patch(
+ "google.auth.transport.grpc.SslCredentials.ssl_credentials",
+ new_callable=mock.PropertyMock,
+ ) as ssl_credentials_mock:
+ if use_client_cert_env == "false":
+ is_mtls_mock.return_value = False
+ ssl_credentials_mock.return_value = None
+ expected_host = client.DEFAULT_ENDPOINT
+ expected_ssl_channel_creds = None
+ else:
+ is_mtls_mock.return_value = True
+ ssl_credentials_mock.return_value = mock.Mock()
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_ssl_channel_creds = (
+ ssl_credentials_mock.return_value
+ )
+
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ ssl_channel_credentials=expected_ssl_channel_creds,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.grpc.SslCredentials.__init__", return_value=None
+ ):
+ with mock.patch(
+ "google.auth.transport.grpc.SslCredentials.is_mtls",
+ new_callable=mock.PropertyMock,
+ ) as is_mtls_mock:
+ is_mtls_mock.return_value = False
+ patched.return_value = None
+ client = client_class()
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"),
+ (
+ OsLoginServiceAsyncClient,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_os_login_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(scopes=["1", "2"],)
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_ENDPOINT,
+ scopes=["1", "2"],
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (OsLoginServiceClient, transports.OsLoginServiceGrpcTransport, "grpc"),
+ (
+ OsLoginServiceAsyncClient,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ ],
+)
+def test_os_login_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client.DEFAULT_ENDPOINT,
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_os_login_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = OsLoginServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ ssl_channel_credentials=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ )
+
+
+def test_delete_posix_account(
+ transport: str = "grpc", request_type=oslogin.DeletePosixAccountRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_posix_account), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_posix_account(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.DeletePosixAccountRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_posix_account_from_dict():
+ test_delete_posix_account(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_delete_posix_account_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.DeletePosixAccountRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_posix_account), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_posix_account(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_posix_account_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.DeletePosixAccountRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_posix_account), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_posix_account(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_posix_account_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.DeletePosixAccountRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_posix_account), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_posix_account(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_posix_account_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_posix_account), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_posix_account(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_posix_account_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_posix_account(
+ oslogin.DeletePosixAccountRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_posix_account_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_posix_account), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_posix_account(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_posix_account_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.delete_posix_account(
+ oslogin.DeletePosixAccountRequest(), name="name_value",
+ )
+
+
+def test_delete_ssh_public_key(
+ transport: str = "grpc", request_type=oslogin.DeleteSshPublicKeyRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.delete_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.DeleteSshPublicKeyRequest()
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_ssh_public_key_from_dict():
+ test_delete_ssh_public_key(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_delete_ssh_public_key_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.DeleteSshPublicKeyRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ response = await client.delete_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_ssh_public_key_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.DeleteSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = None
+
+ client.delete_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_ssh_public_key_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.DeleteSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+
+ await client.delete_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_delete_ssh_public_key_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_ssh_public_key(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_delete_ssh_public_key_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_ssh_public_key(
+ oslogin.DeleteSshPublicKeyRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_ssh_public_key_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.delete_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_ssh_public_key(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_delete_ssh_public_key_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.delete_ssh_public_key(
+ oslogin.DeleteSshPublicKeyRequest(), name="name_value",
+ )
+
+
+def test_get_login_profile(
+ transport: str = "grpc", request_type=oslogin.GetLoginProfileRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_login_profile), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.LoginProfile(name="name_value",)
+
+ response = client.get_login_profile(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.GetLoginProfileRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, oslogin.LoginProfile)
+
+ assert response.name == "name_value"
+
+
+def test_get_login_profile_from_dict():
+ test_get_login_profile(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_get_login_profile_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.GetLoginProfileRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_login_profile), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.LoginProfile(name="name_value",)
+ )
+
+ response = await client.get_login_profile(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, oslogin.LoginProfile)
+
+ assert response.name == "name_value"
+
+
+def test_get_login_profile_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.GetLoginProfileRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_login_profile), "__call__"
+ ) as call:
+ call.return_value = oslogin.LoginProfile()
+
+ client.get_login_profile(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_login_profile_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.GetLoginProfileRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_login_profile), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.LoginProfile()
+ )
+
+ await client.get_login_profile(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_get_login_profile_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_login_profile), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.LoginProfile()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_login_profile(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_login_profile_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_login_profile(
+ oslogin.GetLoginProfileRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_login_profile_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_login_profile), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.LoginProfile()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.LoginProfile()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_login_profile(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_login_profile_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.get_login_profile(
+ oslogin.GetLoginProfileRequest(), name="name_value",
+ )
+
+
+def test_get_ssh_public_key(
+ transport: str = "grpc", request_type=oslogin.GetSshPublicKeyRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey(
+ key="key_value",
+ expiration_time_usec=2144,
+ fingerprint="fingerprint_value",
+ name="name_value",
+ )
+
+ response = client.get_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.GetSshPublicKeyRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, common.SshPublicKey)
+
+ assert response.key == "key_value"
+
+ assert response.expiration_time_usec == 2144
+
+ assert response.fingerprint == "fingerprint_value"
+
+ assert response.name == "name_value"
+
+
+def test_get_ssh_public_key_from_dict():
+ test_get_ssh_public_key(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_get_ssh_public_key_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.GetSshPublicKeyRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ common.SshPublicKey(
+ key="key_value",
+ expiration_time_usec=2144,
+ fingerprint="fingerprint_value",
+ name="name_value",
+ )
+ )
+
+ response = await client.get_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, common.SshPublicKey)
+
+ assert response.key == "key_value"
+
+ assert response.expiration_time_usec == 2144
+
+ assert response.fingerprint == "fingerprint_value"
+
+ assert response.name == "name_value"
+
+
+def test_get_ssh_public_key_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.GetSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = common.SshPublicKey()
+
+ client.get_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_ssh_public_key_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.GetSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey())
+
+ await client.get_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_get_ssh_public_key_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_ssh_public_key(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+def test_get_ssh_public_key_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_ssh_public_key(
+ oslogin.GetSshPublicKeyRequest(), name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_ssh_public_key_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.get_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_ssh_public_key(name="name_value",)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+
+@pytest.mark.asyncio
+async def test_get_ssh_public_key_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.get_ssh_public_key(
+ oslogin.GetSshPublicKeyRequest(), name="name_value",
+ )
+
+
+def test_import_ssh_public_key(
+ transport: str = "grpc", request_type=oslogin.ImportSshPublicKeyRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.ImportSshPublicKeyResponse()
+
+ response = client.import_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.ImportSshPublicKeyRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, oslogin.ImportSshPublicKeyResponse)
+
+
+def test_import_ssh_public_key_from_dict():
+ test_import_ssh_public_key(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_import_ssh_public_key_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.ImportSshPublicKeyRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.ImportSshPublicKeyResponse()
+ )
+
+ response = await client.import_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, oslogin.ImportSshPublicKeyResponse)
+
+
+def test_import_ssh_public_key_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.ImportSshPublicKeyRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = oslogin.ImportSshPublicKeyResponse()
+
+ client.import_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_import_ssh_public_key_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.ImportSshPublicKeyRequest()
+ request.parent = "parent/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.ImportSshPublicKeyResponse()
+ )
+
+ await client.import_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"]
+
+
+def test_import_ssh_public_key_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.ImportSshPublicKeyResponse()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.import_ssh_public_key(
+ parent="parent_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ project_id="project_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].ssh_public_key == common.SshPublicKey(key="key_value")
+
+ assert args[0].project_id == "project_id_value"
+
+
+def test_import_ssh_public_key_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.import_ssh_public_key(
+ oslogin.ImportSshPublicKeyRequest(),
+ parent="parent_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ project_id="project_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_import_ssh_public_key_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.import_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = oslogin.ImportSshPublicKeyResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ oslogin.ImportSshPublicKeyResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.import_ssh_public_key(
+ parent="parent_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ project_id="project_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].parent == "parent_value"
+
+ assert args[0].ssh_public_key == common.SshPublicKey(key="key_value")
+
+ assert args[0].project_id == "project_id_value"
+
+
+@pytest.mark.asyncio
+async def test_import_ssh_public_key_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.import_ssh_public_key(
+ oslogin.ImportSshPublicKeyRequest(),
+ parent="parent_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ project_id="project_id_value",
+ )
+
+
+def test_update_ssh_public_key(
+ transport: str = "grpc", request_type=oslogin.UpdateSshPublicKeyRequest
+):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey(
+ key="key_value",
+ expiration_time_usec=2144,
+ fingerprint="fingerprint_value",
+ name="name_value",
+ )
+
+ response = client.update_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == oslogin.UpdateSshPublicKeyRequest()
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, common.SshPublicKey)
+
+ assert response.key == "key_value"
+
+ assert response.expiration_time_usec == 2144
+
+ assert response.fingerprint == "fingerprint_value"
+
+ assert response.name == "name_value"
+
+
+def test_update_ssh_public_key_from_dict():
+ test_update_ssh_public_key(request_type=dict)
+
+
+@pytest.mark.asyncio
+async def test_update_ssh_public_key_async(transport: str = "grpc_asyncio"):
+ client = OsLoginServiceAsyncClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = oslogin.UpdateSshPublicKeyRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ common.SshPublicKey(
+ key="key_value",
+ expiration_time_usec=2144,
+ fingerprint="fingerprint_value",
+ name="name_value",
+ )
+ )
+
+ response = await client.update_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, common.SshPublicKey)
+
+ assert response.key == "key_value"
+
+ assert response.expiration_time_usec == 2144
+
+ assert response.fingerprint == "fingerprint_value"
+
+ assert response.name == "name_value"
+
+
+def test_update_ssh_public_key_field_headers():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.UpdateSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = common.SshPublicKey()
+
+ client.update_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_ssh_public_key_field_headers_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = oslogin.UpdateSshPublicKeyRequest()
+ request.name = "name/value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey())
+
+ await client.update_ssh_public_key(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert ("x-goog-request-params", "name=name/value",) in kw["metadata"]
+
+
+def test_update_ssh_public_key_flattened():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey()
+
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_ssh_public_key(
+ name="name_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+ assert args[0].ssh_public_key == common.SshPublicKey(key="key_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+def test_update_ssh_public_key_flattened_error():
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_ssh_public_key(
+ oslogin.UpdateSshPublicKeyRequest(),
+ name="name_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_ssh_public_key_flattened_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client._client._transport.update_ssh_public_key), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = common.SshPublicKey()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(common.SshPublicKey())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_ssh_public_key(
+ name="name_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+
+ assert args[0].name == "name_value"
+
+ assert args[0].ssh_public_key == common.SshPublicKey(key="key_value")
+
+ assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"])
+
+
+@pytest.mark.asyncio
+async def test_update_ssh_public_key_flattened_error_async():
+ client = OsLoginServiceAsyncClient(credentials=credentials.AnonymousCredentials(),)
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ await client.update_ssh_public_key(
+ oslogin.UpdateSshPublicKeyRequest(),
+ name="name_value",
+ ssh_public_key=common.SshPublicKey(key="key_value"),
+ update_mask=field_mask.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.OsLoginServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.OsLoginServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = OsLoginServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.OsLoginServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = OsLoginServiceClient(
+ client_options={"scopes": ["1", "2"]}, transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.OsLoginServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ client = OsLoginServiceClient(transport=transport)
+ assert client._transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.OsLoginServiceGrpcTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.OsLoginServiceGrpcAsyncIOTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.OsLoginServiceGrpcTransport,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_transport_adc(transport_class):
+ # Test default credentials are used if not provided.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport_class()
+ adc.assert_called_once()
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = OsLoginServiceClient(credentials=credentials.AnonymousCredentials(),)
+ assert isinstance(client._transport, transports.OsLoginServiceGrpcTransport,)
+
+
+def test_os_login_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(exceptions.DuplicateCredentialArgs):
+ transport = transports.OsLoginServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_os_login_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.OsLoginServiceTransport(
+ credentials=credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "delete_posix_account",
+ "delete_ssh_public_key",
+ "get_login_profile",
+ "get_ssh_public_key",
+ "import_ssh_public_key",
+ "update_ssh_public_key",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+
+def test_os_login_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with mock.patch.object(
+ auth, "load_credentials_from_file"
+ ) as load_creds, mock.patch(
+ "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ load_creds.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.OsLoginServiceTransport(
+ credentials_file="credentials.json", quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_os_login_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with mock.patch.object(auth, "default") as adc, mock.patch(
+ "google.cloud.oslogin_v1.services.os_login_service.transports.OsLoginServiceTransport._prep_wrapped_messages"
+ ) as Transport:
+ Transport.return_value = None
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transport = transports.OsLoginServiceTransport()
+ adc.assert_called_once()
+
+
+def test_os_login_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ OsLoginServiceClient()
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ ),
+ quota_project_id=None,
+ )
+
+
+def test_os_login_service_transport_auth_adc():
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (credentials.AnonymousCredentials(), None)
+ transports.OsLoginServiceGrpcTransport(
+ host="squid.clam.whelk", quota_project_id="octopus"
+ )
+ adc.assert_called_once_with(
+ scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_os_login_service_host_no_port():
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="oslogin.googleapis.com"
+ ),
+ )
+ assert client._transport._host == "oslogin.googleapis.com:443"
+
+
+def test_os_login_service_host_with_port():
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="oslogin.googleapis.com:8000"
+ ),
+ )
+ assert client._transport._host == "oslogin.googleapis.com:8000"
+
+
+def test_os_login_service_grpc_transport_channel():
+ channel = grpc.insecure_channel("http://localhost/")
+
+ # Check that channel is used if provided.
+ transport = transports.OsLoginServiceGrpcTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+
+
+def test_os_login_service_grpc_asyncio_transport_channel():
+ channel = aio.insecure_channel("http://localhost/")
+
+ # Check that channel is used if provided.
+ transport = transports.OsLoginServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk", channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.OsLoginServiceGrpcTransport,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_os_login_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel", autospec=True
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.OsLoginServiceGrpcTransport,
+ transports.OsLoginServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_os_login_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel", autospec=True
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/compute",
+ ),
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_ssh_public_key_path():
+ user = "squid"
+ fingerprint = "clam"
+
+ expected = "users/{user}/sshPublicKeys/{fingerprint}".format(
+ user=user, fingerprint=fingerprint,
+ )
+ actual = OsLoginServiceClient.ssh_public_key_path(user, fingerprint)
+ assert expected == actual
+
+
+def test_parse_ssh_public_key_path():
+ expected = {
+ "user": "whelk",
+ "fingerprint": "octopus",
+ }
+ path = OsLoginServiceClient.ssh_public_key_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = OsLoginServiceClient.parse_ssh_public_key_path(path)
+ assert expected == actual
+
+
+def test_client_withDEFAULT_CLIENT_INFO():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.OsLoginServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = OsLoginServiceClient(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.OsLoginServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = OsLoginServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=credentials.AnonymousCredentials(), client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
diff --git a/packages/google-cloud-os-login/tests/unit/gapic/v1/test_os_login_service_client_v1.py b/packages/google-cloud-os-login/tests/unit/gapic/v1/test_os_login_service_client_v1.py
deleted file mode 100644
index 66fae902ae7d..000000000000
--- a/packages/google-cloud-os-login/tests/unit/gapic/v1/test_os_login_service_client_v1.py
+++ /dev/null
@@ -1,296 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Copyright 2020 Google LLC
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Unit tests."""
-
-import mock
-import pytest
-
-from google.cloud import oslogin_v1
-from google.cloud.oslogin_v1.proto import common_pb2
-from google.cloud.oslogin_v1.proto import oslogin_pb2
-from google.protobuf import empty_pb2
-
-
-class MultiCallableStub(object):
- """Stub for the grpc.UnaryUnaryMultiCallable interface."""
-
- def __init__(self, method, channel_stub):
- self.method = method
- self.channel_stub = channel_stub
-
- def __call__(self, request, timeout=None, metadata=None, credentials=None):
- self.channel_stub.requests.append((self.method, request))
-
- response = None
- if self.channel_stub.responses:
- response = self.channel_stub.responses.pop()
-
- if isinstance(response, Exception):
- raise response
-
- if response:
- return response
-
-
-class ChannelStub(object):
- """Stub for the grpc.Channel interface."""
-
- def __init__(self, responses=[]):
- self.responses = responses
- self.requests = []
-
- def unary_unary(self, method, request_serializer=None, response_deserializer=None):
- return MultiCallableStub(method, self)
-
-
-class CustomException(Exception):
- pass
-
-
-class TestOsLoginServiceClient(object):
- def test_delete_posix_account(self):
- channel = ChannelStub()
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- name = client.posix_account_path("[USER]", "[PROJECT]")
-
- client.delete_posix_account(name)
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.DeletePosixAccountRequest(name=name)
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_delete_posix_account_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- name = client.posix_account_path("[USER]", "[PROJECT]")
-
- with pytest.raises(CustomException):
- client.delete_posix_account(name)
-
- def test_delete_ssh_public_key(self):
- channel = ChannelStub()
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
-
- client.delete_ssh_public_key(name)
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.DeleteSshPublicKeyRequest(name=name)
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_delete_ssh_public_key_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
-
- with pytest.raises(CustomException):
- client.delete_ssh_public_key(name)
-
- def test_get_login_profile(self):
- # Setup Expected Response
- name_2 = "name2-1052831874"
- expected_response = {"name": name_2}
- expected_response = oslogin_pb2.LoginProfile(**expected_response)
-
- # Mock the API response
- channel = ChannelStub(responses=[expected_response])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- name = client.user_path("[USER]")
-
- response = client.get_login_profile(name)
- assert expected_response == response
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.GetLoginProfileRequest(name=name)
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_get_login_profile_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- name = client.user_path("[USER]")
-
- with pytest.raises(CustomException):
- client.get_login_profile(name)
-
- def test_get_ssh_public_key(self):
- # Setup Expected Response
- key = "key106079"
- expiration_time_usec = 2058878882
- fingerprint = "fingerprint-1375934236"
- name_2 = "name2-1052831874"
- expected_response = {
- "key": key,
- "expiration_time_usec": expiration_time_usec,
- "fingerprint": fingerprint,
- "name": name_2,
- }
- expected_response = common_pb2.SshPublicKey(**expected_response)
-
- # Mock the API response
- channel = ChannelStub(responses=[expected_response])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
-
- response = client.get_ssh_public_key(name)
- assert expected_response == response
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.GetSshPublicKeyRequest(name=name)
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_get_ssh_public_key_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
-
- with pytest.raises(CustomException):
- client.get_ssh_public_key(name)
-
- def test_import_ssh_public_key(self):
- # Setup Expected Response
- expected_response = {}
- expected_response = oslogin_pb2.ImportSshPublicKeyResponse(**expected_response)
-
- # Mock the API response
- channel = ChannelStub(responses=[expected_response])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- parent = client.user_path("[USER]")
-
- response = client.import_ssh_public_key(parent)
- assert expected_response == response
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.ImportSshPublicKeyRequest(parent=parent)
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_import_ssh_public_key_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- parent = client.user_path("[USER]")
-
- with pytest.raises(CustomException):
- client.import_ssh_public_key(parent)
-
- def test_update_ssh_public_key(self):
- # Setup Expected Response
- key = "key106079"
- expiration_time_usec = 2058878882
- fingerprint = "fingerprint-1375934236"
- name_2 = "name2-1052831874"
- expected_response = {
- "key": key,
- "expiration_time_usec": expiration_time_usec,
- "fingerprint": fingerprint,
- "name": name_2,
- }
- expected_response = common_pb2.SshPublicKey(**expected_response)
-
- # Mock the API response
- channel = ChannelStub(responses=[expected_response])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup Request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
- ssh_public_key = {}
-
- response = client.update_ssh_public_key(name, ssh_public_key)
- assert expected_response == response
-
- assert len(channel.requests) == 1
- expected_request = oslogin_pb2.UpdateSshPublicKeyRequest(
- name=name, ssh_public_key=ssh_public_key
- )
- actual_request = channel.requests[0][1]
- assert expected_request == actual_request
-
- def test_update_ssh_public_key_exception(self):
- # Mock the API response
- channel = ChannelStub(responses=[CustomException()])
- patch = mock.patch("google.api_core.grpc_helpers.create_channel")
- with patch as create_channel:
- create_channel.return_value = channel
- client = oslogin_v1.OsLoginServiceClient()
-
- # Setup request
- name = client.ssh_public_key_path("[USER]", "[FINGERPRINT]")
- ssh_public_key = {}
-
- with pytest.raises(CustomException):
- client.update_ssh_public_key(name, ssh_public_key)