/// <summary> /// 查询告警规则列表,可以指定分页条件限制结果数量,可以指定排序规则。 /// </summary> /// <param name="cesV1Client"></param> private static void ListAlarms(CesClient cesClient) { ListAlarmsRequest listAlarmRequest = new ListAlarmsRequest() { //Start = "", Limit = 100, Order = "asc" }; try { ListAlarmsResponse listAlarmsResponse = cesClient.ListAlarms(listAlarmRequest); foreach (var metricAlarm in listAlarmsResponse.MetricAlarms) { Console.WriteLine("alarm_id: {0}, alarm_name: {1}", metricAlarm.AlarmId, metricAlarm.AlarmName); } } catch (RequestTimeoutException requestTimeoutException) { Console.WriteLine(requestTimeoutException.ErrorMessage); } catch (ServiceResponseException clientRequestException) { Console.WriteLine(clientRequestException.HttpStatusCode); Console.WriteLine(clientRequestException.ErrorCode); Console.WriteLine(clientRequestException.ErrorMsg); } catch (ConnectionException connectionException) { Console.WriteLine(connectionException.ErrorMessage); } }
protected override void ProcessRecord() { base.ProcessRecord(); ListAlarmsRequest request; try { request = new ListAlarmsRequest { CompartmentId = CompartmentId, OpcRequestId = OpcRequestId, Page = Page, Limit = Limit, DisplayName = DisplayName, LifecycleState = LifecycleState, SortBy = SortBy, SortOrder = SortOrder, CompartmentIdInSubtree = CompartmentIdInSubtree }; IEnumerable <ListAlarmsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.Items, true); } FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
/// <summary> /// Lists the alarms for the specified compartment. /// 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/ListAlarms.cs.html">here</a> to see an example of how to use ListAlarms API.</example> public async Task <ListAlarmsResponse> ListAlarms(ListAlarmsRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called listAlarms"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/alarms".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 <ListAlarmsResponse>(responseMessage)); } catch (Exception e) { logger.Error($"ListAlarms failed with error: {e.Message}"); throw; } }
/// <summary> /// 查询告警规则列表 /// </summary> public async Task <ListAlarmsResponse> ListAlarmsAsync(ListAlarmsRequest listAlarmsRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); string urlPath = HttpUtils.AddUrlPath("/V1.0/{project_id}/alarms", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, listAlarmsRequest); HttpResponseMessage response = await DoHttpRequestAsync("GET", request); return(JsonUtils.DeSerialize <ListAlarmsResponse>(response)); }
/// <summary> /// Lists one or more alarms. The operation returns only the metadata associated with /// each alarm. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListAlarms service method.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListAlarms service method, as returned by IoTEventsData.</returns> /// <exception cref="Amazon.IoTEventsData.Model.InternalFailureException"> /// An internal failure occurred. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.InvalidRequestException"> /// The request was invalid. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ResourceNotFoundException"> /// The resource was not found. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ServiceUnavailableException"> /// The service is currently unavailable. /// </exception> /// <exception cref="Amazon.IoTEventsData.Model.ThrottlingException"> /// The request could not be completed due to throttling. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-data-2018-10-23/ListAlarms">REST API Reference for ListAlarms Operation</seealso> public virtual Task <ListAlarmsResponse> ListAlarmsAsync(ListAlarmsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var options = new InvokeOptions(); options.RequestMarshaller = ListAlarmsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListAlarmsResponseUnmarshaller.Instance; return(InvokeAsync <ListAlarmsResponse>(request, options, cancellationToken)); }
internal virtual ListAlarmsResponse ListAlarms(ListAlarmsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListAlarmsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListAlarmsResponseUnmarshaller.Instance; return(Invoke <ListAlarmsResponse>(request, options)); }
/// <summary> /// Creates a new enumerable which will iterate over the responses received from the ListAlarms operation. This enumerable /// will fetch more data from the server as needed. /// </summary> /// <param name="request">The request object containing the details to send</param> /// <param name="retryConfiguration">The configuration for retrying, may be null</param> /// <param name="cancellationToken">The cancellation token object</param> /// <returns>The enumerator, which supports a simple iteration over a collection of a specified type</returns> public IEnumerable <ListAlarmsResponse> ListAlarmsResponseEnumerator(ListAlarmsRequest request, Common.Retry.RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { return(new Common.Utils.ResponseEnumerable <ListAlarmsRequest, ListAlarmsResponse>( response => response.OpcNextPage, input => { if (!string.IsNullOrEmpty(input)) { request.Page = input; } return request; }, request => client.ListAlarms(request, retryConfiguration, cancellationToken) )); }
/// <summary> /// Lists the alarms for the specified compartment. 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 <ListAlarmsResponse> ListAlarms(ListAlarmsRequest param) { var uri = new Uri($"{GetEndPoint(MonitoringServices.Alarms, this.Region)}?{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 ListAlarmsResponse() { Items = JsonSerializer.Deserialize <List <AlarmSummary> >(response), OpcNextPage = webResponse.Headers.Get("opc-next-page"), OpcRequestId = webResponse.Headers.Get("opc-request-id") }); } }
protected override void ProcessRecord() { base.ProcessRecord(); ListAlarmsRequest request; try { request = new ListAlarmsRequest { CompartmentId = CompartmentId, OpcRequestId = OpcRequestId, Page = Page, Limit = Limit, DisplayName = DisplayName, LifecycleState = LifecycleState, SortBy = SortBy, SortOrder = SortOrder, CompartmentIdInSubtree = CompartmentIdInSubtree }; IEnumerable <ListAlarmsResponse> responses = GetRequestDelegate().Invoke(request); foreach (var item in responses) { response = item; WriteOutput(response, response.Items, true); } if (!ParameterSetName.Equals(AllPageSet) && !ParameterSetName.Equals(LimitSet) && response.OpcNextPage != null) { WriteWarning("This operation supports pagination and not all resources were returned. Re-run using the -All option to auto paginate and list all resources."); } FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
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"); }