in pkg/operator/operator_config.go [416:485]
func (r *operatorConfigReconciler) ensureAlertmanagerConfigSecret(ctx context.Context, spec *monitoringv1.ManagedAlertmanagerSpec) error {
logger, _ := logr.FromContext(ctx)
pubNamespace := r.opts.PublicNamespace
// This is the default, no-op secret config. If we find a user-defined config,
// we will overwrite the default data with the user's data.
// If we don't find a user config, we will still proceed with ensuring this
// default secret exists (so that the alertmanager pod doesn't crash due to no
// config found). This flow also handles user deletion/disabling of managed AM.
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: AlertmanagerSecretName,
Namespace: r.opts.OperatorNamespace,
Annotations: componentAnnotations(),
Labels: alertmanagerLabels(),
},
Data: map[string][]byte{AlertmanagerConfigKey: []byte(AlertmanagerNoOpConfig)},
}
// Set defaults on public namespace secret.
var sel = &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: AlertmanagerPublicSecretName,
},
Key: AlertmanagerPublicSecretKey,
}
// Overwrite defaults if specified.
if spec != nil && spec.ConfigSecret != nil {
sel.Name = spec.ConfigSecret.Name
sel.Key = spec.ConfigSecret.Key
}
// Try and read the secret for use.
b, err := getSecretKeyBytes(ctx, r.client, pubNamespace, sel)
if err != nil {
if !apierrors.IsNotFound(err) {
return err
}
// If the config secret is not found, it may have been manually deleted
// (ie, to disable managed AM), so we will continue with restoring the no-op config
// so that the managed AM pod doesn't crash loop.
logger.Info(fmt.Sprintf("alertmanager config secret not found in namespace %s: %s", pubNamespace, err.Error()))
} else {
config := alertmanagerConfig{}
if err := yaml.Unmarshal(b, &config); err != nil {
return fmt.Errorf("load alertmanager config: %w", err)
}
// Only set the value if we need to. This provides a fail-safe in case users change our
// Alertmanager image with their own. Otherwise, if we always set and they change the image,
// their Alertmanager will fail unless they have our patch.
if config.GoogleCloud.ExternalURL != spec.ExternalURL {
config.GoogleCloud.ExternalURL = spec.ExternalURL
b, err = yaml.Marshal(config)
if err != nil {
return fmt.Errorf("marshal alertmanager config: %w", err)
}
}
secret.Data[AlertmanagerConfigKey] = b
}
if err := r.client.Update(ctx, secret); apierrors.IsNotFound(err) {
if err := r.client.Create(ctx, secret); err != nil {
return fmt.Errorf("create alertmanager config secret: %w", err)
}
} else if err != nil {
return fmt.Errorf("update alertmanager config secret: %w", err)
}
return nil
}