|
| 1 | +/* |
| 2 | +Copyright 2023. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package controllers |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "crypto/rand" |
| 22 | + "crypto/sha1" |
| 23 | + "encoding/base64" |
| 24 | + "strconv" |
| 25 | + |
| 26 | + rayv1 "github.com/ray-project/kuberay/ray-operator/apis/ray/v1" |
| 27 | + |
| 28 | + corev1 "k8s.io/api/core/v1" |
| 29 | + rbacv1 "k8s.io/api/rbac/v1" |
| 30 | + "k8s.io/apimachinery/pkg/api/errors" |
| 31 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 32 | + "k8s.io/apimachinery/pkg/runtime" |
| 33 | + "k8s.io/apimachinery/pkg/types" |
| 34 | + "k8s.io/apimachinery/pkg/util/intstr" |
| 35 | + coreapply "k8s.io/client-go/applyconfigurations/core/v1" |
| 36 | + v1 "k8s.io/client-go/applyconfigurations/meta/v1" |
| 37 | + rbacapply "k8s.io/client-go/applyconfigurations/rbac/v1" |
| 38 | + "k8s.io/client-go/kubernetes" |
| 39 | + ctrl "sigs.k8s.io/controller-runtime" |
| 40 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 41 | + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" |
| 42 | + |
| 43 | + routev1 "github.com/openshift/api/route/v1" |
| 44 | + routeapply "github.com/openshift/client-go/route/applyconfigurations/route/v1" |
| 45 | + routev1client "github.com/openshift/client-go/route/clientset/versioned/typed/route/v1" |
| 46 | +) |
| 47 | + |
| 48 | +// RayClusterReconciler reconciles a RayCluster object |
| 49 | +type RayClusterReconciler struct { |
| 50 | + client.Client |
| 51 | + kubeClient *kubernetes.Clientset |
| 52 | + routeClient *routev1client.RouteV1Client |
| 53 | + Scheme *runtime.Scheme |
| 54 | + CookieSalt string |
| 55 | +} |
| 56 | + |
| 57 | +const ( |
| 58 | + requeueTime = 10 |
| 59 | + controllerName = "codeflare-raycluster-controller" |
| 60 | + oauthAnnotation = "codeflare.dev/oauth=true" |
| 61 | + CodeflareOAuthFinalizer = "codeflare.dev/oauth-finalizer" |
| 62 | + OAuthServicePort = 443 |
| 63 | + OAuthServicePortName = "oauth-proxy" |
| 64 | + strTrue = "true" |
| 65 | + strFalse = "false" |
| 66 | + logRequeueing = "requeueing" |
| 67 | +) |
| 68 | + |
| 69 | +var ( |
| 70 | + deletePolicy = metav1.DeletePropagationForeground |
| 71 | + deleteOptions = client.DeleteOptions{PropagationPolicy: &deletePolicy} |
| 72 | +) |
| 73 | + |
| 74 | +//+kubebuilder:rbac:groups=ray.io,resources=rayclusters,verbs=get;list;watch;create;update;patch;delete |
| 75 | +//+kubebuilder:rbac:groups=ray.io,resources=rayclusters/status,verbs=get;update;patch |
| 76 | +//+kubebuilder:rbac:groups=ray.io,resources=rayclusters/finalizers,verbs=update |
| 77 | +//+kubebuilder:rbac:groups=route.openshift.io,resources=routes,verbs=patch;delete;get |
| 78 | +//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;create;patch;delete;get |
| 79 | +//+kubebuilder:rbac:groups=core,resources=services,verbs=patch;delete;get |
| 80 | +//+kubebuilder:rbac:groups=core,resources=serviceaccounts,verbs=patch;delete;get |
| 81 | + |
| 82 | +// Reconcile is part of the main kubernetes reconciliation loop which aims to |
| 83 | +// move the current state of the cluster closer to the desired state. |
| 84 | +// TODO(user): Modify the Reconcile function to compare the state specified by |
| 85 | +// the RayCluster object against the actual cluster state, and then |
| 86 | +// perform operations to make the cluster state reflect the state specified by |
| 87 | +// the user. |
| 88 | +// |
| 89 | +// For more details, check Reconcile and its Result here: |
| 90 | +// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.15.3/pkg/reconcile |
| 91 | + |
| 92 | +func (r *RayClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { |
| 93 | + logger := ctrl.LoggerFrom(ctx) |
| 94 | + |
| 95 | + var cluster rayv1.RayCluster |
| 96 | + |
| 97 | + if err := r.Get(ctx, req.NamespacedName, &cluster); err != nil { |
| 98 | + if !errors.IsNotFound(err) { |
| 99 | + logger.Error(err, "Error getting RayCluster resource") |
| 100 | + } |
| 101 | + return ctrl.Result{}, client.IgnoreNotFound(err) |
| 102 | + } |
| 103 | + |
| 104 | + if cluster.ObjectMeta.DeletionTimestamp.IsZero() { |
| 105 | + if !controllerutil.ContainsFinalizer(&cluster, CodeflareOAuthFinalizer) { |
| 106 | + logger.Info("Add a finalizer", "finalizer", CodeflareOAuthFinalizer) |
| 107 | + controllerutil.AddFinalizer(&cluster, CodeflareOAuthFinalizer) |
| 108 | + if err := r.Update(ctx, &cluster); err != nil { |
| 109 | + logger.Error(err, "Failed to update RayCluster with finalizer", logRequeueing, strTrue) |
| 110 | + return ctrl.Result{RequeueAfter: requeueTime}, err |
| 111 | + } |
| 112 | + } |
| 113 | + } else if controllerutil.ContainsFinalizer(&cluster, CodeflareOAuthFinalizer) { |
| 114 | + err := r.deleteIfNotExist( |
| 115 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: crbNameFromCluster(&cluster)}, &rbacv1.ClusterRoleBinding{}, |
| 116 | + ) |
| 117 | + if err != nil { |
| 118 | + logger.Error(err, "Failed to remove OAuth ClusterRoleBinding.", logRequeueing, strTrue) |
| 119 | + return ctrl.Result{RequeueAfter: requeueTime}, err |
| 120 | + } |
| 121 | + controllerutil.RemoveFinalizer(&cluster, CodeflareOAuthFinalizer) |
| 122 | + if err := r.Update(ctx, &cluster); err != nil { |
| 123 | + logger.Error(err, "Failed to remove finalizer from RayCluster", logRequeueing, strTrue) |
| 124 | + return ctrl.Result{RequeueAfter: requeueTime}, err |
| 125 | + } |
| 126 | + logger.Info("Successfully removed finalizer.", logRequeueing, strFalse) |
| 127 | + return ctrl.Result{}, nil |
| 128 | + } |
| 129 | + |
| 130 | + val, ok := cluster.ObjectMeta.Annotations["codeflare.dev/oauth"] |
| 131 | + boolVal, err := strconv.ParseBool(val) |
| 132 | + if err != nil { |
| 133 | + logger.Error(err, "Could not convert codeflare.dev/oauth value to bool", "codeflare.dev/oauth", val) |
| 134 | + } |
| 135 | + if !ok || err != nil || !boolVal { |
| 136 | + logger.Info("Removing all OAuth Objects") |
| 137 | + err := r.deleteIfNotExist( |
| 138 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: oauthSecretNameFromCluster(&cluster)}, &corev1.Secret{}, |
| 139 | + ) |
| 140 | + if err != nil { |
| 141 | + logger.Error(err, "Error deleting OAuth Secret, retrying", logRequeueing, strTrue) |
| 142 | + return ctrl.Result{RequeueAfter: requeueTime}, nil |
| 143 | + } |
| 144 | + err = r.deleteIfNotExist( |
| 145 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: oauthServiceNameFromCluster(&cluster)}, &corev1.Service{}, |
| 146 | + ) |
| 147 | + if err != nil { |
| 148 | + logger.Error(err, "Error deleting OAuth Service, retrying", logRequeueing, strTrue) |
| 149 | + return ctrl.Result{RequeueAfter: requeueTime}, nil |
| 150 | + } |
| 151 | + err = r.deleteIfNotExist( |
| 152 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: oauthServiceAccountNameFromCluster(&cluster)}, &corev1.ServiceAccount{}, |
| 153 | + ) |
| 154 | + if err != nil { |
| 155 | + logger.Error(err, "Error deleting OAuth ServiceAccount, retrying", logRequeueing, strTrue) |
| 156 | + return ctrl.Result{RequeueAfter: requeueTime}, nil |
| 157 | + } |
| 158 | + err = r.deleteIfNotExist( |
| 159 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: crbNameFromCluster(&cluster)}, &rbacv1.ClusterRoleBinding{}, |
| 160 | + ) |
| 161 | + if err != nil { |
| 162 | + logger.Error(err, "Error deleting OAuth CRB, retrying", logRequeueing, strTrue) |
| 163 | + return ctrl.Result{RequeueAfter: requeueTime}, nil |
| 164 | + } |
| 165 | + err = r.deleteIfNotExist( |
| 166 | + ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: routeNameFromCluster(&cluster)}, &routev1.Route{}, |
| 167 | + ) |
| 168 | + if err != nil { |
| 169 | + logger.Error(err, "Error deleting OAuth Route, retrying", logRequeueing, strTrue) |
| 170 | + return ctrl.Result{RequeueAfter: requeueTime}, nil |
| 171 | + } |
| 172 | + return ctrl.Result{}, nil |
| 173 | + } |
| 174 | + |
| 175 | + _, err = r.routeClient.Routes(cluster.Namespace).Apply(ctx, desiredClusterRoute(&cluster), metav1.ApplyOptions{FieldManager: controllerName, Force: true}) |
| 176 | + if err != nil { |
| 177 | + logger.Error(err, "Failed to update OAuth Route") |
| 178 | + } |
| 179 | + |
| 180 | + _, err = r.kubeClient.CoreV1().Secrets(cluster.Namespace).Apply(ctx, desiredOAuthSecret(&cluster, r), metav1.ApplyOptions{FieldManager: controllerName, Force: true}) |
| 181 | + if err != nil { |
| 182 | + logger.Error(err, "Failed to create OAuth Secret") |
| 183 | + } |
| 184 | + |
| 185 | + _, err = r.kubeClient.CoreV1().Services(cluster.Namespace).Apply(ctx, desiredOAuthService(&cluster), metav1.ApplyOptions{FieldManager: controllerName, Force: true}) |
| 186 | + if err != nil { |
| 187 | + logger.Error(err, "Failed to update OAuth Service") |
| 188 | + } |
| 189 | + |
| 190 | + _, err = r.kubeClient.CoreV1().ServiceAccounts(cluster.Namespace).Apply(ctx, desiredServiceAccount(&cluster), metav1.ApplyOptions{FieldManager: controllerName, Force: true}) |
| 191 | + if err != nil { |
| 192 | + logger.Error(err, "Failed to update OAuth ServiceAccount") |
| 193 | + } |
| 194 | + |
| 195 | + _, err = r.kubeClient.RbacV1().ClusterRoleBindings().Apply(ctx, desiredOAuthClusterRoleBinding(&cluster), metav1.ApplyOptions{FieldManager: controllerName, Force: true}) |
| 196 | + if err != nil { |
| 197 | + logger.Error(err, "Failed to update OAuth ClusterRoleBinding") |
| 198 | + } |
| 199 | + |
| 200 | + return ctrl.Result{}, nil |
| 201 | +} |
| 202 | + |
| 203 | +func crbNameFromCluster(cluster *rayv1.RayCluster) string { |
| 204 | + return cluster.Name + "-" + cluster.Namespace + "-auth" // NOTE: potential naming conflicts ie {name: foo, ns: bar-baz} and {name: foo-bar, ns: baz} |
| 205 | +} |
| 206 | + |
| 207 | +func (r *RayClusterReconciler) deleteIfNotExist(ctx context.Context, namespacedName types.NamespacedName, obj client.Object) error { |
| 208 | + err := r.Client.Get(ctx, namespacedName, obj) |
| 209 | + if err != nil && errors.IsNotFound(err) { |
| 210 | + return nil |
| 211 | + } else if err != nil { |
| 212 | + return err |
| 213 | + } |
| 214 | + return r.Client.Delete(ctx, obj, &deleteOptions) |
| 215 | +} |
| 216 | + |
| 217 | +func desiredOAuthClusterRoleBinding(cluster *rayv1.RayCluster) *rbacapply.ClusterRoleBindingApplyConfiguration { |
| 218 | + return rbacapply.ClusterRoleBinding( |
| 219 | + crbNameFromCluster(cluster)). |
| 220 | + WithLabels(map[string]string{"ray.io/cluster-name": cluster.Name}). |
| 221 | + WithSubjects( |
| 222 | + rbacapply.Subject(). |
| 223 | + WithKind("ServiceAccount"). |
| 224 | + WithName(oauthServiceAccountNameFromCluster(cluster)). |
| 225 | + WithNamespace(cluster.Namespace), |
| 226 | + ). |
| 227 | + WithRoleRef( |
| 228 | + rbacapply.RoleRef(). |
| 229 | + WithAPIGroup("rbac.authorization.k8s.io"). |
| 230 | + WithKind("ClusterRole"). |
| 231 | + WithName("system:auth-delegator"), |
| 232 | + ). |
| 233 | + WithOwnerReferences( |
| 234 | + v1.OwnerReference().WithUID(cluster.UID).WithName(cluster.Name).WithKind(cluster.Kind).WithAPIVersion(cluster.APIVersion), |
| 235 | + ) |
| 236 | +} |
| 237 | + |
| 238 | +func oauthServiceAccountNameFromCluster(cluster *rayv1.RayCluster) string { |
| 239 | + return cluster.Name + "-oauth-proxy" |
| 240 | +} |
| 241 | + |
| 242 | +func desiredServiceAccount(cluster *rayv1.RayCluster) *coreapply.ServiceAccountApplyConfiguration { |
| 243 | + return coreapply.ServiceAccount(oauthServiceAccountNameFromCluster(cluster), cluster.Namespace). |
| 244 | + WithLabels(map[string]string{"ray.io/cluster-name": cluster.Name}). |
| 245 | + WithAnnotations(map[string]string{ |
| 246 | + "serviceaccounts.openshift.io/oauth-redirectreference.first": "" + |
| 247 | + `{"kind":"OAuthRedirectReference","apiVersion":"v1",` + |
| 248 | + `"reference":{"kind":"Route","name":"` + routeNameFromCluster(cluster) + `"}}`, |
| 249 | + }). |
| 250 | + WithOwnerReferences( |
| 251 | + v1.OwnerReference().WithUID(cluster.UID).WithName(cluster.Name).WithKind(cluster.Kind).WithAPIVersion(cluster.APIVersion), |
| 252 | + ) |
| 253 | +} |
| 254 | + |
| 255 | +func routeNameFromCluster(cluster *rayv1.RayCluster) string { |
| 256 | + return "ray-dashboard-" + cluster.Name |
| 257 | +} |
| 258 | + |
| 259 | +func desiredClusterRoute(cluster *rayv1.RayCluster) *routeapply.RouteApplyConfiguration { |
| 260 | + return routeapply.Route(routeNameFromCluster(cluster), cluster.Namespace). |
| 261 | + WithLabels(map[string]string{"ray.io/cluster-name": cluster.Name}). |
| 262 | + WithSpec(routeapply.RouteSpec(). |
| 263 | + WithTo(routeapply.RouteTargetReference().WithKind("Service").WithName(oauthServiceNameFromCluster(cluster))). |
| 264 | + WithPort(routeapply.RoutePort().WithTargetPort(intstr.FromString((OAuthServicePortName)))). |
| 265 | + WithTLS(routeapply.TLSConfig(). |
| 266 | + WithInsecureEdgeTerminationPolicy(routev1.InsecureEdgeTerminationPolicyRedirect). |
| 267 | + WithTermination(routev1.TLSTerminationReencrypt), |
| 268 | + ), |
| 269 | + ). |
| 270 | + WithOwnerReferences( |
| 271 | + v1.OwnerReference().WithUID(cluster.UID).WithName(cluster.Name).WithKind(cluster.Kind).WithAPIVersion(cluster.APIVersion), |
| 272 | + ) |
| 273 | +} |
| 274 | + |
| 275 | +func oauthServiceNameFromCluster(cluster *rayv1.RayCluster) string { |
| 276 | + return cluster.Name + "-oauth" |
| 277 | +} |
| 278 | + |
| 279 | +func oauthServiceTLSSecretName(cluster *rayv1.RayCluster) string { |
| 280 | + return cluster.Name + "-proxy-tls-secret" |
| 281 | +} |
| 282 | + |
| 283 | +func desiredOAuthService(cluster *rayv1.RayCluster) *coreapply.ServiceApplyConfiguration { |
| 284 | + return coreapply.Service(oauthServiceNameFromCluster(cluster), cluster.Namespace). |
| 285 | + WithLabels(map[string]string{"ray.io/cluster-name": cluster.Name}). |
| 286 | + WithAnnotations(map[string]string{"service.beta.openshift.io/serving-cert-secret-name": oauthServiceTLSSecretName(cluster)}). |
| 287 | + WithSpec( |
| 288 | + coreapply.ServiceSpec(). |
| 289 | + WithPorts( |
| 290 | + coreapply.ServicePort(). |
| 291 | + WithName(OAuthServicePortName). |
| 292 | + WithPort(OAuthServicePort). |
| 293 | + WithTargetPort(intstr.FromString(OAuthServicePortName)). |
| 294 | + WithProtocol(corev1.ProtocolTCP), |
| 295 | + ). |
| 296 | + WithSelector(map[string]string{"ray.io/cluster": cluster.Name, "ray.io/node-type": "head"}), |
| 297 | + ). |
| 298 | + WithOwnerReferences( |
| 299 | + v1.OwnerReference().WithUID(cluster.UID).WithName(cluster.Name).WithKind(cluster.Kind).WithAPIVersion(cluster.APIVersion), |
| 300 | + ) |
| 301 | +} |
| 302 | + |
| 303 | +func oauthSecretNameFromCluster(cluster *rayv1.RayCluster) string { |
| 304 | + return cluster.Name + "-oauth-config" |
| 305 | +} |
| 306 | + |
| 307 | +// desiredOAuthSecret defines the desired OAuth secret object |
| 308 | +func desiredOAuthSecret(cluster *rayv1.RayCluster, r *RayClusterReconciler) *coreapply.SecretApplyConfiguration { |
| 309 | + // Generate the cookie secret for the OAuth proxy |
| 310 | + hasher := sha1.New() // REVIEW is SHA1 okay here? |
| 311 | + hasher.Write([]byte(cluster.Name + r.CookieSalt)) |
| 312 | + cookieSecret := base64.StdEncoding.EncodeToString(hasher.Sum(nil)) |
| 313 | + |
| 314 | + return coreapply.Secret(oauthSecretNameFromCluster(cluster), cluster.Namespace). |
| 315 | + WithLabels(map[string]string{"ray.io/cluster-name": cluster.Name}). |
| 316 | + WithStringData(map[string]string{"cookie_secret": cookieSecret}). |
| 317 | + WithOwnerReferences( |
| 318 | + v1.OwnerReference().WithUID(cluster.UID).WithName(cluster.Name).WithKind(cluster.Kind).WithAPIVersion(cluster.APIVersion), |
| 319 | + ) |
| 320 | + // Create a Kubernetes secret to store the cookie secret |
| 321 | +} |
| 322 | + |
| 323 | +// SetupWithManager sets up the controller with the Manager. |
| 324 | +func (r *RayClusterReconciler) SetupWithManager(mgr ctrl.Manager) error { |
| 325 | + r.kubeClient = kubernetes.NewForConfigOrDie(mgr.GetConfig()) |
| 326 | + r.routeClient = routev1client.NewForConfigOrDie(mgr.GetConfig()) |
| 327 | + b := make([]byte, 16) |
| 328 | + _, err := rand.Read(b) |
| 329 | + if err != nil { |
| 330 | + return err |
| 331 | + } |
| 332 | + r.CookieSalt = string(b) |
| 333 | + return ctrl.NewControllerManagedBy(mgr). |
| 334 | + Named(controllerName). |
| 335 | + For(&rayv1.RayCluster{}). |
| 336 | + Complete(r) |
| 337 | +} |
0 commit comments