func UpdateAlertingRule()

in internal/clients/kibana/alerting.go [223:302]


func UpdateAlertingRule(ctx context.Context, apiClient ApiClient, rule models.AlertingRule) (*models.AlertingRule, diag.Diagnostics) {
	client, err := apiClient.GetAlertingClient()
	if err != nil {
		return nil, diag.FromErr(err)
	}

	ctxWithAuth := apiClient.SetAlertingAuthContext(ctx)

	var alertDelay *alerting.AlertDelay

	if alerting.IsNil(rule.AlertDelay) {
		alertDelay = nil
	} else {
		alertDelay = &alerting.AlertDelay{
			Active: *rule.AlertDelay,
		}
	}

	reqModel := alerting.UpdateRuleRequest{
		Actions:    ruleActionsToActionsInner((rule.Actions)),
		Name:       rule.Name,
		NotifyWhen: (*alerting.NotifyWhen)(rule.NotifyWhen),
		Params:     rule.Params,
		Schedule: alerting.Schedule{
			Interval: &rule.Schedule.Interval,
		},
		Tags:       rule.Tags,
		Throttle:   *alerting.NewNullableString(rule.Throttle),
		AlertDelay: alertDelay,
	}

	req := client.UpdateRule(ctxWithAuth, rule.RuleID, rule.SpaceID).KbnXsrf("true").UpdateRuleRequest(reqModel)

	ruleRes, res, err := req.Execute()
	if err != nil && res == nil {
		return nil, diag.FromErr(err)
	}

	defer res.Body.Close()

	if diags := utils.CheckHttpError(res, "Unable to update alerting rule"); diags.HasError() {
		return nil, diags
	}

	if ruleRes == nil {
		return nil, diag.Diagnostics{diag.Diagnostic{
			Severity: diag.Error,
			Summary:  "Update rule returned an empty response",
			Detail:   fmt.Sprintf("Update rule returned an empty response with HTTP status code [%d].", res.StatusCode),
		}}
	}

	rule.RuleID = ruleRes.Id

	shouldBeEnabled := rule.Enabled != nil && *rule.Enabled

	if shouldBeEnabled && !ruleRes.Enabled {
		res, err := client.EnableRule(ctxWithAuth, rule.RuleID, rule.SpaceID).KbnXsrf("true").Execute()
		if err != nil && res == nil {
			return nil, diag.FromErr(err)
		}

		if diags := utils.CheckHttpError(res, "Unable to enable alerting rule"); diags.HasError() {
			return nil, diag.FromErr(err)
		}
	}

	if !shouldBeEnabled && ruleRes.Enabled {
		res, err := client.DisableRule(ctxWithAuth, rule.RuleID, rule.SpaceID).KbnXsrf("true").Execute()
		if err != nil && res == nil {
			return nil, diag.FromErr(err)
		}

		if diags := utils.CheckHttpError(res, "Unable to disable alerting rule"); diags.HasError() {
			return nil, diag.FromErr(err)
		}
	}

	return ruleResponseToModel(rule.SpaceID, ruleRes), diag.Diagnostics{}
}