testserver.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 testing
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net"
  18. "os"
  19. "path"
  20. "runtime"
  21. "time"
  22. pflag "github.com/spf13/pflag"
  23. "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "k8s.io/apiserver/pkg/registry/generic/registry"
  27. "k8s.io/apiserver/pkg/storage/storagebackend"
  28. "k8s.io/client-go/kubernetes"
  29. restclient "k8s.io/client-go/rest"
  30. "k8s.io/kubernetes/cmd/kube-apiserver/app"
  31. "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
  32. )
  33. // TearDownFunc is to be called to tear down a test server.
  34. type TearDownFunc func()
  35. // TestServerInstanceOptions Instance options the TestServer
  36. type TestServerInstanceOptions struct {
  37. // DisableStorageCleanup Disable the automatic storage cleanup
  38. DisableStorageCleanup bool
  39. }
  40. // TestServer return values supplied by kube-test-ApiServer
  41. type TestServer struct {
  42. ClientConfig *restclient.Config // Rest client config
  43. ServerOpts *options.ServerRunOptions // ServerOpts
  44. TearDownFn TearDownFunc // TearDown function
  45. TmpDir string // Temp Dir used, by the apiserver
  46. }
  47. // Logger allows t.Testing and b.Testing to be passed to StartTestServer and StartTestServerOrDie
  48. type Logger interface {
  49. Errorf(format string, args ...interface{})
  50. Fatalf(format string, args ...interface{})
  51. Logf(format string, args ...interface{})
  52. }
  53. // NewDefaultTestServerOptions Default options for TestServer instances
  54. func NewDefaultTestServerOptions() *TestServerInstanceOptions {
  55. return &TestServerInstanceOptions{
  56. DisableStorageCleanup: false,
  57. }
  58. }
  59. // StartTestServer starts a etcd server and kube-apiserver. A rest client config and a tear-down func,
  60. // and location of the tmpdir are returned.
  61. //
  62. // Note: we return a tear-down func instead of a stop channel because the later will leak temporary
  63. // files that because Golang testing's call to os.Exit will not give a stop channel go routine
  64. // enough time to remove temporary files.
  65. func StartTestServer(t Logger, instanceOptions *TestServerInstanceOptions, customFlags []string, storageConfig *storagebackend.Config) (result TestServer, err error) {
  66. if instanceOptions == nil {
  67. instanceOptions = NewDefaultTestServerOptions()
  68. }
  69. // TODO : Remove TrackStorageCleanup below when PR
  70. // https://github.com/kubernetes/kubernetes/pull/50690
  71. // merges as that shuts down storage properly
  72. if !instanceOptions.DisableStorageCleanup {
  73. registry.TrackStorageCleanup()
  74. }
  75. stopCh := make(chan struct{})
  76. tearDown := func() {
  77. if !instanceOptions.DisableStorageCleanup {
  78. registry.CleanupStorage()
  79. }
  80. close(stopCh)
  81. if len(result.TmpDir) != 0 {
  82. os.RemoveAll(result.TmpDir)
  83. }
  84. }
  85. defer func() {
  86. if result.TearDownFn == nil {
  87. tearDown()
  88. }
  89. }()
  90. result.TmpDir, err = ioutil.TempDir("", "kubernetes-kube-apiserver")
  91. if err != nil {
  92. return result, fmt.Errorf("failed to create temp dir: %v", err)
  93. }
  94. fs := pflag.NewFlagSet("test", pflag.PanicOnError)
  95. s := options.NewServerRunOptions()
  96. for _, f := range s.Flags().FlagSets {
  97. fs.AddFlagSet(f)
  98. }
  99. s.InsecureServing.BindPort = 0
  100. s.SecureServing.Listener, s.SecureServing.BindPort, err = createLocalhostListenerOnFreePort()
  101. if err != nil {
  102. return result, fmt.Errorf("failed to create listener: %v", err)
  103. }
  104. s.SecureServing.ServerCert.CertDirectory = result.TmpDir
  105. s.SecureServing.ExternalAddress = s.SecureServing.Listener.Addr().(*net.TCPAddr).IP // use listener addr although it is a loopback device
  106. _, thisFile, _, ok := runtime.Caller(0)
  107. if !ok {
  108. return result, fmt.Errorf("failed to get current file")
  109. }
  110. s.SecureServing.ServerCert.FixtureDirectory = path.Join(path.Dir(thisFile), "testdata")
  111. s.ServiceClusterIPRange.IP = net.IPv4(10, 0, 0, 0)
  112. s.ServiceClusterIPRange.Mask = net.CIDRMask(16, 32)
  113. s.Etcd.StorageConfig = *storageConfig
  114. s.APIEnablement.RuntimeConfig.Set("api/all=true")
  115. fs.Parse(customFlags)
  116. completedOptions, err := app.Complete(s)
  117. if err != nil {
  118. return result, fmt.Errorf("failed to set default ServerRunOptions: %v", err)
  119. }
  120. t.Logf("runtime-config=%v", completedOptions.APIEnablement.RuntimeConfig)
  121. t.Logf("Starting kube-apiserver on port %d...", s.SecureServing.BindPort)
  122. server, err := app.CreateServerChain(completedOptions, stopCh)
  123. if err != nil {
  124. return result, fmt.Errorf("failed to create server chain: %v", err)
  125. }
  126. errCh := make(chan error)
  127. go func(stopCh <-chan struct{}) {
  128. if err := server.PrepareRun().Run(stopCh); err != nil {
  129. errCh <- err
  130. }
  131. }(stopCh)
  132. t.Logf("Waiting for /healthz to be ok...")
  133. client, err := kubernetes.NewForConfig(server.LoopbackClientConfig)
  134. if err != nil {
  135. return result, fmt.Errorf("failed to create a client: %v", err)
  136. }
  137. // wait until healthz endpoint returns ok
  138. err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  139. select {
  140. case err := <-errCh:
  141. return false, err
  142. default:
  143. }
  144. result := client.CoreV1().RESTClient().Get().AbsPath("/healthz").Do()
  145. status := 0
  146. result.StatusCode(&status)
  147. if status == 200 {
  148. return true, nil
  149. }
  150. return false, nil
  151. })
  152. if err != nil {
  153. return result, fmt.Errorf("failed to wait for /healthz to return ok: %v", err)
  154. }
  155. // wait until default namespace is created
  156. err = wait.Poll(100*time.Millisecond, 30*time.Second, func() (bool, error) {
  157. select {
  158. case err := <-errCh:
  159. return false, err
  160. default:
  161. }
  162. if _, err := client.CoreV1().Namespaces().Get("default", metav1.GetOptions{}); err != nil {
  163. if !errors.IsNotFound(err) {
  164. t.Logf("Unable to get default namespace: %v", err)
  165. }
  166. return false, nil
  167. }
  168. return true, nil
  169. })
  170. if err != nil {
  171. return result, fmt.Errorf("failed to wait for default namespace to be created: %v", err)
  172. }
  173. // from here the caller must call tearDown
  174. result.ClientConfig = server.LoopbackClientConfig
  175. result.ClientConfig.QPS = 1000
  176. result.ClientConfig.Burst = 10000
  177. result.ServerOpts = s
  178. result.TearDownFn = tearDown
  179. return result, nil
  180. }
  181. // StartTestServerOrDie calls StartTestServer t.Fatal if it does not succeed.
  182. func StartTestServerOrDie(t Logger, instanceOptions *TestServerInstanceOptions, flags []string, storageConfig *storagebackend.Config) *TestServer {
  183. result, err := StartTestServer(t, instanceOptions, flags, storageConfig)
  184. if err == nil {
  185. return &result
  186. }
  187. t.Fatalf("failed to launch server: %v", err)
  188. return nil
  189. }
  190. func createLocalhostListenerOnFreePort() (net.Listener, int, error) {
  191. ln, err := net.Listen("tcp", "127.0.0.1:0")
  192. if err != nil {
  193. return nil, 0, err
  194. }
  195. // get port
  196. tcpAddr, ok := ln.Addr().(*net.TCPAddr)
  197. if !ok {
  198. ln.Close()
  199. return nil, 0, fmt.Errorf("invalid listen address: %q", ln.Addr().String())
  200. }
  201. return ln, tcpAddr.Port, nil
  202. }