Skip to content

Commit

Permalink
feat(alertmanagerconfig): statuses and stuff
Browse files Browse the repository at this point in the history
Signed-off-by: Robin Opletal <[email protected]>
  • Loading branch information
fourstepper committed Jun 24, 2024
1 parent eaf7640 commit 3d0bd43
Show file tree
Hide file tree
Showing 9 changed files with 142 additions and 16 deletions.
8 changes: 7 additions & 1 deletion api/osko/v1alpha1/alertmanagerconfig_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,16 @@ type AlertManagerConfigSpec struct {
}

// AlertManagerConfigStatus defines the observed state of AlertManagerConfig
type AlertManagerConfigStatus struct{}
type AlertManagerConfigStatus struct {
Conditions []metav1.Condition `json:"conditions,omitempty"`
LastEvaluationTime metav1.Time `json:"lastEvaluationTime,omitempty"`
Ready string `json:"ready,omitempty"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=.status.ready,description="The reason for the current status of the AlertmanagerConfig resource"
// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=.metadata.creationTimestamp,description="The time when the AlertmanagerConfig resource was created"

// AlertManagerConfig is the Schema for the alertmanagerconfigs API
type AlertManagerConfig struct {
Expand Down
10 changes: 9 additions & 1 deletion api/osko/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

86 changes: 85 additions & 1 deletion config/crd/bases/osko.dev_alertmanagerconfigs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@ spec:
singular: alertmanagerconfig
scope: Namespaced
versions:
- name: v1alpha1
- additionalPrinterColumns:
- description: The reason for the current status of the AlertmanagerConfig resource
jsonPath: .status.ready
name: Ready
type: string
- description: The time when the AlertmanagerConfig resource was created
jsonPath: .metadata.creationTimestamp
name: Age
type: date
name: v1alpha1
schema:
openAPIV3Schema:
description: AlertManagerConfig is the Schema for the alertmanagerconfigs
Expand Down Expand Up @@ -58,6 +67,81 @@ spec:
type: object
status:
description: AlertManagerConfigStatus defines the observed state of AlertManagerConfig
properties:
conditions:
items:
description: "Condition contains details for one aspect of the current
state of this API Resource.\n---\nThis struct is intended for
direct use as an array at the field path .status.conditions. For
example,\n\n\n\ttype FooStatus struct{\n\t // Represents the
observations of a foo's current state.\n\t // Known .status.conditions.type
are: \"Available\", \"Progressing\", and \"Degraded\"\n\t //
+patchMergeKey=type\n\t // +patchStrategy=merge\n\t // +listType=map\n\t
\ // +listMapKey=type\n\t Conditions []metav1.Condition `json:\"conditions,omitempty\"
patchStrategy:\"merge\" patchMergeKey:\"type\" protobuf:\"bytes,1,rep,name=conditions\"`\n\n\n\t
\ // other fields\n\t}"
properties:
lastTransitionTime:
description: |-
lastTransitionTime is the last time the condition transitioned from one status to another.
This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.
format: date-time
type: string
message:
description: |-
message is a human readable message indicating details about the transition.
This may be an empty string.
maxLength: 32768
type: string
observedGeneration:
description: |-
observedGeneration represents the .metadata.generation that the condition was set based upon.
For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date
with respect to the current state of the instance.
format: int64
minimum: 0
type: integer
reason:
description: |-
reason contains a programmatic identifier indicating the reason for the condition's last transition.
Producers of specific condition types may define expected values and meanings for this field,
and whether the values are considered a guaranteed API.
The value should be a CamelCase string.
This field may not be empty.
maxLength: 1024
minLength: 1
pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$
type: string
status:
description: status of the condition, one of True, False, Unknown.
enum:
- "True"
- "False"
- Unknown
type: string
type:
description: |-
type of condition in CamelCase or in foo.example.com/CamelCase.
---
Many .condition.type values are consistent across resources like Available, but because arbitrary conditions can be
useful (see .node.status.conditions), the ability to deconflict is important.
The regex it matches is (dns1123SubdomainFmt/)?(qualifiedNameFmt)
maxLength: 316
pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$
type: string
required:
- lastTransitionTime
- message
- reason
- status
- type
type: object
type: array
lastEvaluationTime:
format: date-time
type: string
ready:
type: string
type: object
type: object
served: true
Expand Down
2 changes: 0 additions & 2 deletions config/samples/config_secret.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ stringData:
alertmanager.yaml: |-
route:
receiver: 'default-receiver'
receivers:
- name: 'default-receiver'
email_configs:
Expand All @@ -20,4 +19,3 @@ stringData:
auth_username: 'alertmanager'
auth_password: 'password'
auth_identity: '[email protected]'
5 changes: 3 additions & 2 deletions config/samples/openslo_v1_datasource.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# TODO: heureka-specific sample, should be replaced in the further-future with a more comprehensive dev environment
# ref.: https://github.com/oskoperator/osko/issues/45
apiVersion: openslo.com/v1
kind: Datasource
metadata:
Expand All @@ -10,7 +8,10 @@ spec:
description: Mimir Datasource for logging tenant
type: mimir
connectionDetails:
address: https://mimir.monitoring.dev.heu.group/
address: http://localhost:9009/
sourceTenants:
- gatekeeper-system
targetTenant: gatekeeper-system
- monitoring
targetTenant: monitoring
1 change: 0 additions & 1 deletion devel/mimir/alertmanager-default-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ data:
route:
group_wait: 0s
receiver: empty-receiver
receivers:
# In this example we're not going to send any notification out of Alertmanager.
- name: 'empty-receiver'
4 changes: 2 additions & 2 deletions devel/mimir/configmap.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ data:
dir: /tmp/mimir/data/tsdb
tsdb:
dir: /tmp/mimir/tsdb
alertmanager:
data_dir: /tmp/mimir/alertmanager
enable_api: true
fallback_config_file: /tmp/mimir/alertmanager-config/alertmanager-fallback-config.yaml
alertmanager_storage:
backend: filesystem
filesystem:
Expand Down
21 changes: 19 additions & 2 deletions internal/controller/osko/alertmanagerconfig_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package osko
import (
"context"
"fmt"
"github.com/oskoperator/osko/internal/utils"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/handler"
"time"
Expand Down Expand Up @@ -65,6 +67,7 @@ func (r *AlertManagerConfigReconciler) Reconcile(ctx context.Context, req ctrl.R
}

log.V(1).Info("Getting datasourceRef", "datasourceRef", amc.ObjectMeta.Annotations["osko.dev/datasourceRef"])

// Get DS from AMC's ref
err = r.Get(ctx, client.ObjectKey{Name: amc.ObjectMeta.Annotations["osko.dev/datasourceRef"], Namespace: amc.Namespace}, ds)
if err != nil {
Expand All @@ -89,7 +92,11 @@ func (r *AlertManagerConfigReconciler) Reconcile(ctx context.Context, req ctrl.R
err = r.Get(ctx, client.ObjectKey{Namespace: amc.Spec.SecretRef.Namespace, Name: amc.Spec.SecretRef.Name}, secret)
if err != nil {
if apierrors.IsNotFound(err) {
log.Error(err, "Secret not found")
if err = utils.UpdateStatus(ctx, amc, r.Client, "Ready", metav1.ConditionFalse, "Secret from secretRef not found"); err != nil {
log.Error(err, "Failed to update amc status")
return ctrl.Result{}, err
}
r.Recorder.Event(amc, "Warning", "SecretNotFound", "Secret from secretRef not found")
return ctrl.Result{}, nil
}
log.Error(err, "Failed to get secret")
Expand All @@ -98,7 +105,11 @@ func (r *AlertManagerConfigReconciler) Reconcile(ctx context.Context, req ctrl.R

yamlData, ok := secret.Data["alertmanager.yaml"]
if !ok {
log.Error(err, "alertmanager.yaml not found in secret")
if err = utils.UpdateStatus(ctx, amc, r.Client, "Ready", metav1.ConditionFalse, "alertmanager.yaml key not found in secret"); err != nil {
log.Error(err, "Failed to update amc status")
return ctrl.Result{}, err
}
r.Recorder.Event(amc, "Warning", "KeyNotFound", "alertmanager.yaml key not found in secret")
return ctrl.Result{}, nil
}

Expand All @@ -114,6 +125,12 @@ func (r *AlertManagerConfigReconciler) Reconcile(ctx context.Context, req ctrl.R
return ctrl.Result{}, err
}

r.Recorder.Event(amc, "Normal", "AlertManagerConfigCreated", "AlertManagerConfig created successfully")
if err = utils.UpdateStatus(ctx, amc, r.Client, "Ready", metav1.ConditionTrue, "PrometheusRule created"); err != nil {
log.V(1).Error(err, "Failed to update SLO status")
return ctrl.Result{}, err
}

return ctrl.Result{}, nil
}

Expand Down
21 changes: 17 additions & 4 deletions internal/utils/common_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func updateCondition(conditions []metav1.Condition, newCondition metav1.Conditio
return updatedConditions
}

func UpdateStatus(ctx context.Context, slo *openslov1.SLO, r client.Client, conditionType string, status metav1.ConditionStatus, message string) error {
func UpdateStatus(ctx context.Context, obj client.Object, r client.Client, conditionType string, status metav1.ConditionStatus, message string) error {
// Update the conditions based on provided arguments
condition := metav1.Condition{
Type: conditionType,
Expand All @@ -101,9 +101,22 @@ func UpdateStatus(ctx context.Context, slo *openslov1.SLO, r client.Client, cond
Message: message,
LastTransitionTime: metav1.NewTime(time.Now()),
}
slo.Status.Conditions = updateCondition(slo.Status.Conditions, condition)
slo.Status.Ready = string(status)
return r.Status().Update(ctx, slo)

statusField := reflect.ValueOf(obj).Elem().FieldByName("Status")

conditionsField := statusField.FieldByName("Conditions")
if conditionsField.IsValid() && conditionsField.CanSet() {
conditions := conditionsField.Interface().([]metav1.Condition)
updatedConditions := updateCondition(conditions, condition)
conditionsField.Set(reflect.ValueOf(updatedConditions))
}

readyField := statusField.FieldByName("Ready")
if readyField.IsValid() && readyField.CanSet() {
readyField.SetString(string(status))
}

return r.Status().Update(ctx, obj)
}

func (m MetricLabel) NewMetricLabelCompiler(rule *monitoringv1.Rule, window string) string {
Expand Down

0 comments on commit 3d0bd43

Please sign in to comment.