Example #1
0
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs patch settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.on_premises_host_port:
            if args.require_ssl:
                raise exceptions.ToolException(
                    'Argument --on-premises-host-port not '
                    'allowed with --require_ssl')
            settings.onPremisesConfiguration = sql_messages.OnPremisesConfiguration(
                hostPort=args.on_premises_host_port)

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup=args.backup,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.storage_type:
            settings.dataDiskType = STORAGE_TYPE_PREFIX + args.storage_type

        # BETA args.
        if release_track == base.ReleaseTrack.BETA:
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         labels=args.labels)
            if labels:
                settings.userLabels = labels

            # Check that availability type is only specified if this is Postgres.
            if (args.IsSpecified('availability_type') and
                    not api_util.InstancesV1Beta4.IsPostgresDatabaseVersion(
                        args.database_version)):
                raise exceptions.InvalidArgumentException(
                    '--availability-type',
                    'Cannot set [--availability-type] on a '
                    'non-Postgres instance.')

        return settings
Example #2
0
    def _ConstructPatchSettingsFromArgs(cls,
                                        sql_messages,
                                        args,
                                        instance,
                                        release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.clear_gae_apps:
            settings.authorizedGaeApplications = []

        if any([args.follow_gae_app, args.gce_zone]):
            settings.locationPreference = sql_messages.LocationPreference(
                followGaeApplication=args.follow_gae_app, zone=args.gce_zone)

        if args.clear_authorized_networks:
            if not settings.ipConfiguration:
                settings.ipConfiguration = sql_messages.IpConfiguration()
            settings.ipConfiguration.authorizedNetworks = []

        if args.enable_database_replication is not None:
            settings.databaseReplicationEnabled = args.enable_database_replication

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            no_backup=args.no_backup,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags,
            clear_database_flags=args.clear_database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        # BETA args.
        if release_track == base.ReleaseTrack.BETA:
            labels_diff = labels_util.ExplicitNullificationDiff.FromUpdateArgs(
                args)
            labels_update = labels_diff.Apply(
                sql_messages.Settings.UserLabelsValue,
                instance.settings.userLabels)
            if labels_update.needs_update:
                settings.userLabels = labels_update.labels

        return settings
Example #3
0
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs patch settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.on_premises_host_port:
            if args.require_ssl:
                raise exceptions.ToolException(
                    'Argument --on-premises-host-port not '
                    'allowed with --require_ssl')
            settings.onPremisesConfiguration = sql_messages.OnPremisesConfiguration(
                hostPort=args.on_premises_host_port)

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup=args.backup,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.storage_type:
            settings.dataDiskType = STORAGE_TYPE_PREFIX + args.storage_type

        # BETA args.
        if release_track == base.ReleaseTrack.BETA:
            labels = reducers.UserLabels(sql_messages,
                                         instance,
                                         labels=args.labels)
            if labels:
                settings.userLabels = labels

        return settings
Example #4
0
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup=args.backup,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.storage_type:
            settings.dataDiskType = STORAGE_TYPE_PREFIX + args.storage_type

        # Check that availability type is only specified if this is Postgres.
        if (args.IsSpecified('availability_type')
                and not api_util.InstancesV1Beta4.IsPostgresDatabaseVersion(
                    args.database_version)):
            raise exceptions.InvalidArgumentException(
                '--availability-type', 'Cannot set [--availability-type] on a '
                'non-Postgres instance.')

        # BETA args.
        if _IsBetaOrNewer(release_track):
            settings.userLabels = labels_util.ParseCreateArgs(
                args, sql_messages.Settings.UserLabelsValue)

        return settings
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)
        if _IsAlpha(release_track):
            enable_point_in_time_recovery = args.enable_point_in_time_recovery
        else:
            enable_point_in_time_recovery = None

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup=args.backup,
            backup_location=args.backup_location,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log,
            enable_point_in_time_recovery=enable_point_in_time_recovery))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.storage_type:
            settings.dataDiskType = _ParseStorageType(
                sql_messages, STORAGE_TYPE_PREFIX + args.storage_type)

        # BETA args.
        if _IsBetaOrNewer(release_track):
            settings.userLabels = labels_util.ParseCreateArgs(
                args, sql_messages.Settings.UserLabelsValue)

        return settings
    def testAddBackupConfigToSettings(self):
        settings = self.messages.Settings(
            activationPolicy=None,
            authorizedGaeApplications=[],
            backupConfiguration=None,
            databaseFlags=[],
            ipConfiguration=None,
            kind='sql#settings',
            locationPreference=None,
            pricingPlan=self.messages.Settings.PricingPlanValueValuesEnum.
            PER_USE,
            replicationType=self.messages.Settings.
            ReplicationTypeValueValuesEnum.SYNCHRONOUS,
            settingsVersion=None,
            tier='D1',
        )

        backup_configuration = (reducers_util.BackupConfiguration(
            self.messages, enable_bin_log=True))
        instances_util.InstancesV1Beta4.AddBackupConfigToSettings(
            settings, backup_configuration)

        self.assertEqual(settings.backupConfiguration, backup_configuration)
Example #7
0
    def _ConstructPatchSettingsFromArgs(cls,
                                        sql_messages,
                                        args,
                                        instance,
                                        release_track=DEFAULT_RELEASE_TRACK):
        """Constructs patch settings object from base settings and args."""
        original_settings = instance.settings
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.clear_gae_apps:
            settings.authorizedGaeApplications = []

        if any([args.follow_gae_app, _GetZone(args)]):
            settings.locationPreference = sql_messages.LocationPreference(
                kind='sql#locationPreference',
                followGaeApplication=args.follow_gae_app,
                zone=_GetZone(args))

        if args.clear_authorized_networks:
            if not settings.ipConfiguration:
                settings.ipConfiguration = sql_messages.IpConfiguration()
            settings.ipConfiguration.authorizedNetworks = []

        if args.enable_database_replication is not None:
            settings.databaseReplicationEnabled = args.enable_database_replication

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup_enabled=not args.no_backup,
            backup_location=args.backup_location,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log,
            enable_point_in_time_recovery=args.enable_point_in_time_recovery))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags,
            clear_database_flags=args.clear_database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.remove_deny_maintenance_period:
            settings.denyMaintenancePeriods = []

        if (args.deny_maintenance_period_start_date
                or args.deny_maintenance_period_end_date
                or args.deny_maintenance_period_time):
            settings.denyMaintenancePeriods = []
            settings.denyMaintenancePeriods.append(
                reducers.DenyMaintenancePeriod(
                    sql_messages,
                    instance,
                    deny_maintenance_period_start_date=args.
                    deny_maintenance_period_start_date,
                    deny_maintenance_period_end_date=args.
                    deny_maintenance_period_end_date,
                    deny_maintenance_period_time=args.
                    deny_maintenance_period_time))

        # BETA args.
        if _IsBetaOrNewer(release_track):
            labels_diff = labels_util.ExplicitNullificationDiff.FromUpdateArgs(
                args)
            labels_update = labels_diff.Apply(
                sql_messages.Settings.UserLabelsValue,
                instance.settings.userLabels)
            if labels_update.needs_update:
                settings.userLabels = labels_update.labels

        # ALPHA args.
        if _IsAlpha(release_track):
            if args.active_directory_domain is not None:
                settings.activeDirectoryConfig = (
                    reducers.ActiveDirectoryConfig(
                        sql_messages, args.active_directory_domain))

        return settings
Example #8
0
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup_enabled=args.backup,
            backup_location=args.backup_location,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log,
            enable_point_in_time_recovery=args.enable_point_in_time_recovery,
            retained_backups_count=args.retained_backups_count,
            retained_transaction_log_days=args.retained_transaction_log_days))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.deny_maintenance_period_start_date and args.deny_maintenance_period_end_date:
            settings.denyMaintenancePeriods = []
            settings.denyMaintenancePeriods.append(
                reducers.DenyMaintenancePeriod(
                    sql_messages,
                    instance,
                    deny_maintenance_period_start_date=args.
                    deny_maintenance_period_start_date,
                    deny_maintenance_period_end_date=args.
                    deny_maintenance_period_end_date,
                    deny_maintenance_period_time=args.
                    deny_maintenance_period_time))

        settings.insightsConfig = (reducers.InsightsConfig(
            sql_messages,
            insights_config_query_insights_enabled=args.
            insights_config_query_insights_enabled,
            insights_config_query_string_length=args.
            insights_config_query_string_length,
            insights_config_record_application_tags=args.
            insights_config_record_application_tags,
            insights_config_record_client_address=args.
            insights_config_record_client_address))

        if args.storage_type:
            settings.dataDiskType = _ParseStorageType(
                sql_messages, STORAGE_TYPE_PREFIX + args.storage_type)

        # BETA args.
        if _IsBetaOrNewer(release_track):
            settings.userLabels = labels_util.ParseCreateArgs(
                args, sql_messages.Settings.UserLabelsValue)

        # ALPHA args.
        if _IsAlpha(release_track):
            if args.active_directory_domain is not None:
                settings.activeDirectoryConfig = (
                    reducers.ActiveDirectoryConfig(
                        sql_messages, args.active_directory_domain))

        return settings
Example #9
0
    def _ConstructPatchSettingsFromArgs(cls,
                                        sql_messages,
                                        args,
                                        instance,
                                        release_track=DEFAULT_RELEASE_TRACK):
        """Constructs patch settings object from base settings and args."""
        original_settings = instance.settings
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        if args.clear_gae_apps:
            settings.authorizedGaeApplications = []

        if any([args.follow_gae_app, _GetZone(args), _GetSecondaryZone(args)]):
            settings.locationPreference = sql_messages.LocationPreference(
                kind='sql#locationPreference',
                followGaeApplication=args.follow_gae_app,
                zone=_GetZone(args),
                secondaryZone=_GetSecondaryZone(args))

        if args.clear_authorized_networks:
            if not settings.ipConfiguration:
                settings.ipConfiguration = sql_messages.IpConfiguration()
            settings.ipConfiguration.authorizedNetworks = []

        if args.enable_database_replication is not None:
            settings.databaseReplicationEnabled = args.enable_database_replication

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup_enabled=not args.no_backup,
            backup_location=args.backup_location,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log,
            enable_point_in_time_recovery=args.enable_point_in_time_recovery,
            retained_backups_count=args.retained_backups_count,
            retained_transaction_log_days=args.retained_transaction_log_days))

        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags,
            clear_database_flags=args.clear_database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.remove_deny_maintenance_period:
            settings.denyMaintenancePeriods = []

        if (args.deny_maintenance_period_start_date
                or args.deny_maintenance_period_end_date
                or args.deny_maintenance_period_time):
            settings.denyMaintenancePeriods = []
            settings.denyMaintenancePeriods.append(
                reducers.DenyMaintenancePeriod(
                    sql_messages,
                    instance,
                    deny_maintenance_period_start_date=args.
                    deny_maintenance_period_start_date,
                    deny_maintenance_period_end_date=args.
                    deny_maintenance_period_end_date,
                    deny_maintenance_period_time=args.
                    deny_maintenance_period_time))

        settings.insightsConfig = (reducers.InsightsConfig(
            sql_messages,
            insights_config_query_insights_enabled=args.
            insights_config_query_insights_enabled,
            insights_config_query_string_length=args.
            insights_config_query_string_length,
            insights_config_record_application_tags=args.
            insights_config_record_application_tags,
            insights_config_record_client_address=args.
            insights_config_record_client_address,
            insights_config_query_plans_per_minute=args.
            insights_config_query_plans_per_minute))

        if args.active_directory_domain is not None:
            settings.activeDirectoryConfig = (reducers.ActiveDirectoryConfig(
                sql_messages, args.active_directory_domain))

        settings.passwordValidationPolicy = (reducers.PasswordPolicy(
            sql_messages,
            password_policy_min_length=args.password_policy_min_length,
            password_policy_complexity=args.password_policy_complexity,
            password_policy_reuse_interval=args.password_policy_reuse_interval,
            password_policy_disallow_username_substring=args.
            password_policy_disallow_username_substring,
            password_policy_password_change_interval=args.
            password_policy_password_change_interval,
            enable_password_policy=args.enable_password_policy,
            clear_password_policy=args.clear_password_policy))

        # BETA args.
        if _IsBetaOrNewer(release_track):
            labels_diff = labels_util.ExplicitNullificationDiff.FromUpdateArgs(
                args)
            labels_update = labels_diff.Apply(
                sql_messages.Settings.UserLabelsValue,
                instance.settings.userLabels)
            if labels_update.needs_update:
                settings.userLabels = labels_update.labels
            # TODO(b/199412671): merge the logic of assigning ip range to
            # _ConstructBaseSettingsFromArgs
            if args.allocated_ip_range_name:
                if not settings.ipConfiguration:
                    settings.ipConfiguration = sql_messages.IpConfiguration()
                settings.ipConfiguration.allocatedIpRange = args.allocated_ip_range_name

        # ALPHA args.
        if _IsAlpha(release_track):
            settings.sqlServerAuditConfig = reducers.SqlServerAuditConfig(
                sql_messages,
                bucket=args.audit_bucket_path,
                retention_interval=args.audit_retention_interval,
                upload_interval=args.audit_upload_interval)

        return settings
Example #10
0
    def _ConstructCreateSettingsFromArgs(cls,
                                         sql_messages,
                                         args,
                                         instance=None,
                                         release_track=DEFAULT_RELEASE_TRACK):
        """Constructs create settings object from base settings and args."""
        original_settings = instance.settings if instance else None
        settings = cls._ConstructBaseSettingsFromArgs(sql_messages, args,
                                                      instance, release_track)

        backup_configuration = (reducers.BackupConfiguration(
            sql_messages,
            instance,
            backup_enabled=args.backup,
            backup_location=args.backup_location,
            backup_start_time=args.backup_start_time,
            enable_bin_log=args.enable_bin_log,
            enable_point_in_time_recovery=args.enable_point_in_time_recovery,
            retained_backups_count=args.retained_backups_count,
            retained_transaction_log_days=args.retained_transaction_log_days))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)

        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages,
            original_settings,
            database_flags=args.database_flags))

        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages,
            instance,
            maintenance_release_channel=args.maintenance_release_channel,
            maintenance_window_day=args.maintenance_window_day,
            maintenance_window_hour=args.maintenance_window_hour))

        if args.deny_maintenance_period_start_date and args.deny_maintenance_period_end_date:
            settings.denyMaintenancePeriods = []
            settings.denyMaintenancePeriods.append(
                reducers.DenyMaintenancePeriod(
                    sql_messages,
                    instance,
                    deny_maintenance_period_start_date=args.
                    deny_maintenance_period_start_date,
                    deny_maintenance_period_end_date=args.
                    deny_maintenance_period_end_date,
                    deny_maintenance_period_time=args.
                    deny_maintenance_period_time))

        settings.insightsConfig = (reducers.InsightsConfig(
            sql_messages,
            insights_config_query_insights_enabled=args.
            insights_config_query_insights_enabled,
            insights_config_query_string_length=args.
            insights_config_query_string_length,
            insights_config_record_application_tags=args.
            insights_config_record_application_tags,
            insights_config_record_client_address=args.
            insights_config_record_client_address,
            insights_config_query_plans_per_minute=args.
            insights_config_query_plans_per_minute))

        if args.storage_type:
            settings.dataDiskType = _ParseStorageType(
                sql_messages, STORAGE_TYPE_PREFIX + args.storage_type)

        if args.active_directory_domain is not None:
            settings.activeDirectoryConfig = (reducers.ActiveDirectoryConfig(
                sql_messages, args.active_directory_domain))

        settings.passwordValidationPolicy = (reducers.PasswordPolicy(
            sql_messages,
            password_policy_min_length=args.password_policy_min_length,
            password_policy_complexity=args.password_policy_complexity,
            password_policy_reuse_interval=args.password_policy_reuse_interval,
            password_policy_disallow_username_substring=args.
            password_policy_disallow_username_substring,
            password_policy_password_change_interval=args.
            password_policy_password_change_interval,
            enable_password_policy=args.enable_password_policy))

        # BETA args.
        if _IsBetaOrNewer(release_track):
            settings.userLabels = labels_util.ParseCreateArgs(
                args, sql_messages.Settings.UserLabelsValue)
            if args.allocated_ip_range_name:
                if not settings.ipConfiguration:
                    settings.ipConfiguration = sql_messages.IpConfiguration()
                settings.ipConfiguration.allocatedIpRange = args.allocated_ip_range_name

        # ALPHA args.
        if _IsAlpha(release_track):
            settings.sqlServerAuditConfig = reducers.SqlServerAuditConfig(
                sql_messages, args.audit_bucket_path,
                args.audit_retention_interval, args.audit_upload_interval)

        return settings
Example #11
0
    def ConstructInstanceFromArgs(cls,
                                  sql_messages,
                                  args,
                                  original=None,
                                  instance_ref=None):
        """Construct a Cloud SQL instance from command line args.

    Args:
      sql_messages: module, The messages module that should be used.
      args: argparse.Namespace, The CLI arg namespace.
      original: sql_messages.DatabaseInstance, The original instance, if some of
          it might be used to fill fields in the new one.
      instance_ref: reference to DatabaseInstance object, used to fill project
          and instance information.

    Returns:
      sql_messages.DatabaseInstance, The constructed (and possibly partial)
      database instance.

    Raises:
      ToolException: An error other than http error occured while executing the
          command.
    """
        original_settings = original.settings if original else None
        settings = cls._ConstructSettingsFromArgs(sql_messages, args, original)
        backup_configuration = (reducers.BackupConfiguration(
            sql_messages, original, getattr(args, 'backup', None),
            getattr(args, 'no_backup', None),
            getattr(args, 'backup_start_time', None),
            getattr(args, 'enable_bin_log', None)))
        if backup_configuration:
            cls.AddBackupConfigToSettings(settings, backup_configuration)
        settings.databaseFlags = (reducers.DatabaseFlags(
            sql_messages, original_settings,
            getattr(args, 'database_flags', None),
            getattr(args, 'clear_database_flags', None)))
        settings.maintenanceWindow = (reducers.MaintenanceWindow(
            sql_messages, original,
            getattr(args, 'maintenance_release_channel', None),
            getattr(args, 'maintenance_window_day', None),
            getattr(args, 'maintenance_window_hour', None)))

        on_premises_host_port = getattr(args, 'on_premises_host_port', None)
        if on_premises_host_port:
            if args.require_ssl:
                raise exceptions.ToolException(
                    'Argument --on-premises-host-port not '
                    'allowed with --require_ssl')
            settings.onPremisesConfiguration = sql_messages.OnPremisesConfiguration(
                hostPort=on_premises_host_port)

        storage_size = getattr(args, 'storage_size', None)
        if storage_size:
            settings.dataDiskSizeGb = int(storage_size / (1 << 30))

        # these flags are only present for the create command
        region = getattr(args, 'region', None)
        database_version = getattr(args, 'database_version', None)

        instance_resource = sql_messages.DatabaseInstance(
            region=region,
            databaseVersion=database_version,
            masterInstanceName=getattr(args, 'master_instance_name', None),
            settings=settings)

        if hasattr(args, 'master_instance_name'):
            if args.master_instance_name:
                replication = 'ASYNCHRONOUS'
                if hasattr(args,
                           'replica_type') and args.replica_type == 'FAILOVER':
                    instance_resource.replicaConfiguration = (
                        sql_messages.ReplicaConfiguration(failoverTarget=True))
            else:
                replication = 'SYNCHRONOUS'
            if not args.replication:
                instance_resource.settings.replicationType = replication

        if instance_ref:
            cls.SetProjectAndInstanceFromRef(instance_resource, instance_ref)

        if hasattr(args, 'storage_type') and args.storage_type:
            instance_resource.settings.dataDiskType = 'PD_' + args.storage_type

        if hasattr(args,
                   'failover_replica_name') and args.failover_replica_name:
            instance_resource.failoverReplica = (
                sql_messages.DatabaseInstance.FailoverReplicaValue(
                    name=args.failover_replica_name))

        if (hasattr(args, 'storage_auto_increase')
                and args.storage_auto_increase is not None):
            instance_resource.settings.storageAutoResize = args.storage_auto_increase

        if (hasattr(args, 'storage_auto_increase_limit')
                and args.IsSpecified('storage_auto_increase_limit')):
            # Resize limit should be settable if the original instance has resize
            # turned on, or if the instance to be created has resize flag.
            if (original and original.settings.storageAutoResize) or (
                    args.storage_auto_increase):
                # If the limit is set to None, we want it to be set to 0. This is a
                # backend requirement.
                instance_resource.settings.storageAutoResizeLimit = (
                    args.storage_auto_increase_limit) or 0
            else:
                raise exceptions.RequiredArgumentException(
                    '--storage-auto-increase',
                    'To set the storage capacity limit '
                    'using [--storage-auto-increase-limit], [--storage-auto-increase] '
                    'must be enabled.')

        return instance_resource