2020-02-25 18:07:01 +01:00
/*
Copyright 2020 The Rook Authors. All rights reserved.
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 controller
import (
"context"
2020-04-17 18:40:54 +02:00
"fmt"
"reflect"
2025-07-17 13:06:51 +03:00
"runtime/debug"
2025-02-07 14:56:24 -07:00
"slices"
2021-02-22 10:19:21 +00:00
"strconv"
2021-01-07 17:24:13 -07:00
"strings"
2020-02-25 18:07:01 +01:00
"time"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
2020-04-17 18:40:54 +02:00
"github.com/rook/rook/pkg/operator/k8sutil"
2021-02-22 10:19:21 +00:00
"github.com/rook/rook/pkg/util/exec"
2025-12-03 10:35:58 -07:00
"github.com/rook/rook/pkg/util/log"
2020-04-17 18:40:54 +02:00
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2020-02-25 18:07:01 +01:00
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
2021-08-06 17:46:01 +02:00
// OperatorConfig represents the configuration of the operator
type OperatorConfig struct {
OperatorNamespace string
Image string
ServiceAccount string
NamespaceToWatch string
}
2022-03-30 11:10:13 +02:00
// ClusterHealth is passed to the various monitoring go routines to stop them when the context is cancelled
type ClusterHealth struct {
InternalCtx context . Context
InternalCancel context . CancelFunc
}
2021-01-22 16:00:06 +01:00
const (
// OperatorSettingConfigMapName refers to ConfigMap that configures rook ceph operator
2024-08-16 19:04:01 +02:00
OperatorSettingConfigMapName string = "rook-ceph-operator-config"
enforceHostNetworkSettingName string = "ROOK_ENFORCE_HOST_NETWORK"
enforceHostNetworkDefaultValue string = "false"
2021-01-22 16:00:06 +01:00
2025-02-07 14:56:24 -07:00
obcAllowAdditionalConfigFieldsSettingName string = "ROOK_OBC_ALLOW_ADDITIONAL_CONFIG_FIELDS"
obcAllowAdditionalConfigFieldsDefaultValue string = "maxObjects,maxSize"
2024-11-05 17:50:40 +01:00
revisionHistoryLimitSettingName string = "ROOK_REVISION_HISTORY_LIMIT"
2024-09-26 14:11:53 +02:00
2021-01-22 16:00:06 +01:00
// UninitializedCephConfigError refers to the error message printed by the Ceph CLI when there is no ceph configuration file
// This typically is raised when the operator has not finished initializing
UninitializedCephConfigError = "error calling conf_read_file"
2021-05-26 17:54:23 +02:00
// OperatorNotInitializedMessage is the message we print when the Operator is not ready to reconcile, typically the ceph.conf has not been generated yet
OperatorNotInitializedMessage = "skipping reconcile since operator is still initializing"
2021-01-22 16:00:06 +01:00
)
2020-03-05 11:50:22 +05:30
2020-02-25 18:07:01 +01:00
var (
// ImmediateRetryResult Return this for a immediate retry of the reconciliation loop with the same request object.
ImmediateRetryResult = reconcile . Result { Requeue : true }
2020-06-16 14:20:50 +02:00
2020-02-25 18:07:01 +01:00
// WaitForRequeueIfCephClusterNotReady waits for the CephCluster to be ready
2020-05-14 15:33:16 -06:00
WaitForRequeueIfCephClusterNotReady = reconcile . Result { Requeue : true , RequeueAfter : 10 * time . Second }
2020-06-16 14:20:50 +02:00
2021-08-06 17:46:01 +02:00
// WaitForRequeueIfCephClusterIsUpgrading waits until the upgrade is complete
WaitForRequeueIfCephClusterIsUpgrading = reconcile . Result { Requeue : true , RequeueAfter : time . Minute }
2020-05-14 16:52:10 -06:00
// WaitForRequeueIfFinalizerBlocked waits for resources to be cleaned up before the finalizer can be removed
WaitForRequeueIfFinalizerBlocked = reconcile . Result { Requeue : true , RequeueAfter : 10 * time . Second }
2020-06-16 14:20:50 +02:00
2021-01-22 16:00:06 +01:00
// WaitForRequeueIfOperatorNotInitialized waits for resources to be cleaned up before the finalizer can be removed
WaitForRequeueIfOperatorNotInitialized = reconcile . Result { Requeue : true , RequeueAfter : 10 * time . Second }
2020-06-16 14:20:50 +02:00
// OperatorCephBaseImageVersion is the ceph version in the operator image
OperatorCephBaseImageVersion string
2022-11-01 08:41:19 +00:00
// loopDevicesAllowed indicates whether loop devices are allowed to be used
2024-09-26 14:11:53 +02:00
loopDevicesAllowed = false
revisionHistoryLimit * int32 = nil
2025-02-07 14:56:24 -07:00
// allowed OBC additional config fields
obcAllowAdditionalConfigFields = strings . Split ( obcAllowAdditionalConfigFieldsDefaultValue , "," )
2020-02-25 18:07:01 +01:00
)
2025-02-21 18:02:00 -07:00
func DiscoveryDaemonEnabled () bool {
return k8sutil . GetOperatorSetting ( "ROOK_ENABLE_DISCOVERY_DAEMON" , "false" ) == "true"
2021-03-11 14:36:09 -07:00
}
2021-02-22 10:19:21 +00:00
// SetCephCommandsTimeout sets the timeout value of Ceph commands which are executed from Rook
2025-02-21 18:02:00 -07:00
func SetCephCommandsTimeout () {
strTimeoutSeconds := k8sutil . GetOperatorSetting ( "ROOK_CEPH_COMMANDS_TIMEOUT_SECONDS" , "15" )
2021-02-22 10:19:21 +00:00
timeoutSeconds , err := strconv . Atoi ( strTimeoutSeconds )
if err != nil || timeoutSeconds < 1 {
logger . Warningf ( "ROOK_CEPH_COMMANDS_TIMEOUT is %q but it should be >= 1, set the default value 15" , strTimeoutSeconds )
timeoutSeconds = 15
}
exec . CephCommandsTimeout = time . Duration ( timeoutSeconds ) * time . Second
}
2025-02-21 18:02:00 -07:00
func SetAllowLoopDevices () {
strLoopDevicesAllowed := k8sutil . GetOperatorSetting ( "ROOK_CEPH_ALLOW_LOOP_DEVICES" , "false" )
2022-11-01 08:41:19 +00:00
var err error
loopDevicesAllowed , err = strconv . ParseBool ( strLoopDevicesAllowed )
if err != nil {
logger . Warningf ( "ROOK_CEPH_ALLOW_LOOP_DEVICES is set to an invalid value %v, set the default value false" , strLoopDevicesAllowed )
loopDevicesAllowed = false
}
}
func LoopDevicesAllowed () bool {
return loopDevicesAllowed
}
2025-02-21 18:02:00 -07:00
func SetEnforceHostNetwork () {
strval := k8sutil . GetOperatorSetting ( enforceHostNetworkSettingName , enforceHostNetworkDefaultValue )
2024-08-16 19:04:01 +02:00
val , err := strconv . ParseBool ( strval )
if err != nil {
logger . Warningf ( "failed to parse value %q for %q. assuming false value" , strval , enforceHostNetworkSettingName )
cephv1 . SetEnforceHostNetwork ( false )
return
}
cephv1 . SetEnforceHostNetwork ( val )
}
func EnforceHostNetwork () bool {
return cephv1 . EnforceHostNetwork ()
}
2025-02-21 18:02:00 -07:00
func SetRevisionHistoryLimit () {
strval := k8sutil . GetOperatorSetting ( revisionHistoryLimitSettingName , "" )
2024-11-05 17:50:40 +01:00
var limit int32
if strval == "" {
logger . Debugf ( "not parsing empty string to int for %q. assuming default value." , revisionHistoryLimitSettingName )
revisionHistoryLimit = nil
return
2024-09-26 14:11:53 +02:00
}
2024-11-05 17:50:40 +01:00
numval , err := strconv . ParseInt ( strval , 10 , 32 )
if err != nil {
logger . Warningf ( "failed to parse value %q for %q. assuming default value. %v" , strval , revisionHistoryLimitSettingName , err )
revisionHistoryLimit = nil
return
}
limit = int32 ( numval )
revisionHistoryLimit = & limit
2024-09-26 14:11:53 +02:00
}
func RevisionHistoryLimit () * int32 {
return revisionHistoryLimit
}
2025-02-21 18:02:00 -07:00
func SetObcAllowAdditionalConfigFields () {
strval := k8sutil . GetOperatorSetting ( obcAllowAdditionalConfigFieldsSettingName , obcAllowAdditionalConfigFieldsDefaultValue )
2025-02-07 14:56:24 -07:00
obcAllowAdditionalConfigFields = strings . Split ( strval , "," )
}
func ObcAdditionalConfigKeyIsAllowed ( configField string ) bool {
return slices . Contains ( obcAllowAdditionalConfigFields , configField )
}
2020-10-27 00:53:51 +00:00
// canIgnoreHealthErrStatusInReconcile determines whether a status of HEALTH_ERR in the CephCluster can be ignored safely.
func canIgnoreHealthErrStatusInReconcile ( cephCluster cephv1 . CephCluster , controllerName string ) bool {
// Get a list of all the keys causing the HEALTH_ERR status.
2025-03-13 15:24:58 -07:00
healthErrKeys := make ([] string , 0 )
2020-10-27 00:53:51 +00:00
for key , health := range cephCluster . Status . CephStatus . Details {
if health . Severity == "HEALTH_ERR" {
healthErrKeys = append ( healthErrKeys , key )
}
}
2025-02-26 16:16:19 -07:00
// If there are no errors, the caller actually expects false to be returned so the absence
// of an error doesn't cause the health status to be ignored. In production, if there are no
// errors, we would anyway expect the health status to be ok or warning. False in this case
// will cover if the health status is blank.
if len ( healthErrKeys ) == 0 {
return false
2020-10-27 00:53:51 +00:00
}
2025-02-26 16:16:19 -07:00
allowedErrStatus := map [ string ] struct {}{
"MDS_ALL_DOWN" : {},
"MGR_MODULE_ERROR" : {},
}
allCanBeIgnored := true
for _ , healthErrKey := range healthErrKeys {
if _ , ok := allowedErrStatus [ healthErrKey ]; ! ok {
allCanBeIgnored = false
break
}
}
if allCanBeIgnored {
logger . Debugf ( "%q: ignoring ceph error status (full status is %+v)" , controllerName , cephCluster . Status . CephStatus )
return true
}
return false
2020-10-27 00:53:51 +00:00
}
2020-02-25 18:07:01 +01:00
// IsReadyToReconcile determines if a controller is ready to reconcile or not
2021-10-26 13:23:11 -06:00
func IsReadyToReconcile ( ctx context . Context , c client . Client , namespacedName types . NamespacedName , controllerName string ) ( cephv1 . CephCluster , bool , bool , reconcile . Result ) {
2020-04-21 13:28:39 -06:00
cephClusterExists := false
2020-02-25 18:07:01 +01:00
// Running ceph commands won't work and the controller will keep re-queuing so I believe it's fine not to check
// Make sure a CephCluster exists before doing anything
2020-04-21 13:28:39 -06:00
var cephCluster cephv1 . CephCluster
clusterList := & cephv1 . CephClusterList {}
2021-10-23 20:29:41 +09:00
err := c . List ( ctx , clusterList , client . InNamespace ( namespacedName . Namespace ))
2020-02-25 18:07:01 +01:00
if err != nil {
2025-12-03 10:35:58 -07:00
log . NamedError ( namespacedName , logger , "%q: failed to fetch CephCluster %v" , controllerName , err )
2020-06-09 18:16:58 +02:00
return cephCluster , false , cephClusterExists , ImmediateRetryResult
2020-02-25 18:07:01 +01:00
}
2020-04-21 13:28:39 -06:00
if len ( clusterList . Items ) == 0 {
2025-12-03 10:35:58 -07:00
log . NamedDebug ( namespacedName , logger , "%q: no CephCluster resource found in namespace" , controllerName )
2020-06-09 18:16:58 +02:00
return cephCluster , false , cephClusterExists , WaitForRequeueIfCephClusterNotReady
2020-04-21 13:28:39 -06:00
}
cephCluster = clusterList . Items [ 0 ]
2021-10-26 13:23:11 -06:00
// If the cluster has a cleanup policy to destroy the cluster and it has been marked for deletion, treat it as if it does not exist
if cephCluster . Spec . CleanupPolicy . HasDataDirCleanPolicy () && ! cephCluster . DeletionTimestamp . IsZero () {
2025-12-03 10:35:58 -07:00
log . NamedInfo ( namespacedName , logger , "%q: CephCluster has a destructive cleanup policy, allowing it to be deleted" , controllerName )
2021-10-26 13:23:11 -06:00
return cephCluster , false , cephClusterExists , WaitForRequeueIfCephClusterNotReady
}
cephClusterExists = true
2025-12-03 10:35:58 -07:00
log . NamedDebug ( namespacedName , logger , "%q: CephCluster resource found" , controllerName )
2020-02-28 12:33:32 +01:00
2020-06-17 18:21:12 +02:00
// read the CR status of the cluster
if cephCluster . Status . CephStatus != nil {
2025-03-13 15:24:58 -07:00
operatorDeploymentOk := cephCluster . Status . CephStatus . Health == "HEALTH_OK" || cephCluster . Status . CephStatus . Health == "HEALTH_WARN"
2020-10-27 00:53:51 +00:00
if operatorDeploymentOk || canIgnoreHealthErrStatusInReconcile ( cephCluster , controllerName ) {
2025-12-03 10:35:58 -07:00
log . NamedDebug ( namespacedName , logger , "%q: ceph status is %q, operator is ready to run ceph command, reconciling" , controllerName , cephCluster . Status . CephStatus . Health )
2020-06-17 18:21:12 +02:00
return cephCluster , true , cephClusterExists , WaitForRequeueIfCephClusterNotReady
2020-02-25 18:07:01 +01:00
}
2020-10-27 00:53:51 +00:00
2021-01-07 17:24:13 -07:00
details := cephCluster . Status . CephStatus . Details
message , ok := details [ "error" ]
if ok && len ( details ) == 1 && strings . Contains ( message . Message , "Error initializing cluster client" ) {
2025-12-03 10:35:58 -07:00
log . NamedInfo ( namespacedName , logger , "%q: skipping reconcile since operator is still initializing" , controllerName )
2021-01-07 17:24:13 -07:00
} else {
2025-12-03 10:35:58 -07:00
log . NamedInfo ( namespacedName , logger , "%q: CephCluster %q found but skipping reconcile since ceph health is %+v" , controllerName , cephCluster . Name , cephCluster . Status . CephStatus )
2021-01-07 17:24:13 -07:00
}
2020-03-25 16:30:03 +01:00
}
2025-12-03 10:35:58 -07:00
log . NamedDebug ( namespacedName , logger , "%q: CephCluster initial reconcile is not complete yet..." , controllerName )
2020-06-09 18:16:58 +02:00
return cephCluster , false , cephClusterExists , WaitForRequeueIfCephClusterNotReady
2020-02-25 18:07:01 +01:00
}
2020-04-17 18:40:54 +02:00
// ClusterOwnerRef represents the owner reference of the CephCluster CR
func ClusterOwnerRef ( clusterName , clusterID string ) metav1 . OwnerReference {
blockOwner := true
2021-02-18 13:10:11 +00:00
controller := true
2020-04-17 18:40:54 +02:00
return metav1 . OwnerReference {
APIVersion : fmt . Sprintf ( "%s/%s" , ClusterResource . Group , ClusterResource . Version ),
Kind : ClusterResource . Kind ,
Name : clusterName ,
UID : types . UID ( clusterID ),
BlockOwnerDeletion : & blockOwner ,
2021-02-18 13:10:11 +00:00
Controller : & controller ,
2020-04-17 18:40:54 +02:00
}
}
// ClusterResource operator-kit Custom Resource Definition
var ClusterResource = k8sutil . CustomResource {
Name : "cephcluster" ,
Plural : "cephclusters" ,
Group : cephv1 . CustomResourceGroup ,
Version : cephv1 . Version ,
2025-08-28 21:31:04 +08:00
Kind : reflect . TypeFor [ cephv1 . CephCluster ](). Name (),
2020-04-17 18:40:54 +02:00
APIVersion : fmt . Sprintf ( "%s/%s" , cephv1 . CustomResourceGroup , cephv1 . Version ),
}
2025-07-17 13:06:51 +03:00
// RecoverAndLogException handles and logs panics from a controller Reconcile loop.
func RecoverAndLogException () {
if r := recover (); r != nil {
logger . Errorf ( "Panic: %v" , r )
logger . Errorf ( "Stack trace:\n%s" , string ( debug . Stack ()))
}
}
2025-12-03 10:35:58 -07:00
func NsName ( namespace , name string ) types . NamespacedName {
return types . NamespacedName { Namespace : namespace , Name : name }
}