1# -*- coding: utf-8 -*- #
2# Copyright 2016 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Util functions for DM commands."""
17
18from __future__ import absolute_import
19from __future__ import division
20from __future__ import unicode_literals
21
22import base64
23import binascii
24import io
25
26from googlecloudsdk.calliope import exceptions as calliope_exceptions
27from googlecloudsdk.core import log
28from googlecloudsdk.core.resource import resource_printer
29from googlecloudsdk.core.util import http_encoding
30
31
32def PrintFingerprint(fingerprint):
33  """Prints the fingerprint for user reference."""
34
35  log.status.Print('The fingerprint of the deployment is %s'
36                   % (base64.urlsafe_b64encode(fingerprint)))
37
38
39def DecodeFingerprint(fingerprint):
40  """Returns the base64 url decoded fingerprint."""
41  try:
42    decoded_fingerprint = base64.urlsafe_b64decode(
43        http_encoding.Encode(fingerprint))
44  except (TypeError, binascii.Error):
45    raise calliope_exceptions.InvalidArgumentException(
46        '--fingerprint', 'fingerprint cannot be decoded.')
47  return decoded_fingerprint
48
49
50def CredentialFrom(message, principal):
51  """Translates a dict of credential data into a message object.
52
53  Args:
54    message: The API message to use.
55    principal: A string contains service account data.
56  Returns:
57    An ServiceAccount message object derived from credential_string.
58  Raises:
59    InvalidArgumentException: principal string unexpected format.
60  """
61  if principal == 'PROJECT_DEFAULT':
62    return message.Credential(useProjectDefault=True)
63  if principal.startswith('serviceAccount:'):
64    service_account = message.ServiceAccount(
65        email=principal[len('serviceAccount:'):])
66    return message.Credential(serviceAccount=service_account)
67  raise calliope_exceptions.InvalidArgumentException(
68      '--credential',
69      'credential must start with serviceAccount: or use PROJECT_DEFAULT.')
70
71
72def RenderMessageAsYaml(message):
73  """Returns a ready-to-print string representation for the provided message.
74
75  Args:
76    message: message object
77
78  Returns:
79    A ready-to-print string representation of the message.
80  """
81  output_message = io.StringIO()
82  resource_printer.Print(message, 'yaml', out=output_message)
83  return output_message.getvalue()
84
85
86def LogOperationStatus(operation, operation_description):
87  """Log operation warnings if there is any."""
88  if operation.warnings:
89    log.warning(
90        '{0} operation {1} completed with warnings:\n{2}'.format(
91            operation_description, operation.name,
92            RenderMessageAsYaml(operation.warnings)))
93
94  else:
95    log.status.Print('{0} operation {1} completed successfully.'.format(
96        operation_description, operation.name))
97