cassandra.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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 upgrades
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "path/filepath"
  21. "sync"
  22. "time"
  23. "github.com/onsi/ginkgo"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/util/version"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. "k8s.io/kubernetes/test/e2e/framework"
  28. e2esset "k8s.io/kubernetes/test/e2e/framework/statefulset"
  29. "k8s.io/kubernetes/test/e2e/framework/testfiles"
  30. )
  31. const cassandraManifestPath = "test/e2e/testing-manifests/statefulset/cassandra"
  32. // CassandraUpgradeTest ups and verifies that a Cassandra StatefulSet behaves
  33. // well across upgrades.
  34. type CassandraUpgradeTest struct {
  35. ip string
  36. successfulWrites int
  37. }
  38. // Name returns the tracking name of the test.
  39. func (CassandraUpgradeTest) Name() string { return "cassandra-upgrade" }
  40. // Skip returns true when this test can be skipped.
  41. func (CassandraUpgradeTest) Skip(upgCtx UpgradeContext) bool {
  42. minVersion := version.MustParseSemantic("1.6.0")
  43. for _, vCtx := range upgCtx.Versions {
  44. if vCtx.Version.LessThan(minVersion) {
  45. return true
  46. }
  47. }
  48. return false
  49. }
  50. func cassandraKubectlCreate(ns, file string) {
  51. input := string(testfiles.ReadOrDie(filepath.Join(cassandraManifestPath, file)))
  52. framework.RunKubectlOrDieInput(ns, input, "create", "-f", "-", fmt.Sprintf("--namespace=%s", ns))
  53. }
  54. // Setup creates a Cassandra StatefulSet and a PDB. It also brings up a tester
  55. // ReplicaSet and associated service and PDB to guarantee availability during
  56. // the upgrade.
  57. // It waits for the system to stabilize before adding two users to verify
  58. // connectivity.
  59. func (t *CassandraUpgradeTest) Setup(f *framework.Framework) {
  60. ns := f.Namespace.Name
  61. statefulsetPoll := 30 * time.Second
  62. statefulsetTimeout := 10 * time.Minute
  63. ginkgo.By("Creating a PDB")
  64. cassandraKubectlCreate(ns, "pdb.yaml")
  65. ginkgo.By("Creating a Cassandra StatefulSet")
  66. e2esset.CreateStatefulSet(f.ClientSet, cassandraManifestPath, ns)
  67. ginkgo.By("Creating a cassandra-test-server deployment")
  68. cassandraKubectlCreate(ns, "tester.yaml")
  69. ginkgo.By("Getting the ingress IPs from the services")
  70. err := wait.PollImmediate(statefulsetPoll, statefulsetTimeout, func() (bool, error) {
  71. if t.ip = t.getServiceIP(f, ns, "test-server"); t.ip == "" {
  72. return false, nil
  73. }
  74. if _, err := t.listUsers(); err != nil {
  75. framework.Logf("Service endpoint is up but isn't responding")
  76. return false, nil
  77. }
  78. return true, nil
  79. })
  80. framework.ExpectNoError(err)
  81. framework.Logf("Service endpoint is up")
  82. ginkgo.By("Adding 2 dummy users")
  83. err = t.addUser("Alice")
  84. framework.ExpectNoError(err)
  85. err = t.addUser("Bob")
  86. framework.ExpectNoError(err)
  87. t.successfulWrites = 2
  88. ginkgo.By("Verifying that the users exist")
  89. users, err := t.listUsers()
  90. framework.ExpectNoError(err)
  91. framework.ExpectEqual(len(users), 2)
  92. }
  93. // listUsers gets a list of users from the db via the tester service.
  94. func (t *CassandraUpgradeTest) listUsers() ([]string, error) {
  95. r, err := http.Get(fmt.Sprintf("http://%s:8080/list", t.ip))
  96. if err != nil {
  97. return nil, err
  98. }
  99. defer r.Body.Close()
  100. if r.StatusCode != http.StatusOK {
  101. b, err := ioutil.ReadAll(r.Body)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return nil, fmt.Errorf(string(b))
  106. }
  107. var names []string
  108. if err := json.NewDecoder(r.Body).Decode(&names); err != nil {
  109. return nil, err
  110. }
  111. return names, nil
  112. }
  113. // addUser adds a user to the db via the tester services.
  114. func (t *CassandraUpgradeTest) addUser(name string) error {
  115. val := map[string][]string{"name": {name}}
  116. r, err := http.PostForm(fmt.Sprintf("http://%s:8080/add", t.ip), val)
  117. if err != nil {
  118. return err
  119. }
  120. defer r.Body.Close()
  121. if r.StatusCode != http.StatusOK {
  122. b, err := ioutil.ReadAll(r.Body)
  123. if err != nil {
  124. return err
  125. }
  126. return fmt.Errorf(string(b))
  127. }
  128. return nil
  129. }
  130. // getServiceIP is a helper method to extract the Ingress IP from the service.
  131. func (t *CassandraUpgradeTest) getServiceIP(f *framework.Framework, ns, svcName string) string {
  132. svc, err := f.ClientSet.CoreV1().Services(ns).Get(context.TODO(), svcName, metav1.GetOptions{})
  133. framework.ExpectNoError(err)
  134. ingress := svc.Status.LoadBalancer.Ingress
  135. if len(ingress) == 0 {
  136. return ""
  137. }
  138. return ingress[0].IP
  139. }
  140. // Test is called during the upgrade.
  141. // It launches two goroutines, one continuously writes to the db and one reads
  142. // from the db. Each attempt is tallied and at the end we verify if the success
  143. // ratio is over a certain threshold (0.75). We also verify that we get
  144. // at least the same number of rows back as we successfully wrote.
  145. func (t *CassandraUpgradeTest) Test(f *framework.Framework, done <-chan struct{}, upgrade UpgradeType) {
  146. ginkgo.By("Continuously polling the database during upgrade.")
  147. var (
  148. success, failures, writeAttempts, lastUserCount int
  149. mu sync.Mutex
  150. errors = map[string]int{}
  151. )
  152. // Write loop.
  153. go wait.Until(func() {
  154. writeAttempts++
  155. if err := t.addUser(fmt.Sprintf("user-%d", writeAttempts)); err != nil {
  156. framework.Logf("Unable to add user: %v", err)
  157. mu.Lock()
  158. errors[err.Error()]++
  159. mu.Unlock()
  160. return
  161. }
  162. t.successfulWrites++
  163. }, 10*time.Millisecond, done)
  164. // Read loop.
  165. wait.Until(func() {
  166. users, err := t.listUsers()
  167. if err != nil {
  168. framework.Logf("Could not retrieve users: %v", err)
  169. failures++
  170. mu.Lock()
  171. errors[err.Error()]++
  172. mu.Unlock()
  173. return
  174. }
  175. success++
  176. lastUserCount = len(users)
  177. }, 10*time.Millisecond, done)
  178. framework.Logf("got %d users; want >=%d", lastUserCount, t.successfulWrites)
  179. framework.ExpectEqual(lastUserCount >= t.successfulWrites, true)
  180. ratio := float64(success) / float64(success+failures)
  181. framework.Logf("Successful gets %d/%d=%v", success, success+failures, ratio)
  182. ratio = float64(t.successfulWrites) / float64(writeAttempts)
  183. framework.Logf("Successful writes %d/%d=%v", t.successfulWrites, writeAttempts, ratio)
  184. framework.Logf("Errors: %v", errors)
  185. // TODO(maisem): tweak this value once we have a few test runs.
  186. framework.ExpectEqual(ratio > 0.75, true)
  187. }
  188. // Teardown does one final check of the data's availability.
  189. func (t *CassandraUpgradeTest) Teardown(f *framework.Framework) {
  190. users, err := t.listUsers()
  191. framework.ExpectNoError(err)
  192. framework.ExpectEqual(len(users) >= t.successfulWrites, true)
  193. }