examples_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. /*
  2. Copyright 2014 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 examples_test
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "os"
  18. "path/filepath"
  19. "regexp"
  20. "strings"
  21. "testing"
  22. "github.com/golang/glog"
  23. "k8s.io/kubernetes/pkg/api"
  24. "k8s.io/kubernetes/pkg/api/testapi"
  25. "k8s.io/kubernetes/pkg/api/validation"
  26. "k8s.io/kubernetes/pkg/apis/batch"
  27. "k8s.io/kubernetes/pkg/apis/extensions"
  28. expvalidation "k8s.io/kubernetes/pkg/apis/extensions/validation"
  29. "k8s.io/kubernetes/pkg/capabilities"
  30. "k8s.io/kubernetes/pkg/registry/job"
  31. "k8s.io/kubernetes/pkg/runtime"
  32. "k8s.io/kubernetes/pkg/types"
  33. "k8s.io/kubernetes/pkg/util/validation/field"
  34. "k8s.io/kubernetes/pkg/util/yaml"
  35. schedulerapi "k8s.io/kubernetes/plugin/pkg/scheduler/api"
  36. schedulerapilatest "k8s.io/kubernetes/plugin/pkg/scheduler/api/latest"
  37. )
  38. func validateObject(obj runtime.Object) (errors field.ErrorList) {
  39. switch t := obj.(type) {
  40. case *api.ReplicationController:
  41. if t.Namespace == "" {
  42. t.Namespace = api.NamespaceDefault
  43. }
  44. errors = validation.ValidateReplicationController(t)
  45. case *api.ReplicationControllerList:
  46. for i := range t.Items {
  47. errors = append(errors, validateObject(&t.Items[i])...)
  48. }
  49. case *api.Service:
  50. if t.Namespace == "" {
  51. t.Namespace = api.NamespaceDefault
  52. }
  53. errors = validation.ValidateService(t)
  54. case *api.ServiceList:
  55. for i := range t.Items {
  56. errors = append(errors, validateObject(&t.Items[i])...)
  57. }
  58. case *api.Pod:
  59. if t.Namespace == "" {
  60. t.Namespace = api.NamespaceDefault
  61. }
  62. errors = validation.ValidatePod(t)
  63. case *api.PodList:
  64. for i := range t.Items {
  65. errors = append(errors, validateObject(&t.Items[i])...)
  66. }
  67. case *api.PersistentVolume:
  68. errors = validation.ValidatePersistentVolume(t)
  69. case *api.PersistentVolumeClaim:
  70. if t.Namespace == "" {
  71. t.Namespace = api.NamespaceDefault
  72. }
  73. errors = validation.ValidatePersistentVolumeClaim(t)
  74. case *api.PodTemplate:
  75. if t.Namespace == "" {
  76. t.Namespace = api.NamespaceDefault
  77. }
  78. errors = validation.ValidatePodTemplate(t)
  79. case *api.Endpoints:
  80. if t.Namespace == "" {
  81. t.Namespace = api.NamespaceDefault
  82. }
  83. errors = validation.ValidateEndpoints(t)
  84. case *api.Namespace:
  85. errors = validation.ValidateNamespace(t)
  86. case *api.Secret:
  87. if t.Namespace == "" {
  88. t.Namespace = api.NamespaceDefault
  89. }
  90. errors = validation.ValidateSecret(t)
  91. case *api.LimitRange:
  92. if t.Namespace == "" {
  93. t.Namespace = api.NamespaceDefault
  94. }
  95. errors = validation.ValidateLimitRange(t)
  96. case *api.ResourceQuota:
  97. if t.Namespace == "" {
  98. t.Namespace = api.NamespaceDefault
  99. }
  100. errors = validation.ValidateResourceQuota(t)
  101. case *extensions.Deployment:
  102. if t.Namespace == "" {
  103. t.Namespace = api.NamespaceDefault
  104. }
  105. errors = expvalidation.ValidateDeployment(t)
  106. case *batch.Job:
  107. if t.Namespace == "" {
  108. t.Namespace = api.NamespaceDefault
  109. }
  110. // Job needs generateSelector called before validation, and job.Validate does this.
  111. // See: https://github.com/kubernetes/kubernetes/issues/20951#issuecomment-187787040
  112. t.ObjectMeta.UID = types.UID("fakeuid")
  113. errors = job.Strategy.Validate(nil, t)
  114. case *extensions.Ingress:
  115. if t.Namespace == "" {
  116. t.Namespace = api.NamespaceDefault
  117. }
  118. errors = expvalidation.ValidateIngress(t)
  119. case *extensions.DaemonSet:
  120. if t.Namespace == "" {
  121. t.Namespace = api.NamespaceDefault
  122. }
  123. errors = expvalidation.ValidateDaemonSet(t)
  124. default:
  125. errors = field.ErrorList{}
  126. errors = append(errors, field.InternalError(field.NewPath(""), fmt.Errorf("no validation defined for %#v", obj)))
  127. }
  128. return errors
  129. }
  130. func walkJSONFiles(inDir string, fn func(name, path string, data []byte)) error {
  131. return filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {
  132. if err != nil {
  133. return err
  134. }
  135. if info.IsDir() && path != inDir {
  136. return filepath.SkipDir
  137. }
  138. file := filepath.Base(path)
  139. if ext := filepath.Ext(file); ext == ".json" || ext == ".yaml" {
  140. glog.Infof("Testing %s", path)
  141. data, err := ioutil.ReadFile(path)
  142. if err != nil {
  143. return err
  144. }
  145. name := strings.TrimSuffix(file, ext)
  146. if ext == ".yaml" {
  147. out, err := yaml.ToJSON(data)
  148. if err != nil {
  149. return fmt.Errorf("%s: %v", path, err)
  150. }
  151. data = out
  152. }
  153. fn(name, path, data)
  154. }
  155. return nil
  156. })
  157. }
  158. func TestExampleObjectSchemas(t *testing.T) {
  159. cases := map[string]map[string]runtime.Object{
  160. "../examples/guestbook": {
  161. "frontend-deployment": &extensions.Deployment{},
  162. "redis-slave-deployment": &extensions.Deployment{},
  163. "redis-master-deployment": &extensions.Deployment{},
  164. "frontend-service": &api.Service{},
  165. "redis-master-service": &api.Service{},
  166. "redis-slave-service": &api.Service{},
  167. },
  168. "../examples/guestbook/legacy": {
  169. "frontend-controller": &api.ReplicationController{},
  170. "redis-slave-controller": &api.ReplicationController{},
  171. "redis-master-controller": &api.ReplicationController{},
  172. },
  173. "../examples/guestbook-go": {
  174. "guestbook-controller": &api.ReplicationController{},
  175. "redis-slave-controller": &api.ReplicationController{},
  176. "redis-master-controller": &api.ReplicationController{},
  177. "guestbook-service": &api.Service{},
  178. "redis-master-service": &api.Service{},
  179. "redis-slave-service": &api.Service{},
  180. },
  181. "../examples/volumes/iscsi": {
  182. "iscsi": &api.Pod{},
  183. },
  184. "../examples/volumes/glusterfs": {
  185. "glusterfs-pod": &api.Pod{},
  186. "glusterfs-endpoints": &api.Endpoints{},
  187. "glusterfs-service": &api.Service{},
  188. },
  189. "../examples": {
  190. "scheduler-policy-config": &schedulerapi.Policy{},
  191. "scheduler-policy-config-with-extender": &schedulerapi.Policy{},
  192. },
  193. "../examples/volumes/rbd/secret": {
  194. "ceph-secret": &api.Secret{},
  195. },
  196. "../examples/volumes/rbd": {
  197. "rbd": &api.Pod{},
  198. "rbd-with-secret": &api.Pod{},
  199. },
  200. "../examples/storage/cassandra": {
  201. "cassandra-daemonset": &extensions.DaemonSet{},
  202. "cassandra-controller": &api.ReplicationController{},
  203. "cassandra-service": &api.Service{},
  204. },
  205. "../examples/cluster-dns": {
  206. "dns-backend-rc": &api.ReplicationController{},
  207. "dns-backend-service": &api.Service{},
  208. "dns-frontend-pod": &api.Pod{},
  209. "namespace-dev": &api.Namespace{},
  210. "namespace-prod": &api.Namespace{},
  211. },
  212. "../examples/elasticsearch": {
  213. "es-rc": &api.ReplicationController{},
  214. "es-svc": &api.Service{},
  215. "service-account": nil,
  216. },
  217. "../examples/explorer": {
  218. "pod": &api.Pod{},
  219. },
  220. "../examples/storage/hazelcast": {
  221. "hazelcast-controller": &api.ReplicationController{},
  222. "hazelcast-service": &api.Service{},
  223. },
  224. "../examples/meteor": {
  225. "meteor-controller": &api.ReplicationController{},
  226. "meteor-service": &api.Service{},
  227. "mongo-pod": &api.Pod{},
  228. "mongo-service": &api.Service{},
  229. },
  230. "../examples/mysql-wordpress-pd": {
  231. "gce-volumes": &api.PersistentVolume{},
  232. "local-volumes": &api.PersistentVolume{},
  233. "mysql-deployment": &api.Service{},
  234. "wordpress-deployment": &api.Service{},
  235. },
  236. "../examples/volumes/nfs": {
  237. "nfs-busybox-rc": &api.ReplicationController{},
  238. "nfs-server-rc": &api.ReplicationController{},
  239. "nfs-server-service": &api.Service{},
  240. "nfs-pv": &api.PersistentVolume{},
  241. "nfs-pvc": &api.PersistentVolumeClaim{},
  242. "nfs-web-rc": &api.ReplicationController{},
  243. "nfs-web-service": &api.Service{},
  244. },
  245. "../examples/openshift-origin": {
  246. "openshift-origin-namespace": &api.Namespace{},
  247. "openshift-controller": &api.ReplicationController{},
  248. "openshift-service": &api.Service{},
  249. "etcd-controller": &api.ReplicationController{},
  250. "etcd-service": &api.Service{},
  251. "etcd-discovery-controller": &api.ReplicationController{},
  252. "etcd-discovery-service": &api.Service{},
  253. "secret": nil,
  254. },
  255. "../examples/phabricator": {
  256. "phabricator-controller": &api.ReplicationController{},
  257. "phabricator-service": &api.Service{},
  258. },
  259. "../examples/storage/redis": {
  260. "redis-controller": &api.ReplicationController{},
  261. "redis-master": &api.Pod{},
  262. "redis-proxy": &api.Pod{},
  263. "redis-sentinel-controller": &api.ReplicationController{},
  264. "redis-sentinel-service": &api.Service{},
  265. },
  266. "../examples/storage/rethinkdb": {
  267. "admin-pod": &api.Pod{},
  268. "admin-service": &api.Service{},
  269. "driver-service": &api.Service{},
  270. "rc": &api.ReplicationController{},
  271. },
  272. "../examples/spark": {
  273. "namespace-spark-cluster": &api.Namespace{},
  274. "spark-master-controller": &api.ReplicationController{},
  275. "spark-master-service": &api.Service{},
  276. "spark-webui": &api.Service{},
  277. "spark-worker-controller": &api.ReplicationController{},
  278. "zeppelin-controller": &api.ReplicationController{},
  279. "zeppelin-service": &api.Service{},
  280. },
  281. "../examples/spark/spark-gluster": {
  282. "spark-master-service": &api.Service{},
  283. "spark-master-controller": &api.ReplicationController{},
  284. "spark-worker-controller": &api.ReplicationController{},
  285. "glusterfs-endpoints": &api.Endpoints{},
  286. },
  287. "../examples/storm": {
  288. "storm-nimbus-service": &api.Service{},
  289. "storm-nimbus": &api.Pod{},
  290. "storm-worker-controller": &api.ReplicationController{},
  291. "zookeeper-service": &api.Service{},
  292. "zookeeper": &api.Pod{},
  293. },
  294. "../examples/volumes/cephfs/": {
  295. "cephfs": &api.Pod{},
  296. "cephfs-with-secret": &api.Pod{},
  297. },
  298. "../examples/volumes/fibre_channel": {
  299. "fc": &api.Pod{},
  300. },
  301. "../examples/javaweb-tomcat-sidecar": {
  302. "javaweb": &api.Pod{},
  303. "javaweb-2": &api.Pod{},
  304. },
  305. "../examples/volumes/azure_file": {
  306. "azure": &api.Pod{},
  307. },
  308. "../examples/volumes/azure_disk": {
  309. "azure": &api.Pod{},
  310. },
  311. }
  312. capabilities.SetForTests(capabilities.Capabilities{
  313. AllowPrivileged: true,
  314. })
  315. for path, expected := range cases {
  316. tested := 0
  317. err := walkJSONFiles(path, func(name, path string, data []byte) {
  318. expectedType, found := expected[name]
  319. if !found {
  320. t.Errorf("%s: %s does not have a test case defined", path, name)
  321. return
  322. }
  323. tested++
  324. if expectedType == nil {
  325. t.Logf("skipping : %s/%s\n", path, name)
  326. return
  327. }
  328. if strings.Contains(name, "scheduler-policy-config") {
  329. if err := runtime.DecodeInto(schedulerapilatest.Codec, data, expectedType); err != nil {
  330. t.Errorf("%s did not decode correctly: %v\n%s", path, err, string(data))
  331. return
  332. }
  333. //TODO: Add validate method for &schedulerapi.Policy
  334. } else {
  335. codec, err := testapi.GetCodecForObject(expectedType)
  336. if err != nil {
  337. t.Errorf("Could not get codec for %s: %s", expectedType, err)
  338. }
  339. if err := runtime.DecodeInto(codec, data, expectedType); err != nil {
  340. t.Errorf("%s did not decode correctly: %v\n%s", path, err, string(data))
  341. return
  342. }
  343. if errors := validateObject(expectedType); len(errors) > 0 {
  344. t.Errorf("%s did not validate correctly: %v", path, errors)
  345. }
  346. }
  347. })
  348. if err != nil {
  349. t.Errorf("Expected no error, Got %v", err)
  350. }
  351. if tested != len(expected) {
  352. t.Errorf("Directory %v: Expected %d examples, Got %d", path, len(expected), tested)
  353. }
  354. }
  355. }
  356. // This regex is tricky, but it works. For future me, here is the decode:
  357. //
  358. // Flags: (?ms) = multiline match, allow . to match \n
  359. // 1) Look for a line that starts with ``` (a markdown code block)
  360. // 2) (?: ... ) = non-capturing group
  361. // 3) (P<name>) = capture group as "name"
  362. // 4) Look for #1 followed by either:
  363. // 4a) "yaml" followed by any word-characters followed by a newline (e.g. ```yamlfoo\n)
  364. // 4b) "any word-characters followed by a newline (e.g. ```json\n)
  365. // 5) Look for either:
  366. // 5a) #4a followed by one or more characters (non-greedy)
  367. // 5b) #4b followed by { followed by one or more characters (non-greedy) followed by }
  368. // 6) Look for #5 followed by a newline followed by ``` (end of the code block)
  369. //
  370. // This could probably be simplified, but is already too delicate. Before any
  371. // real changes, we should have a testscase that just tests this regex.
  372. var sampleRegexp = regexp.MustCompile("(?ms)^```(?:(?P<type>yaml)\\w*\\n(?P<content>.+?)|\\w*\\n(?P<content>\\{.+?\\}))\\n^```")
  373. var subsetRegexp = regexp.MustCompile("(?ms)\\.{3}")
  374. func TestReadme(t *testing.T) {
  375. paths := []struct {
  376. file string
  377. expectedType []runtime.Object
  378. }{
  379. {"../README.md", []runtime.Object{&api.Pod{}}},
  380. {"../examples/volumes/iscsi/README.md", []runtime.Object{&api.Pod{}}},
  381. }
  382. for _, path := range paths {
  383. data, err := ioutil.ReadFile(path.file)
  384. if err != nil {
  385. t.Errorf("Unable to read file %s: %v", path, err)
  386. continue
  387. }
  388. matches := sampleRegexp.FindAllStringSubmatch(string(data), -1)
  389. if matches == nil {
  390. continue
  391. }
  392. ix := 0
  393. for _, match := range matches {
  394. var content, subtype string
  395. for i, name := range sampleRegexp.SubexpNames() {
  396. if name == "type" {
  397. subtype = match[i]
  398. }
  399. if name == "content" && match[i] != "" {
  400. content = match[i]
  401. }
  402. }
  403. if subtype == "yaml" && subsetRegexp.FindString(content) != "" {
  404. t.Logf("skipping (%s): \n%s", subtype, content)
  405. continue
  406. }
  407. var expectedType runtime.Object
  408. if len(path.expectedType) == 1 {
  409. expectedType = path.expectedType[0]
  410. } else {
  411. expectedType = path.expectedType[ix]
  412. ix++
  413. }
  414. json, err := yaml.ToJSON([]byte(content))
  415. if err != nil {
  416. t.Errorf("%s could not be converted to JSON: %v\n%s", path, err, string(content))
  417. }
  418. if err := runtime.DecodeInto(testapi.Default.Codec(), json, expectedType); err != nil {
  419. t.Errorf("%s did not decode correctly: %v\n%s", path, err, string(content))
  420. continue
  421. }
  422. if errors := validateObject(expectedType); len(errors) > 0 {
  423. t.Errorf("%s did not validate correctly: %v", path, errors)
  424. }
  425. _, err = runtime.Encode(testapi.Default.Codec(), expectedType)
  426. if err != nil {
  427. t.Errorf("Could not encode object: %v", err)
  428. continue
  429. }
  430. }
  431. }
  432. }