Exemplo n.º 1
0
    def testDateTimeEncodingInAMap(self):
        msg = MapToDateTimeValue(additionalProperties=[
            MapToDateTimeValue.AdditionalProperty(
                key='1st',
                value=datetime.datetime(2014,
                                        7,
                                        2,
                                        23,
                                        33,
                                        25,
                                        541000,
                                        tzinfo=util.TimeZoneOffset(
                                            datetime.timedelta(0)))),
            MapToDateTimeValue.AdditionalProperty(
                key='2nd',
                value=datetime.datetime(2015,
                                        7,
                                        2,
                                        23,
                                        33,
                                        25,
                                        541000,
                                        tzinfo=util.TimeZoneOffset(
                                            datetime.timedelta(0))))
        ])

        self.assertEqual(
            '{"1st": "2014-07-02T23:33:25.541000+00:00",'
            ' "2nd": "2015-07-02T23:33:25.541000+00:00"}',
            encoding.MessageToJson(msg))
Exemplo n.º 2
0
    def testSslCertsDescribe(self):
        self.mocked_client.sslCerts.List.Expect(
            self.messages.SqlSslCertsListRequest(
                instance='integration-test',
                project=self.Project(),
            ),
            self.messages.SslCertsListResponse(
                items=[
                    self.messages.SslCert(
                        cert=
                        '-----BEGIN CERTIFICATE-----\nMIIC/zCCAeegAwIBAgIES2',
                        certSerialNumber='1264712781',
                        commonName='cert',
                        createTime=datetime.datetime(
                            2014,
                            2,
                            4,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        expirationTime=datetime.datetime(
                            2024,
                            2,
                            2,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        instance='integration-test',
                        kind='sql#sslCert',
                        sha1Fingerprint=
                        '77299aad4c8136911c1f0b07dd9802a9a72124e8',
                    ),
                ],
                kind='sql#sslCertsList',
            ))

        self.Run('sql ssl-certs describe cert --instance=integration-test')
        self.AssertOutputContains("""\
cert: |-
  -----BEGIN CERTIFICATE-----
  MIIC/zCCAeegAwIBAgIES2
certSerialNumber: '1264712781'
commonName: cert
createTime: '2014-02-04T21:10:29.402000+00:00'
expirationTime: '2024-02-02T21:10:29.402000+00:00'
instance: integration-test
kind: sql#sslCert
sha1Fingerprint: 77299aad4c8136911c1f0b07dd9802a9a72124e8
""",
                                  normalize_space=True)

        # Checking for deprecation warning.
        self.AssertErrContains('`gcloud sql ssl-certs` is deprecated')
Exemplo n.º 3
0
 def testJsonDatetime(self):
     msg = TimeMessage(timefield=datetime.datetime(
         2014, 7, 2, 23, 33, 25, 541000,
         tzinfo=util.TimeZoneOffset(datetime.timedelta(0))))
     self.assertEqual(
         '{"timefield": "2014-07-02T23:33:25.541000+00:00"}',
         encoding.MessageToJson(msg))
Exemplo n.º 4
0
    def testRotateWithNoPreviousCert(self):
        active_cert_fingerprint = 'one'
        instance_name = 'integration-test'

        # The list endpoint is called to determine the previous certificate.
        self.mocked_client.instances.ListServerCas.Expect(
            self.messages.SqlInstancesListServerCasRequest(
                instance=instance_name,
                project=self.Project(),
            ),
            self.messages.InstancesListServerCasResponse(
                activeVersion=active_cert_fingerprint,
                certs=[
                    data.GetSslCert(
                        instance_name, active_cert_fingerprint,
                        datetime.datetime(
                            2024,
                            2,
                            2,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat())
                ],
                kind='sql#sslCertsList',
            ))

        with self.AssertRaisesExceptionRegexp(
                exceptions.ResourceNotFoundError,
                r'No previous Server CA Certificate exists.'):
            self.Run('sql ssl server-ca-certs rollback --instance={}'.format(
                instance_name))
Exemplo n.º 5
0
  def testSslCertsList(self):
    active_cert_fingerprint = 'one'
    instance_name = 'integration-test'

    self.mocked_client.instances.ListServerCas.Expect(
        self.messages.SqlInstancesListServerCasRequest(
            instance=instance_name,
            project=self.Project(),
        ),
        self.messages.InstancesListServerCasResponse(
            activeVersion=active_cert_fingerprint,
            certs=[
                data.GetSslCert(
                    instance_name, active_cert_fingerprint,
                    datetime.datetime(
                        2024,
                        2,
                        2,
                        21,
                        10,
                        29,
                        402000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat()),
                data.GetSslCert(
                    instance_name, 'two',
                    datetime.datetime(
                        2024,
                        4,
                        4,
                        21,
                        10,
                        29,
                        402000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat())
            ],
            kind='sql#sslCertsList',
        ))
    self.Run('sql ssl server-ca-certs list --instance={}'.format(instance_name))
    self.AssertOutputContains(
        """\
SHA1_FINGERPRINT EXPIRATION
one              2024-02-02T21:10:29.402000+00:00
two              2024-04-04T21:10:29.402000+00:00
""",
        normalize_space=True)
Exemplo n.º 6
0
def GetOperation(project, instance, op_type, op_status, error=None):
    """Returns a sample Operation of op_type and op_status acting on instance."""
    return sqladmin_v1beta4.Operation(
        # pylint:disable=line-too-long
        insertTime=datetime.datetime(2014,
                                     8,
                                     12,
                                     19,
                                     38,
                                     39,
                                     415000,
                                     tzinfo=protorpc_util.TimeZoneOffset(
                                         datetime.timedelta(0))).isoformat(),
        startTime=datetime.datetime(2014,
                                    8,
                                    12,
                                    19,
                                    38,
                                    39,
                                    525000,
                                    tzinfo=protorpc_util.TimeZoneOffset(
                                        datetime.timedelta(0))).isoformat(),
        endTime=datetime.datetime(2014,
                                  8,
                                  12,
                                  19,
                                  39,
                                  26,
                                  601000,
                                  tzinfo=protorpc_util.TimeZoneOffset(
                                      datetime.timedelta(0))).isoformat(),
        error=error,
        exportContext=None,
        importContext=None,
        targetId=instance.name,
        targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}'.
        format(project),
        targetProject=project,
        kind='sql#operation',
        name='344acb84-0000-1111-2222-1e71c6077b34',
        selfLink=
        'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/sample'
        .format(project),
        operationType=op_type,
        status=op_status,
        user='******',
    )
Exemplo n.º 7
0
    def testClientCertsList(self):
        self.mocked_client.sslCerts.List.Expect(
            self.messages.SqlSslCertsListRequest(
                instance='integration-test',
                project=self.Project(),
            ),
            self.messages.SslCertsListResponse(
                items=[
                    self.messages.SslCert(
                        cert='-----BEGIN CERTIFICATE-----\nMIIC/zCCAeegAwIBA',
                        certSerialNumber='1264712781',
                        commonName='cert',
                        createTime=datetime.datetime(
                            2014,
                            2,
                            4,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        expirationTime=datetime.datetime(
                            2024,
                            2,
                            2,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        instance='integration-test',
                        kind='sql#sslCert',
                        sha1Fingerprint=
                        '77299aad4c8136911c1f0b07dd9802a9a72124e8',
                    ),
                ],
                kind='sql#sslCertsList',
            ))
        self.Run('sql ssl client-certs list --instance=integration-test')
        self.AssertOutputContains("""\
NAME  SHA1_FINGERPRINT                          EXPIRATION
cert  77299aad4c8136911c1f0b07dd9802a9a72124e8  2024-02-02T21:10:29.402000+00:00
""",
                                  normalize_space=True)
 def testValueToMessageWithTimeZone(self):
     time_zone = util.TimeZoneOffset(60 * 10)
     field = message_types.DateTimeField(1)
     message = field.value_to_message(
         datetime.datetime(2033, 2, 4, 11, 22, 10, tzinfo=time_zone))
     self.assertEqual(
         message_types.DateTimeMessage(milliseconds=1991128930000,
                                       time_zone_offset=600), message)
Exemplo n.º 9
0
def GetBackup(instance, backup_id, status):
    """Returns a sample BackupRun w/ id backup_id and the given status."""
    return sqladmin_v1beta4.BackupRun(
        id=backup_id,
        windowStartTime=datetime.datetime(
            2014,
            8,
            13,
            23,
            0,
            0,
            802000,
            tzinfo=protorpc_util.TimeZoneOffset(
                datetime.timedelta(0))).isoformat(),
        endTime=datetime.datetime(2014,
                                  8,
                                  14,
                                  0,
                                  27,
                                  47,
                                  910000,
                                  tzinfo=protorpc_util.TimeZoneOffset(
                                      datetime.timedelta(0))).isoformat(),
        enqueuedTime=datetime.datetime(2014,
                                       8,
                                       14,
                                       0,
                                       25,
                                       12,
                                       318000,
                                       tzinfo=protorpc_util.TimeZoneOffset(
                                           datetime.timedelta(0))).isoformat(),
        error=None,
        instance=instance.name,
        kind='sql#backupRun',
        startTime=datetime.datetime(2014,
                                    8,
                                    14,
                                    0,
                                    25,
                                    12,
                                    321000,
                                    tzinfo=protorpc_util.TimeZoneOffset(
                                        datetime.timedelta(0))).isoformat(),
        status=status,
    )
Exemplo n.º 10
0
def _WhitelistClientIP(instance_ref, sql_client, sql_messages, resources):
    """Add CLIENT_IP to the authorized networks list.

  Makes an API call to add CLIENT_IP to the authorized networks list.
  The server knows to interpret the string CLIENT_IP as the address with which
  the client reaches the server. This IP will be whitelisted for 1 minute.

  Args:
    instance_ref: resources.Resource, The instance we're connecting to.
    sql_client: apitools.BaseApiClient, A working client for the sql version
        to be used.
    sql_messages: module, The module that defines the messages for the sql
        version to be used.
    resources: resources.Registry, The registry that can create resource refs
        for the sql version to be used.

  Returns:
    string, The name of the authorized network rule. Callers can use this name
    to find out the IP the client reached the server with.
  Raises:
    HttpException: An http error response was received while executing api
        request.
    ToolException: Server did not complete the whitelisting operation in time.
  """
    datetime_now = datetime.datetime.now(
        protorpc_util.TimeZoneOffset(datetime.timedelta(0)))

    acl_name = 'sql connect at time {0}'.format(datetime_now)
    user_acl = sql_messages.AclEntry(name=acl_name,
                                     expirationTime=datetime_now +
                                     datetime.timedelta(minutes=1),
                                     value='CLIENT_IP')

    try:
        original = sql_client.instances.Get(
            sql_messages.SqlInstancesGetRequest(
                project=instance_ref.project, instance=instance_ref.instance))
    except apitools_exceptions.HttpError as error:
        raise exceptions.HttpException(error)

    original.settings.ipConfiguration.authorizedNetworks.append(user_acl)
    patch_request = sql_messages.SqlInstancesPatchRequest(
        databaseInstance=original,
        project=instance_ref.project,
        instance=instance_ref.instance)
    result = sql_client.instances.Patch(patch_request)

    operation_ref = resources.Create('sql.operations',
                                     operation=result.name,
                                     project=instance_ref.project,
                                     instance=instance_ref.instance)
    message = 'Whitelisting your IP for incoming connection for 1 minute'

    operations.OperationsV1Beta4.WaitForOperation(sql_client, operation_ref,
                                                  message)

    return acl_name
 def testValueFromMessageWithTimeZone(self):
     message = message_types.DateTimeMessage(milliseconds=1991128000000,
                                             time_zone_offset=300)
     field = message_types.DateTimeField(1)
     timestamp = field.value_from_message(message)
     time_zone = util.TimeZoneOffset(60 * 5)
     self.assertEqual(
         datetime.datetime(2033, 2, 4, 11, 6, 40, tzinfo=time_zone),
         timestamp)
Exemplo n.º 12
0
    def testDateTimeWithTimeZone(self):
        """Test DateTimeFields with time zones."""
        class MyMessage(messages.Message):
            value = message_types.DateTimeField(1)

        value = datetime.datetime(2013, 1, 3, 11, 36, 30, 123000,
                                  util.TimeZoneOffset(8 * 60))
        message = MyMessage(value=value)
        decoded = self.PROTOLIB.decode_message(
            MyMessage, self.PROTOLIB.encode_message(message))
        self.assertEquals(decoded.value, value)
Exemplo n.º 13
0
def get_mock_end_time():
    """Create a datetime object for 2014-08-13T21:13:39.764Z."""
    return datetime.datetime(2014,
                             8,
                             13,
                             21,
                             13,
                             39,
                             764000,
                             tzinfo=protorpc_util.TimeZoneOffset(
                                 datetime.timedelta(0))).isoformat()
Exemplo n.º 14
0
def get_mock_start_time():
    """Create a datetime object for 2014-08-13T21:13:18.925Z."""
    return datetime.datetime(2014,
                             8,
                             13,
                             21,
                             13,
                             18,
                             925000,
                             tzinfo=protorpc_util.TimeZoneOffset(
                                 datetime.timedelta(0))).isoformat()
Exemplo n.º 15
0
 def testMessageToReprWithTime(self):
     msg = TimeMessage(timefield=datetime.datetime(
         2014, 7, 2, 23, 33, 25, 541000,
         tzinfo=util.TimeZoneOffset(datetime.timedelta(0))))
     self.assertEqual(
         encoding.MessageToRepr(msg, multiline=True),
         ('%s.TimeMessage(\n    '
          'timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, '
          'tzinfo=apitools.base.protorpclite.util.TimeZoneOffset('
          'datetime.timedelta(0))),\n)') % __name__)
     self.assertEqual(
         encoding.MessageToRepr(msg, multiline=True, no_modules=True),
         'TimeMessage(\n    '
         'timefield=datetime.datetime(2014, 7, 2, 23, 33, 25, 541000, '
         'tzinfo=TimeZoneOffset(datetime.timedelta(0))),\n)')
Exemplo n.º 16
0
 def testDateTimeTimeZones(self):
     """Test that a datetime string with a timezone is decoded correctly."""
     tests = (
         ('2012-09-30T15:31:50.262-06:00',
          (2012, 9, 30, 15, 31, 50, 262000, util.TimeZoneOffset(-360))),
         ('2012-09-30T15:31:50.262+01:30',
          (2012, 9, 30, 15, 31, 50, 262000, util.TimeZoneOffset(90))),
         ('2012-09-30T15:31:50+00:05',
          (2012, 9, 30, 15, 31, 50, 0, util.TimeZoneOffset(5))),
         ('2012-09-30T15:31:50+00:00',
          (2012, 9, 30, 15, 31, 50, 0, util.TimeZoneOffset(0))),
         ('2012-09-30t15:31:50-00:00',
          (2012, 9, 30, 15, 31, 50, 0, util.TimeZoneOffset(0))),
         ('2012-09-30t15:31:50z',
          (2012, 9, 30, 15, 31, 50, 0, util.TimeZoneOffset(0))),
         ('2012-09-30T15:31:50-23:00',
          (2012, 9, 30, 15, 31, 50, 0, util.TimeZoneOffset(-1380))))
     for datetime_string, datetime_vals in tests:
         decoded = util.decode_datetime(datetime_string)
         expected = datetime.datetime(*datetime_vals)
         self.assertEquals(expected, decoded)
Exemplo n.º 17
0
    def value_from_message(self, message):
        """Convert DateTimeMessage to a datetime.

        Args:
          A DateTimeMessage instance.

        Returns:
          A datetime instance.
        """
        message = super(DateTimeField, self).value_from_message(message)
        if message.time_zone_offset is None:
            return datetime.datetime.utcfromtimestamp(message.milliseconds /
                                                      1000.0)

        # Need to subtract the time zone offset, because when we call
        # datetime.fromtimestamp, it will add the time zone offset to the
        # value we pass.
        milliseconds = (message.milliseconds -
                        60000 * message.time_zone_offset)

        timezone = util.TimeZoneOffset(message.time_zone_offset)
        return datetime.datetime.fromtimestamp(milliseconds / 1000.0,
                                               tz=timezone)
Exemplo n.º 18
0
 def _ExpectExport(self):
     self.mocked_client.instances.Export.Expect(
         self.messages.SqlInstancesExportRequest(
             instance='testinstance',
             instancesExportRequest=self.messages.InstancesExportRequest(
                 exportContext=self.messages.ExportContext(
                     # pylint:disable=line-too-long
                     csvExportOptions=None,
                     fileType=self.messages.ExportContext.
                     FileTypeValueValuesEnum.SQL,
                     kind='sql#exportContext',
                     sqlExportOptions=self.messages.ExportContext.
                     SqlExportOptionsValue(
                         schemaOnly=None,
                         tables=[],
                     ),
                     uri='gs://speckletest/testinstance.gz',
                 ), ),
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 13,
                 20,
                 50,
                 43,
                 963000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=None,
             endTime=None,
             error=None,
             exportContext=self.messages.ExportContext(
                 csvExportOptions=None,
                 fileType=self.messages.ExportContext.
                 FileTypeValueValuesEnum.SQL,
                 kind='sql#exportContext',
                 sqlExportOptions=self.messages.ExportContext.
                 SqlExportOptionsValue(
                     schemaOnly=None,
                     tables=[],
                 ),
                 uri='gs://speckletest/testinstance.gz',
             ),
             importContext=None,
             targetId='testinstance',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/testinstance'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='af859489-ca9c-470f-8340-86da167b368f',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/af859489-ca9c-470f-8340-86da167b368f'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.EXPORT,
             status=self.messages.Operation.StatusValueValuesEnum.PENDING,
             user='******',
         ))
     self.mocked_client.operations.Get.Expect(
         self.messages.SqlOperationsGetRequest(
             operation='af859489-ca9c-470f-8340-86da167b368f',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 13,
                 20,
                 50,
                 43,
                 963000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=datetime.datetime(
                 2014,
                 8,
                 13,
                 20,
                 50,
                 44,
                 13000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             endTime=datetime.datetime(
                 2014,
                 8,
                 13,
                 20,
                 50,
                 49,
                 639000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             error=None,
             exportContext=self.messages.ExportContext(
                 csvExportOptions=None,
                 fileType=self.messages.ExportContext.
                 FileTypeValueValuesEnum.SQL,
                 kind='sql#exportContext',
                 sqlExportOptions=self.messages.ExportContext.
                 SqlExportOptionsValue(
                     schemaOnly=False,
                     tables=[],
                 ),
                 uri='gs://speckletest/testinstance.gz',
             ),
             importContext=None,
             targetId='testinstance',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/testinstance'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='af859489-ca9c-470f-8340-86da167b368f',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/af859489-ca9c-470f-8340-86da167b368f'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.EXPORT,
             status=self.messages.Operation.StatusValueValuesEnum.DONE,
             user='******',
         ))
 def _ExpectRestoreBackup(self):
     self.mocked_client.instances.RestoreBackup.Expect(
         self.messages.SqlInstancesRestoreBackupRequest(
             # pylint:disable=line-too-long
             instance='clone-instance-7',
             project=self.Project(),
             instancesRestoreBackupRequest=self.messages.
             InstancesRestoreBackupRequest(
                 restoreBackupContext=self.messages.RestoreBackupContext(
                     backupRunId=1438876800422,
                     instanceId='clone-instance-7',
                 ), ),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 415000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=None,
             endTime=None,
             error=None,
             exportContext=None,
             importContext=None,
             targetId='clone-instance-7',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='1178746b-14d4-4258-bbdd-52856882c213',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/1178746b-14d4-4258-bbdd-52856882c213'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.RESTORE_VOLUME,
             status=self.messages.Operation.StatusValueValuesEnum.PENDING,
             user='******',
         ))
     self.mocked_client.operations.Get.Expect(
         self.messages.SqlOperationsGetRequest(
             operation='1178746b-14d4-4258-bbdd-52856882c213',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 415000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 525000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             endTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 39,
                 26,
                 601000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             error=None,
             exportContext=None,
             importContext=None,
             targetId='clone-instance-7',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='1178746b-14d4-4258-bbdd-52856882c213',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/1178746b-14d4-4258-bbdd-52856882c213'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.RESTORE_VOLUME,
             status=self.messages.Operation.StatusValueValuesEnum.DONE,
             user='******',
         ))
Exemplo n.º 20
0
 def _ExpectPromoteReplica(self):
     self.mocked_client.instances.PromoteReplica.Expect(
         self.messages.SqlInstancesPromoteReplicaRequest(
             instance='replica-1',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 26,
                 22,
                 6,
                 26,
                 785000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=None,
             endTime=None,
             error=None,
             exportContext=None,
             importContext=None,
             targetId='replica-1',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/patch-instance3'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='56dec13c-fe47-449d-9942-921ad3bb8092',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/56dec13c-fe47-449d-9942-921ad3bb8092'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.PROMOTE_REPLICA,
             status=self.messages.Operation.StatusValueValuesEnum.PENDING,
             user='******',
         ))
     self.mocked_client.operations.Get.Expect(
         self.messages.SqlOperationsGetRequest(
             operation='56dec13c-fe47-449d-9942-921ad3bb8092',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 26,
                 22,
                 6,
                 26,
                 785000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=datetime.datetime(
                 2014,
                 8,
                 26,
                 22,
                 6,
                 27,
                 48000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             endTime=datetime.datetime(
                 2014,
                 8,
                 26,
                 22,
                 6,
                 27,
                 48000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             error=None,
             exportContext=None,
             importContext=None,
             targetId='replica-1',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/patch-instance3'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='56dec13c-fe47-449d-9942-921ad3bb8092',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/56dec13c-fe47-449d-9942-921ad3bb8092'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.PROMOTE_REPLICA,
             status=self.messages.Operation.StatusValueValuesEnum.DONE,
             user='******',
         ))
Exemplo n.º 21
0
  def testSimpleClone(self):
    self.ExpectInstanceGet(self.GetV2Instance('clone-instance-7'))
    self.mocked_client.instances.Clone.Expect(
        self.messages.SqlInstancesCloneRequest(
            instancesCloneRequest=self.messages.InstancesCloneRequest(
                cloneContext=self.messages.CloneContext(
                    binLogCoordinates=None,
                    destinationInstanceName='clone-instance-7a',
                    kind='sql#cloneContext',
                ),),
            instance='clone-instance-7',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    create_time = datetime.datetime(
        2014,
        8,
        13,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    expiration_time = datetime.datetime(
        2024,
        8,
        10,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    self.mocked_client.instances.Get.Expect(
        self.messages.SqlInstancesGetRequest(
            instance='clone-instance-7a',
            project=self.Project(),
        ),
        self.messages.DatabaseInstance(
            currentDiskSize=287592789,
            databaseVersion=self.messages.DatabaseInstance
            .DatabaseVersionValueValuesEnum.MYSQL_5_5,
            etag='"DExdZ69FktjWMJ-ohD1vLZW9pnk/Mw"',
            name='clone-instance-7a',
            ipAddresses=[],
            ipv6Address='2001:4860:4864:1:df7c:6a7a:d107:ab9d',
            kind='sql#instance',
            maxDiskSize=268435456000,
            project=self.Project(),
            region='us-central',
            serverCaCert=self.messages.SslCert(
                cert='-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBg',
                certSerialNumber='0',
                commonName='C=US,O=Google\\, Inc,CN=Google Cloud SQL Server C',
                createTime=create_time,
                expirationTime=expiration_time,
                instance='clone-instance-7a',
                kind='sql#sslCert',
                sha1Fingerprint='2dbfcefd3c962a284035ffb06dccdd2055d32b46',
            ),
            settings=self.messages.Settings(
                activationPolicy=self.messages.Settings
                .ActivationPolicyValueValuesEnum.ON_DEMAND,
                authorizedGaeApplications=[],
                backupConfiguration=self.messages.BackupConfiguration(
                    binaryLogEnabled=True,
                    enabled=True,
                    kind='sql#backupConfiguration',
                    startTime='23:00'),
                databaseFlags=[],
                ipConfiguration=self.messages.IpConfiguration(
                    authorizedNetworks=[],
                    ipv4Enabled=False,
                    requireSsl=None,
                ),
                kind='sql#settings',
                locationPreference=None,
                pricingPlan=self.messages.Settings.PricingPlanValueValuesEnum
                .PER_USE,
                replicationType=self.messages.Settings
                .ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                settingsVersion=3,
                tier='D1',
            ),
            state=self.messages.DatabaseInstance.StateValueValuesEnum.RUNNABLE,
            instanceType=self.messages.DatabaseInstance
            .InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
        ))

    self.Run('sql instances clone clone-instance-7 clone-instance-7a')
    # pylint:disable=line-too-long
    self.AssertOutputContains(
        """\
NAME               DATABASE_VERSION  LOCATION    TIER  PRIMARY_ADDRESS PRIVATE_ADDRESS  STATUS
clone-instance-7a  MYSQL_5_5         us-central  D1    -               -                RUNNABLE
""",
        normalize_space=True)

    # Ensure that the CMEK message doesn't show up by default.
    self.AssertErrNotContains(
        'Your clone will be encrypted with the source instance\'s '
        'customer-managed encryption key. If anyone destroys this key, all '
        'data encrypted with it will be permanently lost.')
Exemplo n.º 22
0
    def testOperationsDescribe(self):
        # pylint: disable=line-too-long
        self.mocked_client.operations.Get.Expect(
            self.messages.SqlOperationsGetRequest(
                operation='1cb8a924-898d-41ec-b695-39a6dc018d16',
                project=self.Project(),
            ),
            self.messages.Operation(
                insertTime=datetime.datetime(
                    2014,
                    7,
                    10,
                    17,
                    23,
                    12,
                    672000,
                    tzinfo=protorpc_util.TimeZoneOffset(
                        datetime.timedelta(0))).isoformat(),
                startTime=datetime.datetime(
                    2014,
                    7,
                    10,
                    17,
                    23,
                    13,
                    672000,
                    tzinfo=protorpc_util.TimeZoneOffset(
                        datetime.timedelta(0))).isoformat(),
                endTime=datetime.datetime(
                    2014,
                    7,
                    10,
                    17,
                    23,
                    16,
                    342000,
                    tzinfo=protorpc_util.TimeZoneOffset(
                        datetime.timedelta(0))).isoformat(),
                error=None,
                exportContext=None,
                importContext=None,
                targetId='integration-test',
                targetLink=
                'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/integration-test'
                .format(self.Project()),
                targetProject=self.Project(),
                kind='sql#operation',
                name='1cb8a924-898d-41ec-b695-39a6dc018d16',
                selfLink=
                'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/1cb8a924-898d-41ec-b695-39a6dc018d16'
                .format(self.Project()),
                operationType=self.messages.Operation.
                OperationTypeValueValuesEnum.CREATE_USER,
                status=self.messages.Operation.StatusValueValuesEnum.DONE,
                user='******',
            ))

        self.Run(
            'sql operations describe 1cb8a924-898d-41ec-b695-39a6dc018d16')
        # pylint: disable=line-too-long
        self.AssertOutputContains("""\
endTime: '2014-07-10T17:23:16.342000+00:00'
insertTime: '2014-07-10T17:23:12.672000+00:00'
kind: sql#operation
name: 1cb8a924-898d-41ec-b695-39a6dc018d16
operationType: CREATE_USER
selfLink: https://sqladmin.googleapis.com/sql/v1beta4/projects/fake-project/operations/1cb8a924-898d-41ec-b695-39a6dc018d16
startTime: '2014-07-10T17:23:13.672000+00:00'
status: DONE
targetId: integration-test
targetLink: https://sqladmin.googleapis.com/sql/v1beta4/projects/fake-project/instances/integration-test
targetProject: fake-project
user: [email protected]
""",
                                  normalize_space=True)
Exemplo n.º 23
0
    def testCreateCert(self):
        instance_name = 'integration-test'

        self.mocked_client.instances.AddServerCa.Expect(
            self.messages.SqlInstancesAddServerCaRequest(
                instance=instance_name,
                project=self.Project(),
            ),
            data.GetOperation(
                self.Project(),
                self.messages.DatabaseInstance(kind='sql#instance',
                                               name=instance_name),
                self.messages.Operation.OperationTypeValueValuesEnum.UPDATE,
                self.messages.Operation.StatusValueValuesEnum.PENDING))
        self.mocked_client.operations.Get.Expect(
            data.GetOperationGetRequest(self.Project()),
            data.GetOperation(
                self.Project(),
                self.messages.DatabaseInstance(kind='sql#instance',
                                               name=instance_name),
                self.messages.Operation.OperationTypeValueValuesEnum.UPDATE,
                self.messages.Operation.StatusValueValuesEnum.DONE))

        # The upcoming cert has fingerprint 'three'.
        active_cert_fingerprint = 'two'

        # The list endpoint is called to check the newly created cert.
        self.mocked_client.instances.ListServerCas.Expect(
            self.messages.SqlInstancesListServerCasRequest(
                instance=instance_name,
                project=self.Project(),
            ),
            self.messages.InstancesListServerCasResponse(
                activeVersion=active_cert_fingerprint,
                certs=[
                    data.GetSslCert(
                        instance_name, 'one',
                        datetime.datetime(
                            2024,
                            2,
                            2,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat()),
                    data.GetSslCert(
                        instance_name, 'two',
                        datetime.datetime(
                            2024,
                            4,
                            4,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat()),
                    data.GetSslCert(
                        instance_name, 'three',
                        datetime.datetime(
                            2024,
                            5,
                            5,
                            21,
                            10,
                            29,
                            402000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat())
                ],
                kind='sql#sslCertsList',
            ))
        self.Run('sql ssl server-ca-certs create --instance={}'.format(
            instance_name))
        self.AssertOutputContains("""\
SHA1_FINGERPRINT EXPIRATION
three            2024-05-05T21:10:29.402000+00:00
""",
                                  normalize_space=True)
Exemplo n.º 24
0
  def testBackupsDescribe(self):
    self.mocked_client.backupRuns.Get.Expect(
        self.messages.SqlBackupRunsGetRequest(
            project=self.Project(), instance='clone-instance-7', id=42),
        self.messages.BackupRun(
            id=42,
            windowStartTime=datetime.datetime(
                2014,
                8,
                13,
                23,
                0,
                0,
                802000,
                tzinfo=protorpc_util.TimeZoneOffset(
                    datetime.timedelta(0))).isoformat(),
            endTime=datetime.datetime(
                2014,
                8,
                14,
                0,
                27,
                47,
                910000,
                tzinfo=protorpc_util.TimeZoneOffset(
                    datetime.timedelta(0))).isoformat(),
            enqueuedTime=datetime.datetime(
                2014,
                8,
                14,
                0,
                25,
                12,
                318000,
                tzinfo=protorpc_util.TimeZoneOffset(
                    datetime.timedelta(0))).isoformat(),
            error=None,
            instance='clone-instance-7',
            kind='sql#backupRun',
            startTime=datetime.datetime(
                2014,
                8,
                14,
                0,
                25,
                12,
                321000,
                tzinfo=protorpc_util.TimeZoneOffset(
                    datetime.timedelta(0))).isoformat(),
            status=self.messages.BackupRun.StatusValueValuesEnum.SUCCESSFUL,
        ))

    self.Run('sql backups describe --instance=clone-instance-7 42')
    self.AssertOutputContains(
        """\
endTime: '2014-08-14T00:27:47.910000+00:00'
enqueuedTime: '2014-08-14T00:25:12.318000+00:00'
id: '42'
instance: clone-instance-7
kind: sql#backupRun
startTime: '2014-08-14T00:25:12.321000+00:00'
status: SUCCESSFUL
windowStartTime: '2014-08-13T23:00:00.802000+00:00'
""",
        normalize_space=True)
Exemplo n.º 25
0
 def _ExpectDelete(self):
     self.mocked_client.instances.Delete.Expect(
         self.messages.SqlInstancesDeleteRequest(
             instance='mock-instance',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 415000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=None,
             endTime=None,
             error=None,
             exportContext=None,
             importContext=None,
             targetId='mock-instance',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/mock-instance'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='56282116-8e0d-43d4-85d1-692b1f0cf044',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/56282116-8e0d-43d4-85d1-692b1f0cf044'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.DELETE,
             status=self.messages.Operation.StatusValueValuesEnum.DONE,
             user='******',
         ))
     self.mocked_client.operations.Get.Expect(
         self.messages.SqlOperationsGetRequest(
             operation='56282116-8e0d-43d4-85d1-692b1f0cf044',
             project=self.Project(),
         ),
         self.messages.Operation(
             # pylint:disable=line-too-long
             insertTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 415000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             startTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 38,
                 39,
                 525000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             endTime=datetime.datetime(
                 2014,
                 8,
                 12,
                 19,
                 39,
                 26,
                 601000,
                 tzinfo=protorpc_util.TimeZoneOffset(
                     datetime.timedelta(0))).isoformat(),
             error=None,
             exportContext=None,
             importContext=None,
             targetId='mock-instance',
             targetLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/mock-instance'
             .format(self.Project()),
             targetProject=self.Project(),
             kind='sql#operation',
             name='56282116-8e0d-43d4-85d1-692b1f0cf044',
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/56282116-8e0d-43d4-85d1-692b1f0cf044'
             .format(self.Project()),
             operationType=self.messages.Operation.
             OperationTypeValueValuesEnum.DELETE,
             status=self.messages.Operation.StatusValueValuesEnum.DONE,
             user='******',
         ))
Exemplo n.º 26
0
 def SetUp(self):
     self.mocked_client.instances.List.Expect(
         self.messages.SqlInstancesListRequest(
             pageToken=None,
             project=self.Project(),
             maxResults=100,
         ),
         self.messages.InstancesListResponse(
             items=[
                 self.messages.DatabaseInstance(
                     currentDiskSize=287571860,
                     databaseVersion=self.messages.DatabaseInstance.
                     DatabaseVersionValueValuesEnum.MYSQL_5_5,
                     etag=
                     '"yGhHGJDUk5hWK-gppo_8C-KD7iU/nbMj8WWUtdJPpSjOHUxEh"',
                     name='backupless-instance',
                     instanceType=self.messages.DatabaseInstance.
                     InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
                     ipAddresses=[],
                     ipv6Address='2001:4860:4864:1:df7c:6a7a:d107:ab9d',
                     kind='sql#instance',
                     masterInstanceName=None,
                     maxDiskSize=268435456000,
                     project=self.Project(),
                     region='us-central',
                     replicaNames=[],
                     serverCaCert=self.messages.SslCert(
                         cert=
                         '-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAg',
                         certSerialNumber='0',
                         commonName=
                         'C=US,O=Google\\, Inc,CN=Google Cloud SQL ',
                         createTime=datetime.datetime(
                             2014,
                             8,
                             11,
                             21,
                             47,
                             10,
                             788000,
                             tzinfo=protorpc_util.TimeZoneOffset(
                                 datetime.timedelta(0))).isoformat(),
                         expirationTime=datetime.datetime(
                             2024,
                             8,
                             8,
                             21,
                             47,
                             10,
                             788000,
                             tzinfo=protorpc_util.TimeZoneOffset(
                                 datetime.timedelta(0))).isoformat(),
                         instance='backupless-instance',
                         kind='sql#sslCert',
                         sha1Fingerprint=
                         'a691db45f7dee0827650fd2eb277d2ca81b9',
                     ),
                     settings=self.messages.Settings(
                         activationPolicy=self.messages.Settings.
                         ActivationPolicyValueValuesEnum.ON_DEMAND,
                         authorizedGaeApplications=[],
                         backupConfiguration=self.messages.
                         BackupConfiguration(
                             binaryLogEnabled=False,
                             enabled=False,
                             kind='sql#backupConfiguration',
                             startTime='00:00',
                         ),
                         databaseFlags=[],
                         databaseReplicationEnabled=None,
                         ipConfiguration=self.messages.IpConfiguration(
                             authorizedNetworks=[],
                             ipv4Enabled=False,
                             requireSsl=False,
                         ),
                         kind='sql#settings',
                         locationPreference=self.messages.
                         LocationPreference(
                             followGaeApplication=None,
                             kind='sql#locationPreference',
                             zone=None,
                         ),
                         pricingPlan=self.messages.Settings.
                         PricingPlanValueValuesEnum.PER_USE,
                         replicationType=self.messages.Settings.
                         ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                         settingsVersion=1,
                         tier='db-n1-standard-1',
                     ),
                     state=self.messages.DatabaseInstance.
                     StateValueValuesEnum.RUNNABLE,
                 ),
             ],
             kind='sql#instancesList',
             nextPageToken=None,
         ))
Exemplo n.º 27
0
 def testTimeZoneOffsetDelta(self):
     """Test that delta works with TimeZoneOffset."""
     time_zone = util.TimeZoneOffset(datetime.timedelta(minutes=3))
     epoch = time_zone.utcoffset(datetime.datetime.utcfromtimestamp(0))
     self.assertEqual(180, util.total_seconds(epoch))
Exemplo n.º 28
0
    def MockIPWhitelisting(self, error=False):
        # Mock the connection time.
        self.StartPatch('googlecloudsdk.api_lib.sql.network.GetCurrentTime',
                        return_value=self.time_of_connection)

        # Mock GET and PATCH endpoints
        self.ExpectInstanceGet()
        patch_request = self.messages.SqlInstancesPatchRequest(
            databaseInstance=self.messages.DatabaseInstance(
                # pylint:disable=line-too-long
                backendType=self.instance['backendType'],
                connectionName='{0}:us-central1:{1}'.format(
                    self.Project(), self.instance['id']),
                currentDiskSize=None,
                databaseVersion=self.instance['databaseVersion'],
                etag='"DlgRosmIegBpXj_rR5uyhdXAbP8/MQ"',
                failoverReplica=None,
                instanceType=self.messages.DatabaseInstance.
                InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
                ipAddresses=[
                    self.messages.IpMapping(
                        ipAddress='104.154.166.249',
                        timeToRetire=None,
                        type=self.messages.IpMapping.TypeValueValuesEnum.
                        PRIMARY,
                    ),
                ],
                ipv6Address=None,
                kind='sql#instance',
                masterInstanceName=None,
                maxDiskSize=None,
                name=self.instance['id'],
                onPremisesConfiguration=None,
                project=self.Project(),
                region='us-central1',
                replicaConfiguration=None,
                replicaNames=[],
                selfLink=
                'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/{1}'
                .format(self.Project(), self.instance['id']),
                serverCaCert=None,
                serviceAccountEmailAddress=
                '*****@*****.**',
                settings=self.messages.Settings(
                    activationPolicy=self.messages.Settings.
                    ActivationPolicyValueValuesEnum.ALWAYS,
                    authorizedGaeApplications=[],
                    availabilityType=None,
                    backupConfiguration=self.messages.BackupConfiguration(
                        binaryLogEnabled=None,
                        enabled=False,
                        kind='sql#backupConfiguration',
                        startTime='10:00',
                    ),
                    crashSafeReplicationEnabled=None,
                    dataDiskSizeGb=10,
                    dataDiskType=self.messages.Settings.
                    DataDiskTypeValueValuesEnum.PD_SSD,
                    databaseFlags=[],
                    databaseReplicationEnabled=None,
                    ipConfiguration=self.messages.IpConfiguration(
                        authorizedNetworks=[
                            self.messages.AclEntry(
                                expirationTime=(
                                    self.time_of_connection +
                                    datetime.timedelta(minutes=5)).replace(
                                        microsecond=10000).isoformat(),
                                kind='sql#aclEntry',
                                name='sql connect at time {0}'.format(
                                    str(self.time_of_connection)),
                                value='CLIENT_IP',
                            ),
                        ],
                        ipv4Enabled=True,
                        requireSsl=None,
                    ),
                    kind='sql#settings',
                    locationPreference=None,
                    maintenanceWindow=None,
                    pricingPlan=self.messages.Settings.
                    PricingPlanValueValuesEnum.PER_USE,
                    replicationType=self.messages.Settings.
                    ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                    settingsVersion=1,
                    storageAutoResize=None,
                    storageAutoResizeLimit=None,
                    tier=self.instance['tier'],
                ),
                state=self.messages.DatabaseInstance.StateValueValuesEnum.
                RUNNABLE,
                suspensionReason=[],
            ),
            instance=self.instance['id'],
            project=self.Project(),
        )
        if error:
            self.mocked_client.instances.Patch.Expect(
                patch_request,
                exception=http_error.MakeHttpError(
                    code=400,
                    message='invalidInstanceProperty',
                    reason='Invalid instance property.',
                ))
        else:
            self.mocked_client.instances.Patch.Expect(
                patch_request,
                self.messages.Operation(
                    # pylint:disable=line-too-long
                    endTime=None,
                    error=None,
                    exportContext=None,
                    importContext=None,
                    insertTime=datetime.datetime(
                        2017,
                        5,
                        15,
                        23,
                        3,
                        50,
                        514000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat(),
                    kind='sql#operation',
                    name='8b7ffa62-e950-45c0-bdad-1d366ad8b964',
                    operationType=self.messages.Operation.
                    OperationTypeValueValuesEnum.UPDATE,
                    selfLink=
                    'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/8b7ffa62-e9'
                    .format(self.Project()),
                    startTime=None,
                    status=self.messages.Operation.StatusValueValuesEnum.
                    PENDING,
                    targetId=self.instance['id'],
                    targetLink=
                    'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/{1}'
                    .format(self.Project(), self.instance['id']),
                    targetProject=self.Project(),
                    user=
                    '******',
                ))
            self.mocked_client.operations.Get.Expect(
                self.messages.SqlOperationsGetRequest(
                    operation='8b7ffa62-e950-45c0-bdad-1d366ad8b964',
                    project=self.Project(),
                ),
                self.messages.Operation(
                    # pylint:disable=line-too-long
                    endTime=datetime.datetime(
                        2017,
                        5,
                        15,
                        23,
                        5,
                        4,
                        809000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat(),
                    error=None,
                    exportContext=None,
                    importContext=None,
                    insertTime=datetime.datetime(
                        2017,
                        5,
                        15,
                        23,
                        3,
                        50,
                        514000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat(),
                    kind='sql#operation',
                    name='8b7ffa62-e950-45c0-bdad-1d366ad8b964',
                    operationType=self.messages.Operation.
                    OperationTypeValueValuesEnum.UPDATE,
                    selfLink=
                    'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/8b7ffa62-e9'
                    .format(self.Project()),
                    startTime=datetime.datetime(
                        2017,
                        5,
                        15,
                        23,
                        3,
                        50,
                        707000,
                        tzinfo=protorpc_util.TimeZoneOffset(
                            datetime.timedelta(0))).isoformat(),
                    status=self.messages.Operation.StatusValueValuesEnum.DONE,
                    targetId=self.instance['id'],
                    targetLink=
                    'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/{1}'
                    .format(self.Project(), self.instance['id']),
                    targetProject=self.Project(),
                    user=
                    '******',
                ))
            self.mocked_client.instances.Get.Expect(
                self.messages.SqlInstancesGetRequest(
                    instance=self.instance['id'],
                    project=self.Project(),
                ),
                self.messages.DatabaseInstance(
                    # pylint:disable=line-too-long
                    backendType=self.instance['backendType'],
                    connectionName='{0}:us-central1:{1}'.format(
                        self.Project(), self.instance['id']),
                    currentDiskSize=None,
                    databaseVersion=self.instance['databaseVersion'],
                    etag='"DlgRosmIegBpXj_rR5uyhdXAbP8/Mw"',
                    failoverReplica=None,
                    instanceType=self.messages.DatabaseInstance.
                    InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
                    ipAddresses=[
                        self.messages.IpMapping(
                            ipAddress='104.154.166.249',
                            timeToRetire=None,
                            type=self.messages.IpMapping.TypeValueValuesEnum.
                            PRIMARY,
                        ),
                    ],
                    ipv6Address=None,
                    kind='sql#instance',
                    masterInstanceName=None,
                    maxDiskSize=None,
                    name=self.instance['id'],
                    onPremisesConfiguration=None,
                    project=self.Project(),
                    region='us-central1',
                    replicaConfiguration=None,
                    replicaNames=[],
                    selfLink=
                    'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/{1}'
                    .format(self.Project(), self.instance['id']),
                    serverCaCert=self.messages.SslCert(
                        cert=
                        '-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBgkqhkiG9w0BAQUFADBIMSMwIQYDVQQDExpHb29n\nbGUgQ2x',
                        certSerialNumber='0',
                        commonName=
                        'C=US,O=Google\\, Inc,CN=Google Cloud SQL Server CA',
                        createTime=datetime.datetime(
                            2017,
                            5,
                            12,
                            21,
                            33,
                            4,
                            844000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        expirationTime=datetime.datetime(
                            2019,
                            5,
                            12,
                            21,
                            34,
                            4,
                            844000,
                            tzinfo=protorpc_util.TimeZoneOffset(
                                datetime.timedelta(0))).isoformat(),
                        instance=self.instance['id'],
                        kind='sql#sslCert',
                        selfLink=None,
                        sha1Fingerprint=
                        'fcddb49c4a00ff8796ba099933dbeb208b8599bd',
                    ),
                    serviceAccountEmailAddress=
                    '*****@*****.**',
                    settings=self.messages.Settings(
                        activationPolicy=self.messages.Settings.
                        ActivationPolicyValueValuesEnum.ALWAYS,
                        authorizedGaeApplications=[],
                        availabilityType=None,
                        backupConfiguration=self.messages.BackupConfiguration(
                            binaryLogEnabled=None,
                            enabled=False,
                            kind='sql#backupConfiguration',
                            startTime='10:00',
                        ),
                        crashSafeReplicationEnabled=None,
                        dataDiskSizeGb=10,
                        dataDiskType=self.messages.Settings.
                        DataDiskTypeValueValuesEnum.PD_SSD,
                        databaseFlags=[],
                        databaseReplicationEnabled=None,
                        ipConfiguration=self.messages.IpConfiguration(
                            authorizedNetworks=[
                                self.messages.AclEntry(
                                    expirationTime=(
                                        self.time_of_connection +
                                        datetime.timedelta(minutes=5)
                                    ).isoformat(),
                                    kind='sql#aclEntry',
                                    name='sql connect at time {0}'.format(
                                        str(self.time_of_connection)),
                                    value='192.0.0.1',
                                ),
                            ],
                            ipv4Enabled=True,
                            requireSsl=None,
                        ),
                        kind='sql#settings',
                        locationPreference=None,
                        maintenanceWindow=None,
                        pricingPlan=self.messages.Settings.
                        PricingPlanValueValuesEnum.PER_USE,
                        replicationType=self.messages.Settings.
                        ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                        settingsVersion=3,
                        storageAutoResize=True,
                        storageAutoResizeLimit=0,
                        tier=self.instance['tier'],
                    ),
                    state=self.messages.DatabaseInstance.StateValueValuesEnum.
                    RUNNABLE,
                    suspensionReason=[],
                ))
Exemplo n.º 29
0
class _BaseInstancesCloneTest(object):
  """The base instance clone test class."""
  # pylint:disable=g-tzinfo-datetime
  _DEFAULT_INSERT_TIME = datetime.datetime(
      2014,
      8,
      7,
      15,
      0,
      1,
      81000,
      tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
  _DEFAULT_START_TIME = datetime.datetime(
      2014,
      8,
      7,
      15,
      0,
      1,
      142000,
      tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
  _DEFAULT_END_TIME = datetime.datetime(
      2014,
      8,
      7,
      15,
      0,
      1,
      142000,
      tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
  messages = core_apis.GetMessagesModule('sql', 'v1beta4')

  def testSimpleClone(self):
    self.ExpectInstanceGet(self.GetV2Instance('clone-instance-7'))
    self.mocked_client.instances.Clone.Expect(
        self.messages.SqlInstancesCloneRequest(
            instancesCloneRequest=self.messages.InstancesCloneRequest(
                cloneContext=self.messages.CloneContext(
                    binLogCoordinates=None,
                    destinationInstanceName='clone-instance-7a',
                    kind='sql#cloneContext',
                ),),
            instance='clone-instance-7',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    create_time = datetime.datetime(
        2014,
        8,
        13,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    expiration_time = datetime.datetime(
        2024,
        8,
        10,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    self.mocked_client.instances.Get.Expect(
        self.messages.SqlInstancesGetRequest(
            instance='clone-instance-7a',
            project=self.Project(),
        ),
        self.messages.DatabaseInstance(
            currentDiskSize=287592789,
            databaseVersion=self.messages.DatabaseInstance
            .DatabaseVersionValueValuesEnum.MYSQL_5_5,
            etag='"DExdZ69FktjWMJ-ohD1vLZW9pnk/Mw"',
            name='clone-instance-7a',
            ipAddresses=[],
            ipv6Address='2001:4860:4864:1:df7c:6a7a:d107:ab9d',
            kind='sql#instance',
            maxDiskSize=268435456000,
            project=self.Project(),
            region='us-central',
            serverCaCert=self.messages.SslCert(
                cert='-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBg',
                certSerialNumber='0',
                commonName='C=US,O=Google\\, Inc,CN=Google Cloud SQL Server C',
                createTime=create_time,
                expirationTime=expiration_time,
                instance='clone-instance-7a',
                kind='sql#sslCert',
                sha1Fingerprint='2dbfcefd3c962a284035ffb06dccdd2055d32b46',
            ),
            settings=self.messages.Settings(
                activationPolicy=self.messages.Settings
                .ActivationPolicyValueValuesEnum.ON_DEMAND,
                authorizedGaeApplications=[],
                backupConfiguration=self.messages.BackupConfiguration(
                    binaryLogEnabled=True,
                    enabled=True,
                    kind='sql#backupConfiguration',
                    startTime='23:00'),
                databaseFlags=[],
                ipConfiguration=self.messages.IpConfiguration(
                    authorizedNetworks=[],
                    ipv4Enabled=False,
                    requireSsl=None,
                ),
                kind='sql#settings',
                locationPreference=None,
                pricingPlan=self.messages.Settings.PricingPlanValueValuesEnum
                .PER_USE,
                replicationType=self.messages.Settings
                .ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                settingsVersion=3,
                tier='D1',
            ),
            state=self.messages.DatabaseInstance.StateValueValuesEnum.RUNNABLE,
            instanceType=self.messages.DatabaseInstance
            .InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
        ))

    self.Run('sql instances clone clone-instance-7 clone-instance-7a')
    # pylint:disable=line-too-long
    self.AssertOutputContains(
        """\
NAME               DATABASE_VERSION  LOCATION    TIER  PRIMARY_ADDRESS PRIVATE_ADDRESS  STATUS
clone-instance-7a  MYSQL_5_5         us-central  D1    -               -                RUNNABLE
""",
        normalize_space=True)

    # Ensure that the CMEK message doesn't show up by default.
    self.AssertErrNotContains(
        'Your clone will be encrypted with the source instance\'s '
        'customer-managed encryption key. If anyone destroys this key, all '
        'data encrypted with it will be permanently lost.')

  def testSimpleAsyncClone(self):
    self.ExpectInstanceGet(self.GetV2Instance('clone-instance-7'))
    self.mocked_client.instances.Clone.Expect(
        self.messages.SqlInstancesCloneRequest(
            instancesCloneRequest=self.messages.InstancesCloneRequest(
                cloneContext=self.messages.CloneContext(
                    binLogCoordinates=None,
                    destinationInstanceName='clone-instance-7a',
                    kind='sql#cloneContext',
                ),),
            instance='clone-instance-7',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55cc250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55cc250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55cc250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55cc250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55cc250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    self.Run('sql instances clone clone-instance-7 clone-instance-7a --async')
    self.AssertOutputEquals("""\
endTime: '2014-08-07T15:00:01.142000+00:00'
insertTime: '2014-08-07T15:00:01.081000+00:00'
kind: sql#operation
name: d930826e-80a5-4477-8218-fb7fb55cc250
operationType: CLONE
selfLink: https://sqladmin.googleapis.com/sql/v1beta4/projects/fake-project/operations/d930826e-80a5-4477-8218-fb7fb55cc250
startTime: '2014-08-07T15:00:01.142000+00:00'
status: DONE
targetId: clone-instance-7a
targetLink: https://sqladmin.googleapis.com/sql/v1beta4/projects/fake-project/instances/clone-instance-7a
targetProject: fake-project
user: [email protected]
""")

  def testSimpleCloneV1(self):
    self.ExpectInstanceGet(self.GetV1Instance('clone-instance-7'))
    with self.AssertRaisesExceptionRegexp(
        exceptions.ArgumentError,
        r'First Generation instances can no longer be created\.'):
      self.Run('sql instances clone clone-instance-7 clone-instance-7a')

  def testMySQLCloneBinLogFromCmekInstance(self):
    diff = {
        'name':
            'clone-instance-7',
        'diskEncryptionConfiguration':
            self.messages.DiskEncryptionConfiguration(
                kind='sql#diskEncryptionConfiguration',
                kmsKeyName='some-kms-key')
    }
    self.ExpectInstanceGet(self.GetV2Instance(), diff)
    self.mocked_client.instances.Clone.Expect(
        self.messages.SqlInstancesCloneRequest(
            instancesCloneRequest=self.messages.InstancesCloneRequest(
                cloneContext=self.messages.CloneContext(
                    binLogCoordinates=self.messages.BinLogCoordinates(
                        binLogFileName='bin.log', binLogPosition=1111),
                    destinationInstanceName='clone-instance-7a',
                    kind='sql#cloneContext',
                ),),
            instance='clone-instance-7',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    create_time = datetime.datetime(
        2014,
        8,
        13,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    expiration_time = datetime.datetime(
        2024,
        8,
        10,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    self.mocked_client.instances.Get.Expect(
        self.messages.SqlInstancesGetRequest(
            instance='clone-instance-7a',
            project=self.Project(),
        ),
        self.messages.DatabaseInstance(
            currentDiskSize=287592789,
            databaseVersion=self.messages.DatabaseInstance
            .DatabaseVersionValueValuesEnum.MYSQL_5_5,
            etag='"DExdZ69FktjWMJ-ohD1vLZW9pnk/Mw"',
            name='clone-instance-7a',
            ipAddresses=[],
            ipv6Address='2001:4860:4864:1:df7c:6a7a:d107:ab9d',
            kind='sql#instance',
            maxDiskSize=268435456000,
            project=self.Project(),
            region='us-central',
            serverCaCert=self.messages.SslCert(
                cert='-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBg',
                certSerialNumber='0',
                commonName='C=US,O=Google\\, Inc,CN=Google Cloud SQL Server C',
                createTime=create_time,
                expirationTime=expiration_time,
                instance='clone-instance-7a',
                kind='sql#sslCert',
                sha1Fingerprint='2dbfcefd3c962a284035ffb06dccdd2055d32b46',
            ),
            settings=self.messages.Settings(
                activationPolicy=self.messages.Settings
                .ActivationPolicyValueValuesEnum.ON_DEMAND,
                authorizedGaeApplications=[],
                backupConfiguration=self.messages.BackupConfiguration(
                    binaryLogEnabled=True,
                    enabled=True,
                    kind='sql#backupConfiguration',
                    startTime='23:00'),
                databaseFlags=[],
                ipConfiguration=self.messages.IpConfiguration(
                    authorizedNetworks=[],
                    ipv4Enabled=False,
                    requireSsl=None,
                ),
                kind='sql#settings',
                locationPreference=None,
                pricingPlan=self.messages.Settings.PricingPlanValueValuesEnum
                .PER_USE,
                replicationType=self.messages.Settings
                .ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                settingsVersion=3,
                tier='D1',
            ),
            state=self.messages.DatabaseInstance.StateValueValuesEnum.RUNNABLE,
            instanceType=self.messages.DatabaseInstance
            .InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
        ))

    self.Run('sql instances clone clone-instance-7 clone-instance-7a '
             '--bin-log-file-name bin.log --bin-log-position 1111')
    # pylint:disable=line-too-long
    self.AssertOutputContains(
        """\
NAME               DATABASE_VERSION  LOCATION    TIER  PRIMARY_ADDRESS PRIVATE_ADDRESS STATUS
clone-instance-7a  MYSQL_5_5         us-central  D1    -               -               RUNNABLE
""",
        normalize_space=True)
    # Ensure that the CMEK message is showing up.
    self.AssertErrContains(
        'Your clone will be encrypted with the source instance\'s '
        'customer-managed encryption key. If anyone destroys this key, all '
        'data encrypted with it will be permanently lost.')

  def testCloneBinLogMissingPosition(self):
    with self.assertRaisesRegex(
        cli_test_base.MockArgumentError,
        'argument --bin-log-position: Must be specified.'):
      self.Run("""
               sql instances clone
               --bin-log-file-name mysql-bin.000006
               clone-instance-7 clone-instance-7a
               """)

  def testCloneBinLogMissingFilename(self):
    with self.assertRaisesRegex(
        cli_test_base.MockArgumentError,
        'argument --bin-log-file-name: Must be specified.'):
      self.Run("""
               sql instances clone
               --bin-log-position 1111
               clone-instance-7 clone-instance-7a
               """)

  def testPostgresCloneTimeFromCmekInstance(self):
    diff = {
        'name':
            'clone-instance-7',
        'diskEncryptionConfiguration':
            self.messages.DiskEncryptionConfiguration(
                kind='sql#diskEncryptionConfiguration',
                kmsKeyName='some-kms-key')
    }
    self.ExpectInstanceGet(self.GetV2Instance(), diff)
    self.mocked_client.instances.Clone.Expect(
        self.messages.SqlInstancesCloneRequest(
            instancesCloneRequest=self.messages.InstancesCloneRequest(
                cloneContext=self.messages.CloneContext(
                    pointInTime='2020-01-22T19:12:11.460000Z',
                    destinationInstanceName='clone-instance-7a',
                    kind='sql#cloneContext',
                ),),
            instance='clone-instance-7',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.RUNNING,
            user='******',
        ))

    self.mocked_client.operations.Get.Expect(
        self.messages.SqlOperationsGetRequest(
            operation='d930826e-80a5-4477-8218-fb7fb55aa250',
            project=self.Project(),
        ),
        self.messages.Operation(
            # pylint:disable=line-too-long
            insertTime=self._DEFAULT_INSERT_TIME,
            startTime=self._DEFAULT_START_TIME,
            endTime=self._DEFAULT_END_TIME,
            error=None,
            exportContext=None,
            importContext=None,
            targetId='clone-instance-7a',
            targetLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/clone-instance-7a'
            .format(self.Project()),
            targetProject=self.Project(),
            kind='sql#operation',
            name='d930826e-80a5-4477-8218-fb7fb55aa250',
            selfLink='https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/operations/d930826e-80a5-4477-8218-fb7fb55aa250'
            .format(self.Project()),
            operationType=self.messages.Operation.OperationTypeValueValuesEnum
            .CLONE,
            status=self.messages.Operation.StatusValueValuesEnum.DONE,
            user='******',
        ))

    create_time = datetime.datetime(
        2014,
        8,
        13,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    expiration_time = datetime.datetime(
        2024,
        8,
        10,
        21,
        47,
        29,
        512000,
        tzinfo=protorpc_util.TimeZoneOffset(datetime.timedelta(0))).isoformat()
    self.mocked_client.instances.Get.Expect(
        self.messages.SqlInstancesGetRequest(
            instance='clone-instance-7a',
            project=self.Project(),
        ),
        self.messages.DatabaseInstance(
            currentDiskSize=287592789,
            databaseVersion=self.messages.DatabaseInstance
            .DatabaseVersionValueValuesEnum.POSTGRES_9_6,
            etag='"DExdZ69FktjWMJ-ohD1vLZW9pnk/Mw"',
            name='clone-instance-7a',
            ipAddresses=[],
            ipv6Address='2001:4860:4864:1:df7c:6a7a:d107:ab9d',
            kind='sql#instance',
            maxDiskSize=268435456000,
            project=self.Project(),
            region='us-central',
            serverCaCert=self.messages.SslCert(
                cert='-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBg',
                certSerialNumber='0',
                commonName='C=US,O=Google\\, Inc,CN=Google Cloud SQL Server C',
                createTime=create_time,
                expirationTime=expiration_time,
                instance='clone-instance-7a',
                kind='sql#sslCert',
                sha1Fingerprint='2dbfcefd3c962a284035ffb06dccdd2055d32b46',
            ),
            settings=self.messages.Settings(
                activationPolicy=self.messages.Settings
                .ActivationPolicyValueValuesEnum.ON_DEMAND,
                authorizedGaeApplications=[],
                backupConfiguration=self.messages.BackupConfiguration(
                    pointInTimeRecoveryEnabled=True,
                    enabled=True,
                    kind='sql#backupConfiguration',
                    startTime='23:00'),
                databaseFlags=[],
                ipConfiguration=self.messages.IpConfiguration(
                    authorizedNetworks=[],
                    ipv4Enabled=False,
                    requireSsl=None,
                ),
                kind='sql#settings',
                locationPreference=None,
                pricingPlan=self.messages.Settings.PricingPlanValueValuesEnum
                .PER_USE,
                replicationType=self.messages.Settings
                .ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                settingsVersion=3,
                tier='D1',
            ),
            state=self.messages.DatabaseInstance.StateValueValuesEnum.RUNNABLE,
            instanceType=self.messages.DatabaseInstance
            .InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
        ))

    self.Run('sql instances clone clone-instance-7 clone-instance-7a '
             '--point-in-time 2020-01-22T19:12:11.460Z')
    # pylint:disable=line-too-long
    self.AssertOutputContains(
        """\
NAME               DATABASE_VERSION  LOCATION    TIER  PRIMARY_ADDRESS PRIVATE_ADDRESS STATUS
clone-instance-7a  POSTGRES_9_6         us-central  D1    -               -               RUNNABLE
""",
        normalize_space=True)
    # Ensure that the CMEK message is showing up.
    self.AssertErrContains(
        'Your clone will be encrypted with the source instance\'s '
        'customer-managed encryption key. If anyone destroys this key, all '
        'data encrypted with it will be permanently lost.')

  def testPointInTimeInvalidFormat(self):
    with self.AssertRaisesArgumentErrorRegexp(
        r'argument --point-in-time: Failed to parse date/time'):
      self.Run("""
               sql instances clone clone-instance-7 clone-instance-7a
               --point-in-time 123-abc
               """)

  def testPointInTimeAndBinLogInvalid(self):
    with self.assertRaisesRegex(
        cli_test_base.MockArgumentError,
        r'argument --point-in-time: At most one of --point-in-time | '
        r'--bin-log-file-name --bin-log-position may be specified'):
      self.Run("""
               sql instances clone clone-instance-7 clone-instance-7a
               --point-in-time 2020-01-22T19:12:11.460Z
               --bin-log-file-name mysql-bin.000007 --bin-log-position 1111
               """)
Exemplo n.º 30
0
 def ExpectInstanceGet(self):
     self.mocked_client.instances.Get.Expect(
         self.messages.SqlInstancesGetRequest(
             instance=self.instance['id'],
             project=self.Project(),
         ),
         self.messages.DatabaseInstance(
             # pylint:disable=line-too-long
             backendType=self.instance['backendType'],
             connectionName='{0}:us-central1:{1}'.format(
                 self.Project(), self.instance['id']),
             currentDiskSize=None,
             databaseVersion=self.instance['databaseVersion'],
             etag='"DlgRosmIegBpXj_rR5uyhdXAbP8/MQ"',
             failoverReplica=None,
             instanceType=self.messages.DatabaseInstance.
             InstanceTypeValueValuesEnum.CLOUD_SQL_INSTANCE,
             ipAddresses=[
                 self.messages.IpMapping(
                     ipAddress='104.154.166.249',
                     timeToRetire=None,
                     type=self.messages.IpMapping.TypeValueValuesEnum.
                     PRIMARY,
                 ),
             ],
             ipv6Address=None,
             kind='sql#instance',
             masterInstanceName=None,
             maxDiskSize=None,
             name=self.instance['id'],
             onPremisesConfiguration=None,
             project=self.Project(),
             region='us-central1',
             replicaConfiguration=None,
             replicaNames=[],
             selfLink=
             'https://sqladmin.googleapis.com/sql/v1beta4/projects/{0}/instances/{1}'
             .format(self.Project(), self.instance['id']),
             serverCaCert=self.messages.SslCert(
                 cert=
                 '-----BEGIN CERTIFICATE-----\nMIIDITCCAgmgAwIBAgIBADANBgkqhkiG9w0BAQUFADBIMSMwIQYDVQQDExpHb29n\nbGUgQ2x',
                 certSerialNumber='0',
                 commonName=
                 'C=US,O=Google\\, Inc,CN=Google Cloud SQL Server CA',
                 createTime=datetime.datetime(
                     2017,
                     5,
                     12,
                     21,
                     33,
                     4,
                     844000,
                     tzinfo=protorpc_util.TimeZoneOffset(
                         datetime.timedelta(0))).isoformat(),
                 expirationTime=datetime.datetime(
                     2019,
                     5,
                     12,
                     21,
                     34,
                     4,
                     844000,
                     tzinfo=protorpc_util.TimeZoneOffset(
                         datetime.timedelta(0))).isoformat(),
                 instance=self.instance['id'],
                 kind='sql#sslCert',
                 selfLink=None,
                 sha1Fingerprint='fcddb49c4a00ff8796ba099933dbeb208b8599bd',
             ),
             serviceAccountEmailAddress=
             '*****@*****.**',
             settings=self.messages.Settings(
                 activationPolicy=self.messages.Settings.
                 ActivationPolicyValueValuesEnum.ALWAYS,
                 authorizedGaeApplications=[],
                 availabilityType=None,
                 backupConfiguration=self.messages.BackupConfiguration(
                     binaryLogEnabled=None,
                     enabled=False,
                     kind='sql#backupConfiguration',
                     startTime='10:00',
                 ),
                 crashSafeReplicationEnabled=None,
                 dataDiskSizeGb=10,
                 dataDiskType=self.messages.Settings.
                 DataDiskTypeValueValuesEnum.PD_SSD,
                 databaseFlags=[],
                 databaseReplicationEnabled=None,
                 ipConfiguration=self.messages.IpConfiguration(
                     authorizedNetworks=[],
                     ipv4Enabled=True,
                     requireSsl=None,
                 ),
                 kind='sql#settings',
                 locationPreference=None,
                 maintenanceWindow=None,
                 pricingPlan=self.messages.Settings.
                 PricingPlanValueValuesEnum.PER_USE,
                 replicationType=self.messages.Settings.
                 ReplicationTypeValueValuesEnum.SYNCHRONOUS,
                 settingsVersion=1,
                 storageAutoResize=None,
                 storageAutoResizeLimit=None,
                 tier=self.instance['tier'],
             ),
             state=self.messages.DatabaseInstance.StateValueValuesEnum.
             RUNNABLE,
             suspensionReason=[],
         ))