2017-03-27 09:12:56 -07:00
/*
Copyright 2016 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.
*/
2018-08-31 13:39:02 -06:00
2017-07-24 07:43:11 -07:00
package pool
2017-03-27 09:12:56 -07:00
import (
2020-03-02 17:26:50 +01:00
"context"
2022-03-10 12:48:23 -07:00
"fmt"
2020-08-25 09:46:18 +02:00
"os"
2017-03-27 09:12:56 -07:00
"testing"
2021-10-08 11:36:18 +02:00
"time"
2017-03-27 09:12:56 -07:00
2020-08-25 09:46:18 +02:00
"github.com/coreos/pkg/capnslog"
2019-10-08 12:51:36 +02:00
"github.com/pkg/errors"
2018-12-03 15:08:29 -07:00
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
2020-02-25 18:07:01 +01:00
rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake"
2017-09-11 14:56:10 -07:00
"github.com/rook/rook/pkg/clusterd"
2020-07-29 19:21:37 +05:30
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
2022-10-04 20:50:28 +05:30
"github.com/rook/rook/pkg/operator/ceph/config"
2021-04-08 15:44:27 +02:00
opcontroller "github.com/rook/rook/pkg/operator/ceph/controller"
2020-07-10 16:40:16 -06:00
"github.com/rook/rook/pkg/operator/k8sutil"
testop "github.com/rook/rook/pkg/operator/test"
2017-09-11 14:56:10 -07:00
exectest "github.com/rook/rook/pkg/util/exec/test"
2017-03-27 09:12:56 -07:00
"github.com/stretchr/testify/assert"
2021-08-09 13:32:02 +05:30
appsv1 "k8s.io/api/apps/v1"
2020-07-10 16:40:16 -06:00
v1 "k8s.io/api/core/v1"
2017-07-24 07:43:11 -07:00
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2020-02-25 18:07:01 +01:00
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/scheme"
2026-02-09 16:38:26 +05:30
"k8s.io/client-go/tools/events"
2020-02-25 18:07:01 +01:00
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
2017-03-27 09:12:56 -07:00
)
func TestCreatePool ( t * testing . T ) {
2021-12-08 16:14:29 -07:00
p := & cephv1 . NamedPoolSpec {}
enabledMetricsApp := false
2022-03-10 12:48:23 -07:00
enabledMgrApp := false
2022-04-24 17:29:47 +02:00
clusterInfo := cephclient . AdminTestClusterInfo ( "mycluster" )
2017-09-11 14:56:10 -07:00
executor := & exectest . MockExecutor {
2024-09-23 10:53:19 +05:30
MockExecuteCommandWithTimeout : func ( timeout time . Duration , command string , args ... string ) ( string , error ) {
logger . Infof ( "CommandTimeout: %s %v" , command , args )
if command == "rbd" {
if args [ 0 ] == "pool" && args [ 1 ] == "init" {
// assert that `rbd pool init` is only run when application is set to `rbd`
assert . Equal ( t , "rbd" , p . Application )
assert . Equal ( t , p . Name , args [ 2 ])
return "{}" , nil
}
}
return "" , nil
},
2021-07-21 11:25:52 +02:00
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
2020-03-24 22:15:11 -06:00
logger . Infof ( "Command: %s %v" , command , args )
2021-12-08 16:14:29 -07:00
if command == "ceph" {
if args [ 1 ] == "erasure-code-profile" {
return `{"k":"2","m":"1","plugin":"jerasure","technique":"reed_sol_van"}` , nil
}
if args [ 0 ] == "osd" && args [ 1 ] == "pool" && args [ 2 ] == "application" {
2022-01-25 15:05:18 -07:00
if args [ 3 ] == "get" {
return `` , nil
}
2021-12-08 16:14:29 -07:00
assert . Equal ( t , "enable" , args [ 3 ])
if args [ 5 ] != "rbd" {
2024-02-09 12:25:09 -07:00
if args [ 4 ] == ".mgr" {
2022-03-10 12:48:23 -07:00
enabledMgrApp = true
assert . Equal ( t , ".mgr" , args [ 4 ])
assert . Equal ( t , "mgr" , args [ 5 ])
} else {
2024-09-23 10:53:19 +05:30
fmt . Printf ( "pool - %v" , args )
2022-03-10 12:48:23 -07:00
assert . Fail ( t , fmt . Sprintf ( "invalid pool %q" , args [ 4 ]))
}
2021-12-08 16:14:29 -07:00
}
}
2017-09-11 14:56:10 -07:00
}
2021-10-06 16:32:30 +05:30
if command == "rbd" {
2024-03-11 08:38:24 +05:30
if args [ 0 ] == "mirror" && args [ 2 ] == "info" {
return "{}" , nil
} else if args [ 0 ] == "mirror" && args [ 2 ] == "disable" {
return "" , nil
}
2021-10-06 16:32:30 +05:30
}
2017-09-11 14:56:10 -07:00
return "" , nil
},
}
2024-09-23 10:53:19 +05:30
2017-09-11 14:56:10 -07:00
context := & clusterd . Context { Executor : executor }
2017-03-27 09:12:56 -07:00
2021-05-14 18:03:38 -06:00
clusterSpec := & cephv1 . ClusterSpec { Storage : cephv1 . StorageScopeSpec { Config : map [ string ] string { cephclient . CrushRootConfigKey : "cluster-crush-root" }}}
2017-03-27 09:12:56 -07:00
2021-12-08 16:14:29 -07:00
t . Run ( "replicated pool" , func ( t * testing . T ) {
p . Name = "replicapool"
p . Replicated . Size = 1
p . Replicated . RequireSafeReplicaSize = false
2024-09-23 10:53:19 +05:30
// reset the application name
p . Application = ""
2021-12-08 16:14:29 -07:00
err := createPool ( context , clusterInfo , clusterSpec , p )
assert . Nil ( t , err )
assert . False ( t , enabledMetricsApp )
})
2022-03-10 12:48:23 -07:00
t . Run ( "built-in mgr pool" , func ( t * testing . T ) {
p . Name = ".mgr"
2024-09-23 10:53:19 +05:30
// reset the application name
p . Application = ""
2022-03-10 12:48:23 -07:00
err := createPool ( context , clusterInfo , clusterSpec , p )
assert . Nil ( t , err )
assert . True ( t , enabledMgrApp )
})
2021-12-08 16:14:29 -07:00
t . Run ( "ec pool" , func ( t * testing . T ) {
p . Name = "ecpool"
p . Replicated . Size = 0
p . ErasureCoded . CodingChunks = 1
p . ErasureCoded . DataChunks = 2
2024-09-23 10:53:19 +05:30
// reset the application name
p . Application = ""
2021-12-08 16:14:29 -07:00
err := createPool ( context , clusterInfo , clusterSpec , p )
assert . Nil ( t , err )
})
}
func TestCephPoolName ( t * testing . T ) {
t . Run ( "spec not set" , func ( t * testing . T ) {
p := cephv1 . CephBlockPool { ObjectMeta : metav1 . ObjectMeta { Name : "metapool" }}
2022-05-31 15:47:29 -06:00
name := p . ToNamedPoolSpec (). Name
2021-12-08 16:14:29 -07:00
assert . Equal ( t , "metapool" , name )
})
t . Run ( "same name already set" , func ( t * testing . T ) {
p := cephv1 . CephBlockPool { ObjectMeta : metav1 . ObjectMeta { Name : "metapool" }, Spec : cephv1 . NamedBlockPoolSpec { Name : "metapool" }}
2022-05-31 15:47:29 -06:00
name := p . ToNamedPoolSpec (). Name
2021-12-08 16:14:29 -07:00
assert . Equal ( t , "metapool" , name )
})
2022-05-31 15:47:29 -06:00
t . Run ( "override mgr" , func ( t * testing . T ) {
p := cephv1 . CephBlockPool { ObjectMeta : metav1 . ObjectMeta { Name : "default-mgr" }, Spec : cephv1 . NamedBlockPoolSpec { Name : ".mgr" }}
name := p . ToNamedPoolSpec (). Name
assert . Equal ( t , ".mgr" , name )
})
2021-12-08 16:14:29 -07:00
t . Run ( "override nfs" , func ( t * testing . T ) {
p := cephv1 . CephBlockPool { ObjectMeta : metav1 . ObjectMeta { Name : "default-nfs" }, Spec : cephv1 . NamedBlockPoolSpec { Name : ".nfs" }}
2022-05-31 15:47:29 -06:00
name := p . ToNamedPoolSpec (). Name
2021-12-08 16:14:29 -07:00
assert . Equal ( t , ".nfs" , name )
})
2017-03-27 09:12:56 -07:00
}
func TestDeletePool ( t * testing . T ) {
2019-09-24 15:05:42 +05:30
failOnDelete := false
2021-11-18 15:22:56 -07:00
clusterInfo := cephclient . AdminTestClusterInfo ( "mycluster" )
2017-09-11 14:56:10 -07:00
executor := & exectest . MockExecutor {
2020-03-18 11:53:33 -06:00
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
2019-09-24 15:05:42 +05:30
emptyPool := "{\"images\":{\"count\":0,\"provisioned_bytes\":0,\"snap_count\":0},\"trash\":{\"count\":1,\"provisioned_bytes\":2048,\"snap_count\":0}}"
p := "{\"images\":{\"count\":1,\"provisioned_bytes\":1024,\"snap_count\":0},\"trash\":{\"count\":1,\"provisioned_bytes\":2048,\"snap_count\":0}}"
logger . Infof ( "Command: %s %v" , command , args )
2021-07-21 11:25:52 +02:00
if command == "ceph" && args [ 1 ] == "lspools" {
return `[{"poolnum":1,"poolname":"mypool"}]` , nil
} else if command == "ceph" && args [ 1 ] == "pool" && args [ 2 ] == "get" {
return `{"pool": "mypool","pool_id": 1,"size":1}` , nil
} else if command == "ceph" && args [ 1 ] == "pool" && args [ 2 ] == "delete" {
return "" , nil
} else if args [ 0 ] == "pool" {
2019-09-24 15:05:42 +05:30
if args [ 1 ] == "stats" {
if ! failOnDelete {
return emptyPool , nil
}
return p , nil
}
2019-10-08 12:51:36 +02:00
return "" , errors . Errorf ( "rbd: error opening pool %q: (2) No such file or directory" , args [ 3 ])
2019-09-24 15:05:42 +05:30
}
2019-10-08 12:51:36 +02:00
return "" , errors . Errorf ( "unexpected rbd command %q" , args )
2019-09-24 15:05:42 +05:30
},
2017-03-27 09:12:56 -07:00
}
2017-09-11 14:56:10 -07:00
context := & clusterd . Context { Executor : executor }
2017-03-27 09:12:56 -07:00
// delete a pool that exists
2021-12-08 16:14:29 -07:00
p := & cephv1 . NamedPoolSpec { Name : "mypool" }
2020-07-10 16:40:16 -06:00
err := deletePool ( context , clusterInfo , p )
2025-05-01 21:03:12 -06:00
assert . NoError ( t , err )
2017-03-27 09:12:56 -07:00
// succeed even if the pool doesn't exist
2021-12-08 16:14:29 -07:00
p = & cephv1 . NamedPoolSpec { Name : "otherpool" }
2020-07-10 16:40:16 -06:00
err = deletePool ( context , clusterInfo , p )
2017-03-27 09:12:56 -07:00
assert . Nil ( t , err )
2019-09-24 15:05:42 +05:30
// fail if images/snapshosts exist in the pool
failOnDelete = true
2021-12-08 16:14:29 -07:00
p = & cephv1 . NamedPoolSpec { Name : "mypool" }
2020-07-10 16:40:16 -06:00
err = deletePool ( context , clusterInfo , p )
2025-05-01 21:03:12 -06:00
assert . Error ( t , err )
2017-03-27 09:12:56 -07:00
}
2018-05-18 14:32:20 -07:00
2020-02-25 18:07:01 +01:00
// TestCephBlockPoolController runs ReconcileCephBlockPool.Reconcile() against a
// fake client that tracks a CephBlockPool object.
func TestCephBlockPoolController ( t * testing . T ) {
2020-11-16 17:29:56 +05:30
ctx := context . TODO ()
2020-08-25 09:46:18 +02:00
// Set DEBUG logging
capnslog . SetGlobalLogLevel ( capnslog . DEBUG )
os . Setenv ( "ROOK_LOG_LEVEL" , "DEBUG" )
2020-02-25 18:07:01 +01:00
var (
name = "my-pool"
namespace = "rook-ceph"
replicas uint = 3
)
2018-05-18 14:32:20 -07:00
2020-02-25 18:07:01 +01:00
// A Pool resource with metadata and spec.
pool := & cephv1 . CephBlockPool {
ObjectMeta : metav1 . ObjectMeta {
2025-03-21 13:48:30 -06:00
Name : name ,
Namespace : namespace ,
UID : types . UID ( "c47cac40-9bee-4d52-823b-ccd803ba5bfe" ),
Finalizers : [] string { "cephblockpool.ceph.rook.io" },
},
TypeMeta : metav1 . TypeMeta {
Kind : "CephBlockPool" ,
2020-02-25 18:07:01 +01:00
},
2021-12-08 16:14:29 -07:00
Spec : cephv1 . NamedBlockPoolSpec {
PoolSpec : cephv1 . PoolSpec {
Replicated : cephv1 . ReplicatedSpec {
Size : replicas ,
},
Mirroring : cephv1 . MirroringSpec {
Peers : & cephv1 . MirroringPeerSpec {},
},
StatusCheck : cephv1 . MirrorHealthCheckSpec {
Mirror : cephv1 . HealthCheckSpec {
Disabled : true ,
},
2021-01-29 18:21:58 +01:00
},
},
2020-02-25 18:07:01 +01:00
},
2020-08-25 09:46:18 +02:00
Status : & cephv1 . CephBlockPoolStatus {
2020-02-25 18:07:01 +01:00
Phase : "" ,
},
}
// Objects to track in the fake client.
object := [] runtime . Object {
pool ,
}
executor := & exectest . MockExecutor {
2021-07-21 11:25:52 +02:00
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
2020-02-25 18:07:01 +01:00
if args [ 0 ] == "status" {
2020-03-25 16:30:03 +01:00
return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_ERR"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}` , nil
2020-02-25 18:07:01 +01:00
}
return "" , nil
},
}
2020-03-02 17:26:50 +01:00
c := & clusterd . Context {
2021-08-06 17:46:01 +02:00
Executor : executor ,
Clientset : testop . New ( t , 1 ),
RookClientset : rookclient . NewSimpleClientset (),
2020-07-10 16:40:16 -06:00
}
2020-02-25 18:07:01 +01:00
// Register operator types with the runtime scheme.
s := scheme . Scheme
2020-07-29 19:21:37 +05:30
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , pool , & cephv1 . CephClusterList {})
2020-02-25 18:07:01 +01:00
// Create a fake client to mock API calls.
2021-01-12 13:14:07 +01:00
cl := fake . NewClientBuilder (). WithRuntimeObjects ( object ... ). Build ()
2020-02-25 18:07:01 +01:00
// Create a ReconcileCephBlockPool object with the scheme and fake client.
2020-08-25 09:46:18 +02:00
r := & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
2021-08-06 17:46:01 +02:00
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2020-08-25 09:46:18 +02:00
}
2020-02-25 18:07:01 +01:00
// Mock request to simulate Reconcile() being called on an event for a
// watched resource .
req := reconcile . Request {
NamespacedName : types . NamespacedName {
Name : name ,
Namespace : namespace ,
},
}
2021-08-06 17:46:01 +02:00
cephCluster := & cephv1 . CephCluster {}
2020-02-25 18:07:01 +01:00
2021-08-06 17:46:01 +02:00
t . Run ( "failure no CephCluster" , func ( t * testing . T ) {
// Create pool for updateCephBlockPoolStatus()
_ , err := c . RookClientset . CephV1 (). CephBlockPools ( namespace ). Create ( ctx , pool , metav1 . CreateOptions {})
assert . NoError ( t , err )
res , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
assert . True ( t , res . Requeue )
})
t . Run ( "failure CephCluster not ready" , func ( t * testing . T ) {
cephCluster = & cephv1 . CephCluster {
ObjectMeta : metav1 . ObjectMeta {
Name : namespace ,
Namespace : namespace ,
2020-06-09 18:16:58 +02:00
},
2021-08-06 17:46:01 +02:00
Status : cephv1 . ClusterStatus {
Phase : "" ,
CephVersion : & cephv1 . ClusterVersion {
Version : "14.2.9-0" ,
},
CephStatus : & cephv1 . CephStatus {
Health : "" ,
},
2025-08-18 14:53:08 -06:00
Cephx : cephv1 . ClusterCephxStatus {},
2020-06-17 18:21:12 +02:00
},
2021-08-06 17:46:01 +02:00
}
2020-04-21 13:28:39 -06:00
2021-08-06 17:46:01 +02:00
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephCluster {}, & cephv1 . CephClusterList {})
2020-02-25 18:07:01 +01:00
2021-08-06 17:46:01 +02:00
// Create CephCluster for updateCephBlockPoolStatus()
_ , err := c . RookClientset . CephV1 (). CephClusters ( namespace ). Create ( ctx , cephCluster , metav1 . CreateOptions {})
assert . NoError ( t , err )
2020-02-25 18:07:01 +01:00
2021-08-06 17:46:01 +02:00
object = append ( object , cephCluster )
// Create a fake client to mock API calls.
cl = fake . NewClientBuilder (). WithRuntimeObjects ( object ... ). Build ()
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r = & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2021-08-06 17:46:01 +02:00
}
2020-02-25 18:07:01 +01:00
2021-08-06 17:46:01 +02:00
res , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
assert . True ( t , res . Requeue )
})
2020-06-17 18:21:12 +02:00
2021-08-06 17:46:01 +02:00
t . Run ( "failure CephCluster is ready" , func ( t * testing . T ) {
cephCluster . Status . Phase = cephv1 . ConditionReady
cephCluster . Status . CephStatus . Health = "HEALTH_OK"
objects := [] runtime . Object {
pool ,
cephCluster ,
}
// Create a fake client to mock API calls.
cl = fake . NewClientBuilder (). WithRuntimeObjects ( objects ... ). Build ()
c . Client = cl
executor = & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
if args [ 0 ] == "status" {
return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_OK"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}` , nil
}
2022-07-11 17:21:19 +03:00
if args [ 0 ] == "config" && args [ 2 ] == "mgr" && args [ 3 ] == "mgr/prometheus/rbd_stats_pools" {
2021-08-06 17:46:01 +02:00
return "" , nil
}
2024-03-11 08:38:24 +05:30
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "info" {
return "{}" , nil
}
2020-07-29 19:21:37 +05:30
return "" , nil
2021-08-06 17:46:01 +02:00
},
}
c . Executor = executor
2020-03-25 16:30:03 +01:00
2021-08-06 17:46:01 +02:00
// Mock clusterInfo
secrets := map [ string ][] byte {
"fsid" : [] byte ( name ),
"mon-secret" : [] byte ( "monsecret" ),
"admin-secret" : [] byte ( "adminsecret" ),
}
secret := & v1 . Secret {
ObjectMeta : metav1 . ObjectMeta {
Name : "rook-ceph-mon" ,
Namespace : namespace ,
},
Data : secrets ,
Type : k8sutil . RookType ,
}
_ , err := c . Clientset . CoreV1 (). Secrets ( namespace ). Create ( ctx , secret , metav1 . CreateOptions {})
assert . NoError ( t , err )
2020-03-25 16:30:03 +01:00
2021-08-06 17:46:01 +02:00
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephBlockPoolList {})
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r = & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2021-08-06 17:46:01 +02:00
}
res , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
assert . False ( t , res . Requeue )
2020-07-10 16:40:16 -06:00
2021-08-06 17:46:01 +02:00
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
assert . Equal ( t , cephv1 . ConditionReady , pool . Status . Phase )
})
2020-02-25 18:07:01 +01:00
2021-08-06 17:46:01 +02:00
t . Run ( "failure no mirror mode" , func ( t * testing . T ) {
pool . Spec . Mirroring . Enabled = true
err := r . client . Update ( context . TODO (), pool )
assert . NoError ( t , err )
res , err := r . Reconcile ( ctx , req )
2022-02-24 13:06:06 +05:30
assert . NoError ( t , err )
2021-08-06 17:46:01 +02:00
assert . True ( t , res . Requeue )
})
2020-08-25 09:46:18 +02:00
2022-07-15 22:44:09 +08:00
t . Setenv ( "POD_NAME" , "test" )
t . Setenv ( "POD_NAMESPACE" , namespace )
2021-08-06 17:46:01 +02:00
p := & v1 . Pod {
2021-08-09 13:32:02 +05:30
ObjectMeta : metav1 . ObjectMeta {
Name : "test" ,
Namespace : namespace ,
OwnerReferences : [] metav1 . OwnerReference {
{
Kind : "ReplicaSet" ,
Name : "testReplicaSet" ,
},
},
},
}
// Create fake pod
2021-08-06 17:46:01 +02:00
_ , err := r . context . Clientset . CoreV1 (). Pods ( namespace ). Create ( context . TODO (), p , metav1 . CreateOptions {})
2021-08-09 13:32:02 +05:30
assert . NoError ( t , err )
replicaSet := & appsv1 . ReplicaSet {
ObjectMeta : metav1 . ObjectMeta {
Name : "testReplicaSet" ,
Namespace : namespace ,
OwnerReferences : [] metav1 . OwnerReference {
{
Kind : "Deployment" ,
},
},
},
}
// Create fake replicaset
_ , err = r . context . Clientset . AppsV1 (). ReplicaSets ( namespace ). Create ( context . TODO (), replicaSet , metav1 . CreateOptions {})
assert . NoError ( t , err )
2021-08-06 17:46:01 +02:00
t . Run ( "success - mirroring set" , func ( t * testing . T ) {
executor = & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "peer" && args [ 3 ] == "bootstrap" && args [ 4 ] == "create" {
return `eyJmc2lkIjoiYzZiMDg3ZjItNzgyOS00ZGJiLWJjZmMtNTNkYzM0ZTBiMzVkIiwiY2xpZW50X2lkIjoicmJkLW1pcnJvci1wZWVyIiwia2V5IjoiQVFBV1lsWmZVQ1Q2RGhBQVBtVnAwbGtubDA5YVZWS3lyRVV1NEE9PSIsIm1vbl9ob3N0IjoiW3YyOjE5Mi4xNjguMTExLjEwOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTA6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjEyOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTI6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjExOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTE6Njc4OV0ifQ==` , nil
}
2024-03-11 08:38:24 +05:30
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "info" {
return "{}" , nil
}
2021-08-06 17:46:01 +02:00
return "" , nil
},
}
c . Executor = executor
r = & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2021-08-06 17:46:01 +02:00
}
pool . Spec . Mirroring . Mode = "image"
pool . Spec . Mirroring . Peers . SecretNames = [] string {}
err = r . client . Update ( context . TODO (), pool )
assert . NoError ( t , err )
for i := 0 ; i < 5 ; i ++ {
res , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
assert . False ( t , res . Requeue )
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
assert . Equal ( t , cephv1 . ConditionReady , pool . Status . Phase )
if _ , ok := pool . Status . Info [ opcontroller . RBDMirrorBootstrapPeerSecretName ]; ok {
break
}
logger . Infof ( "FIX: trying again to update the mirroring status" )
}
assert . NotEmpty ( t , pool . Status . Info [ opcontroller . RBDMirrorBootstrapPeerSecretName ], pool . Status . Info )
// fetch the secret
myPeerSecret , err := c . Clientset . CoreV1 (). Secrets ( namespace ). Get ( ctx , pool . Status . Info [ opcontroller . RBDMirrorBootstrapPeerSecretName ], metav1 . GetOptions {})
assert . NoError ( t , err )
if myPeerSecret != nil {
assert . NotEmpty ( t , myPeerSecret . Data [ "token" ], myPeerSecret . Data )
assert . NotEmpty ( t , myPeerSecret . Data [ "pool" ])
}
})
peerSecretName := "peer-secret"
t . Run ( "failure - import peer token but was not created" , func ( t * testing . T ) {
// Create a fake client to mock API calls.
cl = fake . NewClientBuilder (). WithScheme ( s ). WithRuntimeObjects ( object ... ). Build ()
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r = & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2021-08-06 17:46:01 +02:00
}
pool . Spec . Mirroring . Peers . SecretNames = [] string { peerSecretName }
err := r . client . Update ( context . TODO (), pool )
assert . NoError ( t , err )
res , err := r . Reconcile ( ctx , req )
2024-05-27 10:26:34 +05:30
// assert reconcile failure because peer token secret was not created
2022-02-24 13:06:06 +05:30
assert . NoError ( t , err )
2021-08-06 17:46:01 +02:00
assert . True ( t , res . Requeue )
})
t . Run ( "success - import peer token but was created" , func ( t * testing . T ) {
bootstrapPeerToken := `eyJmc2lkIjoiYzZiMDg3ZjItNzgyOS00ZGJiLWJjZmMtNTNkYzM0ZTBiMzVkIiwiY2xpZW50X2lkIjoicmJkLW1pcnJvci1wZWVyIiwia2V5IjoiQVFBV1lsWmZVQ1Q2RGhBQVBtVnAwbGtubDA5YVZWS3lyRVV1NEE9PSIsIm1vbl9ob3N0IjoiW3YyOjE5Mi4xNjguMTExLjEwOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTA6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjEyOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTI6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjExOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTE6Njc4OV0ifQ==` //nolint:gosec // This is just a var name, not a real token
peerSecret := & v1 . Secret {
ObjectMeta : metav1 . ObjectMeta {
Name : peerSecretName ,
Namespace : namespace ,
},
Data : map [ string ][] byte { "token" : [] byte ( bootstrapPeerToken ), "pool" : [] byte ( "goo" )},
Type : k8sutil . RookType ,
}
_ , err := c . Clientset . CoreV1 (). Secrets ( namespace ). Create ( ctx , peerSecret , metav1 . CreateOptions {})
assert . NoError ( t , err )
res , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
assert . False ( t , res . Requeue )
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
})
t . Run ( "failure - mirroring disabled" , func ( t * testing . T ) {
r = & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2021-08-06 17:46:01 +02:00
}
pool . Spec . Mirroring . Enabled = false
pool . Spec . Mirroring . Mode = "image"
err := r . client . Update ( context . TODO (), pool )
assert . NoError ( t , err )
res , err := r . Reconcile ( ctx , req )
2020-12-04 15:37:30 -07:00
assert . NoError ( t , err )
assert . False ( t , res . Requeue )
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
assert . Equal ( t , cephv1 . ConditionReady , pool . Status . Phase )
2025-09-22 20:36:57 +05:30
assert . Equal ( t , pool . Status . MirroringStatus , & cephv1 . MirroringStatusSpec {})
2021-08-06 17:46:01 +02:00
})
2018-05-18 14:32:20 -07:00
}
2020-07-29 19:21:37 +05:30
2025-05-01 21:03:12 -06:00
func TestDeletionBlocked ( t * testing . T ) {
// A Pool resource with metadata and spec.
pool := & cephv1 . CephBlockPool {
ObjectMeta : metav1 . ObjectMeta {
Name : "test-pool" ,
Namespace : "ns" ,
},
TypeMeta : metav1 . TypeMeta {
Kind : "CephBlockPool" ,
},
Status : & cephv1 . CephBlockPoolStatus {},
}
object := [] runtime . Object { pool }
// Register operator types with the runtime scheme.
s := scheme . Scheme
s . AddKnownTypes ( cephv1 . SchemeGroupVersion ,
& cephv1 . CephBlockPoolList {},
& cephv1 . CephBlockPoolRadosNamespaceList {},
& cephv1 . CephBlockPool {},
& cephv1 . CephBlockPoolRadosNamespace {},
)
blockImageCount := 0
rnsImageCount := 0
2025-08-15 18:27:46 +04:00
poolPresent := false
2025-05-01 21:03:12 -06:00
cl := fake . NewClientBuilder (). WithScheme ( s ). WithRuntimeObjects ( object ... ). Build ()
executor := & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
logger . Infof ( "Command: %s %v" , command , args )
if args [ 0 ] == "pool" {
if args [ 1 ] == "stats" {
response := "{\"images\":{\"count\":%d,\"provisioned_bytes\":0,\"snap_count\":0},\"trash\":{\"count\":1,\"provisioned_bytes\":2048,\"snap_count\":0}}"
if args [ 4 ] == "--namespace" {
return fmt . Sprintf ( response , rnsImageCount ), nil
} else {
return fmt . Sprintf ( response , blockImageCount ), nil
}
}
2025-08-15 18:27:46 +04:00
} else if command == "ceph" && args [ 0 ] == "osd" {
if args [ 1 ] == "lspools" {
if poolPresent {
return fmt . Sprintf ( `[{"poolnum":1,"poolname":"%s"}]` , pool . Name ), nil
} else {
return "[]" , nil
}
}
2025-05-01 21:03:12 -06:00
}
return "not implemented" , nil
},
}
c := & clusterd . Context {
Executor : executor ,
Clientset : testop . New ( t , 1 ),
RookClientset : rookclient . NewSimpleClientset (),
}
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r := & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2025-05-01 21:03:12 -06:00
clusterInfo : cephclient . AdminTestClusterInfo ( "mycluster" ),
}
cephCluster := & cephv1 . CephCluster {}
2025-08-15 18:27:46 +04:00
t . Run ( "deletion is allowed with no pool actually present" , func ( t * testing . T ) {
err := r . handleDeletionBlocked ( pool , cephCluster )
assert . NoError ( t , err )
result := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), types . NamespacedName { Name : pool . Name , Namespace : pool . Namespace }, result )
assert . NoError ( t , err )
assert . Equal ( t , pool . Name , result . Name )
assert . Equal ( t , pool . Namespace , result . Namespace )
assert . Equal ( t , 2 , len ( pool . Status . Conditions ))
assert . Equal ( t , "PoolDeletionIsBlocked" , string ( pool . Status . Conditions [ 0 ]. Type ))
assert . Equal ( t , v1 . ConditionFalse , pool . Status . Conditions [ 0 ]. Status )
assert . Equal ( t , "PoolEmpty" , string ( pool . Status . Conditions [ 0 ]. Reason ))
assert . Equal ( t , "DeletionIsBlocked" , string ( pool . Status . Conditions [ 1 ]. Type ))
assert . Equal ( t , v1 . ConditionFalse , pool . Status . Conditions [ 1 ]. Status )
assert . Equal ( t , "ObjectHasNoDependents" , string ( pool . Status . Conditions [ 1 ]. Reason ))
})
poolPresent = true
2025-05-01 21:03:12 -06:00
t . Run ( "deletion is allowed with no images or rns" , func ( t * testing . T ) {
err := r . handleDeletionBlocked ( pool , cephCluster )
assert . NoError ( t , err )
result := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), types . NamespacedName { Name : pool . Name , Namespace : pool . Namespace }, result )
assert . NoError ( t , err )
assert . Equal ( t , pool . Name , result . Name )
assert . Equal ( t , pool . Namespace , result . Namespace )
assert . Equal ( t , 2 , len ( pool . Status . Conditions ))
assert . Equal ( t , "PoolDeletionIsBlocked" , string ( pool . Status . Conditions [ 0 ]. Type ))
assert . Equal ( t , v1 . ConditionFalse , pool . Status . Conditions [ 0 ]. Status )
assert . Equal ( t , "PoolEmpty" , string ( pool . Status . Conditions [ 0 ]. Reason ))
assert . Equal ( t , "DeletionIsBlocked" , string ( pool . Status . Conditions [ 1 ]. Type ))
assert . Equal ( t , v1 . ConditionFalse , pool . Status . Conditions [ 1 ]. Status )
assert . Equal ( t , "ObjectHasNoDependents" , string ( pool . Status . Conditions [ 1 ]. Reason ))
})
t . Run ( "image prevents deletion" , func ( t * testing . T ) {
blockImageCount = 1
err := r . handleDeletionBlocked ( pool , cephCluster )
assert . Error ( t , err )
result := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), types . NamespacedName { Name : pool . Name , Namespace : pool . Namespace }, result )
assert . NoError ( t , err )
assert . Equal ( t , pool . Name , result . Name )
assert . Equal ( t , pool . Namespace , result . Namespace )
assert . Equal ( t , 2 , len ( pool . Status . Conditions ))
assert . Equal ( t , "PoolDeletionIsBlocked" , string ( pool . Status . Conditions [ 0 ]. Type ))
assert . Equal ( t , v1 . ConditionTrue , pool . Status . Conditions [ 0 ]. Status )
assert . Equal ( t , "PoolNotEmpty" , string ( pool . Status . Conditions [ 0 ]. Reason ))
assert . Equal ( t , "DeletionIsBlocked" , string ( pool . Status . Conditions [ 1 ]. Type ))
assert . Equal ( t , v1 . ConditionFalse , pool . Status . Conditions [ 1 ]. Status )
assert . Equal ( t , "ObjectHasNoDependents" , string ( pool . Status . Conditions [ 1 ]. Reason ))
})
t . Run ( "rados namespace prevents deletion" , func ( t * testing . T ) {
radosNamespace := & cephv1 . CephBlockPoolRadosNamespace {
ObjectMeta : metav1 . ObjectMeta {
Name : "test-rns" ,
Namespace : pool . Namespace ,
},
Spec : cephv1 . CephBlockPoolRadosNamespaceSpec {
BlockPoolName : pool . Name ,
},
}
_ , err := c . RookClientset . CephV1 (). CephBlockPoolRadosNamespaces ( pool . Namespace ). Create ( context . TODO (), radosNamespace , metav1 . CreateOptions {})
assert . NoError ( t , err )
// A radosnamespaces prevents deletion of the pool
blockImageCount = 0
rnsImageCount = 1
err = r . handleDeletionBlocked ( pool , cephCluster )
assert . Error ( t , err )
result := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), types . NamespacedName { Name : pool . Name , Namespace : pool . Namespace }, result )
assert . NoError ( t , err )
assert . Equal ( t , pool . Name , result . Name )
assert . Equal ( t , pool . Namespace , result . Namespace )
assert . Equal ( t , 2 , len ( pool . Status . Conditions ))
assert . Equal ( t , "PoolDeletionIsBlocked" , string ( pool . Status . Conditions [ 0 ]. Type ))
assert . Equal ( t , v1 . ConditionTrue , pool . Status . Conditions [ 0 ]. Status )
assert . Equal ( t , "PoolNotEmpty" , string ( pool . Status . Conditions [ 0 ]. Reason ))
assert . Equal ( t , "DeletionIsBlocked" , string ( pool . Status . Conditions [ 1 ]. Type ))
assert . Equal ( t , v1 . ConditionTrue , pool . Status . Conditions [ 1 ]. Status )
assert . Equal ( t , "ObjectHasDependents" , string ( pool . Status . Conditions [ 1 ]. Reason ))
})
}
2024-09-09 15:49:36 +05:30
func TestIsAnyRadosNamespaceMirrored ( t * testing . T ) {
pool := "test"
object := [] runtime . Object {}
// Register operator types with the runtime scheme.
s := scheme . Scheme
cl := fake . NewClientBuilder (). WithScheme ( s ). WithRuntimeObjects ( object ... ). Build ()
executor := & exectest . MockExecutor {}
c := & clusterd . Context {
Executor : executor ,
Clientset : testop . New ( t , 1 ),
RookClientset : rookclient . NewSimpleClientset (),
}
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r := & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2024-09-09 15:49:36 +05:30
clusterInfo : cephclient . AdminTestClusterInfo ( "mycluster" ),
}
t . Run ( "rados namespace mirroring enabled" , func ( t * testing . T ) {
r . context . Executor = & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
if args [ 0 ] == "namespace" {
assert . Equal ( t , pool , args [ 2 ])
return `[{"name":"abc"},{"name":"abc1"},{"name":"abc3"}]` , nil
}
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "info" {
return "{}" , nil
}
return "" , nil
},
}
enabled , err := r . isAnyRadosNamespaceMirrored ( pool )
assert . NoError ( t , err )
assert . True ( t , enabled )
})
t . Run ( "rados namespace mirroring disabled" , func ( t * testing . T ) {
r . context . Executor = & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
if args [ 0 ] == "namespace" {
assert . Equal ( t , pool , args [ 2 ])
return `[]` , nil
}
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "info" {
return "{}" , nil
}
return "" , nil
},
}
enabled , err := r . isAnyRadosNamespaceMirrored ( pool )
assert . NoError ( t , err )
assert . False ( t , enabled )
})
}
2020-07-29 19:21:37 +05:30
func TestConfigureRBDStats ( t * testing . T ) {
var (
s = runtime . NewScheme ()
context = & clusterd . Context {}
namespace = "rook-ceph"
)
2022-10-04 20:50:28 +05:30
mockedPools := ""
2020-07-29 19:21:37 +05:30
executor := & exectest . MockExecutor {
2021-10-08 11:36:18 +02:00
MockExecuteCommandWithTimeout : func ( timeout time . Duration , command string , args ... string ) ( string , error ) {
2020-07-29 19:21:37 +05:30
logger . Infof ( "Command: %s %v" , command , args )
2022-07-11 17:21:19 +03:00
if args [ 0 ] == "config" && args [ 2 ] == "mgr" && args [ 3 ] == "mgr/prometheus/rbd_stats_pools" {
2022-10-04 20:50:28 +05:30
if args [ 1 ] == "set" {
2024-10-23 20:51:49 +03:00
mockedPools = args [ 4 ]
2021-08-24 14:38:26 -06:00
return "" , nil
}
if args [ 1 ] == "get" {
2022-10-04 20:50:28 +05:30
return mockedPools , nil
2021-08-24 14:38:26 -06:00
}
if args [ 1 ] == "rm" {
2024-10-23 20:51:49 +03:00
mockedPools = ""
2021-08-24 14:38:26 -06:00
return "" , nil
}
2020-07-29 19:21:37 +05:30
}
return "" , errors . Errorf ( "unexpected arguments %q" , args )
},
}
context . Executor = executor
2021-01-12 13:14:07 +01:00
context . Client = fake . NewClientBuilder (). WithScheme ( s ). Build ()
2021-11-18 15:22:56 -07:00
clusterInfo := cephclient . AdminTestClusterInfo ( namespace )
2020-07-29 19:21:37 +05:30
// Case 1: CephBlockPoolList is not registered in scheme.
// So, an error is expected as List() operation would fail.
2022-10-04 20:50:28 +05:30
err := configureRBDStats ( context , clusterInfo , "" )
2020-07-29 19:21:37 +05:30
assert . NotNil ( t , err )
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephBlockPoolList {})
// Case 2: CephBlockPoolList is registered in schema.
// So, no error is expected.
2022-10-04 20:50:28 +05:30
err = configureRBDStats ( context , clusterInfo , "" )
2020-07-29 19:21:37 +05:30
assert . Nil ( t , err )
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephBlockPool {})
// A Pool resource with metadata and spec.
poolWithRBDStatsDisabled := & cephv1 . CephBlockPool {
ObjectMeta : metav1 . ObjectMeta {
Name : "my-pool-without-rbd-stats" ,
Namespace : namespace ,
},
2021-12-08 16:14:29 -07:00
Spec : cephv1 . NamedBlockPoolSpec {
PoolSpec : cephv1 . PoolSpec {
Replicated : cephv1 . ReplicatedSpec {
Size : 3 ,
},
2020-07-29 19:21:37 +05:30
},
},
}
// Case 3: One CephBlockPool with EnableRBDStats:false (default).
objects := [] runtime . Object {
poolWithRBDStatsDisabled ,
}
2021-01-12 13:14:07 +01:00
context . Client = fake . NewClientBuilder (). WithScheme ( s ). WithRuntimeObjects ( objects ... ). Build ()
2022-10-04 20:50:28 +05:30
err = configureRBDStats ( context , clusterInfo , "" )
2020-07-29 19:21:37 +05:30
assert . Nil ( t , err )
// Case 4: Two CephBlockPools with EnableRBDStats:false & EnableRBDStats:true.
poolWithRBDStatsEnabled := poolWithRBDStatsDisabled . DeepCopy ()
poolWithRBDStatsEnabled . Name = "my-pool-with-rbd-stats"
poolWithRBDStatsEnabled . Spec . EnableRBDStats = true
objects = append ( objects , poolWithRBDStatsEnabled )
2021-01-12 13:14:07 +01:00
context . Client = fake . NewClientBuilder (). WithScheme ( s ). WithRuntimeObjects ( objects ... ). Build ()
2022-10-04 20:50:28 +05:30
err = configureRBDStats ( context , clusterInfo , "" )
2020-07-29 19:21:37 +05:30
assert . Nil ( t , err )
2022-10-04 20:50:28 +05:30
// Case 5: Two external pools(non CephBlockPools) with rbd_stats_pools config already set
monStore := config . GetMonStore ( context , clusterInfo )
e := monStore . Set ( "mgr" , "mgr/prometheus/rbd_stats_pools" , "pool1,pool2" )
assert . Nil ( t , e )
e = configureRBDStats ( context , clusterInfo , "" )
assert . Nil ( t , e )
rbdStatsPools , err := monStore . Get ( "mgr" , "mgr/prometheus/rbd_stats_pools" )
assert . Nil ( t , err )
assert . Equal ( t , "my-pool-with-rbd-stats,pool1,pool2" , rbdStatsPools )
// Case 6: Deleted CephBlockPool should be excluded from config
err = configureRBDStats ( context , clusterInfo , "my-pool-with-rbd-stats" )
assert . Nil ( t , err )
rbdStatsPools , err = monStore . Get ( "mgr" , "mgr/prometheus/rbd_stats_pools" )
assert . Nil ( t , err )
assert . Equal ( t , "pool1,pool2" , rbdStatsPools )
2025-03-13 15:24:58 -07:00
// Case 7: Duplicate entries should be removed from config
2022-10-04 20:50:28 +05:30
e = monStore . Set ( "mgr" , "mgr/prometheus/rbd_stats_pools" , "pool1,pool2,pool1" )
assert . Nil ( t , e )
err = configureRBDStats ( context , clusterInfo , "" )
assert . Nil ( t , err )
rbdStatsPools , err = monStore . Get ( "mgr" , "mgr/prometheus/rbd_stats_pools" )
assert . Nil ( t , err )
2024-10-23 20:51:49 +03:00
assert . Equal ( t , "my-pool-with-rbd-stats,pool1,pool2" , rbdStatsPools )
2022-10-04 20:50:28 +05:30
// Case 8: Two CephBlockPools with EnableRBDStats:false & EnableRBDStats:true.
2021-06-08 22:46:58 -06:00
// SetConfig returns an error
2020-07-29 19:21:37 +05:30
context . Executor = & exectest . MockExecutor {
2021-10-08 11:36:18 +02:00
MockExecuteCommandWithTimeout : func ( timeout time . Duration , command string , args ... string ) ( string , error ) {
2020-07-29 19:21:37 +05:30
logger . Infof ( "Command: %s %v" , command , args )
2021-08-24 14:38:26 -06:00
return "" , errors . New ( "mock error to simulate failure of mon store Set() function" )
2020-07-29 19:21:37 +05:30
},
}
2022-10-04 20:50:28 +05:30
err = configureRBDStats ( context , clusterInfo , "" )
2020-07-29 19:21:37 +05:30
assert . NotNil ( t , err )
2024-10-23 20:51:49 +03:00
}
2022-10-04 20:50:28 +05:30
2024-10-23 20:51:49 +03:00
func TestGenerateStatsPoolList ( t * testing . T ) {
tests := [] struct {
name string
existingStatsPools [] string
rookStatsPools [] string
removePools [] string
expectedOutput string
}{
// Basic cases
{
name : "Empty lists" ,
existingStatsPools : [] string {},
rookStatsPools : [] string {},
removePools : [] string {},
expectedOutput : "" ,
},
{
name : "Single-item lists, no removal" ,
existingStatsPools : [] string { "p1" },
rookStatsPools : [] string { "p2" },
removePools : [] string {},
expectedOutput : "p1,p2" ,
},
// Overlap and duplicates
{
name : "Overlapping pools, some to remove" ,
existingStatsPools : [] string { "p1" , "p2" , "p3" },
rookStatsPools : [] string { "p2" , "p4" , "p5" },
removePools : [] string { "p1" , "p5" },
expectedOutput : "p2,p3,p4" ,
},
{
name : "Non-overlapping lists" ,
existingStatsPools : [] string { "p1" , "p2" },
rookStatsPools : [] string { "p3" , "p4" },
removePools : [] string {},
expectedOutput : "p1,p2,p3,p4" ,
},
// All pools removed
{
name : "All pools removed" ,
existingStatsPools : [] string { "p1" , "p2" },
rookStatsPools : [] string { "p2" , "p3" },
removePools : [] string { "p1" , "p2" , "p3" },
expectedOutput : "" ,
},
// Mixed scenarios with edge cases
{
name : "Only removed pools" ,
existingStatsPools : [] string { "p1" , "p2" },
rookStatsPools : [] string { "p2" , "p3" },
removePools : [] string { "p1" , "p2" , "p3" , "p4" },
expectedOutput : "" ,
},
{
name : "Duplicate pools across lists" ,
existingStatsPools : [] string { "p1" , "p2" , "p1" },
rookStatsPools : [] string { "p2" , "p3" , "p3" },
removePools : [] string {},
expectedOutput : "p1,p2,p3" ,
},
{
name : "Empty string in pools" ,
existingStatsPools : [] string { "p1" , "" },
rookStatsPools : [] string { "p2" , "" },
removePools : [] string { "" },
expectedOutput : "p1,p2" ,
},
{
name : "Empty string in remove pools" ,
existingStatsPools : [] string { "p1" , "p2" },
rookStatsPools : [] string { "p3" , "p4" },
removePools : [] string { "" },
expectedOutput : "p1,p2,p3,p4" ,
},
{
name : "All lists empty strings" ,
existingStatsPools : [] string { "" },
rookStatsPools : [] string { "" },
removePools : [] string { "" },
expectedOutput : "" ,
},
// Larger cases
{
name : "Large unique pool list" ,
existingStatsPools : [] string { "p1" , "p2" , "p3" , "p4" },
rookStatsPools : [] string { "p5" , "p6" , "p7" , "p8" },
removePools : [] string { "p1" , "p8" },
expectedOutput : "p2,p3,p4,p5,p6,p7" ,
},
{
name : "Large list with many duplicates" ,
existingStatsPools : [] string { "p1" , "p2" , "p3" , "p2" , "p1" },
rookStatsPools : [] string { "p2" , "p3" , "p3" , "p4" , "p1" },
removePools : [] string { "p4" },
expectedOutput : "p1,p2,p3" ,
},
}
for _ , tt := range tests {
t . Run ( tt . name , func ( t * testing . T ) {
result := generateStatsPoolList ( tt . existingStatsPools , tt . rookStatsPools , tt . removePools )
assert . Equal ( t , tt . expectedOutput , result )
})
}
2020-07-29 19:21:37 +05:30
}
2025-06-30 18:53:31 +05:30
func TestMirrorPeerKeyRotationStatus ( t * testing . T ) {
ctx := context . TODO ()
// Set DEBUG logging
t . Setenv ( "ROOK_LOG_LEVEL" , "DEBUG" )
var (
name = "my-pool"
namespace = "rook-ceph"
replicas uint = 3
)
cephCluster := & cephv1 . CephCluster {
ObjectMeta : metav1 . ObjectMeta {
Name : namespace ,
Namespace : namespace ,
},
Status : cephv1 . ClusterStatus {
Phase : "" ,
CephVersion : & cephv1 . ClusterVersion {
Version : "20.2.0-0" ,
},
CephStatus : & cephv1 . CephStatus {
Health : "HEALTH_OK" ,
},
2025-08-18 14:53:08 -06:00
Cephx : cephv1 . ClusterCephxStatus {},
2025-06-30 18:53:31 +05:30
},
}
// A Pool resource with metadata and spec.
pool := & cephv1 . CephBlockPool {
ObjectMeta : metav1 . ObjectMeta {
Name : name ,
Namespace : namespace ,
UID : types . UID ( "c47cac40-9bee-4d52-823b-ccd803ba5bfe" ),
Finalizers : [] string { "cephblockpool.ceph.rook.io" },
},
TypeMeta : metav1 . TypeMeta {
Kind : "CephBlockPool" ,
},
Spec : cephv1 . NamedBlockPoolSpec {
PoolSpec : cephv1 . PoolSpec {
Replicated : cephv1 . ReplicatedSpec {
Size : replicas ,
},
Mirroring : cephv1 . MirroringSpec {
Enabled : true ,
Mode : "image" ,
Peers : & cephv1 . MirroringPeerSpec {},
},
StatusCheck : cephv1 . MirrorHealthCheckSpec {
Mirror : cephv1 . HealthCheckSpec {
Disabled : true ,
},
},
},
},
Status : & cephv1 . CephBlockPoolStatus {
Phase : "" ,
},
}
// Objects to track in the fake client.
object := [] runtime . Object {
pool , cephCluster ,
}
executor := & exectest . MockExecutor {
MockExecuteCommandWithOutput : func ( command string , args ... string ) ( string , error ) {
if args [ 0 ] == "status" {
return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_OK"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}` , nil
}
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "peer" && args [ 3 ] == "bootstrap" && args [ 4 ] == "create" {
return `eyJmc2lkIjoiYzZiMDg3ZjItNzgyOS00ZGJiLWJjZmMtNTNkYzM0ZTBiMzVkIiwiY2xpZW50X2lkIjoicmJkLW1pcnJvci1wZWVyIiwia2V5IjoiQVFBV1lsWmZVQ1Q2RGhBQVBtVnAwbGtubDA5YVZWS3lyRVV1NEE9PSIsIm1vbl9ob3N0IjoiW3YyOjE5Mi4xNjguMTExLjEwOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTA6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjEyOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTI6Njc4OV0sW3YyOjE5Mi4xNjguMTExLjExOjMzMDAsdjE6MTkyLjE2OC4xMTEuMTE6Njc4OV0ifQ==` , nil
}
if args [ 0 ] == "mirror" && args [ 1 ] == "pool" && args [ 2 ] == "info" {
return "{}" , nil
}
return "" , nil
},
}
// Register operator types with the runtime scheme.
s := scheme . Scheme
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephBlockPool {})
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephCluster {}, & cephv1 . CephClusterList {})
s . AddKnownTypes ( cephv1 . SchemeGroupVersion , & cephv1 . CephBlockPoolList {})
// Create a fake client to mock API calls.
cl := fake . NewClientBuilder (). WithRuntimeObjects ( object ... ). Build ()
c := & clusterd . Context {
Client : cl ,
Executor : executor ,
Clientset : testop . New ( t , 1 ),
RookClientset : rookclient . NewSimpleClientset (),
}
// Mock clusterInfo
secrets := map [ string ][] byte {
"fsid" : [] byte ( name ),
"mon-secret" : [] byte ( "monsecret" ),
"admin-secret" : [] byte ( "adminsecret" ),
}
secret := & v1 . Secret {
ObjectMeta : metav1 . ObjectMeta {
Name : "rook-ceph-mon" ,
Namespace : namespace ,
},
Data : secrets ,
Type : k8sutil . RookType ,
}
_ , err := c . Clientset . CoreV1 (). Secrets ( namespace ). Create ( ctx , secret , metav1 . CreateOptions {})
assert . NoError ( t , err )
// Mock request to simulate Reconcile() being called on an event for a
// watched resource .
req := reconcile . Request {
NamespacedName : types . NamespacedName {
Name : name ,
Namespace : namespace ,
},
}
// Create a ReconcileCephBlockPool object with the scheme and fake client.
r := & ReconcileCephBlockPool {
client : cl ,
scheme : s ,
context : c ,
blockPoolContexts : make ( map [ string ] * blockPoolHealth ),
opManagerContext : context . TODO (),
2026-02-09 16:38:26 +05:30
recorder : events . NewFakeRecorder ( 50 ),
2025-06-30 18:53:31 +05:30
}
t . Setenv ( "POD_NAME" , "test" )
t . Setenv ( "POD_NAMESPACE" , namespace )
p := & v1 . Pod {
ObjectMeta : metav1 . ObjectMeta {
Name : "test" ,
Namespace : namespace ,
OwnerReferences : [] metav1 . OwnerReference {
{
Kind : "ReplicaSet" ,
Name : "testReplicaSet" ,
},
},
},
}
// Create fake pod
_ , err = r . context . Clientset . CoreV1 (). Pods ( namespace ). Create ( context . TODO (), p , metav1 . CreateOptions {})
assert . NoError ( t , err )
replicaSet := & appsv1 . ReplicaSet {
ObjectMeta : metav1 . ObjectMeta {
Name : "testReplicaSet" ,
Namespace : namespace ,
OwnerReferences : [] metav1 . OwnerReference {
{
Kind : "Deployment" ,
},
},
},
}
// Create fake replicaset
_ , err = r . context . Clientset . AppsV1 (). ReplicaSets ( namespace ). Create ( context . TODO (), replicaSet , metav1 . CreateOptions {})
assert . NoError ( t , err )
t . Run ( "first reconcile - PeerToken cephx status is set to empty" , func ( t * testing . T ) {
_ , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
pool := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
assert . Equal ( t , cephv1 . CephxStatus {}, pool . Status . Cephx . PeerToken )
})
t . Run ( "subsequent reconcile - retain PeerToken cephx status" , func ( t * testing . T ) {
_ , err := r . Reconcile ( ctx , req )
assert . NoError ( t , err )
pool := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
assert . Equal ( t , cephv1 . CephxStatus {}, pool . Status . Cephx . PeerToken )
})
t . Run ( "PeerToken cephx status should be updated based on the cephCluster cephx status" , func ( t * testing . T ) {
2025-08-18 14:53:08 -06:00
RDBMirrorPeerStatus := cephv1 . CephxStatus {
2025-06-30 18:53:31 +05:30
KeyGeneration : 2 ,
KeyCephVersion : "20.2.0-0" ,
}
cephCluster . Status . Cephx . RBDMirrorPeer = RDBMirrorPeerStatus
err := r . client . Update ( context . TODO (), cephCluster )
assert . NoError ( t , err )
_ , err = r . Reconcile ( ctx , req )
assert . NoError ( t , err )
pool := & cephv1 . CephBlockPool {}
err = r . client . Get ( context . TODO (), req . NamespacedName , pool )
assert . NoError ( t , err )
2025-08-18 14:53:08 -06:00
assert . Equal ( t , RDBMirrorPeerStatus , pool . Status . Cephx . PeerToken )
2025-06-30 18:53:31 +05:30
})
}