ceph_base_object_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*
  2. Copyright 2016 The Rook Authors. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package integration
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "os"
  19. "path/filepath"
  20. "strconv"
  21. "strings"
  22. "testing"
  23. "time"
  24. cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
  25. "github.com/rook/rook/pkg/operator/k8sutil"
  26. "github.com/rook/rook/tests/framework/clients"
  27. "github.com/rook/rook/tests/framework/installer"
  28. "github.com/rook/rook/tests/framework/utils"
  29. "github.com/stretchr/testify/assert"
  30. "github.com/stretchr/testify/require"
  31. "github.com/stretchr/testify/suite"
  32. v1 "k8s.io/api/core/v1"
  33. "k8s.io/apimachinery/pkg/api/errors"
  34. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  35. "k8s.io/apimachinery/pkg/util/wait"
  36. )
  37. const (
  38. //nolint:gosec // since this is not leaking any hardcoded credentials, it's just the secret name
  39. objectTLSSecretName = "rook-ceph-rgw-tls-test-store-csr"
  40. )
  41. var (
  42. userid = "rook-user"
  43. userdisplayname = "A rook RGW user"
  44. bucketname = "smokebkt"
  45. ObjBody = "Test Rook Object Data"
  46. ObjectKey1 = "rookObj1"
  47. ObjectKey2 = "rookObj2"
  48. ObjectKey3 = "rookObj3"
  49. ObjectKey4 = "rookObj4"
  50. contentType = "plain/text"
  51. obcName = "smoke-delete-bucket"
  52. maxObject = "2"
  53. newMaxObject = "3"
  54. bucketStorageClassName = "rook-smoke-delete-bucket"
  55. maxBucket = 1
  56. maxSize = "100000"
  57. userCap = "*"
  58. )
  59. // Test Object StoreCreation on Rook that was installed via helm
  60. func runObjectE2ETestLite(t *testing.T, helper *clients.TestClient, k8sh *utils.K8sHelper, installer *installer.CephInstaller, namespace, storeName string, replicaSize int, deleteStore bool, enableTLS bool) {
  61. andDeleting := ""
  62. if deleteStore {
  63. andDeleting = "and deleting"
  64. }
  65. logger.Infof("test creating %s object store %q in namespace %q", andDeleting, storeName, namespace)
  66. createCephObjectStore(t, helper, k8sh, installer, namespace, storeName, replicaSize, enableTLS)
  67. if deleteStore {
  68. t.Run("delete object store", func(t *testing.T) {
  69. deleteObjectStore(t, k8sh, namespace, storeName)
  70. assertObjectStoreDeletion(t, k8sh, namespace, storeName)
  71. })
  72. }
  73. }
  74. // create a CephObjectStore and wait for it to report ready status
  75. func createCephObjectStore(t *testing.T, helper *clients.TestClient, k8sh *utils.K8sHelper, installer *installer.CephInstaller, namespace, storeName string, replicaSize int, tlsEnable bool) {
  76. logger.Infof("Create Object Store %q with replica count %d", storeName, replicaSize)
  77. rgwServiceName := "rook-ceph-rgw-" + storeName
  78. if tlsEnable {
  79. t.Run("generate TLS certs", func(t *testing.T) {
  80. generateRgwTlsCertSecret(t, helper, k8sh, namespace, storeName, rgwServiceName)
  81. })
  82. }
  83. t.Run("create CephObjectStore", func(t *testing.T) {
  84. err := helper.ObjectClient.Create(namespace, storeName, int32(replicaSize), tlsEnable)
  85. assert.Nil(t, err)
  86. })
  87. t.Run("wait for RGWs to be running", func(t *testing.T) {
  88. // check that ObjectStore is created
  89. logger.Infof("Check that RGW pods are Running")
  90. for i := 0; i < 24 && k8sh.CheckPodCountAndState("rook-ceph-rgw", namespace, 1, "Running") == false; i++ {
  91. logger.Infof("(%d) RGW pod check sleeping for 5 seconds ...", i)
  92. time.Sleep(5 * time.Second)
  93. }
  94. assert.True(t, k8sh.CheckPodCountAndState("rook-ceph-rgw", namespace, replicaSize, "Running"))
  95. logger.Info("RGW pods are running")
  96. assert.NoError(t, k8sh.WaitForLabeledDeploymentsToBeReady("app=rook-ceph-rgw", namespace))
  97. logger.Infof("Object store %q created successfully", storeName)
  98. })
  99. ctx := context.TODO()
  100. // Check object store status
  101. t.Run("verify object store status", func(t *testing.T) {
  102. retryCount := 40
  103. i := 0
  104. for i = 0; i < retryCount; i++ {
  105. objectStore, err := k8sh.RookClientset.CephV1().CephObjectStores(namespace).Get(ctx, storeName, metav1.GetOptions{})
  106. assert.Nil(t, err)
  107. // TODO: check that object store status is good, and also check that status of
  108. // deployment is good based on health checks
  109. if objectStore.Status == nil {
  110. logger.Infof("(%d) object status check sleeping for 5 seconds ...%+v", i, objectStore.Status)
  111. time.Sleep(5 * time.Second)
  112. continue
  113. }
  114. logger.Info("objectstore status is", objectStore.Status)
  115. // ConditionConnected supports Rook v1.10 clusters that still had health check
  116. // TODO: remove that half of check after Rook v1.12 release
  117. if objectStore.Status.Phase != cephv1.ConditionReady && objectStore.Status.Phase != cephv1.ConditionConnected {
  118. logger.Infof("(%d) bucket status check sleeping for 5 seconds ...%+v", i, objectStore.Status.Phase)
  119. time.Sleep(5 * time.Second)
  120. continue
  121. }
  122. // Info field has the endpoint in it
  123. assert.NotEmpty(t, objectStore.Status.Info)
  124. assert.NotEmpty(t, objectStore.Status.Info["endpoint"])
  125. break
  126. }
  127. if i == retryCount {
  128. t.Fatal("bucket status check failed. status is not connected")
  129. }
  130. })
  131. t.Run("verify RGW liveness probes show healthy", func(t *testing.T) {
  132. err := wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, 90*time.Second, true, func(ctx context.Context) (done bool, err error) {
  133. deployName := "rook-ceph-rgw-" + storeName + "-a"
  134. d, err := k8sh.Clientset.AppsV1().Deployments(namespace).Get(ctx, deployName, metav1.GetOptions{})
  135. if err != nil {
  136. logger.Infof("waiting for rgw deployment %q to be ready; failed to get deployment: %v", deployName, err)
  137. return false, nil
  138. }
  139. if d.Status.UnavailableReplicas != 0 {
  140. logger.Infof("waiting rgw deployment %q to be ready; %d replicas are unavailable", deployName, d.Status.UnavailableReplicas)
  141. return false, nil
  142. }
  143. return true, nil
  144. })
  145. assert.NoError(t, err)
  146. })
  147. t.Run("verify RGW service is up", func(t *testing.T) {
  148. assert.True(t, k8sh.IsServiceUp("rook-ceph-rgw-"+storeName, namespace))
  149. })
  150. t.Run("check if the dashboard-admin user exists in all existing object stores", func(t *testing.T) {
  151. objectStores, err := k8sh.RookClientset.CephV1().CephObjectStores(namespace).List(ctx, metav1.ListOptions{})
  152. assert.Nil(t, err)
  153. for _, objectStore := range objectStores.Items {
  154. err, output := installer.Execute("radosgw-admin", []string{"user", "info", "--uid=dashboard-admin", fmt.Sprintf("--rgw-realm=%s", objectStore.GetName())}, namespace)
  155. logger.Infof("output: %s", output)
  156. assert.NoError(t, err)
  157. }
  158. })
  159. }
  160. func deleteObjectStore(t *testing.T, k8sh *utils.K8sHelper, namespace, storeName string) {
  161. err := k8sh.DeleteResourceAndWait(false, "-n", namespace, "CephObjectStore", storeName)
  162. assert.NoError(t, err)
  163. // wait initially for the controller to detect deletion. Almost always enough, but not
  164. // waiting immediately after this will almost always fail the first check in the loop
  165. time.Sleep(10 * time.Second)
  166. }
  167. func assertObjectStoreDeletion(t *testing.T, k8sh *utils.K8sHelper, namespace, storeName string) {
  168. store := &cephv1.CephObjectStore{}
  169. i := 0
  170. retry := 10
  171. sleepTime := 3 * time.Second
  172. for i = 0; i < retry; i++ {
  173. storeStr, err := k8sh.GetResource("-n", namespace, "CephObjectStore", storeName, "-o", "json")
  174. // if cephobjectstore is not found, just return the test
  175. // no need to check deletion phases as it is already deleted
  176. if err != nil && strings.Contains(storeStr, errors.NewNotFound(v1.Resource("cephobjectstores.ceph.rook.io"), storeName).ErrStatus.Message) {
  177. return
  178. }
  179. assert.NoError(t, err)
  180. logger.Infof("store: \n%s", storeStr)
  181. err = json.Unmarshal([]byte(storeStr), &store)
  182. assert.NoError(t, err)
  183. cond := cephv1.FindStatusCondition(store.Status.Conditions, cephv1.ConditionDeletionIsBlocked)
  184. if cond == nil {
  185. logger.Infof("waiting for CephObjectStore %q to have a deletion condition", storeName)
  186. time.Sleep(sleepTime)
  187. continue
  188. }
  189. if cond.Status == v1.ConditionFalse && cond.Reason == cephv1.ObjectHasNoDependentsReason {
  190. // no longer blocked by dependents
  191. time.Sleep(5 * time.Second) // Let's give some time to the object to be updated
  192. break
  193. }
  194. logger.Infof("waiting 3 more seconds for CephObjectStore %q to be unblocked by dependents", storeName)
  195. time.Sleep(sleepTime)
  196. }
  197. assert.NotEqual(t, retry, i)
  198. assert.Equal(t, cephv1.ConditionDeleting, store.Status.Phase) // phase == "Deleting"
  199. // verify deletion is NOT blocked b/c object has dependents
  200. cond := cephv1.FindStatusCondition(store.Status.Conditions, cephv1.ConditionDeletionIsBlocked)
  201. assert.Equal(t, v1.ConditionFalse, cond.Status)
  202. assert.Equal(t, cephv1.ObjectHasNoDependentsReason, cond.Reason)
  203. err := k8sh.WaitUntilResourceIsDeleted("CephObjectStore", namespace, storeName)
  204. assert.NoError(t, err)
  205. }
  206. func createCephObjectUser(
  207. s *suite.Suite, helper *clients.TestClient, k8sh *utils.K8sHelper,
  208. namespace, storeName, userID string,
  209. checkPhase, checkQuotaAndCaps bool) {
  210. maxObjectInt, err := strconv.Atoi(maxObject)
  211. assert.Nil(s.T(), err)
  212. logger.Infof("creating CephObjectStore user %q for store %q in namespace %q", userID, storeName, namespace)
  213. cosuErr := helper.ObjectUserClient.Create(userID, userdisplayname, storeName, userCap, maxSize, maxBucket, maxObjectInt)
  214. assert.Nil(s.T(), cosuErr)
  215. logger.Infof("Waiting 5 seconds for the object user %q to be created", userID)
  216. time.Sleep(5 * time.Second)
  217. logger.Infof("Checking to see if user %q secret has been created", userID)
  218. for i := 0; i < 6 && helper.ObjectUserClient.UserSecretExists(namespace, storeName, userID) == false; i++ {
  219. logger.Infof("(%d) secret check sleeping for 5 seconds ...", i)
  220. time.Sleep(5 * time.Second)
  221. }
  222. checkCephObjectUser(s, helper, k8sh, namespace, storeName, userID, checkPhase, checkQuotaAndCaps)
  223. }
  224. func checkCephObjectUser(
  225. s *suite.Suite, helper *clients.TestClient, k8sh *utils.K8sHelper,
  226. namespace, storeName, userID string,
  227. checkPhase, checkQuotaAndCaps bool,
  228. ) {
  229. logger.Infof("checking object store \"%s/%s\" user %q", namespace, storeName, userID)
  230. assert.True(s.T(), helper.ObjectUserClient.UserSecretExists(namespace, storeName, userID))
  231. userInfo, err := helper.ObjectUserClient.GetUser(namespace, storeName, userID)
  232. assert.NoError(s.T(), err)
  233. assert.Equal(s.T(), userID, userInfo.UserID)
  234. assert.Equal(s.T(), userdisplayname, *userInfo.DisplayName)
  235. if checkPhase {
  236. // status.phase doesn't exist before Rook v1.6
  237. phase, err := k8sh.GetResource("--namespace", namespace, "cephobjectstoreuser", userID, "--output", "jsonpath={.status.phase}")
  238. assert.NoError(s.T(), err)
  239. assert.Equal(s.T(), k8sutil.ReadyStatus, phase)
  240. }
  241. if checkQuotaAndCaps {
  242. // following fields in CephObjectStoreUser CRD doesn't exist before Rook v1.7.3
  243. maxObjectInt, err := strconv.Atoi(maxObject)
  244. assert.Nil(s.T(), err)
  245. maxSizeInt, err := strconv.Atoi(maxSize)
  246. assert.Nil(s.T(), err)
  247. assert.Equal(s.T(), maxBucket, userInfo.MaxBuckets)
  248. assert.Equal(s.T(), int64(maxObjectInt), *userInfo.UserQuota.MaxObjects)
  249. assert.Equal(s.T(), int64(maxSizeInt), *userInfo.UserQuota.MaxSize)
  250. assert.Equal(s.T(), userCap, userInfo.Caps[0].Perm)
  251. }
  252. }
  253. func objectStoreCleanUp(s *suite.Suite, helper *clients.TestClient, k8sh *utils.K8sHelper, namespace, storeName string) {
  254. logger.Infof("Delete Object Store (will fail if users and buckets still exist)")
  255. err := helper.ObjectClient.Delete(namespace, storeName)
  256. assert.Nil(s.T(), err)
  257. logger.Infof("Done deleting object store")
  258. }
  259. func generateRgwTlsCertSecret(t *testing.T, helper *clients.TestClient, k8sh *utils.K8sHelper, namespace, storeName, rgwServiceName string) {
  260. ctx := context.TODO()
  261. root, err := utils.FindRookRoot()
  262. require.NoError(t, err, "failed to get rook root")
  263. tlscertdir := t.TempDir()
  264. cmdArgs := utils.CommandArgs{Command: filepath.Join(root, "tests/scripts/generate-tls-config.sh"),
  265. CmdArgs: []string{tlscertdir, rgwServiceName, namespace}}
  266. cmdOut := utils.ExecuteCommand(cmdArgs)
  267. require.NoError(t, cmdOut.Err)
  268. tlsKeyIn, err := os.ReadFile(filepath.Join(tlscertdir, rgwServiceName+".key"))
  269. require.NoError(t, err)
  270. tlsCertIn, err := os.ReadFile(filepath.Join(tlscertdir, rgwServiceName+".crt"))
  271. require.NoError(t, err)
  272. tlsCaCertIn, err := os.ReadFile(filepath.Join(tlscertdir, rgwServiceName+".ca"))
  273. require.NoError(t, err)
  274. secretCertOut := fmt.Sprintf("%s%s%s", tlsKeyIn, tlsCertIn, tlsCaCertIn)
  275. tlsK8sSecret := &v1.Secret{
  276. ObjectMeta: metav1.ObjectMeta{
  277. Name: storeName,
  278. Namespace: namespace,
  279. },
  280. Data: map[string][]byte{
  281. "cert": []byte(secretCertOut),
  282. },
  283. }
  284. _, err = k8sh.Clientset.CoreV1().Secrets(namespace).Create(ctx, tlsK8sSecret, metav1.CreateOptions{})
  285. require.Nil(t, err)
  286. }