Skip to content
Open
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
1 change: 1 addition & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import (
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/llamastackoperator"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/modelcontroller"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/modelregistry"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/modelsasservice"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/ray"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/trainer"
_ "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/trainingoperator"
Expand Down
132 changes: 132 additions & 0 deletions internal/controller/components/modelsasservice/modelsasservice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
Copyright 2025.

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 modelsasservice

import (
"context"
"errors"
"fmt"

operatorv1 "github.com/openshift/api/operator/v1"
k8serr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/opendatahub-io/opendatahub-operator/v2/api/common"
componentApi "github.com/opendatahub-io/opendatahub-operator/v2/api/components/v1alpha1"
dscv2 "github.com/opendatahub-io/opendatahub-operator/v2/api/datasciencecluster/v2"
cr "github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/components/registry"
"github.com/opendatahub-io/opendatahub-operator/v2/internal/controller/status"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/conditions"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/types"
odhdeploy "github.com/opendatahub-io/opendatahub-operator/v2/pkg/deploy"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/metadata/annotations"
)

type componentHandler struct{}

func init() { //nolint:gochecknoinits
cr.Add(&componentHandler{})
}

// GetName returns the component name for ModelsAsService.
func (s *componentHandler) GetName() string {
return componentApi.ModelsAsServiceComponentName
}

// Init initializes the ModelsAsService component.
func (s *componentHandler) Init(_ common.Platform) error {
mi := baseManifestInfo(BaseManifestsSourcePath)

if err := odhdeploy.ApplyParams(mi.String(), "params.env", imagesMap, extraParamsMap); err != nil {
return fmt.Errorf("failed to update params on path %s: %w", mi, err)
}

return nil
}

// NewCRObject constructs a new ModelsAsService Custom Resource.
func (s *componentHandler) NewCRObject(dsc *dscv2.DataScienceCluster) common.PlatformObject {
// TODO: ModelsAsService should be integrated into the KServe component
// For now, we create a basic ModelsAsService CR with default values
return &componentApi.ModelsAsService{
TypeMeta: metav1.TypeMeta{
Kind: componentApi.ModelsAsServiceKind,
APIVersion: componentApi.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: componentApi.ModelsAsServiceInstanceName,
Annotations: map[string]string{
annotations.ManagementStateAnnotation: string(operatorv1.Managed),
},
},
Spec: componentApi.ModelsAsServiceSpec{
Gateway: componentApi.GatewaySpec{
Namespace: DefaultGatewayNamespace,
Name: DefaultGatewayName,
},
},
}
}

// IsEnabled checks if the ModelsAsService component should be deployed.
func (s *componentHandler) IsEnabled(dsc *dscv2.DataScienceCluster) bool {
// For now, return false.
// This logic will need to be updated once DSCModelsAsService is integrated into the KServe spec
return false
}

// UpdateDSCStatus updates the ModelsAsService component status in the DataScienceCluster.
func (s *componentHandler) UpdateDSCStatus(ctx context.Context, rr *types.ReconciliationRequest) (metav1.ConditionStatus, error) {
cs := metav1.ConditionUnknown

c := componentApi.ModelsAsService{}
c.Name = componentApi.ModelsAsServiceInstanceName

if err := rr.Client.Get(ctx, client.ObjectKeyFromObject(&c), &c); err != nil && !k8serr.IsNotFound(err) {
return cs, nil
}

dsc, ok := rr.Instance.(*dscv2.DataScienceCluster)
if !ok {
return cs, errors.New("failed to convert to DataScienceCluster")
}

// Since s.IsEnabled() always returns false, for now, the following code will always mark the ready condition as not ready.
// This will need to be updated once DSCModelsAsService is properly integrated

// Set the ready condition based on the ModelsAsService status
rr.Conditions.MarkFalse(ReadyConditionType)

if s.IsEnabled(dsc) {
if rc := conditions.FindStatusCondition(c.GetStatus(), status.ConditionTypeReady); rc != nil {
rr.Conditions.MarkFrom(ReadyConditionType, *rc)
cs = rc.Status
} else {
cs = metav1.ConditionFalse
}
} else {
rr.Conditions.MarkFalse(
ReadyConditionType,
conditions.WithReason(string(operatorv1.Removed)),
conditions.WithMessage("Component ManagementState is set to %s", string(operatorv1.Removed)),
conditions.WithSeverity(common.ConditionSeverityInfo),
)
}

return cs, nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
Copyright 2025.

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 modelsasservice

import (
"context"
"fmt"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
ctrl "sigs.k8s.io/controller-runtime"
gwapiv1 "sigs.k8s.io/gateway-api/apis/v1"

componentApi "github.com/opendatahub-io/opendatahub-operator/v2/api/components/v1alpha1"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/actions/deploy"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/actions/gc"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/actions/render/kustomize"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/actions/status/deployments"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/predicates/resources"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/reconciler"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/metadata/labels"
)

// NewComponentReconciler creates a new ModelsAsService controller.
func (s *componentHandler) NewComponentReconciler(ctx context.Context, mgr ctrl.Manager) error {
_, err := reconciler.ReconcilerFor(mgr, &componentApi.ModelsAsService{}).
// Core Kubernetes resources deployed by MaaS manifests
Owns(&corev1.ConfigMap{}).
Owns(&corev1.Service{}).
Owns(&corev1.ServiceAccount{}).
Owns(&appsv1.Deployment{}, reconciler.WithPredicates(resources.NewDeploymentPredicate())).
// RBAC resources
Owns(&rbacv1.ClusterRole{}).
Owns(&rbacv1.ClusterRoleBinding{}).
// Gateway API resources
Owns(&gwapiv1.HTTPRoute{}).
Owns(&gwapiv1.Gateway{}).
// Note: AuthPolicy (kuadrant.io/v1) is not included here as it's a third-party CRD
// that may not be available in all environments. It should be handled by the
// manifest deployment process.
WithAction(initialize).
WithAction(validateGateway).
WithAction(customizeManifests).
// WithAction(releases.NewAction()). // TODO: Do we need this? How to fix annotation of "platform.opendatahub.io/version:0.0.0"
WithAction(kustomize.NewAction(
// TODO: There are comments in some components mentioning these are legacy labels. Do we still need these?
kustomize.WithLabel(labels.ODH.Component(ComponentName), labels.True),
kustomize.WithLabel(labels.K8SCommon.PartOf, ComponentName),
)).
WithAction(configureMaaSGatewayHostname).
WithAction(deploy.NewAction(
deploy.WithCache(),
)).
WithAction(deployments.NewAction()).
// must be the final action
WithAction(gc.NewAction()).
// declares the list of additional, controller specific conditions that are
// contributing to the controller readiness status
WithConditions(conditionTypes...).
Build(ctx)
if err != nil {
return fmt.Errorf("could not create the ModelsAsService controller: %w", err)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
Copyright 2025.

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 modelsasservice

import (
"context"
"errors"
"fmt"
"strings"

configv1 "github.com/openshift/api/config/v1"
"k8s.io/apimachinery/pkg/runtime"
types2 "k8s.io/apimachinery/pkg/types"
v1 "sigs.k8s.io/gateway-api/apis/v1"

componentApi "github.com/opendatahub-io/opendatahub-operator/v2/api/components/v1alpha1"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/cluster/gvk"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/controller/types"
odhdeploy "github.com/opendatahub-io/opendatahub-operator/v2/pkg/deploy"
"github.com/opendatahub-io/opendatahub-operator/v2/pkg/resources"
)

// validateGateway validates the Gateway specification in the ModelsAsService resource.
func validateGateway(_ context.Context, rr *types.ReconciliationRequest) error {
maas, ok := rr.Instance.(*componentApi.ModelsAsService)
if !ok {
return fmt.Errorf("resource instance %v is not a componentApi.ModelsAsService", rr.Instance)
}

// When the Gateway is omitted, use defaults
if maas.Spec.Gateway.Namespace == "" && maas.Spec.Gateway.Name == "" {
maas.Spec.Gateway.Namespace = DefaultGatewayNamespace
maas.Spec.Gateway.Name = DefaultGatewayName
return nil
}

// If one field of the Gateway reference is specified, both are mandatory
if maas.Spec.Gateway.Namespace == "" || maas.Spec.Gateway.Name == "" {
return errors.New("invalid gateway specification: when specifying a custom gateway, both namespace and name must be provided")
}

// TODO: Add validation logic to check if the specified Gateway exists
// (For now, we'll just validate that the name and namespace are set)

return nil
}

// initialize sets up the manifests for the ModelsAsService component.
func initialize(_ context.Context, rr *types.ReconciliationRequest) error {
rr.Manifests = []types.ManifestInfo{
baseManifestInfo(BaseManifestsSourcePath),
}

return nil
}

// customizeManifests applies component-specific customizations to the manifests.
func customizeManifests(_ context.Context, rr *types.ReconciliationRequest) error {
maas, ok := rr.Instance.(*componentApi.ModelsAsService)
if !ok {
return fmt.Errorf("resource instance %v is not a componentApi.ModelsAsService", rr.Instance)
}

// Customize Gateway parameters in manifests based on the ModelsAsService spec
if err := odhdeploy.ApplyParams(rr.Manifests[0].String(), "params.env", nil, map[string]string{
"GATEWAY_NAMESPACE": maas.Spec.Gateway.Namespace,
"GATEWAY_NAME": maas.Spec.Gateway.Name,
}); err != nil {
return fmt.Errorf("failed to update Gateway params on path %s: %w", rr.Manifests[0].String(), err)
}

return nil
}
Comment on lines +62 to +87
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard against empty manifest slice before indexing

🔒 Security Findings

  • No security issues identified here; values written to params.env are simple gateway identifiers, not secrets.

💡 Other

  • customizeManifests unconditionally accesses rr.Manifests[0]. If the actions pipeline ever changes and initialize is skipped or altered, this will panic the reconciler.
  • A small defensive check avoids a hard crash and surfaces a clear error instead. For example:
 func customizeManifests(_ context.Context, rr *types.ReconciliationRequest) error {
+	if len(rr.Manifests) == 0 {
+		return fmt.Errorf("no manifests configured for ModelsAsService")
+	}
 	maas, ok := rr.Instance.(*componentApi.ModelsAsService)
🤖 Prompt for AI Agents
internal/controller/components/modelsasservice/modelsasservice_controller_actions.go
around lines 62 to 87: customizeManifests unconditionally indexes
rr.Manifests[0] which can panic if the slice is empty; add a defensive check at
the start of the function to verify rr.Manifests is non-nil and has len > 0 and
return a descriptive error (using fmt.Errorf) if not, then proceed to use
rr.Manifests[0] as before.


// TODO: Remove this function. We are not expecting to programatically create the Gateway. Users would create it.
func configureMaaSGatewayHostname(ctx context.Context, rr *types.ReconciliationRequest) error {
for idx, resource := range rr.Resources {
if resource.GroupVersionKind() == gvk.KubernetesGateway {
gateway := &v1.Gateway{}
fromUnstructuredErr := runtime.DefaultUnstructuredConverter.FromUnstructured(resource.Object, gateway)
if fromUnstructuredErr != nil {
return fmt.Errorf("failed converting to Gateway type from resource %s: %w", resources.FormatObjectReference(&resource), fromUnstructuredErr)
}

clusterIngress := &configv1.Ingress{}
ingressFetchErr := rr.Client.Get(ctx, types2.NamespacedName{Namespace: "", Name: "cluster"}, clusterIngress)
if ingressFetchErr != nil {
return fmt.Errorf("failed fetching OpenShift cluster ingress resource: %w", ingressFetchErr)
}

for idxListener := range gateway.Spec.Listeners {
if gateway.Spec.Listeners[idxListener].Hostname != nil {
hostnameTemplate := string(*gateway.Spec.Listeners[idxListener].Hostname)
finalHostname := v1.Hostname(strings.Replace(hostnameTemplate, "${CLUSTER_DOMAIN}", clusterIngress.Spec.Domain, 1))
gateway.Spec.Listeners[idxListener].Hostname = &finalHostname
}
}

unstructuredGw, toUnstructuredErr := resources.ToUnstructured(gateway)
if toUnstructuredErr != nil {
return fmt.Errorf("failed converting Gateway resource to unstructured object: %w", toUnstructuredErr)
}

rr.Resources[idx] = *unstructuredGw
}
}

return nil
}
Loading
Loading