/// <summary> /// Generates a Data request for the create alarm web service method from the Create Alarm Request. /// </summary> /// <param name="request"></param> /// <returns></returns> private Data GenerateAlarmRequest(CreateAlarmRequest request) { //hook this up to the duncan web service to create the event //create the request var dataRequest = new Data { Request = new DataRequest { WorkOrder = new DataRequestWorkOrder[1] } }; //add a single work order and a single alarm to that work order to pass the data to duncn so we can detemrine the eventUID dataRequest.Request.WorkOrder[0] = new DataRequestWorkOrder { WorkOrderId = request.WorkOrderId.ToString(), mid = request.AssetId.ToString(), aid = request.AreaId.ToString(), cid = request.CustomerId.ToString(), ActiveAlarm = new DataRequestWorkOrderActiveAlarm[1] }; //now add the alarm dataRequest.Request.WorkOrder[0].ActiveAlarm[0] = new DataRequestWorkOrderActiveAlarm { EventCode = request.EventCode.ToString(), EventSource = request.EventSource.ToString(), Notes = request.Notes, TimeOfNotification = request.LocalTime.AddMinutes(1), TimeOfOccurrance = request.LocalTime }; return(dataRequest); }
/// <summary> /// Creates a new alarm in 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/CreateAlarm.cs.html">here</a> to see an example of how to use CreateAlarm API.</example> public async Task <CreateAlarmResponse> CreateAlarm(CreateAlarmRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called createAlarm"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/alarms".Trim('/'))); HttpMethod method = new HttpMethod("POST"); 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 <CreateAlarmResponse>(responseMessage)); } catch (Exception e) { logger.Error($"CreateAlarm failed with error: {e.Message}"); throw; } }
/// <summary> /// 创建告警规则 /// </summary> public async Task <CreateAlarmResponse> CreateAlarmAsync(CreateAlarmRequest createAlarmRequest) { Dictionary <string, string> urlParam = new Dictionary <string, string>(); string urlPath = HttpUtils.AddUrlPath("/V1.0/{project_id}/alarms", urlParam); SdkRequest request = HttpUtils.InitSdkRequest(urlPath, "application/json;charset=UTF-8", createAlarmRequest); HttpResponseMessage response = await DoHttpRequestAsync("POST", request); return(JsonUtils.DeSerialize <CreateAlarmResponse>(response)); }
/// <summary> /// 本接口用于创建告警策略。 /// </summary> /// <param name="req"><see cref="CreateAlarmRequest"/></param> /// <returns><see cref="CreateAlarmResponse"/></returns> public CreateAlarmResponse CreateAlarmSync(CreateAlarmRequest req) { JsonResponseModel <CreateAlarmResponse> rsp = null; try { var strResp = this.InternalRequestSync(req, "CreateAlarm"); rsp = JsonConvert.DeserializeObject <JsonResponseModel <CreateAlarmResponse> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return(rsp.Response); }
protected override void ProcessRecord() { base.ProcessRecord(); CreateAlarmRequest request; try { request = new CreateAlarmRequest { CreateAlarmDetails = CreateAlarmDetails, OpcRequestId = OpcRequestId, OpcRetryToken = OpcRetryToken }; response = client.CreateAlarm(request).GetAwaiter().GetResult(); WriteOutput(response, response.Alarm); FinishProcessing(response); } catch (Exception ex) { TerminatingErrorDuringExecution(ex); } }
/// <summary> /// Calls a duncan Web service that will determine if the alarm is already open and return the ID of that, or create a new event ID and return that one. /// </summary> /// <param name="request"></param> /// <returns></returns> public CreateAlarmResponse CreateAlarm(CreateAlarmRequest request) { //fix up the response with some default values var alarmResponse = new CreateAlarmResponse { IsValid = false }; var dataRequest = GenerateAlarmRequest(request); //now that we have our data request, we need to send it to duncan and get the response. string strUrl = ConfigurationManager.AppSettings[Constants.FieldMaintenance.WebServiceCreateAlarmName]; var serializedDataRequest = Serialize(dataRequest); if (string.IsNullOrEmpty(serializedDataRequest)) { return(alarmResponse); } byte[] dataByte = StringToByteArray(serializedDataRequest); var response = PostRequest(strUrl, dataByte); return(GetAlarmResponse(response, alarmResponse)); }
/// <summary> /// Creates a new alarm in 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 <CreateAlarmResponse> CreateAlarm(CreateAlarmRequest param) { var uri = new Uri($"{GetEndPoint(MonitoringServices.Alarms, this.Region)}"); var httpRequestHeaderParam = new HttpRequestHeaderParam() { OpcRetryToken = param.OpcRetryToken, OpcRequestId = param.OpcRequestId }; using (var webResponse = await this.RestClientAsync.Post(uri, param.CreateAlarmDetails, httpRequestHeaderParam)) using (var stream = webResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { var response = await reader.ReadToEndAsync(); return(new CreateAlarmResponse() { AlarmModel = JsonSerializer.Deserialize <AlarmModel>(response), OpcRequestId = webResponse.Headers.Get("opc-request-id"), Etag = webResponse.Headers.Get("etag") }); } }
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"); }
/// <summary> /// 创建报警 /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public async Task <CreateAlarmResponse> CreateAlarm(CreateAlarmRequest request) { return(await new CreateAlarmExecutor().Client(this).Execute <CreateAlarmResponse, CreateAlarmResult, CreateAlarmRequest>(request).ConfigureAwait(false)); }
/// <summary> /// 创建报警 /// </summary> /// <param name="request">请求参数信息</param> /// <returns>请求结果信息</returns> public CreateAlarmResponse CreateAlarm(CreateAlarmRequest request) { return(new CreateAlarmExecutor().Client(this).Execute <CreateAlarmResponse, CreateAlarmResult, CreateAlarmRequest>(request)); }
/// <summary> /// 创建一条告警规则。 /// </summary> /// <param name="cesClient"></param> private static void CreateAlarm(CesClient cesClient) { CreateAlarmRequest createAlarmRequest = new CreateAlarmRequest() { Body = new CreateAlarmRequestBody() { AlarmName = "ces-sdk-02", AlarmDescription = "create ECS alram", Metric = new MetricForAlarm { Namespace = "AGT.ECS", Dimensions = new List <MetricsDimension>() { new MetricsDimension() { Name = "instance_id", Value = "326277f5-ee01-4751-959e-8e9a364b6b3c" } }, MetricName = "cpu_usage_idle" }, Condition = new Condition() { Period = 1, Filter = "average", ComparisonOperator = "<", Value = 20, Unit = "%", Count = 3 }, AlarmEnabled = true, AlarmActionEnabled = true, AlarmLevel = 2, AlarmActions = new List <AlarmActions>() { new AlarmActions() { Type = "notification", NotificationList = new List <string>() { "urn:smn:br-iaas-odin1:0605767fc300d5762ffdc01c5bba0cce:ces_test" } } }, OkActions = new List <AlarmActions>() { new AlarmActions() { Type = "notification", NotificationList = new List <string>() { "urn:smn:br-iaas-odin1:0605767fc300d5762ffdc01c5bba0cce:ces_test" } } }, InsufficientdataActions = new List <AlarmActions>() { new AlarmActions() { Type = "notification", NotificationList = new List <string>() { "urn:smn:br-iaas-odin1:0605767fc300d5762ffdc01c5bba0cce:ces_test" } } } } }; try { CreateAlarmResponse createAlarmResponse = cesClient.CreateAlarm(createAlarmRequest); Console.WriteLine("alarm_id: {0}", createAlarmResponse.AlarmId); } 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); } }
public ActionResult CreateEvent(TechnicianCreateEventModel model, IEnumerable <HttpPostedFileBase> files, FormCollection coll) { var mobileWorkOrderFactory = (new TechnicianWorkOrderFactory(Session[Constants.Security.MaintenanceConnectionStringSessionVariableName].ToString(), Session[Constants.Security.ConnectionStringSessionVariableName].ToString())); //create the work order event in RBAC - //get the selected event code the user chose var eventCode = mobileWorkOrderFactory.GetEventCode(model.SelectedFaultDescription, CurrentCity.Id); if (eventCode == null) { //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Event Code not found. Try again.")); //repopulate the options for the lists model.FaultDescriptions = mobileWorkOrderFactory.GetFaultDescriptions(CurrentCity.Id); model.AssetIdOptions = GetAssetIdOptions(); //send them back to the view with the error return(View("CreateEvent", model)); } //first check to see if the selected asset key is valid //message / error handling if needed bool assetIsValid = true; if (string.IsNullOrEmpty(model.SelectedAssetKey) || model.SelectedAssetKey.Split('|').Count() != 3) { //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Invalid Asset.")); //repopulate the options for the lists model.FaultDescriptions = mobileWorkOrderFactory.GetFaultDescriptions(CurrentCity.Id); model.AssetIdOptions = GetAssetIdOptions(); //send them back to the view with the error return(View("CreateEvent", model)); } //once it all checks out, create the work order, create the event id, and add the images, then send to the listing page //break out the SelectedAssetKey of the model = CustomerId | AreaId | AssetId var ids = model.SelectedAssetKey.Split('|'); var areaid = ids[1]; var assetid = ids[2]; int areaID = int.Parse(areaid); int assetID = int.Parse(assetid); //create work order var workOrderId = mobileWorkOrderFactory.CreateWorkOrder(assetID, model.SelectedFaultDescription, CurrentCity.Id, areaID, CurrentCity.LocalTime); //get event ID var webServiceFactory = new WebServiceFactory(); //create the event via the web service factory. //create the Create Alarm Request object to pass to the web services var createAlarmRequest = new CreateAlarmRequest { AreaId = areaID, AssetId = assetID, CustomerId = CurrentCity.Id, EventCode = eventCode.EventCode1, EventSource = eventCode.EventSource, LocalTime = CurrentCity.LocalTime, Notes = model.Notes, WorkOrderId = workOrderId }; var createAlarmResponse = webServiceFactory.CreateAlarm(createAlarmRequest); //check the response, if it failed, (eventUID is -1 or slaDue is minvalue if (!createAlarmResponse.IsValid) { //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Event could not be created: " + createAlarmResponse.ErrorMessage)); //repopulate the options for the lists model.FaultDescriptions = mobileWorkOrderFactory.GetFaultDescriptions(CurrentCity.Id); model.AssetIdOptions = GetAssetIdOptions(); //send them back to the view with the error return(View("CreateEvent", model)); } //we found the event code, continue. just set the sla to 2 hours int he future, it will be updated below. var workOrderEventId = mobileWorkOrderFactory.CreateWorkOrderEvent(createAlarmResponse.EventUID, workOrderId, eventCode.EventCode1, CurrentCity.LocalTime, eventCode.EventDescVerbose, createAlarmResponse.SlaDue, eventCode.AlarmTier, model.Notes, false, false, (int)WorkOrderEventStatus.Open); //every time a event is created, resolved , etc, we have to update the sladue and highest severity, so lets do that now mobileWorkOrderFactory.UpdateEventAggregateInfo(workOrderId); //now we need to add the images to the work order (if there are any) if (files != null) { foreach (var file in files) { mobileWorkOrderFactory.CreateWorkOrderImage(workOrderId, ImageFactory.StreamToByteArray(file.InputStream), CurrentCity.LocalTime); } } //now that it is created correctly, send them to the listing page so they can see thier new owrk order. return(RedirectToAction("WorkOrders")); }
public ActionResult CreateEventId(DispatcherCreateEventModel model) { //message / error handling if needed //once it all checks out, create the work order, create the event id, then send to the listing page //break out the SelectedAssetKey of the model = CustomerId | AreaId | AssetId var ids = model.SelectedAssetKey.Split('|'); var customerId = ids[0]; var areaid = ids[1]; var assetid = ids[2]; int customerID = int.Parse(customerId); //instantiate the factory with the current maintenance group and the selected city for the asset var selectedCustomer = CurrentCity.MaintenanceCustomers.FirstOrDefault(x => x.Id == customerID); if (selectedCustomer != null) { var workOrderFactory = (new DispatcherWorkOrderFactory(selectedCustomer.PemsConnectionStringName, CurrentCity.MaintenanceConnectionStringName)); //create the work order event in RBAC - //get the selected event code the user chose var eventCode = workOrderFactory.GetEventCode(model.SelectedFaultDescription, selectedCustomer.Id); if (eventCode == null) { //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Event Code not found. Try again.")); //repopulate the options for the lists //we have to pull a facotory for each customer, since their conneciton string could be different. foreach (var maintenanceCustomer in CurrentCity.MaintenanceCustomers) { var woFactory = (new DispatcherWorkOrderFactory(maintenanceCustomer)); model.FaultDescriptions.AddRange(woFactory.GetFaultDescriptions(maintenanceCustomer.Id)); var customerAssetOptions = woFactory.GetAssetsForCustomer(maintenanceCustomer.Id); //fix up all the customer names for the asset options customerAssetOptions.ForEach(x => x.CustomerName = maintenanceCustomer.DisplayName); model.AssetIdOptions.AddRange(customerAssetOptions); } //send them back to the view with the error return(View("CreateEventId", model)); } int areaID = int.Parse(areaid); int assetID = int.Parse(assetid); //create work order var workOrderId = workOrderFactory.CreateWorkOrder(assetID, model.SelectedFaultDescription, selectedCustomer.Id, areaID, selectedCustomer.LocalTime, model.CrossStreet, model.Notes); //get event ID var webServiceFactory = new WebServiceFactory(); //create the event via the web service factory. //create the Create Alarm Request object to pass to the web services var createAlarmRequest = new CreateAlarmRequest { AreaId = areaID, AssetId = assetID, CustomerId = selectedCustomer.Id, EventCode = eventCode.EventCode1, EventSource = eventCode.EventSource, LocalTime = selectedCustomer.LocalTime, Notes = model.Notes, WorkOrderId = workOrderId }; var createAlarmResponse = webServiceFactory.CreateAlarm(createAlarmRequest); //check the response, if it failed, (eventUID is -1 or slaDue is minvalue if (!createAlarmResponse.IsValid) { //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Event could not be created: " + createAlarmResponse.ErrorMessage)); //repopulate the options for the lists //we have to pull a facotory for each customer, since their conneciton string could be different. foreach (var maintenanceCustomer in CurrentCity.MaintenanceCustomers) { var woFactory = (new DispatcherWorkOrderFactory(maintenanceCustomer)); model.FaultDescriptions.AddRange(woFactory.GetFaultDescriptions(maintenanceCustomer.Id)); var customerAssetOptions = woFactory.GetAssetsForCustomer(maintenanceCustomer.Id); //fix up all the customer names for the asset options customerAssetOptions.ForEach(x => x.CustomerName = maintenanceCustomer.DisplayName); model.AssetIdOptions.AddRange(customerAssetOptions); } //send them back to the view with the error return(View("CreateEventId", model)); } //we found the event code, continue. just set the sla to 2 hours int he future, it will be updated below. var workOrderEventId = workOrderFactory.CreateWorkOrderEvent(createAlarmResponse.EventUID, workOrderId, eventCode.EventCode1, CurrentCity.LocalTime, eventCode.EventDescVerbose, createAlarmResponse.SlaDue, eventCode.AlarmTier, model.Notes, false, false, (int)WorkOrderEventStatus.Open); //every time a event is created, resolved , etc, we have to update the sladue and highest severity, so lets do that now workOrderFactory.UpdateEventAggregateInfo(workOrderId); //now that it is created correctly, send them to the listing page so they can see thier new owrk order. return(RedirectToAction("WorkOrderDetail", "WorkOrders", new { workOrderId })); } //fail here, no customer found, refresh page, add error, whatever //if we got this far, something failed. add error to model and display to user ModelState.AddModelError(Constants.ViewData.ModelStateStatusKey, (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.StatusMessage, "Customer Not Found. Try again.")); //repopulate the options for the lists //we have to pull a facotory for each customer, since their conneciton string could be different. foreach (var maintenanceCustomer in CurrentCity.MaintenanceCustomers) { var woFactory = (new DispatcherWorkOrderFactory(maintenanceCustomer)); model.FaultDescriptions.AddRange(woFactory.GetFaultDescriptions(maintenanceCustomer.Id)); var customerAssetOptions = woFactory.GetAssetsForCustomer(maintenanceCustomer.Id); //fix up all the customer names for the asset options customerAssetOptions.ForEach(x => x.CustomerName = maintenanceCustomer.DisplayName); model.AssetIdOptions.AddRange(customerAssetOptions); } return(View("CreateEventId", model)); }