/// <summary> /// Get information about the specified DB System. /// </summary> /// <param name="request">The request object containing the details to send. Required.</param> /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param> /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param> /// <returns>A response object containing details about the completed operation</returns> /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/mysql/GetDbSystem.cs.html">here</a> to see an example of how to use GetDbSystem API.</example> public async Task <GetDbSystemResponse> GetDbSystem(GetDbSystemRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called getDbSystem"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/dbSystems/{dbSystemId}".Trim('/'))); HttpMethod method = new HttpMethod("GET"); HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request); requestMessage.Headers.Add("Accept", "application/json"); GenericRetrier retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration); HttpResponseMessage responseMessage; try { if (retryingClient != null) { responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false); } else { responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false); } this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage); return(Converter.FromHttpResponseMessage <GetDbSystemResponse>(responseMessage)); } catch (Exception e) { logger.Error($"GetDbSystem failed with error: {e.Message}"); throw; } }
private static async Task terminateDbSystem(DatabaseClient databaseClient, string dbSystemId) { try { logger.Info("Terminating the Database..."); TerminateDbSystemRequest terminateDbSystemRequest = new TerminateDbSystemRequest { DbSystemId = dbSystemId }; await databaseClient.TerminateDbSystem(terminateDbSystemRequest); GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest { DbSystemId = dbSystemId }; WaiterConfiguration waiterConfiguration = new WaiterConfiguration { MaxAttempts = 20, GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds }; databaseClient.Waiters.ForDbSystem(getDbSystemRequest, waiterConfiguration, DbSystem.LifecycleStateEnum.Terminated).Execute(); logger.Info("Database terminated"); } catch (Exception e) { logger.Error($"failed to terminate DbSystem: {e}"); } }
/// <summary> /// Creates a waiter using the provided configuration. /// </summary> /// <param name="request">Request to send.</param> /// <param name="config">Wait Configuration</param> /// <param name="targetStates">Desired resource states. If multiple states are provided then the waiter will return once the resource reaches any of the provided states</param> /// <returns>a new Oci.common.Waiter instance</returns> public Waiter <GetDbSystemRequest, GetDbSystemResponse> ForDbSystem(GetDbSystemRequest request, WaiterConfiguration config, params DbSystem.LifecycleStateEnum[] targetStates) { var agent = new WaiterAgent <GetDbSystemRequest, GetDbSystemResponse>( request, request => client.GetDbSystem(request), response => targetStates.Contains(response.DbSystem.LifecycleState.Value), targetStates.Contains(DbSystem.LifecycleStateEnum.Deleted) ); return(new Waiter <GetDbSystemRequest, GetDbSystemResponse>(config, agent)); }
/// <summary> /// Gets information about the specified DB system. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <GetDbSystemResponse> GetDbSystem(GetDbSystemRequest request) { var uri = new Uri($"{GetEndPoint(DatabaseServices.DbSystems, this.Region)}/{request.DbSystemId}"); using (var webResponse = await this.RestClientAsync.Get(uri)) using (var stream = webResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { var response = await reader.ReadToEndAsync(); return(new GetDbSystemResponse() { DbSystem = this.JsonSerializer.Deserialize <DbSystemDetails>(response), OpcRequestId = webResponse.Headers.Get("opc-request-id"), ETag = webResponse.Headers.Get("ETag") }); } }
private void HandleOutput(GetDbSystemRequest request) { var waiterConfig = new WaiterConfiguration { MaxAttempts = MaxWaitAttempts, GetNextDelayInSeconds = (_) => WaitIntervalSeconds }; switch (ParameterSetName) { case LifecycleStateParamSet: response = client.Waiters.ForDbSystem(request, waiterConfig, WaitForLifecycleState).Execute(); break; case Default: response = client.GetDbSystem(request).GetAwaiter().GetResult(); break; } WriteOutput(response, response.DbSystem); }
protected override void ProcessRecord() { base.ProcessRecord(); GetDbSystemRequest request; try { request = new GetDbSystemRequest { DbSystemId = DbSystemId }; HandleOutput(request); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
/// <summary> /// Creates a waiter using default wait configuration. /// </summary> /// <param name="request">Request to send.</param> /// <param name="targetStates">Desired resource states. If multiple states are provided then the waiter will return once the resource reaches any of the provided states</param> /// <returns>a new Oci.common.Waiter instance</returns> public Waiter <GetDbSystemRequest, GetDbSystemResponse> ForDbSystem(GetDbSystemRequest request, params DbSystem.LifecycleStateEnum[] targetStates) { return(this.ForDbSystem(request, WaiterConfiguration.DefaultWaiterConfiguration, targetStates)); }
static void Main(string[] args) { Console.WriteLine("+----------------------------------------+"); Console.WriteLine("| |"); Console.WriteLine("| OCISDK SessionExample |"); Console.WriteLine("| |"); Console.WriteLine("+----------------------------------------+"); string configPath = ".oci/config"; System.OperatingSystem os = System.Environment.OSVersion; // windows if (os.Platform == PlatformID.Win32NT) { string rootPath = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory()); configPath = $"{rootPath}/{configPath}"; if (!Directory.Exists($"{rootPath}/.oci")) { Directory.CreateDirectory($"{rootPath}/.oci"); } } else { configPath = $"/home/user/{configPath}"; } string profile; ConfigFile configReader; if (File.Exists(configPath)) { Console.Write("Connection ProfileName(Empty Input is DEFAULT): "); profile = Console.ReadLine(); if (string.IsNullOrEmpty(profile)) { profile = "DEFAULT"; } // load connection file configReader = ConfigFileReader.Parse(configPath, profile); } else { profile = "DEFAULT"; // create connection file Console.WriteLine("Create connection settings to Oracle Cloud Infrastructure"); Console.Write("TenancyId (Required): "); string tenancyId = OCIDInput(); Console.Write("UserId (Required): "); string userId = OCIDInput(); Console.Write("Fingerprint (Required): "); string fingerprint = KeyInput(); Console.Write("PrivateKeyPath (Required): "); string privateKeyPath = KeyInput(); Console.Write("PrivateKeyPassphrase: "); string privateKeyPassphrase = InputPassword(); string testFileContentsMyProfile = $"[{profile}]\n" + $"tenancy={tenancyId}\n" + $"user={userId}\n" + $"fingerprint={fingerprint}\n" + $"key_file={privateKeyPath}\n" + $"pass_phrase={privateKeyPassphrase}\n"; File.WriteAllText(configPath, testFileContentsMyProfile); configReader = ConfigFileReader.Parse(configPath, profile); } // ClientConfig settings var configSt = new ClientConfigStream(); IOciSession session; using (var st = File.OpenText(configReader.Get("key_file"))) { configSt = new ClientConfigStream { TenancyId = configReader.Get("tenancy"), UserId = configReader.Get("user"), Fingerprint = configReader.Get("fingerprint"), PrivateKey = st, PrivateKeyPassphrase = configReader.Get("pass_phrase"), AccountId = configReader.Get("accountId"), IdentityDomain = configReader.Get("domain"), UserName = configReader.Get("user"), Password = configReader.Get("password"), HomeRegion = configReader.Get("home_region") }; session = new OciSession(configSt); } var comClient = session.GetCommercialClient(); var listPurchaseEntitlementsRequest = new ListPurchaseEntitlementsRequest { CompartmentId = configSt.TenancyId }; var purchase = comClient.ListPurchaseEntitlements(listPurchaseEntitlementsRequest); var getServiceEntitlementRegistrationsRequest = new ListServiceEntitlementRegistrationsRequest() { CompartmentId = configSt.TenancyId }; var services = comClient.ListServiceEntitlementRegistrations(getServiceEntitlementRegistrationsRequest); var costClient = session.GetUsageCostsClient(); var getSubscriptionInfoRequest = new GetSubscriptionInfoRequest { TenancyId = configSt.TenancyId }; var subsc = costClient.GetSubscriptionInfo(getSubscriptionInfoRequest); // get Client var identityClient = session.GetIdentityClient(); var getTenancyRequest = new GetTenancyRequest() { TenancyId = configSt.TenancyId }; var getTenacy = identityClient.GetTenancy(getTenancyRequest); Console.WriteLine($"tenantName: {getTenacy.Tenancy.Name}"); // get compute var computeClient = session.GetComputeClient(); IDictionary <string, IDictionary <string, string> > tags = new Dictionary <string, IDictionary <string, string> >(); tags.Add("CostTracking", new Dictionary <string, string> { { "cost-trakcerA", "aaaa" } }); var dbClient = session.GetDatabaseClient(); GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest() { DbSystemId = "ocid1.dbsystem.oc1.iad.abuwcljrbukbjzlameegvsn3u7qb3qcqvtcdvl74jxfth7xjsya7cxkdpibq" }; var dbSystem = dbClient.GetDbSystem(getDbSystemRequest); UpdateDbSystemRequest updateDbSystemRequest = new UpdateDbSystemRequest() { DbSystemId = "ocid1.dbsystem.oc1.iad.abuwcljrbukbjzlameegvsn3u7qb3qcqvtcdvl74jxfth7xjsya7cxkdpibq", UpdateDbSystemDetails = new OCISDK.Core.Database.Model.UpdateDbSystemDetails() { DefinedTags = tags } }; dbClient.UpdateDbSystem(updateDbSystemRequest); var listCompartmentRequest = new ListCompartmentRequest() { CompartmentId = getTenacy.Tenancy.Id, CompartmentIdInSubtree = true }; var cmparts = identityClient.ListCompartment(listCompartmentRequest); foreach (var com in cmparts.Items) { Console.WriteLine($"compartmentName: {com.Name}"); var listInstanceRequest = new ListInstancesRequest() { CompartmentId = com.Id, Limit = 10, SortOrder = SortOrder.ASC }; var instances = computeClient.ListInstances(listInstanceRequest); foreach (var ins in instances.Items) { Console.WriteLine($"rootCompartmentInstanceName: {ins.DisplayName}"); var workReqestClient = session.GetWorkRequestClient(); var listWorkRequestsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestsRequest() { CompartmentId = ins.CompartmentId, ResourceId = ins.Id }; var workreqs = workReqestClient.ListWorkRequests(listWorkRequestsRequest); foreach (var wq in workreqs.Items) { Console.WriteLine($"\tWorkRequest: {wq.OperationType}, state:{wq.Status}"); var getWorkRequestRequest = new OCISDK.Core.Core.Request.WorkRequest.GetWorkRequestRequest() { WorkRequestId = wq.Id }; var gw = workReqestClient.GetWorkRequest(getWorkRequestRequest); Console.WriteLine($"\taccepted:{gw.WorkRequest.TimeAccepted}, finished:{gw.WorkRequest.TimeFinished}"); var listWorkRequestErrorsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestErrorsRequest() { WorkRequestId = wq.Id, Limit = 100, SortOrder = SortOrder.ASC }; var wqErrors = workReqestClient.ListWorkRequestErrors(listWorkRequestErrorsRequest); foreach (var error in wqErrors.Items) { Console.WriteLine($"\tErrorCode: {error.Code}, ErrorMessage:{error.Message}, ErrorTimeStamp:{error.Timestamp}"); } var listWorkRequestLogsRequest = new OCISDK.Core.Core.Request.WorkRequest.ListWorkRequestLogsRequest() { WorkRequestId = wq.Id, Limit = 100, SortOrder = SortOrder.ASC }; var wqLogs = workReqestClient.ListWorkRequestLogs(listWorkRequestLogsRequest); foreach (var log in wqLogs.Items) { Console.WriteLine($"\tLogMessage:{log.Message}, LogTimeStamp:{log.Timestamp}"); } } } } Console.WriteLine("Exit with key press..."); Console.ReadLine(); }
static async Task MainDatabase(string[] args) { string compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); string adminPassword = Environment.GetEnvironmentVariable("PASSWORD"); logger.Info("Starting example"); // Accepts profile name and creates a auth provider based on config file var provider = new ConfigFileAuthenticationDetailsProvider(OciConfigProfileName); var identityClient = new IdentityClient(provider); var virtualNetworkClient = new VirtualNetworkClient(provider); var databaseClient = new DatabaseClient(provider); var networkCidrBlock = "10.0.1.0/24"; Vcn vcn = null; Subnet subnet = null; string dbSystemId = null; AvailabilityDomain availablityDomain = await getAvailabilityDomains(identityClient, compartmentId); logger.Info($"availability domain is {availablityDomain.Name}"); try { vcn = await createVcn(virtualNetworkClient, compartmentId, networkCidrBlock); subnet = await createSubnet(virtualNetworkClient, compartmentId, availablityDomain, networkCidrBlock, vcn); logger.Info("Launching Database...."); LaunchDbSystemDetails launchDbSystemDetails = new LaunchDbSystemDetails { AvailabilityDomain = availablityDomain.Name, CompartmentId = compartmentId, CpuCoreCount = 4, Shape = "BM.DenseIO2.52", SshPublicKeys = new List <string> { "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyyA8wePstPC69PeuHFtOwyTecByonsHFAjHbVnZ+h0dpomvLZxUtbknNj3+c7MPYKqKBOx9gUKV/diR/mIDqsb405MlrI1kmNR9zbFGYAAwIH/Gxt0Lv5ffwaqsz7cECHBbMojQGEz3IH3twEvDfF6cu5p00QfP0MSmEi/eB+W+h30NGdqLJCziLDlp409jAfXbQm/4Yx7apLvEmkaYSrb5f/pfvYv1FEV1tS8/J7DgdHUAWo6gyGUUSZJgsyHcuJT7v9Tf0xwiFWOWL9WsWXa9fCKqTeYnYJhHlqfinZRnT/+jkz0OZ7YmXo6j4Hyms3RCOqenIX1W6gnIn+eQIkw== This is the key's comment" }, SubnetId = subnet.Id, DatabaseEdition = LaunchDbSystemDetails.DatabaseEditionEnum.EnterpriseEdition, DisplayName = "OCI DotNet SDK database", Hostname = "oci-dotnetsdk-host", Domain = "testdomain", DbHome = new CreateDbHomeDetails { DbVersion = "12.1.0.2", DisplayName = "Example DB Home", Database = new CreateDatabaseDetails { DbName = "dotnetdb", AdminPassword = adminPassword } } }; LaunchDbSystemRequest launchDbSystemRequest = new LaunchDbSystemRequest { LaunchDbSystemDetails = launchDbSystemDetails }; LaunchDbSystemResponse launchDbSystemResponse = await databaseClient.LaunchDbSystem(launchDbSystemRequest); logger.Info($"Database ID: {launchDbSystemResponse.DbSystem.Id} and Database display name: {launchDbSystemResponse.DbSystem.DisplayName}"); logger.Info("Waiting for Database to come to available state...."); GetDbSystemRequest getDbSystemRequest = new GetDbSystemRequest { DbSystemId = launchDbSystemResponse.DbSystem.Id }; WaiterConfiguration waiterConfiguration = new WaiterConfiguration { MaxAttempts = 20, GetNextDelayInSeconds = DelayStrategy.GetExponentialDelayInSeconds }; GetDbSystemResponse getDbSystemResponse = databaseClient.Waiters.ForDbSystem( getDbSystemRequest, waiterConfiguration, DbSystem.LifecycleStateEnum.Available).Execute(); logger.Info("Database is available"); logger.Info($"Database ID: {getDbSystemResponse.DbSystem.Id} and Database display name: {getDbSystemResponse.DbSystem.DisplayName}"); dbSystemId = getDbSystemResponse.DbSystem.Id; } catch (Exception e) { logger.Error($"failed to launch DbSystem: {e}"); } finally { if (dbSystemId != null) { await terminateDbSystem(databaseClient, dbSystemId); } if (subnet != null) { await deleteSubnet(virtualNetworkClient, subnet); } if (vcn != null) { await deleteVcn(virtualNetworkClient, vcn); } identityClient.Dispose(); virtualNetworkClient.Dispose(); databaseClient.Dispose(); logger.Info("End example"); } }