Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions internal/common/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
Copyright 2026.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common //nolint:revive // common is the established package name for multi-group shared code

import (
"context"
"maps"

env "github.com/openstack-k8s-operators/lib-common/modules/common/env"
helper "github.com/openstack-k8s-operators/lib-common/modules/common/helper"
"github.com/openstack-k8s-operators/lib-common/modules/common/secret"
util "github.com/openstack-k8s-operators/lib-common/modules/common/util"
"sigs.k8s.io/controller-runtime/pkg/client"
)

// ConfigGeneratorOptions configures template-based service config generation.
type ConfigGeneratorOptions struct {
ConfigName string
TemplateDir string
BaseExtraTemplates map[string]string
AdditionalTemplates map[string]string
CommonTemplates []string
TemplateParameters map[string]any
ExtraData map[string]string
Labels map[string]string
WithScripts bool
}

// GenerateConfigs renders service configuration secrets from templates.
func (r *ReconcilerBase) GenerateConfigs(
ctx context.Context,
h *helper.Helper,
instance client.Object,
envVars *map[string]env.Setter,
opts ConfigGeneratorOptions,
) error {
if opts.TemplateDir == "" {
return ErrTemplateDirUnset
}

extraTemplates := map[string]string{}
maps.Copy(extraTemplates, opts.BaseExtraTemplates)
maps.Copy(extraTemplates, opts.AdditionalTemplates)

cms := []util.Template{
{
Name: opts.ConfigName,
Namespace: instance.GetNamespace(),
Type: util.TemplateTypeConfig,
InstanceType: instance.GetObjectKind().GroupVersionKind().Kind,
MultiTemplateDir: opts.TemplateDir,
ConfigOptions: opts.TemplateParameters,
Labels: opts.Labels,
CustomData: opts.ExtraData,
Annotations: map[string]string{},
AdditionalTemplate: extraTemplates,
CommonTemplates: opts.CommonTemplates,
},
}
if opts.WithScripts {
cms = append(cms, util.Template{
Name: GetScriptSecretName(instance.GetName()),
Namespace: instance.GetNamespace(),
Type: util.TemplateTypeScripts,
InstanceType: instance.GetObjectKind().GroupVersionKind().Kind,
MultiTemplateDir: opts.TemplateDir,
AdditionalTemplate: map[string]string{},
Annotations: map[string]string{},
Labels: opts.Labels,
})
}
return secret.EnsureSecrets(ctx, h, instance, cms, envVars)
}
28 changes: 28 additions & 0 deletions internal/common/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Copyright 2026.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common //nolint:revive // common is the established package name for multi-group shared code

import "errors"

var (
// ErrACSecretNotFound indicates that the ApplicationCredential secret was not found.
ErrACSecretNotFound = errors.New("ApplicationCredential secret not found")
// ErrACSecretMissingKeys indicates that the ApplicationCredential secret is missing required keys.
ErrACSecretMissingKeys = errors.New("ApplicationCredential secret missing required keys")
// ErrTemplateDirUnset indicates that no template directory was provided.
ErrTemplateDirUnset = errors.New("templateDir must be set")
)
34 changes: 34 additions & 0 deletions internal/common/kolla.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Copyright 2026.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common //nolint:revive // common is the established package name for multi-group shared code

import "fmt"

const (
// ServiceCommand is the command used to start a service binary in Kolla containers.
ServiceCommand = "/usr/local/bin/kolla_start"
)

// GetScriptSecretName returns the name of the Secret used for db sync scripts.
func GetScriptSecretName(crName string) string {
return fmt.Sprintf("%s-scripts", crName)
}

// GetServiceConfigSecretName returns the name of the Secret used to store service configuration.
func GetServiceConfigSecretName(crName string) string {
return fmt.Sprintf("%s-config-data", crName)
}
80 changes: 80 additions & 0 deletions internal/common/network.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
Copyright 2026.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common //nolint:revive // common is the established package name for multi-group shared code

import (
"context"
"fmt"
"time"

networkv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
condition "github.com/openstack-k8s-operators/lib-common/modules/common/condition"
helper "github.com/openstack-k8s-operators/lib-common/modules/common/helper"
nad "github.com/openstack-k8s-operators/lib-common/modules/common/networkattachment"
k8s_errors "k8s.io/apimachinery/pkg/api/errors"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log"
)

// EnsureNetworkAttachments checks requested network attachments exist and returns pod annotations.
func EnsureNetworkAttachments(
ctx context.Context,
h *helper.Helper,
networkAttachments []string,
namespace string,
conditionUpdater ConditionUpdater,
requeueTimeout time.Duration,
) (map[string]string, ctrl.Result, error) {
var nadAnnotations map[string]string

nadList := []networkv1.NetworkAttachmentDefinition{}
for _, netAtt := range networkAttachments {
netDef, err := nad.GetNADWithName(ctx, h, netAtt, namespace)
if err != nil {
if k8s_errors.IsNotFound(err) {
log.FromContext(ctx).Info(fmt.Sprintf("network-attachment-definition %s not found", netAtt))
conditionUpdater.Set(condition.FalseCondition(
condition.NetworkAttachmentsReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.NetworkAttachmentsReadyWaitingMessage,
netAtt))
return nadAnnotations, ctrl.Result{RequeueAfter: requeueTimeout}, nil
}
conditionUpdater.Set(condition.FalseCondition(
condition.NetworkAttachmentsReadyCondition,
condition.ErrorReason,
condition.SeverityWarning,
condition.NetworkAttachmentsErrorMessage,
err.Error()))
return nadAnnotations, ctrl.Result{}, err
}

if netDef != nil {
nadList = append(nadList, *netDef)
}
}

var err error
nadAnnotations, err = nad.EnsureNetworksAnnotation(nadList)
if err != nil {
return nadAnnotations, ctrl.Result{}, fmt.Errorf("failed create network annotation from %s: %w",
networkAttachments, err)
}

return nadAnnotations, ctrl.Result{}, nil
}
98 changes: 98 additions & 0 deletions internal/common/reconciler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Copyright 2026.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package common //nolint:revive // common is the established package name for multi-group shared code

import (
"context"
"time"

"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)

// ReconcilerBase provides a common set of clients, scheme, and settings for reconcilers.
type ReconcilerBase struct {
Client client.Client
Kclient kubernetes.Interface
Scheme *runtime.Scheme
RequeueTimeout time.Duration
}

// Manageable can be registered with a controller-runtime manager.
type Manageable interface {
SetupWithManager(mgr ctrl.Manager) error
}

// Reconciler represents a generic reconciler managed by the operator.
type Reconciler interface {
Manageable
SetRequeueTimeout(timeout time.Duration)
}

// NewReconcilerBase constructs a ReconcilerBase given a manager and Kubernetes client.
func NewReconcilerBase(
mgr ctrl.Manager, kclient kubernetes.Interface,
) ReconcilerBase {
return ReconcilerBase{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
Kclient: kclient,
RequeueTimeout: time.Duration(5) * time.Second,
}
}

// SetRequeueTimeout overrides the default RequeueTimeout of the Reconciler.
func (r *ReconcilerBase) SetRequeueTimeout(timeout time.Duration) {
r.RequeueTimeout = timeout
}

// Reconcilers holds reconciler objects to allow generic management.
type Reconcilers struct {
reconcilers map[string]Reconciler
}

// NewReconcilersRegistry constructs a Reconcilers registry from the provided map.
func NewReconcilersRegistry(reconcilers map[string]Reconciler) *Reconcilers {
return &Reconcilers{reconcilers: reconcilers}
}

// Setup starts the reconcilers by connecting them to the Manager.
func (r *Reconcilers) Setup(mgr ctrl.Manager, setupLog logr.Logger) error {
for name, controller := range r.reconcilers {
if err := controller.SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", name)
return err
}
}
return nil
}

// OverrideRequeueTimeout overrides the default RequeueTimeout of all reconcilers.
func (r *Reconcilers) OverrideRequeueTimeout(timeout time.Duration) {
for _, reconciler := range r.reconcilers {
reconciler.SetRequeueTimeout(timeout)
}
}

// GetLogger returns a logger with controller context fields.
func (r *ReconcilerBase) GetLogger(ctx context.Context) logr.Logger {
return log.FromContext(ctx).WithName("Controllers").WithName("ReconcilerBase")
}
Loading
Loading