protected override void ProcessRecord() { base.ProcessRecord(); GetAlarmHistoryRequest request; try { request = new GetAlarmHistoryRequest { AlarmId = AlarmId, OpcRequestId = OpcRequestId, AlarmHistorytype = AlarmHistorytype, Page = Page, Limit = Limit, TimestampGreaterThanOrEqualTo = TimestampGreaterThanOrEqualTo, TimestampLessThan = TimestampLessThan }; response = client.GetAlarmHistory(request).GetAwaiter().GetResult(); WriteOutput(response, response.AlarmHistoryCollection); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
/// <summary> /// Get the history of the specified alarm. /// For important limits information, see [Limits on Monitoring](https://docs.cloud.oracle.com/iaas/Content/Monitoring/Concepts/monitoringoverview.htm#Limits). /// <br/> /// This call is subject to a Monitoring limit that applies to the total number of requests across all alarm operations. /// Monitoring might throttle this call to reject an otherwise valid request when the total rate of alarm operations exceeds 10 requests, /// or transactions, per second (TPS) for a given tenancy. /// /// </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/monitoring/GetAlarmHistory.cs.html">here</a> to see an example of how to use GetAlarmHistory API.</example> public async Task <GetAlarmHistoryResponse> GetAlarmHistory(GetAlarmHistoryRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called getAlarmHistory"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/alarms/{alarmId}/history".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 <GetAlarmHistoryResponse>(responseMessage)); } catch (Exception e) { logger.Error($"GetAlarmHistory failed with error: {e.Message}"); throw; } }
/// <summary> /// Get the history of the specified alarm. For important limits information, see Limits on Monitoring. /// Transactions Per Second (TPS) per-tenancy limit for this operation: 1. /// </summary> /// <param name="param"></param> /// <returns></returns> public async Task <GetAlarmHistoryResponse> GetAlarmHistory(GetAlarmHistoryRequest param) { var uri = new Uri($"{GetEndPoint(MonitoringServices.Alarms, this.Region)}/{param.AlarmId}/history?{param.GetOptionQuery()}"); using (var webResponse = await this.RestClientAsync.Get(uri, new HttpRequestHeaderParam() { OpcRequestId = param.OpcRequestId })) using (var stream = webResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { var response = await reader.ReadToEndAsync(); return(new GetAlarmHistoryResponse() { AlarmHistoryCollection = JsonSerializer.Deserialize <AlarmHistoryCollection>(response), OpcRequestId = webResponse.Headers.Get("opc-request-id"), OpcNextPage = webResponse.Headers.Get("opc-next-page") }); } }
public static void MonitoringResourceExample(ClientConfig config) { // create client var identityClient = new IdentityClient(config); var computeClient = new ComputeClient(config); var monitoringClient = new MonitoringClient(config); var listCompartmenRequest = new ListCompartmentRequest() { CompartmentId = identityClient.Config.TenancyId, CompartmentIdInSubtree = true, AccessLevel = ListCompartmentRequest.AccessLevels.ACCESSIBLE, Limit = 10 }; // get compartment var listCompartment = identityClient.ListCompartment(listCompartmenRequest).Items; Console.WriteLine("* List Instance Metrics------------------------"); foreach (var compartment in listCompartment) { if (!compartment.IsAccessible.HasValue || !compartment.IsAccessible.Value) { continue; } var listInstanceRequest = new ListInstancesRequest() { CompartmentId = compartment.Id, Limit = 50, LifecycleState = ListInstancesRequest.LifecycleStates.RUNNING, SortOrder = SortOrder.ASC }; var now = DateTime.UtcNow.AddHours(-2); var endTime = DateTime.UtcNow; // get instance var listInstance = computeClient.ListInstances(listInstanceRequest).Items; foreach (var instance in listInstance) { Console.WriteLine($" |-{instance.DisplayName}------------"); // get all computeagent var listMetricsRequest = new ListMetricsRequest() { CompartmentId = compartment.Id, CompartmentIdInSubtree = compartment.CompartmentId == config.TenancyId, ListMetricsDetails = new ListMetricsDetails() { Namespace = "oci_computeagent", DimensionFilters = new DimensionFilter() { ResourceId = instance.Id } } }; // get Metrics try { var listMetrics = monitoringClient.ListMetrics(listMetricsRequest).Items; foreach (var metrics in listMetrics) { Console.WriteLine($"\t| Mertics: {metrics.Name}"); Console.WriteLine($"\t| NameSpace: {metrics.Namespace}"); // metric dimensions //Console.WriteLine($"\t| {metrics.Dimensions}".Replace("\n", "")); var summarizeMetricsDataRequest = new SummarizeMetricsDataRequest() { CompartmentId = compartment.Id, CompartmentIdInSubtree = compartment.CompartmentId == config.TenancyId, SummarizeMetricsDataDetails = new SummarizeMetricsDataDetails() { Namespace = metrics.Namespace, Query = metrics.Name + "[1h]{resourceId = \"" + instance.Id + "\"}.mean()", StartTime = now.ToString("yyyy-MM-ddThh:MM:ssZ"), EndTime = endTime.ToString("yyyy-MM-ddThh:MM:ssZ") } }; var SummarizeMetricsDatas = monitoringClient.SummarizeMetricsData(summarizeMetricsDataRequest).Items; foreach (var summaryData in SummarizeMetricsDatas) { foreach (var aggregatedDatapoint in summaryData.AggregatedDatapoints) { Console.WriteLine("\t| {"); Console.WriteLine($"\t| \tTimeStamp: {aggregatedDatapoint.Timestamp}"); Console.WriteLine($"\t| \tValue: {aggregatedDatapoint.Value}"); Console.WriteLine("\t| }"); } } } } catch (WebException we) { Console.WriteLine($"notfund:{we.Message}"); } } } Console.WriteLine("* List compartment Alarms------------------------"); foreach (var compartment in listCompartment) { Console.WriteLine(" Alarm status------------------------"); var listAlarmsStatusRequest = new ListAlarmsStatusRequest() { CompartmentId = compartment.Id, Limit = 1000 }; var alarmStatus = monitoringClient.ListAlarmsStatus(listAlarmsStatusRequest); if (alarmStatus.Items.Count > 0) { Console.WriteLine($" |-{compartment.Name}------------"); foreach (var alarm in alarmStatus.Items) { Console.WriteLine($"\tid:{alarm.Id}"); Console.WriteLine($"\tname:{alarm.DisplayName}"); Console.WriteLine($"\tstatus:{alarm.Status}"); Console.WriteLine($"\tseverity:{alarm.Severity}"); } } var listAlarmsRequest = new ListAlarmsRequest() { CompartmentId = compartment.Id, Limit = 10 }; Console.WriteLine(" Alarm logs------------------------"); var listAlarms = monitoringClient.ListAlarms(listAlarmsRequest); if (listAlarms.Items.Count > 0) { Console.WriteLine($" |-{compartment.Name}------------"); foreach (var alarm in listAlarms.Items) { Console.WriteLine($"\tid:{alarm.Id}"); Console.WriteLine($"\tname:{alarm.DisplayName}"); Console.WriteLine($"\tdestinations:{alarm.Destinations}"); Console.WriteLine($"\tenable:{alarm.IsEnabled}"); Console.WriteLine($"\tstate:{alarm.LifecycleState}"); var getAlarmHistoryRequest = new GetAlarmHistoryRequest() { AlarmId = alarm.Id, TimestampGreaterThanOrEqualTo = DateTime.UtcNow.ToString() }; var history = monitoringClient.GetAlarmHistory(getAlarmHistoryRequest); foreach (var his in history.AlarmHistoryCollection.Entries) { Console.WriteLine($"\t\t|-summary:{his.Summary}"); Console.WriteLine($"\t\t| timestamp:{his.Timestamp}"); Console.WriteLine($"\t\t| timestampTriggered:{his.TimestampTriggered}"); } } } // Transactions Per Second (TPS) per-tenancy limit for this operation: 1. System.Threading.Thread.Sleep(1000); } }
public static async Task MainMonitoring() { logger.Info("Starting example"); var provider = new ConfigFileAuthenticationDetailsProvider("DEFAULT"); var compartmentId = Environment.GetEnvironmentVariable("OCI_COMPARTMENT_ID"); var metricCompartmentId = Environment.GetEnvironmentVariable("METRIC_COMPARTMENT_ID"); var destinations = Environment.GetEnvironmentVariable("DESTINATION"); var monitoringClient = new MonitoringClient(provider); string alarmId = null; var alarmDestinations = new List <string>(destinations.Split(',')); try { // Create a new alarm var createAlarmDetails = new CreateAlarmDetails { DisplayName = displayName, CompartmentId = compartmentId, MetricCompartmentId = metricCompartmentId, Namespace = ociNamespace, Query = metricQuery, Resolution = resolution, PendingDuration = pendingDuration, Severity = alertSeverity, Body = body, Destinations = alarmDestinations, RepeatNotificationDuration = repeatDuration, IsEnabled = true }; CreateAlarmRequest createAlarmRequest = new CreateAlarmRequest { CreateAlarmDetails = createAlarmDetails }; var createAlarmResponse = await monitoringClient.CreateAlarm(createAlarmRequest); logger.Info($"Created alarm: {displayName}"); alarmId = createAlarmResponse.Alarm.Id; Suppression suppression = new Suppression { Description = "suppress the alarm", TimeSuppressFrom = suppressFrom, TimeSuppressUntil = suppressUntil }; // Update the new alarm. UpdateAlarmDetails updateAlarmDetails = new UpdateAlarmDetails { Suppression = suppression }; UpdateAlarmRequest updateAlarmRequest = new UpdateAlarmRequest { AlarmId = alarmId, UpdateAlarmDetails = updateAlarmDetails }; UpdateAlarmResponse updateAlarmResponse = await monitoringClient.UpdateAlarm(updateAlarmRequest); logger.Info("Updated alarm"); RemoveAlarmSuppressionRequest removeAlarmSuppressionRequest = new RemoveAlarmSuppressionRequest { AlarmId = alarmId }; RemoveAlarmSuppressionResponse removeAlarmSuppressionResponse = await monitoringClient.RemoveAlarmSuppression(removeAlarmSuppressionRequest); logger.Info("removed suppression for the alarm"); // Get the new alarm GetAlarmRequest getAlarmRequest = new GetAlarmRequest { AlarmId = alarmId }; GetAlarmResponse getAlarmResponse = await monitoringClient.GetAlarm(getAlarmRequest); logger.Info($"Retrieved alarm for id: {getAlarmResponse.Alarm.Id}"); // Get alarm history GetAlarmHistoryRequest getAlarmHistoryRequest = new GetAlarmHistoryRequest { AlarmId = alarmId }; GetAlarmHistoryResponse getAlarmHistoryResponse = await monitoringClient.GetAlarmHistory(getAlarmHistoryRequest); logger.Info($"Alarm history for id: {alarmId}"); foreach (var alarmHistoryEntry in getAlarmHistoryResponse.AlarmHistoryCollection.Entries) { logger.Info($"summary: {alarmHistoryEntry.Summary}"); } // List alarms ListAlarmsRequest listAlarmsRequest = new ListAlarmsRequest { CompartmentId = compartmentId, DisplayName = displayName }; ListAlarmsResponse listAlarmsResponse = await monitoringClient.ListAlarms(listAlarmsRequest); logger.Info("Retrieved alarms"); logger.Info("================="); foreach (var alarmSummary in listAlarmsResponse.Items) { logger.Info($"Alarm: {alarmSummary.DisplayName}"); } // List alarm status ListAlarmsStatusRequest listAlarmsStatusRequest = new ListAlarmsStatusRequest { DisplayName = displayName, CompartmentId = compartmentId }; ListAlarmsStatusResponse listAlarmsStatusResponse = await monitoringClient.ListAlarmsStatus(listAlarmsStatusRequest); logger.Info("Retrieved alarms status"); logger.Info("======================="); foreach (var alarmsStatus in listAlarmsStatusResponse.Items) { logger.Info($"Status of the alarm: {alarmsStatus.DisplayName} is {alarmsStatus.Status}"); } } catch (Exception e) { logger.Error($"Exception: {e}"); } finally { if (alarmId != null) { DeleteAlarmRequest deleteAlarmRequest = new DeleteAlarmRequest { AlarmId = alarmId }; DeleteAlarmResponse deleteAlarmResponse = await monitoringClient.DeleteAlarm(deleteAlarmRequest); logger.Info($"Deleted alam: {displayName}"); } monitoringClient.Dispose(); } logger.Info("End example"); }