示例#1
0
        /// <summary>Snippet for CreateTableFromSnapshot</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void CreateTableFromSnapshotResourceNames()
        {
            // Create client
            BigtableTableAdminClient bigtableTableAdminClient = BigtableTableAdminClient.Create();
            // Initialize request argument(s)
            InstanceName parent         = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
            string       tableId        = "";
            SnapshotName sourceSnapshot = SnapshotName.FromProjectInstanceClusterSnapshot("[PROJECT]", "[INSTANCE]", "[CLUSTER]", "[SNAPSHOT]");
            // Make the request
            Operation <Table, CreateTableFromSnapshotMetadata> response = bigtableTableAdminClient.CreateTableFromSnapshot(parent, tableId, sourceSnapshot);

            // Poll until the returned long-running operation is complete
            Operation <Table, CreateTableFromSnapshotMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Table result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Table, CreateTableFromSnapshotMetadata> retrievedResponse = bigtableTableAdminClient.PollOnceCreateTableFromSnapshot(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Table retrievedResult = retrievedResponse.Result;
            }
        }
示例#2
0
        /// <summary>Snippet for RestoreTableAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task RestoreTableRequestObjectAsync()
        {
            // Create client
            BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();

            // Initialize request argument(s)
            RestoreTableRequest request = new RestoreTableRequest
            {
                ParentAsInstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
                TableId            = "",
                BackupAsBackupName = BackupName.FromProjectInstanceClusterBackup("[PROJECT]", "[INSTANCE]", "[CLUSTER]", "[BACKUP]"),
            };
            // Make the request
            Operation <Table, RestoreTableMetadata> response = await bigtableTableAdminClient.RestoreTableAsync(request);

            // Poll until the returned long-running operation is complete
            Operation <Table, RestoreTableMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Table result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Table, RestoreTableMetadata> retrievedResponse = await bigtableTableAdminClient.PollOnceRestoreTableAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Table retrievedResult = retrievedResponse.Result;
            }
        }
示例#3
0
        public static object SpannerGetBackupOperations(string projectId, string instanceId, string databaseId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            var filter =
                $"(metadata.database:{databaseId}) AND " +
                "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateBackupMetadata)";
            ListBackupOperationsRequest request = new ListBackupOperationsRequest
            {
                ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
                Filter = filter
            };

            // List the create backup operations on the database.
            var backupOperations = databaseAdminClient.ListBackupOperations(request);

            foreach (var operation in backupOperations)
            {
                CreateBackupMetadata metadata = operation.Metadata.Unpack <CreateBackupMetadata>();
                Console.WriteLine(
                    $"Backup {metadata.Name} on " +
                    $"database {metadata.Database} is " +
                    $"{metadata.Progress.ProgressPercent}% complete");
            }

            return(0);
        }
示例#4
0
    private async Task DeleteStaleDatabasesAsync()
    {
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = DatabaseAdminClient.ListDatabases(instanceName, pageSize: 200).ToList();

        if (databases.Count < 50)
        {
            return;
        }

        var deleteCount = Math.Max(30, databases.Count - 50);

        var databasesToDelete = databases
                                .OrderBy(db => long.TryParse(
                                             db.DatabaseName.DatabaseId
                                             .Replace("my-db-", "").Replace("my-restore-db-", "")
                                             .Replace("my-enc-db-", "").Replace("my-enc-restore-db-", ""),
                                             out long creationDate) ? creationDate : long.MaxValue)
                                .Take(deleteCount);

        // Delete the databases.
        foreach (var database in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(database.DatabaseName.DatabaseId);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to delete stale test database {database.DatabaseName.DatabaseId}: {e.Message}");
            }
        }
    }
示例#5
0
    public IEnumerable <Database> GetDatabases()
    {
        InstanceName instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var          databases    = DatabaseAdminClient.ListDatabases(instanceName);

        return(databases);
    }
示例#6
0
    private async Task DeleteStaleBackupsAsync()
    {
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var backups      = DatabaseAdminClient.ListBackups(instanceName, pageSize: 200).ToList();

        if (backups.Count < 50)
        {
            return;
        }

        var deleteCount = Math.Max(30, backups.Count - 50);

        var backupsToDelete = backups
                              .OrderBy(db => long.TryParse(
                                           db.BackupName.BackupId.Replace("my-enc-backup-", ""),
                                           out long creationDate) ? creationDate : long.MaxValue)
                              .Take(deleteCount);

        // Delete the backups.
        foreach (var backup in backupsToDelete)
        {
            try
            {
                await DatabaseAdminClient.DeleteBackupAsync(backup.BackupName);
            }
            catch (Exception) { }
        }
    }
        private static async Task MaybeCreateDatabaseOnEmulatorAsync(DatabaseName databaseName)
        {
            // Try to create a database on the emulator and ignore any AlreadyExists error.
            var adminClientBuilder = new DatabaseAdminClientBuilder
            {
                EmulatorDetection = EmulatorDetection.EmulatorOnly
            };
            var databaseAdminClient = await adminClientBuilder.BuildAsync();

            var instanceName = InstanceName.FromProjectInstance(databaseName.ProjectId, databaseName.InstanceId);

            try
            {
                await databaseAdminClient.CreateDatabase(new CreateDatabaseRequest
                {
                    ParentAsInstanceName = instanceName,
                    CreateStatement      = $"CREATE DATABASE `{databaseName.DatabaseId}`",
                }).PollUntilCompletedAsync();

                var connectionStringBuilder = new SpannerConnectionStringBuilder($"Data Source={databaseName}")
                {
                    EmulatorDetection = EmulatorDetection.EmulatorOnly,
                };
                await CreateSampleDataModel(connectionStringBuilder.ConnectionString);
            }
            catch (RpcException e) when(e.StatusCode == StatusCode.AlreadyExists)
            {
                // Ignore
            }
        }
示例#8
0
    public async Task RunWithTemporaryDatabaseAsync(string instanceId, string databaseId, Func <string, Task> testFunction, params string[] extraStatements)
    {
        var operation = await DatabaseAdminClient.CreateDatabaseAsync(new CreateDatabaseRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(ProjectId, instanceId),
            CreateStatement      = $"CREATE DATABASE `{databaseId}`",
            ExtraStatements      = { extraStatements },
        });

        var completedResponse = await operation.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            throw completedResponse.Exception;
        }

        try
        {
            await testFunction(databaseId);
        }
        finally
        {
            // Cleanup the test database.
            await DatabaseAdminClient.DropDatabaseAsync(DatabaseName.FormatProjectInstanceDatabase(ProjectId, instanceId, databaseId));
        }
    }
        private void MaybeCreateInstanceOnEmulator(string projectId)
        {
            if (SpannerClientCreationOptions.UsesEmulator)
            {
                // Try to create an instance on the emulator and ignore any AlreadyExists error.
                var adminClientBuilder = new InstanceAdminClientBuilder
                {
                    EmulatorDetection = EmulatorDetection.EmulatorOnly
                };
                var instanceAdminClient = adminClientBuilder.Build();

                var instanceName = InstanceName.FromProjectInstance(projectId, SpannerInstance);
                try
                {
                    instanceAdminClient.CreateInstance(new CreateInstanceRequest
                    {
                        InstanceId          = instanceName.InstanceId,
                        ParentAsProjectName = ProjectName.FromProject(projectId),
                        Instance            = new Instance
                        {
                            InstanceName = instanceName,
                            ConfigAsInstanceConfigName = new InstanceConfigName(projectId, "emulator-config"),
                            DisplayName = "Test Instance",
                            NodeCount   = 1,
                        },
                    }).PollUntilCompleted();
                }
                catch (RpcException e) when(e.StatusCode == StatusCode.AlreadyExists)
                {
                    // Ignore
                }
            }
        }
        private static async Task MaybeCreateInstanceOnEmulatorAsync(string projectId, string instanceId)
        {
            // Try to create an instance on the emulator and ignore any AlreadyExists error.
            var adminClientBuilder = new InstanceAdminClientBuilder
            {
                EmulatorDetection = EmulatorDetection.EmulatorOnly
            };
            var instanceAdminClient = await adminClientBuilder.BuildAsync();

            var instanceName = InstanceName.FromProjectInstance(projectId, instanceId);

            try
            {
                await instanceAdminClient.CreateInstance(new CreateInstanceRequest
                {
                    InstanceId          = instanceName.InstanceId,
                    ParentAsProjectName = ProjectName.FromProject(projectId),
                    Instance            = new Instance
                    {
                        InstanceName = instanceName,
                        ConfigAsInstanceConfigName = new InstanceConfigName(projectId, "emulator-config"),
                        DisplayName = "Sample Instance",
                        NodeCount   = 1,
                    },
                }).PollUntilCompletedAsync();
            }
            catch (RpcException e) when(e.StatusCode == StatusCode.AlreadyExists)
            {
                // Ignore
            }
        }
        /// <summary>Snippet for CreateCluster</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void CreateClusterRequestObject()
        {
            // Create client
            BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
            // Initialize request argument(s)
            CreateClusterRequest request = new CreateClusterRequest
            {
                ParentAsInstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
                ClusterId            = "",
                Cluster = new Cluster(),
            };
            // Make the request
            Operation <Cluster, CreateClusterMetadata> response = bigtableInstanceAdminClient.CreateCluster(request);

            // Poll until the returned long-running operation is complete
            Operation <Cluster, CreateClusterMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Cluster result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Cluster, CreateClusterMetadata> retrievedResponse = bigtableInstanceAdminClient.PollOnceCreateCluster(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Cluster retrievedResult = retrievedResponse.Result;
            }
        }
        public static void DelelteDatabases()
        {
            string adminConnectionString = $"Data Source=projects/{projectId}/"
                                           + $"instances/{instanceId}";

            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
            InstanceName        instanceName        = InstanceName.FromProjectInstance(projectId, instanceId);
            var databases = databaseAdminClient.ListDatabases(instanceName);

            using (var connection = new SpannerConnection(adminConnectionString))
                foreach (var database in databases)
                {
                    using (var cmd = connection.CreateDdlCommand($@"DROP DATABASE {database.DatabaseName.DatabaseId}"))
                    {
                        try
                        {
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
        }
示例#13
0
    public IEnumerable <Operation> ListDatabaseOperations(string projectId, string instanceId)
    {
        // Create the DatabaseAdminClient instance.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

        var filter = "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)";

        ListDatabaseOperationsRequest request = new ListDatabaseOperationsRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            Filter = filter
        };

        // List the optimize restored databases operations on the instance.
        var operations = databaseAdminClient.ListDatabaseOperations(request);

        foreach (var operation in operations)
        {
            OptimizeRestoredDatabaseMetadata metadata =
                operation.Metadata.Unpack <OptimizeRestoredDatabaseMetadata>();
            Console.WriteLine(
                $"Database {metadata.Name} restored from backup is {metadata.Progress.ProgressPercent}% optimized.");
        }

        return(operations);
    }
    /// <summary>
    /// Deletes 5 oldest databases if the number of databases is more than 94.
    /// This is to avoid resource exhausted errors.
    /// </summary>
    private async Task DeleteStaleDatabasesAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = databaseAdminClient.ListDatabases(instanceName);

        if (databases.Count() < 95)
        {
            return;
        }

        var databasesToDelete = databases
                                .OrderBy(db => long.TryParse(
                                             db.DatabaseName.DatabaseId.Replace("my-db-", "").Replace("my-restore-db-", ""),
                                             out long creationDate) ? creationDate : long.MaxValue)
                                .Take(5);

        // Delete the databases.
        foreach (var database in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(database.DatabaseName.DatabaseId);
            }
            catch (Exception) { }
        }
    }
示例#15
0
        public static object SpannerRestoreDatabase(
            string projectId, string instanceId, string databaseId, string backupId)
        {
            // Create the DatabaseAdminClient instance.
            DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();

            InstanceName parentAsInstanceName =
                InstanceName.FromProjectInstance(projectId, instanceId);
            BackupName backupAsBackupName =
                BackupName.FromProjectInstanceBackup(projectId, instanceId, backupId);

            // Make the RestoreDatabase request.
            Operation <Database, RestoreDatabaseMetadata> response =
                databaseAdminClient.RestoreDatabase(
                    parentAsInstanceName, databaseId, backupAsBackupName);

            Console.WriteLine("Waiting for the operation to finish");

            // Poll until the returned long-running operation is complete.
            var completedResponse = response.PollUntilCompleted();

            if (completedResponse.IsFaulted)
            {
                Console.WriteLine($"Database Restore Failed: {completedResponse.Exception}");
                return(1);
            }

            RestoreInfo restoreInfo = completedResponse.Result.RestoreInfo;

            Console.WriteLine(
                $"Database {restoreInfo.BackupInfo.SourceDatabase} was restored " +
                $"to {databaseId} from backup {restoreInfo.BackupInfo.Backup}");

            return(0);
        }
        /// <summary>Snippet for CreateClusterAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateClusterResourceNamesAsync()
        {
            // Create client
            BigtableInstanceAdminClient bigtableInstanceAdminClient = await BigtableInstanceAdminClient.CreateAsync();

            // Initialize request argument(s)
            InstanceName parent    = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
            string       clusterId = "";
            Cluster      cluster   = new Cluster();
            // Make the request
            Operation <Cluster, CreateClusterMetadata> response = await bigtableInstanceAdminClient.CreateClusterAsync(parent, clusterId, cluster);

            // Poll until the returned long-running operation is complete
            Operation <Cluster, CreateClusterMetadata> completedResponse = await response.PollUntilCompletedAsync();

            // Retrieve the operation result
            Cluster result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation <Cluster, CreateClusterMetadata> retrievedResponse = await bigtableInstanceAdminClient.PollOnceCreateClusterAsync(operationName);

            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Cluster retrievedResult = retrievedResponse.Result;
            }
        }
 /// <summary>Snippet for GetInstance</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetInstanceResourceNames()
 {
     // Create client
     BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
     // Initialize request argument(s)
     InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
     // Make the request
     Instance response = bigtableInstanceAdminClient.GetInstance(name);
 }
示例#18
0
 /// <summary>Snippet for ListClusters</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void ListClustersResourceNames()
 {
     // Create client
     BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
     // Initialize request argument(s)
     InstanceName parent = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
     // Make the request
     ListClustersResponse response = bigtableInstanceAdminClient.ListClusters(parent);
 }
    private async Task DeleteStaleBackupsAndDatabasesAsync()
    {
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName = InstanceName.FromProjectInstance(ProjectId, InstanceId);
        var databases    = databaseAdminClient.ListDatabases(instanceName)
                           .Where(c => c.DatabaseName.DatabaseId.StartsWith("my-db-") || c.DatabaseName.DatabaseId.StartsWith("my-restore-db-"));
        var databasesToDelete = new List <string>();

        // Delete all the databases created before 48 hrs.
        var timestamp = DateTimeOffset.UtcNow.AddHours(-48).ToUnixTimeMilliseconds();

        foreach (var database in databases)
        {
            var databaseId = database.DatabaseName.DatabaseId.Replace("my-restore-db-", "").Replace("my-db-", "");
            if (long.TryParse(databaseId, out long dbCreationTime) && dbCreationTime <= timestamp)
            {
                databasesToDelete.Add(database.DatabaseName.DatabaseId);
            }
        }

        await Console.Out.WriteLineAsync($"{databasesToDelete.Count} old databases found.");

        // Get backups.
        ListBackupsRequest request = new ListBackupsRequest
        {
            ParentAsInstanceName = instanceName,
            Filter = $"database:my-db-"
        };
        var backups = databaseAdminClient.ListBackups(request);

        // Backups that belong to the databases to be deleted.
        var backupsToDelete = backups.Where(c => databasesToDelete.Contains(DatabaseName.Parse(c.Database).DatabaseId));

        await Console.Out.WriteLineAsync($"{backupsToDelete.Count()} old backups found.");

        // Delete the backups.
        foreach (var backup in backupsToDelete)
        {
            try
            {
                DeleteBackupSample deleteBackupSample = new DeleteBackupSample();
                deleteBackupSample.DeleteBackup(ProjectId, InstanceId, backup.BackupName.BackupId);
            }
            catch (Exception) { }
        }

        // Delete the databases.
        foreach (var databaseId in databasesToDelete)
        {
            try
            {
                await DeleteDatabaseAsync(databaseId);
            }
            catch (Exception) { }
        }
    }
        /// <summary>Snippet for GetInstanceAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetInstanceResourceNamesAsync()
        {
            // Create client
            BigtableInstanceAdminClient bigtableInstanceAdminClient = await BigtableInstanceAdminClient.CreateAsync();

            // Initialize request argument(s)
            InstanceName name = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
            // Make the request
            Instance response = await bigtableInstanceAdminClient.GetInstanceAsync(name);
        }
示例#21
0
 /// <summary>Snippet for CreateAppProfile</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void CreateAppProfileResourceNames()
 {
     // Create client
     BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
     // Initialize request argument(s)
     InstanceName parent       = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
     string       appProfileId = "";
     AppProfile   appProfile   = new AppProfile();
     // Make the request
     AppProfile response = bigtableInstanceAdminClient.CreateAppProfile(parent, appProfileId, appProfile);
 }
示例#22
0
 /// <summary>Snippet for GetInstance</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetInstanceRequestObject()
 {
     // Create client
     BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
     // Initialize request argument(s)
     GetInstanceRequest request = new GetInstanceRequest
     {
         InstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
     };
     // Make the request
     Instance response = bigtableInstanceAdminClient.GetInstance(request);
 }
        /// <summary>Snippet for CreateTableAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateTableResourceNamesAsync()
        {
            // Create client
            BigtableTableAdminClient bigtableTableAdminClient = await BigtableTableAdminClient.CreateAsync();

            // Initialize request argument(s)
            InstanceName parent  = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]");
            string       tableId = "";
            Table        table   = new Table();
            // Make the request
            Table response = await bigtableTableAdminClient.CreateTableAsync(parent, tableId, table);
        }
示例#24
0
    public IEnumerable <Database> ListDatabases(string projectId, string instanceId)
    {
        var databaseAdminClient = DatabaseAdminClient.Create();
        var instanceName        = InstanceName.FromProjectInstance(projectId, instanceId);
        var databases           = databaseAdminClient.ListDatabases(instanceName);

        foreach (var database in databases)
        {
            Console.WriteLine($"Default leader for database {database.DatabaseName.DatabaseId}: {database.DefaultLeader}");
        }

        return(databases);
    }
        /// <summary>Snippet for DeleteInstanceAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task DeleteInstanceRequestObjectAsync()
        {
            // Create client
            BigtableInstanceAdminClient bigtableInstanceAdminClient = await BigtableInstanceAdminClient.CreateAsync();

            // Initialize request argument(s)
            DeleteInstanceRequest request = new DeleteInstanceRequest
            {
                InstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
            };
            // Make the request
            await bigtableInstanceAdminClient.DeleteInstanceAsync(request);
        }
 /// <summary>Snippet for ListClusters</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void ListClustersRequestObject()
 {
     // Create client
     BigtableInstanceAdminClient bigtableInstanceAdminClient = BigtableInstanceAdminClient.Create();
     // Initialize request argument(s)
     ListClustersRequest request = new ListClustersRequest
     {
         ParentAsInstanceName = InstanceName.FromProjectInstance("[PROJECT]", "[INSTANCE]"),
         PageToken            = "",
     };
     // Make the request
     ListClustersResponse response = bigtableInstanceAdminClient.ListClusters(request);
 }
示例#27
0
    public async Task <Database> CreateDatabaseWithEncryptionKeyAsync(string projectId, string instanceId, string databaseId, CryptoKeyName kmsKeyName)
    {
        // Create a DatabaseAdminClient instance that can be used to execute a
        // CreateDatabaseRequest with custom encryption configuration options.
        DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create();
        // Define create table statement for table #1.
        var createSingersTable =
            @"CREATE TABLE Singers (
                     SingerId INT64 NOT NULL,
                     FirstName STRING(1024),
                     LastName STRING(1024),
                     ComposerInfo BYTES(MAX)
                 ) PRIMARY KEY (SingerId)";
        // Define create table statement for table #2.
        var createAlbumsTable =
            @"CREATE TABLE Albums (
                     SingerId INT64 NOT NULL,
                     AlbumId INT64 NOT NULL,
                     AlbumTitle STRING(MAX)
                 ) PRIMARY KEY (SingerId, AlbumId),
                 INTERLEAVE IN PARENT Singers ON DELETE CASCADE";

        // Create the CreateDatabase request with encryption configuration and execute it.
        var request = new CreateDatabaseRequest
        {
            ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId),
            CreateStatement      = $"CREATE DATABASE `{databaseId}`",
            ExtraStatements      = { createSingersTable, createAlbumsTable },
            EncryptionConfig     = new EncryptionConfig
            {
                KmsKeyNameAsCryptoKeyName = kmsKeyName,
            },
        };
        var operation = await databaseAdminClient.CreateDatabaseAsync(request);

        // Wait until the operation has finished.
        Console.WriteLine("Waiting for the operation to finish.");
        var completedResponse = await operation.PollUntilCompletedAsync();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating database: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        var database = completedResponse.Result;

        Console.WriteLine($"Database {database.Name} created with encryption key {database.EncryptionConfig.KmsKeyName}");

        return(database);
    }
    public Instance CreateInstanceWithProcessingUnits(string projectId, string instanceId)
    {
        // Create the InstanceAdminClient instance.
        InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();

        InstanceName instanceName = InstanceName.FromProjectInstance(projectId, instanceId);

        // Initialize request parameters.
        Instance instance = new Instance
        {
            InstanceName = instanceName,
            ConfigAsInstanceConfigName = InstanceConfigName.FromProjectInstanceConfig(projectId, "regional-us-central1"),
            DisplayName     = "This is a display name.",
            ProcessingUnits = 500,
            Labels          =
            {
                { "cloud_spanner_samples", "true" },
            }
        };
        ProjectName projectName = ProjectName.FromProject(projectId);

        // Make the CreateInstance request.
        Operation <Instance, CreateInstanceMetadata> response = instanceAdminClient.CreateInstance(projectName, instanceId, instance);

        Console.WriteLine("Waiting for the operation to finish.");

        // Poll until the returned long-running operation is complete.
        Operation <Instance, CreateInstanceMetadata> completedResponse = response.PollUntilCompleted();

        if (completedResponse.IsFaulted)
        {
            Console.WriteLine($"Error while creating instance: {completedResponse.Exception}");
            throw completedResponse.Exception;
        }

        Console.WriteLine($"Instance created successfully.");

        // GetInstance to get the processing units using a field mask.
        GetInstanceRequest getInstanceRequest = new GetInstanceRequest
        {
            FieldMask = new FieldMask
            {
                Paths = { "processing_units" }
            },
            InstanceName = instanceName
        };

        instance = instanceAdminClient.GetInstance(getInstanceRequest);
        Console.WriteLine($"Instance {instanceId} has {instance.ProcessingUnits} processing units.");
        return(instance);
    }
示例#29
0
        void InitializeInstance()
        {
            InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();

            try
            {
                InstanceName instanceName = InstanceName.FromProjectInstance(_fixture.ProjectId, _fixture.InstanceId);
                Instance     response     = instanceAdminClient.GetInstance(instanceName);
            }
            catch (RpcException ex) when(ex.Status.StatusCode == StatusCode.NotFound)
            {
                CreateInstance.SpannerCreateInstance(_fixture.ProjectId, _fixture.InstanceId);
            }
        }
示例#30
0
    private void DeleteInstance(string instanceId)
    {
        InstanceAdminClient instanceAdminClient = InstanceAdminClient.Create();
        InstanceName        instanceName        = InstanceName.FromProjectInstance(ProjectId, instanceId);

        try
        {
            instanceAdminClient.DeleteInstance(instanceName);
        }
        catch (Exception)
        {
            // Silently ignore errors to prevent tests from failing.
        }
    }