HEX
Server: Apache/2.4.59 (Debian)
System: Linux keymana 4.19.0-21-cloud-amd64 #1 SMP Debian 4.19.249-2 (2022-06-30) x86_64
User: lijunjie (1003)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/compute/instant_snapshots_utils.py
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# 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.
"""Utilities for handling Compute ZoneInstantSnapshotService and RegionInstantSnapshotService."""

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import abc
from googlecloudsdk.core.exceptions import Error
import six


class UnknownResourceError(Error):
  """Raised when a instant snapshot resource argument is neither regional nor zonal."""


class _InstantSnapshot(six.with_metaclass(abc.ABCMeta, object)):
  """Common class for InstantSnapshot Service API client."""

  def GetService(self):
    return self._service

  def GetInstantSnapshotResource(self):
    request_msg = self.GetInstantSnapshotRequestMessage()
    return self._service.Get(request_msg)

  @abc.abstractmethod
  def GetInstantSnapshotRequestMessage(self):
    raise NotImplementedError

  @abc.abstractmethod
  def GetSetLabelsRequestMessage(self):
    raise NotImplementedError

  @abc.abstractmethod
  def GetSetInstantSnapshotLabelsRequestMessage(self):
    raise NotImplementedError


class _ZoneInstantSnapshot(_InstantSnapshot):
  """A wrapper for Compute Engine ZoneInstantSnapshotService API client."""

  def __init__(self, client, ips_ref, messages):
    _InstantSnapshot.__init__(self)
    self._ips_ref = ips_ref
    self._client = client
    self._service = client.zoneInstantSnapshots
    self._messages = messages

  @classmethod
  def GetOperationCollection(cls):
    return 'compute.zoneOperations'

  def GetInstantSnapshotRequestMessage(self):
    return self._messages.ComputeZoneInstantSnapshotsGetRequest(
        **self._ips_ref.AsDict())

  def GetSetLabelsRequestMessage(self):
    return self._messages.ZoneSetLabelsRequest

  def GetSetInstantSnapshotLabelsRequestMessage(self, ips, labels):
    req = self._messages.ComputeZoneInstantSnapshotsSetLabelsRequest
    return req(
        project=self._ips_ref.project,
        resource=self._ips_ref.instantSnapshot,
        zone=self._ips_ref.zone,
        zoneSetLabelsRequest=self._messages.ZoneSetLabelsRequest(
            labelFingerprint=ips.labelFingerprint, labels=labels))


class _RegionInstantSnapshot(_InstantSnapshot):
  """A wrapper for Compute Engine RegionInstantSnapshotService API client."""

  def __init__(self, client, ips_ref, messages):
    _InstantSnapshot.__init__(self)
    self._ips_ref = ips_ref
    self._client = client
    self._service = client.regionInstantSnapshots
    self._messages = messages

  @classmethod
  def GetOperationCollection(cls):
    return 'compute.regionOperations'

  def GetInstantSnapshotRequestMessage(self):
    return self._messages.ComputeRegionInstantSnapshotsGetRequest(
        **self._ips_ref.AsDict())

  def GetSetLabelsRequestMessage(self):
    return self._messages.RegionSetLabelsRequest

  def GetSetInstantSnapshotLabelsRequestMessage(self, ips, labels):
    req = self._messages.ComputeRegionInstantSnapshotsSetLabelsRequest
    return req(
        project=self._ips_ref.project,
        resource=self._ips_ref.instantSnapshot,
        region=self._ips_ref.region,
        regionSetLabelsRequest=self._messages.RegionSetLabelsRequest(
            labelFingerprint=ips.labelFingerprint, labels=labels))


def IsZonal(ips_ref):
  """Checks if a compute instant snapshot is zonal or regional.

  Args:
    ips_ref: the instant snapshot resource reference that is parsed from
      resource arguments to modify.

  Returns:
    Boolean, true when the compute instant snapshot resource to modify is a
    zonal compute instant snapshot resource, false when a regional compute
    instant snapshot resource.

  Raises:
    UnknownResourceError: when the compute instant snapshot resource is not in
    the
      correct format.
  """
  # There are 2 types of instant snapshot services,
  # ZoneInstantSnapshotService (by zone) and
  # RegionInstantSnapshotService (by region).
  if ips_ref.Collection() == 'compute.zoneInstantSnapshots':
    return True
  elif ips_ref.Collection() == 'compute.regionInstantSnapshots':
    return False
  else:
    raise UnknownResourceError(
        'Unexpected instant snapshot resource argument of {}'.format(
            ips_ref.Collection()))


def GetInstantSnapshotInfo(ips_ref, client, messages):
  """Gets the zonal or regional instant snapshot api info.

  Args:
    ips_ref: the instant snapshot resource reference that is parsed from
      resource arguments.
    client: the compute api_tools_client.
    messages: the compute message module.

  Returns:
    _ZoneInstantSnapshot or _RegionInstantSnapshot.
  """
  if IsZonal(ips_ref):
    return _ZoneInstantSnapshot(client, ips_ref, messages)
  else:
    return _RegionInstantSnapshot(client, ips_ref, messages)