{"_id":"doc-en-kubernetes-94b76b7158da38f34cef746d9bee478a533e1bd68a65e8e6a6a09dbc8bf5dccf","title":"","text":" Minion kubelet cAdvisor docker container container container Pod container container container Pod container container container Pod Proxy Minion Node kubelet kubelet cAdvisor container docker container container container container Pod cAdvisor Pod container container container container container container Pod Pod "} {"_id":"doc-en-kubernetes-824f179cebec1a3ec1b6fa5fdcd9cd35f61d8444719cf437ae44c17b90532b8d","title":"","text":" Proxy Proxy "} {"_id":"doc-en-kubernetes-71eac7960bd00f4a4e7b80389cfc8171b7068c7cf3dbc6b24e4fd9049e7fbeb0","title":"","text":" Firewall Firewall Internet Internet "} {"_id":"doc-en-kubernetes-ab525215a4137a9e8eb194dc3a34b23bedf19ded3f83b42537b360dc97a142a7","title":"","text":" Distributed Watchable Storage (implemented via etcd) "} {"_id":"doc-en-kubernetes-7786a413dd147e34c6c3a1cd0bef9850fe38c55144ef993457389b474b9739f3","title":"","text":" "} {"_id":"doc-en-kubernetes-7e4f563aa6e0bcbdd1a66b94e0a23144347b3f757ae31ba7c9767c1b68bfc1da","title":"","text":" docker .. ... Node kubelet container container cAdvisor Pod container container container Pod container container container Pod kubelet info service Proxy docker .. ... Distributed Watchable Storage (implemented via etcd) "} {"_id":"doc-en-kubernetes-056c40aae9b523477819c4baf88ce5b646ffaccc6e48d98e17ed490f77cdf7ce","title":"","text":"import ( \"bytes\" \"encoding/json\" \"fmt\" \"io/ioutil\" \"reflect\" \"time\""} {"_id":"doc-en-kubernetes-481c33cb8e6ad4442a325e2f3d999cdd2ea41e65795005f4f258fb56b126afc1","title":"","text":"var lastEndpoints []api.Endpoints sleep := 5 * time.Second // Used to avoid spamming the error log file, makes error logging edge triggered. hadSuccess := true for { data, err := ioutil.ReadFile(s.filename) if err != nil { glog.Errorf(\"Couldn't read file: %s : %v\", s.filename, err) msg := fmt.Sprintf(\"Couldn't read file: %s : %v\", s.filename, err) if hadSuccess { glog.Error(msg) } else { glog.V(1).Info(msg) } hadSuccess = false time.Sleep(sleep) continue } hadSuccess = true if bytes.Equal(lastData, data) { time.Sleep(sleep)"} {"_id":"doc-en-kubernetes-7c3a010463a431c99c68ab693b6a247385b875e2f8f3206865fc0d34d6ad4fb5","title":"","text":"glog.Infof(\"Version test passed\") } func runSelfLinkTest(c *client.Client) { var svc api.Service err := c.Post().Path(\"services\").Body( &api.Service{ ObjectMeta: api.ObjectMeta{ Name: \"selflinktest\", Labels: map[string]string{ \"name\": \"selflinktest\", }, }, Port: 12345, // This is here because validation requires it. Selector: map[string]string{ \"foo\": \"bar\", }, }, ).Do().Into(&svc) if err != nil { glog.Fatalf(\"Failed creating selflinktest service: %v\", err) } err = c.Get().AbsPath(svc.SelfLink).Do().Into(&svc) if err != nil { glog.Fatalf(\"Failed listing service with supplied self link '%v': %v\", svc.SelfLink, err) } var svcList api.ServiceList err = c.Get().Path(\"services\").Do().Into(&svcList) if err != nil { glog.Fatalf(\"Failed listing services: %v\", err) } err = c.Get().AbsPath(svcList.SelfLink).Do().Into(&svcList) if err != nil { glog.Fatalf(\"Failed listing services with supplied self link '%v': %v\", svcList.SelfLink, err) } found := false for i := range svcList.Items { item := &svcList.Items[i] if item.Name != \"selflinktest\" { continue } found = true err = c.Get().AbsPath(item.SelfLink).Do().Into(&svc) if err != nil { glog.Fatalf(\"Failed listing service with supplied self link '%v': %v\", item.SelfLink, err) } break } if !found { glog.Fatalf(\"never found selflinktest service\") } glog.Infof(\"Self link test passed\") // TODO: Should test PUT at some point, too. } func runAtomicPutTest(c *client.Client) { var svc api.Service err := c.Post().Path(\"services\").Body("} {"_id":"doc-en-kubernetes-559cf43ef81f6d6a44fbacc117be3d22b123560c680b895a0d01ee36ecc0a6e0","title":"","text":"runServiceTest, runAPIVersionsTest, runMasterServiceTest, runSelfLinkTest, } var wg sync.WaitGroup wg.Add(len(testFuncs))"} {"_id":"doc-en-kubernetes-5644ac57169d4e7e288c9846590f3ac560ea0c4dcf7375dec4eba330b758d855","title":"","text":"newURL.Path = path.Join(h.canonicalPrefix, req.URL.Path) newURL.RawQuery = \"\" newURL.Fragment = \"\" return h.selfLinker.SetSelfLink(obj, newURL.String()) err := h.selfLinker.SetSelfLink(obj, newURL.String()) if err != nil { return err } if !runtime.IsListType(obj) { return nil } // Set self-link of objects in the list. items, err := runtime.ExtractList(obj) if err != nil { return err } for i := range items { if err := h.setSelfLinkAddName(items[i], req); err != nil { return err } } return runtime.SetList(obj, items) } // Like setSelfLink, but appends the object's name."} {"_id":"doc-en-kubernetes-3e16d4673a4e155a5204361313297ce03461058571e1495995578e343c57aa5f","title":"","text":"\"github.com/GoogleCloudPlatform/kubernetes/pkg/conversion\" ) func IsListType(obj Object) bool { _, err := GetItemsPtr(obj) return err == nil } // GetItemsPtr returns a pointer to the list object's Items member. // If 'list' doesn't have an Items member, it's not really a list type // and an error will be returned."} {"_id":"doc-en-kubernetes-f2b7227aa5809e2ad93786c56678a2f443c615e4425d813324d6b15c85393526","title":"","text":"\"github.com/google/gofuzz\" ) func TestIsList(t *testing.T) { tests := []struct { obj runtime.Object isList bool }{ {&api.PodList{}, true}, {&api.Pod{}, false}, } for _, item := range tests { if e, a := item.isList, runtime.IsListType(item.obj); e != a { t.Errorf(\"%v: Expected %v, got %v\", reflect.TypeOf(item.obj), e, a) } } } func TestExtractList(t *testing.T) { pl := &api.PodList{ Items: []api.Pod{"} {"_id":"doc-en-kubernetes-2f423faa5d7b893bb36e115dd653dc1122e59a11be0c2e04b387deced8cd91c7","title":"","text":"for i, manifest := range manifests.Items { name := manifest.ID if name == \"\" { name = fmt.Sprintf(\"_%d\", i+1) name = fmt.Sprintf(\"%d\", i+1) } pods = append(pods, kubelet.Pod{Name: name, Manifest: manifest}) }"} {"_id":"doc-en-kubernetes-c77fab6f1ada196ff2b2b972bd9baf356870057afcf2ddb04d47111912a366d5","title":"","text":"func TestGetEtcd(t *testing.T) { fakeClient := tools.MakeFakeEtcdClient(t) ch := make(chan interface{}, 1) manifest := api.ContainerManifest{ID: \"foo\", Version: \"v1beta1\", Containers: []api.Container{{Name: \"1\", Image: \"foo\"}}} fakeClient.Data[\"/registry/hosts/machine/kubelet\"] = tools.EtcdResponseWithError{ R: &etcd.Response{ Node: &etcd.Node{ Value: api.EncodeOrDie(&api.ContainerManifestList{ Items: []api.ContainerManifest{{ID: \"foo\"}}, Items: []api.ContainerManifest{manifest}, }), ModifiedIndex: 1, },"} {"_id":"doc-en-kubernetes-1476b2eae164695a67ea94bac2f3228156d93c492177c7192da14ab418fd7d0e","title":"","text":"t.Errorf(\"Expected %#v, Got %#v\", 2, lastIndex) } update := (<-ch).(kubelet.PodUpdate) expected := CreatePodUpdate(kubelet.SET, kubelet.Pod{Name: \"foo\", Manifest: api.ContainerManifest{ID: \"foo\"}}) expected := CreatePodUpdate(kubelet.SET, kubelet.Pod{Name: \"foo\", Manifest: manifest}) if !reflect.DeepEqual(expected, update) { t.Errorf(\"Expected %#v, Got %#v\", expected, update) } for i := range update.Pods { if errs := kubelet.ValidatePod(&update.Pods[i]); len(errs) != 0 { t.Errorf(\"Expected no validation errors on %#v, Got %#v\", update.Pods[i], errs) } } } func TestWatchEtcd(t *testing.T) {"} {"_id":"doc-en-kubernetes-f3dd572040a1f39ce9afb9b135a449a10737f44240dda6f199479d055f8d67a2","title":"","text":"import ( \"crypto/sha1\" \"encoding/base64\" \"encoding/base32\" \"fmt\" \"io/ioutil\" \"os\" \"path/filepath\" \"regexp\" \"sort\" \"strings\" \"time\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet\""} {"_id":"doc-en-kubernetes-0590595e283b75e93838ef59263bca7b4a1496840461423d8b1ae5bd31996b6e","title":"","text":"return pod, nil } var simpleSubdomainSafeEncoding = base64.NewEncoding(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678900\") var simpleSubdomainSafeEncoding = base32.NewEncoding(\"0123456789abcdefghijklmnopqrstuv\") var unsafeDNSLabelReplacement = regexp.MustCompile(\"[^a-z0-9]+\") // simpleSubdomainSafeHash generates a compact hash of the input that uses characters // only in the range a-zA-Z0-9, making it suitable for DNS subdomain labels func simpleSubdomainSafeHash(s string) string { // simpleSubdomainSafeHash generates a pod name for the given path that is // suitable as a subdomain label. func simpleSubdomainSafeHash(path string) string { name := strings.ToLower(filepath.Base(path)) name = unsafeDNSLabelReplacement.ReplaceAllString(name, \"\") hasher := sha1.New() hasher.Write([]byte(s)) hasher.Write([]byte(path)) sha := simpleSubdomainSafeEncoding.EncodeToString(hasher.Sum(nil)) if len(sha) > 20 { sha = sha[:20] } return sha return fmt.Sprintf(\"%.15s%.30s\", name, sha) }"} {"_id":"doc-en-kubernetes-55e55b0f9146d30528f5d535c7f5fffe20b83b9f3794a649fe3b50c665532bb6","title":"","text":"func TestExtractFromDir(t *testing.T) { manifests := []api.ContainerManifest{ {ID: \"\", Containers: []api.Container{{Image: \"foo\"}}}, {ID: \"\", Containers: []api.Container{{Image: \"bar\"}}}, {Version: \"v1beta1\", Containers: []api.Container{{Name: \"1\", Image: \"foo\"}}}, {Version: \"v1beta1\", Containers: []api.Container{{Name: \"2\", Image: \"bar\"}}}, } files := make([]*os.File, len(manifests))"} {"_id":"doc-en-kubernetes-60b8917d0cb759332fdbc5d58e183dc7a24ed48ec20ff3c663cd617b505bb73e","title":"","text":"if !reflect.DeepEqual(expected, update) { t.Errorf(\"Expected %#v, Got %#v\", expected, update) } for i := range update.Pods { if errs := kubelet.ValidatePod(&update.Pods[i]); len(errs) != 0 { t.Errorf(\"Expected no validation errors on %#v, Got %#v\", update.Pods[i], errs) } } } func TestSubdomainSafeName(t *testing.T) { type Case struct { Input string Expected string } testCases := []Case{ {\"/some/path/invalidUPPERCASE\", \"invaliduppercasa6hlenc0vpqbbdtt26ghneqsq3pvud\"}, {\"/some/path/_-!%$#&@^&*(){}\", \"nvhc03p016m60huaiv3avts372rl2p\"}, } for _, testCase := range testCases { value := simpleSubdomainSafeHash(testCase.Input) if value != testCase.Expected { t.Errorf(\"Expected %s, Got %s\", testCase.Expected, value) } value2 := simpleSubdomainSafeHash(testCase.Input) if value != value2 { t.Errorf(\"Value for %s was not stable across runs: %s %s\", testCase.Input, value, value2) } } } // These are used for testing extract json (below)"} {"_id":"doc-en-kubernetes-77ca850f1e7cc522875f4168243c63c85961de8df906aef9f05a075d1e6702f1","title":"","text":"func TestExtractFromHttpMultiple(t *testing.T) { manifests := []api.ContainerManifest{ {Version: \"v1beta1\", ID: \"\"}, {Version: \"v1beta1\", ID: \"bar\"}, {Version: \"v1beta1\", ID: \"\", Containers: []api.Container{{Name: \"1\", Image: \"foo\"}}}, {Version: \"v1beta1\", ID: \"bar\", Containers: []api.Container{{Name: \"1\", Image: \"foo\"}}}, } data, err := json.Marshal(manifests) if err != nil {"} {"_id":"doc-en-kubernetes-1f7a2af8ecde443631baa5df97bc14532c5ec6e5c7ce677f131ada79aecfc5d7","title":"","text":"if !reflect.DeepEqual(expected, update) { t.Errorf(\"Expected: %#v, Got: %#v\", expected, update) } for i := range update.Pods { if errs := kubelet.ValidatePod(&update.Pods[i]); len(errs) != 0 { t.Errorf(\"Expected no validation errors on %#v, Got %#v\", update.Pods[i], errs) } } } func TestExtractFromHttpEmptyArray(t *testing.T) {"} {"_id":"doc-en-kubernetes-8054c8bbdd963bec7e8fd99db1df1a7991f39531fa67ebfb06dff6c1a74f4eae","title":"","text":"* **Kubernetes Web Interface** ([ui.md](ui.md)): Accessing the Kubernetes web user interface. * **Kubecfg Command Line Interface** ([cli.md](cli.md)): The `kubecfg` command line reference. * **Kubectl Command Line Interface** ([kubectl.md](kubectl.md)): The `kubectl` command line reference. * **Roadmap** ([roadmap.md](roadmap.md)): The set of supported use cases, features, docs, and patterns that are required before Kubernetes 1.0."} {"_id":"doc-en-kubernetes-88cd7c30fd22e6a3e7340a791c4484c999037e4e755e9f3bc3aef5fc542c50aa","title":"","text":" ## kubectl The ```kubectl``` command provides command line access to the kubernetes API. See [kubectl documentation](kubectl.md) for details. ## kubecfg is deprecated. Please use kubectl! ## kubecfg command line interface The `kubecfg` command line tools is used to interact with the Kubernetes HTTP API. * [ReplicationController Commands](#replication-controller-commands) * [RESTful Commands](#restful-commands) * [Complete Details](#details) * [Usage](#usage) * [Options](#options) ### Replication Controller Commands #### Run ``` kubecfg [options] run ``` Creates a Kubernetes ReplicaController object. * `[options]` are described in the [Options](#options) section. * `` is the Docker image to use. * `` is the number of replicas of the container to create. * `` is the name to assign to this new ReplicaController. ##### Example ``` kubecfg -p 8080:80 run dockerfile/nginx 2 myNginxController ``` #### Resize ``` kubecfg [options] resize ``` Changes the desired number of replicas, causing replicas to be created or deleted. * `[options]` are described in the [Options](#options) section. ##### Example ``` kubecfg resize myNginxController 3 ``` #### Stop ``` kubecfg [options] stop ``` Stops a controller by setting its desired size to zero. Syntactic sugar on top of resize. * `[options]` are described in the [Options](#options) section. #### Remove ``` kubecfg [options] rm ``` Delete a replication controller. The desired size of the controller must be zero, by calling either `kubecfg resize 0` or `kubecfg stop `. * `[options]` are described in the [Options](#options) section. ### RESTful Commands Kubecfg also supports raw access to the basic restful requests. There are four different resources you can acccess: * `pods` * `replicationControllers` * `services` * `minions` ###### Common Flags * -yaml : output in YAML format * -json : output in JSON format * -c : Accept a file in JSON or YAML for POST/PUT #### Commands ##### get Raw access to a RESTful GET request. ``` kubecfg [options] get pods/pod-abc-123 ``` ##### list Raw access to a RESTful LIST request. ``` kubecfg [options] list pods ``` ##### create Raw access to a RESTful POST request. ``` kubecfg <-c some/body.[json|yaml]> [options] create pods ``` ##### update Raw access to a RESTful PUT request. ``` kubecfg <-c some/body.[json|yaml]> [options] update pods/pod-abc-123 ``` ##### delete Raw access to a RESTful DELETE request. ``` kubecfg [options] delete pods/pod-abc-123 ``` ### Details #### Usage ``` kubecfg -h [-c config/file.json] [-p :,..., :] Kubernetes REST API: kubecfg [OPTIONS] get|list|create|delete|update [/] Manage replication controllers: kubecfg [OPTIONS] stop|rm|rollingupdate kubecfg [OPTIONS] run kubecfg [OPTIONS] resize ``` #### Options * `-V=true|false`: Print the version number. * `-alsologtostderr=true|false`: log to standard error as well as files * `-auth=\"/path/to/.kubernetes_auth\"`: Path to the auth info file. Only used if doing https. * `-c=\"/path/to/config_file\"`: Path to the config file. * `-h=\"\"`: The host to connect to. * `-json=true|false`: If true, print raw JSON for responses * `-l=\"\"`: Selector (label query) to use for listing * `-log_backtrace_at=:0`: when logging hits line file:N, emit a stack trace * `-log_dir=\"\"`: If non-empty, write log files in this directory * `-log_flush_frequency=5s`: Maximum number of seconds between log flushes * `-logtostderr=true|false`: log to standard error instead of files * `-p=\"\"`: The port spec, comma-separated list of `:,...` * `-proxy=true|false`: If true, run a proxy to the API server * `-s=-1`: If positive, create and run a corresponding service on this port, only used with 'run' * `-stderrthreshold=0`: logs at or above this threshold go to stderr * `-template=\"\"`: If present, parse this string as a golang template and use it for output printing * `-template_file=\"\"`: If present, load this file as a golang template and use it for output printing * `-u=1m0s`: Update interval period * `-v=0`: log level for V logs. See [Logging Conventions](devel/logging.md) for details * `-verbose=true|false`: If true, print extra information * `-vmodule=\"\"`: comma-separated list of pattern=N settings for file-filtered logging * `-www=\"\"`: If -proxy is true, use this directory to serve static files * `-yaml=true|false`: If true, print raw YAML for responses "} {"_id":"doc-en-kubernetes-7a671e34f733ae15cb97f401d4620aa5917af4de1b3ad08c7ad6c0a37ceb817b","title":"","text":"* [API](api-conventions.md) * [Client libraries](client-libraries.md) * [Command-line interface](cli.md) * [Command-line interface](kubectl.md) * [UI](ux.md) * [Images and registries](images.md) * [Container environment](container-environment.md)"} {"_id":"doc-en-kubernetes-96fe0bfe1bf4b1cfaa75dda32d8f502734a33f1d73a3eeebc8382cd3b79b9eba","title":"","text":"The replication controller is forever constrained to this narrow responsibility. It itself will not perform readiness nor liveness probes. Rather than performing auto-scaling, it is intended to be controlled by an external auto-scaler (as discussed in [#492](https://github.com/GoogleCloudPlatform/kubernetes/issues/492)), which would change its `replicas` field. We will not add scheduling policies (e.g., [spreading](https://github.com/GoogleCloudPlatform/kubernetes/issues/367#issuecomment-48428019)) to replication controller. Nor should it verify that the pods controlled match the currently specified template, as that would obstruct auto-sizing and other automated processes. Similarly, completion deadlines, ordering dependencies, configuration expansion, and other features belong elsehwere. We even plan to factor out the mechanism for bulk pod creation ([#170](https://github.com/GoogleCloudPlatform/kubernetes/issues/170)). The replication controller is intended to be a composable building-block primitive. We expect higher-level APIs and/or tools to be built on top of it and other complementary primitives for user convenience in the future. The \"macro\" operations currently supported by kubecfg (run, stop, resize, rollingupdate) are proof-of-concept examples of this. For instance, we could imagine something like [Asgard](http://techblog.netflix.com/2012/06/asgard-web-based-cloud-management-and.html) managing replication controllers, auto-scalers, services, scheduling policies, canaries, etc. The replication controller is intended to be a composable building-block primitive. We expect higher-level APIs and/or tools to be built on top of it and other complementary primitives for user convenience in the future. The \"macro\" operations currently supported by kubectl (run-container, stop, resize, rollingupdate) are proof-of-concept examples of this. For instance, we could imagine something like [Asgard](http://techblog.netflix.com/2012/06/asgard-web-based-cloud-management-and.html) managing replication controllers, auto-scalers, services, scheduling policies, canaries, etc. ## Common usage patterns"} {"_id":"doc-en-kubernetes-ee892708bfa41a4f9b5eb02ad3043296cc9d7a00f5616e16ded5b2c6e202cc6e","title":"","text":"Start the server: ```sh cluster/kubecfg.sh -proxy -www $PWD/www cluster/kubectl.sh proxy -www=$PWD/www ``` The UI should now be running on [localhost](http://localhost:8001/static/index.html#/groups//selector)"} {"_id":"doc-en-kubernetes-cba0204e1a4f53cc2176261e51788498d463d235c7d9f3516d9366346705f2a0","title":"","text":"# install. See https://github.com/saltstack/salt-bootstrap/issues/270 # # -M installs the master # FIXME: The following line should be replaced with: # curl -L http://bootstrap.saltstack.com | sh -s -- -M # when the merged salt-api service is included in the fedora salt-master rpm # Merge is here: https://github.com/saltstack/salt/pull/13554 # Fedora git repository is here: http://pkgs.fedoraproject.org/cgit/salt.git/ # (a new service file needs to be added for salt-api) curl -sS -L https://raw.githubusercontent.com/saltstack/salt-bootstrap/v2014.06.30/bootstrap-salt.sh | sh -s -- -M curl -sS -L --connect-timeout 20 --retry 6 --retry-delay 10 https://bootstrap.saltstack.com | sh -s -- -M fi # Build release"} {"_id":"doc-en-kubernetes-d432ad9835130ddff181e23ec081539c60e95bed6e658ebbfe89e3eac77b6391","title":"","text":"# # We specify -X to avoid a race condition that can cause minion failure to # install. See https://github.com/saltstack/salt-bootstrap/issues/270 curl -sS -L http://bootstrap.saltstack.com | sh -s -- -X curl -sS -L --connect-timeout 20 --retry 6 --retry-delay 10 https://bootstrap.saltstack.com | sh -s -- -X ## TODO this only works on systemd distros, need to find a work-around as removing -X above fails to start the services installed systemctl enable salt-minion"} {"_id":"doc-en-kubernetes-8fbd5069dc8d0c6f50725a24a030fe68d0dfa0a75d89baaa3745d64bc3a59e50","title":"","text":"myKubelet := kubelet.NewIntegrationTestKubelet(machineList[0], &fakeDocker1) go util.Forever(func() { myKubelet.Run(cfg1.Updates()) }, 0) go util.Forever(func() { kubelet.ListenAndServeKubeletServer(myKubelet, cfg1.Channel(\"http\"), http.DefaultServeMux, \"localhost\", 10250) kubelet.ListenAndServeKubeletServer(myKubelet, cfg1.Channel(\"http\"), \"localhost\", 10250) }, 0) // Kubelet (machine)"} {"_id":"doc-en-kubernetes-3800f1341f4cd6bdcc9cc4a746fe471dfba758db97dba862a6e4ca9d132cbf20","title":"","text":"otherKubelet := kubelet.NewIntegrationTestKubelet(machineList[1], &fakeDocker2) go util.Forever(func() { otherKubelet.Run(cfg2.Updates()) }, 0) go util.Forever(func() { kubelet.ListenAndServeKubeletServer(otherKubelet, cfg2.Channel(\"http\"), http.DefaultServeMux, \"localhost\", 10251) kubelet.ListenAndServeKubeletServer(otherKubelet, cfg2.Channel(\"http\"), \"localhost\", 10251) }, 0) return apiServer.URL"} {"_id":"doc-en-kubernetes-af2c5c88a18cae048e4729875cbad873e81badb4cda114d4b924ff9bc0ff59cd","title":"","text":"// start the kubelet server if *enableServer { go util.Forever(func() { kubelet.ListenAndServeKubeletServer(k, cfg.Channel(\"http\"), http.DefaultServeMux, *address, *port) kubelet.ListenAndServeKubeletServer(k, cfg.Channel(\"http\"), *address, *port) }, 0) }"} {"_id":"doc-en-kubernetes-5de0dd7e140d5f8b76254ed921689e322f48b6f4eaae2bb827f0d06cb615ab3b","title":"","text":"type Server struct { host HostInterface updates chan<- interface{} handler http.Handler mux *http.ServeMux } func ListenAndServeKubeletServer(host HostInterface, updates chan<- interface{}, delegate http.Handler, address string, port uint) { // ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet func ListenAndServeKubeletServer(host HostInterface, updates chan<- interface{}, address string, port uint) { glog.Infof(\"Starting to listen on %s:%d\", address, port) handler := Server{ host: host, updates: updates, handler: delegate, } handler := NewServer(host, updates) s := &http.Server{ Addr: net.JoinHostPort(address, strconv.FormatUint(uint64(port), 10)), Handler: &handler,"} {"_id":"doc-en-kubernetes-1442573651d91c2a6cf6b8a92832be370c4ed7922f688d3cb66f3c16dbf1ab0a","title":"","text":"ServeLogs(w http.ResponseWriter, req *http.Request) } // NewServer initializes and configures a kubelet.Server object to handle HTTP requests func NewServer(host HostInterface, updates chan<- interface{}) Server { server := Server{ host: host, updates: updates, mux: http.NewServeMux(), } server.InstallDefaultHandlers() return server } // InstallDefaultHandlers registers the set of supported HTTP request patterns with the mux func (s *Server) InstallDefaultHandlers() { s.mux.HandleFunc(\"/healthz\", s.handleHealth) s.mux.HandleFunc(\"/container\", s.handleContainer) s.mux.HandleFunc(\"/containers\", s.handleContainers) s.mux.HandleFunc(\"/podInfo\", s.handlePodInfo) s.mux.HandleFunc(\"/stats/\", s.handleStats) s.mux.HandleFunc(\"/logs/\", s.handleLogs) s.mux.HandleFunc(\"/spec/\", s.handleSpec) } // error serializes an error object into an HTTP response func (s *Server) error(w http.ResponseWriter, err error) { http.Error(w, fmt.Sprintf(\"Internal Error: %v\", err), http.StatusInternalServerError) } func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { defer httplog.MakeLogged(req, &w).StacktraceWhen( httplog.StatusIsNot( http.StatusOK, http.StatusNotFound, ), ).Log() // handleHealth handles health checking requests against the Kubelet func (s *Server) handleHealth(w http.ResponseWriter, req *http.Request) { } // handleContainer handles container requests against the Kubelet func (s *Server) handleContainer(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() data, err := ioutil.ReadAll(req.Body) if err != nil { s.error(w, err) return } // This is to provide backward compatibility. It only supports a single manifest var pod Pod err = yaml.Unmarshal(data, &pod.Manifest) if err != nil { s.error(w, err) return } //TODO: sha1 of manifest? pod.Name = \"1\" s.updates <- PodUpdate{[]Pod{pod}, SET} } // handleContainers handles containers requests against the Kubelet func (s *Server) handleContainers(w http.ResponseWriter, req *http.Request) { defer req.Body.Close() data, err := ioutil.ReadAll(req.Body) if err != nil { s.error(w, err) return } var manifests []api.ContainerManifest err = yaml.Unmarshal(data, &manifests) if err != nil { s.error(w, err) return } pods := make([]Pod, len(manifests)) for i := range manifests { pods[i].Name = fmt.Sprintf(\"%d\", i+1) pods[i].Manifest = manifests[i] } s.updates <- PodUpdate{pods, SET} } // handlePodInfo handles podInfo requests against the Kubelet func (s *Server) handlePodInfo(w http.ResponseWriter, req *http.Request) { u, err := url.ParseRequestURI(req.RequestURI) if err != nil { s.error(w, err) return } // TODO: use an http.ServeMux instead of a switch. switch { case u.Path == \"/container\" || u.Path == \"/containers\": defer req.Body.Close() data, err := ioutil.ReadAll(req.Body) if err != nil { s.error(w, err) return } if u.Path == \"/container\" { // This is to provide backward compatibility. It only supports a single manifest var pod Pod err = yaml.Unmarshal(data, &pod.Manifest) if err != nil { s.error(w, err) return } //TODO: sha1 of manifest? pod.Name = \"1\" s.updates <- PodUpdate{[]Pod{pod}, SET} } else if u.Path == \"/containers\" { var manifests []api.ContainerManifest err = yaml.Unmarshal(data, &manifests) if err != nil { s.error(w, err) return } pods := make([]Pod, len(manifests)) for i := range manifests { pods[i].Name = fmt.Sprintf(\"%d\", i+1) pods[i].Manifest = manifests[i] } s.updates <- PodUpdate{pods, SET} } case u.Path == \"/podInfo\": podID := u.Query().Get(\"podID\") if len(podID) == 0 { w.WriteHeader(http.StatusBadRequest) http.Error(w, \"Missing 'podID=' query entry.\", http.StatusBadRequest) return } // TODO: backwards compatibility with existing API, needs API change podFullName := GetPodFullName(&Pod{Name: podID, Namespace: \"etcd\"}) info, err := s.host.GetPodInfo(podFullName) if err == ErrNoContainersInPod { http.Error(w, \"Pod does not exist\", http.StatusNotFound) return } if err != nil { s.error(w, err) return } data, err := json.Marshal(info) if err != nil { s.error(w, err) return } w.WriteHeader(http.StatusOK) w.Header().Add(\"Content-type\", \"application/json\") w.Write(data) case strings.HasPrefix(u.Path, \"/stats\"): s.serveStats(w, req) case strings.HasPrefix(u.Path, \"/spec\"): info, err := s.host.GetMachineInfo() if err != nil { s.error(w, err) return } data, err := json.Marshal(info) if err != nil { s.error(w, err) return } w.Header().Add(\"Content-type\", \"application/json\") w.Write(data) case strings.HasPrefix(u.Path, \"/logs/\"): s.host.ServeLogs(w, req) default: if s.handler != nil { s.handler.ServeHTTP(w, req) } podID := u.Query().Get(\"podID\") if len(podID) == 0 { w.WriteHeader(http.StatusBadRequest) http.Error(w, \"Missing 'podID=' query entry.\", http.StatusBadRequest) return } // TODO: backwards compatibility with existing API, needs API change podFullName := GetPodFullName(&Pod{Name: podID, Namespace: \"etcd\"}) info, err := s.host.GetPodInfo(podFullName) if err == ErrNoContainersInPod { http.Error(w, \"Pod does not exist\", http.StatusNotFound) return } if err != nil { s.error(w, err) return } data, err := json.Marshal(info) if err != nil { s.error(w, err) return } w.WriteHeader(http.StatusOK) w.Header().Add(\"Content-type\", \"application/json\") w.Write(data) } // handleStats handles stats requests against the Kubelet func (s *Server) handleStats(w http.ResponseWriter, req *http.Request) { s.serveStats(w, req) } // handleLogs handles logs requests against the Kubelet func (s *Server) handleLogs(w http.ResponseWriter, req *http.Request) { s.host.ServeLogs(w, req) } // handleSpec handles spec requests against the Kubelet func (s *Server) handleSpec(w http.ResponseWriter, req *http.Request) { info, err := s.host.GetMachineInfo() if err != nil { s.error(w, err) return } data, err := json.Marshal(info) if err != nil { s.error(w, err) return } w.Header().Add(\"Content-type\", \"application/json\") w.Write(data) } // ServeHTTP responds to HTTP requests on the Kubelet func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { defer httplog.MakeLogged(req, &w).StacktraceWhen( httplog.StatusIsNot( http.StatusOK, http.StatusNotFound, ), ).Log() s.mux.ServeHTTP(w, req) } // serveStats implements stats logic func (s *Server) serveStats(w http.ResponseWriter, req *http.Request) { // /stats// components := strings.Split(strings.TrimPrefix(path.Clean(req.URL.Path), \"/\"), \"/\")"} {"_id":"doc-en-kubernetes-1ed72901bc3ca78d7548879bb28f66a7081d79dd71775fba4ce821cbf87174be","title":"","text":"} fw.updateReader = startReading(fw.updateChan) fw.fakeKubelet = &fakeKubelet{} fw.serverUnderTest = &Server{ host: fw.fakeKubelet, updates: fw.updateChan, } server := NewServer(fw.fakeKubelet, fw.updateChan) fw.serverUnderTest = &server fw.testHTTPServer = httptest.NewServer(fw.serverUnderTest) return fw }"} {"_id":"doc-en-kubernetes-82d6ae4c87c6f8e252c1f0b26293f239ba6c9acb5e3ce72c90d7acd21c87661c","title":"","text":"MASTER_NAME=\"${INSTANCE_PREFIX}-master\" MASTER_TAG=\"${INSTANCE_PREFIX}-master\" MINION_TAG=\"${INSTANCE_PREFIX}-minion\" MINION_NAMES=($(eval echo ${INSTANCE_PREFIX}-minion-{1..${NUM_MINIONS}})) # Unable to use hostnames yet because DNS is not in cluster, so we revert external look-up name to use the minion IP #MINION_NAMES=($(eval echo ${INSTANCE_PREFIX}-minion-{1..${NUM_MINIONS}})) # IP LOCATIONS FOR INTERACTING WITH THE MINIONS MINION_IP_BASE=\"10.245.2.\" for (( i=0; i <${NUM_MINIONS}; i++)) do KUBE_MINION_IP_ADDRESSES[$i]=\"${MINION_IP_BASE}$[$i+2]\" MINION_IP[$i]=\"${MINION_IP_BASE}$[$i+2]\" MINION_NAMES[$i]=\"${MINION_IP[$i]}\" VAGRANT_MINION_NAMES[$i]=\"minion-$[$i+1]\" done"} {"_id":"doc-en-kubernetes-7c71f9e0113efc7076f4fba27ef91e71d7c9106fb82617e594c8a3eefe47839b","title":"","text":"roles: - kubernetes-pool cbr-cidr: $MINION_IP_RANGE minion_ip: $MINION_IP EOF # we will run provision to update code each time we test, so we do not want to do salt install each time"} {"_id":"doc-en-kubernetes-de759a85143135ff9fd02b94e0e816e8a265a2d0db10ffd77d00a4e4b54071ea","title":"","text":"} filteredMinions := v.saltMinionsByRole(minions, \"kubernetes-pool\") for _, minion := range filteredMinions { fmt.Println(\"Minion: \", minion.Host, \" , \", instance, \" IP: \", minion.IP) if minion.Host == instance { // Due to vagrant not running with a dedicated DNS setup, we return the IP address of a minion as its hostname at this time if minion.IP == instance { return net.ParseIP(minion.IP), nil } }"} {"_id":"doc-en-kubernetes-2f8e98e7e98c372dc9b4c1118e0ae7e652f34421dcc2002b0c2601dd17e6286d","title":"","text":"filteredMinions := v.saltMinionsByRole(minions, \"kubernetes-pool\") var instances []string for _, instance := range filteredMinions { instances = append(instances, instance.Host) // With no dedicated DNS setup in cluster, IP address is used as hostname instances = append(instances, instance.IP) } return instances, nil"} {"_id":"doc-en-kubernetes-791f8b2b45dd83fe96b7916ad94854be317260c60d6932552ab3f0694976deb6","title":"","text":"t.Fatalf(\"Incorrect number of instances returned\") } if instances[0] != \"kubernetes-minion-1\" { // no DNS in vagrant cluster, so we return IP as hostname expectedInstanceHost := \"10.245.2.2\" expectedInstanceIP := \"10.245.2.2\" if instances[0] != expectedInstanceHost { t.Fatalf(\"Invalid instance returned\") }"} {"_id":"doc-en-kubernetes-81f29a5f4247c1add94ae8d1f8917b417a051b7b63497d541945536c189c5c49","title":"","text":"t.Fatalf(\"Unexpected error, should have returned a valid IP address: %s\", err) } if ip.String() != \"10.245.2.2\" { if ip.String() != expectedInstanceIP { t.Fatalf(\"Invalid IP address returned\") } }"} {"_id":"doc-en-kubernetes-37f463a451931f1a183550432329e210e208b39cdfd1c14a4a6f7be08b104ec5","title":"","text":"import ( \"fmt\" \"strings\" \"sync\" \"time\""} {"_id":"doc-en-kubernetes-6dad3f50a0b02f8f04123091be0f650f366c3015ea36bcd28a8f019845b5e73c","title":"","text":"if instances == nil || !ok { return \"\" } ix := strings.Index(host, \".\") if ix != -1 { host = host[:ix] } addr, err := instances.IPAddress(host) if err != nil { glog.Errorf(\"Error getting instance IP: %#v\", err)"} {"_id":"doc-en-kubernetes-cfb7307c013043c7a3dfc83f212625ec6957dc00a7151c86cc9526ffa0a6e779","title":"","text":"package main import \"syscall\" import ( \"os\" \"os/signal\" \"syscall\" ) func main() { // Halts execution, waiting on signal. syscall.Pause() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM) // Block until a signal is received. <-c }"} {"_id":"doc-en-kubernetes-d0866d03c769fdfd121dca3ce3da4ce50e94aaafcc4c587d2d096f26c512e658","title":"","text":"set -e set -x # Build the binary. go build --ldflags '-extldflags \"-static\" -s' pause.go # Run goupx to shrink binary size. go get github.com/pwaller/goupx goupx pause "} {"_id":"doc-en-kubernetes-5d4f925e4f8f487394eccdb707b78736978977739e90987215e9c657e8f96ae1","title":"","text":") var ( configFile = flag.String(\"configfile\", \"/tmp/proxy_config\", \"Configuration file for the proxy\") etcdServerList util.StringList etcdConfigFile = flag.String(\"etcd_config\", \"\", \"The config file for the etcd client. Mutually exclusive with -etcd_servers\") bindAddress = util.IP(net.ParseIP(\"0.0.0.0\"))"} {"_id":"doc-en-kubernetes-7fadfd0900aea33319228dc4aa9a01a291a14bf4b52fe3a1a435dca5f27bf3be","title":"","text":"} } // And create a configuration source that reads from a local file config.NewConfigSourceFile(*configFile, serviceConfig.Channel(\"file\"), endpointsConfig.Channel(\"file\")) glog.Infof(\"Using configuration file %s\", *configFile) loadBalancer := proxy.NewLoadBalancerRR() proxier := proxy.NewProxier(loadBalancer, net.IP(bindAddress)) // Wire proxier to handle changes to services"} {"_id":"doc-en-kubernetes-dbb8f8abf8e792e7f35be402092fd88ea529699560ca69eaa05dda215ea1344c","title":"","text":"**-bindaddress**=\"0.0.0.0\" The address for the proxy server to serve on (set to 0.0.0.0 or \"\" for all interfaces) **-configfile**=\"/tmp/proxy_config\" Configuration file for the proxy **-etcd_servers**=[] List of etcd servers to watch (http://ip:port), comma separated (optional)"} {"_id":"doc-en-kubernetes-77da8fc49d75a5e74e299a59487f9a47e1d662a4cffd7ffb963ed801e246f60d","title":"","text":"The address for the proxy server to serve on (set to 0.0.0.0 or \"\" for all interfaces) .PP fB-configfilefP=\"/tmp/proxy_config\" Configuration file for the proxy .PP fB-etcd_serversfP=[] List of etcd servers to watch ( [la]http://ip:port[ra]), comma separated (optional)"} {"_id":"doc-en-kubernetes-29948b79f4a07c40ab6dad57f381072996a465ad212efbe37a0821d75020af7e","title":"","text":" /* Copyright 2014 Google Inc. 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. */ // Reads the configuration from the file. Example file for two services [nodejs & mysql] //{\"Services\": [ // { // \"Name\":\"nodejs\", // \"Port\":10000, // \"Endpoints\":[\"10.240.180.168:8000\", \"10.240.254.199:8000\", \"10.240.62.150:8000\"] // }, // { // \"Name\":\"mysql\", // \"Port\":10001, // \"Endpoints\":[\"10.240.180.168:9000\", \"10.240.254.199:9000\", \"10.240.62.150:9000\"] // } //] //} package config import ( \"bytes\" \"encoding/json\" \"fmt\" \"io/ioutil\" \"reflect\" \"time\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/golang/glog\" ) // serviceConfig is a deserialized form of the config file format which ConfigSourceFile accepts. // TODO: this is apparently untested; is it used? type serviceConfig struct { Services []struct { Name string `json: \"name\"` Port int `json: \"port\"` Endpoints []string `json: \"endpoints\"` } `json:\"service\"` } // ConfigSourceFile periodically reads service configurations in JSON from a file, and sends the services and endpoints defined in the file to the specified channels. type ConfigSourceFile struct { serviceChannel chan ServiceUpdate endpointsChannel chan EndpointsUpdate filename string } // NewConfigSourceFile creates a new ConfigSourceFile and let it immediately runs the created ConfigSourceFile in a goroutine. func NewConfigSourceFile(filename string, serviceChannel chan ServiceUpdate, endpointsChannel chan EndpointsUpdate) ConfigSourceFile { config := ConfigSourceFile{ filename: filename, serviceChannel: serviceChannel, endpointsChannel: endpointsChannel, } go config.Run() return config } // Run begins watching the config file. func (s ConfigSourceFile) Run() { glog.V(1).Infof(\"Watching file %s\", s.filename) var lastData []byte var lastServices []api.Service var lastEndpoints []api.Endpoints sleep := 5 * time.Second // Used to avoid spamming the error log file, makes error logging edge triggered. hadSuccess := true for { data, err := ioutil.ReadFile(s.filename) if err != nil { msg := fmt.Sprintf(\"Couldn't read file: %s : %v\", s.filename, err) if hadSuccess { glog.Error(msg) } else { glog.V(1).Info(msg) } hadSuccess = false time.Sleep(sleep) continue } hadSuccess = true if bytes.Equal(lastData, data) { time.Sleep(sleep) continue } lastData = data config := &serviceConfig{} if err = json.Unmarshal(data, config); err != nil { glog.Errorf(\"Couldn't unmarshal configuration from file : %s %v\", data, err) continue } // Ok, we have a valid configuration, send to channel for // rejiggering. newServices := make([]api.Service, len(config.Services)) newEndpoints := make([]api.Endpoints, len(config.Services)) for i, service := range config.Services { newServices[i] = api.Service{TypeMeta: api.TypeMeta{ID: service.Name}, Port: service.Port} newEndpoints[i] = api.Endpoints{TypeMeta: api.TypeMeta{ID: service.Name}, Endpoints: service.Endpoints} } if !reflect.DeepEqual(lastServices, newServices) { serviceUpdate := ServiceUpdate{Op: SET, Services: newServices} s.serviceChannel <- serviceUpdate lastServices = newServices } if !reflect.DeepEqual(lastEndpoints, newEndpoints) { endpointsUpdate := EndpointsUpdate{Op: SET, Endpoints: newEndpoints} s.endpointsChannel <- endpointsUpdate lastEndpoints = newEndpoints } time.Sleep(sleep) } } "} {"_id":"doc-en-kubernetes-082e7d35941be3e789d491496de3cc2d3041fad7b5e8ac402cd9dd1071c07661","title":"","text":"## Protocols for Collaborative Development Please read [this doc](docs/collab.md) for information on how we're running development for the project. Please read [this doc](docs/devel/collab.md) for information on how we're running development for the project. ## Adding dependencies"} {"_id":"doc-en-kubernetes-718671d140b86ebf5b93a6194596b0324f233352f6657a5cad794f27a1ec1d0d","title":"","text":"* [Example of dynamic updates](examples/update-demo/README.md) * [Cluster monitoring with heapster and cAdvisor](https://github.com/GoogleCloudPlatform/heapster) * [Community projects](https://github.com/GoogleCloudPlatform/kubernetes/wiki/Kubernetes-Community) * [Development guide](docs/development.md) * [Development guide](docs/devel/development.md) Or fork and start hacking!"} {"_id":"doc-en-kubernetes-56dbcbda8b317d88bda99208dd165d87b0e0d280727a2a0e75bb7a199e4b2ab7","title":"","text":" # On Collaborative Development Kubernetes is open source, but many of the people working on it do so as their day job. In order to avoid forcing people to be \"at work\" effectively 24/7, we want to establish some semi-formal protocols around development. Hopefully these rules make things go more smoothly. If you find that this is not the case, please complain loudly. ## Patches welcome First and foremost: as a potential contributor, your changes and ideas are welcome at any hour of the day or night, weekdays, weekends, and holidays. Please do not ever hesitate to ask a question or send a PR. ## Timezones and calendars For the time being, most of the people working on this project are in the US and on Pacific time. Any times mentioned henceforth will refer to this timezone. Any references to \"work days\" will refer to the US calendar. ## Code reviews All changes must be code reviewed. For non-maintainers this is obvious, since you can't commit anyway. But even for maintainers, we want all changes to get at least one review, preferably from someone who knows the areas the change touches. For non-trivial changes we may want two reviewers. The primary reviewer will make this decision and nominate a second reviewer, if needed. Except for trivial changes, PRs should sit for at least a 2 hours to allow for wider review. Most PRs will find reviewers organically. If a maintainer intends to be the primary reviewer of a PR they should set themselves as the assignee on GitHub and say so in a reply to the PR. Only the primary reviewer of a change should actually do the merge, except in rare cases (e.g. they are unavailable in a reasonable timeframe). If a PR has gone 2 work days without an owner emerging, please poke the PR thread and ask for a reviewer to be assigned. Except for rare cases, such as trivial changes (e.g. typos, comments) or emergencies (e.g. broken builds), maintainers should not merge their own changes. Expect reviewers to request that you avoid [common go style mistakes](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) in your PRs. ## Assigned reviews Maintainers can assign reviews to other maintainers, when appropriate. The assignee becomes the shepherd for that PR and is responsible for merging the PR once they are satisfied with it or else closing it. The assignee might request reviews from non-maintainers. ## Merge hours Maintainers will do merges between the hours of 7:00 am Monday and 7:00 pm (19:00h) Friday. PRs that arrive over the weekend or on holidays will only be merged if there is a very good reason for it and if the code review requirements have been met. There may be discussion an even approvals granted outside of the above hours, but merges will generally be deferred. ## Holds Any maintainer or core contributor who wants to review a PR but does not have time immediately may put a hold on a PR simply by saying so on the PR discussion and offering an ETA measured in single-digit days at most. Any PR that has a hold shall not be merged until the person who requested the hold acks the review, withdraws their hold, or is overruled by a preponderance of maintainers. "} {"_id":"doc-en-kubernetes-36cea03b6c0d18b42b316d857d137b1e6afbce0320660f7682c4e5fa621a10b0","title":"","text":" # Development Guide # Releases and Official Builds Official releases are built in Docker containers. Details are [here](build/README.md). You can do simple builds and development with just a local Docker installation. If want to build go locally outside of docker, please continue below. ## Go development environment Kubernetes is written in [Go](http://golang.org) programming language. If you haven't set up Go development environment, please follow [this instruction](http://golang.org/doc/code.html) to install go tool and set up GOPATH. Ensure your version of Go is at least 1.3. ## Put kubernetes into GOPATH We highly recommend to put kubernetes' code into your GOPATH. For example, the following commands will download kubernetes' code under the current user's GOPATH (Assuming there's only one directory in GOPATH.): ``` $ echo $GOPATH /home/user/goproj $ mkdir -p $GOPATH/src/github.com/GoogleCloudPlatform/ $ cd $GOPATH/src/github.com/GoogleCloudPlatform/ $ git clone git@github.com:GoogleCloudPlatform/kubernetes.git ``` The commands above will not work if there are more than one directory in ``$GOPATH``. (Obviously, clone your own fork of Kubernetes if you plan to do development.) ## godep and dependency management Kubernetes uses [godep](https://github.com/tools/godep) to manage dependencies. It is not strictly required for building Kubernetes but it is required when managing dependencies under the Godeps/ tree, and is required by a number of the build and test scripts. Please make sure that ``godep`` is installed and in your ``$PATH``. ### Installing godep There are many ways to build and host go binaries. Here is an easy way to get utilities like ```godep``` installed: 1. Ensure that [mercurial](http://mercurial.selenic.com/wiki/Download) is installed on your system. (some of godep's dependencies use the mercurial source control system). Use ```apt-get install mercurial``` or ```yum install mercurial``` on Linux, or [brew.sh](http://brew.sh) on OS X, or download directly from mercurial. 2. Create a new GOPATH for your tools and install godep: ``` export GOPATH=$HOME/go-tools mkdir -p $GOPATH go get github.com/tools/godep ``` 3. Add $GOPATH/bin to your path. Typically you'd add this to your ~/.profile: ``` export GOPATH=$HOME/go-tools export PATH=$PATH:$GOPATH/bin ``` ### Using godep Here is a quick summary of `godep`. `godep` helps manage third party dependencies by copying known versions into Godeps/_workspace. You can use `godep` in three ways: 1. Use `godep` to call your `go` commands. For example: `godep go test ./...` 2. Use `godep` to modify your `$GOPATH` so that other tools know where to find the dependencies. Specifically: `export GOPATH=$GOPATH:$(godep path)` 3. Use `godep` to copy the saved versions of packages into your `$GOPATH`. This is done with `godep restore`. We recommend using options #1 or #2. ## Hooks Before committing any changes, please link/copy these hooks into your .git directory. This will keep you from accidentally committing non-gofmt'd go code. ``` cd kubernetes ln -s hooks/prepare-commit-msg .git/hooks/prepare-commit-msg ln -s hooks/commit-msg .git/hooks/commit-msg ``` ## Unit tests ``` cd kubernetes hack/test-go.sh ``` Alternatively, you could also run: ``` cd kubernetes godep go test ./... ``` If you only want to run unit tests in one package, you could run ``godep go test`` under the package directory. For example, the following commands will run all unit tests in package kubelet: ``` $ cd kubernetes # step into kubernetes' directory. $ cd pkg/kubelet $ godep go test # some output from unit tests PASS ok github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet 0.317s ``` ## Coverage ``` cd kubernetes godep go tool cover -html=target/c.out ``` ## Integration tests You need an etcd somewhere in your PATH. To install etcd, run: ``` cd kubernetes hack/install-etcd.sh sudo ln -s $(pwd)/third_party/etcd/bin/etcd /usr/bin/etcd ``` ``` cd kubernetes hack/test-integration.sh ``` ## End-to-End tests You can run an end-to-end test which will bring up a master and two minions, perform some tests, and then tear everything down. Make sure you have followed the getting started steps for your chosen cloud platform (which might involve changing the `KUBERNETES_PROVIDER` environment variable to something other than \"gce\". ``` cd kubernetes hack/e2e-test.sh ``` Pressing control-C should result in an orderly shutdown but if something goes wrong and you still have some VMs running you can force a cleanup with the magical incantation: ``` hack/e2e-test.sh 1 1 1 ``` ## Testing out flaky tests [Instructions here](docs/devel/flaky-tests.md) ## Add/Update dependencies Kubernetes uses [godep](https://github.com/tools/godep) to manage dependencies. To add or update a package, please follow the instructions on [godep's document](https://github.com/tools/godep). To add a new package ``foo/bar``: - Make sure the kubernetes' root directory is in $GOPATH/github.com/GoogleCloudPlatform/kubernetes - Run ``godep restore`` to make sure you have all dependancies pulled. - Download foo/bar into the first directory in GOPATH: ``go get foo/bar``. - Change code in kubernetes to use ``foo/bar``. - Run ``godep save ./...`` under kubernetes' root directory. To update a package ``foo/bar``: - Make sure the kubernetes' root directory is in $GOPATH/github.com/GoogleCloudPlatform/kubernetes - Run ``godep restore`` to make sure you have all dependancies pulled. - Update the package with ``go get -u foo/bar``. - Change code in kubernetes accordingly if necessary. - Run ``godep update foo/bar`` under kubernetes' root directory. ## Keeping your development fork in sync One time after cloning your forked repo: ``` git remote add upstream https://github.com/GoogleCloudPlatform/kubernetes.git ``` Then each time you want to sync to upstream: ``` git fetch upstream git rebase upstream/master ``` ## Regenerating the API documentation ``` cd kubernetes/api sudo docker build -t kubernetes/raml2html . sudo docker run --name=\"docgen\" kubernetes/raml2html sudo docker cp docgen:/data/kubernetes.html . ``` View the API documentation using htmlpreview (works on your fork, too): ``` http://htmlpreview.github.io/?https://github.com/GoogleCloudPlatform/kubernetes/blob/master/api/kubernetes.html ``` "} {"_id":"doc-en-kubernetes-ac58de09aeb1517c34a337428ccefa0e0c3ce7872bd3cbb562323271dca9baef","title":"","text":" # Hunting flaky tests in Kubernetes Sometimes unit tests are flaky. This means that due to (usually) race conditions, they will occasionally fail, even though most of the time they pass. We have a goal of 99.9% flake free tests. This means that there is only one flake in one thousand runs of a test. Running a test 1000 times on your own machine can be tedious and time consuming. Fortunately, there is a better way to achieve this using Kubernetes. _Note: these instructions are mildly hacky for now, as we get run once semantics and logging they will get better_ There is a testing image ```brendanburns/flake``` up on the docker hub. We will use this image to test our fix. Create a replication controller with the following config: ```yaml id: flakeController desiredState: replicas: 24 replicaSelector: name: flake podTemplate: desiredState: manifest: version: v1beta1 id: \"\" volumes: [] containers: - name: flake image: brendanburns/flake env: - name: TEST_PACKAGE value: pkg/tools - name: REPO_SPEC value: https://github.com/GoogleCloudPlatform/kubernetes restartpolicy: {} labels: name: flake labels: name: flake ``` ```./cluster/kubecfg.sh -c controller.yaml create replicaControllers``` This will spin up 100 instances of the test. They will run to completion, then exit, the kubelet will restart them, eventually you will have sufficient runs for your purposes, and you can stop the replication controller: ```sh ./cluster/kubecfg.sh stop flakeController ./cluster/kubecfg.sh rm flakeController ``` Now examine the machines with ```docker ps -a``` and look for tasks that exited with non-zero exit codes (ignore those that exited -1, since that's what happens when you stop the replica controller) Happy flake hunting! "} {"_id":"doc-en-kubernetes-f73ac31aad0d03fcbc40548d97e3710f76602dd53a791335b19ad6cd6a910673","title":"","text":" // Build it with: // $ dot -Tsvg releasing.dot >releasing.svg digraph tagged_release { size = \"5,5\" // Arrows go up. rankdir = BT subgraph left { // Group the left nodes together. ci012abc -> pr101 -> ci345cde -> pr102 style = invis } subgraph right { // Group the right nodes together. version_commit -> dev_commit style = invis } { // Align the version commit and the info about it. rank = same // Align them with pr101 pr101 version_commit // release_info shows the change in the commit. release_info } { // Align the dev commit and the info about it. rank = same // Align them with 345cde ci345cde dev_commit dev_info } // Join the nodes from subgraph left. pr99 -> ci012abc pr102 -> pr100 // Do the version node. pr99 -> version_commit dev_commit -> pr100 tag -> version_commit pr99 [ label = \"Merge PR #99\" shape = box fillcolor = \"#ccccff\" style = \"filled\" fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; ci012abc [ label = \"012abc\" shape = circle fillcolor = \"#ffffcc\" style = \"filled\" fontname = \"Consolas, Liberation Mono, Menlo, Courier, monospace\" ]; pr101 [ label = \"Merge PR #101\" shape = box fillcolor = \"#ccccff\" style = \"filled\" fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; ci345cde [ label = \"345cde\" shape = circle fillcolor = \"#ffffcc\" style = \"filled\" fontname = \"Consolas, Liberation Mono, Menlo, Courier, monospace\" ]; pr102 [ label = \"Merge PR #102\" shape = box fillcolor = \"#ccccff\" style = \"filled\" fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; version_commit [ label = \"678fed\" shape = circle fillcolor = \"#ccffcc\" style = \"filled\" fontname = \"Consolas, Liberation Mono, Menlo, Courier, monospace\" ]; dev_commit [ label = \"456dcb\" shape = circle fillcolor = \"#ffffcc\" style = \"filled\" fontname = \"Consolas, Liberation Mono, Menlo, Courier, monospace\" ]; pr100 [ label = \"Merge PR #100\" shape = box fillcolor = \"#ccccff\" style = \"filled\" fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; release_info [ label = \"pkg/version/base.go:ngitVersion = \"v0.5\";\" shape = none fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; dev_info [ label = \"pkg/version/base.go:ngitVersion = \"v0.5-dev\";\" shape = none fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; tag [ label = \"$ git tag -a v0.5\" fillcolor = \"#ffcccc\" style = \"filled\" fontname = \"Helvetica Neue, Helvetica, Segoe UI, Arial, freesans, sans-serif\" ]; } "} {"_id":"doc-en-kubernetes-143abc9f10f3a4e58d6b55563595a05b8eefd676d1b1d179c58a7380dee60f22","title":"","text":" # Releasing Kubernetes This document explains how to create a Kubernetes release (as in version) and how the version information gets embedded into the built binaries. ## Origin of the Sources Kubernetes may be built from either a git tree (using `hack/build-go.sh`) or from a tarball (using either `hack/build-go.sh` or `go install`) or directly by the Go native build system (using `go get`). When building from git, we want to be able to insert specific information about the build tree at build time. In particular, we want to use the output of `git describe` to generate the version of Kubernetes and the status of the build tree (add a `-dirty` prefix if the tree was modified.) When building from a tarball or using the Go build system, we will not have access to the information about the git tree, but we still want to be able to tell whether this build corresponds to an exact release (e.g. v0.3) or is between releases (e.g. at some point in development between v0.3 and v0.4). ## Version Number Format In order to account for these use cases, there are some specific formats that may end up representing the Kubernetes version. Here are a few examples: - **v0.5**: This is official version 0.5 and this version will only be used when building from a clean git tree at the v0.5 git tag, or from a tree extracted from the tarball corresponding to that specific release. - **v0.5-15-g0123abcd4567**: This is the `git describe` output and it indicates that we are 15 commits past the v0.5 release and that the SHA1 of the commit where the binaries were built was `0123abcd4567`. It is only possible to have this level of detail in the version information when building from git, not when building from a tarball. - **v0.5-15-g0123abcd4567-dirty** or **v0.5-dirty**: The extra `-dirty` prefix means that the tree had local modifications or untracked files at the time of the build, so there's no guarantee that the source code matches exactly the state of the tree at the `0123abcd4567` commit or at the `v0.5` git tag (resp.) - **v0.5-dev**: This means we are building from a tarball or using `go get` or, if we have a git tree, we are using `go install` directly, so it is not possible to inject the git version into the build information. Additionally, this is not an official release, so the `-dev` prefix indicates that the version we are building is after `v0.5` but before `v0.6`. (There is actually an exception where a commit with `v0.5-dev` is not present on `v0.6`, see later for details.) ## Injecting Version into Binaries In order to cover the different build cases, we start by providing information that can be used when using only Go build tools or when we do not have the git version information available. To be able to provide a meaningful version in those cases, we set the contents of variables in a Go source file that will be used when no overrides are present. We are using `pkg/version/base.go` as the source of versioning in absence of information from git. Here is a sample of that file's contents: ``` var ( gitVersion string = \"v0.4-dev\" // version from git, output of $(git describe) gitCommit string = \"\" // sha1 from git, output of $(git rev-parse HEAD) ) ``` This means a build with `go install` or `go get` or a build from a tarball will yield binaries that will identify themselves as `v0.4-dev` and will not be able to provide you with a SHA1. To add the extra versioning information when building from git, the `hack/build-go.sh` script will gather that information (using `git describe` and `git rev-parse`) and then create a `-ldflags` string to pass to `go install` and tell the Go linker to override the contents of those variables at build time. It can, for instance, tell it to override `gitVersion` and set it to `v0.4-13-g4567bcdef6789-dirty` and set `gitCommit` to `4567bcdef6789...` which is the complete SHA1 of the (dirty) tree used at build time. ## Handling Official Versions Handling official versions from git is easy, as long as there is an annotated git tag pointing to a specific version then `git describe` will return that tag exactly which will match the idea of an official version (e.g. `v0.5`). Handling it on tarballs is a bit harder since the exact version string must be present in `pkg/version/base.go` for it to get embedded into the binaries. But simply creating a commit with `v0.5` on its own would mean that the commits coming after it would also get the `v0.5` version when built from tarball or `go get` while in fact they do not match `v0.5` (the one that was tagged) exactly. To handle that case, creating a new release should involve creating two adjacent commits where the first of them will set the version to `v0.5` and the second will set it to `v0.5-dev`. In that case, even in the presence of merges, there will be a single comit where the exact `v0.5` version will be used and all others around it will either have `v0.4-dev` or `v0.5-dev`. The diagram below illustrates it. ![Diagram of git commits involved in the release](./releasing.png) After working on `v0.4-dev` and merging PR 99 we decide it is time to release `v0.5`. So we start a new branch, create one commit to update `pkg/version/base.go` to include `gitVersion = \"v0.5\"` and `git commit` it. We test it and make sure everything is working as expected. Before sending a PR for it, we create a second commit on that same branch, updating `pkg/version/base.go` to include `gitVersion = \"v0.5-dev\"`. That will ensure that further builds (from tarball or `go install`) on that tree will always include the `-dev` prefix and will not have a `v0.5` version (since they do not match the official `v0.5` exactly.) We then send PR 100 with both commits in it. Once the PR is accepted, we can use `git tag -a` to create an annotated tag *pointing to the one commit* that has `v0.5` in `pkg/version/base.go` and push it to GitHub. (Unfortunately GitHub tags/releases are not annotated tags, so this needs to be done from a git client and pushed to GitHub using SSH.) ## Parallel Commits While we are working on releasing `v0.5`, other development takes place and other PRs get merged. For instance, in the example above, PRs 101 and 102 get merged to the master branch before the versioning PR gets merged. This is not a problem, it is only slightly inaccurate that checking out the tree at commit `012abc` or commit `345cde` or at the commit of the merges of PR 101 or 102 will yield a version of `v0.4-dev` *but* those commits are not present in `v0.5`. In that sense, there is a small window in which commits will get a `v0.4-dev` or `v0.4-N-gXXX` label and while they're indeed later than `v0.4` but they are not really before `v0.5` in that `v0.5` does not contain those commits. Unfortunately, there is not much we can do about it. On the other hand, other projects seem to live with that and it does not really become a large problem. As an example, Docker commit a327d9b91edf has a `v1.1.1-N-gXXX` label but it is not present in Docker `v1.2.0`: ``` $ git describe a327d9b91edf v1.1.1-822-ga327d9b91edf $ git log --oneline v1.2.0..a327d9b91edf a327d9b91edf Fix data space reporting from Kb/Mb to KB/MB (Non-empty output here means the commit is not present on v1.2.0.) ``` "} {"_id":"doc-en-kubernetes-a6230681f6cd44905810676af4cf1a61b3e1fb0fc64d64f6d4a8f2a8818d0c5f","title":"","text":" tagged_release ci012abc 012abc pr101 Merge PR #101 ci012abc->pr101 ci345cde 345cde pr101->ci345cde pr102 Merge PR #102 ci345cde->pr102 pr100 Merge PR #100 pr102->pr100 version_commit 678fed dev_commit 456dcb version_commit->dev_commit dev_commit->pr100 release_info pkg/version/base.go: gitVersion = "v0.5"; dev_info pkg/version/base.go: gitVersion = "v0.5-dev"; pr99 Merge PR #99 pr99->ci012abc pr99->version_commit tag $ git tag -a v0.5 tag->version_commit "} {"_id":"doc-en-kubernetes-d0b2a1694e137a25f0c9d773183746b4cbbfdc14bd5ba535205288f1c6c3991e","title":"","text":" # Maintainers Eric Paris "} {"_id":"doc-en-kubernetes-a70238982f99fadc61e7ce926d51d6c8b6faa8bfc5da0332d4165249799ad153","title":"","text":" #!bash # # bash completion file for core kubecfg commands # # This script provides completion of non replication controller options # # To enable the completions either: # - place this file in /etc/bash_completion.d # or # - copy this file and add the line below to your .bashrc after # bash completion features are loaded # . kubecfg # # Note: # Currently, the completions will not work if the apiserver daemon is not # running on localhost on the standard port 8080 __contains_word () { local w word=$1; shift for w in \"$@\"; do [[ $w = \"$word\" ]] && return done return 1 } # This should be provided by the bash-completions, but give a really simple # stoopid version just in case. It works most of the time. if ! declare -F _get_comp_words_by_ref >/dev/null 2>&1; then _get_comp_words_by_ref () { while [ $# -gt 0 ]; do case \"$1\" in cur) cur=${COMP_WORDS[COMP_CWORD]} ;; prev) prev=${COMP_WORDS[COMP_CWORD-1]} ;; words) words=(\"${COMP_WORDS[@]}\") ;; cword) cword=$COMP_CWORD ;; -n) shift # we don't handle excludes ;; esac shift done } fi __has_service() { local i for ((i=0; i < cword; i++)); do local word=${words[i]} # strip everything after a / so things like pods/[id] match word=${word%%/*} if __contains_word \"${word}\" \"${services[@]}\" && ! __contains_word \"${words[i-1]}\" \"${opts[@]}\"; then return 0 fi done return 1 } # call kubecfg list $1, # exclude blank lines # skip the header stuff kubecfg prints on the first 2 lines # append $1/ to the first column and use that in compgen __kubecfg_parse_list() { local kubecfg_output if kubecfg_output=$(kubecfg list \"$1\" 2>/dev/null); then out=($(echo \"${kubecfg_output}\" | awk -v prefix=\"$1\" '/^$/ {next} NR > 2 {print prefix\"/\"$1}')) COMPREPLY=( $( compgen -W \"${out[*]}\" -- \"$cur\" ) ) fi } _kubecfg_specific_service_match() { case \"$cur\" in pods/*) __kubecfg_parse_list pods ;; minions/*) __kubecfg_parse_list minions ;; replicationControllers/*) __kubecfg_parse_list replicationControllers ;; services/*) __kubecfg_parse_list services ;; *) if __has_service; then return 0 fi compopt -o nospace COMPREPLY=( $( compgen -S / -W \"${services[*]}\" -- \"$cur\" ) ) ;; esac } _kubecfg_service_match() { if __has_service; then return 0 fi COMPREPLY=( $( compgen -W \"${services[*]}\" -- \"$cur\" ) ) } _kubecfg() { local opts=( -h -c ) local create_services=(pods replicationControllers services) local update_services=(replicationControllers) local all_services=(pods replicationControllers services minions) local services=(\"${all_services[@]}\") local json_commands=(create update) local all_commands=(create update get list delete stop rm rollingupdate resize) local commands=(\"${all_commands[@]}\") COMPREPLY=() local command local cur prev words cword _get_comp_words_by_ref -n : cur prev words cword if __contains_word \"$prev\" \"${opts[@]}\"; then case $prev in -c) _filedir '@(json|yml|yaml)' return 0 ;; -h) return 0 ;; esac fi if [[ \"$cur\" = -* ]]; then COMPREPLY=( $(compgen -W \"${opts[*]}\" -- \"$cur\") ) return 0 fi # if you passed -c, you are limited to create or update if __contains_word \"-c\" \"${words[@]}\"; then services=(\"${create_services[@]}\" \"${update_services[@]}\") commands=(\"${json_commands[@]}\") fi # figure out which command they are running, remembering that arguments to # options don't count as the command! So a hostname named 'create' won't # trip things up local i for ((i=0; i < cword; i++)); do if __contains_word \"${words[i]}\" \"${commands[@]}\" && ! __contains_word \"${words[i-1]}\" \"${opts[@]}\"; then command=${words[i]} break fi done # tell the list of possible commands if [[ -z ${command} ]]; then COMPREPLY=( $( compgen -W \"${commands[*]}\" -- \"$cur\" ) ) return 0 fi # remove services which you can't update given your command if [[ ${command} == \"create\" ]]; then services=(\"${create_services[@]}\") elif [[ ${command} == \"update\" ]]; then services=(\"${update_services[@]}\") fi case $command in create | list) _kubecfg_service_match ;; update | get | delete) _kubecfg_specific_service_match ;; *) ;; esac return 0 } complete -F _kubecfg kubecfg # ex: ts=4 sw=4 et filetype=sh "} {"_id":"doc-en-kubernetes-3b11a81468f6a5ac23a5c5152bea0f7aaadbb57189a6cd5f4abeb0c3a33cdcd4","title":"","text":" #!bash # # bash completion file for core kubecfg commands # # This script provides completion of non replication controller options # # To enable the completions either: # - place this file in /etc/bash_completion.d # or # - copy this file and add the line below to your .bashrc after # bash completion features are loaded # . kubecfg # # Note: # Currently, the completions will not work if the apiserver daemon is not # running on localhost on the standard port 8080 __contains_word () { local w word=$1; shift for w in \"$@\"; do [[ $w = \"$word\" ]] && return done return 1 } # This should be provided by the bash-completions, but give a really simple # stoopid version just in case. It works most of the time. if ! declare -F _get_comp_words_by_ref >/dev/null 2>&1; then _get_comp_words_by_ref () { while [ $# -gt 0 ]; do case \"$1\" in cur) cur=${COMP_WORDS[COMP_CWORD]} ;; prev) prev=${COMP_WORDS[COMP_CWORD-1]} ;; words) words=(\"${COMP_WORDS[@]}\") ;; cword) cword=$COMP_CWORD ;; -n) shift # we don't handle excludes ;; esac shift done } fi __has_service() { local i for ((i=0; i < cword; i++)); do local word=${words[i]} # strip everything after a / so things like pods/[id] match word=${word%%/*} if __contains_word \"${word}\" \"${services[@]}\" && ! __contains_word \"${words[i-1]}\" \"${opts[@]}\"; then return 0 fi done return 1 } # call kubecfg list $1, # exclude blank lines # skip the header stuff kubecfg prints on the first 2 lines # append $1/ to the first column and use that in compgen __kubecfg_parse_list() { local kubecfg_output if kubecfg_output=$(kubecfg list \"$1\" 2>/dev/null); then out=($(echo \"${kubecfg_output}\" | awk -v prefix=\"$1\" '/^$/ {next} NR > 2 {print prefix\"/\"$1}')) COMPREPLY=( $( compgen -W \"${out[*]}\" -- \"$cur\" ) ) fi } _kubecfg_specific_service_match() { case \"$cur\" in pods/*) __kubecfg_parse_list pods ;; minions/*) __kubecfg_parse_list minions ;; replicationControllers/*) __kubecfg_parse_list replicationControllers ;; services/*) __kubecfg_parse_list services ;; *) if __has_service; then return 0 fi compopt -o nospace COMPREPLY=( $( compgen -S / -W \"${services[*]}\" -- \"$cur\" ) ) ;; esac } _kubecfg_service_match() { if __has_service; then return 0 fi COMPREPLY=( $( compgen -W \"${services[*]}\" -- \"$cur\" ) ) } _kubecfg() { local opts=( -h -c ) local create_services=(pods replicationControllers services) local update_services=(replicationControllers) local all_services=(pods replicationControllers services minions) local services=(\"${all_services[@]}\") local json_commands=(create update) local all_commands=(create update get list delete stop rm rollingupdate resize) local commands=(\"${all_commands[@]}\") COMPREPLY=() local command local cur prev words cword _get_comp_words_by_ref -n : cur prev words cword if __contains_word \"$prev\" \"${opts[@]}\"; then case $prev in -c) _filedir '@(json|yml|yaml)' return 0 ;; -h) return 0 ;; esac fi if [[ \"$cur\" = -* ]]; then COMPREPLY=( $(compgen -W \"${opts[*]}\" -- \"$cur\") ) return 0 fi # if you passed -c, you are limited to create or update if __contains_word \"-c\" \"${words[@]}\"; then services=(\"${create_services[@]}\" \"${update_services[@]}\") commands=(\"${json_commands[@]}\") fi # figure out which command they are running, remembering that arguments to # options don't count as the command! So a hostname named 'create' won't # trip things up local i for ((i=0; i < cword; i++)); do if __contains_word \"${words[i]}\" \"${commands[@]}\" && ! __contains_word \"${words[i-1]}\" \"${opts[@]}\"; then command=${words[i]} break fi done # tell the list of possible commands if [[ -z ${command} ]]; then COMPREPLY=( $( compgen -W \"${commands[*]}\" -- \"$cur\" ) ) return 0 fi # remove services which you can't update given your command if [[ ${command} == \"create\" ]]; then services=(\"${create_services[@]}\") elif [[ ${command} == \"update\" ]]; then services=(\"${update_services[@]}\") fi case $command in create | list) _kubecfg_service_match ;; update | get | delete) _kubecfg_specific_service_match ;; *) ;; esac return 0 } complete -F _kubecfg kubecfg # ex: ts=4 sw=4 et filetype=sh "} {"_id":"doc-en-kubernetes-f77dc625a01728214cea9d9fd1d87723bc5b4c785e95afa6e9dca23922dec180","title":"","text":"{% set auth_path = \"-auth_path=/var/lib/kubelet/kubernetes_auth\" -%} {% set registry_qps = \"-registry_qps=0.1\" %} DAEMON_ARGS=\"{{daemon_args}} {{etcd_servers}} {{apiservers}} {{auth_path}} {{hostname_override}} {{address}} {{config}} --allow_privileged={{pillar['allow_privileged']}}\""} {"_id":"doc-en-kubernetes-55ad420d6563fedd0c63cab2bafb6841e198176a2e339ef3148c7d799aad4500","title":"","text":"// TODO: get the real minion object of ourself, // and use the real minion name and UID. ref := &api.ObjectReference{ Kind: \"Minion\", Name: kl.hostname, UID: kl.hostname, Kind: \"Minion\", Name: kl.hostname, UID: kl.hostname, Namespace: api.NamespaceDefault, } record.Eventf(ref, \"\", \"starting\", \"Starting kubelet.\") }"} {"_id":"doc-en-kubernetes-517d53c3009a525b41232b9601ffacb3dc61fc22dcc9b53c518b178e5c14964e","title":"","text":"if !util.IsQualifiedName(strings.ToLower(k)) { allErrs = append(allErrs, errs.NewFieldInvalid(field, k, qualifiedNameErrorMsg)) } if !util.IsValidAnnotationValue(v) { allErrs = append(allErrs, errs.NewFieldInvalid(field, k, \"\")) } totalSize += (int64)(len(k)) + (int64)(len(v)) } if totalSize > (int64)(totalAnnotationSizeLimitB) { allErrs = append(allErrs, errs.NewFieldTooLong(\"annotations\", \"\")) allErrs = append(allErrs, errs.NewFieldTooLong(field, \"\", totalAnnotationSizeLimitB)) } return allErrs }"} {"_id":"doc-en-kubernetes-1b2ac816d4dc23e2d4f2431df4ed7a285abf0bb44114aa941a8b8857f23237c6","title":"","text":"func (v *ValidationError) Error() string { var s string switch v.Type { case ValidationErrorTypeRequired: case ValidationErrorTypeRequired, ValidationErrorTypeTooLong: s = spew.Sprintf(\"%s: %s\", v.Field, v.Type) default: s = spew.Sprintf(\"%s: %s '%+v'\", v.Field, v.Type, v.BadValue)"} {"_id":"doc-en-kubernetes-76434e67b55356557767506e655a59f3b90fe0b2e032527f55efe25497a34359","title":"","text":"return &ValidationError{ValidationErrorTypeNotFound, field, value, \"\"} } func NewFieldTooLong(field string, value interface{}) *ValidationError { return &ValidationError{ValidationErrorTypeTooLong, field, value, \"\"} func NewFieldTooLong(field string, value interface{}, maxLength int) *ValidationError { return &ValidationError{ValidationErrorTypeTooLong, field, value, fmt.Sprintf(\"must have at most %d characters\", maxLength)} } type ValidationErrorList []error"} {"_id":"doc-en-kubernetes-06a5ff00c381f4b5ad8ee5c690b3e991963b61b3814a0ed102bf6e8855e81ef5","title":"","text":"return (len(value) <= LabelValueMaxLength && labelValueRegexp.MatchString(value)) } // Annotation values are opaque. func IsValidAnnotationValue(value string) bool { return true } const QualifiedNameFmt string = \"(\" + qnameTokenFmt + \"/)?\" + qnameTokenFmt const QualifiedNameMaxLength int = 253"} {"_id":"doc-en-kubernetes-8fa55f773d3b6b9b929b83603879ded95a64212e8a79b27aee34e7708749588b","title":"","text":"} pod.Spec.Containers = newContainers if !api.Semantic.DeepEqual(pod.Spec, oldPod.Spec) { // TODO: a better error would include all immutable fields explicitly. allErrs = append(allErrs, errs.NewFieldInvalid(\"spec.containers\", newPod.Spec.Containers, \"some fields are immutable\")) allErrs = append(allErrs, errs.NewFieldInvalid(\"spec\", newPod.Spec, \"may not update fields other than container.image\")) } newPod.Status = oldPod.Status"} {"_id":"doc-en-kubernetes-7e63074f5269f2743d38897873f80902a5baf7405f17ef2b0bb13f5c378d3df3","title":"","text":"if err != nil { glog.Errorf(\"Unable to get pod with name %q and uid %q info, health checks may be invalid\", podFullName, uid) } netInfo, found := podStatus.Info[dockertools.PodInfraContainerName] if found { podStatus.PodIP = netInfo.PodIP } for _, container := range pod.Spec.Containers { expectedHash := dockertools.HashContainer(&container)"} {"_id":"doc-en-kubernetes-54c3e835289ab4f3ac9b277f70cfc4fce3fbd68f2be310758c8360bc14d8cdf5","title":"","text":"return nil, false } // getPhase returns the phase of a pod given its container info. func getPhase(spec *api.PodSpec, info api.PodInfo) api.PodPhase { if info == nil { return api.PodPending } running := 0 waiting := 0 stopped := 0 failed := 0 succeeded := 0 unknown := 0 for _, container := range spec.Containers { if containerStatus, ok := info[container.Name]; ok { if containerStatus.State.Running != nil { running++ } else if containerStatus.State.Termination != nil { stopped++ if containerStatus.State.Termination.ExitCode == 0 { succeeded++ } else { failed++ } } else if containerStatus.State.Waiting != nil { waiting++ } else { unknown++ } } else { unknown++ } } switch { case waiting > 0: // One or more containers has not been started return api.PodPending case running > 0 && unknown == 0: // All containers have been started, and at least // one container is running return api.PodRunning case running == 0 && stopped > 0 && unknown == 0: // All containers are terminated if spec.RestartPolicy.Always != nil { // All containers are in the process of restarting return api.PodRunning } if stopped == succeeded { // RestartPolicy is not Always, and all // containers are terminated in success return api.PodSucceeded } if spec.RestartPolicy.Never != nil { // RestartPolicy is Never, and all containers are // terminated with at least one in failure return api.PodFailed } // RestartPolicy is OnFailure, and at least one in failure // and in the process of restarting return api.PodRunning default: return api.PodPending } } // GetPodStatus returns information from Docker about the containers in a pod func (kl *Kubelet) GetPodStatus(podFullName string, uid types.UID) (api.PodStatus, error) { var manifest api.PodSpec var spec api.PodSpec for _, pod := range kl.pods { if GetPodFullName(&pod) == podFullName { manifest = pod.Spec spec = pod.Spec break } } info, err := dockertools.GetDockerPodInfo(kl.dockerClient, manifest, podFullName, uid) info, err := dockertools.GetDockerPodInfo(kl.dockerClient, spec, podFullName, uid) // TODO(dchen1107): Determine PodPhase here var podStatus api.PodStatus podStatus.Phase = getPhase(&spec, info) netContainerInfo, found := info[dockertools.PodInfraContainerName] if found { podStatus.PodIP = netContainerInfo.PodIP } // TODO(dchen1107): Change Info to list from map podStatus.Info = info return podStatus, err"} {"_id":"doc-en-kubernetes-9a9a6ae74535658161a25a28602ecdef6baead18968850613577a9013de11219","title":"","text":"} } } func TestPodPhaseWithRestartAlways(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{Always: &api.RestartPolicyAlways{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } stoppedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{}, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": stoppedState, \"containerB\": stoppedState, }, Host: \"machine\", }, }, api.PodRunning, \"all stopped with restart always\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": stoppedState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart always\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart always\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } func TestPodPhaseWithRestartNever(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{Never: &api.RestartPolicyNever{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } succeededState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } failedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": succeededState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodSucceeded, \"all succeeded with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": failedState, \"containerB\": failedState, }, Host: \"machine\", }, }, api.PodFailed, \"all failed with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart never\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } func TestPodPhaseWithRestartOnFailure(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{OnFailure: &api.RestartPolicyOnFailure{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } succeededState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } failedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": succeededState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodSucceeded, \"all succeeded with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": failedState, \"containerB\": failedState, }, Host: \"machine\", }, }, api.PodRunning, \"all failed with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart onfailure\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } "} {"_id":"doc-en-kubernetes-36de24b69ec519b506fd9a66eec2c610dcbced6f34af13f61c64b2617e72a3ca","title":"","text":"\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/leaky\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/pod\""} {"_id":"doc-en-kubernetes-09da8c72669ece21951449de9510b58c12eab1ee63e0c9e875b6c0302ea4955b","title":"","text":"newStatus.Phase = api.PodUnknown } else { newStatus.Info = result.Status.Info newStatus.Phase = getPhase(&pod.Spec, newStatus.Info) if netContainerInfo, ok := newStatus.Info[leaky.PodInfraContainerName]; ok { if netContainerInfo.PodIP != \"\" { newStatus.PodIP = netContainerInfo.PodIP } newStatus.PodIP = result.Status.PodIP if newStatus.Info == nil { // There is a small race window that kubelet couldn't // propulated the status yet. This should go away once // we removed boundPods newStatus.Phase = api.PodPending } else { newStatus.Phase = result.Status.Phase } } return newStatus, err"} {"_id":"doc-en-kubernetes-06618979dcf89937d773853cb2b8408fc98f1e215f14b33a7a3438acd9eb169d","title":"","text":"} wg.Wait() } // getPhase returns the phase of a pod given its container info. // TODO(dchen1107): push this all the way down into kubelet. func getPhase(spec *api.PodSpec, info api.PodInfo) api.PodPhase { if info == nil { return api.PodPending } running := 0 waiting := 0 stopped := 0 failed := 0 succeeded := 0 unknown := 0 for _, container := range spec.Containers { if containerStatus, ok := info[container.Name]; ok { if containerStatus.State.Running != nil { running++ } else if containerStatus.State.Termination != nil { stopped++ if containerStatus.State.Termination.ExitCode == 0 { succeeded++ } else { failed++ } } else if containerStatus.State.Waiting != nil { waiting++ } else { unknown++ } } else { unknown++ } } switch { case waiting > 0: // One or more containers has not been started return api.PodPending case running > 0 && unknown == 0: // All containers have been started, and at least // one container is running return api.PodRunning case running == 0 && stopped > 0 && unknown == 0: // All containers are terminated if spec.RestartPolicy.Always != nil { // All containers are in the process of restarting return api.PodRunning } if stopped == succeeded { // RestartPolicy is not Always, and all // containers are terminated in success return api.PodSucceeded } if spec.RestartPolicy.Never != nil { // RestartPolicy is Never, and all containers are // terminated with at least one in failure return api.PodFailed } // RestartPolicy is OnFailure, and at least one in failure // and in the process of restarting return api.PodRunning default: return api.PodPending } } "} {"_id":"doc-en-kubernetes-39ccafab293f28388b6206049c04ee997ba4a2819cde3a0dda1fa8f078d21c8e","title":"","text":"\"reflect\" \"sync\" \"testing\" \"time\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet/leaky\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/registrytest\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/util\" ) type podInfoCall struct {"} {"_id":"doc-en-kubernetes-7326e2a6c8d4e7793cd40cd90f2d0ca60c6a8fb79514ac3dc4b41f83398bfacf","title":"","text":"if status == nil { t.Errorf(\"Unexpected non-status.\") } expected := &api.PodStatus{ Phase: \"Pending\", Host: \"machine\", HostIP: \"1.2.3.5\", Info: api.PodInfo{ \"bar\": api.ContainerStatus{}, }, } if !reflect.DeepEqual(status, expected) { t.Errorf(\"expected:n%#vngot:n%#vn\", expected, status) } } type podCacheTestConfig struct {"} {"_id":"doc-en-kubernetes-04754bae5c499a2b5257bf4be3e211fb7d29df4a340b77fef8b499c9d85c053d","title":"","text":"} } func TestFillPodStatus(t *testing.T) { pod := makePod(api.NamespaceDefault, \"foo\", \"machine\", \"bar\") expectedIP := \"1.2.3.4\" expectedTime, _ := time.Parse(\"2013-Feb-03\", \"2013-Feb-03\") config := podCacheTestConfig{ kubeletContainerInfo: api.PodStatus{ Phase: api.PodPending, Host: \"machine\", HostIP: \"ip of machine\", PodIP: expectedIP, Info: api.PodInfo{ leaky.PodInfraContainerName: { State: api.ContainerState{ Running: &api.ContainerStateRunning{ StartedAt: util.NewTime(expectedTime), }, }, RestartCount: 1, PodIP: expectedIP, }, }, }, nodes: []api.Node{*makeHealthyNode(\"machine\", \"ip of machine\")}, pods: []api.Pod{*pod}, } cache := config.Construct() err := cache.updatePodStatus(&config.pods[0]) if err != nil { t.Fatalf(\"Unexpected error: %+v\", err) } status, err := cache.GetPodStatus(pod.Namespace, pod.Name) if e, a := &config.kubeletContainerInfo, status; !reflect.DeepEqual(e, a) { t.Errorf(\"Expected: %+v, Got %+v\", e, a) } } func TestFillPodInfoNoData(t *testing.T) { pod := makePod(api.NamespaceDefault, \"foo\", \"machine\", \"bar\") expectedIP := \"\""} {"_id":"doc-en-kubernetes-84ec20a9a1c474d5496a5c8caaa421014e5132e3b88c62da6c10a39894c35c64","title":"","text":"} } func TestPodPhaseWithRestartAlways(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{Always: &api.RestartPolicyAlways{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } stoppedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{}, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": stoppedState, \"containerB\": stoppedState, }, Host: \"machine\", }, }, api.PodRunning, \"all stopped with restart always\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": stoppedState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart always\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart always\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } func TestPodPhaseWithRestartNever(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{Never: &api.RestartPolicyNever{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } succeededState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } failedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": succeededState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodSucceeded, \"all succeeded with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": failedState, \"containerB\": failedState, }, Host: \"machine\", }, }, api.PodFailed, \"all failed with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart never\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } func TestPodPhaseWithRestartOnFailure(t *testing.T) { desiredState := api.PodSpec{ Containers: []api.Container{ {Name: \"containerA\"}, {Name: \"containerB\"}, }, RestartPolicy: api.RestartPolicy{OnFailure: &api.RestartPolicyOnFailure{}}, } currentState := api.PodStatus{ Host: \"machine\", } runningState := api.ContainerStatus{ State: api.ContainerState{ Running: &api.ContainerStateRunning{}, }, } succeededState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: 0, }, }, } failedState := api.ContainerStatus{ State: api.ContainerState{ Termination: &api.ContainerStateTerminated{ ExitCode: -1, }, }, } tests := []struct { pod *api.Pod status api.PodPhase test string }{ {&api.Pod{Spec: desiredState, Status: currentState}, api.PodPending, \"waiting\"}, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": runningState, }, Host: \"machine\", }, }, api.PodRunning, \"all running with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": succeededState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodSucceeded, \"all succeeded with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": failedState, \"containerB\": failedState, }, Host: \"machine\", }, }, api.PodRunning, \"all failed with restart never\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, \"containerB\": succeededState, }, Host: \"machine\", }, }, api.PodRunning, \"mixed state #1 with restart onfailure\", }, { &api.Pod{ Spec: desiredState, Status: api.PodStatus{ Info: map[string]api.ContainerStatus{ \"containerA\": runningState, }, Host: \"machine\", }, }, api.PodPending, \"mixed state #2 with restart onfailure\", }, } for _, test := range tests { if status := getPhase(&test.pod.Spec, test.pod.Status.Info); status != test.status { t.Errorf(\"In test %s, expected %v, got %v\", test.test, test.status, status) } } } func TestGarbageCollection(t *testing.T) { pod1 := makePod(api.NamespaceDefault, \"foo\", \"machine\", \"bar\") pod2 := makePod(api.NamespaceDefault, \"baz\", \"machine\", \"qux\")"} {"_id":"doc-en-kubernetes-ec3906e167ac177574f1dfbdf16a30f3ea0f46b4b7e1e7b9c8fa1bdbf873757b","title":"","text":"m := make(api.PodInfo) for k, v := range r.Status.Info { v.Ready = true v.PodIP = \"1.2.3.4\" m[k] = v } r.Status.Info = m"} {"_id":"doc-en-kubernetes-9d5f5c6320636df815efe2d597380cf5cc5fa971206ed9ab10c1037e0d6d61ba","title":"","text":"return func() (bool, error) { endpoints, err := c.Endpoints(serviceNamespace).Get(serviceID) if err != nil { glog.Infof(\"Error on creating endpoints: %v\", err) return false, nil } glog.Infof(\"endpoints: %v\", endpoints.Endpoints) return len(endpoints.Endpoints) == endpointCount, nil } }"} {"_id":"doc-en-kubernetes-4c87a476515a8c76d3a6f64ad7c7ce2836016116da0aecf2defaeec912aa8a2c","title":"","text":"return &containerStatus, nil } // GetDockerPodInfo returns docker info for all containers in the pod/manifest. // GetDockerPodInfo returns docker info for all containers in the pod/manifest and // infrastructure container func GetDockerPodInfo(client DockerInterface, manifest api.PodSpec, podFullName string, uid types.UID) (api.PodInfo, error) { info := api.PodInfo{} expectedContainers := make(map[string]api.Container)"} {"_id":"doc-en-kubernetes-11b19c922f77e269b7916d0efc0723bd45d19f474996ab8d7914c76b3457bbd8","title":"","text":"// Assume info is ready to process podStatus.Phase = getPhase(spec, info) podStatus.Info = api.PodInfo{} for _, c := range spec.Containers { containerStatus := info[c.Name] containerStatus.Ready = kl.readiness.IsReady(containerStatus) info[c.Name] = containerStatus podStatus.Info[c.Name] = containerStatus } podStatus.Conditions = append(podStatus.Conditions, getPodReadyCondition(spec, info)...) podStatus.Conditions = append(podStatus.Conditions, getPodReadyCondition(spec, podStatus.Info)...) netContainerInfo, found := info[dockertools.PodInfraContainerName] if found { podStatus.PodIP = netContainerInfo.PodIP } // TODO(dchen1107): Change Info to list from map podStatus.Info = info return podStatus, nil }"} {"_id":"doc-en-kubernetes-ebff61b4c73740e17a06dc4107e707d8833f3d740685507858804bd48659353e","title":"","text":"} // Takes a list of strings and compiles them into a list of regular expressions func CompileRegexps(regexpStrings StringList) ([]*regexp.Regexp, error) { func CompileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) { regexps := []*regexp.Regexp{} for _, regexpStr := range regexpStrings { r, err := regexp.Compile(regexpStr)"} {"_id":"doc-en-kubernetes-3b91ee1154b112879cefeb6f9f8a3037685f1becb9c7da0784d5b303c08e6e22","title":"","text":"t.Errorf(\"diff returned %v\", diff) } } func TestCompileRegex(t *testing.T) { uncompiledRegexes := []string{\"endsWithMe$\", \"^startingWithMe\"} regexes, err := CompileRegexps(uncompiledRegexes) if err != nil { t.Errorf(\"Failed to compile legal regexes: '%v': %v\", uncompiledRegexes, err) } if len(regexes) != len(uncompiledRegexes) { t.Errorf(\"Wrong number of regexes returned: '%v': %v\", uncompiledRegexes, regexes) } if !regexes[0].MatchString(\"Something that endsWithMe\") { t.Errorf(\"Wrong regex returned: '%v': %v\", uncompiledRegexes[0], regexes[0]) } if regexes[0].MatchString(\"Something that doesn't endsWithMe.\") { t.Errorf(\"Wrong regex returned: '%v': %v\", uncompiledRegexes[0], regexes[0]) } if !regexes[1].MatchString(\"startingWithMe is very important\") { t.Errorf(\"Wrong regex returned: '%v': %v\", uncompiledRegexes[1], regexes[1]) } if regexes[1].MatchString(\"not startingWithMe should fail\") { t.Errorf(\"Wrong regex returned: '%v': %v\", uncompiledRegexes[1], regexes[1]) } } "} {"_id":"doc-en-kubernetes-b1ab63dd995bbe8f064cfc2886c0942e78604d77db1e3422cf43ec13159927d8","title":"","text":"// kubectl command (begining with a space). func kubectlArgs() string { if *checkVersionSkew { return \" --match-server-version --v=4\" return \" --match-server-version\" } return \" --v=4\" return \"\" } func bashWrap(cmd string) string {"} {"_id":"doc-en-kubernetes-88b66a0599dd199c29ab489ef31fc9f4ac102b355c1b3184c93f86fac4c18748","title":"","text":"pod.UID = types.UID(hex.EncodeToString(hasher.Sum(nil)[0:])) glog.V(5).Infof(\"Generated UID %q for pod %q from file %s\", pod.UID, pod.Name, filename) } // This is required for backward compatibility, and should be removed once we // completely deprecate ContainerManifest. if len(pod.Name) == 0 { pod.Name = string(pod.UID) glog.V(5).Infof(\"Generated Name %q for UID %q from file %s\", pod.Name, pod.UID, filename) } if len(pod.Namespace) == 0 { hasher := adler32.New() fmt.Fprint(hasher, filename)"} {"_id":"doc-en-kubernetes-28885ed1d23d44408ab386dcfc093d727dd43da7bc4118c2245dfc8135ee2e4b","title":"","text":"pod.UID = types.UID(hex.EncodeToString(hasher.Sum(nil)[0:])) glog.V(5).Infof(\"Generated UID %q for pod %q from URL %s\", pod.UID, pod.Name, url) } // This is required for backward compatibility, and should be removed once we // completely deprecate ContainerManifest. if len(pod.Name) == 0 { pod.Name = string(pod.UID) glog.V(5).Infof(\"Generate Name %q from UID %q from URL %s\", pod.Name, pod.UID, url) } if len(pod.Namespace) == 0 { hasher := adler32.New() fmt.Fprint(hasher, url)"} {"_id":"doc-en-kubernetes-6e8ce1efddd5f85bb7905a417c527be927c8521935072a1224919598b8519b7b","title":"","text":"}), }, { desc: \"Single manifest without ID\", manifests: api.ContainerManifest{Version: \"v1beta1\", UUID: \"111\"}, expected: CreatePodUpdate(kubelet.SET, kubelet.HTTPSource, api.BoundPod{ ObjectMeta: api.ObjectMeta{ UID: \"111\", Name: \"111\", Namespace: \"foobar\", }, Spec: api.PodSpec{ RestartPolicy: api.RestartPolicy{Always: &api.RestartPolicyAlways{}}, DNSPolicy: api.DNSClusterFirst, }, }), }, { desc: \"Multiple manifests\", manifests: []api.ContainerManifest{ {Version: \"v1beta1\", ID: \"foo\", UUID: \"111\", Containers: []api.Container{{Name: \"1\", Image: \"foo\"}}},"} {"_id":"doc-en-kubernetes-c21d831a1c6df0f8bb2092e36ff1d08333b0382da52b6066f7af08d803d248a4","title":"","text":"source \"${KUBE_ROOT}/cluster/kube-env.sh\" source \"${KUBE_VERSION_ROOT}/cluster/${KUBERNETES_PROVIDER}/util.sh\" function wait_for_running() { echo \"Waiting for pods to come up.\" frontends=$(${KUBECTL} get pods -l name=frontend -o template '--template={{range.items}}{{.id}} {{end}}') master=$(${KUBECTL} get pods -l name=redis-master -o template '--template={{range.items}}{{.id}} {{end}}') slaves=$(${KUBECTL} get pods -l name=redisslave -o template '--template={{range.items}}{{.id}} {{end}}') pods=$(echo $frontends $master $slaves) all_running=0 for i in $(seq 1 30); do sleep 10 all_running=1 for pod in $pods; do status=$(${KUBECTL} get pods $pod -o template '--template={{.currentState.status}}') || true if [[ \"$status\" == \"Pending\" ]]; then all_running=0 break fi done if [[ \"${all_running}\" == 1 ]]; then break fi done if [[ \"${all_running}\" == 0 ]]; then echo \"Pods did not come up in time\" exit 1 fi } function teardown() { ${KUBECTL} stop -f \"${GUESTBOOK}\" } prepare-e2e GUESTBOOK=\"${KUBE_ROOT}/examples/guestbook\" echo \"WARNING: this test is a no op that only attempts to launch guestbook resources.\" # Launch the guestbook example ${KUBECTL} create -f \"${GUESTBOOK}\" sleep 15 POD_LIST_1=$(${KUBECTL} get pods -o template '--template={{range.items}}{{.id}} {{end}}') echo \"Pods running: ${POD_LIST_1}\" # TODO make this an actual test. Open up a firewall and use curl to post and # read a message via the frontend ${KUBECTL} stop -f \"${GUESTBOOK}\" POD_LIST_2=$(${KUBECTL} get pods -o template '--template={{range.items}}{{.id}} {{end}}') echo \"Pods running after shutdown: ${POD_LIST_2}\" trap \"teardown\" EXIT # Verify that all pods are running wait_for_running get-password detect-master # Add a new entry to the guestbook and verify that it was remembered FRONTEND_ADDR=https://${KUBE_MASTER_IP}/api/v1beta1/proxy/services/frontend echo \"Waiting for frontend to serve content\" serving=0 for i in $(seq 1 12); do ENTRY=$(curl ${FRONTEND_ADDR}/index.php?cmd=get&key=messages --insecure --user ${KUBE_USER}:${KUBE_PASSWORD}) echo $ENTRY if [[ $ENTRY == '{\"data\": \"\"}' ]]; then serving=1 break fi sleep 10 done if [[ \"${serving}\" == 0 ]]; then echo \"Pods did not start serving content in time\" exit 1 fi curl ${FRONTEND_ADDR}/index.php?cmd=set&key=messages&value=TestEntry --insecure --user ${KUBE_USER}:${KUBE_PASSWORD} ENTRY=$(curl ${FRONTEND_ADDR}/index.php?cmd=get&key=messages --insecure --user ${KUBE_USER}:${KUBE_PASSWORD}) if [[ $ENTRY != '{\"data\": \"TestEntry\"}' ]]; then echo \"Wrong entry received: ${ENTRY}\" exit 1 fi exit 0"} {"_id":"doc-en-kubernetes-4aca493934e234da31e97e0c81db16b78e41f12174d3281d64dcace2fdbc1400","title":"","text":"local REGION=${ZONE%-*} gcloud compute forwarding-rules delete -q --region ${REGION} \"${INSTANCE_PREFIX}-default-frontend\" || true gcloud compute target-pools delete -q --region ${REGION} \"${INSTANCE_PREFIX}-default-frontend\" || true gcloud compute firewall-rules delete guestbook-e2e-minion-8000 -q || true fi } function wait_for_running() { echo \"Waiting for pods to come up.\" local frontends master slaves pods all_running status i pod frontends=($(${KUBECTL} get pods -l name=frontend -o template '--template={{range.items}}{{.id}} {{end}}')) master=($(${KUBECTL} get pods -l name=redis-master -o template '--template={{range.items}}{{.id}} {{end}}')) slaves=($(${KUBECTL} get pods -l name=redis-slave -o template '--template={{range.items}}{{.id}} {{end}}')) pods=(\"${frontends[@]}\" \"${master[@]}\" \"${slaves[@]}\") all_running=0 for i in {1..30}; do all_running=1 for pod in \"${pods[@]}\"; do status=$(${KUBECTL} get pods \"${pod}\" -o template '--template={{.currentState.status}}') || true if [[ \"$status\" != \"Running\" ]]; then all_running=0 break fi done if [[ \"${all_running}\" == 1 ]]; then break fi sleep 10 done if [[ \"${all_running}\" == 0 ]]; then echo \"Pods did not come up in time\" return 1 fi }"} {"_id":"doc-en-kubernetes-2521f1e5ee1a86d2eaa960a404a5a3b0b2ca547ec69fd54e193159f6c05ff897","title":"","text":"trap \"teardown\" EXIT echo \"WARNING: this test is a no op that only attempts to launch guestbook resources.\" # Launch the guestbook example ${KUBECTL} create -f \"${GUESTBOOK}\" sleep 15 POD_LIST_1=$(${KUBECTL} get pods -o template '--template={{range.items}}{{.id}} {{end}}') echo \"Pods running: ${POD_LIST_1}\" # TODO make this an actual test. Open up a firewall and use curl to post and # read a message via the frontend ${KUBECTL} stop -f \"${GUESTBOOK}\" POD_LIST_2=$(${KUBECTL} get pods -o template '--template={{range.items}}{{.id}} {{end}}') echo \"Pods running after shutdown: ${POD_LIST_2}\" # Verify that all pods are running wait_for_running if [[ \"${KUBERNETES_PROVIDER}\" == \"gce\" ]]; then gcloud compute firewall-rules create --allow=tcp:8000 --network=\"${NETWORK}\" --target-tags=\"${MINION_TAG}\" guestbook-e2e-minion-8000 fi # Add a new entry to the guestbook and verify that it was remembered frontend_addr=$(${KUBECTL} get service frontend -o template '--template={{range .publicIPs}}{{.}}{{end}}:{{.port}}') echo \"Waiting for frontend to serve content\" serving=0 for i in {1..12}; do entry=$(curl \"http://${frontend_addr}/index.php?cmd=get&key=messages\") || true echo ${entry} if [[ \"${entry}\" == '{\"data\": \"\"}' ]]; then serving=1 break fi sleep 10 done if [[ \"${serving}\" == 0 ]]; then echo \"Pods did not start serving content in time\" exit 1 fi curl \"http://${frontend_addr}/index.php?cmd=set&key=messages&value=TestEntry\" entry=$(curl \"http://${frontend_addr}/index.php?cmd=get&key=messages\") if [[ \"${entry}\" != '{\"data\": \"TestEntry\"}' ]]; then echo \"Wrong entry received: ${entry}\" exit 1 fi exit 0"} {"_id":"doc-en-kubernetes-3bb0c9cf2b1c619f738855e9398944c4c0e083699002655ddb0ef6fa6d5cef5d","title":"","text":"return nil, err } c.defaultConfig = config if c.matchVersion { if err := client.MatchesServerVersion(config); err != nil { return nil, err } } } // TODO: have a better config copy method config := *c.defaultConfig if len(version) != 0 { config.Version = version } client.SetKubernetesDefaults(&config) return &config, nil }"} {"_id":"doc-en-kubernetes-55f207ba73aadcafbc935a6ef60f45ffa7231bc70d967395cac2e7b8e32bb1d0","title":"","text":"\"fmt\" \"io\" \"io/ioutil\" \"testing\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest\""} {"_id":"doc-en-kubernetes-40fde2b99eef1bccc273a042dda6da4aa81f071b4b1e1e52e030651613ebe00a","title":"","text":"func stringBody(body string) io.ReadCloser { return ioutil.NopCloser(bytes.NewReader([]byte(body))) } // Verify that resource.RESTClients constructed from a factory respect mapping.APIVersion func TestClientVersions(t *testing.T) { f := NewFactory(nil) versions := []string{ \"v1beta1\", \"v1beta2\", \"v1beta3\", } for _, version := range versions { mapping := &meta.RESTMapping{ APIVersion: version, } c, err := f.RESTClient(nil, mapping) if err != nil { t.Errorf(\"unexpected error: %v\", err) } client := c.(*client.RESTClient) if client.APIVersion() != version { t.Errorf(\"unexpected Client APIVersion: %s %v\", client.APIVersion, client) } } } "} {"_id":"doc-en-kubernetes-e556777f4bcb0dae76d700286af9033698d3970b2990016236956b6725b3cdec","title":"","text":") func GetVersion(w io.Writer, kubeClient client.Interface) { GetClientVersion(w) serverVersion, err := kubeClient.ServerVersion() if err != nil { fmt.Printf(\"Couldn't read version from server: %vn\", err) os.Exit(1) } GetClientVersion(w) fmt.Fprintf(w, \"Server Version: %#vn\", *serverVersion) }"} {"_id":"doc-en-kubernetes-0da7129163210d35d5e034c206a31ca7116622cfda9a6125902e6427b4726adf","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. # Launches a container and verifies it can be reached. Assumes that # we're being called by hack/e2e-test.sh (we use some env vars it sets up). set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/../.. : ${KUBE_VERSION_ROOT:=${KUBE_ROOT}} : ${KUBECTL:=\"${KUBE_VERSION_ROOT}/cluster/kubectl.sh\"} : ${KUBE_CONFIG_FILE:=\"config-test.sh\"} export KUBECTL KUBE_CONFIG_FILE source \"${KUBE_ROOT}/cluster/kube-env.sh\" source \"${KUBE_VERSION_ROOT}/cluster/${KUBERNETES_PROVIDER}/util.sh\" prepare-e2e if [[ \"${KUBERNETES_PROVIDER}\" != \"gce\" ]] && [[ \"${KUBERNETES_PROVIDER}\" != \"gke\" ]]; then echo \"WARNING: Skipping certs.sh for cloud provider: ${KUBERNETES_PROVIDER}.\" exit 0 fi # Set KUBE_MASTER detect-master # IMPORTANT: there are upstream things that rely on these files. # Do *not* fix this test by changing this path, unless you _really_ know # what you are doing. for file in kubecfg.key kubecfg.crt ca.crt; do echo \"Checking for ${file}\" \"${GCLOUD}\" compute ssh --zone=\"${ZONE}\" \"${KUBE_MASTER}\" --command \"ls /srv/kubernetes/${file}\" done "} {"_id":"doc-en-kubernetes-6e46cf9dbab0e8b8adcf862ab681f4b9eb96f39f21e0fa64cf400f3dc1fb52a1","title":"","text":"FilenameParam(flags.Filenames...). Flatten(). Do() checkErr(r.Err()) count := 0 err = r.Visit(func(info *resource.Info) error {"} {"_id":"doc-en-kubernetes-9694cda8568a3beb9abf77d5b9a988ca5af852d00018d4f4ba6d6e124297ea59","title":"","text":"ResourceTypeOrNameArgs(args...). Flatten(). Do() checkErr(r.Err()) found := 0 err = r.IgnoreErrors(errors.IsNotFound).Visit(func(r *resource.Info) error {"} {"_id":"doc-en-kubernetes-b3a93958c0480da0f086458ff2d0abf0df0e6985436ec08cc22d5f694879cb4f","title":"","text":"ResourceTypeOrNameArgs(args...). SingleResourceType(). Do() checkErr(r.Err()) mapping, err := r.ResourceMapping() checkErr(err)"} {"_id":"doc-en-kubernetes-72596694c15ff00fcd0ebed0dc03f0a48335d0e1ae4c4c43c7d9298ded504c37","title":"","text":"FilenameParam(flags.Filenames...). Flatten(). Do() checkErr(r.Err()) patch := cmdutil.GetFlagString(cmd, \"patch\") if len(flags.Filenames) == 0 && len(patch) == 0 {"} {"_id":"doc-en-kubernetes-810c83a0cc98b111cfe90415c1b1d46aca551ee86fbc8fff39752b490dd35377","title":"","text":"# The business logic for whether a given object should be created # was already enforced by salt, and /etc/kubernetes/addons is the # managed result is of that. Start everything below that directory. echo \"== Kubernetes addon manager started at $(date -Is) ==\" KUBECTL=/usr/local/bin/kubectl function create-object() { obj=$1 for tries in {1..5}; do if ${KUBECTL} --server=\"127.0.0.1:8080\" create --validate=true -f ${obj}; then return fi echo \"++ ${obj} failed, attempt ${try} (sleeping 5) ++\" sleep 5 done } echo \"== Kubernetes addon manager started at $(date -Is) ==\" for obj in $(find /etc/kubernetes/addons -name *.yaml); do ${KUBECTL} --server=\"127.0.0.1:8080\" create -f ${obj} & create-object ${obj} & echo \"++ addon ${obj} started in pid $! ++\" done noerrors=\"true\""} {"_id":"doc-en-kubernetes-ee8d8600f1d0b96e5e500b241d5815dc4a2098bfa14b6a959ec296cc7efb8520","title":"","text":"detect-project &> /dev/null export PATH=$(get_absolute_dirname $kubectl):$PATH kubectl=\"${GCLOUD}\" fi if [[ \"$KUBERNETES_PROVIDER\" == \"vagrant\" ]]; then # When we are using vagrant it has hard coded auth. We repeat that here so that # we don't clobber auth that might be used for a publicly facing cluster. config=( \"--auth-path=$HOME/.kubernetes_vagrant_auth\" ) elif [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then # GKE runs kubectl through gcloud. config=( \"preview\""} {"_id":"doc-en-kubernetes-d8a8d8bb01f98d1394bd0f60c6a1ada87e363a154898b9d833b6165f9142c697","title":"","text":"\"--zone=${ZONE}\" \"--cluster=${CLUSTER_NAME}\" ) elif [[ \"$KUBERNETES_PROVIDER\" == \"vagrant\" ]]; then # When we are using vagrant it has hard coded auth. We repeat that here so that # we don't clobber auth that might be used for a publicly facing cluster. config=( \"--auth-path=$HOME/.kubernetes_vagrant_auth\" ) fi detect-master > /dev/null if [[ -n \"${KUBE_MASTER_IP-}\" && -z \"${KUBERNETES_MASTER-}\" ]]; then export KUBERNETES_MASTER=https://${KUBE_MASTER_IP} fi echo \"current-context: \"$(${kubectl} config view -o template --template='{{index . \"current-context\"}}')\"\" echo \"Running:\" \"${kubectl}\" \"${config[@]:+${config[@]}}\" \"${@+$@}\" >&2 \"${kubectl}\" \"${config[@]:+${config[@]}}\" \"${@+$@}\""} {"_id":"doc-en-kubernetes-dd14175eeef8847b088e9c99b27a559deea44afc931513964a7df45489a610cb","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. function detect-master () { echo \"Running locally\" } "} {"_id":"doc-en-kubernetes-bc68184aa48bded97e0d7c2af2778fcecc6eca0328f3bc1543d7a72ada40acbf","title":"","text":"This will build and start a lightweight local cluster, consisting of a master and a single minion. Type Control-C to shut it down. You can use the cluster/kubectl.sh script to interact with the local cluster. You must set the KUBERNETES_PROVIDER environment variable. You can use the cluster/kubectl.sh script to interact with the local cluster. hack/local-up-cluster.sh will print the commands to run to point kubectl at the local cluster. ``` export KUBERNETES_PROVIDER=local ``` ### Running a container"} {"_id":"doc-en-kubernetes-89a0d50330d5f3f0160534006ae5457f635b123c0c8b770c605c474d699edd70","title":"","text":"[[ -n \"${ETCD_PID-}\" ]] && kill \"${ETCD_PID}\" [[ -n \"${ETCD_DIR-}\" ]] && rm -rf \"${ETCD_DIR}\" exit 0 }"} {"_id":"doc-en-kubernetes-f34b610ecddc24c3cd4232a4ca212d943fde9f37920adb6265bbd9a48515bafe","title":"","text":"To start using your cluster, open up another terminal/tab and run: export KUBERNETES_PROVIDER=local cluster/kubectl.sh config set-cluster local --server=http://${API_HOST}:${API_PORT} --insecure-skip-tls-verify=true --global cluster/kubectl.sh config set-context local --cluster=local --global cluster/kubectl.sh config use-context local cluster/kubectl.sh EOF"} {"_id":"doc-en-kubernetes-9a81dd5834be35eb6afc5480f1d6744bf802d32107eaf2722b12eb9c07da54d1","title":"","text":"// 3. CurrentDirectoryPath // 4. HomeDirectoryPath // Empty filenames are ignored. Files with non-deserializable content produced errors. // The first file to set a particular value or map key wins and the value or map key is never changed. // This means that the first file to set CurrentContext will have its context preserved. It also means // that if two files specify a \"red-user\", only values from the first file's red-user are used. Even // The first file to set a particular map key wins and map key's value is never changed. // BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed. // This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two. // It also means that if two files specify a \"red-user\", only values from the first file's red-user are used. Even // non-conflicting entries from the second file's \"red-user\" are discarded. // Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder // and only absolute file paths are returned. func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) { config := clientcmdapi.NewConfig() mergeConfigWithFile(config, rules.CommandLinePath) resolveLocalPaths(rules.CommandLinePath, config) kubeConfigFiles := []string{rules.CommandLinePath, rules.EnvVarPath, rules.CurrentDirectoryPath, rules.HomeDirectoryPath} mergeConfigWithFile(config, rules.EnvVarPath) resolveLocalPaths(rules.EnvVarPath, config) // first merge all of our maps mapConfig := clientcmdapi.NewConfig() for _, file := range kubeConfigFiles { mergeConfigWithFile(mapConfig, file) resolveLocalPaths(file, mapConfig) } mergeConfigWithFile(config, rules.CurrentDirectoryPath) resolveLocalPaths(rules.CurrentDirectoryPath, config) // merge all of the struct values in the reverse order so that priority is given correctly nonMapConfig := clientcmdapi.NewConfig() for i := len(kubeConfigFiles) - 1; i >= 0; i-- { file := kubeConfigFiles[i] mergeConfigWithFile(nonMapConfig, file) resolveLocalPaths(file, nonMapConfig) } mergeConfigWithFile(config, rules.HomeDirectoryPath) resolveLocalPaths(rules.HomeDirectoryPath, config) // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and // get the values we expect. config := clientcmdapi.NewConfig() mergo.Merge(config, mapConfig) mergo.Merge(config, nonMapConfig) return config, nil }"} {"_id":"doc-en-kubernetes-89b69b2b4a0c0fd5280b357025f1541bdeb31bd53485ff1ea5e0606ecb6929d6","title":"","text":"Contexts: map[string]clientcmdapi.Context{ \"gothic-context\": {AuthInfo: \"blue-user\", Cluster: \"chicken-cluster\", Namespace: \"plane-ns\"}}, } testConfigConflictAlfa = clientcmdapi.Config{ AuthInfos: map[string]clientcmdapi.AuthInfo{ \"red-user\": {Token: \"a-different-red-token\"},"} {"_id":"doc-en-kubernetes-83a651d24fdd1abbc5c865eca76961c3186e91441365ed99b8370cd52be93e51","title":"","text":"} ) func TestConflictingCurrentContext(t *testing.T) { commandLineFile, _ := ioutil.TempFile(\"\", \"\") defer os.Remove(commandLineFile.Name()) envVarFile, _ := ioutil.TempFile(\"\", \"\") defer os.Remove(envVarFile.Name()) mockCommandLineConfig := clientcmdapi.Config{ CurrentContext: \"any-context-value\", } mockEnvVarConfig := clientcmdapi.Config{ CurrentContext: \"a-different-context\", } WriteToFile(mockCommandLineConfig, commandLineFile.Name()) WriteToFile(mockEnvVarConfig, envVarFile.Name()) loadingRules := ClientConfigLoadingRules{ CommandLinePath: commandLineFile.Name(), EnvVarPath: envVarFile.Name(), } mergedConfig, err := loadingRules.Load() if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext { t.Errorf(\"expected %v, got %v\", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext) } } func TestResolveRelativePaths(t *testing.T) { pathResolutionConfig1 := clientcmdapi.Config{ AuthInfos: map[string]clientcmdapi.AuthInfo{"} {"_id":"doc-en-kubernetes-5381e1a98ff3037853fe73b819618d954bd1e81045ac71f3de699dcb00ac2918","title":"","text":"} // TODO use generalized labels once they are implemented (#341) b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand(cmd)). b := resource.NewBuilder(mapper, typer, factory.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(\"kubernetes.io/cluster-service=true\"). ResourceTypeOrNameArgs(false, []string{\"services\"}...)."} {"_id":"doc-en-kubernetes-d4c970efc4c373b752fd15bd08a6228e92b5b53ccae85ab4c4585796dca89c90","title":"","text":"return printer, nil } // ClientMapperForCommand returns a ClientMapper for the given command and factory. func (f *Factory) ClientMapperForCommand(cmd *cobra.Command) resource.ClientMapper { // ClientMapperForCommand returns a ClientMapper for the factory. func (f *Factory) ClientMapperForCommand() resource.ClientMapper { return resource.ClientMapperFunc(func(mapping *meta.RESTMapping) (resource.RESTClient, error) { return f.RESTClient(mapping) })"} {"_id":"doc-en-kubernetes-f6a00898c2ac301a6351dea50661b356b736ef0704af2c443a5de13745c7a659","title":"","text":"return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(filenames...)."} {"_id":"doc-en-kubernetes-633755adaf3daa7cec7371a7f676a1b1d5ff596117edaf83c1091062382e1554","title":"","text":"// handle watch separately since we cannot watch multiple resource types isWatch, isWatchOnly := util.GetFlagBool(cmd, \"watch\"), util.GetFlagBool(cmd, \"watch-only\") if isWatch || isWatchOnly { r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...)."} {"_id":"doc-en-kubernetes-f18f9e121f452d6afbe48e99bc690bf839f66be0525f3ae6a2f0777f0260eb59","title":"","text":"return nil } b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector). ResourceTypeOrNameArgs(true, args...)."} {"_id":"doc-en-kubernetes-f54e55cf8bbb9d9f53d4d5e9359c0be50e1660a8c2c184148ccdf158acd8c8dd","title":"","text":"} mapper, typer := f.Object() b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). b := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).DefaultNamespace(). SelectorParam(selector)."} {"_id":"doc-en-kubernetes-d5fda7c6c6ae1d98781d5ca6088117386f77b76a780fe325955b7ac7b1bb7d47","title":"","text":"mapper, typer := f.Object() // TODO: use resource.Builder instead obj, err := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). obj, err := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). NamespaceParam(cmdNamespace).RequireNamespace(). FilenameParam(filename). Do()."} {"_id":"doc-en-kubernetes-56d8a1a03086c3671a08b07bf785651ef064c29d1e7fa59487a3723fde3acf6c","title":"","text":"cmdNamespace, err := f.DefaultNamespace() cmdutil.CheckErr(err) mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). ResourceTypeOrNameArgs(false, args...)."} {"_id":"doc-en-kubernetes-e78d48e54bd620eb54bbd31a262ca5ff7ad46c24ed3d86b2bef014e42290446e","title":"","text":"} mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand(cmd)). r := resource.NewBuilder(mapper, typer, f.ClientMapperForCommand()). ContinueOnError(). NamespaceParam(cmdNamespace).RequireNamespace(). FilenameParam(filenames...)."} {"_id":"doc-en-kubernetes-1149a532ea4c280a1077df621fb46c2cf4f7fac633a025d0a0e7e0cdb969396d","title":"","text":"return func() (bool, error) { for i := range pods.Items { host, id, namespace := pods.Items[i].Status.Host, pods.Items[i].Name, pods.Items[i].Namespace glog.Infof(\"Check whether pod %s.%s exists on node %q\", id, namespace, host) if len(host) == 0 { glog.Infof(\"Pod %s.%s is not bound to a host yet\", id, namespace) return false, nil } if _, err := podInfo.GetPodStatus(host, namespace, id); err != nil {"} {"_id":"doc-en-kubernetes-40687d02006b5b88ee96c7be54da93476087c35e3c73ebc1303404b9de7c49b9","title":"","text":"// ResourceList is a set of (resource name, quantity) pairs. type ResourceList map[ResourceName]resource.Quantity // Get is a convenience function, which returns a 0 quantity if the // resource list is nil, empty, or lacks a value for the requested resource. // Treat as read only! func (rl ResourceList) Get(name ResourceName) *resource.Quantity { if rl == nil { return &resource.Quantity{} } q := rl[name] return &q } // Node is a worker node in Kubernetenes // The name of the node according to etcd is in ObjectMeta.Name. type Node struct {"} {"_id":"doc-en-kubernetes-87cfa115d501a7639afee6c49e443698c1a7fb38b9fb404b28040d74cf25dba1","title":"","text":"HostPort int `json:\"hostPort,omitempty\"` // Required: This must be a valid port number, 0 < x < 65536. ContainerPort int `json:\"containerPort\"` // Optional: Supports \"TCP\" and \"UDP\". Defaults to \"TCP\". // Required: Supports \"TCP\" and \"UDP\". Protocol Protocol `json:\"protocol,omitempty\"` // Optional: What host IP to bind the external port to. HostIP string `json:\"hostIP,omitempty\"`"} {"_id":"doc-en-kubernetes-90eab0c297ade246b462d8ce713b25b2141e4e0ebc8aa225957b1d2f3c0a9bb8","title":"","text":"LivenessProbe *Probe `json:\"livenessProbe,omitempty\"` ReadinessProbe *Probe `json:\"readinessProbe,omitempty\"` Lifecycle *Lifecycle `json:\"lifecycle,omitempty\"` // Optional: Defaults to /dev/termination-log // Required. TerminationMessagePath string `json:\"terminationMessagePath,omitempty\"` // Optional: Default to false. Privileged bool `json:\"privileged,omitempty\"` // Optional: Policy for pulling images for this container // Required: Policy for pulling images for this container ImagePullPolicy PullPolicy `json:\"imagePullPolicy\"` // Optional: Capabilities for container. Capabilities Capabilities `json:\"capabilities,omitempty\"`"} {"_id":"doc-en-kubernetes-acae5b24b4d878f4e994f62d384d1de99e59e1e9f7408a8afa59082df6ed39bd","title":"","text":"Volumes []Volume `json:\"volumes\"` Containers []Container `json:\"containers\"` RestartPolicy RestartPolicy `json:\"restartPolicy,omitempty\"` // Optional: Set DNS policy. Defaults to \"ClusterFirst\" // Required: Set DNS policy. DNSPolicy DNSPolicy `json:\"dnsPolicy,omitempty\"` // NodeSelector is a selector which must be true for the pod to fit on a node NodeSelector map[string]string `json:\"nodeSelector,omitempty\"`"} {"_id":"doc-en-kubernetes-8dc0d96adce126a8df241fc1b7b9e5a050204c913924fe507192985a26f9fa03","title":"","text":"// proxied by this service. Port int `json:\"port\"` // Optional: Supports \"TCP\" and \"UDP\". Defaults to \"TCP\". // Required: Supports \"TCP\" and \"UDP\". Protocol Protocol `json:\"protocol,omitempty\"` // This service will route traffic to pods having labels matching this selector. If empty or not present,"} {"_id":"doc-en-kubernetes-bcdafd674d5f5ca26c8c17b45449a172acf5dfa0510fb194fbc4a402546e7284","title":"","text":"// Optional: If unspecified, the first port on the container will be used. ContainerPort util.IntOrString `json:\"containerPort,omitempty\"` // Optional: Supports \"ClientIP\" and \"None\". Used to maintain session affinity. // Required: Supports \"ClientIP\" and \"None\". Used to maintain session affinity. SessionAffinity AffinityType `json:\"sessionAffinity,omitempty\"` }"} {"_id":"doc-en-kubernetes-4ab00eaa350062fe54db1d3a5b019cacb157aab281aa7d43453540f2bbe271f7","title":"","text":"Volumes []Volume `json:\"volumes\"` Containers []Container `json:\"containers\"` RestartPolicy RestartPolicy `json:\"restartPolicy,omitempty\"` // Optional: Set DNS policy. Defaults to \"ClusterFirst\" // Required: Set DNS policy. DNSPolicy DNSPolicy `json:\"dnsPolicy\"` }"} {"_id":"doc-en-kubernetes-d6c212a64e91204ce1bb9c8b28a0c33157c16262ecb03197bc563300da0abeb8","title":"","text":"} node_count=\"${NUM_MINIONS}\" next_node=\"10.244.0.0\" next_node=\"${KUBE_GCE_CLUSTER_CLASS_B:-10.244}.0.0\" node_subnet_size=24 node_subnet_count=$((2 ** (32-$node_subnet_size))) subnets=()"} {"_id":"doc-en-kubernetes-8352a5f995b0804afbbd0751134d308e7979372b755cf4083db1db69592f2c52","title":"","text":"next_node=$(increment_ipv4 $next_node $node_subnet_count) done CLUSTER_IP_RANGE=\"10.244.0.0/16\" CLUSTER_IP_RANGE=\"${KUBE_GCE_CLUSTER_CLASS_B:-10.244}.0.0/16\" MINION_IP_RANGES=($(eval echo \"${subnets[@]}\")) MINION_SCOPES=(\"storage-ro\" \"compute-rw\" \"https://www.googleapis.com/auth/monitoring\")"} {"_id":"doc-en-kubernetes-3692f2da1a98d5389fd1cd251331d8c3f16bed3780cb2e59a5f7a72d35861beb","title":"","text":"MASTER_NAME=\"${INSTANCE_PREFIX}-master\" MASTER_TAG=\"${INSTANCE_PREFIX}-master\" MINION_TAG=\"${INSTANCE_PREFIX}-minion\" CLUSTER_IP_RANGE=\"10.245.0.0/16\" MINION_IP_RANGES=($(eval echo \"10.245.{1..${NUM_MINIONS}}.0/24\")) CLUSTER_IP_RANGE=\"${KUBE_GCE_CLUSTER_CLASS_B:-10.245}.0.0/16\" MINION_IP_RANGES=($(eval echo \"${KUBE_GCE_CLUSTER_CLASS_B:-10.245}.{1..${NUM_MINIONS}}.0/24\")) MASTER_IP_RANGE=\"${MASTER_IP_RANGE:-10.246.0.0/24}\" MINION_SCOPES=(\"storage-ro\" \"compute-rw\") # Increase the sleep interval value if concerned about API rate limits. 3, in seconds, is the default. POLL_SLEEP_INTERVAL=3"} {"_id":"doc-en-kubernetes-d7d35c293eb9d49a4df5193583b4662358b92613807ccd6a703430b817c80057","title":"","text":" #!/bin/bash # Copyright 2015 Google Inc. 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. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/.. function down-clusters { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} export KUBECONFIG=${cluster_dir}/.kubeconfig go run ${KUBE_ROOT}/hack/e2e.go -down -v & done wait } function up-clusters { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} export KUBE_GCE_CLUSTER_CLASS_B=\"10.$((${count}*2-1))\" export MASTER_IP_RANGE=\"10.$((${count}*2)).0.0/24\" local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} mkdir -p ${cluster_dir} export KUBECONFIG=${cluster_dir}/.kubeconfig go run hack/e2e.go -up -v |& tee ${cluster_dir}/up.log & done fail=0 for job in $(jobs -p); do wait \"${job}\" || fail=$((fail + 1)) done if (( fail != 0 )); then echo \"${fail} cluster creation failures. Not continuing with tests.\" exit 1 fi } function run-tests { for count in $(seq 1 ${clusters}); do export KUBE_GCE_INSTANCE_PREFIX=e2e-test-${USER}-${count} local cluster_dir=${KUBE_ROOT}/_output/e2e/${KUBE_GCE_INSTANCE_PREFIX} export KUBECONFIG=${cluster_dir}/.kubeconfig export E2E_REPORT_DIR=${cluster_dir} go run hack/e2e.go -test --test_args=\"--ginkgo.noColor\" \"${@:-}\" -down |& tee ${cluster_dir}/e2e.log & done wait } # Outputs something like: # _output/e2e/e2e-test-zml-5/junit.xml # FAIL: Shell tests that services.sh passes function post-process { echo $1 cat $1 | python -c ' import sys from xml.dom.minidom import parse failed = False for testcase in parse(sys.stdin).getElementsByTagName(\"testcase\"): if len(testcase.getElementsByTagName(\"failure\")) != 0: failed = True print \" FAIL: {test}\".format(test = testcase.getAttribute(\"name\")) if not failed: print \" SUCCESS!\" ' } function print-results { for count in $(seq 1 ${clusters}); do for junit in ${KUBE_ROOT}/_output/e2e/e2e-test-${USER}-${count}/junit*.xml; do post-process ${junit} done done } if [[ ${KUBERNETES_PROVIDER:-gce} != \"gce\" ]]; then echo \"$0 not supported on ${KUBERNETES_PROVIDER} yet\" >&2 exit 1 fi readonly clusters=${1:-} if ! [[ \"${clusters}\" =~ ^[0-9]+$ ]]; then echo \"Usage: ${0} [options to hack/e2e.go]\" >&2 exit 1 fi shift 1 rm -rf _output/e2e down-clusters up-clusters run-tests \"${@:-}\" print-results "} {"_id":"doc-en-kubernetes-4bf8d8d501c6c1beef684d3d446a22a8bb461c0df7fe98f0d35d9ce3987e6ad2","title":"","text":"id: monitoring-grafana port: 80 containerPort: 80 labels: name: grafana kubernetes.io/cluster-service: \"true\" selector: name: influxGrafana"} {"_id":"doc-en-kubernetes-aabc10c4e70db98d552097afd0892cc748baaab816b67889a2a2baf013292d0a","title":"","text":"id: monitoring-heapster port: 80 containerPort: 8082 labels: name: heapster kubernetes.io/cluster-service: \"true\" selector: name: heapster"} {"_id":"doc-en-kubernetes-8d0b6df481fed03e47dd892b0c954df26cee9d00a1ca5aa1b7871f1648434237","title":"","text":"id: monitoring-influxdb port: 80 containerPort: 8086 labels: name: influxdb kubernetes.io/cluster-service: \"true\" selector: name: influxGrafana"} {"_id":"doc-en-kubernetes-d6055e9b592f05244ce546ab6aec6bdf8553d581c76bc789e9826473781a1952","title":"","text":"- file: /etc/init.d/kubelet {% endif %} - file: /var/lib/kubelet/kubernetes_auth {% if grains.network_mode is defined and grains.network_mode == 'openvswitch' %} - sls: sdn {% endif %} "} {"_id":"doc-en-kubernetes-5b9a37e172661ce5a202c64339f186d844f5ec8062adb5ee69cbb9418faca451","title":"","text":"{% if grains.network_mode is defined and grains.network_mode == 'openvswitch' %} openvswitch: pkg: - installed service.running: - enable: True sdn: cmd.wait: - name: /kubernetes-vagrant/network_closure.sh - watch: - pkg: docker-io - pkg: openvswitch - sls: docker {% endif %}"} {"_id":"doc-en-kubernetes-765b5d2c57ffb5494f030cea12477ed5c7952fa97dfb05520cf9603135fbcb88","title":"","text":"- monit - nginx - kube-client-tools {% if grains['cloud'] is defined and grains['cloud'] != 'vagrant' %} - logrotate {% endif %} - kube-addons {% if grains['cloud'] is defined and grains['cloud'] == 'azure' %} - openvpn"} {"_id":"doc-en-kubernetes-0a3ad4c572b6c3700789a2d604fdbbbc19c6396bd0e34db946b73745d57862be","title":"","text":"mkdir -p /etc/salt/minion.d cat </etc/salt/minion.d/master.conf master: '$(echo \"$MASTER_NAME\" | sed -e \"s/'/''/g\")' master: '$(echo \"$MASTER_NAME\" | sed -e \"s/'/''/g\")' auth_timeout: 10 auth_tries: 2 auth_safemode: True ping_interval: 1 random_reauth_delay: 3 state_aggregrate: - pkg EOF cat </etc/salt/minion.d/grains.conf"} {"_id":"doc-en-kubernetes-a6db8c287ef797d47d8d554ef5764a9dd42e50fed009290511d4403383bb5ac3","title":"","text":"done # Let the minion know who its master is # Recover the salt-minion if the salt-master network changes ## auth_timeout - how long we want to wait for a time out ## auth_tries - how many times we will retry before restarting salt-minion ## auth_safemode - if our cert is rejected, we will restart salt minion ## ping_interval - restart the minion if we cannot ping the master after 1 minute ## random_reauth_delay - wait 0-3 seconds when reauthenticating ## recon_default - how long to wait before reconnecting ## recon_max - how long you will wait upper bound ## state_aggregrate - try to do a single yum command to install all referenced packages where possible at once, should improve startup times ## mkdir -p /etc/salt/minion.d cat </etc/salt/minion.d/master.conf master: '$(echo \"$MASTER_NAME\" | sed -e \"s/'/''/g\")' auth_timeout: 10 auth_tries: 2 auth_safemode: True ping_interval: 1 random_reauth_delay: 3 state_aggregrate: - pkg EOF cat </etc/salt/minion.d/log-level-debug.conf"} {"_id":"doc-en-kubernetes-5359c9b829d77e0556ad8d5e9b58571477b16082defc43450114d2fb5d32c5cc","title":"","text":"# Stop docker before making these updates systemctl stop docker # Install openvswitch yum install -y openvswitch systemctl enable openvswitch systemctl start openvswitch # create new docker bridge ip link set dev ${DOCKER_BRIDGE} down || true brctl delbr ${DOCKER_BRIDGE} || true"} {"_id":"doc-en-kubernetes-ac737da773039ad05b4f0998cb6fd6433620fbc8898203371aa0f5e0139d48db","title":"","text":"echo \"OPTIONS='-b=kbr0 --selinux-enabled ${DOCKER_OPTS}'\" >/etc/sysconfig/docker systemctl daemon-reload systemctl start docker } EOF"} {"_id":"doc-en-kubernetes-b7837b309394b062c5183c0ce076ae40b284fe9ff191e23f2020c6ac489cf6fa","title":"","text":"return } // Redirect requests of the form \"/{resource}/{name}\" to \"/{resource}/{name}/\" // This is essentially a hack for https://github.com/GoogleCloudPlatform/kubernetes/issues/4958. // Note: Keep this code after tryUpgrade to not break that flow. if len(parts) == 2 && !strings.HasSuffix(req.URL.Path, \"/\") { w.Header().Set(\"Location\", req.URL.Path+\"/\") w.WriteHeader(http.StatusMovedPermanently) return } proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: location.Scheme, Host: location.Host}) if transport == nil { prepend := path.Join(r.prefix, resource, id)"} {"_id":"doc-en-kubernetes-a8395cafa576d71b541ab2c3a55e16a2bb267d904c0e18f589b40bc7a8c9628f","title":"","text":"t.Fatalf(\"expected '%#v', got '%#v'\", e, a) } } func TestRedirectOnMissingTrailingSlash(t *testing.T) { table := []struct { // The requested path path string // The path requested on the proxy server. proxyServerPath string }{ {\"/trailing/slash/\", \"/trailing/slash/\"}, {\"/\", \"/\"}, // \"/\" should be added at the end. {\"\", \"/\"}, // \"/\" should not be added at a non-root path. {\"/some/path\", \"/some/path\"}, } for _, item := range table { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != item.proxyServerPath { t.Errorf(\"Unexpected request on path: %s, expected path: %s, item: %v\", req.URL.Path, item.proxyServerPath, item) } })) defer proxyServer.Close() serverURL, _ := url.Parse(proxyServer.URL) simpleStorage := &SimpleRESTStorage{ errors: map[string]error{}, resourceLocation: serverURL, expectedResourceNamespace: \"ns\", } handler := handleNamespaced(map[string]rest.Storage{\"foo\": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() proxyTestPattern := \"/api/version/proxy/namespaces/ns/foo/id\" + item.path req, err := http.NewRequest( \"GET\", server.URL+proxyTestPattern, strings.NewReader(\"\"), ) if err != nil { t.Errorf(\"unexpected error %v\", err) continue } // Note: We are using a default client here, that follows redirects. resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf(\"unexpected error %v\", err) continue } if resp.StatusCode != 200 { t.Errorf(\"Unexpected errorCode: %v, expected: 200. Response: %v, item: %v\", resp.StatusCode, resp, item) } } } "} {"_id":"doc-en-kubernetes-4bd880ef4ddfb8a9db46618b2292f9455e80a6f4e3211b53651d636714fdc24c","title":"","text":"t.Fatalf(\"expected '%#v', got '%#v'\", e, a) } } func TestRedirectOnMissingTrailingSlash(t *testing.T) { table := []struct { // The requested path path string // The path requested on the proxy server. proxyServerPath string }{ {\"/trailing/slash/\", \"/trailing/slash/\"}, {\"/\", \"/\"}, // \"/\" should be added at the end. {\"\", \"/\"}, // \"/\" should not be added at a non-root path. {\"/some/path\", \"/some/path\"}, } for _, item := range table { proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != item.proxyServerPath { t.Errorf(\"Unexpected request on path: %s, expected path: %s, item: %v\", req.URL.Path, item.proxyServerPath, item) } })) defer proxyServer.Close() serverURL, _ := url.Parse(proxyServer.URL) simpleStorage := &SimpleRESTStorage{ errors: map[string]error{}, resourceLocation: serverURL, expectedResourceNamespace: \"ns\", } handler := handleNamespaced(map[string]rest.Storage{\"foo\": simpleStorage}) server := httptest.NewServer(handler) defer server.Close() proxyTestPattern := \"/api/version2/proxy/namespaces/ns/foo/id\" + item.path req, err := http.NewRequest( \"GET\", server.URL+proxyTestPattern, strings.NewReader(\"\"), ) if err != nil { t.Errorf(\"unexpected error %v\", err) continue } // Note: We are using a default client here, that follows redirects. resp, err := http.DefaultClient.Do(req) if err != nil { t.Errorf(\"unexpected error %v\", err) continue } if resp.StatusCode != http.StatusOK { t.Errorf(\"Unexpected errorCode: %v, expected: 200. Response: %v, item: %v\", resp.StatusCode, resp, item) } } } "} {"_id":"doc-en-kubernetes-42ad1333e166aca0b35990bbc08e8fd3e40a602152c86eef15d166f6b8c076c7","title":"","text":"- file: /etc/init.d/kubelet {% endif %} - file: /var/lib/kubelet/kubernetes_auth {% if pillar.get('enable_node_monitoring', '').lower() == 'true' %} - file: /etc/kubernetes/manifests/cadvisor.manifest {% endif %} "} {"_id":"doc-en-kubernetes-7e500488dc11b98056f29ac0a80e04e994d938eeea6d301e3ab8980a72e21832","title":"","text":"'roles:kubernetes-pool': - match: grain - docker {% if grains['cloud'] is defined and grains['cloud'] == 'azure' %} - openvpn-client {% else %} - sdn {% endif %} - kubelet - kube-proxy {% if pillar.get('enable_node_monitoring', '').lower() == 'true' %}"} {"_id":"doc-en-kubernetes-614716874bb4ed3504bd8781da4976fb907024a3a00f6954f2c54d87a613b3ad","title":"","text":"{% endif %} {% endif %} - logrotate {% if grains['cloud'] is defined and grains['cloud'] == 'azure' %} - openvpn-client {% else %} - sdn {% endif %} - monit 'roles:kubernetes-master':"} {"_id":"doc-en-kubernetes-2fff0e2ca9052c2819fb5a178303f5e76a77e47a732cd98b2874247d6984507d","title":"","text":" #!/usr/bin/python # Copyright 2015 Google Inc. 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. import os import sys import yaml def mutate_env(path, var, value): # Load the existing arguments if os.path.exists(path): args = yaml.load(open(path)) else: args = {} args[var] = value yaml.dump(args, stream=open(path, 'w'), default_flow_style=False) if __name__ == \"__main__\": mutate_env(sys.argv[1], sys.argv[2], sys.argv[3]) "} {"_id":"doc-en-kubernetes-02e91e5fcf0ca7690ffa78e334912555f3451b6315e242da2ac90804f3e99d87","title":"","text":"done } # Given a yaml file, add or mutate the given env variable # Quote something appropriate for a yaml string. # # TODO(zmerlynn): Yes, this is an O(n^2) build-up right now. If we end # up with so many environment variables feeding into Salt that this # matters, there's probably an issue... function add-to-env { ${KUBE_ROOT}/cluster/gce/kube-env.py \"$1\" \"$2\" \"$3\" # TODO(zmerlynn): Note that this function doesn't so much \"quote\" as # \"strip out quotes\", and we really should be using a YAML library for # this, but PyYAML isn't shipped by default, and *rant rant rant ... SIGH* function yaml-quote { echo \"'$(echo \"${@}\" | sed -e \"s/'/''/g\")'\" } # $1: if 'true', we're building a master yaml, else a node"} {"_id":"doc-en-kubernetes-201f154bc44c9202f0c580332c3bd1ca932f0b92603891f787bfba007bfc2c29","title":"","text":"local file=$2 rm -f ${file} add-to-env ${file} ENV_TIMESTAMP \"$(date -uIs)\" # Just to track it add-to-env ${file} KUBERNETES_MASTER \"${master}\" add-to-env ${file} INSTANCE_PREFIX \"${INSTANCE_PREFIX}\" add-to-env ${file} NODE_INSTANCE_PREFIX \"${NODE_INSTANCE_PREFIX}\" add-to-env ${file} SERVER_BINARY_TAR_URL \"${SERVER_BINARY_TAR_URL}\" add-to-env ${file} SALT_TAR_URL \"${SALT_TAR_URL}\" add-to-env ${file} PORTAL_NET \"${PORTAL_NET}\" add-to-env ${file} ENABLE_CLUSTER_MONITORING \"${ENABLE_CLUSTER_MONITORING:-false}\" add-to-env ${file} ENABLE_NODE_MONITORING \"${ENABLE_NODE_MONITORING:-false}\" add-to-env ${file} ENABLE_CLUSTER_LOGGING \"${ENABLE_CLUSTER_LOGGING:-false}\" add-to-env ${file} ENABLE_NODE_LOGGING \"${ENABLE_NODE_LOGGING:-false}\" add-to-env ${file} LOGGING_DESTINATION \"${LOGGING_DESTINATION:-}\" add-to-env ${file} ELASTICSEARCH_LOGGING_REPLICAS \"${ELASTICSEARCH_LOGGING_REPLICAS:-}\" add-to-env ${file} ENABLE_CLUSTER_DNS \"${ENABLE_CLUSTER_DNS:-false}\" add-to-env ${file} DNS_REPLICAS \"${DNS_REPLICAS:-}\" add-to-env ${file} DNS_SERVER_IP \"${DNS_SERVER_IP:-}\" add-to-env ${file} DNS_DOMAIN \"${DNS_DOMAIN:-}\" add-to-env ${file} MASTER_HTPASSWD \"${MASTER_HTPASSWD}\" cat >$file < if [[ \"${master}\" != \"true\" ]]; then add-to-env ${file} KUBERNETES_MASTER_NAME \"${MASTER_NAME}\" add-to-env ${file} ZONE \"${ZONE}\" add-to-env ${file} EXTRA_DOCKER_OPTS \"${EXTRA_DOCKER_OPTS}\" add-to-env ${file} ENABLE_DOCKER_REGISTRY_CACHE \"${ENABLE_DOCKER_REGISTRY_CACHE:-false}\" cat >>$file < fi }"} {"_id":"doc-en-kubernetes-b7e82026c08d08b7ae922bd0dedf613c49134c30141cb664f82610c7f9596615","title":"","text":"}) AfterEach(func() { // Remove any remaining pods from this test DeleteRC(c, ns, RCName) // Remove any remaining pods from this test if the // replication controller still exists and the replica count // isn't 0. This means the controller wasn't cleaned up // during the test so clean it up here rc, err := c.ReplicationControllers(ns).Get(RCName) if err == nil && rc.Spec.Replicas != 0 { DeleteRC(c, ns, RCName) } }) It(\"should allow starting 100 pods per node\", func() {"} {"_id":"doc-en-kubernetes-58309873e8f237c1d75ea5028283534cd2880873563fdca39be6e674447b1d47","title":"","text":"if [[ ${GOOS} == \"windows\" ]]; then bin=\"${bin}.exe\" fi CGO_ENABLED=0 go build -installsuffix cgo -o \"${output_path}/${bin}\" go build -o \"${output_path}/${bin}\" \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binary}\" done else CGO_ENABLED=0 go install -installsuffix cgo \"${goflags[@]:+${goflags[@]}}\" go install \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binaries[@]}\" fi"} {"_id":"doc-en-kubernetes-bd9574cf6ad99b1e6306ce6254b5f8778956a474927153f3bbfe683dcacb3c5a","title":"","text":"Long: create_long, Example: create_example, Run: func(cmd *cobra.Command, args []string) { err := RunCreate(f, out, cmd, filenames) cmdutil.CheckErr(err) cmdutil.CheckErr(ValidateArgs(cmd, args)) cmdutil.CheckErr(RunCreate(f, out, cmd, filenames)) }, } cmd.Flags().VarP(&filenames, \"filename\", \"f\", \"Filename, directory, or URL to file to use to create the resource\") return cmd } func ValidateArgs(cmd *cobra.Command, args []string) error { if len(args) != 0 { return cmdutil.UsageError(cmd, \"Unexpected args: %v\", args) } return nil } func RunCreate(f *Factory, out io.Writer, cmd *cobra.Command, filenames util.StringList) error { schema, err := f.Validator() if err != nil {"} {"_id":"doc-en-kubernetes-2b20a6c61d4e9761f363731d28f691dfa8bba87b3516f3f2b3e89a4955ccc1de","title":"","text":"\"testing\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd\" ) func TestExtraArgsFail(t *testing.T) { buf := bytes.NewBuffer([]byte{}) f, _, _ := NewAPIFactory() c := f.NewCmdCreate(buf) if cmd.ValidateArgs(c, []string{\"rc\"}) == nil { t.Errorf(\"unexpected non-error\") } } func TestCreateObject(t *testing.T) { _, _, rc := testData() rc.Items[0].Name = \"redis-master-controller\""} {"_id":"doc-en-kubernetes-55adb618c454a26b81e2819d723ad6d85d5aa63eb3d11cecf8557341d8b64f5b","title":"","text":"\"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/fieldpath\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/types\""} {"_id":"doc-en-kubernetes-7e0140b0adb2b675e56ed5220fc631088f563c9943191ec969ed394cf184c13b","title":"","text":"fmt.Fprintf(out, \" Ready:t%vn\", printBool(status.Ready)) fmt.Fprintf(out, \" Restart Count:t%dn\", status.RestartCount) fmt.Fprintf(out, \" Variables:n\") for _, e := range container.Env { if e.ValueFrom != nil && e.ValueFrom.FieldRef != nil { valueFrom := envValueFrom(pod, e) fmt.Fprintf(out, \" %s:t%s (%s:%s)n\", e.Name, valueFrom, e.ValueFrom.FieldRef.APIVersion, e.ValueFrom.FieldRef.FieldPath) } else { fmt.Fprintf(out, \" %s:t%sn\", e.Name, e.Value) } } } } func envValueFrom(pod *api.Pod, e api.EnvVar) string { internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(e.ValueFrom.FieldRef.APIVersion, \"Pod\", e.ValueFrom.FieldRef.FieldPath, \"\") if err != nil { return \"\" // pod validation should catch this on create } valueFrom, err := fieldpath.ExtractFieldPathAsString(pod, internalFieldPath) if err != nil { return \"\" // pod validation should catch this on create } return valueFrom } func printBool(value bool) string { if value { return \"True\""} {"_id":"doc-en-kubernetes-02014de29a0f0f2a414265e1b7b37e48c6e6d1b6a0b4125d8946ffbb2ee6b2a6","title":"","text":"}, expectedElements: []string{\"test\", \"State\", \"Waiting\", \"Ready\", \"True\", \"Restart Count\", \"7\", \"Image\", \"image\"}, }, //env { container: api.Container{Name: \"test\", Image: \"image\", Env: []api.EnvVar{{Name: \"envname\", Value: \"xyz\"}}}, status: api.ContainerStatus{ Name: \"test\", Ready: true, RestartCount: 7, }, expectedElements: []string{\"test\", \"State\", \"Waiting\", \"Ready\", \"True\", \"Restart Count\", \"7\", \"Image\", \"image\", \"envname\", \"xyz\"}, }, // Using limits. { container: api.Container{"} {"_id":"doc-en-kubernetes-9e8a193df356d1bfa4ea4013a630b82e7f28bfbc8a84ff32231370d87c7ab4d3","title":"","text":"prepare-e2e while true; do ${KUBECTL} --watch-only get events ${KUBECTL} get events --watch-only done"} {"_id":"doc-en-kubernetes-e975dad90bfbdbb52c98e5ada4e8196e527a8fc1cb30ecd4c49eadd44e414a48","title":"","text":"set -e #clean all init/init.d/configs function do_backup_clean() { #backup all config files init_files=`ls init_conf` for i in $init_files do if [ -f /etc/init/$i ] then mv /etc/init/${i} /etc/init/${i}.bak fi done initd_files=`ls initd_scripts` for i in $initd_files do if [ -f /etc/init.d/$i ] then mv /etc/init.d/${i} /etc/init.d/${i}.bak fi done default_files=`ls default_scripts` for i in $default_files do if [ -e /etc/default/$i ] then mv /etc/default/${i} /etc/default/${i}.bak fi done # clean work dir if [ ! -d ./work ] then mkdir work fi cp -rf default_scripts init_conf initd_scripts work } function cpMaster(){ # copy /etc/init files cp init_conf/etcd.conf /etc/init/ cp init_conf/kube-apiserver.conf /etc/init/ cp init_conf/kube-controller-manager.conf /etc/init/ cp init_conf/kube-scheduler.conf /etc/init/ cp work/init_conf/etcd.conf /etc/init/ cp work/init_conf/kube-apiserver.conf /etc/init/ cp work/init_conf/kube-controller-manager.conf /etc/init/ cp work/init_conf/kube-scheduler.conf /etc/init/ # copy /etc/initd/ files cp initd_scripts/etcd /etc/init.d/ cp initd_scripts/kube-apiserver /etc/init.d/ cp initd_scripts/kube-controller-manager /etc/init.d/ cp initd_scripts/kube-scheduler /etc/init.d/ cp work/initd_scripts/etcd /etc/init.d/ cp work/initd_scripts/kube-apiserver /etc/init.d/ cp work/initd_scripts/kube-controller-manager /etc/init.d/ cp work/initd_scripts/kube-scheduler /etc/init.d/ # copy default configs cp default_scripts/etcd /etc/default/ cp default_scripts/kube-apiserver /etc/default/ cp default_scripts/kube-scheduler /etc/default/ cp default_scripts/kube-controller-manager /etc/default/ cp work/default_scripts/etcd /etc/default/ cp work/default_scripts/kube-apiserver /etc/default/ cp work/default_scripts/kube-scheduler /etc/default/ cp work/default_scripts/kube-controller-manager /etc/default/ } function cpMinion(){ # copy /etc/init files cp init_conf/etcd.conf /etc/init/ cp init_conf/kubelet.conf /etc/init/ cp init_conf/flanneld.conf /etc/init/ cp init_conf/kube-proxy.conf /etc/init/ cp work/init_conf/etcd.conf /etc/init/etcd.conf cp work/init_conf/kubelet.conf /etc/init/kubelet.conf cp work/init_conf/flanneld.conf /etc/init/flanneld.conf cp work/init_conf/kube-proxy.conf /etc/init/ # copy /etc/initd/ files cp initd_scripts/etcd /etc/init.d/ cp initd_scripts/flanneld /etc/init.d/ cp initd_scripts/kubelet /etc/init.d/ cp initd_scripts/kube-proxy /etc/init.d/ cp work/initd_scripts/etcd /etc/init.d/ cp work/initd_scripts/flanneld /etc/init.d/ cp work/initd_scripts/kubelet /etc/init.d/ cp work/initd_scripts/kube-proxy /etc/init.d/ # copy default configs cp default_scripts/etcd /etc/default/ cp default_scripts/flanneld /etc/default/ cp default_scripts/kube-proxy /etc/default cp default_scripts/kubelet /etc/default/ cp work/default_scripts/etcd /etc/default/ cp work/default_scripts/flanneld /etc/default/ cp work/default_scripts/kube-proxy /etc/default cp work/default_scripts/kubelet /etc/default/ } # check if input IP in machine list"} {"_id":"doc-en-kubernetes-c3f55efe3425f8ef060adea78459a8f53b1837b141c8847aee79f335f27288fc","title":"","text":"# set values in ETCD_OPTS function configEtcd(){ echo ETCD_OPTS=\"-name $1 -initial-advertise-peer-urls http://$2:2380 -listen-peer-urls http://$2:2380 -initial-cluster-token etcd-cluster-1 -initial-cluster $3 -initial-cluster-state new\" > default_scripts/etcd echo ETCD_OPTS=\"-name $1 -initial-advertise-peer-urls http://$2:2380 -listen-peer-urls http://$2:2380 -initial-cluster-token etcd-cluster-1 -initial-cluster $3 -initial-cluster-state new\" > work/default_scripts/etcd } # check root"} {"_id":"doc-en-kubernetes-812ec79a6bd78f20a26ce3b04f209423fdb37485a8e6c9881dceb80bfa3fc595","title":"","text":"exit 1 fi do_backup_clean # use an array to record name and ip declare -A mm"} {"_id":"doc-en-kubernetes-d6af49864b448cae688f1a60d2c69989f017e30d96eb1231a3a4a77b126f0f19","title":"","text":"inList $etcdName $myIP configEtcd $etcdName $myIP $cluster # For minion set MINION IP in default_scripts/kubelet sed -i \"s/MY_IP/${myIP}/g\" default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" default_scripts/kube-proxy sed -i \"s/MY_IP/${myIP}/g\" work/default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" work/default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" work/default_scripts/kube-proxy # For master set MINION IPs in kube-controller-manager if [ -z \"$minionIPs\" ]; then if [ -z \"$minionIPs\" ]; then #one node act as both minion and master role minionIPs=\"$myIP\" else minionIPs=\"$minionIPs,$myIP\" fi sed -i \"s/MINION_IPS/${minionIPs}/g\" default_scripts/kube-controller-manager sed -i \"s/MINION_IPS/${minionIPs}/g\" work/default_scripts/kube-controller-manager cpMaster cpMinion"} {"_id":"doc-en-kubernetes-4afcefe0ca2b044b6524699f58ae6ce87ec27228fea0b8c4f35c2293ed5c6e88","title":"","text":"inList $etcdName $myIP configEtcd $etcdName $myIP $cluster # set MINION IPs in kube-controller-manager sed -i \"s/MINION_IPS/${minionIPs}/g\" default_scripts/kube-controller-manager sed -i \"s/MINION_IPS/${minionIPs}/g\" work/default_scripts/kube-controller-manager cpMaster break ;;"} {"_id":"doc-en-kubernetes-2c601d9f2c3147613313dedca542b379b32579defaa05386c4c9a6c55cc0e99a","title":"","text":"inList $etcdName $myIP configEtcd $etcdName $myIP $cluster # set MINION IP in default_scripts/kubelet sed -i \"s/MY_IP/${myIP}/g\" default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" default_scripts/kube-proxy sed -i \"s/MY_IP/${myIP}/g\" work/default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" work/default_scripts/kubelet sed -i \"s/MASTER_IP/${masterIP}/g\" work/default_scripts/kube-proxy cpMinion break ;;"} {"_id":"doc-en-kubernetes-a79510632547bcd2f868e1f4f3b2b6d160275c9da772868c7aaa29bd931b6abd","title":"","text":"# Find all of the built client binaries local platform platforms platforms=($(cd \"${LOCAL_OUTPUT_BINPATH}\" ; echo */*)) for platform in \"${platforms[@]}\"; do for platform in \"${platforms[@]}\" ; do local platform_tag=${platform///-} # Replace a \"/\" for a \"-\" kube::log::status \"Starting tarball: client $platform_tag\" kube::log::status \"Building tarball: client $platform_tag\" ( local release_stage=\"${RELEASE_STAGE}/client/${platform_tag}/kubernetes\" rm -rf \"${release_stage}\" mkdir -p \"${release_stage}/client/bin\" local release_stage=\"${RELEASE_STAGE}/client/${platform_tag}/kubernetes\" rm -rf \"${release_stage}\" mkdir -p \"${release_stage}/client/bin\" local client_bins=(\"${KUBE_CLIENT_BINARIES[@]}\") if [[ \"${platform%/*}\" == \"windows\" ]]; then client_bins=(\"${KUBE_CLIENT_BINARIES_WIN[@]}\") fi local client_bins=(\"${KUBE_CLIENT_BINARIES[@]}\") if [[ \"${platform%/*}\" == \"windows\" ]]; then client_bins=(\"${KUBE_CLIENT_BINARIES_WIN[@]}\") fi # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # KUBE_CLIENT_BINARIES array. cp \"${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \"${release_stage}/client/bin/\" # This fancy expression will expand to prepend a path # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the # KUBE_CLIENT_BINARIES array. cp \"${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \"${release_stage}/client/bin/\" kube::release::clean_cruft kube::release::clean_cruft local package_name=\"${RELEASE_DIR}/kubernetes-client-${platform_tag}.tar.gz\" kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\" ) & local package_name=\"${RELEASE_DIR}/kubernetes-client-${platform_tag}.tar.gz\" kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\" done kube::log::status \"Waiting on tarballs\" wait || { kube::log::error \"client tarball creation failed\"; exit 1; } } # Package up all of the server binaries"} {"_id":"doc-en-kubernetes-91c850c1e07e01a691a7fa3ee4bd48c0fb218874d392948e7f48bf8c66e8acc4","title":"","text":"local binaries binaries=($(kube::golang::binaries_from_targets \"${targets[@]}\")) kube::log::status \"Building go targets for ${platforms[@]} in parallel (output will appear in a burst when complete):\" \"${targets[@]}\" local platform for platform in \"${platforms[@]}\"; do ( kube::golang::set_platform_envs \"${platform}\" kube::log::status \"${platform}: Parallel go build started\" for platform in \"${platforms[@]}\"; do kube::golang::set_platform_envs \"${platform}\" kube::log::status \"Building go targets for ${platform}:\" \"${targets[@]}\" local -a statics=() local -a nonstatics=() for binary in \"${binaries[@]}\"; do if kube::golang::is_statically_linked_library \"${binary}\"; then kube::golang::exit_if_stdlib_not_installed; statics+=($binary) else nonstatics+=($binary) fi done if [[ -n ${use_go_build:-} ]]; then # Try and replicate the native binary placement of go install without # calling go install. This means we have to iterate each binary. local output_path=\"${KUBE_GOPATH}/bin\" if [[ $platform != $host_platform ]]; then output_path=\"${output_path}/${platform////_}\" fi local -a statics=() local -a nonstatics=() for binary in \"${binaries[@]}\"; do local bin=$(basename \"${binary}\") if [[ ${GOOS} == \"windows\" ]]; then bin=\"${bin}.exe\" fi if kube::golang::is_statically_linked_library \"${binary}\"; then kube::golang::exit_if_stdlib_not_installed; statics+=($binary) CGO_ENABLED=0 go build -installsuffix cgo -o \"${output_path}/${bin}\" \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binary}\" else nonstatics+=($binary) go build -o \"${output_path}/${bin}\" \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binary}\" fi done if [[ -n ${use_go_build:-} ]]; then # Try and replicate the native binary placement of go install without # calling go install. This means we have to iterate each binary. local output_path=\"${KUBE_GOPATH}/bin\" if [[ $platform != $host_platform ]]; then output_path=\"${output_path}/${platform////_}\" fi for binary in \"${binaries[@]}\"; do local bin=$(basename \"${binary}\") if [[ ${GOOS} == \"windows\" ]]; then bin=\"${bin}.exe\" fi if kube::golang::is_statically_linked_library \"${binary}\"; then kube::golang::exit_if_stdlib_not_installed; CGO_ENABLED=0 go build -installsuffix cgo -o \"${output_path}/${bin}\" \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binary}\" else go build -o \"${output_path}/${bin}\" \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${binary}\" fi done else else # Use go install. if [[ \"${#nonstatics[@]}\" != 0 ]]; then go install \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${nonstatics[@]:+${nonstatics[@]}}\" -ldflags \"${version_ldflags}\" \"${nonstatics[@]:+${nonstatics[@]}}\" fi if [[ \"${#statics[@]}\" != 0 ]]; then CGO_ENABLED=0 go install -installsuffix cgo \"${goflags[@]:+${goflags[@]}}\" -ldflags \"${version_ldflags}\" \"${statics[@]:+${statics[@]}}\" \"${statics[@]:+${statics[@]}}\" fi fi kube::log::status \"${platform}: Parallel go build finished\" ) &> \"/tmp//${platform////_}.build\" & done local fails=0 for job in $(jobs -p); do wait ${job} || let \"fails+=1\" done for platform in \"${platforms[@]}\"; do cat \"/tmp//${platform////_}.build\" fi done exit ${fails} ) }"} {"_id":"doc-en-kubernetes-50684054c414d231b8add9848022cbf279892463352e9810c7a87b588b2a5b73","title":"","text":"// and keep accepting inbound traffic. outConn, err := net.DialTimeout(protocol, endpoint, retryTimeout*time.Second) if err != nil { if isTooManyFDsError(err) { panic(\"Dial failed: \" + err.Error()) } glog.Errorf(\"Dial failed: %v\", err) continue }"} {"_id":"doc-en-kubernetes-7767954c4cde002343b86692dfa0b3abf59cfa5845ab461a7ea43a5fc0d6d8e3","title":"","text":"// Then the service port was just closed so the accept failure is to be expected. break } if isTooManyFDsError(err) { panic(\"Accept failed: \" + err.Error()) } glog.Errorf(\"Accept failed: %v\", err) continue }"} {"_id":"doc-en-kubernetes-acf0e201525d6f4350e2e149ccd9386c478ad0397cfd8ea4fa5953a0bc9793d7","title":"","text":"args = append(args, \"-j\", \"DNAT\", \"--to-destination\", net.JoinHostPort(proxyIP.String(), strconv.Itoa(proxyPort))) return args } func isTooManyFDsError(err error) bool { return strings.Contains(err.Error(), \"too many open files\") } "} {"_id":"doc-en-kubernetes-260b668b9d2b5c332fb8f3aeaac028820db6c03d956dc3c419ea356d5d6a10fe","title":"","text":" // +build integration,!no-etcd /* Copyright 2015 Google Inc. 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. */ package integration // This file tests the scheduler. import ( \"net/http\" \"net/http/httptest\" \"testing\" \"time\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client/record\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/master\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/util/wait\" \"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/admission/admit\" \"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler\" _ \"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/algorithmprovider\" \"github.com/GoogleCloudPlatform/kubernetes/plugin/pkg/scheduler/factory\" ) func init() { requireEtcd() } func TestUnschedulableNodes(t *testing.T) { helper, err := master.NewEtcdHelper(newEtcdClient(), testapi.Version()) if err != nil { t.Fatalf(\"Couldn't create etcd helper: %v\", err) } deleteAllEtcdKeys() var m *master.Master s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { m.Handler.ServeHTTP(w, req) })) defer s.Close() m = master.New(&master.Config{ EtcdHelper: helper, KubeletClient: client.FakeKubeletClient{}, EnableLogsSupport: false, EnableUISupport: false, EnableIndex: true, APIPrefix: \"/api\", Authorizer: apiserver.NewAlwaysAllowAuthorizer(), AdmissionControl: admit.NewAlwaysAdmit(), }) client := client.NewOrDie(&client.Config{Host: s.URL, Version: testapi.Version()}) schedulerConfigFactory := factory.NewConfigFactory(client) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { t.Fatalf(\"Couldn't create scheduler config: %v\", err) } eventBroadcaster := record.NewBroadcaster() schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: \"scheduler\"}) eventBroadcaster.StartRecordingToSink(client.Events(\"\")) scheduler.New(schedulerConfig).Run() defer close(schedulerConfig.StopEverything) DoTestUnschedulableNodes(t, client) } func podScheduled(c *client.Client, podNamespace, podName string) wait.ConditionFunc { return func() (bool, error) { pod, err := c.Pods(podNamespace).Get(podName) if errors.IsNotFound(err) { return false, nil } if err != nil { // This could be a connection error so we want to retry. return false, nil } if pod.Spec.Host == \"\" { return false, nil } return true, nil } } func DoTestUnschedulableNodes(t *testing.T, client *client.Client) { node := &api.Node{ ObjectMeta: api.ObjectMeta{Name: \"node\"}, Spec: api.NodeSpec{Unschedulable: true}, } if _, err := client.Nodes().Create(node); err != nil { t.Fatalf(\"Failed to create node: %v\", err) } pod := &api.Pod{ ObjectMeta: api.ObjectMeta{Name: \"my-pod\"}, Spec: api.PodSpec{ Containers: []api.Container{{Name: \"container\", Image: \"kubernetes/pause:go\"}}, }, } myPod, err := client.Pods(api.NamespaceDefault).Create(pod) if err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } // There are no schedulable nodes - the pod shouldn't be scheduled. err = wait.Poll(time.Second, time.Second*10, podScheduled(client, myPod.Namespace, myPod.Name)) if err == nil { t.Errorf(\"Pod scheduled successfully on unschedulable nodes\") } if err != wait.ErrWaitTimeout { t.Errorf(\"Failed while waiting for scheduled pod: %v\", err) } // Make the node schedulable and wait until the pod is scheduled. newNode, err := client.Nodes().Get(node.Name) if err != nil { t.Fatalf(\"Failed to get node: %v\", err) } newNode.Spec.Unschedulable = false if _, err = client.Nodes().Update(newNode); err != nil { t.Fatalf(\"Failed to update node: %v\", err) } err = wait.Poll(time.Second, time.Second*10, podScheduled(client, myPod.Namespace, myPod.Name)) if err != nil { t.Errorf(\"Failed to schedule a pod: %v\", err) } err = client.Pods(api.NamespaceDefault).Delete(myPod.Name) if err != nil { t.Errorf(\"Failed to delete pod: %v\", err) } } "} {"_id":"doc-en-kubernetes-596f366fa566bc20994b853c1e31f6139b85be55792a1a4bd36a7dbc1640b5f7","title":"","text":"if [[ \"${TRAVIS:-}\" != \"true\" ]]; then local go_version go_version=($(go version)) if [[ \"${go_version[2]}\" < \"go1.6\" ]]; then if [[ \"${go_version[2]}\" < \"go1.6\" && \"${go_version[2]}\" != \"devel\" ]]; then kube::log::usage_from_stdin < var ip net.IP for i = range intfs { if flagsSet(intfs[i].Flags, net.FlagUp) && flagsClear(intfs[i].Flags, net.FlagLoopback|net.FlagPointToPoint) { addrs, err := intfs[i].Addrs()"} {"_id":"doc-en-kubernetes-75266255fad9538b91757d14d8c1567d65eaf6e6a3c40bb991c0c47926346f38","title":"","text":"return nil, err } if len(addrs) > 0 { // This interface should suffice. break for _, addr := range addrs { if addrIP, _, err := net.ParseCIDR(addr.String()); err == nil { if addrIP.To4() != nil { ip = addrIP.To4() break } } } if ip != nil { // This interface should suffice. break } } } } if i == len(intfs) { return nil, err if ip == nil { return nil, fmt.Errorf(\"no acceptable interface from host\") } glog.V(4).Infof(\"Choosing interface %s for from-host portals\", intfs[i].Name) addrs, err := intfs[i].Addrs() if err != nil { return nil, err } glog.V(4).Infof(\"Interface %s = %s\", intfs[i].Name, addrs[0].String()) ip, _, err := net.ParseCIDR(addrs[0].String()) if err != nil { return nil, err } return ip, nil }"} {"_id":"doc-en-kubernetes-050caf3e2e99eef829227dc2c2ddb069f28b920f81d8423a261f6fd9c0c2006a","title":"","text":"``` ### NFS Kubernetes NFS volumes allow an existing NFS share to be made available to containers within a pod. Kubernetes NFS volumes allow an existing NFS share to be made available to containers within a pod. [The NFS Pod example](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/examples/nfs/test.yaml) demonstrates how to specify the usage of an NFS volume within a pod. In this example one can see that a volumeMount called \"myshare\" is being mounted onto /var/www/html/mount-test in the container \"testpd\". The volume \"myshare\" is defined as type nfs, with the NFS server serving from 172.17.0.2 and exporting directory /tmp as the share. The mount being created in this example is not read only. See the [NFS Pod examples](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/examples/nfs/) section for more details. For example, [nfs-web-pod.yaml](https://github.com/GoogleCloudPlatform/kubernetes/blob/master/examples/nfs/nfs-web-pod.yaml) demonstrates how to specify the usage of an NFS volume within a pod. In this example one can see that a `volumeMount` called \"nfs\" is being mounted onto `/var/www/html` in the container \"web\". The volume \"nfs\" is defined as type `nfs`, with the NFS server serving from `nfs-server.default.kube.local` and exporting directory `/` as the share. The mount being created in this example is not read only. "} {"_id":"doc-en-kubernetes-e4f58e4b7a862534312ba345ab6d640436d14dc67e467517089a02f9d5bfc152","title":"","text":"### SEE ALSO * [kubectl](kubectl.md)\t - kubectl controls the Kubernetes cluster manager ###### Auto generated by spf13/cobra at 2015-05-28 22:43:52.329286408 +0000 UTC ###### Auto generated by spf13/cobra at 2015-05-29 22:39:51.164275749 +0000 UTC [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/kubectl_get.md?pixel)]()"} {"_id":"doc-en-kubernetes-5edace254f08e58752c404b036dfb6ee60c1e0ea40591a7ecf8e7ec9532ea243","title":"","text":".PP Possible resources include pods (po), replication controllers (rc), services (svc), nodes, events (ev), component statuses (cs), limit ranges (limits), minions (mi), persistent volumes (pv), persistent volume claims (pvc) nodes (no), persistent volumes (pv), persistent volume claims (pvc) or resource quotas (quota). .PP"} {"_id":"doc-en-kubernetes-11fb5f6d850507b6a82b2c54887356dcb21d421828bfcaefb66fed6338f9f44c","title":"","text":"-s \"http://127.0.0.1:${API_PORT}\" --match-server-version ) [ \"$(kubectl get minions -t '{{ .apiVersion }}' \"${kube_flags[@]}\")\" == \"v1beta3\" ] [ \"$(kubectl get nodes -t '{{ .apiVersion }}' \"${kube_flags[@]}\")\" == \"v1beta3\" ] else kube_flags=( -s \"http://127.0.0.1:${API_PORT}\" --match-server-version --api-version=\"${version}\" ) [ \"$(kubectl get minions -t '{{ .apiVersion }}' \"${kube_flags[@]}\")\" == \"${version}\" ] [ \"$(kubectl get nodes -t '{{ .apiVersion }}' \"${kube_flags[@]}\")\" == \"${version}\" ] fi id_field=\".metadata.name\" labels_field=\".metadata.labels\""} {"_id":"doc-en-kubernetes-373fbcb6c635a1730311b8b29da0ce7d157c512b56ba6337d835bbb43526f8ff","title":"","text":"########### # Minions # # Nodes # ########### if [[ \"${version}\" = \"v1beta1\" ]] || [[ \"${version}\" = \"v1beta2\" ]]; then kube::log::status \"Testing kubectl(${version}:minions)\" kube::log::status \"Testing kubectl(${version}:nodes)\" kube::test::get_object_assert minions \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:' kube::test::get_object_assert nodes \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:' # TODO: I should be a MinionList instead of List kube::test::get_object_assert minions '{{.kind}}' 'List' kube::test::get_object_assert nodes '{{.kind}}' 'List' kube::test::describe_object_assert minions \"127.0.0.1\" \"Name:\" \"Conditions:\" \"Addresses:\" \"Capacity:\" \"Pods:\" kube::test::describe_object_assert nodes \"127.0.0.1\" \"Name:\" \"Conditions:\" \"Addresses:\" \"Capacity:\" \"Pods:\" fi"} {"_id":"doc-en-kubernetes-31d209e72dad7742ce7ae39094ed6a725364ef95953f545dd1a79c598fdf3390","title":"","text":"Possible resources include pods (po), replication controllers (rc), services (svc), nodes, events (ev), component statuses (cs), limit ranges (limits), minions (mi), persistent volumes (pv), persistent volume claims (pvc) nodes (no), persistent volumes (pv), persistent volume claims (pvc) or resource quotas (quota). By specifying the output as 'template' and providing a Go template as the value"} {"_id":"doc-en-kubernetes-9be9663761a30770865e969996625f788e367bfef5f07697b998efc931518e1b","title":"","text":"package kubectl import ( \"fmt\" \"strings\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\""} {"_id":"doc-en-kubernetes-986dd50f306549cf13b0a81b2591589f83bae94cbb57d028e4443b74ee873967","title":"","text":"// mapper. func (e ShortcutExpander) VersionAndKindForResource(resource string) (defaultVersion, kind string, err error) { resource = expandResourceShortcut(resource) return e.RESTMapper.VersionAndKindForResource(resource) defaultVersion, kind, err = e.RESTMapper.VersionAndKindForResource(resource) // TODO: remove this once v1beta1 and v1beta2 are deprecated if err == nil && kind == \"Minion\" { err = fmt.Errorf(\"Alias minion(s) is deprecated. Use node(s) instead\") } return defaultVersion, kind, err } // expandResourceShortcut will return the expanded version of resource"} {"_id":"doc-en-kubernetes-eef61060f7789c86d573dc6fe3e70030b26d4c3881aae95e29d71713faab7570","title":"","text":"\"cs\": \"componentstatuses\", \"ev\": \"events\", \"limits\": \"limitRanges\", \"mi\": \"minions\", \"no\": \"nodes\", \"po\": \"pods\", \"pv\": \"persistentVolumes\", \"pvc\": \"persistentVolumeClaims\","} {"_id":"doc-en-kubernetes-da62bf18bfaf57b7720326dad878c6948bcea64b3eac24e91547b344597e9159","title":"","text":"// implementation of the error interface func (f *FitError) Error() string { output := fmt.Sprintf(\"failed to find fit for pod: %v\", f.Pod) output := fmt.Sprintf(\"failed to find fit for pod, \") for node, predicateList := range f.FailedPredicates { output = output + fmt.Sprintf(\"Node %s: %s\", node, strings.Join(predicateList.List(), \",\")) }"} {"_id":"doc-en-kubernetes-d128b45c8e928fa1fd4466b7d39f18fa4558800ffcce9d4a0f1937d1380e0872","title":"","text":"- `kubectl config set-cluster $CLUSTER_NAME --server=http://$MASTER_IP --insecure-skip-tls-verify=true` - Otherwise, do this to set the apiserver ip, client certs, and user credentials. - `kubectl config set-cluster $CLUSTER_NAME --certificate-authority=$CA_CERT --embed-certs=true --server=https://$MASTER_IP` - `kubectl config set-credentials $CLUSTER_NAME --client-certificate=$CLI_CERT --client-key=$CLI_KEY --embed-certs=true --token=$TOKEN` - `kubectl config set-credentials $USER --client-certificate=$CLI_CERT --client-key=$CLI_KEY --embed-certs=true --token=$TOKEN` - Set your cluster as the default cluster to use: - `kubectl config set-context $CLUSTER_NAME --cluster=$CLUSTER_NAME --user=admin` - `kubectl config use-context $CONTEXT --cluster=$CONTEXT` - `kubectl config set-context $CONTEXT_NAME --cluster=$CLUSTER_NAME --user=$USER` - `kubectl config use-context $CONTEXT_NAME` Next, make a kubeconfig file for the kubelets and kube-proxy. There are a couple of options for how many distinct files to make:"} {"_id":"doc-en-kubernetes-60c2f67364227f41744e421d2501cf12e8f5450e249650348658ea9b55bb1115","title":"","text":"continue } instance, err := s.getInstanceById(instanceID) if err != nil { return nil, err } instanceName := orEmpty(instance.PrivateDNSName) routeName := clusterName + \"-\" + destinationCIDR routes = append(routes, &cloudprovider.Route{routeName, instanceID, destinationCIDR}) routes = append(routes, &cloudprovider.Route{routeName, instanceName, destinationCIDR}) } return routes, nil"} {"_id":"doc-en-kubernetes-42589122f09f7acb8f52967b1e8cf7978f820445514ee3daed96eeac483b1f77","title":"","text":"for _, volumeKindDir := range volumeKindDirs { volumeKind := volumeKindDir.Name() volumeKindPath := path.Join(podVolDir, volumeKind) volumeNameDirs, err := ioutil.ReadDir(volumeKindPath) // ioutil.ReadDir exits without returning any healthy dir when encountering the first lstat error // but skipping dirs means no cleanup for healthy volumes. switching to a no-exit api solves this problem volumeNameDirs, volumeNameDirsStat, err := util.ReadDirNoExit(volumeKindPath) if err != nil { return []*volumeTuple{}, fmt.Errorf(\"could not read directory %s: %v\", volumeKindPath, err) } for _, volumeNameDir := range volumeNameDirs { volumes = append(volumes, &volumeTuple{Kind: volumeKind, Name: volumeNameDir.Name()}) for i, volumeNameDir := range volumeNameDirs { if volumeNameDir != nil { volumes = append(volumes, &volumeTuple{Kind: volumeKind, Name: volumeNameDir.Name()}) } else { lerr := volumeNameDirsStat[i] glog.Errorf(\"Could not read directory %s: %v\", podVolDir, lerr) } } } return volumes, nil"} {"_id":"doc-en-kubernetes-733ebd6433db6c8caa06952a50b5dd20d52087dcdedcaa6ee0a5c614d47a56dd","title":"","text":"} return true, nil } // borrowed from ioutil.ReadDir // ReadDir reads the directory named by dirname and returns // a list of directory entries, minus those with lstat errors func ReadDirNoExit(dirname string) ([]os.FileInfo, []error, error) { if dirname == \"\" { dirname = \".\" } f, err := os.Open(dirname) if err != nil { return nil, nil, err } defer f.Close() names, err := f.Readdirnames(-1) list := make([]os.FileInfo, 0, len(names)) errs := make([]error, 0, len(names)) for _, filename := range names { fip, lerr := os.Lstat(dirname + \"/\" + filename) if os.IsNotExist(lerr) { // File disappeared between readdir + stat. // Just treat it as if it didn't exist. continue } list = append(list, fip) errs = append(errs, lerr) } return list, errs, nil } "} {"_id":"doc-en-kubernetes-30fd36080570400a5bd5a4775071988acc60c367defb35e1dbf9ea702c769db7","title":"","text":"{% set test_args=pillar['kubeproxy_test_args'] %} {% endif -%} DAEMON_ARGS=\"{{daemon_args}} {{api_servers_with_port}} {{kubeconfig}} {{pillar['log_level']}}\" # test_args has to be kept at the end, so they'll overwrite any prior configuration DAEMON_ARGS=\"$DAEMON_ARGS + {{test_args}}\" DAEMON_ARGS=\"{{daemon_args}} {{api_servers_with_port}} {{kubeconfig}} {{pillar['log_level']}} {{test_args}}\" "} {"_id":"doc-en-kubernetes-bbfff21d8c56879968be7d3b8694f86aa7859da6cdb5b6b8c354fb6705322598","title":"","text":"{% set test_args=pillar['kubelet_test_args'] %} {% endif -%} DAEMON_ARGS=\"{{daemon_args}} {{api_servers_with_port}} {{debugging_handlers}} {{hostname_override}} {{cloud_provider}} {{config}} {{manifest_url}} --allow_privileged={{pillar['allow_privileged']}} {{pillar['log_level']}} {{cluster_dns}} {{cluster_domain}} {{docker_root}} {{kubelet_root}} {{configure_cbr0}} {{cgroup_root}} {{system_container}} {{pod_cidr}}\" # test_args has to be kept at the end, so they'll overwrite any prior configuration DAEMON_ARGS=\"$DAEMON_ARGS + {{test_args}}\" DAEMON_ARGS=\"{{daemon_args}} {{api_servers_with_port}} {{debugging_handlers}} {{hostname_override}} {{cloud_provider}} {{config}} {{manifest_url}} --allow_privileged={{pillar['allow_privileged']}} {{pillar['log_level']}} {{cluster_dns}} {{cluster_domain}} {{docker_root}} {{kubelet_root}} {{configure_cbr0}} {{cgroup_root}} {{system_container}} {{pod_cidr}} {{test_args}}\" "} {"_id":"doc-en-kubernetes-eae2ace7fdeeebb19b4e7abea2eb1203e3ce5810d89b901ea12b04d831fb92ba","title":"","text":"\"os\" \"time\" kube_client \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/registry\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/util\" \"github.com/coreos/go-etcd/etcd\""} {"_id":"doc-en-kubernetes-6d81e9a50fa6ef480d54794529ad8406e86eb8c1559dfd6df7fea99fcf335386","title":"","text":"etcd.SetLogger(log.New(os.Stderr, \"etcd \", log.LstdFlags)) controllerManager := registry.MakeReplicationManager(etcd.NewClient([]string{*etcd_servers}), kube_client.Client{ client.Client{ Host: \"http://\" + *master, })"} {"_id":"doc-en-kubernetes-e41a8ac7da5c4913e3b1afba2f468684e76804d65c752d5f81360a994582f75e","title":"","text":"var ( file = flag.String(\"config\", \"\", \"Path to the config file\") etcd_servers = flag.String(\"etcd_servers\", \"\", \"Url of etcd servers in the cluster\") etcdServers = flag.String(\"etcd_servers\", \"\", \"Url of etcd servers in the cluster\") syncFrequency = flag.Duration(\"sync_frequency\", 10*time.Second, \"Max period between synchronizing running containers and config\") fileCheckFrequency = flag.Duration(\"file_check_frequency\", 20*time.Second, \"Duration between checking file for new data\") httpCheckFrequency = flag.Duration(\"http_check_frequency\", 20*time.Second, \"Duration between checking http for new data\") manifest_url = flag.String(\"manifest_url\", \"\", \"URL for accessing the container manifest\") manifestUrl = flag.String(\"manifest_url\", \"\", \"URL for accessing the container manifest\") address = flag.String(\"address\", \"127.0.0.1\", \"The address for the info server to serve on\") port = flag.Uint(\"port\", 10250, \"The port for the info server to serve on\") hostnameOverride = flag.String(\"hostname_override\", \"\", \"If non-empty, will use this string as identification instead of the actual hostname.\") ) const dockerBinary = \"/usr/bin/docker\""} {"_id":"doc-en-kubernetes-2a18d895358c72e58c2762392f6dc264ab9dc1f77a39ac5e5d1d36dae51d1f0b","title":"","text":"log.Fatal(\"Couldn't connnect to docker.\") } hostname, err := exec.Command(\"hostname\", \"-f\").Output() if err != nil { log.Fatalf(\"Couldn't determine hostname: %v\", err) hostname := []byte(*hostnameOverride) if string(hostname) == \"\" { hostname, err = exec.Command(\"hostname\", \"-f\").Output() if err != nil { log.Fatalf(\"Couldn't determine hostname: %v\", err) } } my_kubelet := kubelet.Kubelet{"} {"_id":"doc-en-kubernetes-db13024817c4ac5f84137d799d7e696f88964c989339aa2705d1d064f1df8c84","title":"","text":"SyncFrequency: *syncFrequency, HTTPCheckFrequency: *httpCheckFrequency, } my_kubelet.RunKubelet(*file, *manifest_url, *etcd_servers, *address, *port) my_kubelet.RunKubelet(*file, *manifestUrl, *etcdServers, *address, *port) }"} {"_id":"doc-en-kubernetes-477ce19e1526b0fc2d957f0dab10393085d235078b6c8db61b1651688fe1d0ab","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. # This command builds and runs a local kubernetes cluster. It's just like # local-up.sh, but this one launches the three separate binaries. # You may need to run this as root to allow kubelet to open docker's socket. if [ \"$(which etcd)\" == \"\" ]; then echo \"etcd must be in your PATH\" exit 1 fi # Stop right away if the build fails set -e $(dirname $0)/build-go.sh echo \"Starting etcd\" ETCD_DIR=$(mktemp -d -t kube-integration.XXXXXX) trap \"rm -rf ${ETCD_DIR}\" EXIT etcd -name test -data-dir ${ETCD_DIR} &> /tmp/etcd.log & ETCD_PID=$! sleep 5 # Shut down anyway if there's an error. set +e API_PORT=8080 KUBELET_PORT=10250 $(dirname $0)/../output/go/apiserver --address=\"127.0.0.1\" --port=\"${API_PORT}\" --etcd_servers=\"http://127.0.0.1:4001\" --machines=\"127.0.0.1\" &> /tmp/apiserver.log & APISERVER_PID=$! $(dirname $0)/../output/go/controller-manager --etcd_servers=\"http://127.0.0.1:4001\" --master=\"127.0.0.1:${API_PORT}\" &> /tmp/controller-manager.log & CTLRMGR_PID=$! $(dirname $0)/../output/go/kubelet --etcd_servers=\"http://127.0.0.1:4001\" --hostname_override=\"127.0.0.1\" --address=\"127.0.0.1\" --port=\"$KUBELET_PORT\" &> /tmp/kubelet.log & KUBELET_PID=$! echo \"Local Kubernetes cluster is running. Press enter to shut it down.\" read unused kill ${APISERVER_PID} kill ${CTLRMGR_PID} kill ${KUBELET_PID} kill ${ETCD_PID} "} {"_id":"doc-en-kubernetes-5d15153d6f31aa68a28ecc649d99667226f4b39319938d289c6cd6203a64844f","title":"","text":"flag.StringVar(&testContext.OutputPrintType, \"output-print-type\", \"hr\", \"Comma separated list: 'hr' for human readable summaries 'json' for JSON ones.\") } func TestE2E(t *testing.T) { util.ReallyCrash = true util.InitLogs() defer util.FlushLogs() if testContext.ReportDir != \"\" { if err := os.MkdirAll(testContext.ReportDir, 0755); err != nil { glog.Errorf(\"Failed creating report directory: %v\", err) } defer CoreDump(testContext.ReportDir) } if testContext.Provider == \"\" { // setupProviderConfig validates and sets up cloudConfig based on testContext.Provider. func setupProviderConfig() error { switch testContext.Provider { case \"\": glog.Info(\"The --provider flag is not set. Treating as a conformance test. Some tests may not be run.\") } if testContext.Provider == \"gce\" || testContext.Provider == \"gke\" { case \"gce\", \"gke\": var err error Logf(\"Fetching cloud provider for %qrn\", testContext.Provider) var tokenSource oauth2.TokenSource"} {"_id":"doc-en-kubernetes-e024ecbff2aa15f58d36c31753eb16616e5ca3495eff425aea687534b5f06966","title":"","text":"zone := testContext.CloudConfig.Zone region, err := gcecloud.GetGCERegion(zone) if err != nil { glog.Fatalf(\"error parsing GCE region from zone %q: %v\", zone, err) return fmt.Errorf(\"error parsing GCE/GKE region from zone %q: %v\", zone, err) } managedZones := []string{zone} // Only single-zone for now cloudConfig.Provider, err = gcecloud.CreateGCECloud(testContext.CloudConfig.ProjectID, region, zone, managedZones, \"\" /* networkUrl */, tokenSource, false /* useMetadataServer */) if err != nil { glog.Fatal(\"Error building GCE provider: \", err) return fmt.Errorf(\"Error building GCE/GKE provider: \", err) } } if testContext.Provider == \"aws\" { case \"aws\": awsConfig := \"[Global]n\" if cloudConfig.Zone == \"\" { glog.Fatal(\"gce-zone must be specified for AWS\") return fmt.Errorf(\"gce-zone must be specified for AWS\") } awsConfig += fmt.Sprintf(\"Zone=%sn\", cloudConfig.Zone) if cloudConfig.ClusterTag == \"\" { glog.Fatal(\"--cluster-tag must be specified for AWS\") return fmt.Errorf(\"--cluster-tag must be specified for AWS\") } awsConfig += fmt.Sprintf(\"KubernetesClusterTag=%sn\", cloudConfig.ClusterTag) var err error cloudConfig.Provider, err = cloudprovider.GetCloudProvider(testContext.Provider, strings.NewReader(awsConfig)) if err != nil { glog.Fatal(\"Error building AWS provider: \", err) return fmt.Errorf(\"Error building AWS provider: \", err) } } // Disable skipped tests unless they are explicitly requested. if config.GinkgoConfig.FocusString == \"\" && config.GinkgoConfig.SkipString == \"\" { // TODO(ihmccreery) Remove [Skipped] once all [Skipped] labels have been reclassified. config.GinkgoConfig.SkipString = `[Flaky]|[Skipped]|[Feature:.+]` } gomega.RegisterFailHandler(ginkgo.Fail) c, err := loadClient() if err != nil { glog.Fatal(\"Error loading client: \", err) } return nil } // There are certain operations we only want to run once per overall test invocation // (such as deleting old namespaces, or verifying that all system pods are running. // Because of the way Ginkgo runs tests in parallel, we must use SynchronizedBeforeSuite // to ensure that these operations only run on the first parallel Ginkgo node. // // This function takes two parameters: one function which runs on only the first Ginkgo node, // returning an opaque byte array, and then a second function which runs on all Ginkgo nodes, // accepting the byte array. var _ = ginkgo.SynchronizedBeforeSuite(func() []byte { // Run only on Ginkgo node 1 // Delete any namespaces except default and kube-system. This ensures no // lingering resources are left over from a previous test run. if testContext.CleanStart { c, err := loadClient() if err != nil { glog.Fatal(\"Error loading client: \", err) } deleted, err := deleteNamespaces(c, nil /* deleteFilter */, []string{api.NamespaceSystem, api.NamespaceDefault}) if err != nil { t.Errorf(\"Error deleting orphaned namespaces: %v\", err) Failf(\"Error deleting orphaned namespaces: %v\", err) } glog.Infof(\"Waiting for deletion of the following namespaces: %v\", deleted) if err := waitForNamespacesDeleted(c, deleted, namespaceCleanupTimeout); err != nil { glog.Fatalf(\"Failed to delete orphaned namespaces %v: %v\", deleted, err) Failf(\"Failed to delete orphaned namespaces %v: %v\", deleted, err) } }"} {"_id":"doc-en-kubernetes-075fda8e83d2b1ebd32359900bdd8f68063c3c3f9a2dcc6d37dd5ecdfb817919","title":"","text":"// test pods from running, and tests that ensure all pods are running and // ready will fail). if err := waitForPodsRunningReady(api.NamespaceSystem, testContext.MinStartupPods, podStartupTimeout); err != nil { t.Errorf(\"Error waiting for all pods to be running and ready: %v\", err) return Failf(\"Error waiting for all pods to be running and ready: %v\", err) } return nil }, func(data []byte) { // Run on all Ginkgo nodes }) // Similar to SynchornizedBeforeSuite, we want to run some operations only once (such as collecting cluster logs). // Here, the order of functions is reversed; first, the function which runs everywhere, // and then the function that only runs on the first Ginkgo node. var _ = ginkgo.SynchronizedAfterSuite(func() { // Run on all Ginkgo nodes }, func() { // Run only Ginkgo on node 1 if testContext.ReportDir != \"\" { CoreDump(testContext.ReportDir) } }) // TestE2E checks configuration parameters (specified through flags) and then runs // E2E tests using the Ginkgo runner. // If a \"report directory\" is specified, one or more JUnit test reports will be // generated in this directory, and cluster logs will also be saved. // This function is called on each Ginkgo node in parallel mode. func TestE2E(t *testing.T) { util.ReallyCrash = true util.InitLogs() defer util.FlushLogs() // We must call setupProviderConfig first since SynchronizedBeforeSuite needs // cloudConfig to be set up already. if err := setupProviderConfig(); err != nil { glog.Fatalf(err.Error()) } gomega.RegisterFailHandler(ginkgo.Fail) // Disable skipped tests unless they are explicitly requested. if config.GinkgoConfig.FocusString == \"\" && config.GinkgoConfig.SkipString == \"\" { // TODO(ihmccreery) Remove [Skipped] once all [Skipped] labels have been reclassified. config.GinkgoConfig.SkipString = `[Flaky]|[Skipped]|[Feature:.+]` } // Run tests through the Ginkgo runner with output to console + JUnit for Jenkins var r []ginkgo.Reporter if testContext.ReportDir != \"\" { r = append(r, reporters.NewJUnitReporter(path.Join(testContext.ReportDir, fmt.Sprintf(\"junit_%02d.xml\", config.GinkgoConfig.ParallelNode)))) // TODO: we should probably only be trying to create this directory once // rather than once-per-Ginkgo-node. if err := os.MkdirAll(testContext.ReportDir, 0755); err != nil { glog.Errorf(\"Failed creating report directory: %v\", err) } else { r = append(r, reporters.NewJUnitReporter(path.Join(testContext.ReportDir, fmt.Sprintf(\"junit_%02d.xml\", config.GinkgoConfig.ParallelNode)))) } } glog.Infof(\"Starting e2e run; %q\", runId) glog.Infof(\"Starting e2e run %q on Ginkgo node %d\", runId, config.GinkgoConfig.ParallelNode) ginkgo.RunSpecsWithDefaultAndCustomReporters(t, \"Kubernetes e2e suite\", r) }"} {"_id":"doc-en-kubernetes-4df3b809265b898ae97976f38e0399d4e18a0f0972d78b011094da465d84e873","title":"","text":"func (runner *runner) connectToFirewallD() { bus, err := runner.dbus.SystemBus() if err != nil { glog.V(1).Info(\"Could not connect to D-Bus system bus: %s\", err) glog.V(1).Infof(\"Could not connect to D-Bus system bus: %s\", err) return }"} {"_id":"doc-en-kubernetes-9e29ca0c0ba11ebd4340e34529df31c1cc404ea426f56b90efab1ea4130f2a12","title":"","text":"// GetOriginalConfiguration retrieves the original configuration of the object // from the annotation, or nil if no annotation was found. func GetOriginalConfiguration(info *resource.Info) ([]byte, error) { annots, err := info.Mapping.MetadataAccessor.Annotations(info.Object) func GetOriginalConfiguration(mapping *meta.RESTMapping, obj runtime.Object) ([]byte, error) { annots, err := mapping.MetadataAccessor.Annotations(obj) if err != nil { return nil, err }"} {"_id":"doc-en-kubernetes-eec3c0fcd5c5fe47934eb4a0350d720b88741bbb8b606c69feb94eae72c658c3","title":"","text":"// UpdateApplyAnnotation calls CreateApplyAnnotation if the last applied // configuration annotation is already present. Otherwise, it does nothing. func UpdateApplyAnnotation(info *resource.Info, codec runtime.Encoder) error { if original, err := GetOriginalConfiguration(info); err != nil || len(original) <= 0 { if original, err := GetOriginalConfiguration(info.Mapping, info.Object); err != nil || len(original) <= 0 { return err } return CreateApplyAnnotation(info, codec)"} {"_id":"doc-en-kubernetes-6b8b9a5377af7ed3eb2d5e54950de7aa4a463d9e4a9c4b5eb879a266f179cc00","title":"","text":"import ( \"fmt\" \"io\" \"time\" \"github.com/jonboulle/clockwork\" \"github.com/spf13/cobra\" \"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/errors\" \"k8s.io/kubernetes/pkg/api/meta\" \"k8s.io/kubernetes/pkg/kubectl\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" \"k8s.io/kubernetes/pkg/kubectl/resource\""} {"_id":"doc-en-kubernetes-0efb673e622ab9ce390bc819f7b382d3d383fcf8d4e9e558dc65c9a9e834d0ca","title":"","text":"} const ( // maxPatchRetry is the maximum number of conflicts retry for during a patch operation before returning failure maxPatchRetry = 5 // backOffPeriod is the period to back off when apply patch resutls in error. backOffPeriod = 1 * time.Second // how many times we can retry before back off triesBeforeBackOff = 1 ) const ( apply_long = `Apply a configuration to a resource by filename or stdin. The resource will be created if it doesn't exist yet. To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'."} {"_id":"doc-en-kubernetes-b06151c75944440b6acccade9175bfd78b9950b5e164ceb515fc3e1beb87f32c","title":"","text":"return nil } // Serialize the current configuration of the object from the server. current, err := runtime.Encode(encoder, info.Object) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf(\"serializing current configuration from:n%vnfor:\", info), info.Source, err) } // Retrieve the original configuration of the object from the annotation. original, err := kubectl.GetOriginalConfiguration(info) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving original configuration from:n%vnfor:\", info), info.Source, err) } // Create the versioned struct from the original from the server for // strategic patch. // TODO: Move all structs in apply to use raw data. Can be done once // builder has a RawResult method which delivers raw data instead of // internal objects. versionedObject, _, err := decoder.Decode(current, nil, nil) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf(\"converting encoded server-side object back to versioned struct:n%vnfor:\", info), info.Source, err) } // Compute a three way strategic merge patch to send to server. patch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, versionedObject, true) if err != nil { format := \"creating patch with:noriginal:n%snmodified:n%sncurrent:n%snfrom:n%vnfor:\" return cmdutil.AddSourceToErr(fmt.Sprintf(format, original, modified, current, info), info.Source, err) } helper := resource.NewHelper(info.Client, info.Mapping) _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) patcher := NewPatcher(encoder, decoder, info.Mapping, helper) patchBytes, err := patcher.patch(info.Object, modified, info.Source, info.Namespace, info.Name) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf(\"applying patch:n%snto:n%vnfor:\", patch, info), info.Source, err) return cmdutil.AddSourceToErr(fmt.Sprintf(\"applying patch:n%snto:n%vnfor:\", patchBytes, info), info.Source, err) } if cmdutil.ShouldRecord(cmd, info) { patch, err = cmdutil.ChangeResourcePatch(info, f.Command()) patch, err := cmdutil.ChangeResourcePatch(info, f.Command()) if err != nil { return err }"} {"_id":"doc-en-kubernetes-e7d9fa8a1a021ffe36e2a0728914cde5844f5040a334715ecd736a60d9104c39","title":"","text":"return nil } type patcher struct { encoder runtime.Encoder decoder runtime.Decoder mapping *meta.RESTMapping helper *resource.Helper backOff clockwork.Clock } func NewPatcher(encoder runtime.Encoder, decoder runtime.Decoder, mapping *meta.RESTMapping, helper *resource.Helper) *patcher { return &patcher{ encoder: encoder, decoder: decoder, mapping: mapping, helper: helper, backOff: clockwork.NewRealClock(), } } func (p *patcher) patchSimple(obj runtime.Object, modified []byte, source, namespace, name string) ([]byte, error) { // Serialize the current configuration of the object from the server. current, err := runtime.Encode(p.encoder, obj) if err != nil { return nil, cmdutil.AddSourceToErr(fmt.Sprintf(\"serializing current configuration from:n%vnfor:\", obj), source, err) } // Retrieve the original configuration of the object from the annotation. original, err := kubectl.GetOriginalConfiguration(p.mapping, obj) if err != nil { return nil, cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving original configuration from:n%vnfor:\", obj), source, err) } // Create the versioned struct from the original from the server for // strategic patch. // TODO: Move all structs in apply to use raw data. Can be done once // builder has a RawResult method which delivers raw data instead of // internal objects. versionedObject, _, err := p.decoder.Decode(current, nil, nil) if err != nil { return nil, cmdutil.AddSourceToErr(fmt.Sprintf(\"converting encoded server-side object back to versioned struct:n%vnfor:\", obj), source, err) } // Compute a three way strategic merge patch to send to server. patch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, versionedObject, true) if err != nil { format := \"creating patch with:noriginal:n%snmodified:n%sncurrent:n%snfor:\" return nil, cmdutil.AddSourceToErr(fmt.Sprintf(format, original, modified, current), source, err) } _, err = p.helper.Patch(namespace, name, api.StrategicMergePatchType, patch) return patch, err } func (p *patcher) patch(current runtime.Object, modified []byte, source, namespace, name string) ([]byte, error) { var getErr error patchBytes, err := p.patchSimple(current, modified, source, namespace, name) for i := 1; i <= maxPatchRetry && errors.IsConflict(err); i++ { if i > triesBeforeBackOff { p.backOff.Sleep(backOffPeriod) } current, getErr = p.helper.Get(namespace, name, false) if getErr != nil { return nil, getErr } patchBytes, err = p.patchSimple(current, modified, source, namespace, name) } return patchBytes, err } "} {"_id":"doc-en-kubernetes-19cd83a43e4d8748070de8c6cb30a330aa15448550ad575586bec22e309dd0fe","title":"","text":"import ( \"bytes\" \"encoding/json\" \"fmt\" \"io/ioutil\" \"net/http\" \"os\""} {"_id":"doc-en-kubernetes-faa13d7415f0d7c363915459fa3506a423d16b4a2afae573abe9693339bd2547","title":"","text":"\"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/annotations\" kubeerr \"k8s.io/kubernetes/pkg/api/errors\" \"k8s.io/kubernetes/pkg/api/meta\" \"k8s.io/kubernetes/pkg/api/unversioned\" \"k8s.io/kubernetes/pkg/client/unversioned/fake\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" \"k8s.io/kubernetes/pkg/runtime\""} {"_id":"doc-en-kubernetes-4440ed239d3de07baf1f94a65400fc7783d7117da7a7b872642f488e34b9492e","title":"","text":"} } func TestApplyRetry(t *testing.T) { initTestErrorHandler(t) nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) pathRC := \"/namespaces/test/replicationcontrollers/\" + nameRC firstPatch := true retry := false getCount := 0 f, tf, codec := NewAPIFactory() tf.Printer = &testPrinter{} tf.Client = &fake.RESTClient{ Codec: codec, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { switch p, m := req.URL.Path, req.Method; { case p == pathRC && m == \"GET\": getCount++ bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: bodyRC}, nil case p == pathRC && m == \"PATCH\": if firstPatch { firstPatch = false statusErr := kubeerr.NewConflict(unversioned.GroupResource{Group: \"\", Resource: \"rc\"}, \"test-rc\", fmt.Errorf(\"the object has been modified. Please apply at first.\")) bodyBytes, _ := json.Marshal(statusErr) bodyErr := ioutil.NopCloser(bytes.NewReader(bodyBytes)) return &http.Response{StatusCode: http.StatusConflict, Header: defaultHeader(), Body: bodyErr}, nil } retry = true validatePatchApplication(t, req) bodyRC := ioutil.NopCloser(bytes.NewReader(currentRC)) return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: bodyRC}, nil default: t.Fatalf(\"unexpected request: %#vn%#v\", req.URL, req) return nil, nil } }), } tf.Namespace = \"test\" buf := bytes.NewBuffer([]byte{}) cmd := NewCmdApply(f, buf) cmd.Flags().Set(\"filename\", filenameRC) cmd.Flags().Set(\"output\", \"name\") cmd.Run(cmd, []string{}) if !retry || getCount != 2 { t.Fatalf(\"apply didn't retry when get conflict error\") } // uses the name from the file, not the response expectRC := \"replicationcontroller/\" + nameRC + \"n\" if buf.String() != expectRC { t.Fatalf(\"unexpected output: %snexpected: %s\", buf.String(), expectRC) } } func TestApplyNonExistObject(t *testing.T) { nameRC, currentRC := readAndAnnotateReplicationController(t, filenameRC) pathRC := \"/namespaces/test/replicationcontrollers\""} {"_id":"doc-en-kubernetes-119ae8bea7b8c17fa8273d415455f11e786c30e6047ec58a45e0bb663b439ddb","title":"","text":"\"experimentalsresourcesusagestracking\" # Expect --max-pods=100 ) # Tests which kills or restarts components and/or nodes. DISRUPTIVE_TESTS=( \"DaemonRestart\" \"Etcdsfailure\" \"NodessResize\" \"Reboot\" \"Services.*restarting\" ) # The following tests are known to be flaky, and are thus run only in their own # -flaky- build variants. GCE_FLAKY_TESTS=("} {"_id":"doc-en-kubernetes-48fc47b26db0e3f35d167dee7b19bc005eae04d84a1115274e64ecbc1fe12f9a","title":"","text":"# Tests which are not able to be run in parallel. GCE_PARALLEL_SKIP_TESTS=( \"Etcd\" \"NetworkingNew\" \"NodessNetwork\" \"NodessResize\" \"MaxPods\" \"Resourcesusagesofssystemscontainers\" \"SchedulerPredicates\" \"Services.*restarting\" \"resourcesusagestracking\" \"${DISRUPTIVE_TESTS[@]}\" ) # Tests which are known to be flaky when run in parallel."} {"_id":"doc-en-kubernetes-b682772a7fd9fa3105cdb704e8665c5511aaf299dbed12f300fc21fb879a7ae7","title":"","text":"GCE_SOAK_CONTINUOUS_SKIP_TESTS=( \"Density.*30spods\" \"Elasticsearch\" \"Etcd.*SIGKILL\" \"externalsloadsbalancer\" \"identicallysnamedsservices\" \"networkspartition\" \"Services.*Typesgoessfrom\" \"${DISRUPTIVE_TESTS[@]}\" # avoid component restarts. ) GCE_RELEASE_SKIP_TESTS=("} {"_id":"doc-en-kubernetes-0251dc60d3059cef9de5e23a6e1c14e3c3862a59ffb5ef86f20ed1a9ca7444c9","title":"","text":"# Clean up kubectl delete namespace my-namespace ############## ###################### # Pods in Namespaces # ############## ###################### ### Create a new namespace # Pre-condition: the other namespace does not exist"} {"_id":"doc-en-kubernetes-ffa9769cdc00eccb1fa8c6189837159fc8fe65c87a7d0e00cf24cceb5d926fa7","title":"","text":"kube::test::get_object_assert 'pods --namespace=other' \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:' # Post-condition: verify shorthand `-n other` has the same results as `--namespace=other` kube::test::get_object_assert 'pods -n other' \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:' # Post-condition: a resource cannot be retrieved by name across all namespaces output_message=$(! kubectl get \"${kube_flags[@]}\" pod valid-pod --all-namespaces 2>&1) kube::test::if_has_string \"${output_message}\" \"a resource cannot be retrieved by name across all namespaces\" ### Delete POD valid-pod in specific namespace # Pre-condition: valid-pod POD exists"} {"_id":"doc-en-kubernetes-6d7bdf0dfe1312d54ba2d5f6799c85c5f0930230363985750d24355e11e9d043","title":"","text":"# Clean up kubectl delete namespace other ############## ########### # Secrets # ############## ########### ### Create a new namespace # Pre-condition: the test-secrets namespace does not exist"} {"_id":"doc-en-kubernetes-e70a6303c5d32a40ecdd575a88b42861a46544b54a6d9c4e8c76a5e7065e2512","title":"","text":"resources []string namespace string names []string namespace string allNamespace bool names []string resourceTuples []resourceTuple"} {"_id":"doc-en-kubernetes-8b3decc54b171c90e997ce394b47b09e7e0ded8ddf2b681dad689013fbbd284d","title":"","text":"if allNamespace { b.namespace = api.NamespaceAll } b.allNamespace = allNamespace return b }"} {"_id":"doc-en-kubernetes-3ce7671dbaed66b5a37ced67bc22838f568526e7c63db9f31a1bb728afd1f8df","title":"","text":"selectorNamespace = \"\" } else { if len(b.namespace) == 0 { return &Result{singular: isSingular, err: fmt.Errorf(\"namespace may not be empty when retrieving a resource by name\")} errMsg := \"namespace may not be empty when retrieving a resource by name\" if b.allNamespace { errMsg = \"a resource cannot be retrieved by name across all namespaces\" } return &Result{singular: isSingular, err: fmt.Errorf(errMsg)} } }"} {"_id":"doc-en-kubernetes-b69057100e37a2d57befabb5ab8e77b47cf746a4a69bbbd01478ec2f81ce0a4b","title":"","text":"#run the script once to download the dependent java libraries into the image RUN mkdir /output RUN build/gen-swagger-docs.sh v1 https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes/master/api/swagger-spec/v1.json https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes/master/pkg/api/v1/register.go RUN mkdir /swagger-source RUN wget https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/swagger-spec/v1.json -O /swagger-source/v1.json RUN build/gen-swagger-docs.sh v1 https://raw.githubusercontent.com/GoogleCloudPlatform/kubernetes/master/pkg/api/v1/register.go RUN rm /output/* RUN rm /swagger-source/* ENTRYPOINT [\"build/gen-swagger-docs.sh\"]"} {"_id":"doc-en-kubernetes-1bc77974a96c7ff90a4baba8b549df1a29e59e5ecf830ae76adce57210580e77","title":"","text":"cd /build/ wget \"$2\" -O input.json wget \"$3\" -O register.go wget \"$2\" -O register.go # gendocs takes \"input.json\" as the input swagger spec. cp /swagger-source/\"$1\".json input.json ./gradle-2.5/bin/gradle gendocs --info"} {"_id":"doc-en-kubernetes-1acd3b5f00b9f698c8d00d3f2a57cf4249059e02d645055c40e187af8fa172be","title":"","text":"KUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/../.. V1_PATH=\"$PWD/${KUBE_ROOT}/docs/api-reference/v1/\" V1BETA1_PATH=\"$PWD/${KUBE_ROOT}/docs/api-reference/extensions/v1beta1\" SWAGGER_PATH=\"$PWD/${KUBE_ROOT}/api/swagger-spec/\" mkdir -p $V1_PATH mkdir -p $V1BETA1_PATH docker run -v $V1_PATH:/output gcr.io/google_containers/gen-swagger-docs:v2 docker run -v $V1_PATH:/output -v ${SWAGGER_PATH}:/swagger-source gcr.io/google_containers/gen-swagger-docs:v3 v1 https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/swagger-spec/v1.json https://raw.githubusercontent.com/kubernetes/kubernetes/master/pkg/api/v1/register.go docker run -v $V1BETA1_PATH:/output gcr.io/google_containers/gen-swagger-docs:v2 docker run -v $V1BETA1_PATH:/output -v ${SWAGGER_PATH}:/swagger-source gcr.io/google_containers/gen-swagger-docs:v3 v1beta1 https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/swagger-spec/v1beta1.json https://raw.githubusercontent.com/kubernetes/kubernetes/master/pkg/apis/extensions/v1beta1/register.go"} {"_id":"doc-en-kubernetes-7a96a61adb014355a78cae1f3b8329c09fe45df2fe15335d84e31f56e618a473","title":"","text":"- containerPort: 80 name: \"http-server\" volumeMounts: - mountPath: \"/var/www/html\" - mountPath: \"/usr/share/nginx/html\" name: mypd volumes: - name: mypd"} {"_id":"doc-en-kubernetes-e02806819a359aa1b43fa998eb13ea48cb3f042371a4e40545cd5e084411abe5","title":"","text":"# Specialized tests which should be skipped by default for projects. GCE_DEFAULT_SKIP_TESTS=( \"${REBOOT_SKIP_TESTS[@]}\" \"AutoscalingsSuite\" \"Reboot\" \"ServiceLoadBalancer\" )"} {"_id":"doc-en-kubernetes-81899539dc1a31e8ba82ced0a7cc78dc03d3e9e17956d41f044b10f012c4a3b3","title":"","text":"# Tests which kills or restarts components and/or nodes. DISRUPTIVE_TESTS=( \"AutoscalingsSuite.*scalescluster\" \"DaemonRestart\" \"Etcdsfailure\" \"NodessResize\""} {"_id":"doc-en-kubernetes-453a033a6c395682e208f9b6b53bfaa67c28815b3bea03d4387fc7041cdd2b8c","title":"","text":"# comments below, and for poorly implemented tests, please quote the # issue number tracking speed improvements. GCE_SLOW_TESTS=( # TODO: add deployment test here once it will become stable \"AutoscalingsSuite.*viasreplicationController\" # Before enabling this loadbalancer test in any other test list you must # make sure the associated project has enough quota. At the time of this # writing a GCE project is allowed 3 backend services by default. This"} {"_id":"doc-en-kubernetes-6e74958de9ffead225313b3c054d319c8e881be0a6c47e63a9be3ba2f8d86cef","title":"","text":"}) // CPU tests via replication controllers It(fmt.Sprintf(titleUp, \"[Autoscaling Suite]\", kindRC), func() { It(fmt.Sprintf(titleUp, \"[Skipped][Autoscaling Suite]\", kindRC), func() { scaleUp(\"rc\", kindRC, rc, f) }) It(fmt.Sprintf(titleDown, \"[Autoscaling Suite]\", kindRC), func() { It(fmt.Sprintf(titleDown, \"[Skipped][Autoscaling Suite]\", kindRC), func() { scaleDown(\"rc\", kindRC, rc, f) }) })"} {"_id":"doc-en-kubernetes-62566a0d262661d0e61e82888474b36bd4b22a1b1890dc0b5662f6c1bc21138a","title":"","text":"DEBUG=${DEBUG:-\"false\"} # Add SSH_OPTS: Add this to config ssh port SSH_OPTS=\"-oPort=22 -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oLogLevel=ERROR\" "} {"_id":"doc-en-kubernetes-83b4b7c42e2cf6b629361a435aa70cd983df931ce961f6b083996a4cdf87d968","title":"","text":"ip := pickNodeIP(c) testReachable(ip, nodePort) By(\"verifying the node port is locked\") hostExec := LaunchHostExecPod(f.Client, f.Namespace.Name, \"hostexec\") cmd := fmt.Sprintf(`ss -ant46 'sport = :%d' | tail -n +2 | grep LISTEN`, nodePort) // Loop a bit because we see transient flakes. cmd := fmt.Sprintf(`for i in $(seq 1 10); do if ss -ant46 'sport = :%d' | grep ^LISTEN; then exit 0; fi; sleep 0.1; done; exit 1`, nodePort) stdout, err := RunHostCmd(hostExec.Namespace, hostExec.Name, cmd) if err != nil { Failf(\"expected node port (%d) to be in use, stdout: %v\", nodePort, stdout)"} {"_id":"doc-en-kubernetes-95eadf1c7c273cceb7a6e26e14d26401c63106b87c7340a0e951961e6b2cafd0","title":"","text":"# This tarball is only used by Ubuntu Trusty. KUBE_MANIFESTS_TAR= if [[ \"${OS_DISTRIBUTION}\" == \"trusty\" ]]; then KUBE_MANIFESTS_TAR=\"${KUBE_ROOT}/server/kuernetes-manifests.tar.gz\" if [[ \"${KUBE_OS_DISTRIBUTION}\" == \"trusty\" ]]; then KUBE_MANIFESTS_TAR=\"${KUBE_ROOT}/server/kubernetes-manifests.tar.gz\" if [[ ! -f \"${KUBE_MANIFESTS_TAR}\" ]]; then KUBE_MANIFESTS_TAR=\"${KUBE_ROOT}/_output/release-tars/kubernetes-manifests.tar.gz\" fi"} {"_id":"doc-en-kubernetes-aade3b7b598f081f558e10128e7b70064f4750cf8dcbf5dfc6ba5b365c0d72e1","title":"","text":"package apiserver import ( \"fmt\" \"io/ioutil\" \"net/http\" \"net/http/httptest\""} {"_id":"doc-en-kubernetes-2f71df567e4124c557db9cac4354115d299eb985305446284b7c938e88479f4f","title":"","text":"func (f fakeRL) TryAccept() bool { return bool(f) } func (f fakeRL) Accept() {} func expectHTTP(url string, code int, t *testing.T) { func expectHTTP(url string, code int) error { r, err := http.Get(url) if err != nil { t.Errorf(\"unexpected error: %v\", err) return return fmt.Errorf(\"unexpected error: %v\", err) } if r.StatusCode != code { t.Errorf(\"unexpected response: %v\", r.StatusCode) return fmt.Errorf(\"unexpected response: %v\", r.StatusCode) } return nil } func getPath(resource, namespace, name string) string {"} {"_id":"doc-en-kubernetes-cd22cb52db5241d7811cefa1f9989ca42f487fbf884116c7a46631c92ff4f972","title":"","text":"// 'short' accounted ones. calls := &sync.WaitGroup{} calls.Add(AllowedInflightRequestsNo * 2) // Responses is used to wait until all responses are // received. This prevents some async requests getting EOF // errors from prematurely closing the server responses := sync.WaitGroup{} responses.Add(AllowedInflightRequestsNo * 2) // Block is used to keep requests in flight for as long as we need to. All requests will // be unblocked at the same time. block := sync.WaitGroup{}"} {"_id":"doc-en-kubernetes-bd0f0893ddae620e1a6109f97a5b918f382a4d7a7880004a7fe2019d6aa3ca6a","title":"","text":"for i := 0; i < AllowedInflightRequestsNo; i++ { // These should hang waiting on block... go func() { expectHTTP(server.URL+\"/foo/bar/watch\", http.StatusOK, t) if err := expectHTTP(server.URL+\"/foo/bar/watch\", http.StatusOK); err != nil { t.Error(err) } responses.Done() }() } // Check that sever is not saturated by not-accounted calls expectHTTP(server.URL+\"/dontwait\", http.StatusOK, t) oneAccountedFinished := sync.WaitGroup{} oneAccountedFinished.Add(1) var once sync.Once if err := expectHTTP(server.URL+\"/dontwait\", http.StatusOK); err != nil { t.Error(err) } // These should hang and be accounted, i.e. saturate the server for i := 0; i < AllowedInflightRequestsNo; i++ { // These should hang waiting on block... go func() { expectHTTP(server.URL, http.StatusOK, t) once.Do(oneAccountedFinished.Done) if err := expectHTTP(server.URL, http.StatusOK); err != nil { t.Error(err) } responses.Done() }() } // We wait for all calls to be received by the server"} {"_id":"doc-en-kubernetes-6ed99fc05bdd712e5aaf8bac4aa81c14752153bf69293d8b9db4a90d1b2078bb","title":"","text":"// Do this multiple times to show that it rate limit rejected requests don't block. for i := 0; i < 2; i++ { expectHTTP(server.URL, errors.StatusTooManyRequests, t) if err := expectHTTP(server.URL, errors.StatusTooManyRequests); err != nil { t.Error(err) } } // Validate that non-accounted URLs still work expectHTTP(server.URL+\"/dontwait/watch\", http.StatusOK, t) if err := expectHTTP(server.URL+\"/dontwait/watch\", http.StatusOK); err != nil { t.Error(err) } // Let all hanging requests finish block.Done() // Show that we recover from being blocked up. // Too avoid flakyness we need to wait until at least one of the requests really finishes. oneAccountedFinished.Wait() expectHTTP(server.URL, http.StatusOK, t) responses.Wait() if err := expectHTTP(server.URL, http.StatusOK); err != nil { t.Error(err) } } func TestReadOnly(t *testing.T) {"} {"_id":"doc-en-kubernetes-9437afb02494d13989a1f78405eb7ff0a368d3448cfe1f204df0e2c2156a4bdb","title":"","text":"return pod } var _ = Describe(\"Security Context [Skipped]\", func() { var _ = Describe(\"Security Context [Feature:SecurityContext]\", func() { framework := NewFramework(\"security-context\") It(\"should support pod.Spec.SecurityContext.SupplementalGroups\", func() {"} {"_id":"doc-en-kubernetes-c3b080c48f1e44688bd5cd2e48720471d7c26f6071d381fe037ddd66f2879481","title":"","text":"find-release-tars upload-server-tars # ensure that environmental variables specifying number of migs to create set_num_migs if [[ ${KUBE_USE_EXISTING_MASTER:-} == \"true\" ]]; then create-nodes create-autoscaler"} {"_id":"doc-en-kubernetes-d83d2985b7a92a0f874218e5507e80236e05d33b292a40c3a225be21fc37b540","title":"","text":"create-node-instance-template $template_name } function create-nodes() { local template_name=\"${NODE_INSTANCE_PREFIX}-template\" # Assumes: # - MAX_INSTANCES_PER_MIG # - NUM_NODES # exports: # - NUM_MIGS function set_num_migs() { local defaulted_max_instances_per_mig=${MAX_INSTANCES_PER_MIG:-500} if [[ ${defaulted_max_instances_per_mig} -le \"0\" ]]; then echo \"MAX_INSTANCES_PER_MIG cannot be negative. Assuming default 500\" defaulted_max_instances_per_mig=500 fi local num_migs=$(((${NUM_NODES} + ${defaulted_max_instances_per_mig} - 1) / ${defaulted_max_instances_per_mig})) local instances_per_mig=$(((${NUM_NODES} + ${num_migs} - 1) / ${num_migs})) local last_mig_size=$((${NUM_NODES} - (${num_migs} - 1) * ${instances_per_mig})) export NUM_MIGS=$(((${NUM_NODES} + ${defaulted_max_instances_per_mig} - 1) / ${defaulted_max_instances_per_mig})) } # Assumes: # - NUM_MIGS # - NODE_INSTANCE_PREFIX # - NUM_NODES # - PROJECT # - ZONE function create-nodes() { local template_name=\"${NODE_INSTANCE_PREFIX}-template\" local instances_per_mig=$(((${NUM_NODES} + ${NUM_MIGS} - 1) / ${NUM_MIGS})) local last_mig_size=$((${NUM_NODES} - (${NUM_MIGS} - 1) * ${instances_per_mig})) #TODO: parallelize this loop to speed up the process for i in $(seq $((${num_migs} - 1))); do for i in $(seq $((${NUM_MIGS} - 1))); do gcloud compute instance-groups managed create \"${NODE_INSTANCE_PREFIX}-group-$i\" --project \"${PROJECT}\" "} {"_id":"doc-en-kubernetes-a61aa3d91ce1a3ac58cb5de2d9e064de75651479e965f8df667db993093c1760","title":"","text":"--project \"${PROJECT}\" || true; } # Assumes: # - NUM_MIGS # - NODE_INSTANCE_PREFIX # - PROJECT # - ZONE # - ENABLE_NODE_AUTOSCALER # - TARGET_NODE_UTILIZATION # - AUTOSCALER_MAX_NODES # - AUTOSCALER_MIN_NODES function create-autoscaler() { # Create autoscaler for nodes if requested if [[ \"${ENABLE_NODE_AUTOSCALER}\" == \"true\" ]]; then METRICS=\"\" local metrics=\"\" # Current usage METRICS+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/cpu/node_utilization,\" METRICS+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" METRICS+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/memory/node_utilization,\" METRICS+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" metrics+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/cpu/node_utilization,\" metrics+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" metrics+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/memory/node_utilization,\" metrics+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" # Reservation METRICS+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/cpu/node_reservation,\" METRICS+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" METRICS+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/memory/node_reservation,\" METRICS+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" metrics+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/cpu/node_reservation,\" metrics+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" metrics+=\"--custom-metric-utilization metric=custom.cloudmonitoring.googleapis.com/kubernetes.io/memory/node_reservation,\" metrics+=\"utilization-target=${TARGET_NODE_UTILIZATION},utilization-target-type=GAUGE \" echo \"Creating node autoscalers.\" local max_instances_per_mig=$(((${AUTOSCALER_MAX_NODES} + ${num_migs} - 1) / ${num_migs})) local last_max_instances=$((${AUTOSCALER_MAX_NODES} - (${num_migs} - 1) * ${max_instances_per_mig})) local min_instances_per_mig=$(((${AUTOSCALER_MIN_NODES} + ${num_migs} - 1) / ${num_migs})) local last_min_instances=$((${AUTOSCALER_MIN_NODES} - (${num_migs} - 1) * ${min_instances_per_mig})) local max_instances_per_mig=$(((${AUTOSCALER_MAX_NODES} + ${NUM_MIGS} - 1) / ${NUM_MIGS})) local last_max_instances=$((${AUTOSCALER_MAX_NODES} - (${NUM_MIGS} - 1) * ${max_instances_per_mig})) local min_instances_per_mig=$(((${AUTOSCALER_MIN_NODES} + ${NUM_MIGS} - 1) / ${NUM_MIGS})) local last_min_instances=$((${AUTOSCALER_MIN_NODES} - (${NUM_MIGS} - 1) * ${min_instances_per_mig})) for i in $(seq $((${num_migs} - 1))); do for i in $(seq $((${NUM_MIGS} - 1))); do gcloud compute instance-groups managed set-autoscaling \"${NODE_INSTANCE_PREFIX}-group-$i\" --zone \"${ZONE}\" --project \"${PROJECT}\" --min-num-replicas \"${min_instances_per_mig}\" --max-num-replicas \"${max_instances_per_mig}\" ${METRICS} || true --min-num-replicas \"${min_instances_per_mig}\" --max-num-replicas \"${max_instances_per_mig}\" ${metrics} || true done gcloud compute instance-groups managed set-autoscaling \"${NODE_INSTANCE_PREFIX}-group\" --zone \"${ZONE}\" --project \"${PROJECT}\" --min-num-replicas \"${last_min_instances}\" --max-num-replicas \"${last_max_instances}\" ${METRICS} || true --min-num-replicas \"${last_min_instances}\" --max-num-replicas \"${last_max_instances}\" ${metrics} || true fi }"} {"_id":"doc-en-kubernetes-7c69d934eec530cc7129b48a9ab0a579ddb6762fa2e7b0b6e2efe3acebff6947","title":"","text":"echo -e \"${color_yellow}Attempt ${attempt} failed to create instance template $template_name. Retrying.${color_norm}\" >&2 attempt=$(($attempt+1)) sleep $(($attempt * 5)) # In case the previous attempt failed with something like a # Backend Error and left the entry laying around, delete it # before we try again. gcloud compute instance-templates delete \"$template_name\" --project \"${PROJECT}\" &>/dev/null || true else break fi"} {"_id":"doc-en-kubernetes-2af3f16b74f5b1be74b649544c97960e4fd8a01bacd218ffb29aec310d04257e","title":"","text":"fi } # Deletes a security group # usage: delete_security_group function delete_security_group { local -r sg_id=${1} echo \"Deleting security group: ${sg_id}\" # We retry in case there's a dependent resource - typically an ELB n=0 until [ $n -ge 20 ]; do $AWS_CMD delete-security-group --group-id ${sg_id} > $LOG && return n=$[$n+1] sleep 3 done echo \"Unable to delete security group: ${sg_id}\" exit 1 } function ssh-key-setup { if [[ ! -f \"$AWS_SSH_KEY\" ]]; then ssh-keygen -f \"$AWS_SSH_KEY\" -N ''"} {"_id":"doc-en-kubernetes-2cf6dfd65d08df1a7542e6202e7422f4c86f36ff81420c3b16059ccdbb4f8da2","title":"","text":"continue fi echo \"Deleting security group: ${sg_id}\" $AWS_CMD delete-security-group --group-id ${sg_id} > $LOG delete_security_group ${sg_id} done subnet_ids=$($AWS_CMD describe-subnets "} {"_id":"doc-en-kubernetes-abe299ff9a34766123cf5d47dbe664dabdbc3502c45793018fc677dabdc8637d","title":"","text":"}, \"targetPort\": { \"type\": \"string\", \"description\": \"Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of Port is used (an identity map). Defaults to the service port. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service\" \"description\": \"Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service\" }, \"nodePort\": { \"type\": \"integer\","} {"_id":"doc-en-kubernetes-1ef6c3b371f15e0fcb7e3be51a55664a8c783753a74dd6621d506d7ff24ec072","title":"","text":"

targetPort

Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod’s container ports. If this is not specified, the value of Port is used (an identity map). Defaults to the service port. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service

Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod’s container ports. If this is not specified, the value of the port field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the port field. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service

false

string

"} {"_id":"doc-en-kubernetes-05c95f912510158ad562f4ca219d08f8bce4a5448378fd4a5c3555676185606a","title":"","text":"// Optional: The target port on pods selected by this service. If this // is a string, it will be looked up as a named port in the target // Pod's container ports. If this is not specified, the default value // is the sames as the Port field (an identity map). // Pod's container ports. If this is not specified, the value // of the 'port' field is used (an identity map). // This field is ignored for services with clusterIP=None, and should be // omitted or set equal to the 'port' field. TargetPort intstr.IntOrString `json:\"targetPort\"` // The port on each node on which this service is exposed."} {"_id":"doc-en-kubernetes-5e3694ac29732cd1486e73029b53416a902cc001f3a8e816cde18ab740de7b8d","title":"","text":"// Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. // If this is a string, it will be looked up as a named port in the // target Pod's container ports. If this is not specified, the value // of Port is used (an identity map). // Defaults to the service port. // of the 'port' field is used (an identity map). // This field is ignored for services with clusterIP=None, and should be // omitted or set equal to the 'port' field. // More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service TargetPort intstr.IntOrString `json:\"targetPort,omitempty\"`"} {"_id":"doc-en-kubernetes-80ab4a5dfc80ee8e5007fc1c6525528730c79bf7d4ec04fcecdec6fa7d3d37d7","title":"","text":"\"name\": \"The name of this port within the service. This must be a DNS_LABEL. All ports within a ServiceSpec must have unique names. This maps to the 'Name' field in EndpointPort objects. Optional if only one ServicePort is defined on this service.\", \"protocol\": \"The IP protocol for this port. Supports \"TCP\" and \"UDP\". Default is TCP.\", \"port\": \"The port that will be exposed by this service.\", \"targetPort\": \"Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of Port is used (an identity map). Defaults to the service port. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service\", \"targetPort\": \"Number or name of the port to access on the pods targeted by the service. Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. If this is a string, it will be looked up as a named port in the target Pod's container ports. If this is not specified, the value of the 'port' field is used (an identity map). This field is ignored for services with clusterIP=None, and should be omitted or set equal to the 'port' field. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#defining-a-service\", \"nodePort\": \"The port on each node on which this service is exposed when type=NodePort or LoadBalancer. Usually assigned by the system. If specified, it will be allocated to the service if unused or else creation of the service will fail. Default is to auto-allocate a port if the ServiceType of this Service requires one. More info: http://releases.k8s.io/HEAD/docs/user-guide/services.md#type--nodeport\", }"} {"_id":"doc-en-kubernetes-90592115971551c634ab29405903d852a663b4237b75b940627e0a106d01123d","title":"","text":"allErrs = append(allErrs, field.Invalid(fldPath.Child(\"targetPort\"), sp.TargetPort, PortNameErrorMsg)) } if isHeadlessService { if sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) { allErrs = append(allErrs, field.Invalid(fldPath.Child(\"port\"), sp.Port, \"must be equal to targetPort when clusterIP = None\")) } } // in the v1 API, targetPorts on headless services were tolerated. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. // // if isHeadlessService { // \tif sp.TargetPort.Type == intstr.String || (sp.TargetPort.Type == intstr.Int && sp.Port != sp.TargetPort.IntValue()) { // \t\tallErrs = append(allErrs, field.Invalid(fldPath.Child(\"targetPort\"), sp.TargetPort, \"must be equal to the value of 'port' when clusterIP = None\")) // \t} // } return allErrs }"} {"_id":"doc-en-kubernetes-8d7e5a4d14b75b3a9cb0b8c941b1a1eb9e5a4d6e42c5a4939676a75863877e7e","title":"","text":"numErrs: 0, }, { name: \"invalid port headless\", name: \"invalid port headless 1\", tweakSvc: func(s *api.Service) { s.Spec.Ports[0].Port = 11722 s.Spec.Ports[0].TargetPort = intstr.FromInt(11721) s.Spec.ClusterIP = api.ClusterIPNone }, numErrs: 1, // in the v1 API, targetPorts on headless services were tolerated. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. // numErrs: 1, numErrs: 0, }, { name: \"invalid port headless\", name: \"invalid port headless 2\", tweakSvc: func(s *api.Service) { s.Spec.Ports[0].Port = 11722 s.Spec.Ports[0].TargetPort = intstr.FromString(\"target\") s.Spec.ClusterIP = api.ClusterIPNone }, numErrs: 1, // in the v1 API, targetPorts on headless services were tolerated. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. // numErrs: 1, numErrs: 0, }, { name: \"invalid publicIPs localhost\","} {"_id":"doc-en-kubernetes-26e8d63c91fb7b0db38ad8826b018c87201a07d0542814a489a967c1244dc789","title":"","text":"label := labels.SelectorFromSet(labels.Set(map[string]string{\"name\": name})) pods, err := podsCreated(f.Client, f.Namespace.Name, name, replicas) Expect(err).NotTo(HaveOccurred()) By(\"Ensuring each pod is running\")"} {"_id":"doc-en-kubernetes-a4dc979ce6e7f6401ae9ec175d25467a5f47da0dd953fa7e0061f372dc856478","title":"","text":"# use JENKINS_PUBLISHED_VERSION, default to 'ci/latest', since that's # usually what we're testing. check_dirty_workspace fetch_published_version_tars \"${JENKINS_PUBLISHED_VERSION:-'ci/latest'}\" fetch_published_version_tars \"${JENKINS_PUBLISHED_VERSION:-ci/latest}\" fi # Copy GCE keys so we don't keep cycling them."} {"_id":"doc-en-kubernetes-746c080ab61e2da636a01be15944f54f56478dca9ad8529a7d41c5c277328242","title":"","text":"// Return all the security groups that are tagged as being part of our cluster func (s *AWSCloud) getTaggedSecurityGroups() (map[string]*ec2.SecurityGroup, error) { request := &ec2.DescribeSecurityGroupsInput{} filters := []*ec2.Filter{} request.Filters = s.addFilters(filters) request.Filters = s.addFilters(nil) groups, err := s.ec2.DescribeSecurityGroups(request) if err != nil { return nil, fmt.Errorf(\"error querying security groups: %v\", err)"} {"_id":"doc-en-kubernetes-faa12f11d8ab5105c0c97e4816c6eb3cdcd65a2c2303b4b8481b6045d0c52d83","title":"","text":"describeRequest.Filters = s.addFilters(filters) actualGroups, err := s.ec2.DescribeSecurityGroups(describeRequest) if err != nil { return fmt.Errorf(\"error querying security groups: %v\", err) return fmt.Errorf(\"error querying security groups for ELB: %v\", err) } taggedSecurityGroups, err := s.getTaggedSecurityGroups()"} {"_id":"doc-en-kubernetes-a9cdfe189e34fa530142106e93f38ebbc9fbe9441978686aa6110e04d6ef686a","title":"","text":"for k, v := range s.filterTags { filters = append(filters, newEc2Filter(\"tag:\"+k, v)) } if len(filters) == 0 { // We can't pass a zero-length Filters to AWS (it's an error) // So if we end up with no filters; just return nil return nil } return filters }"} {"_id":"doc-en-kubernetes-5b24538121f7a0f84368916a8ec61f8edbb0ca7a6436fdd080b8088cfe6d3cf4","title":"","text":"if err != nil { t.Errorf(\"Failed to delete pod: %v\", err) } close(schedulerConfig.StopEverything) //\t8. create 2 pods: testPodNoAnnotation2 and testPodWithAnnotationFitsDefault2 //\t\t- note: these two pods belong to default scheduler which no longer exists podWithNoAnnotation2 := createPod(\"pod-with-no-annotation2\", nil) podWithAnnotationFitsDefault2 := createPod(\"pod-with-annotation-fits-default2\", schedulerAnnotationFitsDefault) testPodNoAnnotation2, err := restClient.Pods(api.NamespaceDefault).Create(podWithNoAnnotation2) if err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } testPodWithAnnotationFitsDefault2, err := restClient.Pods(api.NamespaceDefault).Create(podWithAnnotationFitsDefault2) if err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } // The rest of this test assumes that closing StopEverything will cause the // scheduler thread to stop immediately. It won't, and in fact it will often // schedule 1 more pod before finally exiting. Comment out until we fix that. // // See https://github.com/kubernetes/kubernetes/issues/23715 for more details. //\t9. **check point-3**: //\t\t- testPodNoAnnotation2 and testPodWithAnnotationFitsDefault2 shoule NOT be scheduled err = wait.Poll(time.Second, time.Second*5, podScheduled(restClient, testPodNoAnnotation2.Namespace, testPodNoAnnotation2.Name)) if err == nil { t.Errorf(\"Test MultiScheduler: %s Pod got scheduled, %v\", testPodNoAnnotation2.Name, err) } else { t.Logf(\"Test MultiScheduler: %s Pod not scheduled\", testPodNoAnnotation2.Name) } err = wait.Poll(time.Second, time.Second*5, podScheduled(restClient, testPodWithAnnotationFitsDefault2.Namespace, testPodWithAnnotationFitsDefault2.Name)) if err == nil { t.Errorf(\"Test MultiScheduler: %s Pod got scheduled, %v\", testPodWithAnnotationFitsDefault2.Name, err) } else { t.Logf(\"Test MultiScheduler: %s Pod scheduled\", testPodWithAnnotationFitsDefault2.Name) } /* close(schedulerConfig.StopEverything) //\t8. create 2 pods: testPodNoAnnotation2 and testPodWithAnnotationFitsDefault2 //\t\t- note: these two pods belong to default scheduler which no longer exists podWithNoAnnotation2 := createPod(\"pod-with-no-annotation2\", nil) podWithAnnotationFitsDefault2 := createPod(\"pod-with-annotation-fits-default2\", schedulerAnnotationFitsDefault) testPodNoAnnotation2, err := restClient.Pods(api.NamespaceDefault).Create(podWithNoAnnotation2) if err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } testPodWithAnnotationFitsDefault2, err := restClient.Pods(api.NamespaceDefault).Create(podWithAnnotationFitsDefault2) if err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } //\t9. **check point-3**: //\t\t- testPodNoAnnotation2 and testPodWithAnnotationFitsDefault2 shoule NOT be scheduled err = wait.Poll(time.Second, time.Second*5, podScheduled(restClient, testPodNoAnnotation2.Namespace, testPodNoAnnotation2.Name)) if err == nil { t.Errorf(\"Test MultiScheduler: %s Pod got scheduled, %v\", testPodNoAnnotation2.Name, err) } else { t.Logf(\"Test MultiScheduler: %s Pod not scheduled\", testPodNoAnnotation2.Name) } err = wait.Poll(time.Second, time.Second*5, podScheduled(restClient, testPodWithAnnotationFitsDefault2.Namespace, testPodWithAnnotationFitsDefault2.Name)) if err == nil { t.Errorf(\"Test MultiScheduler: %s Pod got scheduled, %v\", testPodWithAnnotationFitsDefault2.Name, err) } else { t.Logf(\"Test MultiScheduler: %s Pod scheduled\", testPodWithAnnotationFitsDefault2.Name) } */ } func createPod(name string, annotation map[string]string) *api.Pod {"} {"_id":"doc-en-kubernetes-e8f1c47cef6eeb6df9beb7ae43dde8dc785aac7f0b519a4f66e24c124798877a","title":"","text":"\"k8s.io/kubernetes/pkg/volume\" ) var errUnsupportedVolumeType = fmt.Errorf(\"unsupported volume type\") // This just exports required functions from kubelet proper, for use by volume // plugins. type volumeHost struct {"} {"_id":"doc-en-kubernetes-9397439368797452b7c30687a9aedc51cf22104863e51d095624aef827a98486","title":"","text":"return vh.kubelet.kubeClient } // NewWrapperMounter attempts to create a volume mounter // from a volume Spec, pod and volume options. // Returns a new volume Mounter or an error. func (vh *volumeHost) NewWrapperMounter(volName string, spec volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { // The name of wrapper volume is set to \"wrapped_{wrapped_volume_name}\" wrapperVolumeName := \"wrapped_\" + volName"} {"_id":"doc-en-kubernetes-27715586bca4f2379961a8436355527140474241ee28336aaef941fdf72a3397","title":"","text":"spec.Volume.Name = wrapperVolumeName } b, err := vh.kubelet.newVolumeMounterFromPlugins(&spec, pod, opts) if err == nil && b == nil { return nil, errUnsupportedVolumeType } return b, nil return vh.kubelet.newVolumeMounterFromPlugins(&spec, pod, opts) } // NewWrapperUnmounter attempts to create a volume unmounter // from a volume name and pod uid. // Returns a new volume Unmounter or an error. func (vh *volumeHost) NewWrapperUnmounter(volName string, spec volume.Spec, podUID types.UID) (volume.Unmounter, error) { // The name of wrapper volume is set to \"wrapped_{wrapped_volume_name}\" wrapperVolumeName := \"wrapped_\" + volName"} {"_id":"doc-en-kubernetes-c551b82e1893314d00cd8faf8fd7a467d9b50800d777329434abf3684a764120","title":"","text":"if err != nil { return nil, err } if plugin == nil { // Not found but not an error return nil, nil } c, err := plugin.NewUnmounter(spec.Name(), podUID) if err == nil && c == nil { return nil, errUnsupportedVolumeType } return c, nil return plugin.NewUnmounter(spec.Name(), podUID) } func (vh *volumeHost) GetCloudProvider() cloudprovider.Interface {"} {"_id":"doc-en-kubernetes-30c536daf4d831701f89dc665a44cdd2cc4a6ccd097464693772a6a56d27cbf3","title":"","text":"glog.Errorf(\"Could not create volume mounter for pod %s: %v\", pod.UID, err) return nil, err } if mounter == nil { return nil, errUnsupportedVolumeType } // some volumes require attachment before mounter's setup. // The plugin can be nil, but non-nil errors are legitimate errors."} {"_id":"doc-en-kubernetes-3919bbce9cc3f836dde3d1f5ccce6801321a078ec0d3c2df938a7e204d9ff4be","title":"","text":"glog.Errorf(\"Could not create volume unmounter for %s: %v\", volume.Name, err) continue } if unmounter == nil { glog.Errorf(\"Could not create volume unmounter for %s: %v\", volume.Name, errUnsupportedVolumeType) continue } tuple := cleanerTuple{Unmounter: unmounter} detacher, err := kl.newVolumeDetacherFromPlugins(volume.Kind, volume.Name, podUID)"} {"_id":"doc-en-kubernetes-c90bf14c4cb2ecd576923bd087c0bbc9f47f469488bcc81f8f507200f889c524","title":"","text":"return currentVolumes } // newVolumeMounterFromPlugins attempts to find a plugin by volume spec, pod // and volume options and then creates a Mounter. // Returns a valid Unmounter or an error. func (kl *Kubelet) newVolumeMounterFromPlugins(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Mounter, error) { plugin, err := kl.volumePluginMgr.FindPluginBySpec(spec) if err != nil { return nil, fmt.Errorf(\"can't use volume plugins for %s: %v\", spec.Name(), err) } if plugin == nil { // Not found but not an error return nil, nil } physicalMounter, err := plugin.NewMounter(spec, pod, opts) if err != nil { return nil, fmt.Errorf(\"failed to instantiate volume physicalMounter for %s: %v\", spec.Name(), err) return nil, fmt.Errorf(\"failed to instantiate mounter for volume: %s using plugin: %s with a root cause: %v\", spec.Name(), plugin.Name(), err) } glog.V(10).Infof(\"Used volume plugin %q to mount %s\", plugin.Name(), spec.Name()) return physicalMounter, nil } // newVolumeAttacherFromPlugins attempts to find a plugin from a volume spec // and then create an Attacher. // Returns: // - an attacher if one exists // - an error if no plugin was found for the volume // or the attacher failed to instantiate // - nil if there is no appropriate attacher for this volume func (kl *Kubelet) newVolumeAttacherFromPlugins(spec *volume.Spec, pod *api.Pod, opts volume.VolumeOptions) (volume.Attacher, error) { plugin, err := kl.volumePluginMgr.FindAttachablePluginBySpec(spec) if err != nil {"} {"_id":"doc-en-kubernetes-7ea5991b5b61aa687c9675a954bae2cfce33db4dc7ca5b081263d5c529402c0f","title":"","text":"return attacher, nil } // newVolumeUnmounterFromPlugins attempts to find a plugin by name and then // create an Unmounter. // Returns a valid Unmounter or an error. func (kl *Kubelet) newVolumeUnmounterFromPlugins(kind string, name string, podUID types.UID) (volume.Unmounter, error) { plugName := strings.UnescapeQualifiedNameForDisk(kind) plugin, err := kl.volumePluginMgr.FindPluginByName(plugName)"} {"_id":"doc-en-kubernetes-97f1f658f1757c3194e6969040d82951514b54815a507f365bf15d1e02b0913d","title":"","text":"// TODO: Maybe we should launch a cleanup of this dir? return nil, fmt.Errorf(\"can't use volume plugins for %s/%s: %v\", podUID, kind, err) } if plugin == nil { // Not found but not an error. return nil, nil } unmounter, err := plugin.NewUnmounter(name, podUID) if err != nil { return nil, fmt.Errorf(\"failed to instantiate volume plugin for %s/%s: %v\", podUID, kind, err)"} {"_id":"doc-en-kubernetes-ce1e9135180c8d33eeeef94e33f36bcd2ee757ee2593b1fbf2ded85c7196681d","title":"","text":"return unmounter, nil } // newVolumeDetacherFromPlugins attempts to find a plugin by a name and then // create a Detacher. // Returns: // - a detacher if one exists // - an error if no plugin was found for the volume // or the detacher failed to instantiate // - nil if there is no appropriate detacher for this volume func (kl *Kubelet) newVolumeDetacherFromPlugins(kind string, name string, podUID types.UID) (volume.Detacher, error) { plugName := strings.UnescapeQualifiedNameForDisk(kind) plugin, err := kl.volumePluginMgr.FindAttachablePluginByName(plugName)"} {"_id":"doc-en-kubernetes-6563ffbd9847c53f7754ca1228a623a2b10b35e164f014021922eed7d799bca7","title":"","text":"options := []string{} if readOnly { options = append(options, \"ro\") } else { // as per https://cloud.google.com/compute/docs/disks/add-persistent-disk#formatting options = append(options, \"discard\") } if notMnt { diskMounter := &mount.SafeFormatAndMount{Interface: mounter, Runner: exec.New()}"} {"_id":"doc-en-kubernetes-b6e0d65922de13099a4ecc62b1ef87b15ee17aebf8857df598681a837a558c8c","title":"","text":".vscode # This is where the result of the go build goes /output/** /output /_output/** /_output /output*/ /_output*/ # Emacs save files *~"} {"_id":"doc-en-kubernetes-9334baf3e20ed291321d7d241181b456450b48c23177a13179588f786643546a","title":"","text":"deleted := false timeout := false var lastPod *api.Pod timer := time.After(30 * time.Second) // The 30s grace period is not an upper-bound of the time it takes to // delete the pod from etcd. timer := time.After(60 * time.Second) for !deleted && !timeout { select { case event, _ := <-w.ResultChan():"} {"_id":"doc-en-kubernetes-8951ce6060e45ae43acc70532e6ba5b7b4393036bb5d9728910dec140fc7fd61","title":"","text":"command := args[0] baseCommand := path.Base(command) serverName := baseCommand args = args[1:] if serverName == hk.Name { args = args[1:] baseFlags := hk.Flags() baseFlags.SetInterspersed(false) // Only parse flags up to the next real command"} {"_id":"doc-en-kubernetes-342bd919e4189b9a016c392abf3da001f5604a531ee3f8cd5505b315bf0e3f3c","title":"","text":"\"strings\" \"testing\" \"github.com/spf13/cobra\" \"github.com/stretchr/testify/assert\" )"} {"_id":"doc-en-kubernetes-11f7fa71984e6925209581a42dc0df4e1a133096850c5be79929d4bff7789038","title":"","text":"} } const defaultCobraMessage = \"default message from cobra command\" const defaultCobraSubMessage = \"default sub-message from cobra command\" const cobraMessageDesc = \"message to print\" const cobraSubMessageDesc = \"sub-message to print\" func testCobraCommand(n string) *Server { var cobraServer *Server var msg string cmd := &cobra.Command{ Use: n, Long: n, Short: n, Run: func(cmd *cobra.Command, args []string) { cobraServer.hk.Printf(\"msg: %sn\", msg) }, } cmd.PersistentFlags().StringVar(&msg, \"msg\", defaultCobraMessage, cobraMessageDesc) var subMsg string subCmdName := \"subcommand\" subCmd := &cobra.Command{ Use: subCmdName, Long: subCmdName, Short: subCmdName, Run: func(cmd *cobra.Command, args []string) { cobraServer.hk.Printf(\"submsg: %s\", subMsg) }, } subCmd.PersistentFlags().StringVar(&subMsg, \"submsg\", defaultCobraSubMessage, cobraSubMessageDesc) cmd.AddCommand(subCmd) localFlags := cmd.LocalFlags() localFlags.SetInterspersed(false) s := &Server{ SimpleUsage: n, Long: fmt.Sprintf(\"A server named %s which uses a cobra command\", n), Run: func(s *Server, args []string) error { cobraServer = s cmd.SetOutput(s.hk.Out()) cmd.SetArgs(args) return cmd.Execute() }, flags: localFlags, } return s } func runFull(t *testing.T, args string) *result { buf := new(bytes.Buffer) hk := HyperKube{"} {"_id":"doc-en-kubernetes-a7b4490e84b0f32f5ba1e1709cd8aa08f76d628c2f212921dfec59011ddcae06","title":"","text":"hk.AddServer(testServer(\"test2\")) hk.AddServer(testServer(\"test3\")) hk.AddServer(testServerError(\"test-error\")) hk.AddServer(testCobraCommand(\"test-cobra-command\")) a := strings.Split(args, \" \") t.Logf(\"Running full with args: %q\", a)"} {"_id":"doc-en-kubernetes-622ce212754b02406333adb22d034248c2542fb6188a4bdc34afb413301ed7ad","title":"","text":"assert.Contains(t, x.output, \"test-error Run\") assert.EqualError(t, x.err, \"Server returning error\") } func TestCobraCommandHelp(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command --help\") assert.NoError(t, x.err) assert.Contains(t, x.output, \"A server named test-cobra-command which uses a cobra command\") assert.Contains(t, x.output, cobraMessageDesc) } func TestCobraCommandDefaultMessage(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command\") assert.Contains(t, x.output, fmt.Sprintf(\"msg: %s\", defaultCobraMessage)) } func TestCobraCommandMessage(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command --msg foobar\") assert.Contains(t, x.output, \"msg: foobar\") } func TestCobraSubCommandHelp(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command subcommand --help\") assert.NoError(t, x.err) assert.Contains(t, x.output, cobraSubMessageDesc) } func TestCobraSubCommandDefaultMessage(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command subcommand\") assert.Contains(t, x.output, fmt.Sprintf(\"submsg: %s\", defaultCobraSubMessage)) } func TestCobraSubCommandMessage(t *testing.T) { x := runFull(t, \"hyperkube test-cobra-command subcommand --submsg foobar\") assert.Contains(t, x.output, \"submsg: foobar\") } "} {"_id":"doc-en-kubernetes-2b5f9f0ffb3cc85ba87433b7f111f9e58e4311fd2a021ffa5ce51382e2523acd","title":"","text":"import ( \"os\" \"k8s.io/kubernetes/cmd/kubectl/app\" \"k8s.io/kubernetes/pkg/kubectl/cmd\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" ) func NewKubectlServer() *Server { cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr) localFlags := cmd.LocalFlags() localFlags.SetInterspersed(false) return &Server{ name: \"kubectl\", SimpleUsage: \"Kubernetes command line client\", Long: \"Kubernetes command line client\", Run: func(s *Server, args []string) error { os.Args = os.Args[1:] if err := app.Run(); err != nil { os.Exit(1) } os.Exit(0) return nil cmd.SetArgs(args) return cmd.Execute() }, flags: localFlags, } }"} {"_id":"doc-en-kubernetes-2732fcd5dc2223412874546d8b3bedb1e727b310d439895f172a715346f9e11c","title":"","text":"cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" ) /* WARNING: this logic is duplicated, with minor changes, in cmd/hyperkube/kubectl.go Any salient changes here will need to be manually reflected in that file. */ func Run() error { cmd := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, os.Stdout, os.Stderr) return cmd.Execute()"} {"_id":"doc-en-kubernetes-fa09ab41b5e12bb6bc8ee74665b9e578edcbfc2894e7a160da324531e4b96bc7","title":"","text":"\"k8s.io/kubernetes/pkg/kubelet/network\" proberesults \"k8s.io/kubernetes/pkg/kubelet/prober/results\" kubetypes \"k8s.io/kubernetes/pkg/kubelet/types\" \"k8s.io/kubernetes/pkg/kubelet/util/cache\" \"k8s.io/kubernetes/pkg/types\" \"k8s.io/kubernetes/pkg/util/flowcontrol\" \"k8s.io/kubernetes/pkg/util/oom\""} {"_id":"doc-en-kubernetes-73ce865f9c34194f1c7450d11e4c6f130974cd16147e0f9040323cc00396a57a","title":"","text":"burst, containerLogsDir, osInterface, networkPlugin, runtimeHelper, httpClient, &NativeExecHandler{}, fakeOOMAdjuster, fakeProcFs, false, imageBackOff, false, false, true) dm.dockerPuller = &FakeDockerPuller{} dm.versionCache = cache.NewVersionCache(func() (kubecontainer.Version, kubecontainer.Version, error) { return dm.getVersionInfo() }) return dm }"} {"_id":"doc-en-kubernetes-09f55eea4acb93558518e82e86888b5d51a02329e1f53f0f6f8d89efab01f261","title":"","text":"optf(dm) } // initialize versionCache with a updater dm.versionCache = cache.NewVersionCache(func() (kubecontainer.Version, kubecontainer.Version, error) { return dm.getVersionInfo() }) // update version cache periodically. if dm.machineInfo != nil { dm.versionCache.UpdateCachePeriodly(dm.machineInfo.MachineID) } return dm }"} {"_id":"doc-en-kubernetes-dafa5b1f678212301837456775a8e4b09e095095055e34f4f0a6e870bc468b0c","title":"","text":"return oomScoreAdj } // getCachedVersionInfo gets cached version info of docker runtime. func (dm *DockerManager) getCachedVersionInfo() (kubecontainer.Version, kubecontainer.Version, error) { apiVersion, daemonVersion, err := dm.versionCache.Get(dm.machineInfo.MachineID) if err != nil { glog.Errorf(\"Failed to get cached docker api version %v \", err) } // If we got nil versions, try to update version info. if apiVersion == nil || daemonVersion == nil { dm.versionCache.Update(dm.machineInfo.MachineID) } return apiVersion, daemonVersion, err } // checkDockerAPIVersion checks current docker API version against expected version. // Return: // 1 : newer than expected version // -1: older than expected version // 0 : same version func (dm *DockerManager) checkDockerAPIVersion(expectedVersion string) (int, error) { apiVersion, _, err := dm.getCachedVersionInfo() apiVersion, _, err := dm.getVersionInfo() if err != nil { return 0, err }"} {"_id":"doc-en-kubernetes-b51f398c3bc15849aa3a4777151155bf9245b507833de557d3ef844055825539","title":"","text":"// Generate final API pod status with pod and status manager status apiPodStatus := kl.generateAPIPodStatus(pod, podStatus) // The pod IP may be changed in generateAPIPodStatus if the pod is using host network. (See #24576) // TODO(random-liu): After writing pod spec into container labels, check whether pod is using host network, and // set pod IP to hostIP directly in runtime.GetPodStatus podStatus.IP = apiPodStatus.PodIP // Record the time it takes for the pod to become running. existingStatus, ok := kl.statusManager.GetPodStatus(pod.UID)"} {"_id":"doc-en-kubernetes-a3c53f1d3c2a0f33bd9744b965463523b96d8a82534c913c98122e70cdfcec94","title":"","text":"\"syscall\" \"github.com/vishvananda/netlink\" \"github.com/vishvananda/netlink/nl\" \"github.com/appc/cni/libcni\" \"github.com/golang/glog\""} {"_id":"doc-en-kubernetes-9ecff11b15f008bfbec7f4ae222c722425b90792c6a83bff9eff2e0b3ab41c65","title":"","text":"} } // ensureBridgeTxQueueLen() ensures that the bridge interface's TX queue // length is greater than zero. Due to a CNI <= 0.3.0 'bridge' plugin bug, // the bridge is initially created with a TX queue length of 0, which gets // used as the packet limit for FIFO traffic shapers, which drops packets. // TODO: remove when we can depend on a fixed CNI func (plugin *kubenetNetworkPlugin) ensureBridgeTxQueueLen() { bridge, err := netlink.LinkByName(BridgeName) if err != nil { return } if bridge.Attrs().TxQLen > 0 { return } req := nl.NewNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) msg := nl.NewIfInfomsg(syscall.AF_UNSPEC) req.AddData(msg) nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(BridgeName)) req.AddData(nameData) qlen := nl.NewRtAttr(syscall.IFLA_TXQLEN, nl.Uint32Attr(1000)) req.AddData(qlen) _, err = req.Execute(syscall.NETLINK_ROUTE, 0) if err != nil { glog.V(5).Infof(\"Failed to set bridge tx queue length: %v\", err) } } func (plugin *kubenetNetworkPlugin) Name() string { return KubenetPluginName }"} {"_id":"doc-en-kubernetes-c9af439bc4a04e9b96a7f947cdb41d824b986a2f523b29ea5b10c5470fe64e1c","title":"","text":"if plugin.shaper == nil { return fmt.Errorf(\"Failed to create bandwidth shaper!\") } plugin.ensureBridgeTxQueueLen() plugin.shaper.ReconcileInterface() }"} {"_id":"doc-en-kubernetes-ea45481e59b7183b1c5731c475b389e629267fa25fcb65e821a0a96c378d9229","title":"","text":"// service account no longer exists, so delete related tokens glog.V(4).Infof(\"syncServiceAccount(%s/%s), service account deleted, removing tokens\", saInfo.namespace, saInfo.name) sa = &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: saInfo.namespace, Name: saInfo.name, UID: saInfo.uid}} if retriable, err := e.deleteTokens(sa); err != nil { retry, err = e.deleteTokens(sa) if err != nil { glog.Errorf(\"error deleting serviceaccount tokens for %s/%s: %v\", saInfo.namespace, saInfo.name, err) retry = retriable } default: // ensure a token exists and is referenced by this service account if retriable, err := e.ensureReferencedToken(sa); err != nil { retry, err = e.ensureReferencedToken(sa) if err != nil { glog.Errorf(\"error synchronizing serviceaccount %s/%s: %v\", saInfo.namespace, saInfo.name, err) retry = retriable } } }"} {"_id":"doc-en-kubernetes-baa4893a8c01d707a5e1112a068b11dfc4e1ce9ad2f29c35554bf42206b5d190","title":"","text":"// ensureReferencedToken makes sure at least one ServiceAccountToken secret exists, and is included in the serviceAccount's Secrets list func (e *TokensController) ensureReferencedToken(serviceAccount *v1.ServiceAccount) ( /* retry */ bool, error) { if len(serviceAccount.Secrets) > 0 { allSecrets, err := e.listTokenSecrets(serviceAccount) if err != nil { // Don't retry cache lookup errors return false, err } referencedSecrets := getSecretReferences(serviceAccount) for _, secret := range allSecrets { if referencedSecrets.Has(secret.Name) { // A service account token already exists, and is referenced, short-circuit return false, nil } } if hasToken, err := e.hasReferencedToken(serviceAccount); err != nil { // Don't retry cache lookup errors return false, err } else if hasToken { // A service account token already exists, and is referenced, short-circuit return false, nil } // We don't want to update the cache's copy of the service account"} {"_id":"doc-en-kubernetes-3e8c3b013ef13b1449ad4bd2c712c4adc618d1f92caecbaf5a3c12b471ddd637","title":"","text":"serviceAccounts := e.client.Core().ServiceAccounts(serviceAccount.Namespace) liveServiceAccount, err := serviceAccounts.Get(serviceAccount.Name, metav1.GetOptions{}) if err != nil { // Retry for any error other than a NotFound return !apierrors.IsNotFound(err), err // Retry if we cannot fetch the live service account (for a NotFound error, either the live lookup or our cache are stale) return true, err } if liveServiceAccount.ResourceVersion != serviceAccount.ResourceVersion { // our view of the service account is not up to date // we'll get notified of an update event later and get to try again glog.V(2).Infof(\"serviceaccount %s/%s is not up to date, skipping token creation\", serviceAccount.Namespace, serviceAccount.Name) return false, nil // Retry if our liveServiceAccount doesn't match our cache's resourceVersion (either the live lookup or our cache are stale) glog.V(4).Infof(\"liveServiceAccount.ResourceVersion (%s) does not match cache (%s), retrying\", liveServiceAccount.ResourceVersion, serviceAccount.ResourceVersion) return true, nil } // Build the secret"} {"_id":"doc-en-kubernetes-064722e3b12f197af86bf290d62916e3abb7e4afb7ce983a078a079a3467a239","title":"","text":"// This prevents the service account update (below) triggering another token creation, if the referenced token couldn't be found in the store e.secrets.Add(createdToken) liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, v1.ObjectReference{Name: secret.Name}) // Try to add a reference to the newly created token to the service account addedReference := false err = clientretry.RetryOnConflict(clientretry.DefaultRetry, func() error { // refresh liveServiceAccount on every retry defer func() { liveServiceAccount = nil }() // fetch the live service account if needed, and verify the UID matches and that we still need a token if liveServiceAccount == nil { liveServiceAccount, err = serviceAccounts.Get(serviceAccount.Name, metav1.GetOptions{}) if err != nil { return err } if liveServiceAccount.UID != serviceAccount.UID { // If we don't have the same service account, stop trying to add a reference to the token made for the old service account. return nil } if hasToken, err := e.hasReferencedToken(liveServiceAccount); err != nil { // Don't retry cache lookup errors return nil } else if hasToken { // A service account token already exists, and is referenced, short-circuit return nil } } // Try to add a reference to the token liveServiceAccount.Secrets = append(liveServiceAccount.Secrets, v1.ObjectReference{Name: secret.Name}) if _, err := serviceAccounts.Update(liveServiceAccount); err != nil { return err } if _, err = serviceAccounts.Update(liveServiceAccount); err != nil { addedReference = true return nil }) if !addedReference { // we weren't able to use the token, try to clean it up. glog.V(2).Infof(\"deleting secret %s/%s because reference couldn't be added (%v)\", secret.Namespace, secret.Name, err) deleteOpts := &metav1.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &createdToken.UID}} if deleteErr := e.client.Core().Secrets(createdToken.Namespace).Delete(createdToken.Name, deleteOpts); deleteErr != nil { glog.Error(deleteErr) // if we fail, just log it } } if err != nil { if apierrors.IsConflict(err) || apierrors.IsNotFound(err) { // if we got a Conflict error, the service account was updated by someone else, and we'll get an update notification later // if we got a NotFound error, the service account no longer exists, and we don't need to create a token for it"} {"_id":"doc-en-kubernetes-0bbd89e62d5f54a1a58962448bd84050df38dd6f1d5d74a4d56517716f679a28","title":"","text":"return false, nil } // hasReferencedToken returns true if the serviceAccount references a service account token secret func (e *TokensController) hasReferencedToken(serviceAccount *v1.ServiceAccount) (bool, error) { if len(serviceAccount.Secrets) == 0 { return false, nil } allSecrets, err := e.listTokenSecrets(serviceAccount) if err != nil { return false, err } referencedSecrets := getSecretReferences(serviceAccount) for _, secret := range allSecrets { if referencedSecrets.Has(secret.Name) { return true, nil } } return false, nil } func (e *TokensController) secretUpdateNeeded(secret *v1.Secret) (bool, bool, bool) { caData := secret.Data[v1.ServiceAccountRootCAKey] needsCA := len(e.rootCA) > 0 && bytes.Compare(caData, e.rootCA) != 0"} {"_id":"doc-en-kubernetes-56cb17bd52acb3a37faf611beea7d9e20a6db552816eb00e094c7443cf6cec85","title":"","text":"\"k8s.io/kubernetes/pkg/api/errors\" \"k8s.io/kubernetes/pkg/api/testapi\" \"k8s.io/kubernetes/pkg/api/unversioned\" \"k8s.io/kubernetes/pkg/client/restclient\" \"k8s.io/kubernetes/pkg/client/unversioned/fake\" )"} {"_id":"doc-en-kubernetes-2da289ba6f0cfb2972610e5a6ac56552c36d94377f9f65cd63323e56c1658600","title":"","text":"t.Errorf(\"unexpected output: %s\", buf.String()) } } func TestResourceErrors(t *testing.T) { testCases := map[string]struct { args []string flags map[string]string errFn func(error) bool }{ \"no args\": { args: []string{}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"you must provide one or more resources\") }, }, \"resources but no selectors\": { args: []string{\"pods\"}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"resource(s) were provided, but no name, label selector, or --all flag specified\") }, }, \"multiple resources but no selectors\": { args: []string{\"pods,deployments\"}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"resource(s) were provided, but no name, label selector, or --all flag specified\") }, }, } for k, testCase := range testCases { f, tf, _ := NewAPIFactory() tf.Printer = &testPrinter{} tf.Namespace = \"test\" tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}} buf := bytes.NewBuffer([]byte{}) cmd := NewCmdDelete(f, buf) cmd.SetOutput(buf) for k, v := range testCase.flags { cmd.Flags().Set(k, v) } err := RunDelete(f, buf, cmd, testCase.args, &DeleteOptions{}) if !testCase.errFn(err) { t.Errorf(\"%s: unexpected error: %v\", k, err) continue } if tf.Printer.(*testPrinter).Objects != nil { t.Errorf(\"unexpected print to default printer\") } if buf.Len() > 0 { t.Errorf(\"buffer should be empty: %s\", string(buf.Bytes())) } } } "} {"_id":"doc-en-kubernetes-b7dba791c3185946230869a336da6b130d5f116b10b729980ddab13cda2dce1b","title":"","text":"args: []string{\"pods=bar\"}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"one or more resources must be specified\") }, }, \"resources but no selectors\": { args: []string{\"pods\", \"app=bar\"}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"resource(s) were provided, but no name, label selector, or --all flag specified\") }, }, \"multiple resources but no selectors\": { args: []string{\"pods,deployments\", \"app=bar\"}, errFn: func(err error) bool { return strings.Contains(err.Error(), \"resource(s) were provided, but no name, label selector, or --all flag specified\") }, }, } for k, testCase := range testCases {"} {"_id":"doc-en-kubernetes-5c3292f0e598bb785460032640759b3a0aa1fae75c3ed3cf2c18376f38d6496e","title":"","text":"return &Result{singular: singular, visitor: visitors, sources: b.paths} } if len(b.resources) != 0 { return &Result{err: fmt.Errorf(\"resource(s) were provided, but no name, label selector, or --all flag specified\")} } return &Result{err: fmt.Errorf(\"you must provide one or more resources by argument or filename (%s)\", strings.Join(InputExtensions, \"|\"))} }"} {"_id":"doc-en-kubernetes-65761135dc6bf6eb8bdd425ce249d937f86ec5d89c67e113ce20faf48d97ab16","title":"","text":"package app import ( \"errors\" \"io/ioutil\" \"strconv\" \"github.com/golang/glog\" \"k8s.io/kubernetes/pkg/util/mount\" \"k8s.io/kubernetes/pkg/util/sysctl\" )"} {"_id":"doc-en-kubernetes-76bbdf5b01ccd140fbfe4437655cd672e6a70e95523ed0bc530be69d8b5accce","title":"","text":"type realConntracker struct{} var readOnlySysFSError = errors.New(\"ReadOnlySysFS\") func (realConntracker) SetMax(max int) error { glog.Infof(\"Setting nf_conntrack_max to %d\", max) if err := sysctl.SetSysctl(\"net/netfilter/nf_conntrack_max\", max); err != nil { return err } // sysfs is expected to be mounted as 'rw'. However, it may be unexpectedly mounted as // 'ro' by docker because of a known docker issue (https://github.com/docker/docker/issues/24000). // Setting conntrack will fail when sysfs is readonly. When that happens, we don't set conntrack // hashsize and return a special error readOnlySysFSError here. The caller should deal with // readOnlySysFSError differently. writable, err := isSysFSWritable() if err != nil { return err } if !writable { return readOnlySysFSError } // TODO: generify this and sysctl to a new sysfs.WriteInt() glog.Infof(\"Setting conntrack hashsize to %d\", max/4) return ioutil.WriteFile(\"/sys/module/nf_conntrack/parameters/hashsize\", []byte(strconv.Itoa(max/4)), 0640)"} {"_id":"doc-en-kubernetes-5aafaa33c8f67ada86bc7f3ddba017f54eff4527436c3451e62ae5003294d095","title":"","text":"glog.Infof(\"Setting nf_conntrack_tcp_timeout_established to %d\", seconds) return sysctl.SetSysctl(\"net/netfilter/nf_conntrack_tcp_timeout_established\", seconds) } // isSysFSWritable checks /proc/mounts to see whether sysfs is 'rw' or not. func isSysFSWritable() (bool, error) { const permWritable = \"rw\" const sysfsDevice = \"sysfs\" m := mount.New() mountPoints, err := m.List() if err != nil { glog.Errorf(\"failed to list mount points: %v\", err) return false, err } for _, mountPoint := range mountPoints { if mountPoint.Device != sysfsDevice { continue } // Check whether sysfs is 'rw' if len(mountPoint.Opts) > 0 && mountPoint.Opts[0] == permWritable { return true, nil } glog.Errorf(\"sysfs is not writable: %+v\", mountPoint) break } return false, nil } "} {"_id":"doc-en-kubernetes-501fb9b94e8dae0f57a8864afbad3b3c2a554a99411fa68dc33e7d26e5467768","title":"","text":"// Tune conntrack, if requested if s.Conntracker != nil { if s.Config.ConntrackMax > 0 { if err := s.Conntracker.SetMax(int(s.Config.ConntrackMax)); err != nil { return err err := s.Conntracker.SetMax(int(s.Config.ConntrackMax)) if err != nil { if err != readOnlySysFSError { return err } // readOnlySysFSError is caused by a known docker issue (https://github.com/docker/docker/issues/24000), // the only remediation we know is to restart the docker daemon. // Here we'll send an node event with specific reason and message, the // administrator should decide whether and how to handle this issue, // whether to drain the node and restart docker. // TODO(random-liu): Remove this when the docker bug is fixed. const message = \"DOCKER RESTART NEEDED (docker issue #24000): /sys is read-only: can't raise conntrack limits, problems may arise later.\" s.Recorder.Eventf(s.Config.NodeRef, api.EventTypeWarning, err.Error(), message) } } if s.Config.ConntrackTCPEstablishedTimeout.Duration > 0 {"} {"_id":"doc-en-kubernetes-0add599a93d358f290a387b56036fbc30b2730b80f6813b5c9c22b4ca3a693dd","title":"","text":"return ConformanceContainer{containers[0], cc.Client, pod.Spec.RestartPolicy, pod.Spec.Volumes, pod.Spec.NodeName, cc.Namespace, cc.podName}, nil } func (cc *ConformanceContainer) GetStatus() (api.ContainerStatus, api.PodPhase, error) { func (cc *ConformanceContainer) IsReady() (bool, error) { pod, err := cc.Client.Pods(cc.Namespace).Get(cc.podName) if err != nil { return api.ContainerStatus{}, api.PodUnknown, err return false, err } return api.IsPodReady(pod), nil } func (cc *ConformanceContainer) GetPhase() (api.PodPhase, error) { pod, err := cc.Client.Pods(cc.Namespace).Get(cc.podName) if err != nil { return api.PodUnknown, err } return pod.Status.Phase, nil } func (cc *ConformanceContainer) GetStatus() (api.ContainerStatus, error) { pod, err := cc.Client.Pods(cc.Namespace).Get(cc.podName) if err != nil { return api.ContainerStatus{}, err } statuses := pod.Status.ContainerStatuses if len(statuses) != 1 { return api.ContainerStatus{}, api.PodUnknown, errors.New(\"Failed to get container status\") if len(statuses) != 1 || statuses[0].Name != cc.Container.Name { return api.ContainerStatus{}, fmt.Errorf(\"unexpected container statuses %v\", statuses) } return statuses[0], pod.Status.Phase, nil return statuses[0], nil } func (cc *ConformanceContainer) Present() (bool, error) {"} {"_id":"doc-en-kubernetes-e9667b2811b19740015a8be453bcbd6266f3c63c1f6844c8f4fc51b2b4247d91","title":"","text":"return false, err } type ContainerState uint32 type ContainerState int const ( ContainerStateWaiting ContainerState = 1 << iota ContainerStateWaiting ContainerState = iota ContainerStateRunning ContainerStateTerminated ContainerStateUnknown"} {"_id":"doc-en-kubernetes-7d0f20186558116c9d129aeb57603503414062cc233f706e09a46ac42458dea2","title":"","text":"pollInterval = time.Second * 5 ) type testStatus struct { type testCase struct { Name string RestartPolicy api.RestartPolicy Phase api.PodPhase"} {"_id":"doc-en-kubernetes-4e168ee6cfc5455ee91a2f8533b45baa279be7ee82cf7959efa154230df67aca","title":"","text":"Ready bool } var _ = Describe(\"[FLAKY] Container runtime Conformance Test\", func() { var _ = Describe(\"Container Runtime Conformance Test\", func() { var cl *client.Client BeforeEach(func() {"} {"_id":"doc-en-kubernetes-496cd48fe616df40d2b146e60cbcbe9c969e7343befa940d388791893a4b05f3","title":"","text":"}) Describe(\"container runtime conformance blackbox test\", func() { var testCContainers []ConformanceContainer namespace := \"runtime-conformance\" BeforeEach(func() { testCContainers = []ConformanceContainer{} }) Context(\"when start a container that exits successfully\", func() { Context(\"when starting a container that exits\", func() { It(\"it should run with the expected status [Conformance]\", func() { restartCountVolumeName := \"restart-count\" restartCountVolumePath := \"/restart-count\" testContainer := api.Container{ Image: ImageRegistry[busyBoxImage], VolumeMounts: []api.VolumeMount{ { MountPath: \"/restart-count\", Name: \"restart-count\", MountPath: restartCountVolumePath, Name: restartCountVolumeName, }, }, ImagePullPolicy: api.PullIfNotPresent, } testVolumes := []api.Volume{ { Name: \"restart-count\", Name: restartCountVolumeName, VolumeSource: api.VolumeSource{ HostPath: &api.HostPathVolumeSource{ Path: os.TempDir(),"} {"_id":"doc-en-kubernetes-f3e748c2e76fd0090cbfd20256785c7a206152780844463dca8007770c4a0d37","title":"","text":"}, }, } testCount := int32(3) testStatuses := []testStatus{ {\"terminate-cmd-rpa\", api.RestartPolicyAlways, api.PodRunning, ContainerStateWaiting | ContainerStateRunning | ContainerStateTerminated, \">\", testCount, false}, {\"terminate-cmd-rpof\", api.RestartPolicyOnFailure, api.PodSucceeded, ContainerStateTerminated, \"==\", testCount, false}, {\"terminate-cmd-rpn\", api.RestartPolicyNever, api.PodSucceeded, ContainerStateTerminated, \"==\", 0, false}, testCases := []testCase{ {\"terminate-cmd-rpa\", api.RestartPolicyAlways, api.PodRunning, ContainerStateRunning, \"==\", 2, true}, {\"terminate-cmd-rpof\", api.RestartPolicyOnFailure, api.PodSucceeded, ContainerStateTerminated, \"==\", 1, false}, {\"terminate-cmd-rpn\", api.RestartPolicyNever, api.PodFailed, ContainerStateTerminated, \"==\", 0, false}, } for _, testStatus := range testStatuses { for _, testCase := range testCases { tmpFile, err := ioutil.TempFile(\"\", \"restartCount\") Expect(err).NotTo(HaveOccurred()) defer os.Remove(tmpFile.Name()) // It fails in the first three runs and succeeds after that. tmpCmd := fmt.Sprintf(\"echo 'hello' >> /restart-count/%s ; test $(wc -l /restart-count/%s| awk {'print $1'}) -ge %d\", path.Base(tmpFile.Name()), path.Base(tmpFile.Name()), testCount+1) testContainer.Name = testStatus.Name // It failed at the 1st run, then succeeded at 2nd run, then run forever cmdScripts := ` f=%s count=$(echo 'hello' >> $f ; wc -l $f | awk {'print $1'}) if [ $count -eq 1 ]; then exit 1 fi if [ $count -eq 2 ]; then exit 0 fi while true; do sleep 1; done ` tmpCmd := fmt.Sprintf(cmdScripts, path.Join(restartCountVolumePath, path.Base(tmpFile.Name()))) testContainer.Name = testCase.Name testContainer.Command = []string{\"sh\", \"-c\", tmpCmd} terminateContainer := ConformanceContainer{ Container: testContainer, Client: cl, RestartPolicy: testStatus.RestartPolicy, RestartPolicy: testCase.RestartPolicy, Volumes: testVolumes, NodeName: *nodeName, Namespace: namespace, } err = terminateContainer.Create() Expect(err).NotTo(HaveOccurred()) testCContainers = append(testCContainers, terminateContainer) Expect(terminateContainer.Create()).To(Succeed()) defer terminateContainer.Delete() Eventually(func() api.PodPhase { _, phase, _ := terminateContainer.GetStatus() return phase }, retryTimeout, pollInterval).ShouldNot(Equal(api.PodPending)) var status api.ContainerStatus By(\"it should get the expected 'RestartCount'\") Eventually(func() int32 { status, _, _ = terminateContainer.GetStatus() return status.RestartCount }, retryTimeout, pollInterval).Should(BeNumerically(testStatus.RestartCountOper, testStatus.RestartCount)) Eventually(func() (int32, error) { status, err := terminateContainer.GetStatus() return status.RestartCount, err }, retryTimeout, pollInterval).Should(BeNumerically(testCase.RestartCountOper, testCase.RestartCount)) By(\"it should get the expected 'Ready' status\") Expect(status.Ready).To(Equal(testStatus.Ready)) By(\"it should get the expected 'Phase'\") Eventually(terminateContainer.GetPhase, retryTimeout, pollInterval).Should(Equal(testCase.Phase)) By(\"it should get the expected 'State'\") Expect(GetContainerState(status.State) & testStatus.State).NotTo(Equal(0)) By(\"it should get the expected 'Ready' condition\") Expect(terminateContainer.IsReady()).Should(Equal(testCase.Ready)) By(\"it should be possible to delete [Conformance]\") err = terminateContainer.Delete() Expect(err).NotTo(HaveOccurred()) Eventually(func() bool { isPresent, err := terminateContainer.Present() return err == nil && !isPresent }, retryTimeout, pollInterval).Should(BeTrue()) } }) }) Context(\"when start a container that keeps running\", func() { It(\"it should run with the expected status [Conformance]\", func() { testContainer := api.Container{ Image: ImageRegistry[busyBoxImage], Command: []string{\"sh\", \"-c\", \"while true; do echo hello; sleep 1; done\"}, ImagePullPolicy: api.PullIfNotPresent, } testStatuses := []testStatus{ {\"loop-cmd-rpa\", api.RestartPolicyAlways, api.PodRunning, ContainerStateRunning, \"==\", 0, true}, {\"loop-cmd-rpof\", api.RestartPolicyOnFailure, api.PodRunning, ContainerStateRunning, \"==\", 0, true}, {\"loop-cmd-rpn\", api.RestartPolicyNever, api.PodRunning, ContainerStateRunning, \"==\", 0, true}, } for _, testStatus := range testStatuses { testContainer.Name = testStatus.Name runningContainer := ConformanceContainer{ Container: testContainer, Client: cl, RestartPolicy: testStatus.RestartPolicy, NodeName: *nodeName, Namespace: namespace, } err := runningContainer.Create() Expect(err).NotTo(HaveOccurred()) testCContainers = append(testCContainers, runningContainer) Eventually(func() api.PodPhase { _, phase, _ := runningContainer.GetStatus() return phase }, retryTimeout, pollInterval).Should(Equal(api.PodRunning)) var status api.ContainerStatus var phase api.PodPhase Consistently(func() api.PodPhase { status, phase, err = runningContainer.GetStatus() return phase }, consistentCheckTimeout, pollInterval).Should(Equal(testStatus.Phase)) Expect(err).NotTo(HaveOccurred()) By(\"it should get the expected 'RestartCount'\") Expect(status.RestartCount).To(BeNumerically(testStatus.RestartCountOper, testStatus.RestartCount)) By(\"it should get the expected 'Ready' status\") Expect(status.Ready).To(Equal(testStatus.Ready)) status, err := terminateContainer.GetStatus() Expect(err).ShouldNot(HaveOccurred()) By(\"it should get the expected 'State'\") Expect(GetContainerState(status.State) & testStatus.State).NotTo(Equal(0)) Expect(GetContainerState(status.State)).To(Equal(testCase.State)) By(\"it should be possible to delete [Conformance]\") err = runningContainer.Delete() Expect(err).NotTo(HaveOccurred()) Eventually(func() bool { isPresent, err := runningContainer.Present() return err == nil && !isPresent }, retryTimeout, pollInterval).Should(BeTrue()) } }) }) Context(\"when start a container that exits failure\", func() { It(\"it should run with the expected status [Conformance]\", func() { testContainer := api.Container{ Image: ImageRegistry[busyBoxImage], Command: []string{\"false\"}, ImagePullPolicy: api.PullIfNotPresent, } testStatuses := []testStatus{ {\"fail-cmd-rpa\", api.RestartPolicyAlways, api.PodRunning, ContainerStateWaiting | ContainerStateRunning | ContainerStateTerminated, \">\", 0, false}, {\"fail-cmd-rpof\", api.RestartPolicyOnFailure, api.PodRunning, ContainerStateTerminated, \">\", 0, false}, {\"fail-cmd-rpn\", api.RestartPolicyNever, api.PodFailed, ContainerStateTerminated, \"==\", 0, false}, } for _, testStatus := range testStatuses { testContainer.Name = testStatus.Name failureContainer := ConformanceContainer{ Container: testContainer, Client: cl, RestartPolicy: testStatus.RestartPolicy, NodeName: *nodeName, Namespace: namespace, } err := failureContainer.Create() Expect(err).NotTo(HaveOccurred()) testCContainers = append(testCContainers, failureContainer) Eventually(func() api.PodPhase { _, phase, _ := failureContainer.GetStatus() return phase }, retryTimeout, pollInterval).ShouldNot(Equal(api.PodPending)) var status api.ContainerStatus By(\"it should get the expected 'RestartCount'\") Eventually(func() int32 { status, _, _ = failureContainer.GetStatus() return status.RestartCount }, retryTimeout, pollInterval).Should(BeNumerically(testStatus.RestartCountOper, testStatus.RestartCount)) By(\"it should get the expected 'Ready' status\") Expect(status.Ready).To(Equal(testStatus.Ready)) By(\"it should get the expected 'State'\") Expect(GetContainerState(status.State) & testStatus.State).NotTo(Equal(0)) By(\"it should be possible to delete [Conformance]\") err = failureContainer.Delete() Expect(err).NotTo(HaveOccurred()) Eventually(func() bool { isPresent, err := failureContainer.Present() return err == nil && !isPresent }, retryTimeout, pollInterval).Should(BeTrue()) Expect(terminateContainer.Delete()).To(Succeed()) Eventually(terminateContainer.Present, retryTimeout, pollInterval).Should(BeFalse()) } }) })"} {"_id":"doc-en-kubernetes-42d7e3f6a08032abb5df01459fb8cbc97fc3e40e70bfe2e1bb39f3f732e3cdc9","title":"","text":"Context(\"when running a container with invalid image\", func() { It(\"it should run with the expected status [Conformance]\", func() { testContainer := api.Container{ Image: \"foo.com/foo/foo\", Command: []string{\"false\"}, ImagePullPolicy: api.PullIfNotPresent, Image: \"foo.com/foo/foo\", Command: []string{\"false\"}, } testStatus := testStatus{\"invalid-image-rpa\", api.RestartPolicyAlways, api.PodPending, ContainerStateWaiting, \"==\", 0, false} testContainer.Name = testStatus.Name testCase := testCase{\"invalid-image-rpa\", api.RestartPolicyAlways, api.PodPending, ContainerStateWaiting, \"==\", 0, false} testContainer.Name = testCase.Name invalidImageContainer := ConformanceContainer{ Container: testContainer, Client: cl, RestartPolicy: testStatus.RestartPolicy, RestartPolicy: testCase.RestartPolicy, NodeName: *nodeName, Namespace: namespace, } err := invalidImageContainer.Create() Expect(err).NotTo(HaveOccurred()) testCContainers = append(testCContainers, invalidImageContainer) Expect(invalidImageContainer.Create()).To(Succeed()) defer invalidImageContainer.Delete() var status api.ContainerStatus var phase api.PodPhase Eventually(invalidImageContainer.GetPhase, retryTimeout, pollInterval).Should(Equal(testCase.Phase)) Consistently(invalidImageContainer.GetPhase, consistentCheckTimeout, pollInterval).Should(Equal(testCase.Phase)) Consistently(func() api.PodPhase { if status, phase, err = invalidImageContainer.GetStatus(); err != nil { return api.PodPending } else { return phase } }, consistentCheckTimeout, pollInterval).Should(Equal(testStatus.Phase)) status, err := invalidImageContainer.GetStatus() Expect(err).NotTo(HaveOccurred()) By(\"it should get the expected 'RestartCount'\") Expect(status.RestartCount).To(BeNumerically(testStatus.RestartCountOper, testStatus.RestartCount)) Expect(status.RestartCount).To(BeNumerically(testCase.RestartCountOper, testCase.RestartCount)) By(\"it should get the expected 'Ready' status\") Expect(status.Ready).To(Equal(testStatus.Ready)) Expect(status.Ready).To(Equal(testCase.Ready)) By(\"it should get the expected 'State'\") Expect(GetContainerState(status.State) & testStatus.State).NotTo(Equal(0)) Expect(GetContainerState(status.State)).To(Equal(testCase.State)) By(\"it should be possible to delete [Conformance]\") err = invalidImageContainer.Delete() Expect(err).NotTo(HaveOccurred()) Eventually(func() bool { isPresent, err := invalidImageContainer.Present() return err == nil && !isPresent }, retryTimeout, pollInterval).Should(BeTrue()) Expect(invalidImageContainer.Delete()).To(Succeed()) Eventually(invalidImageContainer.Present, retryTimeout, pollInterval).Should(BeFalse()) }) }) AfterEach(func() { for _, cc := range testCContainers { cc.Delete() } }) }) })"} {"_id":"doc-en-kubernetes-e49efa8702d2dd204b45132c7f0e661de28a43edea50722af099a2b0e3f58a6e","title":"","text":"import ( \"fmt\" \"io\" \"sort\" \"strconv\" \"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/meta\""} {"_id":"doc-en-kubernetes-9202faa481fc18e47dc861a99a0c6677932eb1d73ae82a64b3845d2a2aef4467","title":"","text":"clientset \"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset\" \"k8s.io/kubernetes/pkg/runtime\" deploymentutil \"k8s.io/kubernetes/pkg/util/deployment\" \"k8s.io/kubernetes/pkg/util/errors\" sliceutil \"k8s.io/kubernetes/pkg/util/slice\" ) const ("} {"_id":"doc-en-kubernetes-bdef9988174204850b71afad632e59270b0b2164fb9eb972197a6a8cfbaa0db0","title":"","text":"return fmt.Sprintf(\"No rollout history found in %s %q\", resource, name), nil } // Sort the revisionToChangeCause map by revision var revisions []string for k := range historyInfo.RevisionToTemplate { revisions = append(revisions, strconv.FormatInt(k, 10)) var revisions []int64 for r := range historyInfo.RevisionToTemplate { revisions = append(revisions, r) } sort.Strings(revisions) sliceutil.SortInts64(revisions) return tabbedString(func(out io.Writer) error { fmt.Fprintf(out, \"%s %q:n\", resource, name) fmt.Fprintf(out, \"REVISIONtCHANGE-CAUSEn\") errs := []error{} for _, r := range revisions { // Find the change-cause of revision r r64, err := strconv.ParseInt(r, 10, 64) if err != nil { errs = append(errs, err) continue } changeCause := historyInfo.RevisionToTemplate[r64].Annotations[ChangeCauseAnnotation] changeCause := historyInfo.RevisionToTemplate[r].Annotations[ChangeCauseAnnotation] if len(changeCause) == 0 { changeCause = \"\" } fmt.Fprintf(out, \"%st%sn\", r, changeCause) fmt.Fprintf(out, \"%dt%sn\", r, changeCause) } return errors.NewAggregate(errs) return nil }) }"} {"_id":"doc-en-kubernetes-beeb26d9d3f67a6478696b0b6a7d4bc41517b362f9b5d4c280e6f6d1e1e91990","title":"","text":"} return shuffled } // Int64Slice attaches the methods of Interface to []int64, // sorting in increasing order. type Int64Slice []int64 func (p Int64Slice) Len() int { return len(p) } func (p Int64Slice) Less(i, j int) bool { return p[i] < p[j] } func (p Int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Sorts []int64 in increasing order func SortInts64(a []int64) { sort.Sort(Int64Slice(a)) } "} {"_id":"doc-en-kubernetes-360921e4f4f43f476ab8d5fa4fa35d2234f8c9bb7e3cd7b93aa56e9ffd46d1e3","title":"","text":"} } } func TestSortInts64(t *testing.T) { src := []int64{10, 1, 2, 3, 4, 5, 6} expected := []int64{1, 2, 3, 4, 5, 6, 10} SortInts64(src) if !reflect.DeepEqual(src, expected) { t.Errorf(\"func Ints64 didnt sort correctly, %v !- %v\", src, expected) } } "} {"_id":"doc-en-kubernetes-949d74511ac1c896810bbf3584cb5ea2759a6395486370578a4d1893b94b4c6d","title":"","text":"numVolumes++ allErrs = append(allErrs, validateAzureFile(source.AzureFile, fldPath.Child(\"azureFile\"))...) } if source.VsphereVolume != nil { if numVolumes > 0 { allErrs = append(allErrs, field.Forbidden(fldPath.Child(\"vsphereVolume\"), \"may not specify more than 1 volume type\")) } else { numVolumes++ allErrs = append(allErrs, validateVsphereVolumeSource(source.VsphereVolume, fldPath.Child(\"vsphereVolume\"))...) } } if numVolumes == 0 { allErrs = append(allErrs, field.Required(fldPath, \"must specify a volume type\")) }"} {"_id":"doc-en-kubernetes-8d7511a03199b15d96f41c7fec845f5d20d46cc4015030fee26a111eb337c9c9","title":"","text":"return allErrs } func validateVsphereVolumeSource(cd *api.VsphereVirtualDiskVolumeSource, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} if len(cd.VolumePath) == 0 { allErrs = append(allErrs, field.Required(fldPath.Child(\"volumePath\"), \"\")) } return allErrs } // ValidatePersistentVolumeName checks that a name is appropriate for a // PersistentVolumeName object. var ValidatePersistentVolumeName = NameIsDNSSubdomain"} {"_id":"doc-en-kubernetes-38e0c4be396d9904cdc0caa0c15f7878d4a5b9e4b7958c83ebe546ec4f62269b","title":"","text":"numVolumes++ allErrs = append(allErrs, validateAzureFile(pv.Spec.AzureFile, specPath.Child(\"azureFile\"))...) } if pv.Spec.VsphereVolume != nil { if numVolumes > 0 { allErrs = append(allErrs, field.Forbidden(specPath.Child(\"vsphereVolume\"), \"may not specify more than 1 volume type\")) } else { numVolumes++ allErrs = append(allErrs, validateVsphereVolumeSource(pv.Spec.VsphereVolume, specPath.Child(\"vsphereVolume\"))...) } } if numVolumes == 0 { allErrs = append(allErrs, field.Required(specPath, \"must specify a volume type\")) }"} {"_id":"doc-en-kubernetes-69f4610b982cfc5347d64830935c1045a02a531cfaab4a6a7a4fa1dcbd30ccee","title":"","text":"pvc := createPVC(\"fake-pvc\", \"5G\", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) w, _ := testClient.PersistentVolumes().Watch(api.ListOptions{}) w, err := testClient.PersistentVolumes().Watch(api.ListOptions{}) if err != nil { t.Errorf(\"Failed to watch PersistentVolumes: %v\", err) } defer w.Stop() _, _ = testClient.PersistentVolumes().Create(pv) _, _ = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) _, err = testClient.PersistentVolumes().Create(pv) if err != nil { t.Errorf(\"Failed to create PersistentVolume: %v\", err) } _, err = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) if err != nil { t.Errorf(\"Failed to create PersistentVolumeClaim: %v\", err) } // wait until the controller pairs the volume and claim waitForPersistentVolumePhase(w, api.VolumeBound)"} {"_id":"doc-en-kubernetes-ab06c5975896b748494152a3af160f8072ce4ef48227c3a9c86f654d2b3d2705","title":"","text":"// change the reclamation policy of the PV for the next test pv.Spec.PersistentVolumeReclaimPolicy = api.PersistentVolumeReclaimDelete w, _ = testClient.PersistentVolumes().Watch(api.ListOptions{}) w, err = testClient.PersistentVolumes().Watch(api.ListOptions{}) if err != nil { t.Errorf(\"Failed to watch PersistentVolumes: %v\", err) } defer w.Stop() _, _ = testClient.PersistentVolumes().Create(pv) _, _ = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) _, err = testClient.PersistentVolumes().Create(pv) if err != nil { t.Errorf(\"Failed to create PersistentVolume: %v\", err) } _, err = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) if err != nil { t.Errorf(\"Failed to create PersistentVolumeClaim: %v\", err) } waitForPersistentVolumePhase(w, api.VolumeBound)"} {"_id":"doc-en-kubernetes-d5e237f5125fe62a6eb80055d1a2d6e7468a7568f8bd76270e9219af52efbaf3","title":"","text":"pvc := createPVC(\"pvc-2\", strconv.Itoa(maxPVs/2)+\"G\", []api.PersistentVolumeAccessMode{api.ReadWriteOnce}) w, _ := testClient.PersistentVolumes().Watch(api.ListOptions{}) w, err := testClient.PersistentVolumes().Watch(api.ListOptions{}) if err != nil { t.Errorf(\"Failed to watch PersistentVolumes: %v\", err) } defer w.Stop() for i := 0; i < maxPVs; i++ { _, _ = testClient.PersistentVolumes().Create(pvs[i]) _, err = testClient.PersistentVolumes().Create(pvs[i]) if err != nil { t.Errorf(\"Failed to create PersistentVolume %d: %v\", i, err) } } _, _ = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) _, err = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) if err != nil { t.Errorf(\"Failed to create PersistentVolumeClaim: %v\", err) } // wait until the controller pairs the volume and claim waitForPersistentVolumePhase(w, api.VolumeBound)"} {"_id":"doc-en-kubernetes-cad12ee78e821ea91d2d3d25408743284295fffe04f1ff1d142bdf71c5422120","title":"","text":"pvc := createPVC(\"pvc-rwm\", \"5G\", []api.PersistentVolumeAccessMode{api.ReadWriteMany}) w, _ := testClient.PersistentVolumes().Watch(api.ListOptions{}) w, err := testClient.PersistentVolumes().Watch(api.ListOptions{}) if err != nil { t.Errorf(\"Failed to watch PersistentVolumes: %v\", err) } defer w.Stop() _, _ = testClient.PersistentVolumes().Create(pv_rwm) _, _ = testClient.PersistentVolumes().Create(pv_rwo) _, err = testClient.PersistentVolumes().Create(pv_rwm) if err != nil { t.Errorf(\"Failed to create PersistentVolume: %v\", err) } _, err = testClient.PersistentVolumes().Create(pv_rwo) if err != nil { t.Errorf(\"Failed to create PersistentVolume: %v\", err) } _, _ = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) _, err = testClient.PersistentVolumeClaims(api.NamespaceDefault).Create(pvc) if err != nil { t.Errorf(\"Failed to create PersistentVolumeClaim: %v\", err) } // wait until the controller pairs the volume and claim waitForPersistentVolumePhase(w, api.VolumeBound)"} {"_id":"doc-en-kubernetes-bb579085541433eea7607bbcec3b281daab625fb4d62f21af3cca072a610211f","title":"","text":"ETCD_HOST=${ETCD_HOST:-127.0.0.1} ETCD_PORT=${ETCD_PORT:-4001} ETCD_PREFIX=${ETCD_PREFIX:-randomPrefix} API_PORT=${API_PORT:-8080} API_HOST=${API_HOST:-127.0.0.1} KUBE_API_VERSIONS=\"\""} {"_id":"doc-en-kubernetes-f4949ced9af0b45f1bfa8099a45bec008466ab0e4baaa62ffdf55566faa1ed5e","title":"","text":"--bind-address=\"${API_HOST}\" --insecure-port=\"${API_PORT}\" --etcd-servers=\"http://${ETCD_HOST}:${ETCD_PORT}\" --etcd-prefix=\"${ETCD_PREFIX}\" --runtime-config=\"${RUNTIME_CONFIG}\" --cert-dir=\"${TMPDIR:-/tmp/}\" --service-cluster-ip-range=\"10.0.0.0/24\" "} {"_id":"doc-en-kubernetes-d3292c1563bd973ca1bb0530f19c4f4e000c0d91ca9a584ceeba2e93c6a5cbd7","title":"","text":"### END TEST DEFINITION CUSTOMIZATION ### ####################################################### # Step 1: Start a server which supports both the old and new api versions, # but KUBE_OLD_API_VERSION is the latest (storage) version."} {"_id":"doc-en-kubernetes-4dc3275367e11f5562004c8b1381ddb178173ded1fb822e1dd719149efc57524","title":"","text":"old_storage_version=${test_data[4]} kube::log::status \"Verifying ${resource}/${namespace}/${name} has storage version ${old_storage_version} in etcd\" curl -s http://${ETCD_HOST}:${ETCD_PORT}/v2/keys/registry/${resource}/${namespace}/${name} | grep ${old_storage_version} curl -s http://${ETCD_HOST}:${ETCD_PORT}/v2/keys/${ETCD_PREFIX}/${resource}/${namespace}/${name} | grep ${old_storage_version} done killApiServer"} {"_id":"doc-en-kubernetes-ea666026182ccfccc6a19616d22f71b8cbd9d8ea62fdfd2e828b408581b8a1a0","title":"","text":"new_storage_version=${test_data[5]} kube::log::status \"Verifying ${resource}/${namespace}/${name} has updated storage version ${new_storage_version} in etcd\" curl -s http://${ETCD_HOST}:${ETCD_PORT}/v2/keys/registry/${resource}/${namespace}/${name} | grep ${new_storage_version} curl -s http://${ETCD_HOST}:${ETCD_PORT}/v2/keys/${ETCD_PREFIX}/${resource}/${namespace}/${name} | grep ${new_storage_version} done killApiServer"} {"_id":"doc-en-kubernetes-880af6824cf1396ec77b6524be64b165abb5f80b5f51187b1e57d369b2b917b5","title":"","text":"const ( SchedulerAnnotationKey = \"scheduler.alpha.kubernetes.io/name\" initialGetBackoff = 100 * time.Millisecond maximalGetBackoff = time.Minute ) // ConfigFactory knows how to fill out a scheduler config with its support functions."} {"_id":"doc-en-kubernetes-d3d903d1d477dcdd4c9fc1409e711c28e0d98b0b0f1c5de37359cc855cad9544","title":"","text":"} // Get the pod again; it may have changed/been scheduled already. pod = &api.Pod{} err := factory.Client.Get().Namespace(podID.Namespace).Resource(\"pods\").Name(podID.Name).Do().Into(pod) if err != nil { if !errors.IsNotFound(err) { glog.Errorf(\"Error getting pod %v for retry: %v; abandoning\", podID, err) getBackoff := initialGetBackoff for { if err := factory.Client.Get().Namespace(podID.Namespace).Resource(\"pods\").Name(podID.Name).Do().Into(pod); err == nil { break } return if errors.IsNotFound(err) { glog.Warning(\"A pod %v no longer exists\", podID) return } glog.Errorf(\"Error getting pod %v for retry: %v; retrying...\", podID, err) if getBackoff = getBackoff * 2; getBackoff > maximalGetBackoff { getBackoff = maximalGetBackoff } time.Sleep(getBackoff) } if pod.Spec.NodeName == \"\" { podQueue.AddIfNotPresent(pod)"} {"_id":"doc-en-kubernetes-f8cfc0397cffa4621eecb3111246462eca5618cde1cd8f5611701d2d1e5a13c6","title":"","text":"if len(list.Items) > 1 { return cmdutil.UsageError(cmd, \"%s specifies multiple items\", filename) } if len(list.Items) == 0 { return cmdutil.UsageError(cmd, \"please make sure %s exists and is not empty\", filename) } obj = list.Items[0] } newRc, ok = obj.(*api.ReplicationController)"} {"_id":"doc-en-kubernetes-2d9abc84f7d83687196a738c8c0517698a256dde96e31270b2f2e187abdc8391","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v18 name: kube-dns-v19 namespace: kube-system labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: replicas: __PILLAR__DNS__REPLICAS__ selector: k8s-app: kube-dns version: v18 version: v19 template: metadata: labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-bb7ed09e60cf086d9428d487460bca6bed3c87139bb7c3d5957bfebce6ace503","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.__PILLAR__DNS__DOMAIN__ 127.0.0.1 >/dev/null && nslookup kubernetes.default.svc.__PILLAR__DNS__DOMAIN__ 127.0.0.1:10053 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-91268e90086f52f1e9aa926852589b88c07051a0f6351235dbb4cce7282453e3","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v18 name: kube-dns-v19 namespace: kube-system labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: replicas: {{ pillar['dns_replicas'] }} selector: k8s-app: kube-dns version: v18 version: v19 template: metadata: labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-698bc41afd4cdf6edf397de5584ee9f4c28b1939c6cbced1e8ee571d0d1248f2","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.{{ pillar['dns_domain'] }} 127.0.0.1 >/dev/null && nslookup kubernetes.default.svc.{{ pillar['dns_domain'] }} 127.0.0.1:10053 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-c910906c697e3fa1c6f06091c15c4a915709e4c37a247bd3d799c72cdb1e8427","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v18 name: kube-dns-v19 namespace: kube-system labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: replicas: $DNS_REPLICAS selector: k8s-app: kube-dns version: v18 version: v19 template: metadata: labels: k8s-app: kube-dns version: v18 version: v19 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-12db0bdff444977b5df92669d8af725a8a2446d9ea05b111904e5c5d3fdfe23c","title":"","text":"# \"burstable\" category so the kubelet doesn't backoff from restarting it. limits: cpu: 100m memory: 200Mi memory: 170Mi requests: cpu: 100m memory: 100Mi memory: 70Mi livenessProbe: httpGet: path: /healthz"} {"_id":"doc-en-kubernetes-5ab066989f827398a2d71668d0a5e668030f1e64f01a26e865b29a44446416dd","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.$DNS_DOMAIN 127.0.0.1 >/dev/null && nslookup kubernetes.default.svc.$DNS_DOMAIN 127.0.0.1:10053 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-b04492437015dcacda2d4eced572a07c951a7acba827e4dffe8128d673df23b6","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v17 name: kube-dns-v17.1 namespace: kube-system labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: replicas: __PILLAR__DNS__REPLICAS__ selector: k8s-app: kube-dns version: v17 version: v17.1 template: metadata: labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-dc28f2d2e3a23fdd2c0331cd23d651d85de25a03b06dfd1beb9a260f397d6998","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.__PILLAR__DNS__DOMAIN__ 127.0.0.1 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-8967f725a8b647ed04389f31a984147076d364d59087f131ee3164f27ba4ba00","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v17 name: kube-dns-v17.1 namespace: kube-system labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: replicas: {{ pillar['dns_replicas'] }} selector: k8s-app: kube-dns version: v17 version: v17.1 template: metadata: labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-870ac7fc599968439250cadbc207abcbaae0c107e1251648197f6cf5790ed88e","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.{{ pillar['dns_domain'] }} 127.0.0.1 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-be4dc01cb5abbc785ba135d92af93b36399626318c514f7e98a32747b6cf9d36","title":"","text":"apiVersion: v1 kind: ReplicationController metadata: name: kube-dns-v17 name: kube-dns-v17.1 namespace: kube-system labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: replicas: $DNS_REPLICAS selector: k8s-app: kube-dns version: v17 version: v17.1 template: metadata: labels: k8s-app: kube-dns version: v17 version: v17.1 kubernetes.io/cluster-service: \"true\" spec: containers:"} {"_id":"doc-en-kubernetes-64023d3a61409eda09f6f3f4ee67811336097202149915f9935a5c0e6fa64fea","title":"","text":"# keep request = limit to keep this container in guaranteed class limits: cpu: 10m memory: 20Mi memory: 50Mi requests: cpu: 10m memory: 20Mi # Note that this container shouldn't really need 50Mi of memory. The # limits are set higher than expected pending investigation on #29688. # The extra memory was stolen from the kubedns container to keep the # net memory requested by the pod constant. memory: 50Mi args: - -cmd=nslookup kubernetes.default.svc.$DNS_DOMAIN 127.0.0.1 >/dev/null - -port=8080"} {"_id":"doc-en-kubernetes-1cd4a2ec7bc492ef0c3f78adb0d286c6da34f61f04f6e2f303dc937ab2ea7585","title":"","text":"// test when the pod anti affinity rule is not satisfied, the pod would stay pending. It(\"validates that InterPodAntiAffinity is respected if matching 2\", func() { // launch a pod to find a node which can launch a pod. We intentionally do // not just take the node list and choose the first of them. Depending on the // cluster and the scheduler it might be that a \"normal\" pod cannot be // scheduled onto it. By(\"Trying to launch a pod with a label to get a node which can launch it.\") // launch pods to find nodes which can launch a pod. We intentionally do // not just take the node list and choose the first and the second of them. // Depending on the cluster and the scheduler it might be that a \"normal\" pod // cannot be scheduled onto it. By(\"Launching two pods on two distinct nodes to get two node names\") CreateHostPortPods(f, \"host-port\", 2, true) defer framework.DeleteRC(f.Client, f.Namespace.Name, \"host-port\") podList, err := c.Pods(ns).List(api.ListOptions{}) ExpectNoError(err) Expect(len(podList.Items)).To(Equal(2)) nodeNames := []string{podList.Items[0].Spec.NodeName, podList.Items[1].Spec.NodeName} Expect(nodeNames[0]).ToNot(Equal(nodeNames[1])) By(\"Applying a random label to both nodes.\") k := \"e2e.inter-pod-affinity.kubernetes.io/zone\" v := \"china-e2etest\" for _, nodeName := range nodeNames { framework.AddOrUpdateLabelOnNode(c, nodeName, k, v) framework.ExpectNodeHasLabel(c, nodeName, k, v) defer framework.RemoveLabelOffNode(c, nodeName, k) } By(\"Trying to launch another pod on the first node with the service label.\") podName := \"with-label-\" + string(uuid.NewUUID()) pod, err := c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{"} {"_id":"doc-en-kubernetes-900e1c058dce909200242e0921ee8d4ecdd9b1aedec867ae9f021f25b3170515","title":"","text":"Image: framework.GetPauseImageName(f.Client), }, }, NodeSelector: map[string]string{k: v}, // only launch on our two nodes }, }) framework.ExpectNoError(err)"} {"_id":"doc-en-kubernetes-ab88b3f964120ea9e709648838d46461d21adb705b40092af6ae7fa6520fcd73","title":"","text":"pod, err = c.Pods(ns).Get(podName) framework.ExpectNoError(err) nodeName := pod.Spec.NodeName By(\"Trying to apply a random label on the found node.\") k := \"e2e.inter-pod-affinity.kubernetes.io/zone\" v := \"china-e2etest\" framework.AddOrUpdateLabelOnNode(c, nodeName, k, v) framework.ExpectNodeHasLabel(c, nodeName, k, v) defer framework.RemoveLabelOffNode(c, nodeName, k) By(\"Trying to launch the pod, now with podAffinity with same Labels.\") labelPodName := \"with-podaffinity-\" + string(uuid.NewUUID()) By(\"Trying to launch another pod, now with podAntiAffinity with same Labels.\") labelPodName := \"with-podantiaffinity-\" + string(uuid.NewUUID()) _, err = c.Pods(ns).Create(&api.Pod{ TypeMeta: unversioned.TypeMeta{ Kind: \"Pod\","} {"_id":"doc-en-kubernetes-497f9c9acf19e9078f11a587a73ad7850261eb86579f6d3e4099b35e2b8585f1","title":"","text":"Image: framework.GetPauseImageName(f.Client), }, }, NodeSelector: map[string]string{k: v}, // only launch on our two nodes, contradicting the podAntiAffinity }, }) framework.ExpectNoError(err)"} {"_id":"doc-en-kubernetes-dabac2a64e0328fb7c1db41b2b100c32e116c87e1f43822a12ec9ceb78d78f6b","title":"","text":"framework.Logf(\"Sleeping 10 seconds and crossing our fingers that scheduler will run in that time.\") time.Sleep(10 * time.Second) verifyResult(c, labelPodName, 2, 0, ns) verifyResult(c, labelPodName, 3, 1, ns) }) // test the pod affinity successful matching scenario with multiple Label Operators."} {"_id":"doc-en-kubernetes-f6c55bdc399e6286717ff723b851c75c5b2b5b1408560f085d1544ee508cd69d","title":"","text":"Expect(err).NotTo(HaveOccurred()) }() // Waiting for service to expose endpoint // Waiting for service to expose endpoint. validateEndpointsOrFail(c, ns, serviceName, PortsByPodName{serverPodName: {servicePort}}) By(\"Retrieve sourceip from a pod on the same node\")"} {"_id":"doc-en-kubernetes-73cfc07f077ec264d75583fcd4225e594e841957ac66097194029fbaee3f11c0","title":"","text":"timeout := 2 * time.Minute framework.Logf(\"Waiting up to %v for sourceIp test to be executed\", timeout) cmd := fmt.Sprintf(`wget -T 30 -qO- %s:%d | grep client_address`, serviceIp, servicePort) // need timeout mechanism because it may takes more times for iptables to be populated // Need timeout mechanism because it may takes more times for iptables to be populated. for start := time.Now(); time.Since(start) < timeout; time.Sleep(2) { stdout, err = framework.RunHostCmd(execPod.Namespace, execPod.Name, cmd) if err != nil { framework.Logf(\"got err: %v, retry until timeout\", err) continue } // Need to check output because wget -q might omit the error. if strings.TrimSpace(stdout) == \"\" { framework.Logf(\"got empty stdout, retry until timeout\") continue } break } ExpectNoError(err) // the stdout return from RunHostCmd seems to come with \"n\", so TrimSpace is needed // desired stdout in this format: client_address=x.x.x.x // The stdout return from RunHostCmd seems to come with \"n\", so TrimSpace is needed. // Desired stdout in this format: client_address=x.x.x.x outputs := strings.Split(strings.TrimSpace(stdout), \"=\") sourceIp := \"\" if len(outputs) != 2 { // fail the test if output format is unexpected // Fail the test if output format is unexpected. framework.Failf(\"exec pod returned unexpected stdout format: [%v]n\", stdout) return execPodIp, \"\" } else { sourceIp = outputs[1] } return execPodIp, outputs[1] return execPodIp, sourceIp }"} {"_id":"doc-en-kubernetes-d0606c836343780806d9aa462e0a07f2d19efb232d2e3407f3b0aa98169c9dc3","title":"","text":"docker_opts+=\" --log-level=warn\" fi local use_net_plugin=\"true\" if [[ \"${NETWORK_PROVIDER:-}\" != \"kubenet\" && \"${NETWORK_PROVIDER:-}\" != \"cni\" ]]; then if [[ \"${NETWORK_PROVIDER:-}\" == \"kubenet\" || \"${NETWORK_PROVIDER:-}\" == \"cni\" ]]; then # set docker0 cidr to private ip address range to avoid conflict with cbr0 cidr range docker_opts+=\" --bip=169.254.123.1/24\" else use_net_plugin=\"false\" docker_opts+=\" --bridge=cbr0\" fi"} {"_id":"doc-en-kubernetes-5ce277c5b29c24a23fa0113c6d41f8cdc72bc32aeed65bcabc94fc887bd32adb","title":"","text":"WantedBy=multi-user.target EOF # Delete docker0 to avoid interference # Flush iptables nat table iptables -t nat -F || true ip link set docker0 down || true brctl delbr docker0 || true systemctl start kubelet.service }"} {"_id":"doc-en-kubernetes-a479fcef92f855d9f8c331b63e287627496db6df67541290b6a2f6ed16ce48b4","title":"","text":"\"os\" \"k8s.io/kubernetes/pkg/healthz\" \"k8s.io/kubernetes/pkg/util\" \"k8s.io/kubernetes/pkg/util/flag\" \"k8s.io/kubernetes/pkg/util/logs\" \"k8s.io/kubernetes/pkg/version/verflag\""} {"_id":"doc-en-kubernetes-d4e94b3a6a3959c1e6e906a3d4d4cc320186adeb1ac205c01f334c1d114f8dcc","title":"","text":"\"github.com/spf13/pflag\" \"k8s.io/kubernetes/contrib/mesos/pkg/executor/service\" \"k8s.io/kubernetes/contrib/mesos/pkg/hyperkube\" \"k8s.io/kubernetes/pkg/util\" \"k8s.io/kubernetes/pkg/util/flag\" \"k8s.io/kubernetes/pkg/util/logs\" \"k8s.io/kubernetes/pkg/version/verflag\""} {"_id":"doc-en-kubernetes-ab7319771dca689e973b1476f8f62042d648f2178db94897ba1dadf705da52b6","title":"","text":"\"github.com/spf13/pflag\" \"k8s.io/kubernetes/contrib/mesos/pkg/hyperkube\" \"k8s.io/kubernetes/contrib/mesos/pkg/scheduler/service\" \"k8s.io/kubernetes/pkg/util\" \"k8s.io/kubernetes/pkg/util/flag\" \"k8s.io/kubernetes/pkg/util/logs\" \"k8s.io/kubernetes/pkg/version/verflag\""} {"_id":"doc-en-kubernetes-83302a99ab452b94f286e986bdc6b925693a83056cf52096a255d7aeab06a467","title":"","text":"livenessProbe: httpGet: path: /healthz port: 8080 port: 8082 scheme: HTTP initialDelaySeconds: 180 timeoutSeconds: 5"} {"_id":"doc-en-kubernetes-e23ef35c0c92fa40e582033a1dc418822df40ea7cb4fa7191f37ac0f7a0ad07a","title":"","text":"if len(address.Hostname) > 0 { allErrs = append(allErrs, ValidateDNS1123Label(address.Hostname, fldPath.Child(\"hostname\"))...) } // During endpoint update, validate NodeName is DNS1123 compliant and transition rules allow the update // During endpoint update, verify that NodeName is a DNS subdomain and transition rules allow the update if address.NodeName != nil { allErrs = append(allErrs, ValidateDNS1123Label(*address.NodeName, fldPath.Child(\"nodeName\"))...) for _, msg := range ValidateNodeName(*address.NodeName, false) { allErrs = append(allErrs, field.Invalid(fldPath.Child(\"nodeName\"), *address.NodeName, msg)) } } allErrs = append(allErrs, validateEpAddrNodeNameTransition(address, ipToNodeName, fldPath.Child(\"nodeName\"))...) if len(allErrs) > 0 {"} {"_id":"doc-en-kubernetes-d1f2d8ba982bdf760f6c4791f288aa280e32514d2650dd5b67d56c5d5948c414","title":"","text":"} } func TestEndpointAddressNodeNameInvalidDNS1123(t *testing.T) { func TestEndpointAddressNodeNameInvalidDNSSubdomain(t *testing.T) { // Check NodeName DNS validation endpoint := newNodeNameEndpoint(\"illegal.nodename\") endpoint := newNodeNameEndpoint(\"illegal*.nodename\") errList := ValidateEndpoints(endpoint) if len(errList) == 0 { t.Error(\"Endpoint should reject invalid NodeName\") } } func TestEndpointAddressNodeNameCanBeAnIPAddress(t *testing.T) { endpoint := newNodeNameEndpoint(\"10.10.1.1\") errList := ValidateEndpoints(endpoint) if len(errList) != 0 { t.Error(\"Endpoint should accept a NodeName that is an IP address\") } } "} {"_id":"doc-en-kubernetes-16c0ef436a98f55d88b5948bf9e69c7b590706e841dbb758076b9dc80b378cd5","title":"","text":"function usage() { echo \"!!! EXPERIMENTAL !!!\" echo \"\" echo \"${0} [-M|-N|-P] -l | \" echo \"${0} [-M|-N|-P] -l -o | \" echo \" Upgrades master and nodes by default\" echo \" -M: Upgrade master only\" echo \" -N: Upgrade nodes only\" echo \" -P: Node upgrade prerequisites only (create a new instance template)\" echo \" -o: Use os distro sepcified in KUBE_NODE_OS_DISTRIBUTION for new nodes\" echo \" -l: Use local(dev) binaries\" echo \"\" echo ' Version number or publication is either a proper version number'"} {"_id":"doc-en-kubernetes-8c5c2d6ee689fd4f32f4adace332f17a3c0eac4a73d2acce8952be7233b0197c","title":"","text":"'http://metadata/computeMetadata/v1/instance/attributes/kube-env'\" 2>/dev/null } # Read os distro information from /os/release on node. # $1: The name of node # # Assumed vars: # PROJECT # ZONE function get-node-os() { gcloud compute ssh \"$1\" --project \"${PROJECT}\" --zone \"${ZONE}\" --command \"cat /etc/os-release | grep \"^ID=.*\" | cut -c 4-\" } # Assumed vars: # KUBE_VERSION # NODE_SCOPES"} {"_id":"doc-en-kubernetes-fb4d73b5db05b095052d2b22d5f371888573b15e31bca7d1579751748d352914","title":"","text":"# compatible way? write-node-env if [[ \"${env_os_distro}\" == \"false\" ]]; then NODE_OS_DISTRIBUTION=$(get-node-os \"${NODE_NAMES[0]}\") source \"${KUBE_ROOT}/cluster/gce/${NODE_OS_DISTRIBUTION}/node-helper.sh\" # Reset the node image based on current os distro set-node-image fi # TODO(zmerlynn): Get configure-vm script from ${version}. (Must plumb this # through all create-node-instance-template implementations). local template_name=$(get-template-name-from-version ${SANITIZED_VERSION})"} {"_id":"doc-en-kubernetes-0507b246aa02ba08dc6913f9be80af68317891f83f136f9e2086b06cd9df1ee3","title":"","text":"node_upgrade=true node_prereqs=false local_binaries=false env_os_distro=false while getopts \":MNPlh\" opt; do case ${opt} in"} {"_id":"doc-en-kubernetes-317045b41310f9debc1325fdac6086fdb7d7724e6dcaa079ca5d70866d3a8498","title":"","text":"l) local_binaries=true ;; o) env_os_distro=true ;; h) usage exit 0"} {"_id":"doc-en-kubernetes-0614f79dcd8e9a09815612ac925c66b4eecd797f8fc1a36b406c21d97fd77c66","title":"","text":"MASTER_IMAGE_PROJECT=${KUBE_GCE_MASTER_PROJECT:-google-containers} fi if [[ \"${NODE_OS_DISTRIBUTION}\" == \"gci\" ]]; then # If the node image is not set, we use the latest GCI image. # Otherwise, we respect whatever is set by the user. NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${GCI_VERSION}} NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-google-containers} elif [[ \"${NODE_OS_DISTRIBUTION}\" == \"debian\" ]]; then NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${CVM_VERSION}} NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-google-containers} fi # Sets node image based on the specified os distro. Currently this function only # supports gci and debian. function set-node-image() { if [[ \"${NODE_OS_DISTRIBUTION}\" == \"gci\" ]]; then # If the node image is not set, we use the latest GCI image. # Otherwise, we respect whatever is set by the user. NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${GCI_VERSION}} NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-google-containers} elif [[ \"${NODE_OS_DISTRIBUTION}\" == \"debian\" ]]; then NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${CVM_VERSION}} NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-google-containers} fi } set-node-image # Verfiy cluster autoscaler configuration. if [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then"} {"_id":"doc-en-kubernetes-dfc6ad9d9accc5787d6c0001e56a180791c451a8416ddffddce72e2555ffd34e","title":"","text":"# Delete the master replica pd (possibly leaked by kube-up if master create failed). # TODO(jszczepkowski): remove also possibly leaked replicas' pds local -r replica-pd=\"${REPLICA_NAME:-${MASTER_NAME}}-pd\" if gcloud compute disks describe \"${replica-pd}\" --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then local -r replica_pd=\"${REPLICA_NAME:-${MASTER_NAME}}-pd\" if gcloud compute disks describe \"${replica_pd}\" --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then gcloud compute disks delete --project \"${PROJECT}\" --quiet --zone \"${ZONE}\" \"${replica-pd}\" \"${replica_pd}\" fi # Delete disk for cluster registry if enabled"} {"_id":"doc-en-kubernetes-4d34a948dbd42d950fe10b33fe115cead3c679add0fe34ad03522a731f4f878f","title":"","text":" # This Dockerfile will build an image that is configured # to run Fluentd with an Elasticsearch plug-in and the # provided configuration file. # TODO(satnam6502): Use a lighter base image, e.g. some form of busybox. # The image acts as an executable for the binary /usr/sbin/td-agent. # Note that fluentd is run with root permssion to allow access to # log files with root only access under /var/lib/docker/containers/* # Please see http://docs.fluentd.org/articles/install-by-deb for more # information about installing fluentd using deb package. FROM ubuntu:14.04 MAINTAINER Satnam Singh \"satnam@google.com\" # Ensure there are enough file descriptors for running Fluentd. RUN ulimit -n 65536 # Install prerequisites. RUN apt-get update && apt-get install -y curl && apt-get install -y -q libcurl4-openssl-dev make && apt-get clean # Install Fluentd. RUN /usr/bin/curl -L http://toolbelt.treasuredata.com/sh/install-ubuntu-trusty-td-agent2.sh | sh # Change the default user and group to root. # Needed to allow access to /var/log/docker/... files. RUN sed -i -e \"s/USER=td-agent/USER=root/\" -e \"s/GROUP=td-agent/GROUP=root/\" /etc/init.d/td-agent # Install the Elasticsearch Fluentd plug-in. RUN /usr/sbin/td-agent-gem install fluent-plugin-elasticsearch # Copy the Fluentd configuration file. COPY td-agent.conf /etc/td-agent/td-agent.conf # Copy a script that determines the name of the host machine # and then patch the Fluentd configuration files and then # run Fluentd in the foreground. ADD run.sh /run.sh # Always run the this setup script. ENTRYPOINT [\"/run.sh\"] "} {"_id":"doc-en-kubernetes-dab31027122866f58e8e938ce5ec4117f20ea478734d791209d9d00a6fd46d81","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. # Build the fluentd-elasticsearch image and push # to google/fluentd-elasticsearch. sudo docker build -t kubernetes/fluentd-elasticsearch . sudo docker push kubernetes/fluentd-elasticsearch "} {"_id":"doc-en-kubernetes-70110d5c6ffc0451f07001914705172d394a99b071c33120c0d3da9869671711","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. # WARNING! HORRIBLE HACK! We expect /outerhost to be mapped to # the enclosing /etc/host file so we can determine the name of # the host machine (super fragile). This is a temporary hack until # service IPs are done. OUTER_HOST=`tail -n 1 /outerhost | awk '{print $3}'` # Copy the Fluentd config file and patch it to refer to the # name of the host machine for ES_HOST. HACK! cp td-agent.conf /etc/td-agent sed -i -e \"s/ES_HOST/${OUTER_HOST}/\" /etc/td-agent/td-agent.conf /usr/sbin/td-agent "} {"_id":"doc-en-kubernetes-dac7ce3b756390a961a3487c79ac685ec5848ede5f1417c03ecb0bf659467b79","title":"","text":" # This configuration file for Fluentd / td-agent is used # to watch changes to Docker log files that live in the # directory /var/lib/docker/containers/ which are then submitted to # Elasticsearch (running on the machine ES_HOST:9200) which # assumes the installation of the fluentd-elasticsearch plug-in. # See https://github.com/uken/fluent-plugin-elasticsearch for # more information about the plug-in. This file needs to be # patched to replace ES_HOST with the name of the actual # machine running Elasticsearch. # Maintainer: Satnam Singh (satnam@google.com) # # Exampe # ====== # A line in the Docker log file might like like this JSON: # # {\"log\":\"2014/09/25 21:15:03 Got request with path wombatn\", # \"stream\":\"stderr\", # \"time\":\"2014-09-25T21:15:03.499185026Z\"} # # The time_format specification below makes sure we properly # parse the time format produced by Docker. This will be # submitted to Elasticsearch and should appear like: # $ curl 'http://elasticsearch:9200/_search?pretty' # ... # { # \"_index\" : \"logstash-2014.09.25\", # \"_type\" : \"fluentd\", # \"_id\" : \"VBrbor2QTuGpsQyTCdfzqA\", # \"_score\" : 1.0, # \"_source\":{\"log\":\"2014/09/25 22:45:50 Got request with path wombatn\", # \"stream\":\"stderr\",\"tag\":\"docker.container.all\", # \"@timestamp\":\"2014-09-25T22:45:50+00:00\"} # }, # ... type tail format json time_key time path /var/lib/docker/containers/*/*-json.log time_format %Y-%m-%dT%H:%M:%S tag docker.container.all type elasticsearch log_level info include_tag_key true host ES_HOST port 9200 logstash_format true flush_interval 5s "} {"_id":"doc-en-kubernetes-acf7d4c212138fc6d10860cf50d207e6d1afa3901f85c7178da53b847b6f63e9","title":"","text":"source /run/flannel/subnet.env source /etc/default/docker echo DOCKER_OPTS=\"${DOCKER_OPTS} -H tcp://127.0.0.1:4243 -H unix:///var/run/docker.sock echo DOCKER_OPTS=\" -H tcp://127.0.0.1:4243 -H unix:///var/run/docker.sock --bip=${FLANNEL_SUBNET} --mtu=${FLANNEL_MTU}\" > /etc/default/docker sudo service docker restart }"} {"_id":"doc-en-kubernetes-4c7a504e9ce3d4483cf43ffc319706342208fcc8602e0566f5cb69ccedc29a4e","title":"","text":"if len(tc.plugin) != 0 { c.AuthProvider = &clientcmdapi.AuthProviderConfig{Name: tc.plugin} } tConfig, err := c.transportConfig() tConfig, err := c.TransportConfig() if err != nil { // Unknown/bad plugins are expected to fail here. if !tc.expectErr {"} {"_id":"doc-en-kubernetes-e11cfd6bbb46a8ec4952551a4abe38067f465ccb7f37905096932989599448b2","title":"","text":"// TLSConfigFor returns a tls.Config that will provide the transport level security defined // by the provided Config. Will return nil if no transport level security is requested. func TLSConfigFor(config *Config) (*tls.Config, error) { cfg, err := config.transportConfig() cfg, err := config.TransportConfig() if err != nil { return nil, err }"} {"_id":"doc-en-kubernetes-edb8769e03ae4e0084c56d93238832199c3f4914a20cc69e22e7411ed4c6a880","title":"","text":"// or transport level security defined by the provided Config. Will return the // default http.DefaultTransport if no special case behavior is needed. func TransportFor(config *Config) (http.RoundTripper, error) { cfg, err := config.transportConfig() cfg, err := config.TransportConfig() if err != nil { return nil, err }"} {"_id":"doc-en-kubernetes-338a222b842e4f3de3e86175f33687de20c2de39c1b587a902e5ce7322cabfad","title":"","text":"// the underlying connection (like WebSocket or HTTP2 clients). Pure HTTP clients should use // the higher level TransportFor or RESTClientFor methods. func HTTPWrappersForConfig(config *Config, rt http.RoundTripper) (http.RoundTripper, error) { cfg, err := config.transportConfig() cfg, err := config.TransportConfig() if err != nil { return nil, err } return transport.HTTPWrappersForConfig(cfg, rt) } // transportConfig converts a client config to an appropriate transport config. func (c *Config) transportConfig() (*transport.Config, error) { // TransportConfig converts a client config to an appropriate transport config. func (c *Config) TransportConfig() (*transport.Config, error) { wt := c.WrapTransport if c.AuthProvider != nil { provider, err := GetAuthProvider(c.Host, c.AuthProvider, c.AuthConfigPersister)"} {"_id":"doc-en-kubernetes-b27241a3fe3289867015e582beff85551da2930f4a6701d78342e3e99792f2d1","title":"","text":"\"fmt\" \"math\" \"math/rand\" \"net\" \"net/http\" \"os\" \"strconv\" \"sync\""} {"_id":"doc-en-kubernetes-cb9abe00153df5e51873b9f5ab7e3ffcd23271f07f40c9ecad45b97247238e41","title":"","text":"\"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset\" unversionedcore \"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/unversioned\" \"k8s.io/kubernetes/pkg/client/restclient\" \"k8s.io/kubernetes/pkg/client/transport\" client \"k8s.io/kubernetes/pkg/client/unversioned\" \"k8s.io/kubernetes/pkg/labels\" \"k8s.io/kubernetes/pkg/util/intstr\" utilnet \"k8s.io/kubernetes/pkg/util/net\" \"k8s.io/kubernetes/test/e2e/framework\" . \"github.com/onsi/ginkgo\""} {"_id":"doc-en-kubernetes-aba2889c8f26edd6669075af99e738a1ba959f568752a5e1786be882c0588d94","title":"","text":"namespaces = createNamespaces(f, nodeCount, itArg.podsPerNode) totalPods := itArg.podsPerNode * nodeCount configs = generateRCConfigs(totalPods, itArg.image, itArg.command, c, namespaces) configs = generateRCConfigs(totalPods, itArg.image, itArg.command, namespaces) var services []*api.Service // Read the environment variable to see if we want to create services createServices := os.Getenv(\"CREATE_SERVICES\")"} {"_id":"doc-en-kubernetes-f88b416c1c8cd23efda250ffd4526221cf497d0e2d0a9e7d5dc2d92bc2035fc5","title":"","text":"return namespaces } func createClients(numberOfClients int) ([]*client.Client, error) { clients := make([]*client.Client, numberOfClients) for i := 0; i < numberOfClients; i++ { config, err := framework.LoadConfig() Expect(err).NotTo(HaveOccurred()) config.QPS = 100 config.Burst = 200 if framework.TestContext.KubeAPIContentType != \"\" { config.ContentType = framework.TestContext.KubeAPIContentType } // For the purpose of this test, we want to force that clients // do not share underlying transport (which is a default behavior // in Kubernetes). Thus, we are explicitly creating transport for // each client here. transportConfig, err := config.TransportConfig() if err != nil { return nil, err } tlsConfig, err := transport.TLSConfigFor(transportConfig) if err != nil { return nil, err } config.Transport = utilnet.SetTransportDefaults(&http.Transport{ Proxy: http.ProxyFromEnvironment, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: tlsConfig, MaxIdleConnsPerHost: 100, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, }) // Overwrite TLS-related fields from config to avoid collision with // Transport field. config.TLSClientConfig = restclient.TLSClientConfig{} c, err := client.New(config) if err != nil { return nil, err } clients[i] = c } return clients, nil } func computeRCCounts(total int) (int, int, int) { // Small RCs owns ~0.5 of total number of pods, medium and big RCs ~0.25 each. // For example for 3000 pods (100 nodes, 30 pods per node) there are:"} {"_id":"doc-en-kubernetes-bbdbbacd8e9d8c3e3746bdcd06c797b3c757269ec9877dc045bac82a63b2b3d9","title":"","text":"return smallRCCount, mediumRCCount, bigRCCount } func generateRCConfigs(totalPods int, image string, command []string, c *client.Client, nss []*api.Namespace) []*framework.RCConfig { func generateRCConfigs(totalPods int, image string, command []string, nss []*api.Namespace) []*framework.RCConfig { configs := make([]*framework.RCConfig, 0) smallRCCount, mediumRCCount, bigRCCount := computeRCCounts(totalPods) configs = append(configs, generateRCConfigsForGroup(c, nss, smallRCGroupName, smallRCSize, smallRCCount, image, command)...) configs = append(configs, generateRCConfigsForGroup(c, nss, mediumRCGroupName, mediumRCSize, mediumRCCount, image, command)...) configs = append(configs, generateRCConfigsForGroup(c, nss, bigRCGroupName, bigRCSize, bigRCCount, image, command)...) configs = append(configs, generateRCConfigsForGroup(nss, smallRCGroupName, smallRCSize, smallRCCount, image, command)...) configs = append(configs, generateRCConfigsForGroup(nss, mediumRCGroupName, mediumRCSize, mediumRCCount, image, command)...) configs = append(configs, generateRCConfigsForGroup(nss, bigRCGroupName, bigRCSize, bigRCCount, image, command)...) // Create a number of clients to better simulate real usecase // where not everyone is using exactly the same client. rcsPerClient := 20 clients, err := createClients((len(configs) + rcsPerClient - 1) / rcsPerClient) framework.ExpectNoError(err) for i := 0; i < len(configs); i++ { configs[i].Client = clients[i%len(clients)] } return configs } func generateRCConfigsForGroup(c *client.Client, nss []*api.Namespace, groupName string, size, count int, image string, command []string) []*framework.RCConfig { func generateRCConfigsForGroup( nss []*api.Namespace, groupName string, size, count int, image string, command []string) []*framework.RCConfig { configs := make([]*framework.RCConfig, 0, count) for i := 1; i <= count; i++ { config := &framework.RCConfig{ Client: c, Client: nil, // this will be overwritten later Name: groupName + \"-\" + strconv.Itoa(i), Namespace: nss[i%len(nss)].Name, Timeout: 10 * time.Minute,"} {"_id":"doc-en-kubernetes-6aa2ad414abe5acb41e91416b87578b3d2095bbad07cde825f966e9851549d54","title":"","text":"MASTER_CPU=1 NODE_NAMES=($(eval echo ${INSTANCE_PREFIX}-minion-{1..${NUM_NODES}})) NODE_IP_RANGES=\"10.244.0.0/16\" NODE_IP_RANGES=\"10.244.0.0/16\" # Min Prefix supported is 16 MASTER_IP_RANGE=\"${MASTER_IP_RANGE:-10.246.0.0/24}\" NODE_MEMORY_MB=2048 NODE_CPU=1"} {"_id":"doc-en-kubernetes-b7b17c669788d497428062485299e18a629d651ffa6d9625f41abda0f3530727","title":"","text":"# identify the subnet assigned to the node by the kubernetes controller manager. KUBE_NODE_BRIDGE_NETWORK=() for (( i=0; i<${#NODE_NAMES[@]}; i++)); do printf \" finding network of cbr0 bridge on node ${NODE_NAMES[$i]}n\" network=$(kube-ssh ${KUBE_NODE_IP_ADDRESSES[$i]} 'sudo ip route show | grep -E \"dev cbr0\" | cut -d \" \" -f1') KUBE_NODE_BRIDGE_NETWORK+=(\"${network}\") done printf \" finding network of cbr0 bridge on node ${NODE_NAMES[$i]}n\" network=\"\" top2_octets_final=$(echo $NODE_IP_RANGES | awk -F \".\" '{ print $1 \".\" $2 }') # Assume that a 24 bit mask per node attempt=0 max_attempt=60 while true ; do attempt=$(($attempt+1)) network=$(kube-ssh ${KUBE_NODE_IP_ADDRESSES[$i]} 'sudo ip route show | grep -E \"dev cbr0\" | cut -d \" \" -f1') top2_octets_read=$(echo $network | awk -F \".\" '{ print $1 \".\" $2 }') if [[ \"$top2_octets_read\" == \"$top2_octets_final\" ]]; then break fi if (( $attempt == $max_attempt )); then echo echo \"(Failed) Waiting for cbr0 bridge to come up @ ${NODE_NAMES[$i]}\" echo exit 1 fi printf \".\" sleep 5 done printf \"n\" KUBE_NODE_BRIDGE_NETWORK+=(\"${network}\") done # Make the pods visible to each other and to the master. # The master needs have routes to the pods for the UI to work. local j for (( i=0; i<${#NODE_NAMES[@]}; i++)); do printf \"setting up routes for ${NODE_NAMES[$i]}\" kube-ssh \"${KUBE_MASTER_IP}\" \"sudo route add -net ${KUBE_NODE_BRIDGE_NETWORK[${i}]} gw ${KUBE_NODE_IP_ADDRESSES[${i}]}\" for (( j=0; j<${#NODE_NAMES[@]}; j++)); do if [[ $i != $j ]]; then kube-ssh ${KUBE_NODE_IP_ADDRESSES[$i]} \"sudo route add -net ${KUBE_NODE_BRIDGE_NETWORK[$j]} gw ${KUBE_NODE_IP_ADDRESSES[$j]}\" fi done printf \"setting up routes for ${NODE_NAMES[$i]}n\" printf \" adding route to ${MASTER_NAME} for network ${KUBE_NODE_BRIDGE_NETWORK[${i}]} via ${KUBE_NODE_IP_ADDRESSES[${i}]}n\" kube-ssh \"${KUBE_MASTER_IP}\" \"sudo route add -net ${KUBE_NODE_BRIDGE_NETWORK[${i}]} gw ${KUBE_NODE_IP_ADDRESSES[${i}]}\" for (( j=0; j<${#NODE_NAMES[@]}; j++)); do if [[ $i != $j ]]; then printf \" adding route to ${NODE_NAMES[$j]} for network ${KUBE_NODE_BRIDGE_NETWORK[${i}]} via ${KUBE_NODE_IP_ADDRESSES[${i}]}n\" kube-ssh ${KUBE_NODE_IP_ADDRESSES[$i]} \"sudo route add -net ${KUBE_NODE_BRIDGE_NETWORK[$j]} gw ${KUBE_NODE_IP_ADDRESSES[$j]}\" fi done printf \"n\" done }"} {"_id":"doc-en-kubernetes-9c8601faad6f82bbbb88a75c8b0e776039e90b4266b8e6ab5fe06e36c64b5224","title":"","text":"printf \"Waiting for salt-master to be up on ${KUBE_MASTER} ...n\" remote-pgrep ${KUBE_MASTER_IP} \"salt-master\" printf \"Waiting for all packages to be installed on ${KUBE_MASTER} ...n\" kube-check ${KUBE_MASTER_IP} 'sudo salt \"kubernetes-master\" state.highstate -t 30 | grep -E \"Failed:[[:space:]]+0\"' local i for (( i=0; i<${#NODE_NAMES[@]}; i++)); do printf \"Waiting for salt-minion to be up on ${NODE_NAMES[$i]} ....n\" remote-pgrep ${KUBE_NODE_IP_ADDRESSES[$i]} \"salt-minion\" printf \"Waiting for all salt packages to be installed on ${NODE_NAMES[$i]} .... n\" kube-check ${KUBE_MASTER_IP} 'sudo salt '\"${NODE_NAMES[$i]}\"' state.highstate -t 30 | grep -E \"Failed:[[:space:]]+0\"' printf \" OKn\" done printf \"Waiting for init highstate to be done on all nodes (this can take a few minutes) ...n\" kube-check ${KUBE_MASTER_IP} 'sudo salt '''*''' state.show_highstate -t 50' printf \"Waiting for all packages to be installed on all nodes (this can take a few minutes) ...n\" kube-check ${KUBE_MASTER_IP} 'sudo salt '''*''' state.highstate -t 50 | grep -E \"Failed:[[:space:]]+0\"' echo echo \"Waiting for master and node initialization.\""} {"_id":"doc-en-kubernetes-11a23d68a53cc23621f7c81f02f43b62b96d7b32f5adcc0e35be808425cb57e5","title":"","text":"\"//pkg/runtime:go_default_library\", \"//pkg/types:go_default_library\", \"//pkg/util/errors:go_default_library\", \"//pkg/util/hash:go_default_library\", \"//pkg/util/metrics:go_default_library\", \"//pkg/util/runtime:go_default_library\", \"//pkg/util/wait:go_default_library\","} {"_id":"doc-en-kubernetes-1484fab69a17845a133d95ffc63682543297824d6e5a70e84f2a0a6a6248d32e","title":"","text":"import ( \"encoding/json\" \"fmt\" \"hash/adler32\" \"time\" \"github.com/golang/glog\""} {"_id":"doc-en-kubernetes-6cd1cb973578f88d0ec9e66237fdb7bb9d9e9daf2d705be775682a417a4aaac4","title":"","text":"\"k8s.io/kubernetes/pkg/apis/batch\" \"k8s.io/kubernetes/pkg/runtime\" \"k8s.io/kubernetes/pkg/types\" hashutil \"k8s.io/kubernetes/pkg/util/hash\" ) // Utilities for dealing with Jobs and CronJobs and time."} {"_id":"doc-en-kubernetes-18b5bf76c1ec8e273c12695d30b44afadfebfe6564acf49e0914b896ee149c11","title":"","text":"return job, nil } func getTimeHash(scheduledTime time.Time) uint32 { timeHasher := adler32.New() hashutil.DeepHashObject(timeHasher, scheduledTime) return timeHasher.Sum32() // Return Unix Epoch Time func getTimeHash(scheduledTime time.Time) int64 { return scheduledTime.Unix() } // makeCreatedByRefJson makes a json string with an object reference for use in \"created-by\" annotation value"} {"_id":"doc-en-kubernetes-9eaa01497f9dabf4c879a7ac9bd3da67061bf3ab5737f85a54b128e0947f55ff","title":"","text":"kube::build::run_build_command make test-integration fi kube::build::copy_output if [[ \"${FEDERATION:-}\" == \"true\" ]];then ( source \"${KUBE_ROOT}/build/util.sh\""} {"_id":"doc-en-kubernetes-5c5ac41516d1522f3ff522741ceecff8bb18370d5f1c7d2e0371122056fcff81","title":"","text":") fi kube::build::copy_output kube::release::package_tarballs kube::release::package_hyperkube"} {"_id":"doc-en-kubernetes-fab72fd71153da3379098eff45458c1094b3dde8a2cadb1f0469ff328d19f796","title":"","text":" /* Copyright 2016 The Kubernetes Authors. 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. */ package images import ( \"fmt\" \"runtime\" \"testing\" kubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\" ) type getCoreImageTest struct { i string c *kubeadmapi.MasterConfiguration o string } const testversion = \"1\" func TestGetCoreImage(t *testing.T) { var tokenTest = []struct { t getCoreImageTest expected string }{ {getCoreImageTest{o: \"override\"}, \"override\"}, {getCoreImageTest{ i: KubeEtcdImage, c: &kubeadmapi.MasterConfiguration{}}, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"etcd\", runtime.GOARCH, etcdVersion), }, {getCoreImageTest{ i: KubeAPIServerImage, c: &kubeadmapi.MasterConfiguration{KubernetesVersion: testversion}}, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kube-apiserver\", runtime.GOARCH, testversion), }, {getCoreImageTest{ i: KubeControllerManagerImage, c: &kubeadmapi.MasterConfiguration{KubernetesVersion: testversion}}, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kube-controller-manager\", runtime.GOARCH, testversion), }, {getCoreImageTest{ i: KubeSchedulerImage, c: &kubeadmapi.MasterConfiguration{KubernetesVersion: testversion}}, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kube-scheduler\", runtime.GOARCH, testversion), }, {getCoreImageTest{ i: KubeProxyImage, c: &kubeadmapi.MasterConfiguration{KubernetesVersion: testversion}}, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kube-proxy\", runtime.GOARCH, testversion), }, } for _, rt := range tokenTest { actual := GetCoreImage(rt.t.i, rt.t.c, rt.t.o) if actual != rt.expected { t.Errorf( \"failed GetCoreImage:ntexpected: %snt actual: %s\", rt.expected, actual, ) } } } func TestGetAddonImage(t *testing.T) { var tokenTest = []struct { t string expected string }{ {\"matches nothing\", \"\"}, { KubeDNSImage, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kubedns\", runtime.GOARCH, kubeDNSVersion), }, { KubeDNSmasqImage, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"kube-dnsmasq\", runtime.GOARCH, dnsmasqVersion), }, { KubeExechealthzImage, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"exechealthz\", runtime.GOARCH, exechealthzVersion), }, { Pause, fmt.Sprintf(\"%s/%s-%s:%s\", gcrPrefix, \"pause\", runtime.GOARCH, pauseVersion), }, } for _, rt := range tokenTest { actual := GetAddonImage(rt.t) if actual != rt.expected { t.Errorf( \"failed GetCoreImage:ntexpected: %snt actual: %s\", rt.expected, actual, ) } } } "} {"_id":"doc-en-kubernetes-6d12e73095aa6b41d935ff72fde77e5bc736e633a346ab308ba6f0d162ee2628","title":"","text":"package mount type Mounter struct{} type Mounter struct { mounterPath string } func (mounter *Mounter) Mount(source string, target string, fstype string, options []string) error { return nil"} {"_id":"doc-en-kubernetes-546d2780874ab3ebcf4b459f97e0f8d379dff0b3b72e8a671cc9b7c7f4777f0a","title":"","text":"tags = [\"automanaged\"], deps = [ \"//pkg/api:go_default_library\", \"//pkg/api/helper:go_default_library\", \"//pkg/api/service:go_default_library\", \"//pkg/api/testing:go_default_library\", \"//pkg/features:go_default_library\","} {"_id":"doc-en-kubernetes-c8867da14fcfe960d851085c8543a0a1b7a1f7cec081fe37badd86f89f95f4d6","title":"","text":"} }() if helper.IsServiceIPRequested(service) { // Allocate next available. ip, err := rs.serviceIPs.AllocateNext() if err != nil { // TODO: what error should be returned here? It's not a // field-level validation failure (the field is valid), and it's // not really an internal error. return nil, errors.NewInternalError(fmt.Errorf(\"failed to allocate a serviceIP: %v\", err)) } service.Spec.ClusterIP = ip.String() releaseServiceIP = true } else if helper.IsServiceIPSet(service) { // Try to respect the requested IP. if err := rs.serviceIPs.Allocate(net.ParseIP(service.Spec.ClusterIP)); err != nil { // TODO: when validation becomes versioned, this gets more complicated. el := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"clusterIP\"), service.Spec.ClusterIP, err.Error())} return nil, errors.NewInvalid(api.Kind(\"Service\"), service.Name, el) var err error if service.Spec.Type != api.ServiceTypeExternalName { if releaseServiceIP, err = rs.initClusterIP(service); err != nil { return nil, err } releaseServiceIP = true } nodePortOp := portallocator.StartOperation(rs.serviceNodePorts) defer nodePortOp.Finish() assignNodePorts := shouldAssignNodePorts(service) svcPortToNodePort := map[int]int{} for i := range service.Spec.Ports { servicePort := &service.Spec.Ports[i] allocatedNodePort := svcPortToNodePort[int(servicePort.Port)] if allocatedNodePort == 0 { // This will only scan forward in the service.Spec.Ports list because any matches // before the current port would have been found in svcPortToNodePort. This is really // looking for any user provided values. np := findRequestedNodePort(int(servicePort.Port), service.Spec.Ports) if np != 0 { err := nodePortOp.Allocate(np) if err != nil { // TODO: when validation becomes versioned, this gets more complicated. el := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), np, err.Error())} return nil, errors.NewInvalid(api.Kind(\"Service\"), service.Name, el) } servicePort.NodePort = int32(np) svcPortToNodePort[int(servicePort.Port)] = np } else if assignNodePorts { nodePort, err := nodePortOp.AllocateNext() if err != nil { // TODO: what error should be returned here? It's not a // field-level validation failure (the field is valid), and it's // not really an internal error. return nil, errors.NewInternalError(fmt.Errorf(\"failed to allocate a nodePort: %v\", err)) } servicePort.NodePort = int32(nodePort) svcPortToNodePort[int(servicePort.Port)] = nodePort } } else if int(servicePort.NodePort) != allocatedNodePort { if servicePort.NodePort == 0 { servicePort.NodePort = int32(allocatedNodePort) } else { err := nodePortOp.Allocate(int(servicePort.NodePort)) if err != nil { // TODO: when validation becomes versioned, this gets more complicated. el := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), servicePort.NodePort, err.Error())} return nil, errors.NewInvalid(api.Kind(\"Service\"), service.Name, el) } } if service.Spec.Type == api.ServiceTypeNodePort || service.Spec.Type == api.ServiceTypeLoadBalancer { if err := rs.initNodePorts(service, nodePortOp); err != nil { return nil, err } }"} {"_id":"doc-en-kubernetes-473ea90178323de9eeb4fe6fb30c59e57f265a8170d166f1a9d9c3be15bc227b","title":"","text":"// Update service from NodePort or LoadBalancer to ExternalName or ClusterIP, should release NodePort if exists. if (oldService.Spec.Type == api.ServiceTypeNodePort || oldService.Spec.Type == api.ServiceTypeLoadBalancer) && (service.Spec.Type == api.ServiceTypeExternalName || service.Spec.Type == api.ServiceTypeClusterIP) { rs.releaseNodePort(oldService, nodePortOp) rs.releaseNodePorts(oldService, nodePortOp) } // Update service from any type to NodePort or LoadBalancer, should update NodePort. if service.Spec.Type == api.ServiceTypeNodePort || service.Spec.Type == api.ServiceTypeLoadBalancer { if err := rs.updateNodePort(oldService, service, nodePortOp); err != nil { if err := rs.updateNodePorts(oldService, service, nodePortOp); err != nil { return nil, false, err } }"} {"_id":"doc-en-kubernetes-3c3d75e6fc1bbb49d8da2315dbe47ee771c9bc77a5a82dce877f8e11925389aa","title":"","text":"return servicePorts } func shouldAssignNodePorts(service *api.Service) bool { switch service.Spec.Type { case api.ServiceTypeLoadBalancer: return true case api.ServiceTypeNodePort: return true case api.ServiceTypeClusterIP: return false case api.ServiceTypeExternalName: return false default: glog.Errorf(\"Unknown service type: %v\", service.Spec.Type) return false } } // Loop through the service ports list, find one with the same port number and // NodePort specified, return this NodePort otherwise return 0. func findRequestedNodePort(port int, servicePorts []api.ServicePort) int {"} {"_id":"doc-en-kubernetes-7ad3c24eb3e2c50938f6bc2e7bdd204ceabc9db3ff203e6f2fc90533b8f35c75","title":"","text":"return false, nil } func (rs *REST) updateNodePort(oldService, newService *api.Service, nodePortOp *portallocator.PortAllocationOperation) error { func (rs *REST) initNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) error { svcPortToNodePort := map[int]int{} for i := range service.Spec.Ports { servicePort := &service.Spec.Ports[i] allocatedNodePort := svcPortToNodePort[int(servicePort.Port)] if allocatedNodePort == 0 { // This will only scan forward in the service.Spec.Ports list because any matches // before the current port would have been found in svcPortToNodePort. This is really // looking for any user provided values. np := findRequestedNodePort(int(servicePort.Port), service.Spec.Ports) if np != 0 { err := nodePortOp.Allocate(np) if err != nil { // TODO: when validation becomes versioned, this gets more complicated. el := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), np, err.Error())} return errors.NewInvalid(api.Kind(\"Service\"), service.Name, el) } servicePort.NodePort = int32(np) svcPortToNodePort[int(servicePort.Port)] = np } else { nodePort, err := nodePortOp.AllocateNext() if err != nil { // TODO: what error should be returned here? It's not a // field-level validation failure (the field is valid), and it's // not really an internal error. return errors.NewInternalError(fmt.Errorf(\"failed to allocate a nodePort: %v\", err)) } servicePort.NodePort = int32(nodePort) svcPortToNodePort[int(servicePort.Port)] = nodePort } } else if int(servicePort.NodePort) != allocatedNodePort { // TODO(xiangpengzhao): do we need to allocate a new NodePort in this case? // Note: the current implementation is better, because it saves a NodePort. if servicePort.NodePort == 0 { servicePort.NodePort = int32(allocatedNodePort) } else { err := nodePortOp.Allocate(int(servicePort.NodePort)) if err != nil { // TODO: when validation becomes versioned, this gets more complicated. el := field.ErrorList{field.Invalid(field.NewPath(\"spec\", \"ports\").Index(i).Child(\"nodePort\"), servicePort.NodePort, err.Error())} return errors.NewInvalid(api.Kind(\"Service\"), service.Name, el) } } } } return nil } func (rs *REST) updateNodePorts(oldService, newService *api.Service, nodePortOp *portallocator.PortAllocationOperation) error { oldNodePorts := CollectServiceNodePorts(oldService) newNodePorts := []int{}"} {"_id":"doc-en-kubernetes-90056a1143c7f228814c87ad6501a6197af1886e6203f4d7c15c080bcbac3b37","title":"","text":"return nil } func (rs *REST) releaseNodePort(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) { func (rs *REST) releaseNodePorts(service *api.Service, nodePortOp *portallocator.PortAllocationOperation) { nodePorts := CollectServiceNodePorts(service) for _, nodePort := range nodePorts {"} {"_id":"doc-en-kubernetes-cb30776a47404d5bb2aa601323af66b62891c36869ba45c1efb1458e83d9f3cd","title":"","text":"\"k8s.io/apiserver/pkg/registry/rest\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/helper\" \"k8s.io/kubernetes/pkg/api/service\" \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/pkg/registry/core/service/ipallocator\""} {"_id":"doc-en-kubernetes-22ec6fe0f7109f2204afbef68c05317a54fe99c66699a4aba7342fe601b14367","title":"","text":"if test.name == \"Allocate specified ClusterIP\" && test.svc.Spec.ClusterIP != \"1.2.3.4\" { t.Errorf(\"%q: expected ClusterIP %q, but got %q\", test.name, \"1.2.3.4\", test.svc.Spec.ClusterIP) } if hasAllocatedIP { if helper.IsServiceIPSet(test.svc) { storage.serviceIPs.Release(net.ParseIP(test.svc.Spec.ClusterIP)) } } } } func TestInitNodePorts(t *testing.T) { storage, _ := NewTestREST(t, nil) nodePortOp := portallocator.StartOperation(storage.serviceNodePorts) defer nodePortOp.Finish() testCases := []struct { name string service *api.Service expectSpecifiedNodePorts []int }{ { name: \"Service doesn't have specified NodePort\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, }, }, }, }, expectSpecifiedNodePorts: []int{}, }, { name: \"Service has one specified NodePort\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{{ Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, NodePort: 30053, }}, }, }, expectSpecifiedNodePorts: []int{30053}, }, { name: \"Service has two same ports with different protocols and specifies same NodePorts\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, NodePort: 30054, }, { Name: \"port-udp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolUDP, NodePort: 30054, }, }, }, }, expectSpecifiedNodePorts: []int{30054, 30054}, }, { name: \"Service has two same ports with different protocols and specifies different NodePorts\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, NodePort: 30055, }, { Name: \"port-udp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolUDP, NodePort: 30056, }, }, }, }, expectSpecifiedNodePorts: []int{30055, 30056}, }, { name: \"Service has two different ports with different protocols and specifies different NodePorts\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, NodePort: 30057, }, { Name: \"port-udp\", Port: 54, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolUDP, NodePort: 30058, }, }, }, }, expectSpecifiedNodePorts: []int{30057, 30058}, }, { name: \"Service has two same ports with different protocols but only specifies one NodePort\", service: &api.Service{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: api.ServiceSpec{ Selector: map[string]string{\"bar\": \"baz\"}, Type: api.ServiceTypeNodePort, Ports: []api.ServicePort{ { Name: \"port-tcp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolTCP, NodePort: 30059, }, { Name: \"port-udp\", Port: 53, TargetPort: intstr.FromInt(6502), Protocol: api.ProtocolUDP, }, }, }, }, expectSpecifiedNodePorts: []int{30059, 30059}, }, } for _, test := range testCases { err := storage.initNodePorts(test.service, nodePortOp) if err != nil { t.Errorf(\"%q: unexpected error: %v\", test.name, err) continue } serviceNodePorts := CollectServiceNodePorts(test.service) if len(test.expectSpecifiedNodePorts) == 0 { for _, nodePort := range serviceNodePorts { if !storage.serviceNodePorts.Has(nodePort) { t.Errorf(\"%q: unexpected NodePort %d, out of range\", test.name, nodePort) } } } else if !reflect.DeepEqual(serviceNodePorts, test.expectSpecifiedNodePorts) { t.Errorf(\"%q: expected NodePorts %v, but got %v\", test.name, test.expectSpecifiedNodePorts, serviceNodePorts) } } } func TestUpdateNodePort(t *testing.T) { func TestUpdateNodePorts(t *testing.T) { storage, _ := NewTestREST(t, nil) nodePortOp := portallocator.StartOperation(storage.serviceNodePorts) defer nodePortOp.Finish()"} {"_id":"doc-en-kubernetes-e9b0df1ce1a76be3e78597dcda54e0cfa90d25105b96886dec63f06011f7b6a0","title":"","text":"} for _, test := range testCases { err := storage.updateNodePort(test.oldService, test.newService, nodePortOp) err := storage.updateNodePorts(test.oldService, test.newService, nodePortOp) if err != nil { t.Errorf(\"%q: unexpected error: %v\", test.name, err) continue } _ = nodePortOp.Commit() serviceNodePorts := CollectServiceNodePorts(test.newService)"} {"_id":"doc-en-kubernetes-abf395a1f3c70cde60033c0b012a8e9602500a97dbc69b7f2007fe44c6bd4bc6","title":"","text":"KUBELET_CERT_BASE64=$(get-env-val \"${master_env}\" \"KUBELET_CERT\") KUBELET_KEY_BASE64=$(get-env-val \"${master_env}\" \"KUBELET_KEY\") } # Update or verify required gcloud components are installed # at minimum required version. # Assumed vars # KUBE_PROMPT_FOR_UPDATE function update-or-verify-gcloud() { local sudo_prefix=\"\" if [ ! -w $(dirname `which gcloud`) ]; then sudo_prefix=\"sudo\" fi # update and install components as needed if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" == \"y\" ]]; then ${sudo_prefix} gcloud ${gcloud_prompt:-} components install alpha ${sudo_prefix} gcloud ${gcloud_prompt:-} components install beta ${sudo_prefix} gcloud ${gcloud_prompt:-} components update else local version=$(${sudo_prefix} gcloud version --format=json) python -c' import json,sys from distutils import version minVersion = version.LooseVersion(\"1.3.0\") required = [ \"alpha\", \"beta\", \"core\" ] data = json.loads(sys.argv[1]) rel = data.get(\"Google Cloud SDK\") if rel != \"HEAD\" and version.LooseVersion(rel) < minVersion: print \"gcloud version out of date ( < %s )\" % minVersion exit(1) missing = [] for c in required: if not data.get(c): missing += [c] if missing: for c in missing: print (\"missing required gcloud component \"{0}\"\".format(c)) exit(1) ' \"\"\"${version}\"\"\" fi } "} {"_id":"doc-en-kubernetes-2de30bda42218a876892f5bfa52f6af31a539f976c8f452165c41f97452a770b","title":"","text":"ALLOCATE_NODE_CIDRS=true KUBE_PROMPT_FOR_UPDATE=y KUBE_SKIP_UPDATE=${KUBE_SKIP_UPDATE-\"n\"} KUBE_PROMPT_FOR_UPDATE=${KUBE_PROMPT_FOR_UPDATE:-\"n\"} # How long (in seconds) to wait for cluster initialization. KUBE_CLUSTER_INITIALIZATION_TIMEOUT=${KUBE_CLUSTER_INITIALIZATION_TIMEOUT:-300}"} {"_id":"doc-en-kubernetes-926420af46c05d670deca88b0fe0138bcb696cac8ffcb3ad817ca47eef6f2db5","title":"","text":"local cmd for cmd in gcloud gsutil; do if ! which \"${cmd}\" >/dev/null; then local resp local resp=\"n\" if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" == \"y\" ]]; then echo \"Can't find ${cmd} in PATH. Do you wish to install the Google Cloud SDK? [Y/n]\" read resp else resp=\"y\" fi if [[ \"${resp}\" != \"n\" && \"${resp}\" != \"N\" ]]; then curl https://sdk.cloud.google.com | bash"} {"_id":"doc-en-kubernetes-2e974456bed4fba7efc91b3e2e51b04ec0d6c51f3790d3c9d92d7cf8e3302dab","title":"","text":"fi fi done if [[ \"${KUBE_SKIP_UPDATE}\" == \"y\" ]]; then return fi # update and install components as needed if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" != \"y\" ]]; then gcloud_prompt=\"-q\" fi local sudo_prefix=\"\" if [ ! -w $(dirname `which gcloud`) ]; then sudo_prefix=\"sudo\" fi ${sudo_prefix} gcloud ${gcloud_prompt:-} components install alpha || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components install beta || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components update || true update-or-verify-gcloud } # Create a temp dir that'll be deleted at the end of this bash session."} {"_id":"doc-en-kubernetes-80dad9c37dd339b61ab826579263f702cf01121bbdb7fe6b6f36a69ed5c8e86a","title":"","text":"# Uses the config file specified in $KUBE_CONFIG_FILE, or defaults to config-default.sh KUBE_PROMPT_FOR_UPDATE=y KUBE_SKIP_UPDATE=${KUBE_SKIP_UPDATE-\"n\"} KUBE_PROMPT_FOR_UPDATE=${KUBE_PROMPT_FOR_UPDATE:-\"n\"} KUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/../.. source \"${KUBE_ROOT}/cluster/gke/${KUBE_CONFIG_FILE:-config-default.sh}\" source \"${KUBE_ROOT}/cluster/common.sh\""} {"_id":"doc-en-kubernetes-c3310ef379ed3dac91546827630a4cf8fb17a30c4fba93b6626b606a8afebbca","title":"","text":"if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" == \"y\" ]]; then echo \"Can't find gcloud in PATH. Do you wish to install the Google Cloud SDK? [Y/n]\" read resp else resp=\"y\" fi if [[ \"${resp}\" != \"n\" && \"${resp}\" != \"N\" ]]; then curl https://sdk.cloud.google.com | bash"} {"_id":"doc-en-kubernetes-d857c1c57ef17c94a86790ee73aeea3556764c7e4e252e75834bcb33923a4351","title":"","text":"exit 1 fi fi if [[ \"${KUBE_SKIP_UPDATE}\" == \"y\" ]]; then return fi # update and install components as needed if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" != \"y\" ]]; then gcloud_prompt=\"-q\" fi local sudo_prefix=\"\" if [ ! -w $(dirname `which gcloud`) ]; then sudo_prefix=\"sudo\" fi ${sudo_prefix} gcloud ${gcloud_prompt:-} components install alpha || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components install beta || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components install kubectl|| true ${sudo_prefix} gcloud ${gcloud_prompt:-} components update || true update-or-verify-gcloud } # Validate a kubernetes cluster"} {"_id":"doc-en-kubernetes-6a2118b7d86fa919f4743e7e687fa1586c75b70a18bc795103f8b234a1de32cf","title":"","text":"\"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/types:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/watch:go_default_library\", \"//vendor/k8s.io/client-go/pkg/api/v1:go_default_library\","} {"_id":"doc-en-kubernetes-036ae274e75184025f083cb230dbd611ba3464705a8721f8c4772032ac3af7b4","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" pkgruntime \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/apimachinery/pkg/watch\" \"k8s.io/client-go/tools/cache\""} {"_id":"doc-en-kubernetes-06c4003e04f19c8e075b9dc36c6d1a8c70df8d5a7b7374e27b1c10a8cec8350c","title":"","text":"non-nil error is also returned (possibly along with a partially complete list of resolved endpoints. */ func getResolvedEndpoints(endpoints []string) ([]string, error) { resolvedEndpoints := make([]string, 0, len(endpoints)) resolvedEndpoints := sets.String{} for _, endpoint := range endpoints { if net.ParseIP(endpoint) == nil { // It's not a valid IP address, so assume it's a DNS name, and try to resolve it, // replacing its DNS name with its IP addresses in expandedEndpoints ipAddrs, err := net.LookupHost(endpoint) if err != nil { return resolvedEndpoints, err return resolvedEndpoints.List(), err } for _, ip := range ipAddrs { resolvedEndpoints = resolvedEndpoints.Union(sets.NewString(ip)) } resolvedEndpoints = append(resolvedEndpoints, ipAddrs...) } else { resolvedEndpoints = append(resolvedEndpoints, endpoint) resolvedEndpoints = resolvedEndpoints.Union(sets.NewString(endpoint)) } } return resolvedEndpoints, nil return resolvedEndpoints.List(), nil } /* ensureDNSRrsets ensures (idempotently, and with minimum mutations) that all of the DNS resource record sets for dnsName are consistent with endpoints."} {"_id":"doc-en-kubernetes-3f74a11db6da878ed249d31ade6eeeb8ffa4b06ffb11a6310c374fb04851ace6","title":"","text":"if observedReadyCondition.Status != v1.ConditionUnknown { currentReadyCondition.Status = v1.ConditionUnknown currentReadyCondition.Reason = \"NodeStatusUnknown\" currentReadyCondition.Message = fmt.Sprintf(\"Kubelet stopped posting node status.\") currentReadyCondition.Message = \"Kubelet stopped posting node status.\" // LastProbeTime is the last time we heard from kubelet. currentReadyCondition.LastHeartbeatTime = observedReadyCondition.LastHeartbeatTime currentReadyCondition.LastTransitionTime = nc.now() } } // Like NodeReady condition, NodeOutOfDisk was last set longer ago than gracePeriod, so update // it to Unknown (regardless of its current value) in the master. // TODO(madhusudancs): Refactor this with readyCondition to remove duplicated code. _, oodCondition := v1.GetNodeCondition(&node.Status, v1.NodeOutOfDisk) if oodCondition == nil { glog.V(2).Infof(\"Out of disk condition of node %v is never updated by kubelet\", node.Name) node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{ Type: v1.NodeOutOfDisk, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: fmt.Sprintf(\"Kubelet never posted node status.\"), LastHeartbeatTime: node.CreationTimestamp, LastTransitionTime: nc.now(), }) } else { glog.V(4).Infof(\"node %v hasn't been updated for %+v. Last out of disk condition is: %+v\", node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), oodCondition) if oodCondition.Status != v1.ConditionUnknown { oodCondition.Status = v1.ConditionUnknown oodCondition.Reason = \"NodeStatusUnknown\" oodCondition.Message = fmt.Sprintf(\"Kubelet stopped posting node status.\") oodCondition.LastTransitionTime = nc.now() // remaining node conditions should also be set to Unknown remainingNodeConditionTypes := []v1.NodeConditionType{v1.NodeOutOfDisk, v1.NodeMemoryPressure, v1.NodeDiskPressure} nowTimestamp := nc.now() for _, nodeConditionType := range remainingNodeConditionTypes { _, currentCondition := v1.GetNodeCondition(&node.Status, nodeConditionType) if currentCondition == nil { glog.V(2).Infof(\"Condition %v of node %v was never updated by kubelet\", nodeConditionType, node.Name) node.Status.Conditions = append(node.Status.Conditions, v1.NodeCondition{ Type: nodeConditionType, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: \"Kubelet never posted node status.\", LastHeartbeatTime: node.CreationTimestamp, LastTransitionTime: nowTimestamp, }) } else { glog.V(4).Infof(\"node %v hasn't been updated for %+v. Last %v is: %+v\", node.Name, nc.now().Time.Sub(savedNodeStatus.probeTimestamp.Time), nodeConditionType, currentCondition) if currentCondition.Status != v1.ConditionUnknown { currentCondition.Status = v1.ConditionUnknown currentCondition.Reason = \"NodeStatusUnknown\" currentCondition.Message = \"Kubelet stopped posting node status.\" currentCondition.LastTransitionTime = nowTimestamp } } }"} {"_id":"doc-en-kubernetes-6ca89af2283366bb38ff35f84dcc3d90e61a79a9984907063ec4efc9c4d5fbb5","title":"","text":"LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: fakeNow, }, { Type: v1.NodeMemoryPressure, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: \"Kubelet never posted node status.\", LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: fakeNow, }, { Type: v1.NodeDiskPressure, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: \"Kubelet never posted node status.\", LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: fakeNow, }, }, }, },"} {"_id":"doc-en-kubernetes-7ea9c89f8c3526458415ef4017fcb3b43c0f41e2eb44f8b6927161c9c7cf5ef1","title":"","text":"LastHeartbeatTime: metav1.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC), LastTransitionTime: metav1.Time{Time: metav1.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC).Add(time.Hour)}, }, { Type: v1.NodeMemoryPressure, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: \"Kubelet never posted node status.\", LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), // should default to node creation time if condition was never updated LastTransitionTime: metav1.Time{Time: metav1.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC).Add(time.Hour)}, }, { Type: v1.NodeDiskPressure, Status: v1.ConditionUnknown, Reason: \"NodeStatusNeverUpdated\", Message: \"Kubelet never posted node status.\", LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), // should default to node creation time if condition was never updated LastTransitionTime: metav1.Time{Time: metav1.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC).Add(time.Hour)}, }, }, Capacity: v1.ResourceList{ v1.ResourceName(v1.ResourceCPU): resource.MustParse(\"10\"),"} {"_id":"doc-en-kubernetes-03256de707327460099b4079ecc1785ff92848b5f817642ee0db89368eda7748","title":"","text":"\"strings\" \"time\" \"k8s.io/kubernetes/pkg/api/resource\" \"k8s.io/kubernetes/pkg/api/v1\" clientset \"k8s.io/kubernetes/pkg/client/clientset_generated/release_1_5\" \"k8s.io/kubernetes/pkg/labels\""} {"_id":"doc-en-kubernetes-5cf80e5899cb242157c4dd029773863c309163202cac5a4af4ba1228fc7ac6ea","title":"","text":"const ( DNSdefaultTimeout = 5 * time.Minute DNSscaleUpTimeout = 5 * time.Minute DNSscaleDownTimeout = 10 * time.Minute DNSNamespace = \"kube-system\" ClusterAddonLabelKey = \"k8s-app\" KubeDNSLabelName = \"kube-dns\""} {"_id":"doc-en-kubernetes-84d0ef74323670a4e13a992bb2f0d210ed25f5e0f3e2ca96ad4dd55f8a1fee8b","title":"","text":"var _ = framework.KubeDescribe(\"DNS horizontal autoscaling\", func() { f := framework.NewDefaultFramework(\"dns-autoscaling\") var c clientset.Interface var nodeCount int var previousParams map[string]string DNSParams_1 := map[string]string{\"linear\": \"{\"nodesPerReplica\": 1}\"} DNSParams_2 := map[string]string{\"linear\": \"{\"nodesPerReplica\": 2}\"} DNSParams_3 := map[string]string{\"linear\": \"{\"nodesPerReplica\": 3}\"} DNSParams_1 := DNSParamsLinear{map[string]string{\"linear\": \"{\"nodesPerReplica\": 1}\"}, 1.0, 0.0} DNSParams_2 := DNSParamsLinear{map[string]string{\"linear\": \"{\"nodesPerReplica\": 2}\"}, 2.0, 0.0} DNSParams_3 := DNSParamsLinear{map[string]string{\"linear\": \"{\"nodesPerReplica\": 3, \"coresPerReplica\": 3}\"}, 3.0, 3.0} BeforeEach(func() { framework.SkipUnlessProviderIs(\"gce\") c = f.ClientSet nodes := framework.GetReadySchedulableNodesOrDie(c) nodeCount = len(nodes.Items) Expect(nodeCount).NotTo(BeZero()) Expect(len(framework.GetReadySchedulableNodesOrDie(c).Items)).NotTo(BeZero()) pcm, err := fetchDNSScalingConfigMap(c) ExpectNoError(err) Expect(err).NotTo(HaveOccurred()) previousParams = pcm.Data By(\"Replace the dns autoscaling parameters with testing parameters\") ExpectNoError(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_1))) Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_1.data))).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, nodeCount, DNSdefaultTimeout)) getExpectReplicasLinear := getExpectReplicasFuncLinear(c, &DNSParams_1) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) }) AfterEach(func() { By(\"Restoring intial dns autoscaling parameters\") ExpectNoError(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(previousParams))) Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(previousParams))).NotTo(HaveOccurred()) }) // This test is separated because it is slow and need to run serially"} {"_id":"doc-en-kubernetes-9b3d7525c81a5c17e537579835e695ddd9e6052cac35cd0d920e900796886c5d","title":"","text":"sum := 0 for _, mig := range strings.Split(framework.TestContext.CloudConfig.NodeInstanceGroup, \",\") { size, err := GroupSize(mig) ExpectNoError(err) Expect(err).NotTo(HaveOccurred()) By(fmt.Sprintf(\"Initial size of %s: %d\", mig, size)) originalSizes[mig] = size sum += size } Expect(nodeCount).Should(Equal(sum)) By(\"Manually increase cluster size\") increasedSize := 0"} {"_id":"doc-en-kubernetes-0be3e4c83c43c1883106c34984d4387977a92ff09ed94a29b7d64bcd1a1c7b6c","title":"","text":"increasedSize += increasedSizes[key] } setMigSizes(increasedSizes) ExpectNoError(WaitForClusterSizeFunc(c, func(size int) bool { return size == increasedSize }, DNSscaleUpTimeout)) Expect(WaitForClusterSizeFunc(c, func(size int) bool { return size == increasedSize }, scaleUpTimeout)).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") getExpectReplicasLinear := getExpectReplicasFuncLinear(c, &DNSParams_1) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) By(\"Replace the dns autoscaling parameters with another testing parameters\") Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_3.data))).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, increasedSize, DNSdefaultTimeout)) getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams_3) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) By(\"Restoring cluster size\") setMigSizes(originalSizes) framework.ExpectNoError(framework.WaitForClusterSize(c, nodeCount, DNSscaleDownTimeout)) Expect(framework.WaitForClusterSize(c, sum, scaleDownTimeout)).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, nodeCount, DNSdefaultTimeout)) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) }) It(\"kube-dns-autoscaler should scale kube-dns pods in both nonfaulty and faulty scenarios\", func() { By(\"--- Scenario: should scale kube-dns based on changed parameters ---\") By(\"Replace the dns autoscaling parameters with the second testing parameters\") ExpectNoError(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_2))) By(\"Replace the dns autoscaling parameters with another testing parameters\") Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_3.data))).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, int(math.Ceil(float64(nodeCount)/2.0)), DNSdefaultTimeout)) getExpectReplicasLinear := getExpectReplicasFuncLinear(c, &DNSParams_3) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) By(\"--- Scenario: should re-create scaling parameters with default value when parameters got deleted ---\") By(\"Delete the ConfigMap for autoscaler\") err := deleteDNSScalingConfigMap(c) ExpectNoError(err) Expect(err).NotTo(HaveOccurred()) By(\"Wait for the ConfigMap got re-created\") configMap, err := waitForDNSConfigMapCreated(c, DNSdefaultTimeout) ExpectNoError(err) Expect(err).NotTo(HaveOccurred()) By(\"Check the new created ConfigMap got the same data as we have\") Expect(reflect.DeepEqual(previousParams, configMap.Data)).To(Equal(true)) By(\"Replace the dns autoscaling parameters with the second testing parameters\") ExpectNoError(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_2))) By(\"Replace the dns autoscaling parameters with another testing parameters\") Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_2.data))).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, int(math.Ceil(float64(nodeCount)/2.0)), DNSdefaultTimeout)) getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams_2) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) By(\"--- Scenario: should recover after autoscaler pod got deleted ---\") By(\"Delete the autoscaler pod for kube-dns\") ExpectNoError(deleteDNSAutoscalerPod(c)) Expect(deleteDNSAutoscalerPod(c)).NotTo(HaveOccurred()) By(\"Replace the dns autoscaling parameters with the third testing parameters\") ExpectNoError(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_3))) By(\"Replace the dns autoscaling parameters with another testing parameters\") Expect(updateDNSScalingConfigMap(c, packDNSScalingConfigMap(DNSParams_1.data))).NotTo(HaveOccurred()) By(\"Wait for kube-dns scaled to expected number\") ExpectNoError(waitForDNSReplicasSatisfied(c, int(math.Ceil(float64(nodeCount)/3.0)), DNSdefaultTimeout)) getExpectReplicasLinear = getExpectReplicasFuncLinear(c, &DNSParams_1) Expect(waitForDNSReplicasSatisfied(c, getExpectReplicasLinear, DNSdefaultTimeout)).NotTo(HaveOccurred()) }) }) type DNSParamsLinear struct { data map[string]string nodesPerReplica float64 coresPerReplica float64 } type getExpectReplicasFunc func(c clientset.Interface) int func getExpectReplicasFuncLinear(c clientset.Interface, params *DNSParamsLinear) getExpectReplicasFunc { return func(c clientset.Interface) int { var replicasFromNodes float64 var replicasFromCores float64 nodes := framework.GetReadySchedulableNodesOrDie(c).Items if params.nodesPerReplica > 0 { replicasFromNodes = math.Ceil(float64(len(nodes)) / params.nodesPerReplica) } if params.coresPerReplica > 0 { replicasFromCores = math.Ceil(float64(getScheduableCores(nodes)) / params.coresPerReplica) } return int(math.Max(1.0, math.Max(replicasFromNodes, replicasFromCores))) } } func getScheduableCores(nodes []v1.Node) int64 { var sc resource.Quantity for _, node := range nodes { if !node.Spec.Unschedulable { sc.Add(node.Status.Capacity[v1.ResourceCPU]) } } scInt64, scOk := sc.AsInt64() if !scOk { framework.Logf(\"unable to compute integer values of schedulable cores in the cluster\") return 0 } return scInt64 } func fetchDNSScalingConfigMap(c clientset.Interface) (*v1.ConfigMap, error) { cm, err := c.Core().ConfigMaps(DNSNamespace).Get(DNSAutoscalerLabelName) if err != nil {"} {"_id":"doc-en-kubernetes-d12481dae516e3e0d0881a1a779b33114f990ad350123b3c03d3c3f4c4c462fa","title":"","text":"return nil } func waitForDNSReplicasSatisfied(c clientset.Interface, expected int, timeout time.Duration) (err error) { func waitForDNSReplicasSatisfied(c clientset.Interface, getExpected getExpectReplicasFunc, timeout time.Duration) (err error) { var current int framework.Logf(\"Waiting up to %v for kube-dns reach %v replicas\", timeout, expected) var expected int framework.Logf(\"Waiting up to %v for kube-dns to reach expected replicas\", timeout) condition := func() (bool, error) { current, err = getDNSReplicas(c) if err != nil { return false, err } expected = getExpected(c) if current != expected { framework.Logf(\"replicas not as expected: got %v, expected %v\", current, expected) return false, nil } return true, nil } if err = wait.Poll(time.Second, timeout, condition); err != nil { if err = wait.Poll(2*time.Second, timeout, condition); err != nil { return fmt.Errorf(\"err waiting for DNS replicas to satisfy %v, got %v: %v\", expected, current, err) } framework.Logf(\"kube-dns reaches expected replicas: %v\", expected) return nil }"} {"_id":"doc-en-kubernetes-5df55c5d4296ef65620bc9ab5a6318e13c5933833aa80c2c659d689db733ed96","title":"","text":"VolumeMounts: volumeMounts, LivenessProbe: componentProbe(8080, \"/healthz\"), Resources: componentResources(\"250m\"), Env: getProxyEnvVars(), }, volumes...), kubeControllerManager: componentPod(api.Container{ Name: kubeControllerManager,"} {"_id":"doc-en-kubernetes-81aaaa2c32c35b12422456e05906af40a56154a8f6aa6e4b7d9e0e6fcbc5bf84","title":"","text":"VolumeMounts: volumeMounts, LivenessProbe: componentProbe(10252, \"/healthz\"), Resources: componentResources(\"200m\"), Env: getProxyEnvVars(), }, volumes...), kubeScheduler: componentPod(api.Container{ Name: kubeScheduler,"} {"_id":"doc-en-kubernetes-5942d75cfa7a69c14666ad6f951408012954c803e0aba5e4fe1bb36b924946d7","title":"","text":"Command: getSchedulerCommand(cfg), LivenessProbe: componentProbe(10251, \"/healthz\"), Resources: componentResources(\"100m\"), Env: getProxyEnvVars(), }), }"} {"_id":"doc-en-kubernetes-7b18bab35e421acf1a8a6b1648d1e48f3ed68db49fa302b28e91cd8be214b4c1","title":"","text":"return } func getProxyEnvVars() []api.EnvVar { envs := []api.EnvVar{} for _, env := range os.Environ() { pos := strings.Index(env, \"=\") if pos == -1 { // malformed environment variable, skip it. continue } name := env[:pos] value := env[pos+1:] if strings.HasSuffix(strings.ToLower(name), \"_proxy\") && value != \"\" { envVar := api.EnvVar{Name: name, Value: value} envs = append(envs, envVar) } } return envs } "} {"_id":"doc-en-kubernetes-e8db3a62748a6bb0dfa050301c7bda30497b470d898a12e7513b704552987ae2","title":"","text":"&HorizontalPodAutoscaler{}, &HorizontalPodAutoscalerList{}, &api.ListOptions{}, &api.DeleteOptions{}, ) return nil }"} {"_id":"doc-en-kubernetes-eccb1088fe9274105971606c691981e017941ec16764a037ef2440c863743f37","title":"","text":"&CronJob{}, &CronJobList{}, &api.ListOptions{}, &api.DeleteOptions{}, ) scheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"ScheduledJob\"), &CronJob{}) scheme.AddKnownTypeWithName(SchemeGroupVersion.WithKind(\"ScheduledJobList\"), &CronJobList{})"} {"_id":"doc-en-kubernetes-acdde24c5d3e53ac19d61101c4c46d071a70e2336e2a81ef4f4578c9acb1d49d","title":"","text":"return } // truncatePodHostnameIfNeeded truncates the pod hostname if it's longer than 63 chars. func truncatePodHostnameIfNeeded(podName, hostname string) (string, error) { // Cap hostname at 63 chars (specification is 64bytes which is 63 chars and the null terminating char). const hostnameMaxLen = 63 if len(hostname) <= hostnameMaxLen { return hostname, nil } truncated := hostname[:hostnameMaxLen] glog.Errorf(\"hostname for pod:%q was longer than %d. Truncated hostname to :%q\", podName, hostnameMaxLen, truncated) // hostname should not end with '-' or '.' truncated = strings.TrimRight(truncated, \"-.\") if len(truncated) == 0 { // This should never happen. return \"\", fmt.Errorf(\"hostname for pod %q was invalid: %q\", podName, hostname) } return truncated, nil } // GeneratePodHostNameAndDomain creates a hostname and domain name for a pod, // given that pod's spec and annotations or returns an error. func (kl *Kubelet) GeneratePodHostNameAndDomain(pod *api.Pod) (string, string, error) { // TODO(vmarmol): Handle better. // Cap hostname at 63 chars (specification is 64bytes which is 63 chars and the null terminating char). clusterDomain := kl.clusterDomain const hostnameMaxLen = 63 podAnnotations := pod.Annotations if podAnnotations == nil { podAnnotations = make(map[string]string)"} {"_id":"doc-en-kubernetes-6ab5b0e51870dd33c95931952bc96f487195f6c4fcaeb6c257cd5ccacaca1d6f","title":"","text":"hostname = hostnameCandidate } } if len(hostname) > hostnameMaxLen { hostname = hostname[:hostnameMaxLen] glog.Errorf(\"hostname for pod:%q was longer than %d. Truncated hostname to :%q\", pod.Name, hostnameMaxLen, hostname) hostname, err := truncatePodHostnameIfNeeded(pod.Name, hostname) if err != nil { return \"\", \"\", err } hostDomain := \"\""} {"_id":"doc-en-kubernetes-50f0a7a5f79dc6e7d0936e47093fb77e302af89047e9f10d6edfda126e8bbc5a","title":"","text":"} } } func TestTruncatePodHostname(t *testing.T) { for c, test := range map[string]struct { input string output string }{ \"valid hostname\": { input: \"test.pod.hostname\", output: \"test.pod.hostname\", }, \"too long hostname\": { input: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.\", // 8*9=72 chars output: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567\", //8*8-1=63 chars }, \"hostname end with .\": { input: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456.1234567.\", // 8*9-1=71 chars output: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456\", //8*8-2=62 chars }, \"hostname end with -\": { input: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456-1234567.\", // 8*9-1=71 chars output: \"1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456\", //8*8-2=62 chars }, } { t.Logf(\"TestCase: %q\", c) output, err := truncatePodHostnameIfNeeded(\"test-pod\", test.input) assert.NoError(t, err) assert.Equal(t, test.output, output) } } "} {"_id":"doc-en-kubernetes-9ce72afa661464b5dfbfb188c8cbce94dbc29e38fe4910884c4833a2789019de","title":"","text":"// badGatewayError renders a simple bad gateway error. func badGatewayError(w http.ResponseWriter, req *http.Request) { w.Header().Set(\"Content-Type\", \"text/plain\") w.Header().Set(\"X-Content-Type-Options\", \"nosniff\") w.WriteHeader(http.StatusBadGateway) fmt.Fprintf(w, \"Bad Gateway: %#v\", req.RequestURI) }"} {"_id":"doc-en-kubernetes-13e4cd538d7179507c2a15d1455cb159f416ca28f7d22c1f1d216d350d03dace","title":"","text":"// forbidden renders a simple forbidden error func forbidden(attributes authorizer.Attributes, w http.ResponseWriter, req *http.Request, reason string) { msg := forbiddenMessage(attributes) w.Header().Set(\"Content-Type\", \"text/plain\") w.Header().Set(\"X-Content-Type-Options\", \"nosniff\") w.WriteHeader(http.StatusForbidden) fmt.Fprintf(w, \"%s: %q\", msg, reason) }"} {"_id":"doc-en-kubernetes-edb0aaf3cb540cf9d8484f7225b9e9941786e25f317157e8d33d308e9a5621b9","title":"","text":"// internalError renders a simple internal error func internalError(w http.ResponseWriter, req *http.Request, err error) { w.Header().Set(\"Content-Type\", \"text/plain\") w.Header().Set(\"X-Content-Type-Options\", \"nosniff\") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, \"Internal Server Error: %#v\", req.RequestURI) runtime.HandleError(err)"} {"_id":"doc-en-kubernetes-3137f279e745cf76d98d8a458bd4cf1438b4d98c37caf22f27605f474d24534c","title":"","text":"var ( // TODO: Deprecate gitMajor and gitMinor, use only gitVersion instead. gitMajor string = \"0\" // major version, always numeric gitMinor string = \"4.2+\" // minor version, numeric possibly followed by \"+\" gitVersion string = \"v0.4.2-dev\" // version from git, output of $(git describe) gitMinor string = \"4.3+\" // minor version, numeric possibly followed by \"+\" gitVersion string = \"v0.4.3-dev\" // version from git, output of $(git describe) gitCommit string = \"\" // sha1 from git, output of $(git rev-parse HEAD) gitTreeState string = \"not a git tree\" // state of git tree, either \"clean\" or \"dirty\" )"} {"_id":"doc-en-kubernetes-8c467caecf5200eafa8b8a2f263bf3c6b6e121e690618ce8a661a0f3e40a61a9","title":"","text":"\"//test/e2e_node/services:go_default_library\", \"//test/e2e_node/system:go_default_library\", \"//test/utils:go_default_library\", \"//vendor:github.com/coreos/go-systemd/util\", \"//vendor:github.com/davecgh/go-spew/spew\", \"//vendor:github.com/golang/glog\", \"//vendor:github.com/kardianos/osext\","} {"_id":"doc-en-kubernetes-a701d97f6b606857ad676eaf7e3e874536f0587c7e9331d78d581bc9fc9ae5b5","title":"","text":"\"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/stats\" \"k8s.io/kubernetes/test/e2e/framework\" systemdutil \"github.com/coreos/go-systemd/util\" . \"github.com/onsi/ginkgo\" . \"github.com/onsi/gomega\" \"github.com/onsi/gomega/gstruct\""} {"_id":"doc-en-kubernetes-dc70d6005f083f2a6b41c6aa4503f2ed205d90d667bd54ee81cc7aeec98c5032","title":"","text":"\"Logs\": BeNil(), \"UserDefinedMetrics\": BeEmpty(), }) systemContainers := gstruct.Elements{ \"kubelet\": sysContExpectations, \"runtime\": sysContExpectations, } // The Kubelet only manages the 'misc' system container if the host is not running systemd. if !systemdutil.IsRunningSystemd() { framework.Logf(\"Host not running systemd; expecting 'misc' system container.\") systemContainers[\"misc\"] = sysContExpectations } // Expectations for pods. podExpectations := gstruct.MatchAllFields(gstruct.Fields{ \"PodRef\": gstruct.Ignore(),"} {"_id":"doc-en-kubernetes-af3b62fd3d98e7596533a817bb4d172662e9f3b64841679a414460a8bfe15ef5","title":"","text":"}) matchExpectations := ptrMatchAllFields(gstruct.Fields{ \"Node\": gstruct.MatchAllFields(gstruct.Fields{ \"NodeName\": Equal(framework.TestContext.NodeName), \"StartTime\": recent(maxStartAge), \"SystemContainers\": gstruct.MatchElements(summaryObjectID, gstruct.IgnoreExtras, gstruct.Elements{ \"kubelet\": sysContExpectations, \"runtime\": sysContExpectations, }), \"NodeName\": Equal(framework.TestContext.NodeName), \"StartTime\": recent(maxStartAge), \"SystemContainers\": gstruct.MatchAllElements(summaryObjectID, systemContainers), \"CPU\": ptrMatchAllFields(gstruct.Fields{ \"Time\": recent(maxStatsAge), \"UsageNanoCores\": bounded(100E3, 2E9),"} {"_id":"doc-en-kubernetes-be39fa1afb4eddcfa9728edc5859e03bb99d3b7f192c13cc02308c0f713990a3","title":"","text":"// list all pods to include the pods that don't match the rs`s selector // anymore but has the stale controller ref. // TODO: Do the List and Filter in a single pass, or use an index. pods, err := rsc.podLister.Pods(rs.Namespace).List(labels.Everything()) allPods, err := rsc.podLister.Pods(rs.Namespace).List(labels.Everything()) if err != nil { return err } // Ignore inactive pods. var filteredPods []*v1.Pod for _, pod := range pods { for _, pod := range allPods { if controller.IsPodActive(pod) { filteredPods = append(filteredPods, pod) }"} {"_id":"doc-en-kubernetes-e4f92dafde6780422859680195d7f48a0a8249b36e2ae1a41c56632c6746f6f8","title":"","text":"defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) // A controller with 2 replicas and no pods in the store, 2 creates expected // A controller with 2 replicas and no active pods in the store. // Inactive pods should be ignored. 2 creates expected. labelMap := map[string]string{\"foo\": \"bar\"} rs := newReplicaSet(2, labelMap) informers.Extensions().V1beta1().ReplicaSets().Informer().GetIndexer().Add(rs) failedPod := newPod(\"failed-pod\", rs, v1.PodFailed, nil, true) deletedPod := newPod(\"deleted-pod\", rs, v1.PodRunning, nil, true) deletedPod.DeletionTimestamp = &metav1.Time{Time: time.Now()} informers.Core().V1().Pods().Informer().GetIndexer().Add(failedPod) informers.Core().V1().Pods().Informer().GetIndexer().Add(deletedPod) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl"} {"_id":"doc-en-kubernetes-39b2deef9cd74f5120775ae32b4237153a265703e1e7d8cfc1723e83848a95a2","title":"","text":"// list all pods to include the pods that don't match the rc's selector // anymore but has the stale controller ref. // TODO: Do the List and Filter in a single pass, or use an index. pods, err := rm.podLister.Pods(rc.Namespace).List(labels.Everything()) allPods, err := rm.podLister.Pods(rc.Namespace).List(labels.Everything()) if err != nil { return err } // Ignore inactive pods. var filteredPods []*v1.Pod for _, pod := range pods { for _, pod := range allPods { if controller.IsPodActive(pod) { filteredPods = append(filteredPods, pod) }"} {"_id":"doc-en-kubernetes-cb880f561db8c0b3063b48f053c87a9d27456ac8c6e320fe0cc2ab60cee27cba","title":"","text":"cm := controller.NewPodControllerRefManager(rm.podControl, rc, labels.Set(rc.Spec.Selector).AsSelectorPreValidated(), controllerKind) // NOTE: filteredPods are pointing to objects from cache - if you need to // modify them, you need to copy it first. filteredPods, err = cm.ClaimPods(pods) filteredPods, err = cm.ClaimPods(filteredPods) if err != nil { return err }"} {"_id":"doc-en-kubernetes-fa8ef9f34c29137e79fd04fbbda414424bbc054b4d1e77b0b32589f4ef5a8da1","title":"","text":"func TestSyncReplicationControllerCreates(t *testing.T) { c := clientset.NewForConfigOrDie(&restclient.Config{Host: \"\", ContentConfig: restclient.ContentConfig{GroupVersion: &api.Registry.GroupOrDie(v1.GroupName).GroupVersion}}) manager, _, rcInformer := newReplicationManagerFromClient(c, BurstReplicas) manager, podInformer, rcInformer := newReplicationManagerFromClient(c, BurstReplicas) // A controller with 2 replicas and no pods in the store, 2 creates expected // A controller with 2 replicas and no active pods in the store. // Inactive pods should be ignored. 2 creates expected. rc := newReplicationController(2) rcInformer.Informer().GetIndexer().Add(rc) failedPod := newPod(\"failed-pod\", rc, v1.PodFailed, nil, true) deletedPod := newPod(\"deleted-pod\", rc, v1.PodRunning, nil, true) deletedPod.DeletionTimestamp = &metav1.Time{Time: time.Now()} podInformer.Informer().GetIndexer().Add(failedPod) podInformer.Informer().GetIndexer().Add(deletedPod) fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl"} {"_id":"doc-en-kubernetes-b9abb94346c1f8ec98293003fa2f7988c0b5ed930955f96cec9c419816c4e6a0","title":"","text":"func (adc *attachDetachController) nodeAdd(obj interface{}) { node, ok := obj.(*v1.Node) // TODO: investigate if nodeName is empty then if we can return // kubernetes/kubernetes/issues/37777 if node == nil || !ok { return } nodeName := types.NodeName(node.Name) adc.nodeUpdate(nil, obj) // kubernetes/kubernetes/issues/37586 // This is to workaround the case when a node add causes to wipe out // the attached volumes field. This function ensures that we sync with // the actual status. adc.actualStateOfWorld.SetNodeStatusUpdateNeeded(nodeName) } func (adc *attachDetachController) nodeUpdate(oldObj, newObj interface{}) { node, ok := newObj.(*v1.Node) // TODO: investigate if nodeName is empty then if we can return if node == nil || !ok { return }"} {"_id":"doc-en-kubernetes-ccaa0f58b3757d5ceadc267991c0b6fd9d44ff50005daba86955d85c8faed2ef","title":"","text":"// detach controller. Add it to desired state of world. adc.desiredStateOfWorld.AddNode(nodeName) } adc.processVolumesInUse(nodeName, node.Status.VolumesInUse) } func (adc *attachDetachController) nodeUpdate(oldObj, newObj interface{}) { // The flow for update is the same as add. adc.nodeAdd(newObj) } func (adc *attachDetachController) nodeDelete(obj interface{}) { node, ok := obj.(*v1.Node) if node == nil || !ok {"} {"_id":"doc-en-kubernetes-2b2ae4fa92d0733a52363f5d50aee2b5450eb4627fc0e12ccc8bd645f0bf2bce","title":"","text":"// since volumes should be removed from this list as soon a detach operation // is considered, before the detach operation is triggered). GetVolumesToReportAttached() map[types.NodeName][]v1.AttachedVolume // GetNodesToUpdateStatusFor returns the map of nodeNames to nodeToUpdateStatusFor GetNodesToUpdateStatusFor() map[types.NodeName]nodeToUpdateStatusFor } // AttachedVolume represents a volume that is attached to a node."} {"_id":"doc-en-kubernetes-847ad16935b819db33de0cb99a951593056e9f47abf914eaafa72a78b2124f47","title":"","text":"\"Failed to set statusUpdateNeeded to needed %t because nodeName=%q does not exist\", needed, nodeName) return } nodeToUpdate.statusUpdateNeeded = needed"} {"_id":"doc-en-kubernetes-99137c8dde2269bd2338e5e69b987d3be339f12d28300489cf5daa651099b2f4","title":"","text":"return volumesToReportAttached } func (asw *actualStateOfWorld) GetNodesToUpdateStatusFor() map[types.NodeName]nodeToUpdateStatusFor { return asw.nodesToUpdateStatusFor } func getAttachedVolume( attachedVolume *attachedVolume, nodeAttachedTo *nodeAttachedTo) AttachedVolume {"} {"_id":"doc-en-kubernetes-94b79e932178aed43ad947576b11fd689f3c0d9064444ed5adc7b436319e5c65","title":"","text":"verifyAttachedVolume(t, attachedVolumes, generatedVolumeName2, string(volumeName), node2Name, devicePath2, true /* expectedMountedByNode */, false /* expectNonZeroDetachRequestedTime */) } // Test_SetNodeStatusUpdateNeededError expects the map nodesToUpdateStatusFor // to be empty if the SetNodeStatusUpdateNeeded is called on a node that // does not exist in the actual state of the world func Test_SetNodeStatusUpdateNeededError(t *testing.T) { // Arrange volumePluginMgr, _ := volumetesting.GetTestVolumePluginMgr(t) asw := NewActualStateOfWorld(volumePluginMgr) nodeName := types.NodeName(\"node-1\") // Act asw.SetNodeStatusUpdateNeeded(nodeName) // Assert nodesToUpdateStatusFor := asw.GetNodesToUpdateStatusFor() if len(nodesToUpdateStatusFor) != 0 { t.Fatalf(\"nodesToUpdateStatusFor should be empty as nodeName does not exist\") } } func verifyAttachedVolume( t *testing.T, attachedVolumes []AttachedVolume,"} {"_id":"doc-en-kubernetes-70eaf6b6af82c2ab337177470085df162cb96bc60179a987c6029599033a704a","title":"","text":"} func (nsu *nodeStatusUpdater) UpdateNodeStatuses() error { // TODO: investigate right behavior if nodeName is empty // kubernetes/kubernetes/issues/37777 nodesToUpdate := nsu.actualStateOfWorld.GetVolumesToReportAttached() for nodeName, attachedVolumes := range nodesToUpdate { nodeObj, exists, err := nsu.nodeInformer.GetStore().GetByKey(string(nodeName))"} {"_id":"doc-en-kubernetes-b189bd3e3ce02b057b09034bb4a2cae952bea2cec0923fc1143afab4381cef8c","title":"","text":"e2e_storage_test_environment: '$(echo \"$E2E_STORAGE_TEST_ENVIRONMENT\" | sed -e \"s/'/''/g\")' kube_uid: '$(echo \"${KUBE_UID}\" | sed -e \"s/'/''/g\")' initial_etcd_cluster: '$(echo \"${INITIAL_ETCD_CLUSTER:-}\" | sed -e \"s/'/''/g\")' etcd_quorum_read: '$(echo \"${ETCD_QUORUM_READ:-}\" | sed -e \"s/'/''/g\")' hostname: $(hostname -s) enable_default_storage_class: '$(echo \"$ENABLE_DEFAULT_STORAGE_CLASS\" | sed -e \"s/'/''/g\")'"} {"_id":"doc-en-kubernetes-42b6ffd7a2933a5e6acd72e15c904deb0f3b59d62398ee993e0d261cc65e5c08","title":"","text":"etcd_over_ssl: 'false' EOF fi if [ -n \"${ETCD_QUORUM_READ:-}\" ]; then cat <>/srv/salt-overlay/pillar/cluster-params.sls etcd_quorum_read: '$(echo \"${ETCD_QUORUM_READ}\" | sed -e \"s/'/''/g\")' EOF fi # Configuration changes for test clusters if [ -n \"${APISERVER_TEST_ARGS:-}\" ]; then cat <>/srv/salt-overlay/pillar/cluster-params.sls"} {"_id":"doc-en-kubernetes-589012fea78f0b398630161f378a902755d2d2a73f388c182a64c3faaa0b70ed","title":"","text":"e2e_storage_test_environment: '$(echo \"$E2E_STORAGE_TEST_ENVIRONMENT\" | sed -e \"s/'/''/g\")' kube_uid: '$(echo \"${KUBE_UID}\" | sed -e \"s/'/''/g\")' initial_etcd_cluster: '$(echo \"${INITIAL_ETCD_CLUSTER:-}\" | sed -e \"s/'/''/g\")' etcd_quorum_read: '$(echo \"${ETCD_QUORUM_READ:-}\" | sed -e \"s/'/''/g\")' hostname: $(hostname -s) EOF"} {"_id":"doc-en-kubernetes-58991cedb19db09ceb87225a6efc2bf147e096b2f10712f3f87bb7d31b5407cb","title":"","text":"tags = [\"automanaged\"], deps = [ \"//pkg/api:go_default_library\", \"//pkg/api/v1:go_default_library\", \"//pkg/apis/componentconfig:go_default_library\", \"//pkg/apis/componentconfig/v1alpha1:go_default_library\", \"//pkg/kubelet/qos:go_default_library\","} {"_id":"doc-en-kubernetes-9ad2022dde279dc09c2b30b1322c9e4084144ba60b33dea634e54f2b2805d0fa","title":"","text":"\"time\" \"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/v1\" \"k8s.io/kubernetes/pkg/apis/componentconfig\" \"k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1\" \"k8s.io/kubernetes/pkg/kubelet/qos\""} {"_id":"doc-en-kubernetes-dc99ffe4e40ed6eed48a4a4a9378d239a1581d4dd87a2a21f9f4c9f33ffb83b5","title":"","text":"KubeAPIBurst int32 ConfigSyncPeriod time.Duration CleanupAndExit bool NodeRef *api.ObjectReference NodeRef *v1.ObjectReference Master string Kubeconfig string }"} {"_id":"doc-en-kubernetes-f253d2f57048ca449243526e55ff5fb9b3893b71ca1735c8503e4102df78cf0b","title":"","text":"endpointsConfig.Channel(\"api\"), ) config.NodeRef = &api.ObjectReference{ config.NodeRef = &v1.ObjectReference{ Kind: \"Node\", Name: hostname, UID: types.UID(hostname),"} {"_id":"doc-en-kubernetes-409094fe455c2453f22817a63ec2178ed9c9bab851dd082682b4930b4d7eb991","title":"","text":"\"//cmd/kube-proxy/app/options:go_default_library\", \"//cmd/kubelet/app:go_default_library\", \"//pkg/api:go_default_library\", \"//pkg/api/v1:go_default_library\", \"//pkg/apis/componentconfig:go_default_library\", \"//pkg/apis/componentconfig/v1alpha1:go_default_library\", \"//pkg/client/clientset_generated/clientset:go_default_library\","} {"_id":"doc-en-kubernetes-cba3f17c8c44e16cbe9932373931090067ddddc0ab0a1a814d688bdab0e67e0b","title":"","text":"proxyapp \"k8s.io/kubernetes/cmd/kube-proxy/app\" \"k8s.io/kubernetes/cmd/kube-proxy/app/options\" \"k8s.io/kubernetes/pkg/api\" \"k8s.io/kubernetes/pkg/api/v1\" clientset \"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset\" \"k8s.io/kubernetes/pkg/client/record\" proxyconfig \"k8s.io/kubernetes/pkg/proxy/config\""} {"_id":"doc-en-kubernetes-4ebc1db99847d665e90a2787b305fcde9e822d11e5f3096666c5b99a98a405de","title":"","text":"config := options.NewProxyConfig() config.OOMScoreAdj = util.Int32Ptr(0) config.ResourceContainer = \"\" config.NodeRef = &api.ObjectReference{ config.NodeRef = &v1.ObjectReference{ Kind: \"Node\", Name: nodeName, UID: types.UID(nodeName),"} {"_id":"doc-en-kubernetes-2cb7b213f491d2124dfe605a0573a127e5eefa6555c15cc1eed47cb592ea7a1c","title":"","text":"docs/man/man1/kubectl-delete.1 docs/man/man1/kubectl-describe.1 docs/man/man1/kubectl-drain.1 docs/man/man1/kubectl-edit-configmap.1 docs/man/man1/kubectl-edit.1 docs/man/man1/kubectl-exec.1 docs/man/man1/kubectl-explain.1"} {"_id":"doc-en-kubernetes-49046feba193e27db23d9b7b9a681cbd899f3c63d9449dc4d5049c59d15a115b","title":"","text":"docs/user-guide/kubectl/kubectl_describe.md docs/user-guide/kubectl/kubectl_drain.md docs/user-guide/kubectl/kubectl_edit.md docs/user-guide/kubectl/kubectl_edit_configmap.md docs/user-guide/kubectl/kubectl_exec.md docs/user-guide/kubectl/kubectl_explain.md docs/user-guide/kubectl/kubectl_expose.md"} {"_id":"doc-en-kubernetes-c5b5bd6ba02859f778c0059ace5c6e826d7641a62e83cf1638d26bdc85afafe3","title":"","text":" This file is autogenerated, but we've stopped checking such files into the repository to reduce the need for rebases. Please run hack/generate-docs.sh to populate this file. "} {"_id":"doc-en-kubernetes-174d61cf5828e74b1159622b35d464c05fb882be4b1350b5f9500fe0bd6877d7","title":"","text":" This file is autogenerated, but we've stopped checking such files into the repository to reduce the need for rebases. Please run hack/generate-docs.sh to populate this file. [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_edit_configmap.md?pixel)]() "} {"_id":"doc-en-kubernetes-54e2e9be0fe36878c64c8ac989095887075506a28302915844fd6722a00bb138","title":"","text":"concurrent-serviceaccount-token-syncs concurrent-service-syncs config-map config-map-data config-map-namespace config-sync-period configure-cloud-routes"} {"_id":"doc-en-kubernetes-fa0a5eb725ecaf710001c598561154179b69cd98dba6f4bf8c56e3f6761e5d64","title":"","text":"\"describe.go\", \"drain.go\", \"edit.go\", \"edit_configmap.go\", \"exec.go\", \"explain.go\", \"expose.go\","} {"_id":"doc-en-kubernetes-056d98202e728b37ece4c6567383d1140bbbbe4c90dfd1aa2ba75cbbcf10913a","title":"","text":"Long: editLong, Example: fmt.Sprintf(editExample), Run: func(cmd *cobra.Command, args []string) { args = append([]string{\"configmap\"}, args...) err := RunEdit(f, out, errOut, cmd, args, options) cmdutil.CheckErr(err) }, ValidArgs: validArgs, ArgAliases: argAliases, } addEditFlags(cmd, options) cmd.AddCommand(NewCmdEditConfigMap(f, out, errOut)) return cmd } func addEditFlags(cmd *cobra.Command, options *resource.FilenameOptions) { usage := \"to use to edit the resource\" cmdutil.AddFilenameOptionFlags(cmd, options, usage) cmdutil.AddValidateFlags(cmd)"} {"_id":"doc-en-kubernetes-bc544f231b71f26863b8bd150b6292ea1a6a70cbf6bc961e84b879421f70f569","title":"","text":"cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddRecordFlag(cmd) cmdutil.AddInclude3rdPartyFlags(cmd) return cmd } func RunEdit(f cmdutil.Factory, out, errOut io.Writer, cmd *cobra.Command, args []string, options *resource.FilenameOptions) error {"} {"_id":"doc-en-kubernetes-b98ad6cc8053ffd0041e849411ca7b6a2ce878ff2a5ddf7417e8f2b44c138927","title":"","text":" /* Copyright 2016 The Kubernetes Authors. 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. */ package cmd import ( \"bytes\" \"fmt\" \"io\" \"os\" \"github.com/spf13/cobra\" \"k8s.io/apimachinery/pkg/apis/meta/v1\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" \"k8s.io/kubernetes/pkg/kubectl/cmd/util/editor\" \"k8s.io/kubernetes/pkg/kubectl/resource\" ) // NewCmdEditConfigMap is a macro command to edit config maps func NewCmdEditConfigMap(f cmdutil.Factory, cmdOut, errOut io.Writer) *cobra.Command { options := &resource.FilenameOptions{} cmd := &cobra.Command{ Use: \"configmap\", Aliases: []string{\"cm\"}, Short: \"Edit a config map object.\", Long: \"Edit and update a config map object\", Run: func(cmd *cobra.Command, args []string) { RunEditConfigMap(cmd, f, args, cmdOut, errOut, options) }, } addEditFlags(cmd, options) cmd.Flags().String(\"config-map-data\", \"\", \"If non-empty, specify the name of a data slot in a config map to edit.\") return cmd } // RunEditConfigMap runs the edit command for config maps. It either edits the complete map // or it edits individual files inside the config map. func RunEditConfigMap(cmd *cobra.Command, f cmdutil.Factory, args []string, cmdOut, errOut io.Writer, options *resource.FilenameOptions) error { dataFile := cmdutil.GetFlagString(cmd, \"config-map-data\") if len(dataFile) == 0 { // We need to add the resource type back on to the front args = append([]string{\"configmap\"}, args...) return RunEdit(f, cmdOut, errOut, cmd, args, options) } cmdNamespace, _, err := f.DefaultNamespace() if err != nil { return err } cs, err := f.ClientSet() if err != nil { return err } configMap, err := cs.Core().ConfigMaps(cmdNamespace).Get(args[0], v1.GetOptions{}) if err != nil { return err } value, found := configMap.Data[dataFile] if !found { keys := []string{} for key := range configMap.Data { keys = append(keys, key) } return fmt.Errorf(\"No such data file (%s), filenames are: %vn\", dataFile, keys) } edit := editor.NewDefaultEditor(os.Environ()) data, file, err := edit.LaunchTempFile(fmt.Sprintf(\"%s-edit-\", dataFile), \"\", bytes.NewBuffer([]byte(value))) defer func() { os.Remove(file) }() if err != nil { return err } configMap.Data[dataFile] = string(data) if _, err := cs.Core().ConfigMaps(cmdNamespace).Update(configMap); err != nil { return err } return nil } "} {"_id":"doc-en-kubernetes-f33023912292b04305983620be7369cab51c4b87bb4067c5b92998f6523d7aa2","title":"","text":"return nil, err } if mount.SubPath != \"\" { fileinfo, err := os.Lstat(hostPath) if err != nil { return nil, err } perm := fileinfo.Mode() hostPath = filepath.Join(hostPath, mount.SubPath) // Create the sub path now because if it's auto-created later when referenced, it may have an // incorrect ownership and mode. For example, the sub path directory must have at least g+rwx // when the pod specifies an fsGroup, and if the directory is not created here, Docker will // later auto-create it with the incorrect mode 0750 if err := os.MkdirAll(hostPath, perm); err != nil { glog.Errorf(\"failed to mkdir:%s\", hostPath) return nil, err } // chmod the sub path because umask may have prevented us from making the sub path with the same // permissions as the mounter path if err := os.Chmod(hostPath, perm); err != nil { return nil, err } } // Docker Volume Mounts fail on Windows if it is not of the form C:/"} {"_id":"doc-en-kubernetes-4ebf351e64b0b3ca7a14c86d047901e0c5f36de581c636c9b69fd9dba83943ab","title":"","text":"// running on that node. func (dsc *DaemonSetsController) nodeShouldRunDaemonPod(node *v1.Node, ds *extensions.DaemonSet) (wantToRun, shouldSchedule, shouldContinueRunning bool, err error) { newPod := NewPod(ds, node.Name) critical := utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalCriticalPodAnnotation) && kubelettypes.IsCriticalPod(newPod) // Because these bools require an && of all their required conditions, we start // with all bools set to true and set a bool to false if a condition is not met."} {"_id":"doc-en-kubernetes-09f758328ed7b667671aceefadb24410685224790b81a79eaaaa6068e779fe91","title":"","text":"return false, false, false, nil } // TODO: Move it to the predicates for _, c := range node.Status.Conditions { if critical { break } // TODO: There are other node status that the DaemonSet should ideally respect too, // e.g. MemoryPressure, and DiskPressure if c.Type == v1.NodeOutOfDisk && c.Status == v1.ConditionTrue { // the kubelet will evict this pod if it needs to. Let kubelet // decide whether to continue running this pod so leave shouldContinueRunning // set to true shouldSchedule = false } } reasons, nodeInfo, err := dsc.simulate(newPod, node, ds) if err != nil { glog.Warningf(\"DaemonSet Predicates failed on node %s for ds '%s/%s' due to unexpected error: %v\", node.Name, ds.ObjectMeta.Namespace, ds.ObjectMeta.Name, err)"} {"_id":"doc-en-kubernetes-d24fa6230d40345d5b808b585a6ba122d35f47a1bde5a08d9720f1b030ca5e70","title":"","text":"} var insufficientResourceErr error for _, r := range reasons { glog.V(4).Infof(\"DaemonSet Predicates failed on node %s for ds '%s/%s' for reason: %v\", node.Name, ds.ObjectMeta.Namespace, ds.ObjectMeta.Name, r.GetReason()) switch reason := r.(type) {"} {"_id":"doc-en-kubernetes-89743467ef34880f3fb325aa2ec5b556d78e7cc906ab353740d8ab0f56779086","title":"","text":"var emitEvent bool // we try to partition predicates into two partitions here: intentional on the part of the operator and not. switch reason { case predicates.ErrNodeOutOfDisk: // the kubelet will evict this pod if it needs to. Let kubelet // decide whether to continue running this pod so leave shouldContinueRunning // set to true shouldSchedule = false // intentional case predicates.ErrNodeSelectorNotMatch,"} {"_id":"doc-en-kubernetes-61f1c99a25af1aa1c95096a41510161b0b3387abc0680a7ac00ea99ff3f5418d","title":"","text":"if !fit { predicateFails = append(predicateFails, reasons...) } if critical { // If the pod is marked as critical and support for critical pod annotations is enabled, // check predicates for critical pods only. fit, reasons, err = predicates.EssentialPredicates(pod, nil, nodeInfo) } else { fit, reasons, err = predicates.GeneralPredicates(pod, nil, nodeInfo) ncFit, ncReasons := NodeConditionPredicates(nodeInfo) fit = ncFit && fit reasons = append(reasons, ncReasons...) } if err != nil { return false, predicateFails, err"} {"_id":"doc-en-kubernetes-f22eccf459a3337cef3ea0b678da2cc5ce92b9ebc37da25414cdeea0dfaba6de","title":"","text":"return len(predicateFails) == 0, predicateFails, nil } func NodeConditionPredicates(nodeInfo *schedulercache.NodeInfo) (bool, []algorithm.PredicateFailureReason) { reasons := []algorithm.PredicateFailureReason{} for _, c := range nodeInfo.Node().Status.Conditions { // TODO: There are other node status that the DaemonSet should ideally respect too, // e.g. MemoryPressure, and DiskPressure if c.Type == v1.NodeOutOfDisk && c.Status == v1.ConditionTrue { reasons = append(reasons, predicates.ErrNodeSelectorNotMatch) break } } return len(reasons) == 0, reasons } // newControllerRef creates a ControllerRef pointing to the given DaemonSet. func newControllerRef(ds *extensions.DaemonSet) *metav1.OwnerReference { blockOwnerDeletion := true"} {"_id":"doc-en-kubernetes-c7ac6f1fc0823b2bd1fda94cdc8f642aa5607b5339f3bf12edc5474808d37820","title":"","text":"ErrMaxVolumeCountExceeded = newPredicateFailureError(\"MaxVolumeCount\") ErrNodeUnderMemoryPressure = newPredicateFailureError(\"NodeUnderMemoryPressure\") ErrNodeUnderDiskPressure = newPredicateFailureError(\"NodeUnderDiskPressure\") ErrNodeOutOfDisk = newPredicateFailureError(\"NodeOutOfDisk\") ErrVolumeNodeConflict = newPredicateFailureError(\"NoVolumeNodeConflict\") // ErrFakePredicate is used for test only. The fake predicates returning false also returns error // as ErrFakePredicate."} {"_id":"doc-en-kubernetes-1cbf2f61ded15cb87017f4522c0267f0d5dd95c9b997747a868eeca70ba7b336","title":"","text":"// TestListContainers creates several containers and then list them to check // whether the correct metadatas, states, and labels are returned. func TestListContainers(t *testing.T) { ds, _, _ := newTestDockerService() ds, _, fakeClock := newTestDockerService() podName, namespace := \"foo\", \"bar\" containerName, image := \"sidecar\", \"logger\""} {"_id":"doc-en-kubernetes-fc88a201557e3c54653e6237caa09e18cef2eef5488d14d559429ef415e3af20","title":"","text":"expected := []*runtimeapi.Container{} state := runtimeapi.ContainerState_CONTAINER_RUNNING var createdAt int64 = 0 var createdAt int64 = fakeClock.Now().UnixNano() for i := range configs { // We don't care about the sandbox id; pass a bogus one. sandboxID := fmt.Sprintf(\"sandboxid%d\", i)"} {"_id":"doc-en-kubernetes-6f9993b08a0df507a84dd01d121c5b572f1109e7f73de1d3392a2acc81549b8a","title":"","text":"// TestListSandboxes creates several sandboxes and then list them to check // whether the correct metadatas, states, and labels are returned. func TestListSandboxes(t *testing.T) { ds, _, _ := newTestDockerService() ds, _, fakeClock := newTestDockerService() name, namespace := \"foo\", \"bar\" configs := []*runtimeapi.PodSandboxConfig{} for i := 0; i < 3; i++ {"} {"_id":"doc-en-kubernetes-27bb69d232af611415ae4d80d35a08dc4775d13a30b568df76aa6fc0998ce88c","title":"","text":"expected := []*runtimeapi.PodSandbox{} state := runtimeapi.PodSandboxState_SANDBOX_READY var createdAt int64 = 0 var createdAt int64 = fakeClock.Now().UnixNano() for i := range configs { id, err := ds.RunPodSandbox(configs[i]) assert.NoError(t, err)"} {"_id":"doc-en-kubernetes-20050560e47e22fb222c14808a8b721eb98d2b156717a0536c9718f807fbbf0e","title":"","text":"// (kubecontainer) types. const ( statusRunningPrefix = \"Up\" statusCreatedPrefix = \"Created\" statusExitedPrefix = \"Exited\" )"} {"_id":"doc-en-kubernetes-fe30087171f80224e67a69e48c3b4e1cd22174b85a72236b032c2d475fc0bc03","title":"","text":"name := \"/\" + c.Name id := GetFakeContainerID(name) f.appendContainerTrace(\"Created\", id) timestamp := f.Clock.Now() // The newest container should be in front, because we assume so in GetPodStatus() f.RunningContainerList = append([]dockertypes.Container{ {ID: id, Names: []string{name}, Image: c.Config.Image, Labels: c.Config.Labels}, {ID: id, Names: []string{name}, Image: c.Config.Image, Created: timestamp.Unix(), State: statusCreatedPrefix, Labels: c.Config.Labels}, }, f.RunningContainerList...) f.ContainerMap[id] = convertFakeContainer(&FakeContainer{ ID: id, Name: name, Config: c.Config, HostConfig: c.HostConfig, CreatedAt: f.Clock.Now()}) ID: id, Name: name, Config: c.Config, HostConfig: c.HostConfig, CreatedAt: timestamp}) f.normalSleep(100, 25, 25)"} {"_id":"doc-en-kubernetes-cfa5e67938cdee55ae560c4064578db4a0a735bf256d439393c8d9b96232f236","title":"","text":"} f.appendContainerTrace(\"Started\", id) container, ok := f.ContainerMap[id] timestamp := f.Clock.Now() if !ok { container = convertFakeContainer(&FakeContainer{ID: id, Name: id}) container = convertFakeContainer(&FakeContainer{ID: id, Name: id, CreatedAt: timestamp}) } container.State.Running = true container.State.Pid = os.Getpid() container.State.StartedAt = dockerTimestampToString(f.Clock.Now()) container.State.StartedAt = dockerTimestampToString(timestamp) container.NetworkSettings.IPAddress = \"2.3.4.5\" f.ContainerMap[id] = container f.updateContainerStatus(id, statusRunningPrefix)"} {"_id":"doc-en-kubernetes-d1f0053be5c30f52ae674bb4a625105b3a691fe5adea348ea84d0ad12a4f11f8","title":"","text":"// print the current object if !isWatchOnly { var objsToPrint []runtime.Object writer := printers.GetNewTabWriter(out) if isList { objsToPrint, _ = meta.ExtractList(obj) } else { objsToPrint = append(objsToPrint, obj) } for _, objToPrint := range objsToPrint { if err := printer.PrintObj(objToPrint, out); err != nil { if err := printer.PrintObj(objToPrint, writer); err != nil { return fmt.Errorf(\"unable to output the provided object: %v\", err) } } writer.Flush() } // print watched changes"} {"_id":"doc-en-kubernetes-4b14e6739775fcfbb0e2e8c8806b3afe8ebdf7a70462ec58c56b0cca4d958a7b","title":"","text":"\"//vendor:github.com/blang/semver\", \"//vendor:github.com/docker/engine-api/types\", \"//vendor:github.com/docker/engine-api/types/container\", \"//vendor:github.com/docker/go-connections/nat\", \"//vendor:github.com/golang/mock/gomock\", \"//vendor:github.com/stretchr/testify/assert\", \"//vendor:github.com/stretchr/testify/require\","} {"_id":"doc-en-kubernetes-d20fc7762007cafd5bd354be0ca70749a29e46dba9e073022ddb319ad50fb507","title":"","text":"// Some of this port stuff is under-documented voodoo. // See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api var protocol string switch strings.ToUpper(string(port.Protocol)) { case \"UDP\": switch port.Protocol { case runtimeapi.Protocol_UDP: protocol = \"/udp\" case \"TCP\": case runtimeapi.Protocol_TCP: protocol = \"/tcp\" default: glog.Warningf(\"Unknown protocol %q: defaulting to TCP\", port.Protocol)"} {"_id":"doc-en-kubernetes-628099cd698ba35affff6495591d9bdfeb5abdf14eb4534b7a5963fb1ca8f035","title":"","text":"\"github.com/blang/semver\" dockertypes \"github.com/docker/engine-api/types\" dockernat \"github.com/docker/go-connections/nat\" \"github.com/stretchr/testify/assert\" \"github.com/stretchr/testify/require\""} {"_id":"doc-en-kubernetes-c1f4a7f951a623e54f647b7496990430afd418229f71b85db2b5641149f01853","title":"","text":"assert.Equal(t, test.err, err != nil) } } func TestMakePortsAndBindings(t *testing.T) { for desc, test := range map[string]struct { pm []*runtimeapi.PortMapping exposedPorts map[dockernat.Port]struct{} portmappings map[dockernat.Port][]dockernat.PortBinding }{ \"no port mapping\": { pm: nil, exposedPorts: map[dockernat.Port]struct{}{}, portmappings: map[dockernat.Port][]dockernat.PortBinding{}, }, \"tcp port mapping\": { pm: []*runtimeapi.PortMapping{ { Protocol: runtimeapi.Protocol_TCP, ContainerPort: 80, HostPort: 80, }, }, exposedPorts: map[dockernat.Port]struct{}{ \"80/tcp\": {}, }, portmappings: map[dockernat.Port][]dockernat.PortBinding{ \"80/tcp\": { { HostPort: \"80\", }, }, }, }, \"udp port mapping\": { pm: []*runtimeapi.PortMapping{ { Protocol: runtimeapi.Protocol_UDP, ContainerPort: 80, HostPort: 80, }, }, exposedPorts: map[dockernat.Port]struct{}{ \"80/udp\": {}, }, portmappings: map[dockernat.Port][]dockernat.PortBinding{ \"80/udp\": { { HostPort: \"80\", }, }, }, }, \"multipe port mappings\": { pm: []*runtimeapi.PortMapping{ { Protocol: runtimeapi.Protocol_TCP, ContainerPort: 80, HostPort: 80, }, { Protocol: runtimeapi.Protocol_TCP, ContainerPort: 80, HostPort: 81, }, }, exposedPorts: map[dockernat.Port]struct{}{ \"80/tcp\": {}, }, portmappings: map[dockernat.Port][]dockernat.PortBinding{ \"80/tcp\": { { HostPort: \"80\", }, { HostPort: \"81\", }, }, }, }, } { t.Logf(\"TestCase: %s\", desc) actualExposedPorts, actualPortMappings := makePortsAndBindings(test.pm) assert.Equal(t, test.exposedPorts, actualExposedPorts) assert.Equal(t, test.portmappings, actualPortMappings) } } "} {"_id":"doc-en-kubernetes-f1f3f340348b0202d529c1f0f270fd1a6512c616cfd358db9579c21b8e783624","title":"","text":"return c, informers } func (f *fixture) runExpectError(deploymentName string) { f.run_(deploymentName, true) func (f *fixture) runExpectError(deploymentName string, startInformers bool) { f.run_(deploymentName, startInformers, true) } func (f *fixture) run(deploymentName string) { f.run_(deploymentName, false) f.run_(deploymentName, true, false) } func (f *fixture) run_(deploymentName string, expectError bool) { func (f *fixture) run_(deploymentName string, startInformers bool, expectError bool) { c, informers := f.newController() stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) if startInformers { stopCh := make(chan struct{}) defer close(stopCh) informers.Start(stopCh) } err := c.syncDeployment(deploymentName) if !expectError && err != nil {"} {"_id":"doc-en-kubernetes-d3def5c7c466ea6e6298f0997218662d7000a5aaba8d7a66e0bfe0ddbd03fa4d","title":"","text":"// Expect to only recheck DeletionTimestamp. f.expectGetDeploymentAction(d) // Sync should fail and requeue to let cache catch up. f.runExpectError(getKey(d, t)) // Don't start informers, since we don't want cache to catch up for this test. f.runExpectError(getKey(d, t), false) } // issue: https://github.com/kubernetes/kubernetes/issues/23218"} {"_id":"doc-en-kubernetes-02fa85fffb97ea2289654e4206db07d34fb2ff92bd7ee8fdbeb206a5148b7b0d","title":"","text":"// updateIndices modifies the objects location in the managed indexes, if this is an update, you must provide an oldObj // updateIndices must be called from a function that already has a lock on the cache func (c *threadSafeMap) updateIndices(oldObj interface{}, newObj interface{}, key string) error { func (c *threadSafeMap) updateIndices(oldObj interface{}, newObj interface{}, key string) { // if we got an old object, we need to remove it before we add it again if oldObj != nil { c.deleteFromIndices(oldObj, key)"} {"_id":"doc-en-kubernetes-de140ac1f6dc55f59ea8077036b21534eb0b93760b2c94ab419e7d13b3921588","title":"","text":"for name, indexFunc := range c.indexers { indexValues, err := indexFunc(newObj) if err != nil { return err panic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err)) } index := c.indices[name] if index == nil {"} {"_id":"doc-en-kubernetes-770b6c20804d40f32f1db3c70d266457384ba3cc1cac2cd839d4553c729d60a1","title":"","text":"set.Insert(key) } } return nil } // deleteFromIndices removes the object from each of the managed indexes // it is intended to be called from a function that already has a lock on the cache func (c *threadSafeMap) deleteFromIndices(obj interface{}, key string) error { func (c *threadSafeMap) deleteFromIndices(obj interface{}, key string) { for name, indexFunc := range c.indexers { indexValues, err := indexFunc(obj) if err != nil { return err panic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err)) } index := c.indices[name]"} {"_id":"doc-en-kubernetes-e883d7e46f9843e98a43ec756a777ff84ca204cd0df85817b053c55761997cdc","title":"","text":"} } } return nil } func (c *threadSafeMap) Resync() error {"} {"_id":"doc-en-kubernetes-532e4ed69ece69dbdeed5d87c6364aed65cc51642b591aee102b61d0ea40ca20","title":"","text":"kube::test::version::json_object_to_file() { flags=$1 file=$2 kubectl version $flags --output json | sed -e s/'\"'/''/g -e s/'}'/''/g -e s/'{'/''/g -e s/'clientVersion:'/'clientVersion:,'/ -e s/'serverVersion:'/'serverVersion:,'/ | tr , 'n' > \"${file}\" kubectl version $flags --output json | sed -e s/' '/''/g -e s/'\"'/''/g -e s/'}'/''/g -e s/'{'/''/g -e s/'clientVersion:'/'clientVersion:,'/ -e s/'serverVersion:'/'serverVersion:,'/ | tr , 'n' > \"${file}\" } kube::test::version::json_client_server_object_to_file() {"} {"_id":"doc-en-kubernetes-5f26e29596e68aeeed945e94e7400a2e26d24060f4d0f2bc1d58e99b5def0eb6","title":"","text":"} cmd.Flags().BoolP(\"client\", \"c\", false, \"Client version only (no server required).\") cmd.Flags().BoolP(\"short\", \"\", false, \"Print just the version number.\") cmd.Flags().String(\"output\", \"\", \"one of 'yaml' or 'json'\") cmd.Flags().StringP(\"output\", \"o\", \"\", \"One of 'yaml' or 'json'.\") cmd.Flags().MarkShorthandDeprecated(\"client\", \"please use --client instead.\") return cmd }"} {"_id":"doc-en-kubernetes-51477ab25d21a0cdcf8be2d98d442a1ad481259ee0be8cc36943ac5be34b596f","title":"","text":"} fmt.Fprintln(out, string(marshalled)) case \"json\": marshalled, err := json.Marshal(&versionInfo) marshalled, err := json.MarshalIndent(&versionInfo, \"\", \" \") if err != nil { return err }"} {"_id":"doc-en-kubernetes-804a219c1997de0611cf2b0c8e1682c21f388e42f38ec0e1970a2a6e66135c0c","title":"","text":"{\"name\" : \"ServiceSpreadingPriority\", \"weight\" : 1}, {\"name\" : \"EqualPriority\", \"weight\" : 1} ], \"extenders\":[ \"extenders\" : [ { \"urlPrefix\": \"http://127.0.0.1:12346/scheduler\", \"apiVersion\": \"v1beta1\","} {"_id":"doc-en-kubernetes-3233c751ea2287fbdb5ff8e6f3e80c3d9f3435eb9a9a927a5d5fb9424f685f09","title":"","text":"\"enableHttps\": false, \"nodeCacheCapable\": false } ] ], \"hardPodAffinitySymmetricWeight\" : 10 }"} {"_id":"doc-en-kubernetes-2f1dfce6af80261f312f4da284e389cdd710fc4e958bcd17e7b86c481d7b3b40","title":"","text":"{\"name\" : \"BalancedResourceAllocation\", \"weight\" : 1}, {\"name\" : \"ServiceSpreadingPriority\", \"weight\" : 1}, {\"name\" : \"EqualPriority\", \"weight\" : 1} ] ], \"hardPodAffinitySymmetricWeight\" : 10 }"} {"_id":"doc-en-kubernetes-62e2af84c42a2d1da5934d7473397d3695d64ca85144cbb525ac93b02a109716","title":"","text":"fs.IntVar(&s.HardPodAffinitySymmetricWeight, \"hard-pod-affinity-symmetric-weight\", api.DefaultHardPodAffinitySymmetricWeight, \"RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule corresponding \"+ \"to every RequiredDuringScheduling affinity rule. --hard-pod-affinity-symmetric-weight represents the weight of implicit PreferredDuringScheduling affinity rule.\") fs.MarkDeprecated(\"hard-pod-affinity-symmetric-weight\", \"This option was moved to the policy configuration file\") fs.StringVar(&s.FailureDomains, \"failure-domains\", api.DefaultFailureDomains, \"Indicate the \"all topologies\" set for an empty topologyKey when it's used for PreferredDuringScheduling pod anti-affinity.\") fs.MarkDeprecated(\"failure-domains\", \"Doesn't have any effect. Will be removed in future version.\") leaderelection.BindFlags(&s.LeaderElection, fs)"} {"_id":"doc-en-kubernetes-6079718c006e3aab69e724b8c3e64944e4284cfa46309e78662154d4878da361","title":"","text":"Priorities []PriorityPolicy // Holds the information to communicate with the extender(s) ExtenderConfigs []ExtenderConfig // RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule // corresponding to every RequiredDuringScheduling affinity rule. // HardPodAffinitySymmetricWeight represents the weight of implicit PreferredDuringScheduling affinity rule, in the range 1-100. HardPodAffinitySymmetricWeight int } type PredicatePolicy struct {"} {"_id":"doc-en-kubernetes-5d9ce08e6493056a7a2f01fa74b3b16fb94d5f6fa5eb488c7997ca7e2c0780aa","title":"","text":"Priorities []PriorityPolicy `json:\"priorities\"` // Holds the information to communicate with the extender(s) ExtenderConfigs []ExtenderConfig `json:\"extenders\"` // RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule // corresponding to every RequiredDuringScheduling affinity rule. // HardPodAffinitySymmetricWeight represents the weight of implicit PreferredDuringScheduling affinity rule, in the range 1-100. HardPodAffinitySymmetricWeight int `json:\"hardPodAffinitySymmetricWeight\"` } type PredicatePolicy struct {"} {"_id":"doc-en-kubernetes-1c067fcda6fb2f7494ed129125533874bd7515489bb612cfc69c0e71aa58ae40","title":"","text":"} } } // Providing HardPodAffinitySymmetricWeight in the policy config is the new and preferred way of providing the value. // Give it higher precedence than scheduler CLI configuration when it is provided. if policy.HardPodAffinitySymmetricWeight != 0 { f.hardPodAffinitySymmetricWeight = policy.HardPodAffinitySymmetricWeight } return f.CreateFromKeys(predicateKeys, priorityKeys, extenders) }"} {"_id":"doc-en-kubernetes-9ce6d39f210c1071a80a91f537ccf7e861330a59a98cdb1499fcbe3611f67caa","title":"","text":"func (f *ConfigFactory) CreateFromKeys(predicateKeys, priorityKeys sets.String, extenders []algorithm.SchedulerExtender) (*scheduler.Config, error) { glog.V(2).Infof(\"Creating scheduler with fit predicates '%v' and priority functions '%v\", predicateKeys, priorityKeys) if f.GetHardPodAffinitySymmetricWeight() < 0 || f.GetHardPodAffinitySymmetricWeight() > 100 { return nil, fmt.Errorf(\"invalid hardPodAffinitySymmetricWeight: %d, must be in the range 0-100\", f.GetHardPodAffinitySymmetricWeight()) if f.GetHardPodAffinitySymmetricWeight() < 1 || f.GetHardPodAffinitySymmetricWeight() > 100 { return nil, fmt.Errorf(\"invalid hardPodAffinitySymmetricWeight: %d, must be in the range 1-100\", f.GetHardPodAffinitySymmetricWeight()) } predicateFuncs, err := f.GetPredicates(predicateKeys)"} {"_id":"doc-en-kubernetes-0000ac51c1276b4740fb122d9b802bdadd2033eee75dec85386e4ab3896771a8","title":"","text":"} factory.CreateFromConfig(policy) hpa := factory.GetHardPodAffinitySymmetricWeight() if hpa != v1.DefaultHardPodAffinitySymmetricWeight { t.Errorf(\"Wrong hardPodAffinitySymmetricWeight, ecpected: %d, got: %d\", v1.DefaultHardPodAffinitySymmetricWeight, hpa) } } func TestCreateFromConfigWithHardPodAffinitySymmetricWeight(t *testing.T) { var configData []byte var policy schedulerapi.Policy handler := utiltesting.FakeHandler{ StatusCode: 500, ResponseBody: \"\", T: t, } server := httptest.NewServer(&handler) defer server.Close() client := clientset.NewForConfigOrDie(&restclient.Config{Host: server.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &api.Registry.GroupOrDie(v1.GroupName).GroupVersion}}) informerFactory := informers.NewSharedInformerFactory(client, 0) factory := NewConfigFactory( v1.DefaultSchedulerName, client, informerFactory.Core().V1().Nodes(), informerFactory.Core().V1().Pods(), informerFactory.Core().V1().PersistentVolumes(), informerFactory.Core().V1().PersistentVolumeClaims(), informerFactory.Core().V1().ReplicationControllers(), informerFactory.Extensions().V1beta1().ReplicaSets(), informerFactory.Apps().V1beta1().StatefulSets(), informerFactory.Core().V1().Services(), v1.DefaultHardPodAffinitySymmetricWeight, ) // Pre-register some predicate and priority functions RegisterFitPredicate(\"PredicateOne\", PredicateOne) RegisterFitPredicate(\"PredicateTwo\", PredicateTwo) RegisterPriorityFunction(\"PriorityOne\", PriorityOne, 1) RegisterPriorityFunction(\"PriorityTwo\", PriorityTwo, 1) configData = []byte(`{ \"kind\" : \"Policy\", \"apiVersion\" : \"v1\", \"predicates\" : [ {\"name\" : \"TestZoneAffinity\", \"argument\" : {\"serviceAffinity\" : {\"labels\" : [\"zone\"]}}}, {\"name\" : \"TestRequireZone\", \"argument\" : {\"labelsPresence\" : {\"labels\" : [\"zone\"], \"presence\" : true}}}, {\"name\" : \"PredicateOne\"}, {\"name\" : \"PredicateTwo\"} ], \"priorities\" : [ {\"name\" : \"RackSpread\", \"weight\" : 3, \"argument\" : {\"serviceAntiAffinity\" : {\"label\" : \"rack\"}}}, {\"name\" : \"PriorityOne\", \"weight\" : 2}, {\"name\" : \"PriorityTwo\", \"weight\" : 1} ], \"hardPodAffinitySymmetricWeight\" : 10 }`) if err := runtime.DecodeInto(latestschedulerapi.Codec, configData, &policy); err != nil { t.Errorf(\"Invalid configuration: %v\", err) } factory.CreateFromConfig(policy) hpa := factory.GetHardPodAffinitySymmetricWeight() if hpa != 10 { t.Errorf(\"Wrong hardPodAffinitySymmetricWeight, ecpected: %d, got: %d\", 10, hpa) } } func TestCreateFromEmptyConfig(t *testing.T) {"} {"_id":"doc-en-kubernetes-d32398aee52e55358cde516d34026a1bb6aa4ced9570749d29e914ceb243ca0d","title":"","text":"apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/runtime/serializer\" \"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters\" v1listers \"k8s.io/client-go/listers/core/v1\""} {"_id":"doc-en-kubernetes-c986b580e4e2dbd97c2d6e12aab6c382b8e14b0b412991b20015153496c60262","title":"","text":"} } json, err := runtime.Encode(r.codecs.LegacyCodec(), discoveryGroupList) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if _, err := w.Write(json); err != nil { panic(err) } responsewriters.WriteObjectNegotiated(r.codecs, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroupList) } // convertToDiscoveryAPIGroup takes apiservices in a single group and returns a discovery compatible object."} {"_id":"doc-en-kubernetes-a7393ea476cb35f349f7d983c1551c39503def3716af68bd29459436e5d7b11d","title":"","text":"http.Error(w, \"\", http.StatusNotFound) return } json, err := runtime.Encode(r.codecs.LegacyCodec(), discoveryGroup) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if _, err := w.Write(json); err != nil { panic(err) } responsewriters.WriteObjectNegotiated(r.codecs, schema.GroupVersion{}, w, req, http.StatusOK, discoveryGroup) }"} {"_id":"doc-en-kubernetes-996e9c6ffd28fbd24d4e09148365a52c86a1161ac83efd8268ca32b19971db7e","title":"","text":"go_test( name = \"go_default_test\", srcs = [\"humanreadable_test.go\"], srcs = [ \"humanreadable_test.go\", \"template_test.go\", ], embed = [\":go_default_library\"], deps = [ \"//pkg/apis/core:go_default_library\","} {"_id":"doc-en-kubernetes-2a32018457b95fb0107655ed4bd58b3c5c356716ce6b35e6b65aa8dc58699960","title":"","text":"package printers import ( \"encoding/base64\" \"encoding/json\" \"fmt\" \"io\""} {"_id":"doc-en-kubernetes-84c019045c859a166076ea09d620e4c190c57fec7c4f3e09f187a197a0194f76","title":"","text":"func NewTemplatePrinter(tmpl []byte) (*TemplatePrinter, error) { t, err := template.New(\"output\"). Funcs(template.FuncMap{\"exists\": exists}). Funcs(template.FuncMap{ \"exists\": exists, \"base64decode\": base64decode, }). Parse(string(tmpl)) if err != nil { return nil, err"} {"_id":"doc-en-kubernetes-d6894de33ea9c7a8093af0159960f3f9bdc0feff142a44b527eaf40a9f608cd0","title":"","text":"} return retErr } func base64decode(v string) (string, error) { data, err := base64.StdEncoding.DecodeString(v) if err != nil { return \"\", fmt.Errorf(\"base64 decode failed: %v\", err) } return string(data), nil } "} {"_id":"doc-en-kubernetes-f61d60a0c80135ec4974589e0ce332de6cd1fc6b9b859b3507c7a85d17e93127","title":"","text":" /* Copyright 2018 The Kubernetes Authors. 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. */ package printers import ( \"bytes\" \"strings\" \"testing\" \"k8s.io/apimachinery/pkg/runtime\" api \"k8s.io/kubernetes/pkg/apis/core\" ) func TestTemplate(t *testing.T) { testCase := map[string]struct { template string obj runtime.Object expectOut string expectErr func(error) (string, bool) }{ \"support base64 decoding of secret data\": { template: \"{{ .Data.username | base64decode }}\", obj: &api.Secret{ Data: map[string][]byte{ \"username\": []byte(\"hunter\"), }, }, expectOut: \"hunter\", }, \"test error path for base64 decoding\": { template: \"{{ .Data.username | base64decode }}\", obj: &badlyMarshaledSecret{}, expectErr: func(err error) (string, bool) { matched := strings.Contains(err.Error(), \"base64 decode\") return \"a base64 decode error\", matched }, }, } for name, test := range testCase { buffer := &bytes.Buffer{} p, err := NewTemplatePrinter([]byte(test.template)) if err != nil { if test.expectErr == nil { t.Errorf(\"[%s]expected success but got:n %vn\", name, err) continue } if expected, ok := test.expectErr(err); !ok { t.Errorf(\"[%s]expect:n %vn but got:n %vn\", name, expected, err) } continue } err = p.PrintObj(test.obj, buffer) if err != nil { if test.expectErr == nil { t.Errorf(\"[%s]expected success but got:n %vn\", name, err) continue } if expected, ok := test.expectErr(err); !ok { t.Errorf(\"[%s]expect:n %vn but got:n %vn\", name, expected, err) } continue } if test.expectErr != nil { t.Errorf(\"[%s]expect:n errorn but got:n no errorn\", name) continue } if test.expectOut != buffer.String() { t.Errorf(\"[%s]expect:n %vn but got:n %vn\", name, test.expectOut, buffer.String()) } } } type badlyMarshaledSecret struct { api.Secret } func (a badlyMarshaledSecret) MarshalJSON() ([]byte, error) { return []byte(`{\"apiVersion\":\"v1\",\"Data\":{\"username\":\"--THIS IS NOT BASE64--\"},\"kind\":\"Secret\"}`), nil } "} {"_id":"doc-en-kubernetes-e8a32cfcbe609177b7de56b164b1ce0c9d13fbfca7713b0879076d866a3e89d4","title":"","text":"labels: app: cockroachdb annotations: scheduler.alpha.kubernetes.io/affinity: > { \"podAntiAffinity\": { \"preferredDuringSchedulingIgnoredDuringExecution\": [{ \"weight\": 100, \"labelSelector\": { \"matchExpressions\": [{ \"key\": \"app\", \"operator\": \"In\", \"values\": [\"cockroachdb\"] }] }, \"topologyKey\": \"kubernetes.io/hostname\" }] } } # Init containers are run only once in the lifetime of a pod, before # it's started up for the first time. It has to exit successfully # before the pod's main containers are allowed to start."} {"_id":"doc-en-kubernetes-92cfd4c107973b2d96179785e4d4aae825d84949564793e2ea7e333f72dbf2d3","title":"","text":"} ]' spec: affinity: podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpress: - key: app operator: In values: - cockroachdb topologyKey: kubernetes.io/hostname containers: - name: cockroachdb # Runs the master branch. Not recommended for production, but since"} {"_id":"doc-en-kubernetes-91b094bb1f9427df1c8c4781b04d4137046eff9b4b4ba967a17e0573a134f7ec","title":"","text":"function run-gcloud-compute-with-retries { RETRIES=\"${RETRIES:-3}\" for attempt in $(seq 1 ${RETRIES}); do local -r gcloud_result=$(gcloud compute \"$@\" 2>&1) local -r ret_val=\"$?\" # We don't use 'local' to declare gcloud_result as then ret_val always gets value 0. gcloud_result=$(gcloud compute \"$@\" 2>&1) || local ret_val=\"$?\" echo \"${gcloud_result}\" if [[ \"${ret_val}\" -ne \"0\" ]]; then if [[ \"${ret_val:-0}\" -ne \"0\" ]]; then if [[ $(echo \"${gcloud_result}\" | grep -c \"already exists\") -gt 0 ]]; then if [[ \"${attempt}\" == 1 ]]; then echo -e \"${color_red}Failed to $1 $2 $3 as the resource hasn't been deleted from a previous run.${color_norm}\" >& 2"} {"_id":"doc-en-kubernetes-fc4a863b2104069ef22e7126b8d27c08da8f9b5abbc88ac8fe3e20587ad58bc1","title":"","text":"--disk \"name=${MASTER_NAME}-pd,device-name=master-pd,mode=rw,boot=no,auto-delete=no\" run-gcloud-compute-with-retries instances add-metadata \"${MASTER_NAME}\" ${GCLOUD_COMMON_ARGS} --metadata-from-file startup-script=\"${KUBE_ROOT}/test/kubemark/resources/start-kubemark-master.sh\" if [ \"${EVENT_PD:-false}\" == \"true\" ]; then"} {"_id":"doc-en-kubernetes-7a1e782b04bd5e778209e2f43eca4e99ec5c1ad3a84674467a4e14935868eb89","title":"","text":"\"//pkg/api/v1/pod:go_default_library\", \"//pkg/client/clientset_generated/clientset:go_default_library\", \"//pkg/client/informers/informers_generated/externalversions/core/v1:go_default_library\", \"//pkg/client/leaderelection/resourcelock:go_default_library\", \"//pkg/client/listers/core/v1:go_default_library\", \"//pkg/controller:go_default_library\", \"//pkg/util/metrics:go_default_library\","} {"_id":"doc-en-kubernetes-169ccd11105580faa6e48c27e4dc4f333d9f76cbe9a1d0e761b9a53d2289bd3e","title":"","text":"podutil \"k8s.io/kubernetes/pkg/api/v1/pod\" \"k8s.io/kubernetes/pkg/client/clientset_generated/clientset\" coreinformers \"k8s.io/kubernetes/pkg/client/informers/informers_generated/externalversions/core/v1\" \"k8s.io/kubernetes/pkg/client/leaderelection/resourcelock\" corelisters \"k8s.io/kubernetes/pkg/client/listers/core/v1\" \"k8s.io/kubernetes/pkg/controller\" \"k8s.io/kubernetes/pkg/util/metrics\""} {"_id":"doc-en-kubernetes-495e774394a30dfd9c16e4561707864713590a940123b2a6e115aaeb8b46705e","title":"","text":"} for i := range list.Items { ep := &list.Items[i] if _, ok := ep.Annotations[resourcelock.LeaderElectionRecordAnnotationKey]; ok { // when there are multiple controller-manager instances, // we observe that it will delete leader-election endpoints after 5min // and cause re-election // so skip the delete here // as leader-election only have endpoints without service continue } key, err := keyFunc(ep) if err != nil { utilruntime.HandleError(fmt.Errorf(\"Unable to get key for endpoint %#v\", ep))"} {"_id":"doc-en-kubernetes-85ce34979f79816576507bde7f3ef76bc18f1ad1708419e5d21f1cfd722d7b51","title":"","text":"// if the number of consecutive read failure equals or exceeds the failureThreshold , the // configuration is regarded as not ready. failureThreshold int // number of consecutive failures so far. failures int // if the configuration is regarded as ready. ready bool mergedConfiguration runtime.Object"} {"_id":"doc-en-kubernetes-a709f3b6c0cfd0ffca6eef48e242827d350f3c40cf26ac5fc2532b0dddcdaef7","title":"","text":"} func (a *poller) Run(stopCh <-chan struct{}) { var failure int go wait.Until(func() { configuration, err := a.get() if err != nil { failure++ if failure >= a.failureThreshold { a.notReady() } return go wait.Until(a.sync, a.interval, stopCh) } func (a *poller) sync() { configuration, err := a.get() if err != nil { a.failures++ if a.failures >= a.failureThreshold { a.notReady() } failure = 0 a.setConfigurationAndReady(configuration) }, a.interval, stopCh) return } a.failures = 0 a.setConfigurationAndReady(configuration) }"} {"_id":"doc-en-kubernetes-cfea31fa486ec1647c36c7798a001b5c40080ffe08630f2dc8abcb0c01c74916","title":"","text":"invoked int successes int failures int stopCh chan struct{} configurationList v1alpha1.InitializerConfigurationList t *testing.T }"} {"_id":"doc-en-kubernetes-74a342b8dd8b4a673d9612e13af678e13869a04728728fbcc32adc1fde42ceff","title":"","text":"failures: failures, successes: successes, configurationList: configurationList, stopCh: make(chan struct{}), t: t, } } // The first List will be successful; the next m.failures List will // fail; the next m.successes List will be successful; the stopCh is closed at // the 1+m.failures+m.successes call. // fail; the next m.successes List will be successful // List should only be called 1+m.failures+m.successes times. func (m *mockLister) List(options metav1.ListOptions) (*v1alpha1.InitializerConfigurationList, error) { m.invoked++ // m.successes could be 0, so call this `if` first. if m.invoked == 1+m.failures+m.successes { close(m.stopCh) } if m.invoked == 1 { return &m.configurationList, nil }"} {"_id":"doc-en-kubernetes-a5116794158fec586a2a827c4bc664bb71f4cd552376998039861e4906b6c53b","title":"","text":"if m.invoked <= 1+m.failures+m.successes { return &m.configurationList, nil } m.t.Fatalf(\"unexpected call to List, stopCh has been closed at the %d time call\", 1+m.successes+m.failures) m.t.Fatalf(\"unexpected call to List, should only be called %d times\", 1+m.successes+m.failures) return nil, nil }"} {"_id":"doc-en-kubernetes-b75e7a65a5d79a404f592ef12f751f7ff29756cab28ca1fbc0341a2914107fe4","title":"","text":"mock := newMockLister(c.successes, c.failures, v1alpha1.InitializerConfigurationList{}, t) manager := NewInitializerConfigurationManager(mock) manager.interval = 1 * time.Millisecond manager.Run(mock.stopCh) <-mock.stopCh for i := 0; i < 1+c.successes+c.failures; i++ { manager.sync() } _, err := manager.Initializers() if err != nil && c.expectReady { t.Errorf(\"case %s, expect ready, got: %v\", c.name, err)"} {"_id":"doc-en-kubernetes-2c2d5258eee1860c1e9c2e0fc47e3194e462c1ed6f72067a041a403dcb6d3c41","title":"","text":"HOSTNAME_OVERRIDE=${HOSTNAME_OVERRIDE:-\"127.0.0.1\"} CLOUD_PROVIDER=${CLOUD_PROVIDER:-\"\"} CLOUD_CONFIG=${CLOUD_CONFIG:-\"\"} FEATURE_GATES=${FEATURE_GATES:-\"AllAlpha=true\"} FEATURE_GATES=${FEATURE_GATES:-\"AllAlpha=false\"} STORAGE_BACKEND=${STORAGE_BACKEND:-\"etcd3\"} # enable swagger ui ENABLE_SWAGGER_UI=${ENABLE_SWAGGER_UI:-false}"} {"_id":"doc-en-kubernetes-454583e865b3ddd9d9182b54ff0cc60b633d24b4680c49e4cc22c9fd6798df1d","title":"","text":"// Build a detailed log of the denial. // Make the whole block conditional so we don't do a lot of string-building we won't use. if glog.V(2) { if glog.V(5) { var operation string if requestAttributes.IsResourceRequest() { b := &bytes.Buffer{}"} {"_id":"doc-en-kubernetes-488695ee5ef82cc01ab2d86a334a6c22bf25c9a5a99d3352a5f55f950cbe893c","title":"","text":"for attempts := 0; attempts < 4; attempts++ { outputBytes, err = exec.Command(\"gcloud\", \"compute\", \"addresses\", \"create\", name, \"--project\", TestContext.CloudConfig.ProjectID, \"--region\", region, \"-q\").CombinedOutput() \"--region\", region, \"-q\", \"--format=yaml\").CombinedOutput() if err == nil { break }"} {"_id":"doc-en-kubernetes-54722c959fcab2c9a55b5198359416858ec8c3467f3a3b679c904e3224996892","title":"","text":"# Metadata for driving the build lives here. META_DIR := .make # Our build flags. # TODO(thockin): it would be nice to just use the native flags. Can we EOL # these \"wrapper\" flags? KUBE_GOFLAGS := $(GOFLAGS) KUBE_GOLDFLAGS := $(GOLDFLAGS) KUBE_GOGCFLAGS = $(GOGCFLAGS) ifdef KUBE_GOFLAGS $(info KUBE_GOFLAGS is now deprecated. Please use GOFLAGS instead.) ifndef GOFLAGS GOFLAGS := $(KUBE_GOFLAGS) unexport KUBE_GOFLAGS else $(error Both KUBE_GOFLAGS and GOFLAGS are set. Please use just GOFLAGS) endif endif # Extra options for the release or quick-release options: KUBE_RELEASE_RUN_TESTS := $(KUBE_RELEASE_RUN_TESTS)"} {"_id":"doc-en-kubernetes-4b94fd987891e3523a0269fec370fbf64122b9ceabd2d41c66f07b7cf1103665","title":"","text":"# Use eval to preserve embedded quoted strings. local goflags goldflags gogcflags eval \"goflags=(${KUBE_GOFLAGS:-})\" goldflags=\"${KUBE_GOLDFLAGS:-} $(kube::version::ldflags)\" gogcflags=\"${KUBE_GOGCFLAGS:-}\" eval \"goflags=(${GOFLAGS:-})\" goldflags=\"${GOLDFLAGS:-} $(kube::version::ldflags)\" gogcflags=\"${GOGCFLAGS:-}\" local use_go_build local -a targets=()"} {"_id":"doc-en-kubernetes-fa47001b7b15885e9957c8e3feedbadddbcd09eb295cc953e8bb8e45909584fb","title":"","text":"# KUBE_RACE=\"-race\" make -C \"${KUBE_ROOT}\" test WHAT=\"${WHAT:-$(kube::test::find_integration_test_dirs | paste -sd' ' -)}\" KUBE_GOFLAGS=\"${KUBE_GOFLAGS:-}\" GOFLAGS=\"${GOFLAGS:-}\" KUBE_TEST_ARGS=\"${KUBE_TEST_ARGS:-} ${SHORT:--short=true} --vmodule=garbage*collector*=6 --alsologtostderr=true\" KUBE_RACE=\"\" KUBE_TIMEOUT=\"${KUBE_TIMEOUT}\" "} {"_id":"doc-en-kubernetes-d83d6f4816aeffe9f1dba8e8e22ab378c245bdf70a96b7c7ac9ce020d54ae43a","title":"","text":"shift $((OPTIND - 1)) # Use eval to preserve embedded quoted strings. eval \"goflags=(${KUBE_GOFLAGS:-})\" eval \"goflags=(${GOFLAGS:-})\" eval \"testargs=(${KUBE_TEST_ARGS:-})\" # Used to filter verbose test output."} {"_id":"doc-en-kubernetes-dd42d9842e5d6652950ac5642f236562fe2b00e339cc14663187fd18f6b265fd","title":"","text":"go install ./cmd/... # Use eval to preserve embedded quoted strings. eval \"goflags=(${KUBE_GOFLAGS:-})\" eval \"goflags=(${GOFLAGS:-})\" # Filter out arguments that start with \"-\" and move them to goflags. targets=()"} {"_id":"doc-en-kubernetes-f6877c36c3d8147ea8a61399515943a4d5a8132be20b80f66cc289a430295573","title":"","text":"echo ' make test-integration' echo echo \"The following invocation will run a specific test with the verbose flag set: \" echo ' make test-integration WHAT=./test/integration/pods KUBE_GOFLAGS=\"-v\" KUBE_TEST_ARGS=\"-run ^TestPodUpdateActiveDeadlineSeconds$\"' echo ' make test-integration WHAT=./test/integration/pods GOFLAGS=\"-v\" KUBE_TEST_ARGS=\"-run ^TestPodUpdateActiveDeadlineSeconds$\"' echo exit 1"} {"_id":"doc-en-kubernetes-f47276383b86c477ce142c5b11695cb23d6dd76227214bdfcd04cff0b2bce375","title":"","text":"// if container doesn't exist, create one and retry PutPageBlob detail := err.Error() if strings.Contains(detail, errContainerNotFound) { err = blobClient.CreateContainer(vhdContainerName, azs.ContainerAccessTypeContainer) err = blobClient.CreateContainer(vhdContainerName, azs.ContainerAccessTypePrivate) if err == nil { err = blobClient.PutPageBlob(vhdContainerName, name, vhdSize, tags) }"} {"_id":"doc-en-kubernetes-5763949a56eb0d4650a444d0488858f0cbd126d07368ca327abe5dbad2663888","title":"","text":"// getListener creates a listener on the interface targeted by the given hostname on the given port with // the given protocol. protocol is in net.Listen style which basically admits values like tcp, tcp4, tcp6 func (pf *PortForwarder) getListener(protocol string, hostname string, port *ForwardedPort) (net.Listener, error) { listener, err := net.Listen(protocol, fmt.Sprintf(\"%s:%d\", hostname, port.Local)) listener, err := net.Listen(protocol, net.JoinHostPort(hostname, strconv.Itoa(int(port.Local)))) if err != nil { return nil, fmt.Errorf(\"Unable to create listener: Error %s\", err) }"} {"_id":"doc-en-kubernetes-7bab1cecfc69d35532bb1817ba1d70682c96454001f55bbe95a28bb67d846f2f","title":"","text":"ExpectedListenerAddress: \"127.0.0.1\", }, { Hostname: \"[::1]\", Hostname: \"::1\", Protocol: \"tcp6\", ShouldRaiseError: false, ExpectedListenerAddress: \"::1\", }, { Hostname: \"[::1]\", Hostname: \"::1\", Protocol: \"tcp4\", ShouldRaiseError: true, },"} {"_id":"doc-en-kubernetes-4a11c94e207efe352c1bd8d02aa540a394f8d3c3312250a0cdf4be59485102e5","title":"","text":"Protocol: \"tcp6\", ShouldRaiseError: true, }, { // IPv6 address must be put into brackets. This test reveals this. Hostname: \"::1\", Protocol: \"tcp6\", ShouldRaiseError: true, }, } for i, testCase := range testCases {"} {"_id":"doc-en-kubernetes-cddb935d9201d8dc138a7a8b62bc6c2e53936ea49af7ce88c2752047d7d1cb4d","title":"","text":"host, port, _ := net.SplitHostPort(listener.Addr().String()) t.Logf(\"Asked a %s forward for: %s:%v, got listener %s:%s, expected: %s\", testCase.Protocol, testCase.Hostname, 12345, host, port, expectedListenerPort) if host != testCase.ExpectedListenerAddress { t.Errorf(\"Test case #%d failed: Listener does not listen on exepected address: asked %v got %v\", i, testCase.ExpectedListenerAddress, host) t.Errorf(\"Test case #%d failed: Listener does not listen on expected address: asked '%v' got '%v'\", i, testCase.ExpectedListenerAddress, host) } if port != expectedListenerPort { t.Errorf(\"Test case #%d failed: Listener does not listen on exepected port: asked %v got %v\", i, expectedListenerPort, port)"} {"_id":"doc-en-kubernetes-c6d79f6fe5a86e43e160a9fdfe60e814c4413c8cafd5ed949583d7c36edef2ed","title":"","text":"fi params+=\" --tls-cert-file=/etc/srv/kubernetes/server.cert\" params+=\" --tls-private-key-file=/etc/srv/kubernetes/server.key\" params+=\" --requestheader-client-ca-file=/etc/srv/kubernetes/aggr_ca.crt\" params+=\" --requestheader-allowed-names=aggregator\" params+=\" --requestheader-extra-headers-prefix=X-Remote-Extra-\" params+=\" --requestheader-group-headers=X-Remote-Group\" params+=\" --requestheader-username-headers=X-Remote-User\" params+=\" --proxy-client-cert-file=/etc/srv/kubernetes/proxy_client.crt\" params+=\" --proxy-client-key-file=/etc/srv/kubernetes/proxy_client.key\" params+=\" --enable-aggregator-routing=true\" params+=\" --client-ca-file=/etc/srv/kubernetes/ca.crt\" params+=\" --token-auth-file=/etc/srv/kubernetes/known_tokens.csv\" params+=\" --secure-port=443\""} {"_id":"doc-en-kubernetes-8d440a561fa31c779880e437685ec497795252de1bef83b5c66a27d0dc5d7d80","title":"","text":"sudo bash -c \"echo ${CA_CERT_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/ca.crt\" && sudo bash -c \"echo ${MASTER_CERT_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/server.cert\" && sudo bash -c \"echo ${MASTER_KEY_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/server.key\" && sudo bash -c \"echo ${REQUESTHEADER_CA_CERT_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/aggr_ca.crt\" && sudo bash -c \"echo ${PROXY_CLIENT_CERT_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/proxy_client.crt\" && sudo bash -c \"echo ${PROXY_CLIENT_KEY_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/proxy_client.key\" && sudo bash -c \"echo ${KUBECFG_CERT_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/kubecfg.crt\" && sudo bash -c \"echo ${KUBECFG_KEY_BASE64} | base64 --decode > /home/kubernetes/k8s_auth_data/kubecfg.key\" && sudo bash -c \"echo \"${KUBE_BEARER_TOKEN},admin,admin\" > /home/kubernetes/k8s_auth_data/known_tokens.csv\" && "} {"_id":"doc-en-kubernetes-2f8f72dd32b98dba9d051f9e660595c43d52b4e55e572b9f584a369efee5b878","title":"","text":"go run ./hack/e2e.go -v -build # Push to GCS yes | ./build/push-ci-build.sh ./build/push-ci-build.sh sha256sum _output/release-tars/kubernetes*.tar.gz"} {"_id":"doc-en-kubernetes-ef79b1bfcdd0dd17d4afa3fdd42082177addf3317c7b998571758c2cb749b798","title":"","text":"for portname := range oldPortsToEndpoints { svcPort := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: oldEndpoints.Namespace, Name: oldEndpoints.Name}, Port: portname} if _, exists := registeredEndpoints[svcPort]; !exists { lb.resetService(svcPort) } } } func (lb *LoadBalancerRR) resetService(svcPort proxy.ServicePortName) { // If the service is still around, reset but don't delete. if state, ok := lb.services[svcPort]; ok { if len(state.endpoints) > 0 { glog.V(2).Infof(\"LoadBalancerRR: Removing endpoints for %s\", svcPort) // Reset but don't delete. state := lb.services[svcPort] state.endpoints = []string{} state.index = 0 state.affinity.affinityMap = map[string]*affinityState{} } state.index = 0 state.affinity.affinityMap = map[string]*affinityState{} } }"} {"_id":"doc-en-kubernetes-260181c8f2e458b6ecf518ddaa44b7c392fdf00f91cd549493339680a4b4bb85","title":"","text":"for portname := range portsToEndpoints { svcPort := proxy.ServicePortName{NamespacedName: types.NamespacedName{Namespace: endpoints.Namespace, Name: endpoints.Name}, Port: portname} glog.V(2).Infof(\"LoadBalancerRR: Removing endpoints for %s\", svcPort) // If the service is still around, reset but don't delete. if state, ok := lb.services[svcPort]; ok { state.endpoints = []string{} state.index = 0 state.affinity.affinityMap = map[string]*affinityState{} } lb.resetService(svcPort) } }"} {"_id":"doc-en-kubernetes-2b7f5c11e58194108b14ac79b162eee40d8a168aa7e43c10897e72cba24d4823","title":"","text":"DockerEndpoint: dockerEndpoint, DockershimRootDirectory: \"/var/lib/dockershim\", DockerExecHandlerName: \"native\", DockerDisableSharedPID: true, PodSandboxImage: defaultPodSandboxImage, ImagePullProgressDeadline: metav1.Duration{Duration: 1 * time.Minute}, RktAPIEndpoint: defaultRktAPIServiceEndpoint,"} {"_id":"doc-en-kubernetes-14d36ea28cf3eb7d58577939a7e5d942785d80fe2a53520f8a54e0fc35dd94be","title":"","text":"It(\"processes in different containers of the same pod should be able to see each other\", func() { // TODO(yguo0905): Change this test to run unless the runtime is // Docker and its version is <1.13. By(\"Check whether shared PID namespace is enabled.\") isEnabled, err := isSharedPIDNamespaceEnabled() By(\"Check whether shared PID namespace is supported.\") isEnabled, err := isSharedPIDNamespaceSupported() framework.ExpectNoError(err) if !isEnabled { framework.Skipf(\"Skipped because shared PID namespace is not enabled.\") framework.Skipf(\"Skipped because shared PID namespace is not supported by this docker version.\") } By(\"Create a pod with two containers.\")"} {"_id":"doc-en-kubernetes-209365c186e906215f8b465c094380d253207e907560c7bf368167e1e6f629e8","title":"","text":"return semver.MustParse(version.APIVersion + \".0\"), nil } // isSharedPIDNamespaceEnabled returns true if the Docker version is 1.13.1+ // isSharedPIDNamespaceSupported returns true if the Docker version is 1.13.1+ // (API version 1.26+), and false otherwise. func isSharedPIDNamespaceEnabled() (bool, error) { func isSharedPIDNamespaceSupported() (bool, error) { version, err := getDockerAPIVersion() if err != nil { return false, err"} {"_id":"doc-en-kubernetes-c22b04c92886a258c84b165174e2bd1868a10c95e39952bafe5f80aac049f3b9","title":"","text":"\"--serialize-image-pulls\", \"false\", \"--pod-manifest-path\", manifestPath, \"--file-check-frequency\", \"10s\", // Check file frequently so tests won't wait too long \"--docker-disable-shared-pid=false\", // Assign a fixed CIDR to the node because there is no node controller. // // Note: this MUST be in sync with with the IP in"} {"_id":"doc-en-kubernetes-eff01f8b68e8f8a1c9952bd9e0985e92e1fa7c937dbaece507c3afc16b3ba19e","title":"","text":"{Type: v1.NodeMemoryPressure, Status: v1.ConditionFalse}, {Type: v1.NodeDiskPressure, Status: v1.ConditionFalse}, {Type: v1.NodeNetworkUnavailable, Status: v1.ConditionFalse}, {Type: v1.NodeInodePressure, Status: v1.ConditionFalse}, } return node }(),"} {"_id":"doc-en-kubernetes-76ed9941f6568b10987402f1d02b195a933c4a81ab823dc2fcde884a44565718","title":"","text":"node := newNode(\"node1\", nil) node.Status.Conditions = []v1.NodeCondition{ {Type: v1.NodeOutOfDisk, Status: v1.ConditionTrue}, {Type: v1.NodeInodePressure, Status: v1.ConditionFalse}, } return node }(),"} {"_id":"doc-en-kubernetes-bd5a0b06201c0496c7216fba6c2af63ce440a2d5e2db9cde2c9c21dff44c510a","title":"","text":"NodeDiskPressure NodeConditionType = \"DiskPressure\" // NodeNetworkUnavailable means that network for the node is not correctly configured. NodeNetworkUnavailable NodeConditionType = \"NetworkUnavailable\" // NodeInodePressure means the kubelet is under pressure due to insufficient available inodes. NodeInodePressure NodeConditionType = \"InodePressure\" ) // NodeCondition contains condition information for a node."} {"_id":"doc-en-kubernetes-1590441343ccba9a69ba5393d97cc3e5da9ca003ecbf4eb4d6261a77ea07df8e","title":"","text":"v1.NodeOutOfDisk, v1.NodeMemoryPressure, v1.NodeDiskPressure, // We don't change 'NodeInodePressure' condition, as it'll be removed in future. // v1.NodeInodePressure, // We don't change 'NodeNetworkUnavailable' condition, as it's managed on a control plane level. // v1.NodeNetworkUnavailable, }"} {"_id":"doc-en-kubernetes-93e86edd144d1848c89af167aa51ca862860b40e047f2520a11da08031cfdedd","title":"","text":"if realPath != \"\" { // Only create the symlink when container log path is specified and log file exists. // Delete possibly existing file first if err = ds.os.Remove(path); err == nil { glog.Warningf(\"Deleted previously existing symlink file: %q\", path) } if err = ds.os.Symlink(realPath, path); err != nil { return fmt.Errorf(\"failed to create symbolic link %q to the container log file %q for container %q: %v\", path, realPath, containerID, err)"} {"_id":"doc-en-kubernetes-5cd0e78062c42b446b930fd58598cb43a381537e08efbda396036444ba972587","title":"","text":"assert.NoError(t, err) // Verify container log symlink deletion // symlink is also tentatively deleted at startup err = ds.RemoveContainer(id) assert.NoError(t, err) assert.Equal(t, fakeOS.Removes, []string{kubeletContainerLogPath}) assert.Equal(t, []string{kubeletContainerLogPath, kubeletContainerLogPath}, fakeOS.Removes) } // TestContainerCreationConflict tests the logic to work around docker container"} {"_id":"doc-en-kubernetes-5632100484bf4ae1bad612d2cc506d750b52004df6637225aa25ba77d231fb33","title":"","text":"if strings.Contains(cfg.Global.NetworkName, \"/\") { networkURL = cfg.Global.NetworkName } else { networkURL = gceNetworkURL(apiEndpoint, projectID, networkName) networkURL = gceNetworkURL(apiEndpoint, projectID, cfg.Global.NetworkName) } }"} {"_id":"doc-en-kubernetes-5d07a9781963de6aa92b23c78818e177a3870167f9ff63309535a4c6ba14d607","title":"","text":"gce := &GCECloud{ service: service, serviceAlpha: serviceAlpha, serviceBeta: serviceBeta, containerService: containerService, cloudkmsService: cloudkmsService,"} {"_id":"doc-en-kubernetes-f06b76db91b3043b88f9f7dca6d106c356ebeae9b7636d7d07d2c74c0daae15a","title":"","text":"desiredReplicas = scaleUpLimit case hpa.Spec.MinReplicas != nil && desiredReplicas < *hpa.Spec.MinReplicas: // make sure we aren't below our minimum setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, \"TooFewReplicas\", \"the desired replica count was less than the minimum replica count\") var statusMsg string if desiredReplicas == 0 { statusMsg = \"the desired replica count was zero\" } else { statusMsg = \"the desired replica count was less than the minimum replica count\" } setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, \"TooFewReplicas\", statusMsg) desiredReplicas = *hpa.Spec.MinReplicas case desiredReplicas == 0: // never scale down to 0, reserved for disabling autoscaling"} {"_id":"doc-en-kubernetes-2f0965c252c5906f63197abc0cabf193595c60d9afaecbcd430d621f978a7821","title":"","text":"func addNamespaceRoleBinding(namespace string, roleBinding rbac.RoleBinding) { if !strings.HasPrefix(namespace, \"kube-\") { glog.Fatalf(`roles can only be bootstrapped into reserved namespaces starting with \"kube-\", not %q`, namespace) glog.Fatalf(`rolebindings can only be bootstrapped into reserved namespaces starting with \"kube-\", not %q`, namespace) } existingRoleBindings := namespaceRoleBindings[namespace]"} {"_id":"doc-en-kubernetes-90c16fc798300b155aaf191594c9b87905fb004606b2d55ddfda302079ccace1","title":"","text":"// addTokenSecretReference adds a reference to the ServiceAccountToken that will be created func addTokenSecretReference(refs []v1.ObjectReference) []v1.ObjectReference { return addNamedTokenSecretReference(refs, \"default-token-p7w9c\") return addNamedTokenSecretReference(refs, \"default-token-stdpg\") } // addNamedTokenSecretReference adds a reference to the named ServiceAccountToken"} {"_id":"doc-en-kubernetes-19b9c71b950c88ac849ca7ec6e620d3908cc3c634caa72d1f8960dc1213f9dba","title":"","text":"} // createdTokenSecret returns the ServiceAccountToken secret posted when creating a new token secret. // Named \"default-token-p7w9c\", since that is the first generated name after rand.Seed(1) // Named \"default-token-stdpg\", since that is the first generated name after rand.Seed(1) func createdTokenSecret(overrideName ...string) *v1.Secret { return namedCreatedTokenSecret(\"default-token-p7w9c\") return namedCreatedTokenSecret(\"default-token-stdpg\") } // namedTokenSecret returns the ServiceAccountToken secret posted when creating a new token secret with the given name."} {"_id":"doc-en-kubernetes-6b2909ea312a6666eb3483363ad89ca8427c5472fa03039654dec552997a2496","title":"","text":"// Attempt 2 core.NewGetAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, \"default\"), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-x50vb\")), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-jk9rt\")), // Attempt 3 core.NewGetAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, \"default\"), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-scq98\")), core.NewUpdateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, serviceAccount(addNamedTokenSecretReference(emptySecretReferences(), \"default-token-scq98\"))), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-684pg\")), core.NewUpdateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, serviceAccount(addNamedTokenSecretReference(emptySecretReferences(), \"default-token-684pg\"))), }, }, \"new serviceaccount with no secrets encountering unending create error\": {"} {"_id":"doc-en-kubernetes-79991f29e7db07d8f51399af2542feb6e0928ebd65f26b4a533e5fb560971c09","title":"","text":"core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, createdTokenSecret()), // Retry 1 core.NewGetAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, \"default\"), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-x50vb\")), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-jk9rt\")), // Retry 2 core.NewGetAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"serviceaccounts\"}, metav1.NamespaceDefault, \"default\"), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-scq98\")), core.NewCreateAction(schema.GroupVersionResource{Version: \"v1\", Resource: \"secrets\"}, metav1.NamespaceDefault, namedCreatedTokenSecret(\"default-token-684pg\")), }, }, \"new serviceaccount with missing secrets\": {"} {"_id":"doc-en-kubernetes-031a371f4e9dc27240de0780df947f71e41decc7fc67a32b05ef0f068f3bf925","title":"","text":"// We omit vowels from the set of available characters to reduce the chances // of \"bad words\" being formed. var alphanums = []rune(\"bcdfghjklmnpqrstvwxz0123456789\") var alphanums = []rune(\"bcdfghjklmnpqrstvwxz2456789\") // String generates a random alphanumeric string, without vowels, which is n // characters long. This will panic if n is less than zero."} {"_id":"doc-en-kubernetes-4f41c6314f222f21dfe193002cac483879b4aa44fe8973f8dd1007cc23616ad7","title":"","text":"responses: 200: body: application/json: example: !include examples/pod-list.json example: !include examples/pod-list.json post: description: Create a new pod. currentState is ignored if present. body: json/application: schema: !include doc/pod-schema.json example: !include examples/pod.json schema: !include doc/pod-schema.json example: !include examples/pod.json /{podId}: get:"} {"_id":"doc-en-kubernetes-f367dc0ce31ce1772d9b9235fbe2ea5b7e581bb8596bddd9bbc583924635ee7a","title":"","text":"responses: 200: body: application/json: example: !include examples/pod.json example: !include examples/pod.json put: description: Update a pod body: json/application: schema: !include doc/pod-schema.json example: !include examples/pod.json schema: !include doc/pod-schema.json example: !include examples/pod.json delete: description: Delete a specific pod responses: 200: body: application/json: example: | { \"success\": true } example: | { \"success\": true } /replicationControllers: get:"} {"_id":"doc-en-kubernetes-fdc0a040c3a440786db3802cdef3cad9369866df19bb1f214ff6137ce438da28","title":"","text":"responses: 200: body: application/json: example: !include examples/controller-list.json example: !include examples/controller-list.json post: description: Create a new controller. currentState is ignored if present. body: json/application: schema: !include doc/controller-schema.json example: !include examples/controller.json schema: !include doc/controller-schema.json example: !include examples/controller.json /{controllerId}: get:"} {"_id":"doc-en-kubernetes-56e79b59bb23d6541bfce2fec917d5cfe2b2949594192e249380622c65c96fdf","title":"","text":"responses: 200: body: application/json: example: !include examples/controller.json example: !include examples/controller.json put: description: Update a controller body: json/application: schema: !include doc/controller-schema.json example: !include examples/controller.json schema: !include doc/controller-schema.json example: !include examples/controller.json delete: description: Delete a specific controller responses: 200: body: application/json: example: | { \"success\": true } example: | { \"success\": true } /services: get:"} {"_id":"doc-en-kubernetes-e9648dcc06ae9bd64b789439eac62d1c1525d39ed26b6d31aecc797ff16cbbeb","title":"","text":"responses: 200: body: application/json: example: !include examples/service-list.json example: !include examples/service-list.json post: description: Create a new service body: json/application: schema: !include doc/service-schema.json example: !include examples/service.json schema: !include doc/service-schema.json example: !include examples/service.json /{serviceId}: get:"} {"_id":"doc-en-kubernetes-c4ddd782ec355888260a72bea623f3ba590467aec02cf57f9c04d00a5e414077","title":"","text":"responses: 200: body: application/json: example: !include examples/service.json example: !include examples/service.json put: description: Update a service body: json/application: schema: !include doc/service-schema.json example: !include examples/service.json schema: !include doc/service-schema.json example: !include examples/service.json delete: description: Delete a specific service responses: 200: body: application/json: example: | { \"success\": true } example: | { \"success\": true } "} {"_id":"doc-en-kubernetes-6df6709dfafa44422a7128a69bbcab4b6e701c0774a7afed6df5cf0db48043a3","title":"","text":"} } // Set OODCondition for the node. func (kl *Kubelet) setNodeOODCondition(node *v1.Node) { currentTime := metav1.NewTime(kl.clock.Now()) var nodeOODCondition *v1.NodeCondition // Check if NodeOutOfDisk condition already exists and if it does, just pick it up for update. for i := range node.Status.Conditions { if node.Status.Conditions[i].Type == v1.NodeOutOfDisk { nodeOODCondition = &node.Status.Conditions[i] } } newOODCondition := nodeOODCondition == nil if newOODCondition || nodeOODCondition.Status == v1.ConditionUnknown { nodeOODCondition = &v1.NodeCondition{ Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse, Reason: \"KubeletHasSufficientDisk\", Message: \"kubelet has sufficient disk space available\", LastTransitionTime: currentTime, } } // Update the heartbeat time irrespective of all the conditions. nodeOODCondition.LastHeartbeatTime = currentTime if newOODCondition { node.Status.Conditions = append(node.Status.Conditions, *nodeOODCondition) } } // Maintains Node.Spec.Unschedulable value from previous run of tryUpdateNodeStatus() // TODO: why is this a package var? var oldNodeUnschedulable bool"} {"_id":"doc-en-kubernetes-2f99386b1d3989dc6702d35a02d0da442e0f5f9bb16c08abd12b1ef860b7e7ba","title":"","text":"return []func(*v1.Node) error{ kl.setNodeAddress, withoutError(kl.setNodeStatusInfo), withoutError(kl.setNodeOODCondition), withoutError(kl.setNodeMemoryPressureCondition), withoutError(kl.setNodeDiskPressureCondition), withoutError(kl.setNodeReadyCondition),"} {"_id":"doc-en-kubernetes-3975c8c05f89972a7d7f9188595e487ce84af0afd4311f0f73ed06b67773f01a","title":"","text":"Status: v1.NodeStatus{ Conditions: []v1.NodeCondition{ { Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse, Reason: \"KubeletHasSufficientDisk\", Message: fmt.Sprintf(\"kubelet has sufficient disk space available\"), LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), }, { Type: v1.NodeMemoryPressure, Status: v1.ConditionFalse, Reason: \"KubeletHasSufficientMemory\","} {"_id":"doc-en-kubernetes-8f5c8d14e5624f2958308b2e94987e30121017f3500cdc2473355d366de57445","title":"","text":"Status: v1.NodeStatus{ Conditions: []v1.NodeCondition{ { Type: v1.NodeOutOfDisk, Status: v1.ConditionFalse, Reason: \"KubeletHasSufficientDisk\", Message: fmt.Sprintf(\"kubelet has sufficient disk space available\"), LastHeartbeatTime: metav1.Time{}, LastTransitionTime: metav1.Time{}, }, { Type: v1.NodeMemoryPressure, Status: v1.ConditionFalse, Reason: \"KubeletHasSufficientMemory\","} {"_id":"doc-en-kubernetes-64348926d5386e5fd569284711718dcb27f5bd68083b620e895d6dc4cda1866c","title":"","text":" FROM debian:jessie RUN apt-get update RUN apt-get -qy install python-seqdiag make curl WORKDIR /diagrams RUN curl -sLo DroidSansMono.ttf https://googlefontdirectory.googlecode.com/hg/apache/droidsansmono/DroidSansMono.ttf ADD . /diagrams CMD bash -c 'make >/dev/stderr && tar cf - *.png' No newline at end of file"} {"_id":"doc-en-kubernetes-e939fb5debdbea59b360333b507c66c1b4c13623ecc0a2507d06f088af51575d","title":"","text":"%.png: %.seqdiag $(FONT) seqdiag --no-transparency -a -f '$(FONT)' $< # Build the stuff via a docker image .PHONY: docker docker: docker build -t clustering-seqdiag . docker run --rm clustering-seqdiag | tar xvf - docker-clean: docker rmi clustering-seqdiag || true docker images -q --filter \"dangling=true\" | xargs docker rmi fix-clock-skew: boot2docker ssh sudo date -u -D \"%Y%m%d%H%M.%S\" --set \"$(shell date -u +%Y%m%d%H%M.%S)\" "} {"_id":"doc-en-kubernetes-27f62daa9220fb6b09f9157b2af70de4e0ac599b001569f6a5fbd5f2460cb994","title":"","text":"``` Just call `make` to regenerate the diagrams. ## Building with Docker If you are on a Mac or your pip install is messed up, you can easily build with docker. ``` make docker ``` The first run will be slow but things should be fast after that. To clean up the docker containers that are created (and other cruft that is left around) you can run `make docker-clean`. If you are using boot2docker and get warnings about clock skew (or if things aren't building for some reason) then you can fix that up with `make fix-clock-skew`. ## Automatically rebuild on file changes If you have the fswatch utility installed, you can have it monitor the file system and automatically rebuild when files have changed. Just do a `make watch`. No newline at end of file"} {"_id":"doc-en-kubernetes-61a02e31d60648a80f04b969bb35b04e1d407c7a56237a6fcaaaecefd6840a56","title":"","text":"\"format\": \"int32\" }, \"revisionHistoryLimit\": { \"description\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.\", \"description\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.\", \"type\": \"integer\", \"format\": \"int32\" },"} {"_id":"doc-en-kubernetes-0c0d5b0e29a7263e6fac783f8acfba3c26cbf1ab7c3c330764ee9a028d23d531","title":"","text":"\"revisionHistoryLimit\": { \"type\": \"integer\", \"format\": \"int32\", \"description\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.\" \"description\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.\" }, \"paused\": { \"type\": \"boolean\","} {"_id":"doc-en-kubernetes-255992049cfd82c505d8119475ce098edbc2212fd4bfff4db1e2a4bc79c4f2a6","title":"","text":"

revisionHistoryLimit

The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.

The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.

false

integer (int32)

"} {"_id":"doc-en-kubernetes-c367cd39395fa11a22e1627a44a210005832955b2844e30bd90d852f960faccc","title":"","text":"// in extensions. These addons are: // - MaxUnavailable during rolling update set to 25% (1 in extensions) // - MaxSurge value during rolling update set to 25% (1 in extensions) // - RevisionHistoryLimit set to 2 (not set in extensions) // - RevisionHistoryLimit set to 10 (not set in extensions) // - ProgressDeadlineSeconds set to 600s (not set in extensions) func SetDefaults_Deployment(obj *appsv1beta2.Deployment) { // Default labels and selector to labels from pod template spec."} {"_id":"doc-en-kubernetes-826e938885a802ccbb961e549d60951becfe180f6e750cce15c0f8ceec7e7440","title":"","text":"} if obj.Spec.RevisionHistoryLimit == nil { obj.Spec.RevisionHistoryLimit = new(int32) *obj.Spec.RevisionHistoryLimit = 2 *obj.Spec.RevisionHistoryLimit = 10 } if obj.Spec.ProgressDeadlineSeconds == nil { obj.Spec.ProgressDeadlineSeconds = new(int32)"} {"_id":"doc-en-kubernetes-d8a3ca33769dc89c5d5b73649839cc958402c550b330c1770ae4f9c3d85424a9","title":"","text":"MaxUnavailable: &defaultIntOrString, }, }, RevisionHistoryLimit: newInt32(2), RevisionHistoryLimit: newInt32(10), ProgressDeadlineSeconds: newInt32(600), Template: defaultTemplate, },"} {"_id":"doc-en-kubernetes-a16f1a85936118302ca65cca921797c09089472881abec5e2e9f02beabeb6f85","title":"","text":"// The number of old ReplicaSets to retain to allow rollback. // This is a pointer to distinguish between explicit zero and not specified. // Defaults to 2. // Defaults to 10. // +optional optional int32 revisionHistoryLimit = 6;"} {"_id":"doc-en-kubernetes-92ca455bcfc0122eccb31aa0a6c9909097875aa9fe5f9511b48c70d9a9920ea3","title":"","text":"// The number of old ReplicaSets to retain to allow rollback. // This is a pointer to distinguish between explicit zero and not specified. // Defaults to 2. // Defaults to 10. // +optional RevisionHistoryLimit *int32 `json:\"revisionHistoryLimit,omitempty\" protobuf:\"varint,6,opt,name=revisionHistoryLimit\"`"} {"_id":"doc-en-kubernetes-114624ad96811c770bac611ca64a979d050931c2c3b896391b29b11ffa6e5389","title":"","text":"\"template\": \"Template describes the pods that will be created.\", \"strategy\": \"The deployment strategy to use to replace existing pods with new ones.\", \"minReadySeconds\": \"Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)\", \"revisionHistoryLimit\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 2.\", \"revisionHistoryLimit\": \"The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.\", \"paused\": \"Indicates that the deployment is paused.\", \"rollbackTo\": \"The config this deployment is rolling back to. Will be cleared after rollback is done.\", \"progressDeadlineSeconds\": \"The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Once autoRollback is implemented, the deployment controller will automatically rollback failed deployments. Note that progress will not be estimated during the time a deployment is paused. Defaults to 600s.\","} {"_id":"doc-en-kubernetes-08dd6b90322f408bd6ffb6fa73901fe2171022d454ea8ef8e56b2c8f771cfa60","title":"","text":"podSpecificFieldsSet[\"spec.nodeName\"] = pod.Spec.NodeName podSpecificFieldsSet[\"spec.restartPolicy\"] = string(pod.Spec.RestartPolicy) podSpecificFieldsSet[\"status.phase\"] = string(pod.Status.Phase) podSpecificFieldsSet[\"status.podIP\"] = string(pod.Status.PodIP) return generic.AddObjectMetaFieldsSet(podSpecificFieldsSet, &pod.ObjectMeta, true) }"} {"_id":"doc-en-kubernetes-e7b2e1d7c0c690d5a21ee1192166fe75fb382e9a8564829b55ad24070eb30ce1","title":"","text":"fieldSelector: fields.ParseSelectorOrDie(\"status.phase=Pending\"), expectMatch: false, }, { in: &api.Pod{ Status: api.PodStatus{PodIP: \"1.2.3.4\"}, }, fieldSelector: fields.ParseSelectorOrDie(\"status.podIP=1.2.3.4\"), expectMatch: true, }, { in: &api.Pod{ Status: api.PodStatus{PodIP: \"1.2.3.4\"}, }, fieldSelector: fields.ParseSelectorOrDie(\"status.podIP=4.3.2.1\"), expectMatch: false, }, } for _, testCase := range testCases { m := MatchPod(labels.Everything(), testCase.fieldSelector)"} {"_id":"doc-en-kubernetes-1e8bad2374e09e248aceb9409fb88cdfb1f931a6a24290ffd69c49dcc6e30ffe","title":"","text":"factory.RegisterFitPredicate(\"CheckNodeDiskPressure\", predicates.CheckNodeDiskPressurePredicate), // Fit is determied by node condtions: not ready, network unavailable and out of disk. factory.RegisterFitPredicate(\"CheckNodeCondition\", predicates.CheckNodeConditionPredicate), factory.RegisterMandatoryFitPredicate(\"CheckNodeCondition\", predicates.CheckNodeConditionPredicate), // Fit is determined by volume zone requirements."} {"_id":"doc-en-kubernetes-5b2e064f429601391f69f016b0102cc95944980dd99611a60f60fd46a1006cbd","title":"","text":"schedulerFactoryMutex sync.Mutex // maps that hold registered algorithm types fitPredicateMap = make(map[string]FitPredicateFactory) mandatoryFitPredicateMap = make(map[string]FitPredicateFactory) priorityFunctionMap = make(map[string]PriorityConfigFactory) algorithmProviderMap = make(map[string]AlgorithmProviderConfig) fitPredicateMap = make(map[string]FitPredicateFactory) mandatoryFitPredicates = sets.NewString() priorityFunctionMap = make(map[string]PriorityConfigFactory) algorithmProviderMap = make(map[string]AlgorithmProviderConfig) // Registered metadata producers priorityMetadataProducer MetadataProducerFactory"} {"_id":"doc-en-kubernetes-5484eacba909ccafafad1366c77c7bd6a8932c89299cf8d84c1efc7e5421c58f","title":"","text":"schedulerFactoryMutex.Lock() defer schedulerFactoryMutex.Unlock() validateAlgorithmNameOrDie(name) mandatoryFitPredicateMap[name] = func(PluginFactoryArgs) algorithm.FitPredicate { return predicate } fitPredicateMap[name] = func(PluginFactoryArgs) algorithm.FitPredicate { return predicate } mandatoryFitPredicates.Insert(name) return name }"} {"_id":"doc-en-kubernetes-bfb207b65fd73b8d2a6b4f82d3b64e6ecec86f6007bbbdc8fa613af81ec59f31","title":"","text":"predicates[name] = factory(args) } // Always include required fit predicates. for name, factory := range mandatoryFitPredicateMap { if _, found := predicates[name]; !found { // Always include mandatory fit predicates. for name := range mandatoryFitPredicates { if factory, found := fitPredicateMap[name]; found { predicates[name] = factory(args) } }"} {"_id":"doc-en-kubernetes-594db835883742bb43ba779ab46fec8c52b303fc80324cb7027b740a79d01e6b","title":"","text":"return nil, apierrors.NewBadRequest(fmt.Sprintf(\"namespace is not allowed on this type: %v\", namespace)) } if len(tokenReview.Spec.Token) == 0 { return nil, apierrors.NewBadRequest(fmt.Sprintf(\"token is required for TokenReview in authentication\")) } if r.tokenAuthenticator == nil { return tokenReview, nil }"} {"_id":"doc-en-kubernetes-b13a0464af31484ccb4645367f6b24e78572734cf0870d50f9bfd04e5c157481","title":"","text":"\"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Initializer\" } }, \"x-kubernetes-patch-merge-key\": \"name\", \"x-kubernetes-patch-strategy\": \"merge\" }, \"result\": { \"description\": \"If result is set with the Failure field, the object will be persisted to storage and then deleted, ensuring that other clients can observe the deletion.\","} {"_id":"doc-en-kubernetes-00f6e638d16a0a37ea10a0c6bc9c4aebd2f04acae4fb2fd3c927cf68a73e413d","title":"","text":"library = \":go_default_library\", deps = [ \"//vendor/k8s.io/api/admissionregistration/v1alpha1:go_default_library\", \"//vendor/k8s.io/api/core/v1:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library\", \"//vendor/k8s.io/apiserver/pkg/admission:go_default_library\", \"//vendor/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-b392d4768b5e4ec38ba8b4f9701639315aa3625cc46f0d18f606d43f20e36f9f","title":"","text":"glog.V(5).Infof(\"Modifying uninitialized resource %s\", a.GetResource()) if updated != nil && len(updated.Pending) == 0 && updated.Result == nil { accessor.SetInitializers(nil) } // because we are called before validation, we need to ensure the update transition is valid. if errs := validation.ValidateInitializersUpdate(updated, existing, initializerFieldPath); len(errs) > 0 { return errors.NewInvalid(a.GetKind().GroupKind(), a.GetName(), errs)"} {"_id":"doc-en-kubernetes-01425a101c0c1b2fd73b8d2bc70fef93beaeaad32e0c7a9c28431d5d8ca2cadd","title":"","text":"import ( \"reflect\" \"strings\" \"testing\" \"k8s.io/api/admissionregistration/v1alpha1\" \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/meta\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apiserver/pkg/admission\" \"k8s.io/apiserver/pkg/authorization/authorizer\" ) func newInitializer(name string, rules ...v1alpha1.Rule) *v1alpha1.InitializerConfiguration {"} {"_id":"doc-en-kubernetes-0f9f274c04977fb1074ac181e7ef95e4c893aaf2a94e311c62f7c080adc14284","title":"","text":"}) } } type fakeAuthorizer struct { accept bool } func (f *fakeAuthorizer) Authorize(a authorizer.Attributes) (bool, string, error) { if f.accept { return true, \"\", nil } return false, \"denied\", nil } func TestAdmitUpdate(t *testing.T) { tests := []struct { name string oldInitializers *metav1.Initializers newInitializers *metav1.Initializers verifyUpdatedObj func(runtime.Object) (pass bool, reason string) err string }{ { name: \"updates on initialized resources are allowed\", oldInitializers: nil, newInitializers: nil, err: \"\", }, { name: \"updates on initialized resources are allowed\", oldInitializers: &metav1.Initializers{Pending: []metav1.Initializer{{Name: \"init.k8s.io\"}}}, newInitializers: &metav1.Initializers{}, verifyUpdatedObj: func(obj runtime.Object) (bool, string) { accessor, err := meta.Accessor(obj) if err != nil { return false, \"cannot get accessor\" } if accessor.GetInitializers() != nil { return false, \"expect nil initializers\" } return true, \"\" }, err: \"\", }, { name: \"initializers may not be set once initialized\", oldInitializers: nil, newInitializers: &metav1.Initializers{Pending: []metav1.Initializer{{Name: \"init.k8s.io\"}}}, err: \"field is immutable once initialization has completed\", }, } plugin := initializer{ config: nil, authorizer: &fakeAuthorizer{true}, } for _, tc := range tests { oldObj := &v1.Pod{} oldObj.Initializers = tc.oldInitializers newObj := &v1.Pod{} newObj.Initializers = tc.newInitializers a := admission.NewAttributesRecord(newObj, oldObj, schema.GroupVersionKind{}, \"\", \"foo\", schema.GroupVersionResource{}, \"\", admission.Update, nil) err := plugin.Admit(a) switch { case tc.err == \"\" && err != nil: t.Errorf(\"%q: unexpected error: %v\", tc.name, err) case tc.err != \"\" && err == nil: t.Errorf(\"%q: unexpected no error, expected %s\", tc.name, tc.err) case tc.err != \"\" && err != nil && !strings.Contains(err.Error(), tc.err): t.Errorf(\"%q: expected %s, got %v\", tc.name, tc.err, err) } } } "} {"_id":"doc-en-kubernetes-d4ac7484cef37c602e20c0bc0cf38db926a0854f0b2b7ca26235d364663302ba","title":"","text":"} } allErrs = append(allErrs, validateInitializersResult(initializers.Result, fldPath.Child(\"result\"))...) if len(initializers.Pending) == 0 && initializers.Result == nil { allErrs = append(allErrs, field.Invalid(fldPath.Child(\"pending\"), nil, \"must be non-empty when result is not set\")) } return allErrs }"} {"_id":"doc-en-kubernetes-bf73b18dd7d0b67dfa06befef6dc54cfba138adc92502d08f654db184492311c","title":"","text":"// When the last pending initializer is removed, and no failing result is set, the initializers // struct will be set to nil and the object is considered as initialized and visible to all // clients. // +patchMergeKey=name // +patchStrategy=merge repeated Initializer pending = 1; // If result is set with the Failure field, the object will be persisted to storage and then deleted,"} {"_id":"doc-en-kubernetes-e1a20082ad8416cd865c5124cb9e376b4f6c23708b6a62b67197329cf305543f","title":"","text":"// When the last pending initializer is removed, and no failing result is set, the initializers // struct will be set to nil and the object is considered as initialized and visible to all // clients. Pending []Initializer `json:\"pending\" protobuf:\"bytes,1,rep,name=pending\"` // +patchMergeKey=name // +patchStrategy=merge Pending []Initializer `json:\"pending\" protobuf:\"bytes,1,rep,name=pending\" patchStrategy:\"merge\" patchMergeKey:\"name\"` // If result is set with the Failure field, the object will be persisted to storage and then deleted, // ensuring that other clients can observe the deletion. Result *Status `json:\"result,omitempty\" protobuf:\"bytes,2,opt,name=result\"`"} {"_id":"doc-en-kubernetes-f02a54711f24675c5038ae8dc0c58a59d20e1b7e2dfb13d058e85e0e640612cc","title":"","text":"Expect(err).NotTo(HaveOccurred()) Expect(len(pods.Items)).Should(Equal(1)) }) It(\"will be set to nil if a patch removes the last pending initializer\", func() { ns := f.Namespace.Name c := f.ClientSet podName := \"to-be-patch-initialized-pod\" framework.Logf(\"Creating pod %s\", podName) // TODO: lower the timeout so that the server responds faster. _, err := c.CoreV1().Pods(ns).Create(newUninitializedPod(podName)) if err != nil && !errors.IsTimeout(err) { framework.Failf(\"expect err to be timeout error, got %v\", err) } uninitializedPod, err := c.CoreV1().Pods(ns).Get(podName, metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred()) Expect(uninitializedPod.Initializers).NotTo(BeNil()) Expect(len(uninitializedPod.Initializers.Pending)).Should(Equal(1)) patch := fmt.Sprintf(`{\"metadata\":{\"initializers\":{\"pending\":[{\"$patch\":\"delete\",\"name\":\"%s\"}]}}}`, uninitializedPod.Initializers.Pending[0].Name) patchedPod, err := c.CoreV1().Pods(ns).Patch(uninitializedPod.Name, types.StrategicMergePatchType, []byte(patch)) Expect(err).NotTo(HaveOccurred()) Expect(patchedPod.Initializers).To(BeNil()) }) }) func newUninitializedPod(podName string) *v1.Pod {"} {"_id":"doc-en-kubernetes-41364cae11ef91ab6fef33c9d3c40b7404cf50ad97c7069294e74b4ad483a2f0","title":"","text":"}) func cleanTest(f *framework.Framework, block bool) { // delete the APIService first to avoid causing discovery errors aggrclient := f.AggregatorClient _ = aggrclient.ApiregistrationV1beta1().APIServices().Delete(\"v1alpha1.wardle.k8s.io\", nil) namespace := \"sample-system\" client := f.ClientSet _ = client.ExtensionsV1beta1().Deployments(namespace).Delete(\"sample-apiserver\", nil)"} {"_id":"doc-en-kubernetes-df0f6e5f93b4fb7027f5ac8b3af9157e61fd95e6753d0ed955755c2ace77491b","title":"","text":"_ = client.CoreV1().Namespaces().Delete(namespace, nil) _ = client.RbacV1beta1().ClusterRoles().Delete(\"wardler\", nil) _ = client.RbacV1beta1().ClusterRoleBindings().Delete(\"wardler:sample-system:anonymous\", nil) aggrclient := f.AggregatorClient _ = aggrclient.ApiregistrationV1beta1().APIServices().Delete(\"v1alpha1.wardle.k8s.io\", nil) if block { _ = wait.Poll(100*time.Millisecond, 5*time.Second, func() (bool, error) { _, err := client.CoreV1().Namespaces().Get(\"sample-system\", metav1.GetOptions{})"} {"_id":"doc-en-kubernetes-503caa161f127cf003fe0230428393ccb584f252a4155a9b1930e45a04f5a6d8","title":"","text":"return numPods, missingTimestamp, nil } // isDynamicDiscoveryError returns true if the error is a group discovery error // only for groups expected to be created/deleted dynamically during e2e tests func isDynamicDiscoveryError(err error) bool { if !discovery.IsGroupDiscoveryFailedError(err) { return false } discoveryErr := err.(*discovery.ErrGroupDiscoveryFailed) for gv := range discoveryErr.Groups { switch gv.Group { case \"mygroup.example.com\": // custom_resource_definition // garbage_collector case \"wardle.k8s.io\": // aggregator default: Logf(\"discovery error for unexpected group: %#v\", gv) return false } } return false } // hasRemainingContent checks if there is remaining content in the namespace via API discovery func hasRemainingContent(c clientset.Interface, clientPool dynamic.ClientPool, namespace string) (bool, error) { // some tests generate their own framework.Client rather than the default"} {"_id":"doc-en-kubernetes-afc4b130a3aacbae6727a66bf60081f398e4d2d07e6effcb5f2bb19f764418e4","title":"","text":"// find out what content is supported on the server resources, err := c.Discovery().ServerPreferredNamespacedResources() if err != nil { if err != nil && !isDynamicDiscoveryError(err) { return false, err } groupVersionResources, err := discovery.GroupVersionResources(resources) if err != nil { if err != nil && !isDynamicDiscoveryError(err) { return false, err }"} {"_id":"doc-en-kubernetes-dff9f5ab70232651d5a516b447fb07f2c7746ceae3d9a4d4ca2b0d94395118a6","title":"","text":"} debugLogThresholdsWithObservation(\"thresholds - reclaim not satisfied\", thresholds, observations) // determine the set of thresholds whose stats have been updated since the last sync thresholds = thresholdsUpdatedStats(thresholds, observations, m.lastObservations) debugLogThresholdsWithObservation(\"thresholds - updated stats\", thresholds, observations) // track when a threshold was first observed now := m.clock.Now() thresholdsFirstObservedAt := thresholdsFirstObservedAt(thresholds, m.thresholdsFirstObservedAt, now)"} {"_id":"doc-en-kubernetes-549ce1a78c80994e00378dfd267fae11e51d740b50a2d8b9815cd5bed4a0aed8","title":"","text":"m.thresholdsFirstObservedAt = thresholdsFirstObservedAt m.nodeConditionsLastObservedAt = nodeConditionsLastObservedAt m.thresholdsMet = thresholds // determine the set of thresholds whose stats have been updated since the last sync thresholds = thresholdsUpdatedStats(thresholds, observations, m.lastObservations) debugLogThresholdsWithObservation(\"thresholds - updated stats\", thresholds, observations) m.lastObservations = observations m.Unlock()"} {"_id":"doc-en-kubernetes-c6e29b77585ac90173bc2af9250c8d321c16a4abb8495a885c0621969e4172b6","title":"","text":"color: bfe5bf - name: do-not-merge color: e11d21 - name: do-not-merge/work-in-progress color: e11d21 - name: do-not-merge/hold color: e11d21 - name: do-not-merge/cherry-pick-not-approved color: e11d21 - name: do-not-merge/release-note-label-needed color: e11d21 - name: do-not-merge/blocked-paths color: e11d21 - name: flake-has-meta color: fbca04 - name: for-new-contributors"} {"_id":"doc-en-kubernetes-2a700cdbf8ead0239350ff6f2452546fa5b359b4e941acece1749e238c97340e","title":"","text":"\"k8s.io/api/core/v1\" \"k8s.io/client-go/tools/record\" \"k8s.io/kubernetes/pkg/kubelet/cadvisor\" kubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\" \"k8s.io/kubernetes/pkg/util/mount\" )"} {"_id":"doc-en-kubernetes-e4cc679c71a8b35f7213aa3fce2be2705ba80adfd98f099dc69ec417de2dd50a","title":"","text":"// without needing to be deleted and recreated. if firewallExists { glog.Infof(\"EnsureLoadBalancer(%v(%v)): updating firewall\", loadBalancerName, serviceName) if err := gce.updateFirewall(apiService, makeFirewallName(loadBalancerName), gce.region, desc, sourceRanges, ports, hosts); err != nil { if err := gce.updateFirewall(apiService, MakeFirewallName(loadBalancerName), gce.region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } glog.Infof(\"EnsureLoadBalancer(%v(%v)): updated firewall\", loadBalancerName, serviceName) } else { glog.Infof(\"EnsureLoadBalancer(%v(%v)): creating firewall\", loadBalancerName, serviceName) if err := gce.createFirewall(apiService, makeFirewallName(loadBalancerName), gce.region, desc, sourceRanges, ports, hosts); err != nil { if err := gce.createFirewall(apiService, MakeFirewallName(loadBalancerName), gce.region, desc, sourceRanges, ports, hosts); err != nil { return nil, err } glog.Infof(\"EnsureLoadBalancer(%v(%v)): created firewall\", loadBalancerName, serviceName)"} {"_id":"doc-en-kubernetes-ada1f517ec193eaf4494d9d9a638207502deb31622172aa6aabb2599f9f0477f","title":"","text":"// target pool to use local traffic health check. glog.V(2).Infof(\"Updating from nodes health checks to local traffic health checks for service %v LB %v\", apiService.Name, loadBalancerName) if supportsNodesHealthCheck { hcToDelete = makeHttpHealthCheck(makeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort()) hcToDelete = makeHttpHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort()) } tpNeedsUpdate = true }"} {"_id":"doc-en-kubernetes-6a25fbb6202b6acf8987967929e64df33a775bc431494e30ac0a5a381795f498","title":"","text":"tpNeedsUpdate = true } if supportsNodesHealthCheck { hcToCreate = makeHttpHealthCheck(makeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort()) hcToCreate = makeHttpHealthCheck(MakeNodesHealthCheckName(clusterID), GetNodesHealthCheckPath(), GetNodesHealthCheckPort()) } } // Now we get to some slightly more interesting logic."} {"_id":"doc-en-kubernetes-23f44da23a103ac5a8b1082916bc6ae95062ed219194728d1b3b4625eef68df0","title":"","text":"// using local traffic health check or nodes health check. Attempt to delete // both to prevent leaking. hcNames = append(hcNames, loadBalancerName) hcNames = append(hcNames, makeNodesHealthCheckName(clusterID)) hcNames = append(hcNames, MakeNodesHealthCheckName(clusterID)) } errs := utilerrors.AggregateGoroutines( func() error { fwName := makeFirewallName(loadBalancerName) fwName := MakeFirewallName(loadBalancerName) err := ignoreNotFound(gce.DeleteFirewall(fwName)) if isForbidden(err) && gce.OnXPN() { glog.V(4).Infof(\"ensureExternalLoadBalancerDeleted(%v): do not have permission to delete firewall rule (on XPN). Raising event.\", loadBalancerName)"} {"_id":"doc-en-kubernetes-887ec4e7657ebf94d9b9189c52643b5cb1fc0c617ff5478b5ca01e56b5569504","title":"","text":"} func (gce *GCECloud) firewallNeedsUpdate(name, serviceName, region, ipAddress string, ports []v1.ServicePort, sourceRanges netsets.IPNet) (exists bool, needsUpdate bool, err error) { fw, err := gce.service.Firewalls.Get(gce.NetworkProjectID(), makeFirewallName(name)).Do() fw, err := gce.service.Firewalls.Get(gce.NetworkProjectID(), MakeFirewallName(name)).Do() if err != nil { if isHTTPErrorCode(err, http.StatusNotFound) { return false, true, nil"} {"_id":"doc-en-kubernetes-b6c67e3c51a2ac267a8176d85be700004edf0f7fff6690b138e6c56c9c40f118","title":"","text":"return fmt.Sprintf(`{\"kubernetes.io/service-name\":\"%s\"}`, serviceName) } // makeNodesHealthCheckName returns name of the health check resource used by // MakeNodesHealthCheckName returns name of the health check resource used by // the GCE load balancers (l4) for performing health checks on nodes. func makeNodesHealthCheckName(clusterID string) string { func MakeNodesHealthCheckName(clusterID string) string { return fmt.Sprintf(\"k8s-%v-node\", clusterID) }"} {"_id":"doc-en-kubernetes-93b51d4109c1d347e68ac422e30e66b378c7501b2966944b7893eda473c0014d","title":"","text":"// balancers (l4) for performing health checks. func MakeHealthCheckFirewallName(clusterID, hcName string, isNodesHealthCheck bool) string { if isNodesHealthCheck { return makeNodesHealthCheckName(clusterID) + \"-http-hc\" return MakeNodesHealthCheckName(clusterID) + \"-http-hc\" } return \"k8s-\" + hcName + \"-http-hc\" } func makeFirewallName(name string) string { // MakeFirewallName returns the firewall name used by the GCE load // balancers (l4) for serving traffic. func MakeFirewallName(name string) string { return fmt.Sprintf(\"k8s-fw-%s\", name) }"} {"_id":"doc-en-kubernetes-0b7a8c86353338395f1f5ab121b15f01a9d87b1dc794f1e34dd5fabdcd16cf68","title":"","text":"if err != nil { return fmt.Errorf(\"error parsing GCE/GKE region from zone %q: %v\", zone, err) } if err := gceCloud.DeleteFirewall(loadBalancerName); err != nil && if err := gceCloud.DeleteFirewall(gcecloud.MakeFirewallName(loadBalancerName)); err != nil && !IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) { retErr = err }"} {"_id":"doc-en-kubernetes-ddd74c86c935f204f0b9c6a38a3f0a0e56742eb9d3ce3effd34b4534a66409ff","title":"","text":"!IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) { retErr = fmt.Errorf(\"%vn%v\", retErr, err) } var hcNames []string clusterID, err := GetClusterID(c) if err != nil { retErr = fmt.Errorf(\"%vn%v\", retErr, err) return } hcNames := []string{gcecloud.MakeNodesHealthCheckName(clusterID)} hc, getErr := gceCloud.GetHttpHealthCheck(loadBalancerName) if getErr != nil && !IsGoogleAPIHTTPErrorCode(getErr, http.StatusNotFound) { retErr = fmt.Errorf(\"%vn%v\", retErr, getErr)"} {"_id":"doc-en-kubernetes-3bcaed23624eef856a77b52010582319ea83184e4c568dd9fb0273cc65779481","title":"","text":"if hc != nil { hcNames = append(hcNames, hc.Name) } clusterID, err := GetClusterID(c) if err != nil { retErr = fmt.Errorf(\"%vn%v\", retErr, err) return } if err := gceCloud.DeleteExternalTargetPoolAndChecks(nil, loadBalancerName, region, clusterID, hcNames...); err != nil && !IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) { retErr = fmt.Errorf(\"%vn%v\", retErr, err)"} {"_id":"doc-en-kubernetes-e7fb43584f267c652d776e3a392f9cd64cdd0f65aca3e4af3061571f83f78288","title":"","text":"// check the status of containers. for idx, container := range pod.Spec.Containers { containerStatus := podStatus.FindContainerStatusByName(container.Name) // Call internal container post-stop lifecycle hook for any non-running container so that any // allocated cpus are released immediately. If the container is restarted, cpus will be re-allocated // to it. if containerStatus != nil && containerStatus.State != kubecontainer.ContainerStateRunning { if err := m.internalLifecycle.PostStopContainer(containerStatus.ID.ID); err != nil { glog.Errorf(\"internal container post-stop lifecycle hook failed for container %v in pod %v with error %v\", container.Name, pod.Name, err) } } // If container does not exist, or is not running, check whether we // need to restart it. if containerStatus == nil || containerStatus.State != kubecontainer.ContainerStateRunning {"} {"_id":"doc-en-kubernetes-eb6b032c61e23b3db74b4bb4c3182a87070589122df9f19a09cb11ecdeaa6a0e","title":"","text":"kind: ConfigMap apiVersion: v1 metadata: name: fluentd-es-config-v0.1.5 name: fluentd-es-config-v0.1.6 namespace: kube-system labels: addonmanager.kubernetes.io/mode: Reconcile"} {"_id":"doc-en-kubernetes-e4b8edbd14cb886848cc19640672c822d3b66645c8cb94e6b313a1516d532c8b","title":"","text":"@type kubernetes_metadata # Concatenate multi-line logs @type concat key message multiline_end_regexp /n$/ separator \"\" @id elasticsearch @type elasticsearch"} {"_id":"doc-en-kubernetes-871614931650ed3a51def763568e348c6de819708ff912e72ebc2746f4b7424c","title":"","text":"apiVersion: apps/v1 kind: DaemonSet metadata: name: fluentd-es-v2.2.0 name: fluentd-es-v2.2.1 namespace: kube-system labels: k8s-app: fluentd-es version: v2.2.0 version: v2.2.1 kubernetes.io/cluster-service: \"true\" addonmanager.kubernetes.io/mode: Reconcile spec: selector: matchLabels: k8s-app: fluentd-es version: v2.2.0 version: v2.2.1 template: metadata: labels: k8s-app: fluentd-es kubernetes.io/cluster-service: \"true\" version: v2.2.0 version: v2.2.1 # This annotation ensures that fluentd does not get evicted if the node # supports critical pod annotation based priority scheme. # Note that this does not guarantee admission on the nodes (#40573)."} {"_id":"doc-en-kubernetes-a7eb6e7241809e6815da98ca6c47619bba895e5b6df6dabc926a431952318ae8","title":"","text":"path: /var/lib/docker/containers - name: config-volume configMap: name: fluentd-es-config-v0.1.5 name: fluentd-es-config-v0.1.6 "} {"_id":"doc-en-kubernetes-6964297b4e88ca2a5c469430288d17b267d86f6067a3062959f1f04c544d1ee4","title":"","text":"gem 'fluentd', '<=1.2.4' gem 'activesupport', '~>5.2.1' gem 'fluent-plugin-kubernetes_metadata_filter', '~>2.0.0' gem 'fluent-plugin-elasticsearch', '~>2.11.5' gem 'fluent-plugin-systemd', '~>1.0.1' gem 'fluent-plugin-concat', '~>2.3.0' gem 'fluent-plugin-detect-exceptions', '~>0.0.11' gem 'fluent-plugin-prometheus', '~>1.0.1' gem 'fluent-plugin-elasticsearch', '~>2.11.5' gem 'fluent-plugin-kubernetes_metadata_filter', '~>2.0.0' gem 'fluent-plugin-multi-format-parser', '~>1.0.0' gem 'fluent-plugin-prometheus', '~>1.0.1' gem 'fluent-plugin-systemd', '~>1.0.1' gem 'oj', '~>3.6.5'"} {"_id":"doc-en-kubernetes-77e750066502e15a14a2b0c897d4fcdfe48ba6122f6b9d5a2fdd8650dcbcc28d","title":"","text":"local network=$(make-gcloud-network-argument \"${NETWORK_PROJECT}\" \"${REGION}\" \"${NETWORK}\" \"${NETWORK}\" \"${SUBNETWORK:-}\" \"\" \"${ENABLE_IP_ALIASES:-}\" "} {"_id":"doc-en-kubernetes-fcf7762745bb346d3a10532398d7ba29550e1c01ab4de40bc3e722d73830d6d9","title":"","text":"glog.V(2).Infof(\"Deleted obsolete listener: %s\", listener.ID) } status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} portID := loadbalancer.VipPortID floatIP, err := getFloatingIPByPortID(lbaas.network, portID) if err != nil && err != ErrNotFound {"} {"_id":"doc-en-kubernetes-f28a59d923115966a16c028f02a9d52dd2ff20c9185955f3f4dfbc2d27330d9f","title":"","text":"return nil, fmt.Errorf(\"Error creating LB floatingip %+v: %v\", floatIPOpts, err) } } status := &v1.LoadBalancerStatus{} if floatIP != nil { status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) status.Ingress = []v1.LoadBalancerIngress{{IP: floatIP.FloatingIP}} } else { status.Ingress = []v1.LoadBalancerIngress{{IP: loadbalancer.VipAddress}} } if lbaas.opts.ManageSecurityGroups {"} {"_id":"doc-en-kubernetes-c8daf83783ed76f337a8a26b78cc92e66d2a215bf83d28566b9364a546814f9d","title":"","text":"} status := &v1.LoadBalancerStatus{} status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} if floatingPool != \"\" && !internalAnnotation { floatIPOpts := floatingips.CreateOpts{ FloatingNetworkID: floatingPool,"} {"_id":"doc-en-kubernetes-f7b6b4c5943cf12122452692e870eb568dc14403673bf0023f8e21ca56e915ff","title":"","text":"return nil, fmt.Errorf(\"Error creating floatingip for openstack load balancer %s: %v\", name, err) } status.Ingress = append(status.Ingress, v1.LoadBalancerIngress{IP: floatIP.FloatingIP}) status.Ingress = []v1.LoadBalancerIngress{{IP: floatIP.FloatingIP}} } else { status.Ingress = []v1.LoadBalancerIngress{{IP: vip.Address}} } return status, nil"} {"_id":"doc-en-kubernetes-47343a80e8d1281325a41ddfed4e8259b011e7336892062471e7f5a64a25e083","title":"","text":"return \"\", err } if len(volumeSource.TargetWWNs) != 0 { // API server validates these parameters beforehand but attach/detach // controller creates volumespec without validation. They may be nil // or zero length. We should check again to avoid unexpected conditions. if len(volumeSource.TargetWWNs) != 0 && volumeSource.Lun != nil { // TargetWWNs are the FibreChannel target worldwide names return fmt.Sprintf(\"%v\", volumeSource.TargetWWNs), nil return fmt.Sprintf(\"%v:%v\", volumeSource.TargetWWNs, *volumeSource.Lun), nil } else if len(volumeSource.WWIDs) != 0 { // WWIDs are the FibreChannel World Wide Identifiers return fmt.Sprintf(\"%v\", volumeSource.WWIDs), nil"} {"_id":"doc-en-kubernetes-e5c8483e0fd57170719a0efe1d3fd4a984fd7fabe30d65a0d84daa2044de7560","title":"","text":"// attempted before returning. // // In case there is a pod with the same namespace+name already running, this // function assumes it's an older instance of the recycler pod and watches // this old pod instead of starting a new one. // function deletes it as it is not able to judge if it is an old recycler // or user has forged a fake recycler to block Kubernetes from recycling.// // // pod - the pod designed by a volume plugin to recycle the volume. pod.Name // will be overwritten with unique name based on PV.Name."} {"_id":"doc-en-kubernetes-5f1f95bcec70bab9f2169a1fbe59576f98b511fb9a208e42bff64bf1c053df58","title":"","text":"_, err = recyclerClient.CreatePod(pod) if err != nil { if errors.IsAlreadyExists(err) { glog.V(5).Infof(\"old recycler pod %q found for volume\", pod.Name) deleteErr := recyclerClient.DeletePod(pod.Name, pod.Namespace) if deleteErr != nil { return fmt.Errorf(\"failed to delete old recycler pod %s/%s: %s\", pod.Namespace, pod.Name, deleteErr) } // Recycler will try again and the old pod will be hopefuly deleted // at that time. return fmt.Errorf(\"old recycler pod found, will retry later\") } else { return fmt.Errorf(\"unexpected error creating recycler pod: %+vn\", err) } } defer func(pod *v1.Pod) { glog.V(2).Infof(\"deleting recycler pod %s/%s\", pod.Namespace, pod.Name) if err := recyclerClient.DeletePod(pod.Name, pod.Namespace); err != nil { glog.Errorf(\"failed to delete recycler pod %s/%s: %v\", pod.Namespace, pod.Name, err) } }(pod) err = waitForPod(pod, recyclerClient, podCh) // In all cases delete the recycler pod and log its result. glog.V(2).Infof(\"deleting recycler pod %s/%s\", pod.Namespace, pod.Name) deleteErr := recyclerClient.DeletePod(pod.Name, pod.Namespace) if deleteErr != nil { glog.Errorf(\"failed to delete recycler pod %s/%s: %v\", pod.Namespace, pod.Name, err) } // Returning recycler error is preferred, the pod will be deleted again on // the next retry. if err != nil { return fmt.Errorf(\"failed to recycle volume: %s\", err) } // Recycle succeeded but we failed to delete the recycler pod. Report it, // the controller will re-try recycling the PV again shortly. if deleteErr != nil { return fmt.Errorf(\"failed to delete recycler pod: %s\", deleteErr) } return nil } // Now only the old pod or the new pod run. Watch it until it finishes // and send all events on the pod to the PV // waitForPod watches the pod it until it finishes and send all events on the // pod to the PV. func waitForPod(pod *v1.Pod, recyclerClient recyclerClient, podCh <-chan watch.Event) error { for { event, ok := <-podCh if !ok {"} {"_id":"doc-en-kubernetes-5d6592288aa7d34884225e944d1ceff27b62c9dad43463e3df3d43e8473ff0fa","title":"","text":"{v1.EventTypeWarning, \"Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount\"}, {v1.EventTypeWarning, \"Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"default\"/\"recycler-for-podRecyclerFailure\". list of unattached/unmounted\"}, }, expectedError: \"Pod was active on the node longer than specified deadline\", expectedError: \"failed to recycle volume: Pod was active on the node longer than specified deadline\", }, { // Recycler pod gets deleted"} {"_id":"doc-en-kubernetes-e903a29cc05de3825d6b42d70570ef8f7fbe23237bff6057969caacdc7a60dc0","title":"","text":"expectedEvents: []mockEvent{ {v1.EventTypeNormal, \"Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1\"}, }, expectedError: \"recycler pod was deleted\", expectedError: \"failed to recycle volume: recycler pod was deleted\", }, { // Another recycler pod is already running name: \"RecyclerRunning\", existingPod: newPod(\"podOldRecycler\", v1.PodRunning, \"\"), createPod: newPod(\"podNewRecycler\", v1.PodFailed, \"mock message\"), eventSequence: []watch.Event{ // Old pod succeeds newPodEvent(watch.Modified, \"podOldRecycler\", v1.PodSucceeded, \"\"), }, // No error = old pod succeeded. If the new pod was used, there // would be error with \"mock message\". expectedError: \"\", }, { // Another recycler pod is already running and fails name: \"FailedRecyclerRunning\", existingPod: newPod(\"podOldRecycler\", v1.PodRunning, \"\"), createPod: newPod(\"podNewRecycler\", v1.PodFailed, \"mock message\"), eventSequence: []watch.Event{ // Old pod failure newPodEvent(watch.Modified, \"podOldRecycler\", v1.PodFailed, \"Pod was active on the node longer than specified deadline\"), }, // If the new pod was used, there would be error with \"mock message\". expectedError: \"Pod was active on the node longer than specified deadline\", name: \"RecyclerRunning\", existingPod: newPod(\"podOldRecycler\", v1.PodRunning, \"\"), createPod: newPod(\"podNewRecycler\", v1.PodFailed, \"mock message\"), eventSequence: []watch.Event{}, expectedError: \"old recycler pod found, will retry later\", }, }"} {"_id":"doc-en-kubernetes-bf2ee9670f979d1744ac30dd938b92b05c6a2d9df0b9ba044892811b29fbba00","title":"","text":"pkg_tar( name = \"kubernetes-cni-data\", package_dir = \"/opt/cni\", package_dir = \"/opt/cni/bin\", deps = [\"@kubernetes_cni//file\"], )"} {"_id":"doc-en-kubernetes-fd8be5741dc110ef4631bf288d3e606f293dfc0ae10266b478bfc09bced52efd","title":"","text":"func ValidatePersistentVolumeUpdate(newPv, oldPv *api.PersistentVolume) field.ErrorList { allErrs := field.ErrorList{} allErrs = ValidatePersistentVolume(newPv) // PersistentVolumeSource should be immutable after creation. if !apiequality.Semantic.DeepEqual(newPv.Spec.PersistentVolumeSource, oldPv.Spec.PersistentVolumeSource) { allErrs = append(allErrs, field.Forbidden(field.NewPath(\"spec\", \"persistentvolumesource\"), \"is immutable after creation\")) } newPv.Status = oldPv.Status return allErrs }"} {"_id":"doc-en-kubernetes-51516f153605ec2de71f4c339301056b39fe8b792c203be17eae243a24341a21","title":"","text":"} func TestValidatePersistentVolumeSourceUpdate(t *testing.T) { validVolume := testVolume(\"foo\", \"\", api.PersistentVolumeSpec{ Capacity: api.ResourceList{ api.ResourceName(api.ResourceStorage): resource.MustParse(\"1G\"), }, AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce}, PersistentVolumeSource: api.PersistentVolumeSource{ HostPath: &api.HostPathVolumeSource{ Path: \"/foo\", Type: newHostPathType(string(api.HostPathDirectory)), }, }, StorageClassName: \"valid\", }) validPvSourceNoUpdate := validVolume.DeepCopy() invalidPvSourceUpdateType := validVolume.DeepCopy() invalidPvSourceUpdateType.Spec.PersistentVolumeSource = api.PersistentVolumeSource{ FlexVolume: &api.FlexVolumeSource{ Driver: \"kubernetes.io/blue\", FSType: \"ext4\", }, } invalidPvSourceUpdateDeep := validVolume.DeepCopy() invalidPvSourceUpdateDeep.Spec.PersistentVolumeSource = api.PersistentVolumeSource{ HostPath: &api.HostPathVolumeSource{ Path: \"/updated\", Type: newHostPathType(string(api.HostPathDirectory)), }, } scenarios := map[string]struct { isExpectedFailure bool oldVolume *api.PersistentVolume newVolume *api.PersistentVolume }{ \"condition-no-update\": { isExpectedFailure: false, oldVolume: validVolume, newVolume: validPvSourceNoUpdate, }, \"condition-update-source-type\": { isExpectedFailure: true, oldVolume: validVolume, newVolume: invalidPvSourceUpdateType, }, \"condition-update-source-deep\": { isExpectedFailure: true, oldVolume: validVolume, newVolume: invalidPvSourceUpdateDeep, }, } for name, scenario := range scenarios { errs := ValidatePersistentVolumeUpdate(scenario.newVolume, scenario.oldVolume) if len(errs) == 0 && scenario.isExpectedFailure { t.Errorf(\"Unexpected success for scenario: %s\", name) } if len(errs) > 0 && !scenario.isExpectedFailure { t.Errorf(\"Unexpected failure for scenario: %s - %+v\", name, errs) } } } func TestValidateLocalVolumes(t *testing.T) { scenarios := map[string]struct { isExpectedFailure bool"} {"_id":"doc-en-kubernetes-70f7c3973e1944b7e36a52a18ef0997d43079892ffd33990cf9e5f43624b504e","title":"","text":"- /heapster - --source=kubernetes.summary_api:'' - --sink=gcm - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.0 - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.1 name: eventer command: - /eventer"} {"_id":"doc-en-kubernetes-b03003efa85513d5dd4732a8825fcadab0a5a18894f6293ce6c536a75184e192","title":"","text":"- --memory={{base_eventer_memory}} - --extra-memory={{eventer_memory_per_node}}Ki - --threshold=5 - --deployment=heapster-v1.5.0-beta.0 - --deployment=heapster-v1.5.0-beta.1 - --container=eventer - --poll-period=300000 - --estimator=exponential"} {"_id":"doc-en-kubernetes-aaff41258be579f78d0d063743f4a84f29cf18b92bcb427d29bb5cde428fd62c","title":"","text":"- --source=kubernetes.summary_api:'' - --sink=influxdb:http://monitoring-influxdb:8086 - --sink=gcm:?metrics=autoscaling - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.0 - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.1 name: eventer command: - /eventer"} {"_id":"doc-en-kubernetes-1fbcfc41bcab4b03faf160d7b90f6140b8ac2eac1659774b7a32af1c6382e8c8","title":"","text":"- /heapster - --source=kubernetes.summary_api:'' - --sink=influxdb:http://monitoring-influxdb:8086 - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.0 - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.1 name: eventer command: - /eventer"} {"_id":"doc-en-kubernetes-f04305706aa28e13bfc7ffe45704d4bbd821bca711461f61a9dc45a3ef92578f","title":"","text":"- --memory={{ base_eventer_memory }} - --extra-memory={{ eventer_memory_per_node }}Ki - --threshold=5 - --deployment=heapster-v1.5.0-beta.0 - --deployment=heapster-v1.5.0-beta.1 - --container=eventer - --poll-period=300000 - --estimator=exponential"} {"_id":"doc-en-kubernetes-8cda9c5aec8d359f167555e1cf3520644f513865efb86611976844c42b1ab64a","title":"","text":"- --memory={{ base_metrics_memory }} - --extra-memory={{metrics_memory_per_node}}Mi - --threshold=5 - --deployment=heapster-v1.5.0-beta.0 - --deployment=heapster-v1.5.0-beta.1 - --container=heapster - --poll-period=300000 - --estimator=exponential"} {"_id":"doc-en-kubernetes-f72c6ba30f0da440f3ffdb43ec0df341d7ab541a13dfe01cb15a4a7a61ebe474","title":"","text":"apiVersion: extensions/v1beta1 kind: Deployment metadata: name: heapster-v1.5.0-beta.0 name: heapster-v1.5.0-beta.1 namespace: kube-system labels: k8s-app: heapster kubernetes.io/cluster-service: \"true\" addonmanager.kubernetes.io/mode: Reconcile version: v1.5.0-beta.0 version: v1.5.0-beta.1 spec: replicas: 1 selector: matchLabels: k8s-app: heapster version: v1.5.0-beta.0 version: v1.5.0-beta.1 template: metadata: labels: k8s-app: heapster version: v1.5.0-beta.0 version: v1.5.0-beta.1 annotations: scheduler.alpha.kubernetes.io/critical-pod: '' spec: containers: - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.0 - image: gcr.io/google_containers/heapster-amd64:v1.5.0-beta.1 name: heapster livenessProbe: httpGet:"} {"_id":"doc-en-kubernetes-69dae384c5d32bc7a7113fdccf5ad106e2f4343d3bf6548fabc20e1694308049","title":"","text":"- --memory={{ base_metrics_memory }} - --extra-memory={{ metrics_memory_per_node }}Mi - --threshold=5 - --deployment=heapster-v1.5.0-beta.0 - --deployment=heapster-v1.5.0-beta.1 - --container=heapster - --poll-period=300000 - --estimator=exponential"} {"_id":"doc-en-kubernetes-bb50e0fe1ec5028b27e3af3b072c25332b3f306bfb0169f44a943d1e5163c806","title":"","text":"func diskConsumingPod(name string, diskConsumedMB int, volumeSource *v1.VolumeSource, resources v1.ResourceRequirements) *v1.Pod { // Each iteration writes 1 Mb, so do diskConsumedMB iterations. return podWithCommand(volumeSource, resources, name, fmt.Sprintf(\"i=0; while [ $i -lt %d ];\", diskConsumedMB)+\" do dd if=/dev/urandom of=%s${i} bs=1048576 count=1; i=$(($i+1)); done; while true; do sleep 5; done\") return podWithCommand(volumeSource, resources, name, fmt.Sprintf(\"i=0; while [ $i -lt %d ];\", diskConsumedMB)+\" do dd if=/dev/urandom of=%s${i} bs=1048576 count=1 2>/dev/null ; i=$(($i+1)); done; while true; do sleep 5; done\") } // podWithCommand returns a pod with the provided volumeSource and resourceRequirements."} {"_id":"doc-en-kubernetes-eb3cbbe26e97a43a8835c0288a3427c1759b665076b100e85c745fe31f4b7d9c","title":"","text":"EmptyDir: &v1.EmptyDirVolumeSource{SizeLimit: &sizeLimit}, }, v1.ResourceRequirements{}), }, { evictionPriority: 0, // This pod should not be evicted because it uses less than its limit pod: diskConsumingPod(\"emptydir-disk-below-sizelimit\", useUnderLimit, nil, v1.ResourceRequirements{Limits: containerLimit}), }, }) }) })"} {"_id":"doc-en-kubernetes-7a61bcd1623b0b56c2d809c0946194ffdb2968b8a13414f41ece21303317f6d9","title":"","text":"}, { evictionPriority: 0, pod: diskConsumingPod(\"guaranteed-disk\", 299 /* Mb */, nil, v1.ResourceRequirements{ // Only require 99% accuracy (297/300 Mb) because on some OS distributions, the file itself (excluding contents), consumes disk space. pod: diskConsumingPod(\"guaranteed-disk\", 297 /* Mb */, nil, v1.ResourceRequirements{ Requests: v1.ResourceList{ v1.ResourceEphemeralStorage: resource.MustParse(\"300Mi\"), },"} {"_id":"doc-en-kubernetes-89b5167e3be311ca17ca0cbb1a5562591cfa0f681ca13685a94fbdb26eb43315","title":"","text":"\"persistent_volumes-vsphere.go\", \"pv_reclaimpolicy.go\", \"pvc_label_selector.go\", \"volume_expand.go\", \"volume_io.go\", \"volume_metrics.go\", \"volume_provisioning.go\","} {"_id":"doc-en-kubernetes-9d818088a744e544319bd24101cfe4b02a8b269891f77d27cd35f1a1643a6bc6","title":"","text":" /* Copyright 2017 The Kubernetes Authors. 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. */ package storage import ( \"fmt\" \"time\" . \"github.com/onsi/ginkgo\" . \"github.com/onsi/gomega\" \"k8s.io/api/core/v1\" storage \"k8s.io/api/storage/v1\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/wait\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/kubernetes/test/e2e/framework\" ) const ( resizePollInterval = 2 * time.Second // total time to wait for cloudprovider or file system resize to finish totalResizeWaitPeriod = 20 * time.Minute ) var _ = SIGDescribe(\"Volume expand [Feature:ExpandPersistentVolumes] [Slow]\", func() { var ( c clientset.Interface ns string err error pvc *v1.PersistentVolumeClaim resizableSc *storage.StorageClass ) f := framework.NewDefaultFramework(\"volume-expand\") BeforeEach(func() { framework.SkipUnlessProviderIs(\"aws\", \"gce\") c = f.ClientSet ns = f.Namespace.Name framework.ExpectNoError(framework.WaitForAllNodesSchedulable(c, framework.TestContext.NodeSchedulableTimeout)) test := storageClassTest{ name: \"default\", claimSize: \"2Gi\", } resizableSc, err = createResizableStorageClass(test, ns, \"resizing\", c) Expect(err).NotTo(HaveOccurred(), \"Error creating resizable storage class\") Expect(*resizableSc.AllowVolumeExpansion).To(BeTrue()) pvc = newClaim(test, ns, \"default\") pvc.Spec.StorageClassName = &resizableSc.Name pvc, err = c.CoreV1().PersistentVolumeClaims(pvc.Namespace).Create(pvc) Expect(err).NotTo(HaveOccurred(), \"Error creating pvc\") }) AfterEach(func() { framework.ExpectNoError(framework.DeletePersistentVolumeClaim(c, pvc.Name, pvc.Namespace)) framework.ExpectNoError(c.StorageV1().StorageClasses().Delete(resizableSc.Name, nil)) }) It(\"Verify if editing PVC allows resize\", func() { By(\"Waiting for pvc to be in bound phase\") pvcClaims := []*v1.PersistentVolumeClaim{pvc} pvs, err := framework.WaitForPVClaimBoundPhase(c, pvcClaims, framework.ClaimProvisionTimeout) Expect(err).NotTo(HaveOccurred(), \"Failed waiting for PVC to be bound %v\", err) Expect(len(pvs)).To(Equal(1)) By(\"Creating a pod with dynamically provisioned volume\") pod, err := framework.CreatePod(c, ns, nil, pvcClaims, false, \"\") Expect(err).NotTo(HaveOccurred(), \"While creating pods for resizing\") defer func() { err = framework.DeletePodWithWait(f, c, pod) Expect(err).NotTo(HaveOccurred(), \"while cleaning up pod already deleted in resize test\") }() By(\"Expanding current pvc\") newSize := resource.MustParse(\"6Gi\") pvc, err = expandPVCSize(pvc, newSize, c) Expect(err).NotTo(HaveOccurred(), \"While updating pvc for more size\") Expect(pvc).NotTo(BeNil()) pvcSize := pvc.Spec.Resources.Requests[v1.ResourceStorage] if pvcSize.Cmp(newSize) != 0 { framework.Failf(\"error updating pvc size %q\", pvc.Name) } By(\"Waiting for cloudprovider resize to finish\") err = waitForControllerVolumeResize(pvc, c) Expect(err).NotTo(HaveOccurred(), \"While waiting for pvc resize to finish\") By(\"Checking for conditions on pvc\") pvc, err = c.CoreV1().PersistentVolumeClaims(ns).Get(pvc.Name, metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred(), \"While fetching pvc after controller resize\") inProgressConditions := pvc.Status.Conditions Expect(len(inProgressConditions)).To(Equal(1), \"pvc must have resize condition\") Expect(inProgressConditions[0].Type).To(Equal(v1.PersistentVolumeClaimResizing), \"pvc must have resizing condition\") By(\"Deleting the previously created pod\") err = framework.DeletePodWithWait(f, c, pod) Expect(err).NotTo(HaveOccurred(), \"while deleting pod for resizing\") By(\"Creating a new pod with same volume\") pod2, err := framework.CreatePod(c, ns, nil, pvcClaims, false, \"\") Expect(err).NotTo(HaveOccurred(), \"while recreating pod for resizing\") defer func() { err = framework.DeletePodWithWait(f, c, pod2) Expect(err).NotTo(HaveOccurred(), \"while cleaning up pod before exiting resizing test\") }() By(\"Waiting for file system resize to finish\") pvc, err = waitForFSResize(pvc, c) Expect(err).NotTo(HaveOccurred(), \"while waiting for fs resize to finish\") pvcConditions := pvc.Status.Conditions Expect(len(pvcConditions)).To(Equal(0), \"pvc should not have conditions\") }) }) func createResizableStorageClass(t storageClassTest, ns string, suffix string, c clientset.Interface) (*storage.StorageClass, error) { stKlass := newStorageClass(t, ns, suffix) allowExpansion := true stKlass.AllowVolumeExpansion = &allowExpansion var err error stKlass, err = c.StorageV1().StorageClasses().Create(stKlass) return stKlass, err } func expandPVCSize(origPVC *v1.PersistentVolumeClaim, size resource.Quantity, c clientset.Interface) (*v1.PersistentVolumeClaim, error) { pvcName := origPVC.Name updatedPVC := origPVC.DeepCopy() waitErr := wait.PollImmediate(resizePollInterval, 30*time.Second, func() (bool, error) { var err error updatedPVC, err = c.CoreV1().PersistentVolumeClaims(origPVC.Namespace).Get(pvcName, metav1.GetOptions{}) if err != nil { return false, fmt.Errorf(\"error fetching pvc %q for resizing with %v\", pvcName, err) } updatedPVC.Spec.Resources.Requests[v1.ResourceStorage] = size updatedPVC, err = c.CoreV1().PersistentVolumeClaims(origPVC.Namespace).Update(updatedPVC) if err == nil { return true, nil } framework.Logf(\"Error updating pvc %s with %v\", pvcName, err) return false, nil }) return updatedPVC, waitErr } func waitForControllerVolumeResize(pvc *v1.PersistentVolumeClaim, c clientset.Interface) error { pvName := pvc.Spec.VolumeName return wait.PollImmediate(resizePollInterval, totalResizeWaitPeriod, func() (bool, error) { pvcSize := pvc.Spec.Resources.Requests[v1.ResourceStorage] pv, err := c.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{}) if err != nil { return false, fmt.Errorf(\"error fetching pv %q for resizing %v\", pvName, err) } pvSize := pv.Spec.Capacity[v1.ResourceStorage] // If pv size is greater or equal to requested size that means controller resize is finished. if pvSize.Cmp(pvcSize) >= 0 { return true, nil } return false, nil }) } func waitForFSResize(pvc *v1.PersistentVolumeClaim, c clientset.Interface) (*v1.PersistentVolumeClaim, error) { var updatedPVC *v1.PersistentVolumeClaim waitErr := wait.PollImmediate(resizePollInterval, totalResizeWaitPeriod, func() (bool, error) { var err error updatedPVC, err = c.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{}) if err != nil { return false, fmt.Errorf(\"error fetching pvc %q for checking for resize status : %v\", pvc.Name, err) } pvcSize := updatedPVC.Spec.Resources.Requests[v1.ResourceStorage] pvcStatusSize := updatedPVC.Status.Capacity[v1.ResourceStorage] //If pvc's status field size is greater than or equal to pvc's size then done if pvcStatusSize.Cmp(pvcSize) >= 0 { return true, nil } return false, nil }) return updatedPVC, waitErr } "} {"_id":"doc-en-kubernetes-ec4496e4dae76b7aa8b079415d4c52f1411816793b784f5e81badf200201770a","title":"","text":"// InstanceType returns the type of the specified instance. func (m *metadata) InstanceType(name types.NodeName) (string, error) { instanceType, err := m.get(metadataTypeInstanceType) if err == nil { if err != nil { return \"\", fmt.Errorf(\"could not get instance type: %v\", err) }"} {"_id":"doc-en-kubernetes-a74a50776bd1fe5d033aef35b5b7d95e0a5f1927fcd8d7b3a56eeb3472b6a9f4","title":"","text":"Skip(\"Nvidia GPUs do not exist on the node. Skipping test.\") } framework.WaitForAllNodesSchedulable(f.ClientSet, framework.TestContext.NodeSchedulableTimeout) By(\"Creating the Google Device Plugin pod for NVIDIA GPU in GKE\") devicePluginPod = f.PodClient().CreateSync(framework.NVIDIADevicePlugin(f.Namespace.Name))"} {"_id":"doc-en-kubernetes-b7ecde21091f29728036710b2836880d94181d7f7fcce8019439c9b6239a3f3b","title":"","text":"f.PodClient().Delete(devicePluginPod.Name, &metav1.DeleteOptions{}) By(\"Waiting for GPUs to become unavailable on the local node\") Eventually(func() bool { return framework.NumberOfNVIDIAGPUs(getLocalNode(f)) <= 0 node, err := f.ClientSet.CoreV1().Nodes().Get(framework.TestContext.NodeName, metav1.GetOptions{}) framework.ExpectNoError(err) return framework.NumberOfNVIDIAGPUs(node) <= 0 }, 10*time.Minute, framework.Poll).Should(BeTrue()) By(\"Checking that scheduled pods can continue to run even after we delete device plugin.\") count1, devIdRestart1 = getDeviceId(f, p1.Name, p1.Name, count1+1)"} {"_id":"doc-en-kubernetes-cfa410b76dc232dbccd91cb6e9989917f9aba5a94dacfb4d1858ba1c390dbef2","title":"","text":"glog.V(6).Infof(\"Resizing is not enabled for this volume %s\", volumeToMount.VolumeName) return nil } mounter := og.volumePluginMgr.Host.GetMounter(pluginName) // Get expander, if possible expandableVolumePlugin, _ :="} {"_id":"doc-en-kubernetes-ee909260cac657b14668d7d0bcdc63938e045dc4ef05d3022ad4fd33c44fae3d","title":"","text":"// File system resize was requested, proceed glog.V(4).Infof(volumeToMount.GenerateMsgDetailed(\"MountVolume.resizeFileSystem entering\", fmt.Sprintf(\"DevicePath %q\", volumeToMount.DevicePath))) if volumeToMount.VolumeSpec.ReadOnly { simpleMsg, detailedMsg := volumeToMount.GenerateMsg(\"MountVolume.resizeFileSystem failed\", \"requested read-only file system\") glog.Warningf(detailedMsg) og.recorder.Eventf(volumeToMount.Pod, v1.EventTypeWarning, kevents.FileSystemResizeFailed, simpleMsg) return nil } diskFormatter := &mount.SafeFormatAndMount{ Interface: mounter, Exec: og.volumePluginMgr.Host.GetExec(expandableVolumePlugin.GetPluginName()),"} {"_id":"doc-en-kubernetes-4338e374ad06d2d3af778017002009afb6dc9c08b26741f979f0c8ec708926d4","title":"","text":"} pvcCopy.Status.Capacity = capacity pvcCopy.Status.Conditions = []v1.PersistentVolumeClaimCondition{} newData, err := json.Marshal(pvcCopy) if err != nil {"} {"_id":"doc-en-kubernetes-2e04f0468901ec53d15c336f410f9a4909307cce2f86a8713a7c980fbf5114c3","title":"","text":"Accelerators utilfeature.Feature = \"Accelerators\" // owner: @jiayingz // alpha: v1.8 // beta: v1.10 // // Enables support for Device Plugins // Only Nvidia GPUs are tested as of v1.8. DevicePlugins utilfeature.Feature = \"DevicePlugins\" // owner: @gmarek"} {"_id":"doc-en-kubernetes-cafeab30dd76638bee2d04bcf96549e3194a7aec7e1ff417945dae7b87d701c3","title":"","text":"ExperimentalHostUserNamespaceDefaultingGate: {Default: false, PreRelease: utilfeature.Beta}, ExperimentalCriticalPodAnnotation: {Default: false, PreRelease: utilfeature.Alpha}, Accelerators: {Default: false, PreRelease: utilfeature.Alpha}, DevicePlugins: {Default: false, PreRelease: utilfeature.Alpha}, DevicePlugins: {Default: true, PreRelease: utilfeature.Beta}, TaintBasedEvictions: {Default: false, PreRelease: utilfeature.Alpha}, RotateKubeletServerCertificate: {Default: false, PreRelease: utilfeature.Alpha}, RotateKubeletClientCertificate: {Default: true, PreRelease: utilfeature.Beta},"} {"_id":"doc-en-kubernetes-e406e600d848a8694d498b3cec6860bff6b964156ad27ab34424f0e4ca66d20e","title":"","text":"}, Spec: storage.VolumeAttachmentSpec{ NodeName: node, Attacher: csiPluginName, Attacher: csiSource.Driver, Source: storage.VolumeAttachmentSource{ PersistentVolumeName: &pvName, },"} {"_id":"doc-en-kubernetes-41a4a2db3ef44211e00acdc14cad6997666e824166e524fba535a36896334272","title":"","text":"}, Spec: storage.VolumeAttachmentSpec{ NodeName: nodeName, Attacher: csiPluginName, Attacher: \"mock\", Source: storage.VolumeAttachmentSource{ PersistentVolumeName: &pvName, },"} {"_id":"doc-en-kubernetes-146fa887ad19cab936b33504d7ba7e23de0d2b1b1f2c4b9ad11d404ca43cf060","title":"","text":"// This is a temporary workaround to get stats for cri-o from cadvisor // and should be removed. // Related to https://github.com/kubernetes/kubernetes/issues/51798 if i.runtimeEndpoint == \"/var/run/crio.sock\" { if i.runtimeEndpoint == CrioSocket { return cadvisorfs.LabelCrioImages, nil } }"} {"_id":"doc-en-kubernetes-4f222672f2fc9be43f3c5f9d25e309f048f981809aeddaf1a74b367fd5556bb8","title":"","text":"kubetypes \"k8s.io/kubernetes/pkg/kubelet/types\" ) const ( // Please keep this in sync with the one in: // github.com/google/cadvisor/container/crio/client.go CrioSocket = \"/var/run/crio/crio.sock\" ) func CapacityFromMachineInfo(info *cadvisorapi.MachineInfo) v1.ResourceList { c := v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity("} {"_id":"doc-en-kubernetes-10600eae4ef9becac0fb8ff2e0ba6df47c73a62bbeb7e3949e4a503fe9f35f79","title":"","text":"func UsingLegacyCadvisorStats(runtime, runtimeEndpoint string) bool { return runtime == kubetypes.RktContainerRuntime || (runtime == kubetypes.DockerContainerRuntime && goruntime.GOOS == \"linux\") || runtimeEndpoint == \"/var/run/crio.sock\" runtimeEndpoint == CrioSocket }"} {"_id":"doc-en-kubernetes-1cb2ebc315c942ba008645f752d0271cc995bb26c7eecee639c40dc8d69ba2a4","title":"","text":"} if !s.LeaderElection.LeaderElect { run(nil) stopCh := make(chan struct{}) defer close(stopCh) run(stopCh) panic(\"unreachable\") }"} {"_id":"doc-en-kubernetes-1fedaaf725933839bb739ed47b99aef56db4d161b7888745b0f529bbb61bb99a","title":"","text":"var _ Manager = &manager{} // NewManager creates new cpu manager based on provided policy func NewManager( cpuPolicyName string, reconcilePeriod time.Duration, machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, stateFileDirecory string, ) (Manager, error) { func NewManager(cpuPolicyName string, reconcilePeriod time.Duration, machineInfo *cadvisorapi.MachineInfo, nodeAllocatableReservation v1.ResourceList, stateFileDirecory string) (Manager, error) { var policy Policy switch policyName(cpuPolicyName) {"} {"_id":"doc-en-kubernetes-7540ff9e51a9061fe0223e93a63f7fa93d0d7be1a5d63d651fea8b839c7791f0","title":"","text":"glog.Infof(\"[cpumanager] detected CPU topology: %v\", topo) reservedCPUs, ok := nodeAllocatableReservation[v1.ResourceCPU] if !ok { // The static policy cannot initialize without this information. Panic! panic(\"[cpumanager] unable to determine reserved CPU resources for static policy\") // The static policy cannot initialize without this information. return nil, fmt.Errorf(\"[cpumanager] unable to determine reserved CPU resources for static policy\") } if reservedCPUs.IsZero() { // Panic! // // The static policy requires this to be nonzero. Zero CPU reservation // would allow the shared pool to be completely exhausted. At that point // either we would violate our guarantee of exclusivity or need to evict // any pod that has at least one container that requires zero CPUs. // See the comments in policy_static.go for more details. panic(\"[cpumanager] the static policy requires systemreserved.cpu + kubereserved.cpu to be greater than zero\") return nil, fmt.Errorf(\"[cpumanager] the static policy requires systemreserved.cpu + kubereserved.cpu to be greater than zero\") } // Take the ceiling of the reservation, since fractional CPUs cannot be"} {"_id":"doc-en-kubernetes-bf45d8d68ad99acd2abe4796ef93d1ecde8df7effd820edc93ec69f1f9ee5c6c","title":"","text":"cpuPolicyName string nodeAllocatableReservation v1.ResourceList isTopologyBroken bool panicMsg string expectedPolicy string expectedError error skipIfPermissionsError bool"} {"_id":"doc-en-kubernetes-c8a2bb6a494ab466503ffa0129e8e18b25c7d451442f5ecfb58c1f3bcc96d205","title":"","text":"description: \"static policy - broken reservation\", cpuPolicyName: \"static\", nodeAllocatableReservation: v1.ResourceList{}, panicMsg: \"unable to determine reserved CPU resources for static policy\", expectedError: fmt.Errorf(\"unable to determine reserved CPU resources for static policy\"), skipIfPermissionsError: true, }, { description: \"static policy - no CPU resources\", cpuPolicyName: \"static\", nodeAllocatableReservation: v1.ResourceList{v1.ResourceCPU: *resource.NewQuantity(0, resource.DecimalSI)}, panicMsg: \"the static policy requires systemreserved.cpu + kubereserved.cpu to be greater than zero\", expectedError: fmt.Errorf(\"the static policy requires systemreserved.cpu + kubereserved.cpu to be greater than zero\"), skipIfPermissionsError: true, }, }"} {"_id":"doc-en-kubernetes-df3ddd727e274dc639316beef21dbcb5f6e9d9bc89e1e13e68231e340b9f8967","title":"","text":"t.Errorf(\"cannot create state file: %s\", err.Error()) } defer os.RemoveAll(sDir) defer func() { if err := recover(); err != nil { if testCase.panicMsg != \"\" { if !strings.Contains(err.(string), testCase.panicMsg) { t.Errorf(\"Unexpected panic message. Have: %q wants %q\", err, testCase.panicMsg) } } else { t.Errorf(\"Unexpected panic: %q\", err) } } else if testCase.panicMsg != \"\" { t.Error(\"Expected panic hasn't been raised\") } }() mgr, err := NewManager(testCase.cpuPolicyName, 5*time.Second, machineInfo, testCase.nodeAllocatableReservation, sDir) if testCase.expectedError != nil {"} {"_id":"doc-en-kubernetes-f80351ae56f53c5134dad04131e4702ba667fcbe5d2b1d82696873f17663b1ab","title":"","text":"EnableLogsHandler: true, EventTTL: 1 * time.Hour, MasterCount: 1, EndpointReconcilerType: string(reconcilers.MasterCountReconcilerType), EndpointReconcilerType: string(reconcilers.LeaseEndpointReconcilerType), KubeletConfig: kubeletclient.KubeletClientConfig{ Port: ports.KubeletPort, ReadOnlyPort: ports.KubeletReadOnlyPort,"} {"_id":"doc-en-kubernetes-09680e3262b9b2f951126be9f6b608ea8db399aa66ef69308bc574ef88318d6a","title":"","text":"\"Currently only applies to long-running requests.\") fs.IntVar(&s.MasterCount, \"apiserver-count\", s.MasterCount, \"The number of apiservers running in the cluster, must be a positive number.\") \"The number of apiservers running in the cluster, must be a positive number. (In use when --endpoint-reconciler-type=master-count is enabled.)\") fs.StringVar(&s.EndpointReconcilerType, \"endpoint-reconciler-type\", string(s.EndpointReconcilerType), \"Use an endpoint reconciler (\"+strings.Join(reconcilers.AllTypes.Names(), \", \")+\")\")"} {"_id":"doc-en-kubernetes-10d0aa78c13b119ed245ef846721e4d8a39c8ecadab7f80d4a5a6787613a4264","title":"","text":"\"--enable-aggregator-routing=true\", \"--enable-logs-handler=false\", \"--enable-swagger-ui=true\", \"--endpoint-reconciler-type=\" + string(reconcilers.MasterCountReconcilerType), \"--endpoint-reconciler-type=\" + string(reconcilers.LeaseEndpointReconcilerType), \"--etcd-quorum-read=false\", \"--etcd-keyfile=/var/run/kubernetes/etcd.key\", \"--etcd-certfile=/var/run/kubernetes/etcdce.crt\","} {"_id":"doc-en-kubernetes-d1b30d97cd0e0e59d61ebbd49afe67c86775098a0cfb21c2a59c076c0f257dad","title":"","text":"ServiceNodePortRange: kubeoptions.DefaultServiceNodePortRange, ServiceClusterIPRange: kubeoptions.DefaultServiceIPCIDR, MasterCount: 5, EndpointReconcilerType: string(reconcilers.MasterCountReconcilerType), EndpointReconcilerType: string(reconcilers.LeaseEndpointReconcilerType), AllowPrivileged: false, GenericServerRunOptions: &apiserveroptions.ServerRunOptions{ AdvertiseAddress: net.ParseIP(\"192.168.10.10\"),"} {"_id":"doc-en-kubernetes-d6e32ebe3341c84fb05ee36c95c650393c68eed98d0bd0c5a2cf65cfbccf326a","title":"","text":"local message=$1 local match=$2 if echo \"$message\" | grep -q \"$match\"; then if grep -q \"${match}\" <<< \"${message}\"; then echo \"Successful\" echo \"message:$message\" echo \"has:$match\""} {"_id":"doc-en-kubernetes-fee8b9316b5629e75a744506a7d43028367bb33e10f28e934065c725631905c0","title":"","text":"local message=$1 local match=$2 if echo \"$message\" | grep -q \"$match\"; then if grep -q \"${match}\" <<< \"${message}\"; then echo \"FAIL!\" echo \"message:$message\" echo \"has:$match\""} {"_id":"doc-en-kubernetes-910f41f856332f87a73d5a738243f1be032d61980135945cdf5b624af50f7b53","title":"","text":"print('File %s is missing the year' % filename, file=verbose_out) return False # Replace all occurrences of the regex \"2017|2016|2015|2014\" with \"YEAR\" # Replace all occurrences of the regex \"2014|2015|2016|2017|2018\" with \"YEAR\" p = regexs[\"date\"] for i, d in enumerate(data): (data[i], found) = p.subn('YEAR', d)"} {"_id":"doc-en-kubernetes-d1565eca7123ff1fa5617204bf3887f75dc24f9343548d981923cf3f253178de","title":"","text":"regexs = {} # Search for \"YEAR\" which exists in the boilerplate, but shouldn't in the real thing regexs[\"year\"] = re.compile( 'YEAR' ) # dates can be 2014, 2015, 2016, or 2017; company holder names can be anything regexs[\"date\"] = re.compile( '(2014|2015|2016|2017)' ) # dates can be 2014, 2015, 2016, 2017, or 2018; company holder names can be anything regexs[\"date\"] = re.compile( '(2014|2015|2016|2017|2018)' ) # strip // +build nn build constraints regexs[\"go_build_constraints\"] = re.compile(r\"^(// +build.*n)+n\", re.MULTILINE) # strip #!.* from shell scripts"} {"_id":"doc-en-kubernetes-6973b944b84ca0fc05b7f6446c2f4dd838f4455d1e3f72096424379c89588904","title":"","text":"BASH_TARGETS=\" update-generated-protobuf update-codegen update-generated-runtime update-generated-device-plugin update-generated-docs update-generated-swagger-docs update-swagger-spec"} {"_id":"doc-en-kubernetes-d36aec6395e170c851a4b1f6f201813ceab2685cf505fa9073dc4de4d0d1886f","title":"","text":"// +build !ignore_autogenerated /* Copyright 2017 The Kubernetes Authors. Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License."} {"_id":"doc-en-kubernetes-98e8dc46352bf836ee18b0b8346ea7878c67be5cacb4840ab8ba5574c8aa6258","title":"","text":"/* Copyright 2017 The Kubernetes Authors. Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License."} {"_id":"doc-en-kubernetes-cf46d539e11a5c819473fefbc11923df9e90dbeb0d6519e7a811d876303eaccf","title":"","text":"} service, err := e.serviceLister.Services(namespace).Get(name) if err != nil { // Delete the corresponding endpoint, as the service has been deleted. // TODO: Please note that this will delete an endpoint when a // service is deleted. However, if we're down at the time when // the service is deleted, we will miss that deletion, so this // doesn't completely solve the problem. See #6877. err = e.client.CoreV1().Endpoints(namespace).Delete(name, nil) if err != nil && !errors.IsNotFound(err) { return err } // Service has been deleted. So no need to do any more operations. return nil }"} {"_id":"doc-en-kubernetes-2507d67511c601618582f67a4b66fdc122b57e5d867128aa83e113ceda77aaa0","title":"","text":"// See http://docs.openstack.org/user-guide/cli_config_drive.html type Metadata struct { Uuid string `json:\"uuid\"` Name string `json:\"name\"` Hostname string `json:\"hostname\"` AvailabilityZone string `json:\"availability_zone\"` Devices []DeviceMetadata `json:\"devices,omitempty\"` // .. and other fields we don't care about. Expand as necessary."} {"_id":"doc-en-kubernetes-2dcfdc32ec95f4a7c39964bb257c621e0b48bf7cde9833a9babbee93209b4ccd","title":"","text":"var FakeMetadata = Metadata{ Uuid: \"83679162-1378-4288-a2d4-70e13ec132aa\", Name: \"test\", Hostname: \"test\", AvailabilityZone: \"nova\", }"} {"_id":"doc-en-kubernetes-9b3c0be1af1fcfc6c5565e331c94052767e0d1955ac32604551aee76f62faaa7","title":"","text":"t.Fatalf(\"Should succeed when provided with valid data: %s\", err) } if md.Name != \"test\" { t.Errorf(\"incorrect name: %s\", md.Name) if md.Hostname != \"test.novalocal\" { t.Errorf(\"incorrect hostname: %s\", md.Hostname) } if md.Uuid != \"83679162-1378-4288-a2d4-70e13ec132aa\" {"} {"_id":"doc-en-kubernetes-ea210561d5459a056231c6e2865f3341d910de65b2ac7bbd198d750fe8249168","title":"","text":"if err != nil { return \"\", err } return types.NodeName(md.Name), nil return types.NodeName(md.Hostname), nil } func (i *Instances) AddSSHKeyToAllInstances(user string, keyData []byte) error {"} {"_id":"doc-en-kubernetes-a3db1245724005909221303552e1f5f3dc0a6c36a64d5ab6277a91c317d91c29","title":"","text":"\"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/util/sets\" utilflag \"k8s.io/apiserver/pkg/util/flag\" clientset \"k8s.io/client-go/kubernetes\" kubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\" kubeadmapiext \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha1\""} {"_id":"doc-en-kubernetes-af2a865f75f458840d2d6a74b05e08274255148314b53661531e1f664d2d793d","title":"","text":") flagSet.StringVar(featureGatesString, \"feature-gates\", *featureGatesString, \"A set of key=value pairs that describe feature gates for various features. \"+ \"Options are:n\"+strings.Join(features.KnownFeatures(&features.InitFeatureGates), \"n\")) flagSet.Var(utilflag.NewMapStringString(&cfg.APIServerExtraArgs), \"apiserver-extra-args\", \"A set of extra flags to pass to the API Server or override default ones in form of =\") flagSet.Var(utilflag.NewMapStringString(&cfg.ControllerManagerExtraArgs), \"controller-manager-extra-args\", \"A set of extra flags to pass to the Controller Manager or override default ones in form of =\") flagSet.Var(utilflag.NewMapStringString(&cfg.SchedulerExtraArgs), \"scheduler-extra-args\", \"A set of extra flags to pass to the Scheduler or override default ones in form of =\") } // AddInitOtherFlags adds init flags that are not bound to a configuration file to the given flagset"} {"_id":"doc-en-kubernetes-f0473ff09a293093d3529c174ab174f30eb61dc636e513d5f2219f318bfa6121","title":"","text":"\"//vendor/github.com/spf13/pflag:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library\", \"//vendor/k8s.io/apiserver/pkg/util/flag:go_default_library\", \"//vendor/k8s.io/client-go/kubernetes:go_default_library\", \"//vendor/k8s.io/client-go/tools/bootstrap/token/api:go_default_library\", \"//vendor/k8s.io/client-go/tools/bootstrap/token/util:go_default_library\","} {"_id":"doc-en-kubernetes-a339bbde268e18c08b6b5f91da6de880b52314221e6c8b8d2c3f0621e2d5965c","title":"","text":"\"github.com/spf13/cobra\" utilflag \"k8s.io/apiserver/pkg/util/flag\" kubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\" kubeadmapiext \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/v1alpha1\" \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation\""} {"_id":"doc-en-kubernetes-dff712e8ca38bf6b81a9f16e47c4c22f94de6ce6b9bbf9b03913ffe44037e3fe","title":"","text":"cmd.Flags().StringVar(&cfg.Networking.ServiceSubnet, \"service-cidr\", cfg.Networking.ServiceSubnet, \"The range of IP address used for service VIPs\") cmd.Flags().StringVar(&featureGatesString, \"feature-gates\", featureGatesString, \"A set of key=value pairs that describe feature gates for various features. \"+ \"Options are:n\"+strings.Join(features.KnownFeatures(&features.InitFeatureGates), \"n\")) cmd.Flags().Var(utilflag.NewMapStringString(&cfg.APIServerExtraArgs), \"apiserver-extra-args\", \"A set of extra flags to pass to the API Server or override default ones in form of =\") } if properties.use == \"all\" || properties.use == \"controller-manager\" { cmd.Flags().StringVar(&cfg.Networking.PodSubnet, \"pod-network-cidr\", cfg.Networking.PodSubnet, \"The range of IP addresses used for the Pod network\") cmd.Flags().Var(utilflag.NewMapStringString(&cfg.ControllerManagerExtraArgs), \"controller-manager-extra-args\", \"A set of extra flags to pass to the Controller Manager or override default ones in form of =\") } if properties.use == \"all\" || properties.use == \"scheduler\" { cmd.Flags().Var(utilflag.NewMapStringString(&cfg.SchedulerExtraArgs), \"scheduler-extra-args\", \"A set of extra flags to pass to the Scheduler or override default ones in form of =\") } cmd.Flags().StringVar(&cfgPath, \"config\", cfgPath, \"Path to kubeadm config file (WARNING: Usage of a configuration file is experimental)\")"} {"_id":"doc-en-kubernetes-69afbcfd34f1b190931caa8543af2ece9f4b2e8dd48dcabc6786b4f2527282d7","title":"","text":"} func (plugin *fcPlugin) ConstructVolumeSpec(volumeName, mountPath string) (*volume.Spec, error) { fcVolume := &v1.Volume{ Name: volumeName, VolumeSource: v1.VolumeSource{ FC: &v1.FCVolumeSource{}, }, // Find globalPDPath from pod volume directory(mountPath) // examples: // mountPath: pods/{podUid}/volumes/kubernetes.io~fc/{volumeName} // globalPDPath : plugins/kubernetes.io/fc/50060e801049cfd1-lun-0 var globalPDPath string mounter := plugin.host.GetMounter(plugin.GetPluginName()) paths, err := mount.GetMountRefs(mounter, mountPath) if err != nil { return nil, err } for _, path := range paths { if strings.Contains(path, plugin.host.GetPluginDir(fcPluginName)) { globalPDPath = path break } } // Couldn't fetch globalPDPath if len(globalPDPath) == 0 { return nil, fmt.Errorf(\"couldn't fetch globalPDPath. failed to obtain volume spec\") } arr := strings.Split(globalPDPath, \"/\") if len(arr) < 1 { return nil, fmt.Errorf(\"failed to retrieve volume plugin information from globalPDPath: %v\", globalPDPath) } volumeInfo := arr[len(arr)-1] // Create volume from wwn+lun or wwid var fcVolume *v1.Volume if strings.Contains(volumeInfo, \"-lun-\") { wwnLun := strings.Split(volumeInfo, \"-lun-\") if len(wwnLun) < 2 { return nil, fmt.Errorf(\"failed to retrieve TargetWWN and Lun. volumeInfo is invalid: %v\", volumeInfo) } lun, err := strconv.Atoi(wwnLun[1]) if err != nil { return nil, err } lun32 := int32(lun) fcVolume = &v1.Volume{ Name: volumeName, VolumeSource: v1.VolumeSource{ FC: &v1.FCVolumeSource{TargetWWNs: []string{wwnLun[0]}, Lun: &lun32}, }, } glog.V(5).Infof(\"ConstructVolumeSpec: TargetWWNs: %v, Lun: %v\", fcVolume.VolumeSource.FC.TargetWWNs, *fcVolume.VolumeSource.FC.Lun) } else { fcVolume = &v1.Volume{ Name: volumeName, VolumeSource: v1.VolumeSource{ FC: &v1.FCVolumeSource{WWIDs: []string{volumeInfo}}, }, } glog.V(5).Infof(\"ConstructVolumeSpec: WWIDs: %v\", fcVolume.VolumeSource.FC.WWIDs) } return volume.NewSpecFromVolume(fcVolume), nil }"} {"_id":"doc-en-kubernetes-908d1bd8b7835072528d95421854f86333b0f2ccb4a72e0f91d6409b640bea9d","title":"","text":"// - If a file is found, then retreives volumePluginDependentPath from globalMapPathUUID. // - Once volumePluginDependentPath is obtained, store volume information to VolumeSource // examples: // mapPath: pods/{podUid}}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName} // mapPath: pods/{podUid}/{DefaultKubeletVolumeDevicesDirName}/{escapeQualifiedPluginName}/{volumeName} // globalMapPathUUID : plugins/kubernetes.io/{PluginName}/{DefaultKubeletVolumeDevicesDirName}/{volumePluginDependentPath}/{pod uuid} func (plugin *fcPlugin) ConstructBlockVolumeSpec(podUID types.UID, volumeName, mapPath string) (*volume.Spec, error) { pluginDir := plugin.host.GetVolumeDevicePluginDir(fcPluginName)"} {"_id":"doc-en-kubernetes-b4441c5008802d3640636a25558ed03e298ff82ded4370b86b3b2e0b03de2461","title":"","text":"v1.FCVolumeSource{TargetWWNs: []string{wwnLun[0]}, Lun: &lun32}) glog.V(5).Infof(\"ConstructBlockVolumeSpec: TargetWWNs: %v, Lun: %v\", fcPV.Spec.PersistentVolumeSource.FC.TargetWWNs, fcPV.Spec.PersistentVolumeSource.FC.Lun) *fcPV.Spec.PersistentVolumeSource.FC.Lun) } else { fcPV = createPersistentVolumeFromFCVolumeSource(volumeName, v1.FCVolumeSource{WWIDs: []string{volumeInfo}})"} {"_id":"doc-en-kubernetes-317ac14dc627508473d67d8543531c23a7f8b3b8c7f6d72270102d2074c3b396","title":"","text":"import ( \"fmt\" \"os\" \"strconv\" \"strings\" \"testing\" \"k8s.io/api/core/v1\""} {"_id":"doc-en-kubernetes-298e5c1548ad59031cdce56118ed36a9d4a57c9bd7b4079d731e83552434d866","title":"","text":"t.Errorf(\"unexpected fc disk found\") } } func Test_ConstructVolumeSpec(t *testing.T) { fm := &mount.FakeMounter{ MountPoints: []mount.MountPoint{ {Device: \"/dev/sdb\", Path: \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod1\"}, {Device: \"/dev/sdb\", Path: \"/var/lib/kubelet/plugins/kubernetes.io/fc/50060e801049cfd1-lun-0\"}, {Device: \"/dev/sdc\", Path: \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod2\"}, {Device: \"/dev/sdc\", Path: \"/var/lib/kubelet/plugins/kubernetes.io/fc/volumeDevices/3600508b400105e210000900000490000\"}, }, } mountPaths := []string{ \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod1\", \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod2\", } for _, path := range mountPaths { refs, _ := mount.GetMountRefs(fm, path) var globalPDPath string for _, ref := range refs { if strings.Contains(ref, \"kubernetes.io/fc\") { globalPDPath = ref break } } if len(globalPDPath) == 0 { t.Errorf(\"couldn't fetch mountrefs\") } arr := strings.Split(globalPDPath, \"/\") if len(arr) < 1 { t.Errorf(\"failed to retrieve volume plugin information from globalPDPath: %v\", globalPDPath) } volumeInfo := arr[len(arr)-1] if strings.Contains(volumeInfo, \"-lun-\") { wwnLun := strings.Split(volumeInfo, \"-lun-\") if len(wwnLun) < 2 { t.Errorf(\"failed to retrieve TargetWWN and Lun. volumeInfo is invalid: %v\", volumeInfo) } lun, _ := strconv.Atoi(wwnLun[1]) lun32 := int32(lun) if wwnLun[0] != \"50060e801049cfd1\" || lun32 != 0 { t.Errorf(\"failed to retrieve TargetWWN and Lun\") } } else { if volumeInfo != \"3600508b400105e210000900000490000\" { t.Errorf(\"failed to retrieve WWIDs\") } } } } func Test_ConstructVolumeSpecNoRefs(t *testing.T) { fm := &mount.FakeMounter{ MountPoints: []mount.MountPoint{ {Device: \"/dev/sdd\", Path: \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod1\"}, }, } mountPaths := []string{ \"/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~fc/fc-in-pod1\", } for _, path := range mountPaths { refs, _ := mount.GetMountRefs(fm, path) var globalPDPath string for _, ref := range refs { if strings.Contains(ref, \"kubernetes.io/fc\") { globalPDPath = ref break } } if len(globalPDPath) != 0 { t.Errorf(\"invalid globalPDPath\") } } } "} {"_id":"doc-en-kubernetes-967168c5d7eb3245d8e2655a0053325ed1be580b55496a2c410eca9715ffc8f8","title":"","text":"GetStats(path string, stats *libcontainercgroups.Stats) error } // getSupportedSubsystems returns list of subsystems supported func getSupportedSubsystems() []subsystem { supportedSubsystems := []subsystem{ &cgroupfs.MemoryGroup{}, &cgroupfs.CpuGroup{}, // getSupportedSubsystems returns a map of subsystem and if it must be mounted for the kubelet to function. func getSupportedSubsystems() map[subsystem]bool { supportedSubsystems := map[subsystem]bool{ &cgroupfs.MemoryGroup{}: true, &cgroupfs.CpuGroup{}: true, } // not all hosts support hugetlb cgroup, and in the absent of hugetlb, we will fail silently by reporting no capacity. if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.HugePages) { supportedSubsystems = append(supportedSubsystems, &cgroupfs.HugetlbGroup{}) supportedSubsystems[&cgroupfs.HugetlbGroup{}] = false } if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.SupportPodPidsLimit) { supportedSubsystems = append(supportedSubsystems, &cgroupfs.PidsGroup{}) supportedSubsystems[&cgroupfs.PidsGroup{}] = true } return supportedSubsystems }"} {"_id":"doc-en-kubernetes-5b9ab0d3a761ab1698dcb6ea8fe55bd3493023193d5d04d38a972043740ff816","title":"","text":"// but this is not possible with libcontainers Set() method // See https://github.com/opencontainers/runc/issues/932 func setSupportedSubsystems(cgroupConfig *libcontainerconfigs.Cgroup) error { for _, sys := range getSupportedSubsystems() { for sys, required := range getSupportedSubsystems() { if _, ok := cgroupConfig.Paths[sys.Name()]; !ok { return fmt.Errorf(\"Failed to find subsystem mount for subsystem: %v\", sys.Name()) if required { return fmt.Errorf(\"Failed to find subsystem mount for required subsystem: %v\", sys.Name()) } // the cgroup is not mounted, but its not required so continue... glog.V(6).Infof(\"Unable to find subsystem mount for optional subsystem: %v\", sys.Name()) continue } if err := sys.Set(cgroupConfig.Paths[sys.Name()], cgroupConfig); err != nil { return fmt.Errorf(\"Failed to set config for supported subsystems : %v\", err)"} {"_id":"doc-en-kubernetes-9709ea9b87677a053b4996639d8167f51bd65d94df1fa9932f58bb1b90e274e0","title":"","text":"func getStatsSupportedSubsystems(cgroupPaths map[string]string) (*libcontainercgroups.Stats, error) { stats := libcontainercgroups.NewStats() for _, sys := range getSupportedSubsystems() { for sys, required := range getSupportedSubsystems() { if _, ok := cgroupPaths[sys.Name()]; !ok { return nil, fmt.Errorf(\"Failed to find subsystem mount for subsystem: %v\", sys.Name()) if required { return nil, fmt.Errorf(\"Failed to find subsystem mount for required subsystem: %v\", sys.Name()) } // the cgroup is not mounted, but its not required so continue... glog.V(6).Infof(\"Unable to find subsystem mount for optional subsystem: %v\", sys.Name()) continue } if err := sys.GetStats(cgroupPaths[sys.Name()], stats); err != nil { return nil, fmt.Errorf(\"Failed to get stats for supported subsystems : %v\", err)"} {"_id":"doc-en-kubernetes-ec2f5610e3934ee478e42b59396e2aa6f4f802addc393b537e49e55e21a7e80e","title":"","text":"if !(runtime.IsMissingVersion(err) || runtime.IsMissingKind(err) || runtime.IsNotRegisteredError(err)) { return nil, err } // Only tolerate load errors if the file appears to be one of the two legacy plugin configs unstructuredData := map[string]interface{}{} if err2 := yaml.Unmarshal(data, &unstructuredData); err2 != nil { return nil, err } _, isLegacyImagePolicy := unstructuredData[\"imagePolicy\"] _, isLegacyPodNodeSelector := unstructuredData[\"podNodeSelectorPluginConfig\"] if !isLegacyImagePolicy && !isLegacyPodNodeSelector { return nil, err } // convert the legacy format to the new admission control format // in order to preserve backwards compatibility, we set plugins that // previously read input from a non-versioned file configuration to the"} {"_id":"doc-en-kubernetes-3937e3e750aa2039932e8f9e80a218c10cde97da7fd7d47d7c950d91bb3f0ee2","title":"","text":"\"k8s.io/client-go/rest\" ) var scheme = runtime.NewScheme() var configScheme = runtime.NewScheme() func init() { apiserverapi.AddToScheme(scheme) apiserverapiv1alpha1.AddToScheme(scheme) apiserverapi.AddToScheme(configScheme) apiserverapiv1alpha1.AddToScheme(configScheme) } // AdmissionOptions holds the admission options"} {"_id":"doc-en-kubernetes-f83383edc92b114e136d6b1ea863cd08e64912622ba90d0b11feae213eb13c95","title":"","text":"pluginNames = a.enabledPluginNames() } pluginsConfigProvider, err := admission.ReadAdmissionConfiguration(pluginNames, a.ConfigFile, scheme) pluginsConfigProvider, err := admission.ReadAdmissionConfiguration(pluginNames, a.ConfigFile, configScheme) if err != nil { return fmt.Errorf(\"failed to read plugin config: %v\", err) }"} {"_id":"doc-en-kubernetes-5480bd511ef76bcee89a8040f4083b6a96570ab2786a8fc53e42822ce1b3c6a9","title":"","text":"\"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/runtime/serializer/json:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/uuid:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library\","} {"_id":"doc-en-kubernetes-aca8a86778c4688ffd991881bb76b35bcf9bd60eca86f43ac0c987136ad5e46b","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/serializer\" \"k8s.io/apimachinery/pkg/runtime/serializer/json\" utilruntime \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/wait\""} {"_id":"doc-en-kubernetes-8b29c40dc5ad58a5027757923905b09b0e276beca77eaecf3716eaa52d4dced8","title":"","text":"// ConfigFile is the location of the scheduler server's configuration file. ConfigFile string // WriteConfigTo is the path where the default configuration will be written. WriteConfigTo string // config is the scheduler server's configuration object. config *componentconfig.KubeSchedulerConfiguration"} {"_id":"doc-en-kubernetes-a4840b1f2edd8a43772a0724e957cd5f651119615239b616ed2501d8478fb880","title":"","text":"// AddFlags adds flags for a specific SchedulerServer to the specified FlagSet func (o *Options) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&o.ConfigFile, \"config\", o.ConfigFile, \"The path to the configuration file.\") fs.StringVar(&o.WriteConfigTo, \"write-config-to\", o.WriteConfigTo, \"If set, write the configuration values to this file and exit.\") // All flags below here are deprecated and will eventually be removed."} {"_id":"doc-en-kubernetes-93ee3b6ab49e9af819b9a29eb39da0db2c30cbfdc4d1234769a483a0394a72d3","title":"","text":"} func (o *Options) Complete() error { if len(o.ConfigFile) == 0 { glog.Warning(\"WARNING: all flags other than --config are deprecated. Please begin using a config file ASAP.\") if len(o.ConfigFile) == 0 && len(o.WriteConfigTo) == 0 { glog.Warning(\"WARNING: all flags other than --config, --write-config-to, and --cleanup are deprecated. Please begin using a config file ASAP.\") o.applyDeprecatedHealthzAddressToConfig() o.applyDeprecatedHealthzPortToConfig() o.applyDeprecatedAlgorithmSourceOptionsToConfig() } if len(o.ConfigFile) > 0 { if c, err := o.loadConfigFromFile(o.ConfigFile); err != nil { return err } else { o.config = c } } // Apply algorithms based on feature gates. // TODO: make configurable? algorithmprovider.ApplyFeatureGates() return nil }"} {"_id":"doc-en-kubernetes-d4820c9211f8a2238519baaf0aad92a55a62d3e78d11f8dccae7290c277c730c","title":"","text":"} func (o *Options) Run() error { config := o.config if len(o.ConfigFile) > 0 { if c, err := o.loadConfigFromFile(o.ConfigFile); err != nil { return err } else { config = c } // If user only want to generate a configure file. if len(o.WriteConfigTo) > 0 { return o.writeConfigFile() } // Apply algorithms based on feature gates. // TODO: make configurable? algorithmprovider.ApplyFeatureGates() server, err := NewSchedulerServer(config, o.master) server, err := NewSchedulerServer(o.config, o.master) if err != nil { return err }"} {"_id":"doc-en-kubernetes-a7d957a749035cafa74bc248f872c7b8800517a131e4c7577f45359909e61b4f","title":"","text":"return server.Run(stop) } func (o *Options) writeConfigFile() error { var encoder runtime.Encoder mediaTypes := o.codecs.SupportedMediaTypes() for _, info := range mediaTypes { if info.MediaType == \"application/yaml\" { encoder = info.Serializer break } } if encoder == nil { return errors.New(\"unable to locate yaml encoder\") } encoder = json.NewYAMLSerializer(json.DefaultMetaFactory, o.scheme, o.scheme) encoder = o.codecs.EncoderForVersion(encoder, componentconfigv1alpha1.SchemeGroupVersion) configFile, err := os.Create(o.WriteConfigTo) if err != nil { return err } defer configFile.Close() if err := encoder.Encode(o.config, configFile); err != nil { return err } glog.Infof(\"Wrote configuration to: %sn\", o.WriteConfigTo) return nil } // NewSchedulerCommand creates a *cobra.Command object with default parameters func NewSchedulerCommand() *cobra.Command { opts, err := NewOptions()"} {"_id":"doc-en-kubernetes-62d284cb266ae92ee4427f65d48d83f6b5feb6a35ebbfff13308dee3b26d1cfe","title":"","text":"return cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving modified configuration from:n%vnfor:\", info), info.Source, err) } // Print object only if output format other than \"name\" is specified printObject := len(output) > 0 && !shortOutput if err := info.Get(); err != nil { if !errors.IsNotFound(err) { return cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:n%vnfrom server for:\", info), info.Source, err)"} {"_id":"doc-en-kubernetes-3d6da35035eb1757864d27448dcda522f6dbf57328c590409866e287c178a773","title":"","text":"} count++ if len(output) > 0 && !shortOutput { if printObject { return cmdutil.PrintObject(cmd, info.Object, out) } cmdutil.PrintSuccess(shortOutput, out, info.Object, dryRun, \"created\")"} {"_id":"doc-en-kubernetes-1c487ec319fdd6f328cf5c1a3b2659808ba9feff311fa0bfc0062a7d35577e13","title":"","text":"visitedUids.Insert(string(uid)) } if string(patchBytes) == \"{}\" { if string(patchBytes) == \"{}\" && !printObject { count++ cmdutil.PrintSuccess(shortOutput, out, info.Object, false, \"unchanged\") return nil } } count++ if len(output) > 0 && !shortOutput { if printObject { return cmdutil.PrintObject(cmd, info.Object, out) } cmdutil.PrintSuccess(shortOutput, out, info.Object, dryRun, \"configured\")"} {"_id":"doc-en-kubernetes-9be936528c3c09a878cb773ffdd39f815effa6702b7421555ecbb59be0d67fbf","title":"","text":"s.GenericServerRunOptions.AddUniversalFlags(fs) s.Etcd.AddFlags(fs) s.SecureServing.AddFlags(fs) s.SecureServing.AddDeprecatedFlags(fs) s.InsecureServing.AddFlags(fs) s.InsecureServing.AddDeprecatedFlags(fs) s.Audit.AddFlags(fs)"} {"_id":"doc-en-kubernetes-7254d8081ca034ae81afaf21c7aeafd9d1ff76e28c618d066c49a02a8b844426","title":"","text":"limitations under the License. */ // Package options contains flags and options for initializing an apiserver // Package options contains flags and options for initializing kube-apiserver package options import ("} {"_id":"doc-en-kubernetes-2ed3417a6ddf392c146d401289503cf918f980c28658ca3bfcfbe8417a90b26d","title":"","text":"kubeserver \"k8s.io/kubernetes/pkg/kubeapiserver/server\" ) // NewSecureServingOptions gives default values for the kube-apiserver and federation-apiserver which are not the options wanted by // NewSecureServingOptions gives default values for the kube-apiserver which are not the options wanted by // \"normal\" API servers running on the platform func NewSecureServingOptions() *genericoptions.SecureServingOptions { return &genericoptions.SecureServingOptions{"} {"_id":"doc-en-kubernetes-bf73f96b4d5e8ea65d7e66db6f2db45fec5a71f2317d9cb4b6a06fae1f7bb48a","title":"","text":"if s.AdvertiseAddress == nil || s.AdvertiseAddress.IsUnspecified() { hostIP, err := insecure.DefaultExternalAddress() if err != nil { return fmt.Errorf(\"Unable to find suitable network address.error='%v'. \"+ \"Try to set the AdvertiseAddress directly or provide a valid BindAddress to fix this.\", err) return fmt.Errorf(\"unable to find suitable network address.error='%v'. \"+ \"Try to set the AdvertiseAddress directly or provide a valid BindAddress to fix this\", err) } s.AdvertiseAddress = hostIP }"} {"_id":"doc-en-kubernetes-7f45e52fb246915d739c20f265688f96522cb2fc5db68ff53a21d1b4f0d8f1b1","title":"","text":"errors := []error{} if s.BindPort < 0 || s.BindPort > 65535 { errors = append(errors, fmt.Errorf(\"--insecure-port %v must be between 0 and 65535, inclusive. 0 for turning off insecure (HTTP) port.\", s.BindPort)) errors = append(errors, fmt.Errorf(\"--insecure-port %v must be between 0 and 65535, inclusive. 0 for turning off insecure (HTTP) port\", s.BindPort)) } return errors"} {"_id":"doc-en-kubernetes-f4f53bfa844b2ae33976378bf90ff001d832d445c57a1769a8ae7a20b587235a","title":"","text":"func (s *InsecureServingOptions) AddFlags(fs *pflag.FlagSet) { fs.IPVar(&s.BindAddress, \"insecure-bind-address\", s.BindAddress, \"\"+ \"The IP address on which to serve the --insecure-port (set to 0.0.0.0 for all interfaces).\") fs.MarkDeprecated(\"insecure-bind-address\", \"This flag will be removed in a future version.\") fs.IntVar(&s.BindPort, \"insecure-port\", s.BindPort, \"\"+ \"The port on which to serve unsecured, unauthenticated access. It is assumed \"+ \"that firewall rules are set up such that this port is not reachable from outside of \"+ \"the cluster and that port 443 on the cluster's public address is proxied to this \"+ \"port. This is performed by nginx in the default setup. Set to zero to disable\") \"port. This is performed by nginx in the default setup. Set to zero to disable.\") fs.MarkDeprecated(\"insecure-port\", \"This flag will be removed in a future version.\") } // TODO: remove it until kops stop using `--address` func (s *InsecureServingOptions) AddDeprecatedFlags(fs *pflag.FlagSet) { fs.IPVar(&s.BindAddress, \"address\", s.BindAddress, \"DEPRECATED: see --insecure-bind-address instead.\")"} {"_id":"doc-en-kubernetes-c72d04f7357c317578d2d671c02259ee092008825c48036036e5cdd22b1a0de5","title":"","text":"errors := []error{} if s.BindPort < 0 || s.BindPort > 65535 { errors = append(errors, fmt.Errorf(\"--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port.\", s.BindPort)) errors = append(errors, fmt.Errorf(\"--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port\", s.BindPort)) } return errors"} {"_id":"doc-en-kubernetes-0720c4a43b7e168d6da2a11826fddee235f4c06f1dda11ecc68dc943cf6056f3","title":"","text":"} func (s *SecureServingOptions) AddDeprecatedFlags(fs *pflag.FlagSet) { fs.IPVar(&s.BindAddress, \"public-address-override\", s.BindAddress, \"DEPRECATED: see --bind-address instead.\") fs.MarkDeprecated(\"public-address-override\", \"see --bind-address instead.\") } // ApplyTo fills up serving information in the server configuration. func (s *SecureServingOptions) ApplyTo(c *server.Config) error { if s == nil {"} {"_id":"doc-en-kubernetes-a928f2e17c8f9accb4f8d76b90626f56b670919d56fc4df73523ad1fb73997b1","title":"","text":"ec.InvalidateCachedPredicateItem(nodeName, invalidPredicates) } // getHashEquivalencePod returns the hash of equivalence pod. // 1. equivalenceHash // 2. if equivalence hash is valid func (ec *EquivalenceCache) getHashEquivalencePod(pod *v1.Pod) (uint64, bool) { // equivalenceClassInfo holds equivalence hash which is used for checking equivalence cache. // We will pass this to podFitsOnNode to ensure equivalence hash is only calculated per schedule. type equivalenceClassInfo struct { // Equivalence hash. hash uint64 } // getEquivalenceClassInfo returns the equivalence class of given pod. func (ec *EquivalenceCache) getEquivalenceClassInfo(pod *v1.Pod) *equivalenceClassInfo { equivalencePod := ec.getEquivalencePod(pod) if equivalencePod != nil { hash := fnv.New32a() hashutil.DeepHashObject(hash, equivalencePod) return uint64(hash.Sum32()), true return &equivalenceClassInfo{ hash: uint64(hash.Sum32()), } } return 0, false return nil }"} {"_id":"doc-en-kubernetes-c92855f7c207e6daeb36f9f75905a972b7ad91e73086d7be0119a7116ab07649","title":"","text":"for _, test := range tests { for i, podInfo := range test.podInfoList { testPod := podInfo.pod hash, isValid := ecache.getHashEquivalencePod(testPod) if isValid != podInfo.hashIsValid { eclassInfo := ecache.getEquivalenceClassInfo(testPod) if eclassInfo == nil && podInfo.hashIsValid { t.Errorf(\"Failed: pod %v is expected to have valid hash\", testPod) } // NOTE(harry): the first element will be used as target so // this logic can't verify more than two inequivalent pods if i == 0 { targetHash = hash targetPodInfo = podInfo } else { if targetHash != hash { if test.isEquivalent { t.Errorf(\"Failed: pod: %v is expected to be equivalent to: %v\", testPod, targetPodInfo.pod) if eclassInfo != nil { // NOTE(harry): the first element will be used as target so // this logic can't verify more than two inequivalent pods if i == 0 { targetHash = eclassInfo.hash targetPodInfo = podInfo } else { if targetHash != eclassInfo.hash { if test.isEquivalent { t.Errorf(\"Failed: pod: %v is expected to be equivalent to: %v\", testPod, targetPodInfo.pod) } } } }"} {"_id":"doc-en-kubernetes-b02c353b1f95ed6acafa3cc91f7357097fa8bb8b1c8ec1edadc7f041d230e9ec","title":"","text":"// We can use the same metadata producer for all nodes. meta := metadataProducer(pod, nodeNameToInfo) var equivCacheInfo *equivalenceClassInfo if ecache != nil { // getEquivalenceClassInfo will return immediately if no equivalence pod found equivCacheInfo = ecache.getEquivalenceClassInfo(pod) } checkNode := func(i int) { nodeName := nodes[i].Name fits, failedPredicates, err := podFitsOnNode(pod, meta, nodeNameToInfo[nodeName], predicateFuncs, ecache, schedulingQueue, alwaysCheckAllPredicates) fits, failedPredicates, err := podFitsOnNode( pod, meta, nodeNameToInfo[nodeName], predicateFuncs, ecache, schedulingQueue, alwaysCheckAllPredicates, equivCacheInfo, ) if err != nil { predicateResultLock.Lock() errs[err.Error()]++"} {"_id":"doc-en-kubernetes-0556fa3293d555d3b183a3956c2285ba005cc468b2240b161b79e29854c3fb77","title":"","text":"} // podFitsOnNode checks whether a node given by NodeInfo satisfies the given predicate functions. // For given pod, podFitsOnNode will check if any equivalent pod exists and try to reuse its cached // predicate results as possible. // This function is called from two different places: Schedule and Preempt. // When it is called from Schedule, we want to test whether the pod is schedulable // on the node with all the existing pods on the node plus higher and equal priority"} {"_id":"doc-en-kubernetes-77a7804fa184f32e6a2289b3175c515b68d261b42b4fdbb882e20c1047cc632e","title":"","text":"ecache *EquivalenceCache, queue SchedulingQueue, alwaysCheckAllPredicates bool, equivCacheInfo *equivalenceClassInfo, ) (bool, []algorithm.PredicateFailureReason, error) { var ( equivalenceHash uint64 failedPredicates []algorithm.PredicateFailureReason eCacheAvailable bool failedPredicates []algorithm.PredicateFailureReason invalid bool fit bool reasons []algorithm.PredicateFailureReason"} {"_id":"doc-en-kubernetes-1d83ad7baa4b68483882a6790385b6c0b193c8f048346b49a33ce055ce09eead","title":"","text":") predicateResults := make(map[string]HostPredicate) if ecache != nil { // getHashEquivalencePod will return immediately if no equivalence pod found equivalenceHash, eCacheAvailable = ecache.getHashEquivalencePod(pod) } podsAdded := false // We run predicates twice in some cases. If the node has greater or equal priority // nominated pods, we run them when those pods are added to meta and nodeInfo."} {"_id":"doc-en-kubernetes-9a90551b44fd737e34f836894b36c18ae4152b6b50fb69a020877eba31b60ac6","title":"","text":"// Bypass eCache if node has any nominated pods. // TODO(bsalamat): consider using eCache and adding proper eCache invalidations // when pods are nominated or their nominations change. eCacheAvailable = eCacheAvailable && !podsAdded eCacheAvailable = equivCacheInfo != nil && !podsAdded for _, predicateKey := range predicates.PredicatesOrdering() { //TODO (yastij) : compute average predicate restrictiveness to export it as promethus metric //TODO (yastij) : compute average predicate restrictiveness to export it as Prometheus metric if predicate, exist := predicateFuncs[predicateKey]; exist { if eCacheAvailable { // PredicateWithECache will return its cached predicate results. fit, reasons, invalid = ecache.PredicateWithECache(pod.GetName(), info.Node().GetName(), predicateKey, equivalenceHash) fit, reasons, invalid = ecache.PredicateWithECache(pod.GetName(), info.Node().GetName(), predicateKey, equivCacheInfo.hash) } if !eCacheAvailable || invalid {"} {"_id":"doc-en-kubernetes-54b6ba1382785c63088aedb7ffe760a3e2ce0eee1fc8b3b07442ed450c787a10","title":"","text":"for predKey, result := range predicateResults { // update equivalence cache with newly computed fit & reasons // TODO(resouer) should we do this in another thread? any race? ecache.UpdateCachedPredicateItem(pod.GetName(), nodeName, predKey, result.Fit, result.FailReasons, equivalenceHash) ecache.UpdateCachedPredicateItem(pod.GetName(), nodeName, predKey, result.Fit, result.FailReasons, equivCacheInfo.hash) } } return len(failedPredicates) == 0, failedPredicates, nil"} {"_id":"doc-en-kubernetes-f671d24d2afaeb4b98284b2d1ea1040bb86e40eedcf79ac4a2528d9801906ada","title":"","text":"// that we should check is if the \"pod\" is failing to schedule due to pod affinity // failure. // TODO(bsalamat): Consider checking affinity to lower priority pods if feasible with reasonable performance. if fits, _, err := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, nil, queue, false); !fits { if fits, _, err := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, nil, queue, false, nil); !fits { if err != nil { glog.Warningf(\"Encountered error while selecting victims on node %v: %v\", nodeInfo.Node().Name, err) }"} {"_id":"doc-en-kubernetes-7b8de52b5256fc09a510b8a7bc0f8ab8527537d60ce79bdfcda227edfac92dbe","title":"","text":"violatingVictims, nonViolatingVictims := filterPodsWithPDBViolation(potentialVictims.Items, pdbs) reprievePod := func(p *v1.Pod) bool { addPod(p) fits, _, _ := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, nil, queue, false) fits, _, _ := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, nil, queue, false, nil) if !fits { removePod(p) victims = append(victims, p)"} {"_id":"doc-en-kubernetes-b170d8890585cd1a41973f2539105945793e58d64cff50f963783b93f7d69524","title":"","text":"\"//pkg/util/sysctl:go_default_library\", \"//pkg/util/version:go_default_library\", \"//vendor/github.com/golang/glog:go_default_library\", \"//vendor/golang.org/x/sys/unix:go_default_library\", \"//vendor/k8s.io/api/core/v1:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/types:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library\","} {"_id":"doc-en-kubernetes-86139033920ebbb6f3b4994cf7149fb56493d18bfcff5df5afe2790c0c78a403","title":"","text":"] + select({ \"@io_bazel_rules_go//go/platform:linux\": [ \"//vendor/github.com/vishvananda/netlink:go_default_library\", \"//vendor/golang.org/x/sys/unix:go_default_library\", ], \"//conditions:default\": [], }),"} {"_id":"doc-en-kubernetes-abe74f01e1d1328229901aa844ff1ae0cf0197f1a2e604fe7acea6ecde4ebd45","title":"","text":"return false, nil } // UnbindAddress unbind address from the interface // UnbindAddress makes sure IP address is unbound from the network interface. func (h *netlinkHandle) UnbindAddress(address, devName string) error { dev, err := h.LinkByName(devName) if err != nil {"} {"_id":"doc-en-kubernetes-3610928e57123848ac20823c951ba54a7d1cd176f7e4b5152e5d08379a8e1b06","title":"","text":"return fmt.Errorf(\"error parse ip address: %s\", address) } if err := h.AddrDel(dev, &netlink.Addr{IPNet: netlink.NewIPNet(addr)}); err != nil { return fmt.Errorf(\"error unbind address: %s from interface: %s, err: %v\", address, devName, err) if err != unix.ENXIO { return fmt.Errorf(\"error unbind address: %s from interface: %s, err: %v\", address, devName, err) } } return nil }"} {"_id":"doc-en-kubernetes-59b723c3f72c26e4af9e93f8a36b4470b6e0ca03339f13e5cd001a30b1540930","title":"","text":"utilipvs \"k8s.io/kubernetes/pkg/util/ipvs\" utilsysctl \"k8s.io/kubernetes/pkg/util/sysctl\" utilexec \"k8s.io/utils/exec\" \"golang.org/x/sys/unix\" ) const ("} {"_id":"doc-en-kubernetes-be05f9cf74f64b2b8247831235a2002a2bbe66def7955f46495c7f52adb31359","title":"","text":"for _, addr := range unbindIPAddr.UnsortedList() { err := proxier.netlinkHandle.UnbindAddress(addr, DefaultDummyDevice) // Ignore no such address error when try to unbind address if err != nil && err != unix.ENXIO { if err != nil { glog.Errorf(\"Failed to unbind service addr %s from dummy interface %s: %v\", addr, DefaultDummyDevice, err) } }"} {"_id":"doc-en-kubernetes-2d61fe9cabf6a96a5319e9914fde614975d1ff39ea974323a8e18e8b66b140c1","title":"","text":"} if err := d.writeCachedFile(filename, liveResources); err != nil { glog.V(3).Infof(\"failed to write cache to %v due to %v\", filename, err) glog.V(1).Infof(\"failed to write cache to %v due to %v\", filename, err) } return liveResources, nil"} {"_id":"doc-en-kubernetes-74722e7125a5f8a0f46da4bd3ad297eba64173a46256c2433c66fe3675a20528","title":"","text":"} if err := d.writeCachedFile(filename, liveGroups); err != nil { glog.V(3).Infof(\"failed to write cache to %v due to %v\", filename, err) glog.V(1).Infof(\"failed to write cache to %v due to %v\", filename, err) } return liveGroups, nil"} {"_id":"doc-en-kubernetes-33d67137f776886907200f232d3aee3ae907472b2f0b47f98753f0c91bffe296","title":"","text":"// 3. Ties are broken by sum of priorities of all victims. // 4. If there are still ties, node with the minimum number of victims is picked. // 5. If there are still ties, the first such node is picked (sort of randomly). //TODO(bsalamat): Try to reuse the \"min*Nodes\" slices in order to save GC time. // The 'minNodes1' and 'minNodes2' are being reused here to save the memory // allocation and garbage collection time. func pickOneNodeForPreemption(nodesToVictims map[*v1.Node]*Victims) *v1.Node { if len(nodesToVictims) == 0 { return nil } minNumPDBViolatingPods := math.MaxInt32 var minPDBViolatingNodes []*v1.Node var minNodes1 []*v1.Node lenNodes1 := 0 for node, victims := range nodesToVictims { if len(victims.pods) == 0 { // We found a node that doesn't need any preemption. Return it!"} {"_id":"doc-en-kubernetes-14253aaeb22a594b8980f9931d2e67be6cd1c09b4b6dd841e748ece768a85015","title":"","text":"numPDBViolatingPods := victims.numPDBViolations if numPDBViolatingPods < minNumPDBViolatingPods { minNumPDBViolatingPods = numPDBViolatingPods minPDBViolatingNodes = nil minNodes1 = nil lenNodes1 = 0 } if numPDBViolatingPods == minNumPDBViolatingPods { minPDBViolatingNodes = append(minPDBViolatingNodes, node) minNodes1 = append(minNodes1, node) lenNodes1++ } } if len(minPDBViolatingNodes) == 1 { return minPDBViolatingNodes[0] if lenNodes1 == 1 { return minNodes1[0] } // There are more than one node with minimum number PDB violating pods. Find // the one with minimum highest priority victim. minHighestPriority := int32(math.MaxInt32) var minPriorityNodes []*v1.Node for _, node := range minPDBViolatingNodes { var minNodes2 = make([]*v1.Node, lenNodes1) lenNodes2 := 0 for i := 0; i < lenNodes1; i++ { node := minNodes1[i] victims := nodesToVictims[node] // highestPodPriority is the highest priority among the victims on this node. highestPodPriority := util.GetPodPriority(victims.pods[0]) if highestPodPriority < minHighestPriority { minHighestPriority = highestPodPriority minPriorityNodes = nil lenNodes2 = 0 } if highestPodPriority == minHighestPriority { minPriorityNodes = append(minPriorityNodes, node) minNodes2[lenNodes2] = node lenNodes2++ } } if len(minPriorityNodes) == 1 { return minPriorityNodes[0] if lenNodes2 == 1 { return minNodes2[0] } // There are a few nodes with minimum highest priority victim. Find the // smallest sum of priorities. minSumPriorities := int64(math.MaxInt64) var minSumPriorityNodes []*v1.Node for _, node := range minPriorityNodes { lenNodes1 = 0 for i := 0; i < lenNodes2; i++ { var sumPriorities int64 node := minNodes2[i] for _, pod := range nodesToVictims[node].pods { // We add MaxInt32+1 to all priorities to make all of them >= 0. This is // needed so that a node with a few pods with negative priority is not"} {"_id":"doc-en-kubernetes-2f94ec0161ded9951a8c4c9f94a7b922e31999d8f838be3d26fdbc89f58ec382","title":"","text":"} if sumPriorities < minSumPriorities { minSumPriorities = sumPriorities minSumPriorityNodes = nil lenNodes1 = 0 } if sumPriorities == minSumPriorities { minSumPriorityNodes = append(minSumPriorityNodes, node) minNodes1[lenNodes1] = node lenNodes1++ } } if len(minSumPriorityNodes) == 1 { return minSumPriorityNodes[0] if lenNodes1 == 1 { return minNodes1[0] } // There are a few nodes with minimum highest priority victim and sum of priorities. // Find one with the minimum number of pods. minNumPods := math.MaxInt32 var minNumPodNodes []*v1.Node for _, node := range minSumPriorityNodes { lenNodes2 = 0 for i := 0; i < lenNodes1; i++ { node := minNodes1[i] numPods := len(nodesToVictims[node].pods) if numPods < minNumPods { minNumPods = numPods minNumPodNodes = nil lenNodes2 = 0 } if numPods == minNumPods { minNumPodNodes = append(minNumPodNodes, node) minNodes2[lenNodes2] = node lenNodes2++ } } // At this point, even if there are more than one node with the same score, // return the first one. if len(minNumPodNodes) > 0 { return minNumPodNodes[0] if lenNodes2 > 0 { return minNodes2[0] } glog.Errorf(\"Error in logic of node scoring for preemption. We should never reach here!\") return nil"} {"_id":"doc-en-kubernetes-c96acd34e456b36be37909f69918d27803c9819f48521ca119ee71dfce8928ed","title":"","text":"Status: v1.ConditionTrue, }) hostIP, err := kl.getHostIPAnyWay() if err != nil { glog.V(4).Infof(\"Cannot get host IP: %v\", err) return *s } s.HostIP = hostIP.String() if kubecontainer.IsHostNetworkPod(pod) && s.PodIP == \"\" { s.PodIP = hostIP.String() if kl.kubeClient != nil { hostIP, err := kl.getHostIPAnyWay() if err != nil { glog.V(4).Infof(\"Cannot get host IP: %v\", err) } else { s.HostIP = hostIP.String() if kubecontainer.IsHostNetworkPod(pod) && s.PodIP == \"\" { s.PodIP = hostIP.String() } } } return *s }"} {"_id":"doc-en-kubernetes-55e071a3aaca6420622e14861bc9c668dcd4978baa69b6beaec8cb9eb0e8cd48","title":"","text":"glog.Infof(volumeToMount.GenerateMsgDetailed(\"MapVolume.WaitForAttach succeeded\", fmt.Sprintf(\"DevicePath %q\", devicePath))) // Update actual state of world to reflect volume is globally mounted markDeviceMappedErr := actualStateOfWorld.MarkDeviceAsMounted( volumeToMount.VolumeName, devicePath, globalMapPath) if markDeviceMappedErr != nil { // On failure, return error. Caller will log and retry. return volumeToMount.GenerateError(\"MapVolume.MarkDeviceAsMounted failed\", markDeviceMappedErr) } } // A plugin doesn't have attacher also needs to map device to global map path with SetUpDevice() pluginDevicePath, mapErr := blockVolumeMapper.SetUpDevice()"} {"_id":"doc-en-kubernetes-3cb55c0b069b9fd797370d1a2b4442c244ddb1d18e67afe8e5e7f3e499db4832","title":"","text":"return volumeToMount.GenerateError(\"MapVolume failed\", fmt.Errorf(\"Device path of the volume is empty\")) } } // Update actual state of world to reflect volume is globally mounted markDeviceMappedErr := actualStateOfWorld.MarkDeviceAsMounted( volumeToMount.VolumeName, devicePath, globalMapPath) if markDeviceMappedErr != nil { // On failure, return error. Caller will log and retry. return volumeToMount.GenerateError(\"MapVolume.MarkDeviceAsMounted failed\", markDeviceMappedErr) } mapErr = og.blkUtil.MapDevice(devicePath, globalMapPath, string(volumeToMount.Pod.UID)) if mapErr != nil {"} {"_id":"doc-en-kubernetes-375877a7473598c02e517dbc16c92a951c8008b918d43a671e5b4d20fb5aed91","title":"","text":"// Try to unmap podUID symlink under global map path dir // plugins/kubernetes.io/{PluginName}/volumeDevices/{volumePluginDependentPath}/{podUID} globalUnmapPath := volumeToUnmount.DeviceMountPath if err != nil { // On failure, return error. Caller will log and retry. return volumeToUnmount.GenerateError(\"UnmapVolume.GetGlobalUnmapPath failed\", err) } unmapDeviceErr = og.blkUtil.UnmapDevice(globalUnmapPath, string(volumeToUnmount.PodUID)) if unmapDeviceErr != nil { // On failure, return error. Caller will log and retry."} {"_id":"doc-en-kubernetes-164b4b2025a81db5fa3921b61f97b31ff4e805744353a363b780db3225a20927","title":"","text":"// Search under globalMapPath dir if all symbolic links from pods have been removed already. // If symbolick links are there, pods may still refer the volume. globalMapPath := deviceToDetach.DeviceMountPath if err != nil { // On failure, return error. Caller will log and retry. return deviceToDetach.GenerateError(\"UnmapDevice.GetGlobalMapPath failed\", err) } refs, err := og.blkUtil.GetDeviceSymlinkRefs(deviceToDetach.DevicePath, globalMapPath) if err != nil { return deviceToDetach.GenerateError(\"UnmapDevice.GetDeviceSymlinkRefs check failed\", err)"} {"_id":"doc-en-kubernetes-f5aecaf02ee48f556d9b2749085ce4a2f27397d87c051f167141f182e565179b","title":"","text":"if newRS != nil && newRS.UID == rsUID { continue } if len(podList.Items) > 0 { return true for _, pod := range podList.Items { switch pod.Status.Phase { case v1.PodFailed, v1.PodSucceeded: // Don't count pods in terminal state. continue case v1.PodUnknown: // This happens in situation like when the node is temporarily disconnected from the cluster. // If we can't be sure that the pod is not running, we have to count it. return true default: // Pod is not in terminal phase. return true } } } return false"} {"_id":"doc-en-kubernetes-3a24a9f177d95521a7445d2a4c69a8754ba35c255a6f9913f25d55979b64db10","title":"","text":"oldRSs []*extensions.ReplicaSet podMap map[types.UID]*v1.PodList expected bool hasOldPodsRunning bool }{ { name: \"no old RSs\", expected: false, name: \"no old RSs\", hasOldPodsRunning: false, }, { name: \"old RSs with running pods\", oldRSs: []*extensions.ReplicaSet{rsWithUID(\"some-uid\"), rsWithUID(\"other-uid\")}, podMap: podMapWithUIDs([]string{\"some-uid\", \"other-uid\"}), expected: true, name: \"old RSs with running pods\", oldRSs: []*extensions.ReplicaSet{rsWithUID(\"some-uid\"), rsWithUID(\"other-uid\")}, podMap: podMapWithUIDs([]string{\"some-uid\", \"other-uid\"}), hasOldPodsRunning: true, }, { name: \"old RSs without pods but with non-zero status replicas\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-blabla\", 0, 1, nil)}, expected: true, name: \"old RSs without pods but with non-zero status replicas\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 1, nil)}, hasOldPodsRunning: true, }, { name: \"old RSs without pods or non-zero status replicas\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-blabla\", 0, 0, nil)}, expected: false, name: \"old RSs without pods or non-zero status replicas\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, hasOldPodsRunning: false, }, { name: \"old RSs with zero status replicas but pods in terminal state are present\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, podMap: map[types.UID]*v1.PodList{ \"uid-1\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodFailed, }, }, { Status: v1.PodStatus{ Phase: v1.PodSucceeded, }, }, }, }, }, hasOldPodsRunning: false, }, { name: \"old RSs with zero status replicas but pod in unknown phase present\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, podMap: map[types.UID]*v1.PodList{ \"uid-1\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodUnknown, }, }, }, }, }, hasOldPodsRunning: true, }, { name: \"old RSs with zero status replicas with pending pod present\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, podMap: map[types.UID]*v1.PodList{ \"uid-1\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodPending, }, }, }, }, }, hasOldPodsRunning: true, }, { name: \"old RSs with zero status replicas with running pod present\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, podMap: map[types.UID]*v1.PodList{ \"uid-1\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodRunning, }, }, }, }, }, hasOldPodsRunning: true, }, { name: \"old RSs with zero status replicas but pods in terminal state and pending are present\", oldRSs: []*extensions.ReplicaSet{newRSWithStatus(\"rs-1\", 0, 0, nil)}, podMap: map[types.UID]*v1.PodList{ \"uid-1\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodFailed, }, }, { Status: v1.PodStatus{ Phase: v1.PodSucceeded, }, }, }, }, \"uid-2\": { Items: []v1.Pod{}, }, \"uid-3\": { Items: []v1.Pod{ { Status: v1.PodStatus{ Phase: v1.PodPending, }, }, }, }, }, hasOldPodsRunning: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if expected, got := test.expected, oldPodsRunning(test.newRS, test.oldRSs, test.podMap); expected != got { if expected, got := test.hasOldPodsRunning, oldPodsRunning(test.newRS, test.oldRSs, test.podMap); expected != got { t.Errorf(\"%s: expected %t, got %t\", test.name, expected, got) } })"} {"_id":"doc-en-kubernetes-e6771feb95a0c95017154cf86225354e47025b538ae262f4a29364626eccfb00","title":"","text":"\"//cmd/kube-proxy/app:go_default_library\", \"//pkg/client/metrics/prometheus:go_default_library\", \"//pkg/version/prometheus:go_default_library\", \"//vendor/github.com/spf13/pflag:go_default_library\", \"//vendor/k8s.io/apiserver/pkg/util/flag:go_default_library\", \"//vendor/k8s.io/apiserver/pkg/util/logs:go_default_library\", ],"} {"_id":"doc-en-kubernetes-9a0b9185ee586b2da20cc3631977604149db73070176de267f7992383dadba4e","title":"","text":"glog.Fatalf(\"unable to create flag defaults: %v\", err) } opts.AddFlags(pflag.CommandLine) opts.AddFlags(cmd.Flags()) cmd.MarkFlagFilename(\"config\", \"yaml\", \"yml\", \"json\")"} {"_id":"doc-en-kubernetes-eb2fb2b99a42f440fa5477b0aa260ea8fde4068f05afeab9e58c44a24efdcb42","title":"","text":"package main import ( goflag \"flag\" \"fmt\" \"math/rand\" \"os\" \"time\" \"github.com/spf13/pflag\" utilflag \"k8s.io/apiserver/pkg/util/flag\" \"k8s.io/apiserver/pkg/util/logs\" \"k8s.io/kubernetes/cmd/kube-proxy/app\""} {"_id":"doc-en-kubernetes-d8c8a47f42319517c58f8d3f0acd0568d8385e0f30dbd5592de64822a157c028","title":"","text":"command := app.NewProxyCommand() utilflag.InitFlags() // TODO: once we switch everything over to Cobra commands, we can go back to calling // utilflag.InitFlags() (by removing its pflag.Parse() call). For now, we have to set the // normalize func and add the go flag set by hand. pflag.CommandLine.SetNormalizeFunc(utilflag.WordSepNormalizeFunc) pflag.CommandLine.AddGoFlagSet(goflag.CommandLine) // utilflag.InitFlags() logs.InitLogs() defer logs.FlushLogs()"} {"_id":"doc-en-kubernetes-01f8bee03ae53e71786914051519a2f8c946278bf69dac53226b5637dd1fff55","title":"","text":"if err != nil { return nil, err } readOnly, err := getReadOnlyFromSpec(spec) if err != nil { return nil, err } // before it is used in any paths such as socket etc addr := fmt.Sprintf(csiAddrTemplate, pvSource.Driver)"} {"_id":"doc-en-kubernetes-ab44ceaa090486bd2f84473abd39c5c6b5a1f43a782c0f2f2157b037068abbf3","title":"","text":"volumeID: pvSource.VolumeHandle, specVolumeID: spec.Name(), csiClient: client, readOnly: readOnly, } return mounter, nil }"} {"_id":"doc-en-kubernetes-71fbf39d944614159a59b69edab7a57e3d592c217fed7d07f9e2de79872e9f3d","title":"","text":"return nil, fmt.Errorf(\"CSIPersistentVolumeSource not defined in spec\") } func getReadOnlyFromSpec(spec *volume.Spec) (bool, error) { if spec.PersistentVolume != nil && spec.PersistentVolume.Spec.CSI != nil { return spec.ReadOnly, nil } return false, fmt.Errorf(\"CSIPersistentVolumeSource not defined in spec\") } // log prepends log string with `kubernetes.io/csi` func log(msg string, parts ...interface{}) string { return fmt.Sprintf(fmt.Sprintf(\"%s: %s\", csiPluginName, msg), parts...)"} {"_id":"doc-en-kubernetes-e30273bf3a383776cf2bbf3f739ebec04aa40dcebed240d884c39d9d966e4460","title":"","text":"set +o errexit } # Runs tests for kubectl alpha diff run_kubectl_diff_tests() { set -o nounset set -o errexit create_and_use_new_namespace kube::log::status \"Testing kubectl alpha diff\" kubectl apply -f hack/testdata/pod.yaml # Ensure that selfLink has been added, and shown in the diff output_message=$(kubectl alpha diff -f hack/testdata/pod.yaml) kube::test::if_has_string \"${output_message}\" 'selfLink' output_message=$(kubectl alpha diff LOCAL LIVE -f hack/testdata/pod.yaml) kube::test::if_has_string \"${output_message}\" 'selfLink' output_message=$(kubectl alpha diff LOCAL MERGED -f hack/testdata/pod.yaml) kube::test::if_has_string \"${output_message}\" 'selfLink' output_message=$(kubectl alpha diff MERGED MERGED -f hack/testdata/pod.yaml) kube::test::if_empty_string \"${output_message}\" output_message=$(kubectl alpha diff LIVE LIVE -f hack/testdata/pod.yaml) kube::test::if_empty_string \"${output_message}\" output_message=$(kubectl alpha diff LAST LAST -f hack/testdata/pod.yaml) kube::test::if_empty_string \"${output_message}\" output_message=$(kubectl alpha diff LOCAL LOCAL -f hack/testdata/pod.yaml) kube::test::if_empty_string \"${output_message}\" kubectl delete -f hack/testdata/pod.yaml set +o nounset set +o errexit } # Runs tests for --save-config tests. run_save_config_tests() { set -o nounset"} {"_id":"doc-en-kubernetes-ef453dc33c5d72afac1d559c368a8597ebcbddef10099b11eab8096d9805d190","title":"","text":"record_command run_kubectl_apply_deployments_tests fi ################ # Kubectl diff # ################ record_command run_kubectl_diff_tests ############### # Kubectl get # ###############"} {"_id":"doc-en-kubernetes-8027a2a1bd967c7b0b6244ccb78e75a4516bf645ee24c3b0687f053c1bbc88a6","title":"","text":"\"github.com/ghodss/yaml\" \"github.com/spf13/cobra\" \"k8s.io/apimachinery/pkg/api/errors\" \"k8s.io/apimachinery/pkg/api/meta\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/client-go/dynamic\" api \"k8s.io/kubernetes/pkg/apis/core\" \"k8s.io/kubernetes/pkg/kubectl/apply/parse\" \"k8s.io/kubernetes/pkg/kubectl/apply/strategy\""} {"_id":"doc-en-kubernetes-352fb2a8a92a2337093d1adbac14c2cca880d5df102c2c5e00d10198cb67ea93","title":"","text":"// InfoObject is an implementation of the Object interface. It gets all // the information from the Info object. type InfoObject struct { Remote runtime.Unstructured Info *resource.Info Encoder runtime.Encoder Parser *parse.Factory"} {"_id":"doc-en-kubernetes-8787eb5f34232568e5cbc680fe1c04088949f69ad0f7edd36bf0787ca112f065","title":"","text":"} func (obj InfoObject) Live() (map[string]interface{}, error) { if obj.Info.Object == nil { if obj.Remote == nil { return nil, nil // Object doesn't exist on cluster. } data, err := runtime.Encode(obj.Encoder, obj.Info.Object) if err != nil { return nil, err } return obj.toMap(data) return obj.Remote.UnstructuredContent(), nil } func (obj InfoObject) Merged() (map[string]interface{}, error) {"} {"_id":"doc-en-kubernetes-44782b9e7171af52a2254aa9f3406f98eb47aeb4c0958ed1ff32ae6ebde0b98c","title":"","text":"} func (obj InfoObject) Last() (map[string]interface{}, error) { if obj.Info.Object == nil { if obj.Remote == nil { return nil, nil // No object is live, return empty } accessor, err := meta.Accessor(obj.Info.Object) accessor, err := meta.Accessor(obj.Remote) if err != nil { return nil, err }"} {"_id":"doc-en-kubernetes-f792b0a3f93b35a9fa3419552e0f026883c1795c726fbc48f53396fa341950bb","title":"","text":"d.To.Dir.Delete() // Ignore error } type Downloader struct { mapper meta.RESTMapper dclient dynamic.Interface ns string } func NewDownloader(f cmdutil.Factory) (*Downloader, error) { var err error var d Downloader d.mapper, err = f.RESTMapper() if err != nil { return nil, err } d.dclient, err = f.DynamicClient() if err != nil { return nil, err } d.ns, _, _ = f.DefaultNamespace() return &d, nil } func (d *Downloader) Download(info *resource.Info) (*unstructured.Unstructured, error) { gvk := info.Object.GetObjectKind().GroupVersionKind() mapping, err := d.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) if err != nil { return nil, err } var resource dynamic.ResourceInterface switch mapping.Scope.Name() { case meta.RESTScopeNameNamespace: if info.Namespace == \"\" { info.Namespace = d.ns } resource = d.dclient.Resource(mapping.Resource).Namespace(info.Namespace) case meta.RESTScopeNameRoot: resource = d.dclient.Resource(mapping.Resource) } return resource.Get(info.Name, metav1.GetOptions{}) } // RunDiff uses the factory to parse file arguments, find the version to // diff, and find each Info object for each files, and runs against the // differ."} {"_id":"doc-en-kubernetes-9d37f57db9bdfa074dd628f89183876db835fd4d5d66ba0e7a311cbca78e6730","title":"","text":"Unstructured(). NamespaceParam(cmdNamespace).DefaultNamespace(). FilenameParam(enforceNamespace, &options.FilenameOptions). Local(). Flatten(). Do() if err := r.Err(); err != nil { return err } dl, err := NewDownloader(f) if err != nil { return err } err = r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } if err := info.Get(); err != nil { if !errors.IsNotFound(err) { return cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:n%snfrom server for:\", info.String()), info.Source, err) } info.Object = nil } remote, _ := dl.Download(info) obj := InfoObject{ Remote: remote, Info: info, Parser: parser, Encoder: cmdutil.InternalVersionJSONEncoder(),"} {"_id":"doc-en-kubernetes-52f8a6c3bc189eae19929303042bdbf14c5a9f169c5adccd2b8eb04855e80359","title":"","text":"// CommonAccessor returns a Common interface for the provided object or an error if the object does // not provide List. // TODO: return bool instead of error func CommonAccessor(obj interface{}) (metav1.Common, error) { switch t := obj.(type) { case List:"} {"_id":"doc-en-kubernetes-adedd7c967307087170a156f6a1c6410e6f48b2d4937345ccc3d5ada6cca24cf","title":"","text":"// not provide List. // IMPORTANT: Objects are NOT a superset of lists. Do not use this check to determine whether an // object *is* a List. // TODO: return bool instead of error func ListAccessor(obj interface{}) (List, error) { switch t := obj.(type) { case List:"} {"_id":"doc-en-kubernetes-2dc3a34a616ed76ef91a7018eafa799b2c61c2cc43390498ada1187c32e7824a","title":"","text":"// obj must be a pointer to an API type. An error is returned if the minimum // required fields are missing. Fields that are not required return the default // value and are a no-op if set. // TODO: return bool instead of error func Accessor(obj interface{}) (metav1.Object, error) { switch t := obj.(type) { case metav1.Object:"} {"_id":"doc-en-kubernetes-028ba0604796d938e93fb0ec69eb2f3169832b87c7a76137eb5434236c3da076","title":"","text":"cmd.Flags().BoolVar(&options.DeleteAll, \"all\", options.DeleteAll, \"Delete all resources, including uninitialized ones, in the namespace of the specified resource types.\") cmd.Flags().BoolVar(&options.IgnoreNotFound, \"ignore-not-found\", options.IgnoreNotFound, \"Treat \"resource not found\" as a successful delete. Defaults to \"true\" when --all is specified.\") cmd.Flags().BoolVar(&options.Cascade, \"cascade\", options.Cascade, \"If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true.\") cmd.Flags().IntVar(&options.GracePeriod, \"grace-period\", options.GracePeriod, \"Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.\") cmd.Flags().IntVar(&options.GracePeriod, \"grace-period\", options.GracePeriod, \"Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).\") cmd.Flags().BoolVar(&options.DeleteNow, \"now\", options.DeleteNow, \"If true, resources are signaled for immediate shutdown (same as --grace-period=1).\") cmd.Flags().BoolVar(&options.ForceDeletion, \"force\", options.ForceDeletion, \"Immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.\") cmd.Flags().BoolVar(&options.ForceDeletion, \"force\", options.ForceDeletion, \"Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires confirmation.\") cmd.Flags().DurationVar(&options.Timeout, \"timeout\", options.Timeout, \"The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object\") cmdutil.AddOutputVarFlagsForMutation(cmd, &options.Output) cmdutil.AddInclude3rdPartyVarFlags(cmd, &options.Include3rdParty)"} {"_id":"doc-en-kubernetes-5c30c59de41e14247b897d5a10e34b549cc719acdeb1960a36bebd537e589949","title":"","text":"o.WaitForDeletion = true o.GracePeriod = 1 } } else if o.ForceDeletion { fmt.Fprintf(o.ErrOut, \"warning: --force is ignored because --grace-period is not 0.n\") } return nil }"} {"_id":"doc-en-kubernetes-7035dae3540d3a02520e84d1901b68135f4a5b899377b808a6ce3f6d48c0f409","title":"","text":"// If there is no reaper for this resources and the user didn't explicitly ask for stop. if kubectl.IsNoSuchReaperError(err) && isDefaultDelete { // No client side reaper found. Let the server do cascading deletion. return cascadingDeleteResource(info, out, shortOutput) return cascadingDeleteResource(info, out, shortOutput, gracePeriod) } return cmdutil.AddSourceToErr(\"reaping\", info.Source, err) }"} {"_id":"doc-en-kubernetes-4a18c87a8396f07ddc0a5f89b5a5fcc94c3f52ced7f764c110ef49af15d21ac6","title":"","text":"} } if !quiet { printDeletion(info, out, shortOutput) printDeletion(info, out, shortOutput, gracePeriod) } return nil })"} {"_id":"doc-en-kubernetes-5367461adace9f5ea67f5eba59dbbbd2788de76e54f27fdcfecbddabbb6496eb","title":"","text":"options = metav1.NewDeleteOptions(int64(gracePeriod)) } options.OrphanDependents = &orphan return deleteResource(info, out, shortOutput, options) return deleteResource(info, out, shortOutput, options, gracePeriod) }) if err != nil { return err"} {"_id":"doc-en-kubernetes-eac43836f069f9dfb8a9497eaeaeb200fd69f4f9500f3e67b0326228ed8a61ee","title":"","text":"return nil } func cascadingDeleteResource(info *resource.Info, out io.Writer, shortOutput bool) error { func cascadingDeleteResource(info *resource.Info, out io.Writer, shortOutput bool, gracePeriod int) error { falseVar := false deleteOptions := &metav1.DeleteOptions{OrphanDependents: &falseVar} return deleteResource(info, out, shortOutput, deleteOptions) return deleteResource(info, out, shortOutput, deleteOptions, gracePeriod) } func deleteResource(info *resource.Info, out io.Writer, shortOutput bool, deleteOptions *metav1.DeleteOptions) error { func deleteResource(info *resource.Info, out io.Writer, shortOutput bool, deleteOptions *metav1.DeleteOptions, gracePeriod int) error { if err := resource.NewHelper(info.Client, info.Mapping).DeleteWithOptions(info.Namespace, info.Name, deleteOptions); err != nil { return cmdutil.AddSourceToErr(\"deleting\", info.Source, err) } printDeletion(info, out, shortOutput) printDeletion(info, out, shortOutput, gracePeriod) return nil } // deletion printing is special because they don't have an object to print. This logic mirrors PrintSuccess func printDeletion(info *resource.Info, out io.Writer, shortOutput bool) { func printDeletion(info *resource.Info, out io.Writer, shortOutput bool, gracePeriod int) { operation := \"deleted\" groupKind := info.Mapping.GroupVersionKind kindString := fmt.Sprintf(\"%s.%s\", strings.ToLower(groupKind.Kind), groupKind.Group)"} {"_id":"doc-en-kubernetes-194cf78e41984a9e8761e6da3db6054e1cc49b00ae89305d857e65192e5b4603","title":"","text":"kindString = strings.ToLower(groupKind.Kind) } if gracePeriod == 0 { operation = \"force deleted\" } if shortOutput { // -o name: prints resource/name fmt.Fprintf(out, \"%s/%sn\", kindString, info.Name)"} {"_id":"doc-en-kubernetes-ca494be2c79ac35d516651ff0683b3aefb95b8e934a667f41c5d4a9fa56250b6","title":"","text":"\"format\": \"byte\" }, \"service\": { \"description\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnIf there is only one port open for the service, that port will be used. If there are multiple ports open, port 443 will be used if it is open, otherwise it is an error.\", \"description\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnPort 443 will be used if it is open, otherwise it is an error.\", \"$ref\": \"#/definitions/io.k8s.api.admissionregistration.v1beta1.ServiceReference\" }, \"url\": {"} {"_id":"doc-en-kubernetes-46717783076edbc5dfb3fa5913149d2f4acc813db3a8f8b9b37d3dd90e6cfbf1","title":"","text":"}, \"service\": { \"$ref\": \"v1beta1.ServiceReference\", \"description\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnIf there is only one port open for the service, that port will be used. If there are multiple ports open, port 443 will be used if it is open, otherwise it is an error.\" \"description\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnPort 443 will be used if it is open, otherwise it is an error.\" }, \"caBundle\": { \"type\": \"string\","} {"_id":"doc-en-kubernetes-e99cd6d826b7cc78fa031ccffeb1f55ebf6f5d636c2efc4274fa7b7ec81efa4e","title":"","text":"
If the webhook is running within the cluster, then you should use service.

If there is only one port open for the service, that port will be used. If there are multiple ports open, port 443 will be used if it is open, otherwise it is an error.

Port 443 will be used if it is open, otherwise it is an error.

true

v1beta1.ServiceReference

"} {"_id":"doc-en-kubernetes-d5e2545bf34286d96ff51d82472251e668f443f6969a3d1bc7946ea44ced8930","title":"","text":"// // If the webhook is running within the cluster, then you should use `service`. // // If there is only one port open for the service, that port will be // used. If there are multiple ports open, port 443 will be used if it // is open, otherwise it is an error. // Port 443 will be used if it is open, otherwise it is an error. // // +optional Service *ServiceReference"} {"_id":"doc-en-kubernetes-bcdc82c840a407ec7b7978a31f6edfaedbf0b4d5b26427dd055fed6566ca5710","title":"","text":"// // If the webhook is running within the cluster, then you should use `service`. // // If there is only one port open for the service, that port will be // used. If there are multiple ports open, port 443 will be used if it // is open, otherwise it is an error. // Port 443 will be used if it is open, otherwise it is an error. // // +optional optional ServiceReference service = 1;"} {"_id":"doc-en-kubernetes-85eb562602e75ca1c0122264a931f64584b04f44d1b18d239901dbd51729ccdf","title":"","text":"// // If the webhook is running within the cluster, then you should use `service`. // // If there is only one port open for the service, that port will be // used. If there are multiple ports open, port 443 will be used if it // is open, otherwise it is an error. // Port 443 will be used if it is open, otherwise it is an error. // // +optional Service *ServiceReference `json:\"service\" protobuf:\"bytes,1,opt,name=service\"`"} {"_id":"doc-en-kubernetes-cff99e7134c7f8bfc5a86250a17e9aae45c51032db19a66e6d9facb47d897dd7","title":"","text":"var map_WebhookClientConfig = map[string]string{ \"\": \"WebhookClientConfig contains the information to make a TLS connection with the webhook\", \"url\": \"`url` gives the location of the webhook, in standard URL form (`[scheme://]host:port/path`). Exactly one of `url` or `service` must be specified.nnThe `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address.nnPlease note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster.nnThe scheme must be \"https\"; the URL must begin with \"https://\".nnA path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier.nnAttempting to use a user or basic auth e.g. \"user:password@\" is not allowed. Fragments (\"#...\") and query parameters (\"?...\") are not allowed, either.\", \"service\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnIf there is only one port open for the service, that port will be used. If there are multiple ports open, port 443 will be used if it is open, otherwise it is an error.\", \"service\": \"`service` is a reference to the service for this webhook. Either `service` or `url` must be specified.nnIf the webhook is running within the cluster, then you should use `service`.nnPort 443 will be used if it is open, otherwise it is an error.\", \"caBundle\": \"`caBundle` is a PEM encoded CA bundle which will be used to validate the webhook's server certificate. Required.\", }"} {"_id":"doc-en-kubernetes-748d957e6e10c2dcb1c293578d126202eb53d2338d30a08bafa9f900d9ba9684","title":"","text":"} func TestPerformance(t *testing.T) { if testing.Short() { // TODO (#61854) find why flakiness is caused by etcd connectivity before enabling always t.Skip(\"Skipping because we want to run short tests\") } apiURL, masterShutdown := util.StartApiserver() defer masterShutdown()"} {"_id":"doc-en-kubernetes-d4b42e3ee42541e4af3957ebfe66137f7f09dffedf9b2eb544e87c1b4117ad7d","title":"","text":"createTagFactor = 2.0 createTagSteps = 9 // encryptedCheck* is configuration of poll for created volume to check // it has not been silently removed by AWS. // On a random AWS account (shared among several developers) it took 4s on // average. encryptedCheckInterval = 1 * time.Second encryptedCheckTimeout = 30 * time.Second // Number of node names that can be added to a filter. The AWS limit is 200 // but we are using a lower limit on purpose filterNodeLimit = 150"} {"_id":"doc-en-kubernetes-ae7c5b92876febebfb525fe6c51572f921309ec45d47cb2f1baca0a6c9b5e2af","title":"","text":"request.VolumeType = aws.String(createType) request.Encrypted = aws.Bool(volumeOptions.Encrypted) if len(volumeOptions.KmsKeyId) > 0 { if missing, err := c.checkEncryptionKey(volumeOptions.KmsKeyId); err != nil { if missing { // KSM key is missing, provisioning would fail return \"\", err } // Log checkEncryptionKey error and try provisioning anyway. glog.Warningf(\"Cannot check KSM key %s: %v\", volumeOptions.KmsKeyId, err) } request.KmsKeyId = aws.String(volumeOptions.KmsKeyId) request.Encrypted = aws.Bool(true) }"} {"_id":"doc-en-kubernetes-cf19c7cc0fe4fb4d27138a4b463f5069ce81e7c12d4cffaf82613acb292cdb74","title":"","text":"return \"\", fmt.Errorf(\"error tagging volume %s: %q\", volumeName, err) } // AWS has a bad habbit of reporting success when creating a volume with // encryption keys that either don't exists or have wrong permissions. // Such volume lives for couple of seconds and then it's silently deleted // by AWS. There is no other check to ensure that given KMS key is correct, // because Kubernetes may have limited permissions to the key. if len(volumeOptions.KmsKeyId) > 0 { err := c.waitUntilVolumeAvailable(volumeName) if err != nil { if isAWSErrorVolumeNotFound(err) { err = fmt.Errorf(\"failed to create encrypted volume: the volume disappeared after creation, most likely due to inaccessible KMS encryption key\") } return \"\", err } } return volumeName, nil } // checkEncryptionKey tests that given encryption key exists. func (c *Cloud) checkEncryptionKey(keyId string) (missing bool, err error) { input := &kms.DescribeKeyInput{ KeyId: aws.String(keyId), } _, err = c.kms.DescribeKey(input) if err == nil { return false, nil func (c *Cloud) waitUntilVolumeAvailable(volumeName KubernetesVolumeID) error { disk, err := newAWSDisk(c, volumeName) if err != nil { // Unreachable code return err } if awsError, ok := err.(awserr.Error); ok { if awsError.Code() == \"NotFoundException\" { return true, fmt.Errorf(\"KMS key %s not found: %q\", keyId, err) err = wait.Poll(encryptedCheckInterval, encryptedCheckTimeout, func() (done bool, err error) { vol, err := disk.describeVolume() if err != nil { return true, err } } return false, fmt.Errorf(\"Error checking KSM key %s: %q\", keyId, err) if vol.State != nil { switch *vol.State { case \"available\": // The volume is Available, it won't be deleted now. return true, nil case \"creating\": return false, nil default: return true, fmt.Errorf(\"unexpected State of newly created AWS EBS volume %s: %q\", volumeName, *vol.State) } } return false, nil }) return err } // DeleteDisk implements Volumes.DeleteDisk"} {"_id":"doc-en-kubernetes-23472db875ee32f235fdf4016a2d439490ca9864fc5db9b5eab23a4e120f2886","title":"","text":"testDynamicProvisioning(test, c, claim, nil) }) }) Describe(\"Invalid AWS KMS key\", func() { It(\"should report an error and create no PV\", func() { framework.SkipUnlessProviderIs(\"aws\") test := storageClassTest{ name: \"AWS EBS with invalid KMS key\", provisioner: \"kubernetes.io/aws-ebs\", claimSize: \"2Gi\", parameters: map[string]string{\"kmsKeyId\": \"arn:aws:kms:us-east-1:123456789012:key/55555555-5555-5555-5555-555555555555\"}, } By(\"creating a StorageClass\") suffix := fmt.Sprintf(\"invalid-aws\") class := newStorageClass(test, ns, suffix) class, err := c.StorageV1().StorageClasses().Create(class) Expect(err).NotTo(HaveOccurred()) defer func() { framework.Logf(\"deleting storage class %s\", class.Name) framework.ExpectNoError(c.StorageV1().StorageClasses().Delete(class.Name, nil)) }() By(\"creating a claim object with a suffix for gluster dynamic provisioner\") claim := newClaim(test, ns, suffix) claim.Spec.StorageClassName = &class.Name claim, err = c.CoreV1().PersistentVolumeClaims(claim.Namespace).Create(claim) Expect(err).NotTo(HaveOccurred()) defer func() { framework.Logf(\"deleting claim %q/%q\", claim.Namespace, claim.Name) err = c.CoreV1().PersistentVolumeClaims(claim.Namespace).Delete(claim.Name, nil) if err != nil && !apierrs.IsNotFound(err) { framework.Failf(\"Error deleting claim %q. Error: %v\", claim.Name, err) } }() // Watch events until the message about invalid key appears err = wait.Poll(time.Second, framework.ClaimProvisionTimeout, func() (bool, error) { events, err := c.CoreV1().Events(claim.Namespace).List(metav1.ListOptions{}) Expect(err).NotTo(HaveOccurred()) for _, event := range events.Items { if strings.Contains(event.Message, \"failed to create encrypted volume: the volume disappeared after creation, most likely due to inaccessible KMS encryption key\") { return true, nil } } return false, nil }) Expect(err).NotTo(HaveOccurred()) }) }) }) func getDefaultStorageClassName(c clientset.Interface) string {"} {"_id":"doc-en-kubernetes-139460fb4f766f7bea0aced557a3b54391b122576ead574552aab5e2a1bcb20c","title":"","text":"if [[ \"${MASTER_OS_DISTRIBUTION}\" == \"gci\" ]] || [[ \"${MASTER_OS_DISTRIBUTION}\" == \"ubuntu\" ]]; then MASTER_KUBELET_TEST_ARGS=\" --experimental-kernel-memcg-notification=true\" fi APISERVER_TEST_ARGS=\"${APISERVER_TEST_ARGS:-} --vmodule=httplog=3 --runtime-config=extensions/v1beta1 ${TEST_CLUSTER_DELETE_COLLECTION_WORKERS} ${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT}\" APISERVER_TEST_ARGS=\"${APISERVER_TEST_ARGS:-} --vmodule=httplog=3 --runtime-config=extensions/v1beta1,scheduling.k8s.io/v1alpha1 ${TEST_CLUSTER_DELETE_COLLECTION_WORKERS} ${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT}\" CONTROLLER_MANAGER_TEST_ARGS=\"${CONTROLLER_MANAGER_TEST_ARGS:-} ${TEST_CLUSTER_RESYNC_PERIOD} ${TEST_CLUSTER_API_CONTENT_TYPE}\" SCHEDULER_TEST_ARGS=\"${SCHEDULER_TEST_ARGS:-} ${TEST_CLUSTER_API_CONTENT_TYPE}\" KUBEPROXY_TEST_ARGS=\"${KUBEPROXY_TEST_ARGS:-} ${TEST_CLUSTER_API_CONTENT_TYPE}\""} {"_id":"doc-en-kubernetes-7fc059b95310afce4324b2dc300d1a9c9858271a676093b046c30704dc214f35","title":"","text":"fi if [[ -z \"${KUBE_ADMISSION_CONTROL:-}\" ]]; then ADMISSION_CONTROL=\"Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,PodPreset,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection\" ADMISSION_CONTROL=\"Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection\" if [[ \"${ENABLE_POD_SECURITY_POLICY:-}\" == \"true\" ]]; then ADMISSION_CONTROL=\"${ADMISSION_CONTROL},PodSecurityPolicy\" fi"} {"_id":"doc-en-kubernetes-3bbdea84ccf182703e4b1e6e7dcea8d02624fd1e77009111208370158dc27af4","title":"","text":"KUBEMARK_MASTER_COMPONENTS_QPS_LIMITS=\"${KUBEMARK_MASTER_COMPONENTS_QPS_LIMITS:-}\" CUSTOM_ADMISSION_PLUGINS=\"${CUSTOM_ADMISSION_PLUGINS:-Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,PodPreset,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota}\" CUSTOM_ADMISSION_PLUGINS=\"${CUSTOM_ADMISSION_PLUGINS:-Initializers,NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota}\" # Master components' test arguments. APISERVER_TEST_ARGS=\"${KUBEMARK_APISERVER_TEST_ARGS:-} --vmodule=httplog=3 --runtime-config=extensions/v1beta1 ${API_SERVER_TEST_LOG_LEVEL} ${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT} ${TEST_CLUSTER_DELETE_COLLECTION_WORKERS}\" APISERVER_TEST_ARGS=\"${KUBEMARK_APISERVER_TEST_ARGS:-} --vmodule=httplog=3 --runtime-config=extensions/v1beta1,scheduling.k8s.io/v1alpha1 ${API_SERVER_TEST_LOG_LEVEL} ${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT} ${TEST_CLUSTER_DELETE_COLLECTION_WORKERS}\" CONTROLLER_MANAGER_TEST_ARGS=\"${KUBEMARK_CONTROLLER_MANAGER_TEST_ARGS:-} ${CONTROLLER_MANAGER_TEST_LOG_LEVEL} ${TEST_CLUSTER_RESYNC_PERIOD} ${TEST_CLUSTER_API_CONTENT_TYPE} ${KUBEMARK_MASTER_COMPONENTS_QPS_LIMITS}\" SCHEDULER_TEST_ARGS=\"${KUBEMARK_SCHEDULER_TEST_ARGS:-} ${SCHEDULER_TEST_LOG_LEVEL} ${TEST_CLUSTER_API_CONTENT_TYPE} ${KUBEMARK_MASTER_COMPONENTS_QPS_LIMITS}\""} {"_id":"doc-en-kubernetes-6f2dc0752569a3e17a575743b6b9ff8a5a35e608a483a563350ca509eda9005b","title":"","text":"func (a *azureDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) { var err error lun, err := strconv.Atoi(devicePath) volumeSource, err := getVolumeSource(spec) if err != nil { return \"\", fmt.Errorf(\"azureDisk - Wait for attach expect device path as a lun number, instead got: %s (%v)\", devicePath, err) return \"\", err } volumeSource, err := getVolumeSource(spec) diskController, err := getDiskController(a.plugin.host) if err != nil { return \"\", err } nodeName := types.NodeName(a.plugin.host.GetHostName()) diskName := volumeSource.DiskName glog.V(5).Infof(\"azureDisk - WaitForAttach: begin to GetDiskLun by diskName(%s), DataDiskURI(%s), nodeName(%s), devicePath(%s)\", diskName, volumeSource.DataDiskURI, nodeName, devicePath) lun, err := diskController.GetDiskLun(diskName, volumeSource.DataDiskURI, nodeName) if err != nil { return \"\", err } glog.V(5).Infof(\"azureDisk - WaitForAttach: GetDiskLun succeeded, got lun(%v)\", lun) exec := a.plugin.host.GetExec(a.plugin.GetPluginName()) io := &osIOHandler{} scsiHostRescan(io, exec) diskName := volumeSource.DiskName nodeName := a.plugin.host.GetHostName() newDevicePath := \"\" err = wait.Poll(1*time.Second, timeout, func() (bool, error) { if newDevicePath, err = findDiskByLun(lun, io, exec); err != nil { if newDevicePath, err = findDiskByLun(int(lun), io, exec); err != nil { return false, fmt.Errorf(\"azureDisk - WaitForAttach ticker failed node (%s) disk (%s) lun(%v) err(%s)\", nodeName, diskName, lun, err) }"} {"_id":"doc-en-kubernetes-eb1e9172f78b13429049dd88208e224cd7a7613efecdb8389276bf7823e5c8a2","title":"","text":"} if !initializing { restarts = 0 hasRunning := false for i := len(pod.Status.ContainerStatuses) - 1; i >= 0; i-- { container := pod.Status.ContainerStatuses[i]"} {"_id":"doc-en-kubernetes-0a73b39078cae66d77dceda85c078a7fcec5ef3281b173884ec8232061f6aef1","title":"","text":"reason = fmt.Sprintf(\"ExitCode:%d\", container.State.Terminated.ExitCode) } } else if container.Ready && container.State.Running != nil { hasRunning = true readyContainers++ } } // change pod status back to \"Running\" if there is at least one container still reporting as \"Running\" status if reason == \"Completed\" && hasRunning { reason = \"Running\" } } if pod.DeletionTimestamp != nil && pod.Status.Reason == node.NodeUnreachablePodReason {"} {"_id":"doc-en-kubernetes-5c5f91e8426f347f1734329126cbab5bad45ecea625014a5f05b287b7ba8dccc","title":"","text":"}, []metav1beta1.TableRow{{Cells: []interface{}{\"test5\", \"1/2\", \"podReason\", 6, \"\"}}}, }, { // Test pod has 2 containers, one is running and the other is completed. api.Pod{ ObjectMeta: metav1.ObjectMeta{Name: \"test6\"}, Spec: api.PodSpec{Containers: make([]api.Container, 2)}, Status: api.PodStatus{ Phase: \"Running\", Reason: \"\", ContainerStatuses: []api.ContainerStatus{ {Ready: true, RestartCount: 3, State: api.ContainerState{Terminated: &api.ContainerStateTerminated{Reason: \"Completed\", ExitCode: 0}}}, {Ready: true, RestartCount: 3, State: api.ContainerState{Running: &api.ContainerStateRunning{}}}, }, }, }, []metav1beta1.TableRow{{Cells: []interface{}{\"test6\", \"1/2\", \"Running\", 6, \"\"}}}, }, } for i, test := range tests {"} {"_id":"doc-en-kubernetes-50720e7e7c559f5e0d1649624f25b385fb972c940b9bf05c7154a53faf97c45f","title":"","text":"cinderVolumePluginName = \"kubernetes.io/cinder\" ) func getPath(uid types.UID, volName string, host volume.VolumeHost) string { return host.GetPodVolumeDir(uid, kstrings.EscapeQualifiedNameForDisk(cinderVolumePluginName), volName) } func (plugin *cinderPlugin) Init(host volume.VolumeHost) error { plugin.host = host plugin.volumeLocks = keymutex.NewKeyMutex()"} {"_id":"doc-en-kubernetes-5fd86e86e4acc84b92851c35b00f98c39743bf9da677c09b93560aa170538842","title":"","text":"return &cinderVolumeMounter{ cinderVolume: &cinderVolume{ podUID: podUID, volName: spec.Name(), pdName: pdName, mounter: mounter, manager: manager, plugin: plugin, podUID: podUID, volName: spec.Name(), pdName: pdName, mounter: mounter, manager: manager, plugin: plugin, MetricsProvider: volume.NewMetricsStatFS(getPath(podUID, spec.Name(), plugin.host)), }, fsType: fsType, readOnly: readOnly,"} {"_id":"doc-en-kubernetes-4817e89cc21d6d0fda6ec6492b89cc1810d221c10ba0ad83e6076d7647515183","title":"","text":"func (plugin *cinderPlugin) newUnmounterInternal(volName string, podUID types.UID, manager cdManager, mounter mount.Interface) (volume.Unmounter, error) { return &cinderVolumeUnmounter{ &cinderVolume{ podUID: podUID, volName: volName, manager: manager, mounter: mounter, plugin: plugin, podUID: podUID, volName: volName, manager: manager, mounter: mounter, plugin: plugin, MetricsProvider: volume.NewMetricsStatFS(getPath(podUID, volName, plugin.host)), }}, nil }"} {"_id":"doc-en-kubernetes-ba18939aef858f23935d97480027110dcb5d089e517ec09f9b760741a9026f7b","title":"","text":"// diskMounter provides the interface that is used to mount the actual block device. blockDeviceMounter mount.Interface plugin *cinderPlugin volume.MetricsNil volume.MetricsProvider } func (b *cinderVolumeMounter) GetAttributes() volume.Attributes {"} {"_id":"doc-en-kubernetes-01ea6a6937c0c20a183680d54e9091d7be2907347135b53594fb15deed075adc","title":"","text":"} func (cd *cinderVolume) GetPath() string { name := cinderVolumePluginName return cd.plugin.host.GetPodVolumeDir(cd.podUID, kstrings.EscapeQualifiedNameForDisk(name), cd.volName) return getPath(cd.podUID, cd.volName, cd.plugin.host) } type cinderVolumeUnmounter struct {"} {"_id":"doc-en-kubernetes-61fc18b0bd1bf3b083c7992a9faa266146ae9a8ad18c53af089d701c92df3a89","title":"","text":"var _ volume.Deleter = &cinderVolumeDeleter{} func (r *cinderVolumeDeleter) GetPath() string { name := cinderVolumePluginName return r.plugin.host.GetPodVolumeDir(r.podUID, kstrings.EscapeQualifiedNameForDisk(name), r.volName) return getPath(r.podUID, r.volName, r.plugin.host) } func (r *cinderVolumeDeleter) Delete() error {"} {"_id":"doc-en-kubernetes-b9b22feac0608b4fb4803f64866200d99ca3222348c84c12d965f62ef5103a8c","title":"","text":"SchedulerName: config.SchedulerName, Client: client, InformerFactory: informers.NewSharedInformerFactory(client, 0), PodInformer: factory.NewPodInformer(client, 0, config.SchedulerName), PodInformer: factory.NewPodInformer(client, 0), AlgorithmSource: config.AlgorithmSource, HardPodAffinitySymmetricWeight: config.HardPodAffinitySymmetricWeight, EventClient: eventClient,"} {"_id":"doc-en-kubernetes-e233c547dd324133fedb37d204a496fb98a5bf57a1a58c0c00fa1fb173fa19ab","title":"","text":"FilterFunc: func(obj interface{}) bool { switch t := obj.(type) { case *v1.Pod: return unassignedNonTerminatedPod(t) return unassignedNonTerminatedPod(t) && responsibleForPod(t, schedulerName) case cache.DeletedFinalStateUnknown: if pod, ok := t.Obj.(*v1.Pod); ok { return unassignedNonTerminatedPod(pod) return unassignedNonTerminatedPod(pod) && responsibleForPod(pod, schedulerName) } runtime.HandleError(fmt.Errorf(\"unable to convert object %T to *v1.Pod in %T\", obj, c)) return false"} {"_id":"doc-en-kubernetes-910c6e73dbb314a8fa0e38da099f157b6c431f715625e88d9fcf314802f92584","title":"","text":"return true } // responsibleForPod returns true if the pod has asked to be scheduled by the given scheduler. func responsibleForPod(pod *v1.Pod, schedulerName string) bool { return schedulerName == pod.Spec.SchedulerName } // assignedPodLister filters the pods returned from a PodLister to // only include those that have a node name set. type assignedPodLister struct {"} {"_id":"doc-en-kubernetes-133b92d77b0ae1df0ac5dff11780cff236f06f7f1c28c32d761107dfe6392e14","title":"","text":"} // NewPodInformer creates a shared index informer that returns only non-terminal pods. func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration, schedulerName string) coreinformers.PodInformer { func NewPodInformer(client clientset.Interface, resyncPeriod time.Duration) coreinformers.PodInformer { selector := fields.ParseSelectorOrDie( \"spec.schedulerName=\" + schedulerName + \",status.phase!=\" + string(v1.PodSucceeded) + \"status.phase!=\" + string(v1.PodSucceeded) + \",status.phase!=\" + string(v1.PodFailed)) lw := cache.NewListWatchFromClient(client.CoreV1().RESTClient(), string(v1.ResourcePods), metav1.NamespaceAll, selector) return &podInformer{"} {"_id":"doc-en-kubernetes-1caaea9fd207d4c4f73586352469afd9d916ec0b04b2d765d565d18bfab228dc","title":"","text":"HardPodAffinitySymmetricWeight: v1.DefaultHardPodAffinitySymmetricWeight, Client: clientSet, InformerFactory: informerFactory, PodInformer: factory.NewPodInformer(clientSet, 0, v1.DefaultSchedulerName), PodInformer: factory.NewPodInformer(clientSet, 0), EventClient: clientSet.CoreV1(), Recorder: eventBroadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: v1.DefaultSchedulerName}), Broadcaster: eventBroadcaster,"} {"_id":"doc-en-kubernetes-763a05d9d507835ff1d80c273f08728d5c519e4e32fab0a9e3cb6ef879b7cf1a","title":"","text":"// 5. create and start a scheduler with name \"foo-scheduler\" clientSet2 := clientset.NewForConfigOrDie(&restclient.Config{Host: context.httpServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: testapi.Groups[v1.GroupName].GroupVersion()}}) informerFactory2 := informers.NewSharedInformerFactory(context.clientSet, 0) podInformer2 := factory.NewPodInformer(context.clientSet, 0, fooScheduler) podInformer2 := factory.NewPodInformer(context.clientSet, 0) schedulerConfigFactory2 := createConfiguratorWithPodInformer(fooScheduler, clientSet2, podInformer2, informerFactory2) schedulerConfig2, err := schedulerConfigFactory2.Create()"} {"_id":"doc-en-kubernetes-078ff44ad2934ba0eed954c1b0eaa8a56b3647a5e03b0258452d1c9310f53529","title":"","text":"t.Errorf(\"No PDB was deleted from the cache: %v\", err) } } // TestSchedulerInformers tests that scheduler receives informer events and updates its cache when // pods are scheduled by other schedulers. func TestSchedulerInformers(t *testing.T) { // Initialize scheduler. context := initTest(t, \"scheduler-informer\") defer cleanupTest(t, context) cs := context.clientSet defaultPodRes := &v1.ResourceRequirements{Requests: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(200, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(200, resource.BinarySI)}, } defaultNodeRes := &v1.ResourceList{ v1.ResourcePods: *resource.NewQuantity(32, resource.DecimalSI), v1.ResourceCPU: *resource.NewMilliQuantity(500, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(500, resource.BinarySI), } type nodeConfig struct { name string res *v1.ResourceList } tests := []struct { description string nodes []*nodeConfig existingPods []*v1.Pod pod *v1.Pod preemptedPodIndexes map[int]struct{} }{ { description: \"Pod cannot be scheduled when node is occupied by pods scheduled by other schedulers\", nodes: []*nodeConfig{{name: \"node-1\", res: defaultNodeRes}}, existingPods: []*v1.Pod{ initPausePod(context.clientSet, &pausePodConfig{ Name: \"pod1\", Namespace: context.ns.Name, Resources: defaultPodRes, Labels: map[string]string{\"foo\": \"bar\"}, NodeName: \"node-1\", SchedulerName: \"foo-scheduler\", }), initPausePod(context.clientSet, &pausePodConfig{ Name: \"pod2\", Namespace: context.ns.Name, Resources: defaultPodRes, Labels: map[string]string{\"foo\": \"bar\"}, NodeName: \"node-1\", SchedulerName: \"bar-scheduler\", }), }, pod: initPausePod(cs, &pausePodConfig{ Name: \"unschedulable-pod\", Namespace: context.ns.Name, Resources: defaultPodRes, }), preemptedPodIndexes: map[int]struct{}{2: {}}, }, } for _, test := range tests { for _, nodeConf := range test.nodes { _, err := createNode(cs, nodeConf.name, nodeConf.res) if err != nil { t.Fatalf(\"Error creating node %v: %v\", nodeConf.name, err) } } pods := make([]*v1.Pod, len(test.existingPods)) var err error // Create and run existingPods. for i, p := range test.existingPods { if pods[i], err = runPausePod(cs, p); err != nil { t.Fatalf(\"Test [%v]: Error running pause pod: %v\", test.description, err) } } // Create the new \"pod\". unschedulable, err := createPausePod(cs, test.pod) if err != nil { t.Errorf(\"Error while creating new pod: %v\", err) } if err := waitForPodUnschedulable(cs, unschedulable); err != nil { t.Errorf(\"Pod %v got scheduled: %v\", unschedulable.Name, err) } // Cleanup pods = append(pods, unschedulable) cleanupPods(cs, t, pods) cs.PolicyV1beta1().PodDisruptionBudgets(context.ns.Name).DeleteCollection(nil, metav1.ListOptions{}) cs.CoreV1().Nodes().DeleteCollection(nil, metav1.ListOptions{}) } } "} {"_id":"doc-en-kubernetes-6d522a8ff173c44b5db6b010532917baaa07ef5331e7407a667be9160d2cdcb1","title":"","text":"// create independent pod informer if required if setPodInformer { podInformer = factory.NewPodInformer(context.clientSet, 12*time.Hour, v1.DefaultSchedulerName) podInformer = factory.NewPodInformer(context.clientSet, 12*time.Hour) } else { podInformer = context.informerFactory.Core().V1().Pods() }"} {"_id":"doc-en-kubernetes-87a75f7bb0fb66ae9e1b11494c636810b97619bf6b24542bf22d5686a0a92071","title":"","text":"import ( \"bufio\" //\"fmt\" \"net\" \"net/http\" \"regexp\" \"strconv\" \"strings\" \"sync\" \"time\" utilnet \"k8s.io/apimachinery/pkg/util/net\""} {"_id":"doc-en-kubernetes-02983cfcbd67cf231d06be2d08f5bc6ce45143cf2fdc9db90119a011c3fa22f2","title":"","text":"\"github.com/prometheus/client_golang/prometheus\" ) // resettableCollector is the interface implemented by prometheus.MetricVec // that can be used by Prometheus to collect metrics and reset their values. type resettableCollector interface { prometheus.Collector Reset() } var ( // TODO(a-robinson): Add unit tests for the handling of these metrics once // the upstream library supports it."} {"_id":"doc-en-kubernetes-e0a4c5339f1fcdb3180cdd6beb1d06fceea5f176a575f48333e7d87f8a263bc7","title":"","text":"[]string{\"requestKind\"}, ) kubectlExeRegexp = regexp.MustCompile(`^.*((?i:kubectl.exe))`) metrics = []resettableCollector{ requestCounter, longRunningRequestGauge, requestLatencies, requestLatenciesSummary, responseSizes, DroppedRequests, currentInflightRequests, } ) const ("} {"_id":"doc-en-kubernetes-395b12573e7435ba34f3a4b413ea232ef56a3f013a084eb84b12d806ded31197","title":"","text":"MutatingKind = \"mutating\" ) func init() { // Register all metrics. prometheus.MustRegister(requestCounter) prometheus.MustRegister(longRunningRequestGauge) prometheus.MustRegister(requestLatencies) prometheus.MustRegister(requestLatenciesSummary) prometheus.MustRegister(responseSizes) prometheus.MustRegister(DroppedRequests) prometheus.MustRegister(currentInflightRequests) var registerMetrics sync.Once // Register all metrics. func Register() { registerMetrics.Do(func() { for _, metric := range metrics { prometheus.MustRegister(metric) } }) } // Reset all metrics. func Reset() { for _, metric := range metrics { metric.Reset() } } func UpdateInflightRequestMetrics(nonmutating, mutating int) {"} {"_id":"doc-en-kubernetes-e865a2e476bae08d897656d71cbc6cd62cd2781c0b73f8cbed706b3993aa1384","title":"","text":"} } func Reset() { requestCounter.Reset() requestLatencies.Reset() requestLatenciesSummary.Reset() responseSizes.Reset() } // InstrumentRouteFunc works like Prometheus' InstrumentHandlerFunc but wraps // the go-restful RouteFunction instead of a HandlerFunc plus some Kubernetes endpoint specific information. func InstrumentRouteFunc(verb, resource, subresource, scope string, routeFunc restful.RouteFunction) restful.RouteFunction {"} {"_id":"doc-en-kubernetes-7144973b5e77ec7719760dcb8ff3cafdc14a51a07cd56b9a3a86380f7732e698","title":"","text":"// Install adds the DefaultMetrics handler func (m DefaultMetrics) Install(c *mux.PathRecorderMux) { register() c.Handle(\"/metrics\", prometheus.Handler()) }"} {"_id":"doc-en-kubernetes-4e65ed2ed8585dfcf8cdd4b88e77c86857a31afc8bc64129f81dc36c2f5be5b9","title":"","text":"// Install adds the MetricsWithReset handler func (m MetricsWithReset) Install(c *mux.PathRecorderMux) { register() defaultMetricsHandler := prometheus.Handler().ServeHTTP c.HandleFunc(\"/metrics\", func(w http.ResponseWriter, req *http.Request) { if req.Method == \"DELETE\" {"} {"_id":"doc-en-kubernetes-f32b7d178e48e2103b6e507a17cbd030d3cd0763576795b2822be2e430123f28","title":"","text":"defaultMetricsHandler(w, req) }) } // register apiserver and etcd metrics func register() { apimetrics.Register() etcdmetrics.Register() } "} {"_id":"doc-en-kubernetes-307673bf13a13e1ea6fbd0854a7dc1998c1e74f0a1dae0ca6587c5e5832ef1c1","title":"","text":"cache utilcache.Cache } func init() { metrics.Register() } // Implements storage.Interface. func (h *etcdHelper) Versioner() storage.Versioner { return h.versioner"} {"_id":"doc-en-kubernetes-d2b960964e95c69b5ea7917280b40b545e44dc3177517e448d6ee6f39b6d76dd","title":"","text":"// did we find it? if newDevicePath != \"\" { // the current sequence k8s uses for unformated disk (check-disk, mount, fail, mkfs.extX) hangs on // Azure Managed disk scsi interface. this is a hack and will be replaced once we identify and solve // the root case on Azure. formatIfNotFormatted(newDevicePath, *volumeSource.FSType, exec) return true, nil }"} {"_id":"doc-en-kubernetes-b02c4f8e5f96c2d9d6437cfaa1833b2212d6555c19072736eff3c04280b58354","title":"","text":"} return \"\", err } func formatIfNotFormatted(disk string, fstype string, exec mount.Exec) { notFormatted, err := diskLooksUnformatted(disk, exec) if err == nil && notFormatted { args := []string{disk} // Disk is unformatted so format it. // Use 'ext4' as the default if len(fstype) == 0 { fstype = \"ext4\" } if fstype == \"ext4\" || fstype == \"ext3\" { args = []string{\"-E\", \"lazy_itable_init=0,lazy_journal_init=0\", \"-F\", disk} } glog.Infof(\"azureDisk - Disk %q appears to be unformatted, attempting to format as type: %q with options: %v\", disk, fstype, args) _, err := exec.Run(\"mkfs.\"+fstype, args...) if err == nil { // the disk has been formatted successfully try to mount it again. glog.Infof(\"azureDisk - Disk successfully formatted with 'mkfs.%s %v'\", fstype, args) } else { glog.Warningf(\"azureDisk - Error formatting volume with 'mkfs.%s %v': %v\", fstype, args, err) } } else { if err != nil { glog.Warningf(\"azureDisk - Failed to check if the disk %s formatted with error %s, will attach anyway\", disk, err) } else { glog.Infof(\"azureDisk - Disk %s already formatted, will not format\", disk) } } } func diskLooksUnformatted(disk string, exec mount.Exec) (bool, error) { args := []string{\"-nd\", \"-o\", \"FSTYPE\", disk} glog.V(4).Infof(\"Attempting to determine if disk %q is formatted using lsblk with args: (%v)\", disk, args) dataOut, err := exec.Run(\"lsblk\", args...) if err != nil { glog.Errorf(\"Could not determine if disk %q is formatted (%v)\", disk, err) return false, err } output := libstrings.TrimSpace(string(dataOut)) return output == \"\", nil } "} {"_id":"doc-en-kubernetes-e995872e6bcb181e81d8560d29683d425798cfe13a32be5a07a58051843bd989","title":"","text":"func findDiskByLun(lun int, io ioHandler, exec mount.Exec) (string, error) { return \"\", nil } func formatIfNotFormatted(disk string, fstype string, exec mount.Exec) { } "} {"_id":"doc-en-kubernetes-66160e254bba06d08c09f7d1788d632067de093223e496844943896940bd3b52","title":"","text":"awaiting <-chan interface{} finished *time.Time lock sync.Mutex notify chan struct{} notify chan bool } // Operations tracks all the ongoing operations."} {"_id":"doc-en-kubernetes-ced0b8e6fa864d9fa60896c3250a84cbb69847c6c7846eb7574550974e14782e","title":"","text":"op := &Operation{ ID: strconv.FormatInt(id, 10), awaiting: from, notify: make(chan struct{}), notify: make(chan bool, 1), } go op.wait() go ops.insert(op)"} {"_id":"doc-en-kubernetes-25a8ad0042b924a0b129403aefa292183d4090581f9d95c5edc1c92e1f6ec971","title":"","text":"op.result = result finished := time.Now() op.finished = &finished close(op.notify) op.notify <- true } // WaitFor waits for the specified duration, or until the operation finishes,"} {"_id":"doc-en-kubernetes-7aaf93750bb77c6ead92389b9ebe0e2f28f05805da32766bc85ca753f4ef4a78","title":"","text":"select { case <-time.After(timeout): case <-op.notify: // Re-send on this channel in case there are others // waiting for notification. op.notify <- true } }"} {"_id":"doc-en-kubernetes-2c24b5ab99e56bf5e0de51a6a0b55f7caa98cec4232641e1564e83ff1cbef88d","title":"","text":"if accountName == \"\" || accountKey == \"\" { return \"\", \"\", fmt.Errorf(\"Invalid %v/%v, couldn't extract azurestorageaccountname or azurestorageaccountkey\", nameSpace, secretName) } accountName = strings.TrimSpace(accountName) return accountName, accountKey, nil }"} {"_id":"doc-en-kubernetes-7fc976d67ffee16fa08bf30f74baad28cc17bd0359f658f81a8330846e76f0e4","title":"","text":"\"//vendor/k8s.io/client-go/discovery:go_default_library\", ], ) go_test( name = \"go_default_test\", srcs = [\"status_strategy_test.go\"], embed = [\":go_default_library\"], deps = [\"//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library\"], ) "} {"_id":"doc-en-kubernetes-df4de7cc42d96dce751926b8330b4521e708b4dfa710337afe244e6b4edbd084","title":"","text":"} func (a statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) { // update is only allowed to set status newCustomResourceObject := obj.(*unstructured.Unstructured) oldCustomResourceObject := old.(*unstructured.Unstructured) newCustomResource := newCustomResourceObject.UnstructuredContent() oldCustomResource := oldCustomResourceObject.UnstructuredContent() // update is not allowed to set spec and metadata _, ok1 := newCustomResource[\"spec\"] _, ok2 := oldCustomResource[\"spec\"] switch { case ok2: newCustomResource[\"spec\"] = oldCustomResource[\"spec\"] case ok1: delete(newCustomResource, \"spec\") } status, ok := newCustomResource[\"status\"] newCustomResourceObject.SetAnnotations(oldCustomResourceObject.GetAnnotations()) newCustomResourceObject.SetFinalizers(oldCustomResourceObject.GetFinalizers()) newCustomResourceObject.SetGeneration(oldCustomResourceObject.GetGeneration()) newCustomResourceObject.SetLabels(oldCustomResourceObject.GetLabels()) newCustomResourceObject.SetOwnerReferences(oldCustomResourceObject.GetOwnerReferences()) newCustomResourceObject.SetSelfLink(oldCustomResourceObject.GetSelfLink()) // copy old object into new object oldCustomResourceObject := old.(*unstructured.Unstructured) // overridding the resourceVersion in metadata is safe here, we have already checked that // new object and old object have the same resourceVersion. *newCustomResourceObject = *oldCustomResourceObject.DeepCopy() // set status newCustomResource = newCustomResourceObject.UnstructuredContent() if ok { newCustomResource[\"status\"] = status } else { delete(newCustomResource, \"status\") } } // ValidateUpdate is the default update validation for an end user updating status."} {"_id":"doc-en-kubernetes-cc8d73082ee0a6cf5a5c647e6c2d1f3d68c5a6039ff062c05ebd63a78c03ff3e","title":"","text":" /* Copyright 2018 The Kubernetes Authors. 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. */ package customresource import ( \"context\" \"reflect\" \"testing\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" ) func TestPrepareForUpdate(t *testing.T) { strategy := statusStrategy{} tcs := []struct { old *unstructured.Unstructured obj *unstructured.Unstructured expected *unstructured.Unstructured }{ { // changes to spec are ignored old: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, obj: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"new\", }, }, expected: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, }, { // changes to other places are also ignored old: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, obj: &unstructured.Unstructured{ Object: map[string]interface{}{ \"new\": \"new\", }, }, expected: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, }, { // delete status old: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", \"status\": \"old\", }, }, obj: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, expected: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", }, }, }, { // update status old: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", \"status\": \"old\", }, }, obj: &unstructured.Unstructured{ Object: map[string]interface{}{ \"status\": \"new\", }, }, expected: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", \"status\": \"new\", }, }, }, { // update status and other parts old: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", \"status\": \"old\", }, }, obj: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"new\", \"new\": \"new\", \"status\": \"new\", }, }, expected: &unstructured.Unstructured{ Object: map[string]interface{}{ \"spec\": \"old\", \"status\": \"new\", }, }, }, } for index, tc := range tcs { strategy.PrepareForUpdate(context.TODO(), tc.obj, tc.old) if !reflect.DeepEqual(tc.obj, tc.expected) { t.Errorf(\"test %d failed: expected: %v, got %v\", index, tc.expected, tc.obj) } } } "} {"_id":"doc-en-kubernetes-56074765ee78b5099d19c292add9601ee62c1a8386c52a62f260a034eecf1c61","title":"","text":"var IP string // TODO: Remove this when sandbox is available on windows // Currently windows supports both sandbox and non-sandbox cases. // This is a workaround for windows, where sandbox is not in use, and pod IP is determined through containers belonging to the Pod. if IP = ds.determinePodIPBySandboxID(podSandboxID); IP == \"\" { if IP = ds.determinePodIPBySandboxID(podSandboxID, r); IP == \"\" { IP = ds.getIP(podSandboxID, r) }"} {"_id":"doc-en-kubernetes-4f3c41974a04165cab2894c50a40aa42cc6c74311beba8f2362f87b8831c0399","title":"","text":"return nil } func (ds *dockerService) determinePodIPBySandboxID(uid string) string { func (ds *dockerService) determinePodIPBySandboxID(uid string, sandbox *dockertypes.ContainerJSON) string { return \"\" }"} {"_id":"doc-en-kubernetes-b8170980a30ca903fd4aae204865d2d3bcd4ec8a43be4216f48c64f38ae65513","title":"","text":"return nil } func (ds *dockerService) determinePodIPBySandboxID(uid string) string { func (ds *dockerService) determinePodIPBySandboxID(uid string, sandbox *dockertypes.ContainerJSON) string { glog.Warningf(\"determinePodIPBySandboxID is unsupported in this build\") return \"\" }"} {"_id":"doc-en-kubernetes-588cc563be510f0356effe4c28f3306bfcb0a07c8dd49a8446649c355ad6ff71","title":"","text":"return nil } func (ds *dockerService) determinePodIPBySandboxID(sandboxID string) string { func (ds *dockerService) determinePodIPBySandboxID(sandboxID string, sandbox *dockertypes.ContainerJSON) string { // Versions and feature support // ============================ // Windows version >= Windows Server, Version 1709, Supports both sandbox and non-sandbox case // Windows version == Windows Server 2016 Support only non-sandbox case // Windows version < Windows Server 2016 is Not Supported // Sandbox support in Windows mandates CNI Plugin. // Presence of CONTAINER_NETWORK flag is considered as non-Sandbox cases here // Hyper-V isolated containers are also considered as non-Sandbox cases // Todo: Add a kernel version check for more validation // Hyper-V only supports one container per Pod yet and the container will have a different // IP address from sandbox. Retrieve the IP from the containers as this is a non-Sandbox case. // TODO(feiskyer): remove this workaround after Hyper-V supports multiple containers per Pod. if networkMode := os.Getenv(\"CONTAINER_NETWORK\"); networkMode == \"\" && sandbox.HostConfig.Isolation != kubeletapis.HypervIsolationValue { // Sandbox case, fetch the IP from the sandbox container. return ds.getIP(sandboxID, sandbox) } // Non-Sandbox case, fetch the IP from the containers within the Pod. opts := dockertypes.ContainerListOptions{ All: true, Filters: dockerfilters.NewArgs(),"} {"_id":"doc-en-kubernetes-c0b0af6d55ffc112a5f254957dc2a057453c89331cb9bc0c40e38bd49c333831","title":"","text":"continue } // Versions and feature support // ============================ // Windows version == Windows Server, Version 1709,, Supports both sandbox and non-sandbox case // Windows version == Windows Server 2016 Support only non-sandbox case // Windows version < Windows Server 2016 is Not Supported // Sandbox support in Windows mandates CNI Plugin. // Presence of CONTAINER_NETWORK flag is considered as non-Sandbox cases here // Todo: Add a kernel version check for more validation if networkMode := os.Getenv(\"CONTAINER_NETWORK\"); networkMode == \"\" { // On Windows, every container that is created in a Sandbox, needs to invoke CNI plugin again for adding the Network, // with the shared container name as NetNS info, // This is passed down to the platform to replicate some necessary information to the new container // // This place is chosen as a hack for now, since ds.getIP would end up calling CNI's addToNetwork // That is why addToNetwork is required to be idempotent // Instead of relying on this call, an explicit call to addToNetwork should be // done immediately after ContainerCreation, in case of Windows only. TBD Issue # to handle this if r.HostConfig.Isolation == kubeletapis.HypervIsolationValue { // Hyper-V only supports one container per Pod yet and the container will have a different // IP address from sandbox. Return the first non-sandbox container IP as POD IP. // TODO(feiskyer): remove this workaround after Hyper-V supports multiple containers per Pod. if containerIP := ds.getIP(c.ID, r); containerIP != \"\" { return containerIP } } else { // Do not return any IP, so that we would continue and get the IP of the Sandbox ds.getIP(sandboxID, r) } } else { // ds.getIP will call the CNI plugin to fetch the IP if containerIP := ds.getIP(c.ID, r); containerIP != \"\" { return containerIP } if containerIP := ds.getIP(c.ID, r); containerIP != \"\" { return containerIP } }"} {"_id":"doc-en-kubernetes-ff27c54de48bc1d30a989bbec328bd3a5d941cd3df788aa31a6c4e0e00d0075f","title":"","text":"// by REST storage - these typically indicate programmer // error by not using pkg/api/errors, or unexpected failure // cases. runtime.HandleError(fmt.Errorf(\"apiserver received an error that is not an metav1.Status: %v\", err)) runtime.HandleError(fmt.Errorf(\"apiserver received an error that is not an metav1.Status: %#+v\", err)) return &metav1.Status{ TypeMeta: metav1.TypeMeta{ Kind: \"Status\","} {"_id":"doc-en-kubernetes-175a72f7779ce771517cdda80a1df996c7f7b24a80fee8e95ce6259e52892489","title":"","text":"}, { \"ImportPath\": \"github.com/evanphx/json-patch\", \"Rev\": \"ed7cfbae1fffc071f71e068df27bf4f0521402d8\" \"Rev\": \"94e38aa1586e8a6c8a75770bddf5ff84c48a106b\" }, { \"ImportPath\": \"github.com/exponent-io/jsonpath\","} {"_id":"doc-en-kubernetes-11eddce6fd2f02cab044be77bfdbb2b592b786dd676f9b4ccaf5b143b7dc4e77","title":"","text":"}, { \"ImportPath\": \"github.com/evanphx/json-patch\", \"Rev\": \"ed7cfbae1fffc071f71e068df27bf4f0521402d8\" \"Rev\": \"94e38aa1586e8a6c8a75770bddf5ff84c48a106b\" }, { \"ImportPath\": \"github.com/ghodss/yaml\","} {"_id":"doc-en-kubernetes-99ff62c2022af1a3ed2e6bcdac5346cae6b5612ae4d3c5fc1ecc65360713a811","title":"","text":" ## JSON-Patch # JSON-Patch `jsonpatch` is a library which provides functionallity for both applying [RFC6902 JSON patches](http://tools.ietf.org/html/rfc6902) against documents, as well as for calculating & applying [RFC7396 JSON merge patches](https://tools.ietf.org/html/rfc7396). Provides the ability to modify and test a JSON according to a [RFC6902 JSON patch](http://tools.ietf.org/html/rfc6902) and [RFC7396 JSON Merge Patch](https://tools.ietf.org/html/rfc7396). [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) [![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) [![Report Card](https://goreportcard.com/badge/github.com/evanphx/json-patch)](https://goreportcard.com/report/github.com/evanphx/json-patch) *Version*: **1.0** # Get It! [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) **Latest and greatest**: ```bash go get -u github.com/evanphx/json-patch ``` [![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=master)](https://travis-ci.org/evanphx/json-patch) **Stable Versions**: * Version 3: `go get -u gopkg.in/evanphx/json-patch.v3` (previous versions below `v3` are unavailable) # Use It! * [Create and apply a merge patch](#create-and-apply-a-merge-patch) * [Create and apply a JSON Patch](#create-and-apply-a-json-patch) * [Comparing JSON documents](#comparing-json-documents) * [Combine merge patches](#combine-merge-patches) ## Create and apply a merge patch Given both an original JSON document and a modified JSON document, you can create a [Merge Patch](https://tools.ietf.org/html/rfc7396) document. It can describe the changes needed to convert from the original to the modified JSON document. Once you have a merge patch, you can apply it to other JSON documents using the `jsonpatch.MergePatch(document, patch)` function. ```go package main import ( \"fmt\" jsonpatch \"github.com/evanphx/json-patch\" ) func main() { // Let's create a merge patch from these two documents... original := []byte(`{\"name\": \"John\", \"age\": 24, \"height\": 3.21}`) target := []byte(`{\"name\": \"Jane\", \"age\": 24}`) patch, err := jsonpatch.CreateMergePatch(original, target) if err != nil { panic(err) } // Now lets apply the patch against a different JSON document... alternative := []byte(`{\"name\": \"Tina\", \"age\": 28, \"height\": 3.75}`) modifiedAlternative, err := jsonpatch.MergePatch(alternative, patch) fmt.Printf(\"patch document: %sn\", patch) fmt.Printf(\"updated alternative doc: %sn\", modifiedAlternative) } ``` When ran, you get the following output: ```bash $ go run main.go patch document: {\"height\":null,\"name\":\"Jane\"} updated tina doc: {\"age\":28,\"name\":\"Jane\"} ``` ## Create and apply a JSON Patch You can create patch objects using `DecodePatch([]byte)`, which can then be applied against JSON documents. The following is an example of creating a patch from two operations, and applying it against a JSON document. ```go package main import ( \"fmt\" jsonpatch \"github.com/evanphx/json-patch\" ) func main() { original := []byte(`{\"name\": \"John\", \"age\": 24, \"height\": 3.21}`) patchJSON := []byte(`[ {\"op\": \"replace\", \"path\": \"/name\", \"value\": \"Jane\"}, {\"op\": \"remove\", \"path\": \"/height\"} ]`) patch, err := jsonpatch.DecodePatch(patchJSON) if err != nil { panic(err) } modified, err := patch.Apply(original) if err != nil { panic(err) } fmt.Printf(\"Original document: %sn\", original) fmt.Printf(\"Modified document: %sn\", modified) } ``` When ran, you get the following output: ```bash $ go run main.go Original document: {\"name\": \"John\", \"age\": 24, \"height\": 3.21} Modified document: {\"age\":24,\"name\":\"Jane\"} ``` ## Comparing JSON documents Due to potential whitespace and ordering differences, one cannot simply compare JSON strings or byte-arrays directly. As such, you can instead use `jsonpatch.Equal(document1, document2)` to determine if two JSON documents are _structurally_ equal. This ignores whitespace differences, and key-value ordering. ```go package main import ( \"fmt\" jsonpatch \"github.com/evanphx/json-patch\" ) func main() { original := []byte(`{\"name\": \"John\", \"age\": 24, \"height\": 3.21}`) similar := []byte(` { \"age\": 24, \"height\": 3.21, \"name\": \"John\" } `) different := []byte(`{\"name\": \"Jane\", \"age\": 20, \"height\": 3.37}`) if jsonpatch.Equal(original, similar) { fmt.Println(`\"original\" is structurally equal to \"similar\"`) } if !jsonpatch.Equal(original, different) { fmt.Println(`\"original\" is _not_ structurally equal to \"similar\"`) } } ``` When ran, you get the following output: ```bash $ go run main.go \"original\" is structurally equal to \"similar\" \"original\" is _not_ structurally equal to \"similar\" ``` ## Combine merge patches Given two JSON merge patch documents, it is possible to combine them into a single merge patch which can describe both set of changes. The resulting merge patch can be used such that applying it results in a document structurally similar as merging each merge patch to the document in succession. ```go package main import ( \"fmt\" jsonpatch \"github.com/evanphx/json-patch\" ) func main() { original := []byte(`{\"name\": \"John\", \"age\": 24, \"height\": 3.21}`) nameAndHeight := []byte(`{\"height\":null,\"name\":\"Jane\"}`) ageAndEyes := []byte(`{\"age\":4.23,\"eyes\":\"blue\"}`) // Let's combine these merge patch documents... combinedPatch, err := jsonpatch.MergeMergePatches(nameAndHeight, ageAndEyes) if err != nil { panic(err) } // Apply each patch individual against the original document withoutCombinedPatch, err := jsonpatch.MergePatch(original, nameAndHeight) if err != nil { panic(err) } withoutCombinedPatch, err = jsonpatch.MergePatch(withoutCombinedPatch, ageAndEyes) if err != nil { panic(err) } // Apply the combined patch against the original document withCombinedPatch, err := jsonpatch.MergePatch(original, combinedPatch) if err != nil { panic(err) } // Do both result in the same thing? They should! if jsonpatch.Equal(withCombinedPatch, withoutCombinedPatch) { fmt.Println(\"Both JSON documents are structurally the same!\") } fmt.Printf(\"combined merge patch: %s\", combinedPatch) } ``` When ran, you get the following output: ```bash $ go run main.go Both JSON documents are structurally the same! combined merge patch: {\"age\":4.23,\"eyes\":\"blue\",\"height\":null,\"name\":\"Jane\"} ``` # CLI for comparing JSON documents You can install the commandline program `json-patch`. This program can take multiple JSON patch documents as arguments, and fed a JSON document from `stdin`. It will apply the patch(es) against the document and output the modified doc. **patch.1.json** ```json [ {\"op\": \"replace\", \"path\": \"/name\", \"value\": \"Jane\"}, {\"op\": \"remove\", \"path\": \"/height\"} ] ``` **patch.2.json** ```json [ {\"op\": \"add\", \"path\": \"/address\", \"value\": \"123 Main St\"}, {\"op\": \"replace\", \"path\": \"/age\", \"value\": \"21\"} ] ``` ### API Usage **document.json** ```json { \"name\": \"John\", \"age\": 24, \"height\": 3.21 } ``` * Given a `[]byte`, obtain a Patch object You can then run: `obj, err := jsonpatch.DecodePatch(patch)` ```bash $ go install github.com/evanphx/json-patch/cmd/json-patch $ cat document.json | json-patch -p patch.1.json -p patch.2.json {\"address\":\"123 Main St\",\"age\":\"21\",\"name\":\"Jane\"} ``` * Apply the patch and get a new document back # Help It! Contributions are welcomed! Leave [an issue](https://github.com/evanphx/json-patch/issues) or [create a PR](https://github.com/evanphx/json-patch/compare). `out, err := obj.Apply(doc)` * Create a JSON Merge Patch document based on two json documents (a to b): Before creating a pull request, we'd ask that you make sure tests are passing and that you have added new tests when applicable. `mergeDoc, err := jsonpatch.CreateMergePatch(a, b)` * Bonus API: compare documents for structural equality Contributors can run tests using: `jsonpatch.Equal(doca, docb)` ```bash go test -cover ./... ``` Builds for pull requests are tested automatically using [TravisCI](https://travis-ci.org/evanphx/json-patch). "} {"_id":"doc-en-kubernetes-0803131c5f0120628deab42665abd4e36e55e345aca0173db3f46c410d11b9b3","title":"","text":"package jsonpatch import ( \"bytes\" \"encoding/json\" \"fmt\" \"reflect\""} {"_id":"doc-en-kubernetes-f7ce21d49c9cc28eb20a11850a34026bfa251c080f39dedac8a4904e2c2ff4cd","title":"","text":"var errBadJSONDoc = fmt.Errorf(\"Invalid JSON Document\") var errBadJSONPatch = fmt.Errorf(\"Invalid JSON Patch\") var errBadMergeTypes = fmt.Errorf(\"Mismatched JSON Documents\") // MergeMergePatches merges two merge patches together, such that // applying this resulting merged merge patch to a document yields the same"} {"_id":"doc-en-kubernetes-1164aec3e1c35848a8f471a980369a40628f3a3744ba906a5426f3c88f297fc6","title":"","text":"return json.Marshal(doc) } // CreateMergePatch creates a merge patch as specified in http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 // // 'a' is original, 'b' is the modified document. Both are to be given as json encoded content. // The function will return a mergeable json document with differences from a to b. // // An error will be returned if any of the two documents are invalid. func CreateMergePatch(a, b []byte) ([]byte, error) { aI := map[string]interface{}{} bI := map[string]interface{}{} err := json.Unmarshal(a, &aI) // resemblesJSONArray indicates whether the byte-slice \"appears\" to be // a JSON array or not. // False-positives are possible, as this function does not check the internal // structure of the array. It only checks that the outer syntax is present and // correct. func resemblesJSONArray(input []byte) bool { input = bytes.TrimSpace(input) hasPrefix := bytes.HasPrefix(input, []byte(\"[\")) hasSuffix := bytes.HasSuffix(input, []byte(\"]\")) return hasPrefix && hasSuffix } // CreateMergePatch will return a merge patch document capable of converting // the original document(s) to the modified document(s). // The parameters can be bytes of either two JSON Documents, or two arrays of // JSON documents. // The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalResemblesArray := resemblesJSONArray(originalJSON) modifiedResemblesArray := resemblesJSONArray(modifiedJSON) // Do both byte-slices seem like JSON arrays? if originalResemblesArray && modifiedResemblesArray { return createArrayMergePatch(originalJSON, modifiedJSON) } // Are both byte-slices are not arrays? Then they are likely JSON objects... if !originalResemblesArray && !modifiedResemblesArray { return createObjectMergePatch(originalJSON, modifiedJSON) } // None of the above? Then return an error because of mismatched types. return nil, errBadMergeTypes } // createObjectMergePatch will return a merge-patch document capable of // converting the original document to the modified document. func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDoc := map[string]interface{}{} modifiedDoc := map[string]interface{}{} err := json.Unmarshal(originalJSON, &originalDoc) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(b, &bI) err = json.Unmarshal(modifiedJSON, &modifiedDoc) if err != nil { return nil, errBadJSONDoc } dest, err := getDiff(aI, bI) dest, err := getDiff(originalDoc, modifiedDoc) if err != nil { return nil, err } return json.Marshal(dest) } // createArrayMergePatch will return an array of merge-patch documents capable // of converting the original document to the modified document for each // pair of JSON documents provided in the arrays. // Arrays of mismatched sizes will result in an error. func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDocs := []json.RawMessage{} modifiedDocs := []json.RawMessage{} err := json.Unmarshal(originalJSON, &originalDocs) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(modifiedJSON, &modifiedDocs) if err != nil { return nil, errBadJSONDoc } total := len(originalDocs) if len(modifiedDocs) != total { return nil, errBadJSONDoc } result := []json.RawMessage{} for i := 0; i < len(originalDocs); i++ { original := originalDocs[i] modified := modifiedDocs[i] patch, err := createObjectMergePatch(original, modified) if err != nil { return nil, err } result = append(result, json.RawMessage(patch)) } return json.Marshal(result) } // Returns true if the array matches (must be json types). // As is idiomatic for go, an empty array is not the same as a nil array. func matchesArray(a, b []interface{}) bool {"} {"_id":"doc-en-kubernetes-0add3ab52da07373382c08191a9be6f440603d7147db0ac32bea34055c83d973","title":"","text":"} idx = len(ary) - idx } if idx < 0 || idx >= len(ary) || idx > len(cur) { return fmt.Errorf(\"Unable to access invalid index: %d\", idx) } copy(ary[0:idx], cur[0:idx]) ary[idx] = val copy(ary[idx+1:], cur[idx:])"} {"_id":"doc-en-kubernetes-00ab173a7273fc84a2bc1d8066783539b20408331794f49cfd4d736e063f6eaa","title":"","text":"return fmt.Errorf(\"couldn't get key for object %#v: %v\", ds, err) } // If the DaemonSet is being deleted (either by foreground deletion or // orphan deletion), we cannot be sure if the DaemonSet history objects // it owned still exist -- those history objects can either be deleted // or orphaned. Garbage collector doesn't guarantee that it will delete // DaemonSet pods before deleting DaemonSet history objects, because // DaemonSet history doesn't own DaemonSet pods. We cannot reliably // calculate the status of a DaemonSet being deleted. Therefore, return // here without updating status for the DaemonSet being deleted. if ds.DeletionTimestamp != nil { return nil } // Construct histories of the DaemonSet, and get the hash of current history cur, old, err := dsc.constructHistory(ds) if err != nil {"} {"_id":"doc-en-kubernetes-282666b6c403db4082c0e6b2a69647e19c09a42fc69233b3d07c7f96acbc62e0","title":"","text":"} hash := cur.Labels[apps.DefaultDaemonSetUniqueLabelKey] if ds.DeletionTimestamp != nil || !dsc.expectations.SatisfiedExpectations(dsKey) { if !dsc.expectations.SatisfiedExpectations(dsKey) { // Only update status. return dsc.updateDaemonSetStatus(ds, hash) }"} {"_id":"doc-en-kubernetes-89bf0e337d947ff2c48c09663aeca2a6f2cfc6d90e03879477c615253d40b9a1","title":"","text":"\"//vendor/github.com/renstrom/dedent:go_default_library\", \"//vendor/github.com/spf13/cobra:go_default_library\", \"//vendor/github.com/spf13/pflag:go_default_library\", \"//vendor/k8s.io/api/apps/v1:go_default_library\", \"//vendor/k8s.io/api/autoscaling/v1:go_default_library\", \"//vendor/k8s.io/api/core/v1:go_default_library\", \"//vendor/k8s.io/api/policy/v1beta1:go_default_library\","} {"_id":"doc-en-kubernetes-a6f854f8c58ad347a659df0e7ccdf3a5fafbd5b87621ceadbd7a81dfd72b7851","title":"","text":"\"//vendor/k8s.io/apimachinery/pkg/util/net:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/strategicpatch:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/uuid:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library\", \"//vendor/k8s.io/apimachinery/pkg/util/yaml:go_default_library\","} {"_id":"doc-en-kubernetes-c4a43762325f944e4f8bb0b3a20be61451d074616ddf8569dad649f82e77c6fb","title":"","text":"\"github.com/golang/glog\" \"github.com/spf13/cobra\" appsv1 \"k8s.io/api/apps/v1\" \"k8s.io/apimachinery/pkg/api/errors\" \"k8s.io/apimachinery/pkg/api/meta\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/dynamic\" \"k8s.io/kubernetes/pkg/kubectl/cmd/templates\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\""} {"_id":"doc-en-kubernetes-93c0349ad9b099d85843a2b6c0e05970ce4554005e7ce5a9aea57a9bb6157549","title":"","text":"} func (o *DeleteOptions) deleteResource(info *resource.Info, deleteOptions *metav1.DeleteOptions) error { // TODO: this should be removed as soon as DaemonSet controller properly handles object deletion // see https://github.com/kubernetes/kubernetes/issues/64313 for details mapping := info.ResourceMapping() if mapping.Resource.GroupResource() == (schema.GroupResource{Group: \"extensions\", Resource: \"daemonsets\"}) || mapping.Resource.GroupResource() == (schema.GroupResource{Group: \"apps\", Resource: \"daemonsets\"}) { if err := updateDaemonSet(info.Namespace, info.Name, o.DynamicClient); err != nil { return err } } if err := resource.NewHelper(info.Client, info.Mapping).DeleteWithOptions(info.Namespace, info.Name, deleteOptions); err != nil { return cmdutil.AddSourceToErr(\"deleting\", info.Source, err) }"} {"_id":"doc-en-kubernetes-e0db50370527f553ae4f01461aa7f51ebe2d2981cf3c2cd3b6b553d9c7c4616c","title":"","text":"return nil } func updateDaemonSet(namespace, name string, dynamicClient dynamic.Interface) error { dsClient := dynamicClient.Resource(schema.GroupVersionResource{Group: \"apps\", Version: \"v1\", Resource: \"daemonsets\"}).Namespace(namespace) obj, err := dsClient.Get(name, metav1.GetOptions{}) if err != nil { return err } ds := &appsv1.DaemonSet{} if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, ds); err != nil { return err } // We set the nodeSelector to a random label. This label is nearly guaranteed // to not be set on any node so the DameonSetController will start deleting // daemon pods. Once it's done deleting the daemon pods, it's safe to delete // the DaemonSet. ds.Spec.Template.Spec.NodeSelector = map[string]string{ string(uuid.NewUUID()): string(uuid.NewUUID()), } // force update to avoid version conflict ds.ResourceVersion = \"\" out, err := runtime.DefaultUnstructuredConverter.ToUnstructured(ds) if err != nil { return err } if _, err = dsClient.Update(&unstructured.Unstructured{Object: out}); err != nil { return err } // Wait for the daemon set controller to kill all the daemon pods. if err := wait.Poll(1*time.Second, 5*time.Minute, func() (bool, error) { updatedObj, err := dsClient.Get(name, metav1.GetOptions{}) if err != nil { return false, nil } updatedDS := &appsv1.DaemonSet{} if err := runtime.DefaultUnstructuredConverter.FromUnstructured(updatedObj.Object, ds); err != nil { return false, nil } return updatedDS.Status.CurrentNumberScheduled+updatedDS.Status.NumberMisscheduled == 0, nil }); err != nil { return err } return nil } // deletion printing is special because we do not have an object to print. // This mirrors name printer behavior func (o *DeleteOptions) PrintObj(info *resource.Info) {"} {"_id":"doc-en-kubernetes-1d17b48875eea0e3c912ae5218c4326901c0833c6ea252050b38a8af56953536","title":"","text":"deleteFlags.AddFlags(cmd) cmd.Flags().Bool(\"wait\", true, `If true, wait for resources to be gone before returning. This waits for finalizers.`) cmdutil.AddIncludeUninitializedFlag(cmd) return cmd }"} {"_id":"doc-en-kubernetes-0b1a184c38e88e5f6a5b939d7fd9ce5a98f58791e3e1b31e2a9ed594291b45aa","title":"","text":"} if o.GracePeriod == 0 && !o.ForceDeletion { // To preserve backwards compatibility, but prevent accidental data loss, we convert --grace-period=0 // into --grace-period=1 and wait until the object is successfully deleted. Users may provide --force // to bypass this wait. o.WaitForDeletion = true // into --grace-period=1. Users may provide --force to bypass this conversion. o.GracePeriod = 1 } if b, err := cmd.Flags().GetBool(\"wait\"); err == nil { o.WaitForDeletion = b } includeUninitialized := cmdutil.ShouldIncludeUninitialized(cmd, false) r := f.NewBuilder()."} {"_id":"doc-en-kubernetes-5a09d02bf9378c6b24a6d6727da75626014c402cf89a7b31df2559b0798a8152","title":"","text":"return fmt.Errorf(\"cannot set --all and --field-selector at the same time\") } if o.GracePeriod == 0 && !o.ForceDeletion && !o.WaitForDeletion { // With the explicit --wait flag we need extra validation for backward compatibility return fmt.Errorf(\"--grace-period=0 must have either --force specified, or --wait to be set to true\") } switch { case o.GracePeriod == 0 && o.ForceDeletion: fmt.Fprintf(o.ErrOut, \"warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.n\")"} {"_id":"doc-en-kubernetes-856715a22bc219c11171ff6d2f97deec6fd1278279a29bb5f1738a1c9b2f1226","title":"","text":"IgnoreNotFound *bool Now *bool Timeout *time.Duration Wait *bool Output *string }"} {"_id":"doc-en-kubernetes-f404757df0dd344cfd6b77dee5259e2dae5a1fc0cfbca305b8acbc5a7ed33a13","title":"","text":"if f.Timeout != nil { options.Timeout = *f.Timeout } if f.Wait != nil { options.WaitForDeletion = *f.Wait } return options }"} {"_id":"doc-en-kubernetes-d48d60801f6dbded1d2eade1321bfa4bb88e9ac06ef9c50e84aee286e248a38c","title":"","text":"if f.IgnoreNotFound != nil { cmd.Flags().BoolVar(f.IgnoreNotFound, \"ignore-not-found\", *f.IgnoreNotFound, \"Treat \"resource not found\" as a successful delete. Defaults to \"true\" when --all is specified.\") } if f.Wait != nil { cmd.Flags().BoolVar(f.Wait, \"wait\", *f.Wait, \"If true, wait for resources to be gone before returning. This waits for finalizers.\") } if f.Output != nil { cmd.Flags().StringVarP(f.Output, \"output\", \"o\", *f.Output, \"Output mode. Use \"-o name\" for shorter output (resource/name).\") } } // NewDeleteCommandFlags provides default flags and values for use with the \"delete\" command"} {"_id":"doc-en-kubernetes-65db481d201103f891c95778499e3118e87e9317b34373c6a7b45e0d913431aa","title":"","text":"labelSelector := \"\" fieldSelector := \"\" timeout := time.Duration(0) wait := true filenames := []string{} recursive := false"} {"_id":"doc-en-kubernetes-9d1828919b20f69b99e7694c51859d0f928f93ec560b191cd73786666ced95dc","title":"","text":"IgnoreNotFound: &ignoreNotFound, Now: &now, Timeout: &timeout, Wait: &wait, Output: &output, } }"} {"_id":"doc-en-kubernetes-ce7d3d9c789aeb3d5eb3b3bb0c0b7ca381399c7d150b58ee2b215071eadd48de","title":"","text":"force := false timeout := time.Duration(0) wait := false filenames := []string{} recursive := false"} {"_id":"doc-en-kubernetes-31dd2c9e63059a24ade46266128cdedf1a4d2da4e0ef8129b5d2d8245d7594d9","title":"","text":"// add non-defaults Force: &force, Timeout: &timeout, Wait: &wait, } }"} {"_id":"doc-en-kubernetes-82564835e356a2b5a605c940799f7a9cc4aa1247f5ce06d0009296a94699dca5","title":"","text":"effectiveTimeout = 168 * time.Hour } waitOptions := kubectlwait.WaitOptions{ ResourceFinder: genericclioptions.ResourceFinderForResult(o.Result), ResourceFinder: genericclioptions.ResourceFinderForResult(r), DynamicClient: o.DynamicClient, Timeout: effectiveTimeout,"} {"_id":"doc-en-kubernetes-02690a6908678c5f12e0086125be41c1ac381c9e444b8ff323a31f426e891524","title":"","text":"operator: Exists - key: {{ .MasterTaintKey }} effect: NoSchedule # TODO: Remove this affinity field as soon as we are using manifest lists affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: beta.kubernetes.io/arch operator: In values: - {{ .Arch }} nodeSelector: beta.kubernetes.io/arch: {{ .Arch }} ` // KubeDNSService is the kube-dns Service manifest"} {"_id":"doc-en-kubernetes-f8127fde80f95078705e86bf5bdde69d056c3311659f09cb680cbf3eb88c1881","title":"","text":"importpath = \"k8s.io/kubernetes/cmd/kubeadm/app/phases/addons/proxy\", deps = [ \"//cmd/kubeadm/app/apis/kubeadm:go_default_library\", \"//cmd/kubeadm/app/constants:go_default_library\", \"//cmd/kubeadm/app/util:go_default_library\", \"//cmd/kubeadm/app/util/apiclient:go_default_library\", \"//pkg/proxy/apis/kubeproxyconfig/scheme:go_default_library\","} {"_id":"doc-en-kubernetes-a9d209d667f38f7e6aaa41ccc4a4fd20a626273c5a7a0acad1f8482155234d78","title":"","text":"readOnly: true hostNetwork: true serviceAccountName: kube-proxy tolerations: - operator: Exists volumes: - name: kube-proxy configMap:"} {"_id":"doc-en-kubernetes-35094439a4babfa0e28a96287ae0cf2bfdd63cbdfb8c714ceae04f9e3357c515","title":"","text":"- name: lib-modules hostPath: path: /lib/modules tolerations: - key: CriticalAddonsOnly operator: Exists - key: {{ .MasterTaintKey }} effect: NoSchedule nodeSelector: beta.kubernetes.io/arch: {{ .Arch }} ` )"} {"_id":"doc-en-kubernetes-c734566f26a8908e64fea5910175b011dc1363fcba5605b958dd8e59df94061e","title":"","text":"clientset \"k8s.io/client-go/kubernetes\" clientsetscheme \"k8s.io/client-go/kubernetes/scheme\" kubeadmapi \"k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm\" kubeadmconstants \"k8s.io/kubernetes/cmd/kubeadm/app/constants\" kubeadmutil \"k8s.io/kubernetes/cmd/kubeadm/app/util\" \"k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient\" kubeproxyconfigscheme \"k8s.io/kubernetes/pkg/proxy/apis/kubeproxyconfig/scheme\""} {"_id":"doc-en-kubernetes-f98990551677d2eb0a78ac850844bdbde89593f36f43dd5ee18aff72cb068120","title":"","text":"if err != nil { return fmt.Errorf(\"error when parsing kube-proxy configmap template: %v\", err) } proxyDaemonSetBytes, err = kubeadmutil.ParseTemplate(KubeProxyDaemonSet19, struct{ ImageRepository, Arch, Version, ImageOverride string }{ proxyDaemonSetBytes, err = kubeadmutil.ParseTemplate(KubeProxyDaemonSet19, struct{ ImageRepository, Arch, Version, ImageOverride, MasterTaintKey string }{ ImageRepository: cfg.GetControlPlaneImageRepository(), Arch: runtime.GOARCH, Version: kubeadmutil.KubernetesVersionToImageTag(cfg.KubernetesVersion), ImageOverride: cfg.UnifiedControlPlaneImage, MasterTaintKey: kubeadmconstants.LabelNodeRoleMaster, }) if err != nil { return fmt.Errorf(\"error when parsing kube-proxy daemonset template: %v\", err)"} {"_id":"doc-en-kubernetes-4a07aa35a20bf8fd245630430bf1b640508bd2d30458c22c7e255728e3866ea3","title":"","text":"spec = specHandler.DefaultSpec() } // Pass all parameters as volume labels for Portworx server-side processing. spec.VolumeLabels = p.options.Parameters // Pass all parameters as volume labels for Portworx server-side processing if len(p.options.Parameters) > 0 { spec.VolumeLabels = p.options.Parameters } else { spec.VolumeLabels = make(map[string]string, 0) } // Update the requested size in the spec spec.Size = uint64(requestGiB * volutil.GIB)"} {"_id":"doc-en-kubernetes-7a4eaf43aa0bd0d84f0268fd23045463ff1116a99a547c0f8a5d6b3528b56eb9","title":"","text":"// HTTP Handler interface func (server *ApiServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { defer func() { if x := recover(); x != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, \"apiserver panic. Look in log for details.\") log.Printf(\"ApiServer panic'd: %#vn\", x) } }() log.Printf(\"%s %s\", req.Method, req.RequestURI) url, err := url.ParseRequestURI(req.RequestURI) if err != nil {"} {"_id":"doc-en-kubernetes-7c745702c09c787796bc28e29caedbad44840f9c5998b0e5a3885524fd0ae82d","title":"","text":"func (storage *ControllerRegistryStorage) Get(id string) (interface{}, error) { controller, err := storage.registry.GetController(id) if err != nil { return nil, err } controller.Kind = \"cluster#replicationController\" return controller, err }"} {"_id":"doc-en-kubernetes-5a0a01fe3b3fe2d366548efd9f6857c7393f66d34edfcc5c62489d9a1d53e135","title":"","text":"func (sr *ServiceRegistryStorage) List(*url.URL) (interface{}, error) { list, err := sr.registry.ListServices() if err != nil { return nil, err } list.Kind = \"cluster#serviceList\" return list, err } func (sr *ServiceRegistryStorage) Get(id string) (interface{}, error) { service, err := sr.registry.GetService(id) if err != nil { return nil, err } service.Kind = \"cluster#service\" return service, err }"} {"_id":"doc-en-kubernetes-d33b707f29baa9c9af4758d055c2032d52d855a9669940d0516e2419bfe44dbd","title":"","text":"fi } # A helper function to set up a custom yaml for a k8s addon. # # $1: addon category under /etc/kubernetes # $2: manifest source dir # $3: manifest file # $4: custom yaml function setup-addon-custom-yaml { local -r manifest_path=\"/etc/kubernetes/$1/$2/$3\" local -r custom_yaml=\"$4\" if [ -n \"${custom_yaml:-}\" ]; then # Replace with custom manifest. cat > \"${manifest_path}\" < # Prepares the manifests of k8s addons, and starts the addon manager. # Vars assumed: # CLUSTER_NAME"} {"_id":"doc-en-kubernetes-19186301e5d2b90500c4c8c9cf1a02506a2ef825e3b1016787debbd528666345","title":"","text":"if [[ \"${NETWORK_POLICY_PROVIDER:-}\" == \"calico\" ]]; then setup-addon-manifests \"addons\" \"calico-policy-controller\" setup-addon-custom-yaml \"addons\" \"calico-policy-controller\" \"calico-node-daemonset.yaml\" \"${CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}\" setup-addon-custom-yaml \"addons\" \"calico-policy-controller\" \"typha-deployment.yaml\" \"${CUSTOM_TYPHA_DEPLOYMENT_YAML:-}\" # Configure Calico CNI directory. local -r ds_file=\"${dst_dir}/calico-policy-controller/calico-node-daemonset.yaml\" sed -i -e \"s@__CALICO_CNI_DIR__@/home/kubernetes/bin@g\" \"${ds_file}\""} {"_id":"doc-en-kubernetes-f784aefd05b036ee783a6e78488e9a2ad09072d3a90a5a8c9610d5c27ff7d116","title":"","text":"} // add service Cluster IP:Port to kubeServiceAccess ip set for the purpose of solving hairpin. // proxier.kubeServiceAccessSet.activeEntries.Insert(entry.String()) // Install masquerade rules if 'masqueradeAll' or 'clusterCIDR' is specified. if proxier.masqueradeAll || len(proxier.clusterCIDR) > 0 { if valid := proxier.ipsetList[kubeClusterIPSet].validateEntry(entry); !valid { glog.Errorf(\"%s\", fmt.Sprintf(EntryInvalidErr, entry, proxier.ipsetList[kubeClusterIPSet].Name)) continue } proxier.ipsetList[kubeClusterIPSet].activeEntries.Insert(entry.String()) if valid := proxier.ipsetList[kubeClusterIPSet].validateEntry(entry); !valid { glog.Errorf(\"%s\", fmt.Sprintf(EntryInvalidErr, entry, proxier.ipsetList[kubeClusterIPSet].Name)) continue } proxier.ipsetList[kubeClusterIPSet].activeEntries.Insert(entry.String()) // ipvs call serv := &utilipvs.VirtualServer{ Address: svcInfo.ClusterIP,"} {"_id":"doc-en-kubernetes-14407ec943bbe2a833b9145f463d1fda4d60687e4580098f3c7c9d3752ad7fea","title":"","text":"// KindFor fulfills meta.RESTMapper func (e shortcutExpander) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { return e.RESTMapper.KindFor(e.expandResourceShortcut(resource)) // expandResourceShortcut works with current API resources as read from discovery cache. // In case of new CRDs this means we potentially don't have current state of discovery. // In the current wiring in k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#toRESTMapper, // we are using DeferredDiscoveryRESTMapper which on KindFor failure will clear the // cache and fetch all data from a cluster (see vendor/k8s.io/client-go/restmapper/discovery.go#KindFor). // Thus another call to expandResourceShortcut, after a NoMatchError should successfully // read Kind to the user or an error. gvk, err := e.RESTMapper.KindFor(e.expandResourceShortcut(resource)) if meta.IsNoMatchError(err) { return e.RESTMapper.KindFor(e.expandResourceShortcut(resource)) } return gvk, err } // KindsFor fulfills meta.RESTMapper"} {"_id":"doc-en-kubernetes-db34ab19d1b3b6cdeac3d0f20a280b9f02a765d3be88a2b2088da7ebcd25e67f","title":"","text":"\"testing\" openapi_v2 \"github.com/google/gnostic/openapiv2\" \"github.com/google/go-cmp/cmp\" \"k8s.io/apimachinery/pkg/api/errors\" \"k8s.io/apimachinery/pkg/api/meta\""} {"_id":"doc-en-kubernetes-9091df387423e28854bf13ceb057fcd3262e867c3191fdad566db2601fa6a9e1","title":"","text":"} } func TestKindForWithNewCRDs(t *testing.T) { tests := map[string]struct { in schema.GroupVersionResource expected schema.GroupVersionKind srvRes []*metav1.APIResourceList }{ \"\": { in: schema.GroupVersionResource{Group: \"a\", Version: \"\", Resource: \"sc\"}, expected: schema.GroupVersionKind{Group: \"a\", Version: \"v1\", Kind: \"StorageClass\"}, srvRes: []*metav1.APIResourceList{ { GroupVersion: \"a/v1\", APIResources: []metav1.APIResource{ { Name: \"storageclasses\", ShortNames: []string{\"sc\"}, Kind: \"StorageClass\", }, }, }, }, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { invalidateCalled := false fakeDiscovery := &fakeDiscoveryClient{} fakeDiscovery.serverResourcesHandler = func() ([]*metav1.APIResourceList, error) { if invalidateCalled { return test.srvRes, nil } return []*metav1.APIResourceList{}, nil } fakeCachedDiscovery := &fakeCachedDiscoveryClient{DiscoveryInterface: fakeDiscovery} fakeCachedDiscovery.invalidateHandler = func() { invalidateCalled = true } fakeCachedDiscovery.freshHandler = func() bool { return invalidateCalled } // in real world the discovery client is fronted with a cache which // will answer the initial request, only failure to match will trigger // the cache invalidation and live discovery call delegate := NewDeferredDiscoveryRESTMapper(fakeCachedDiscovery) mapper := NewShortcutExpander(delegate, fakeCachedDiscovery) gvk, err := mapper.KindFor(test.in) if err != nil { t.Errorf(\"unexpected error: %v\", err) } if diff := cmp.Equal(gvk, test.expected); !diff { t.Errorf(\"unexpected data returned %#v, expected %#v\", gvk, test.expected) } }) } } type fakeRESTMapper struct { kindForInput schema.GroupVersionResource }"} {"_id":"doc-en-kubernetes-d0f35c768c261ce23f69c7d28c5f6685c26d9a095d3ad6c683a626b3c47b70b4","title":"","text":"func (c *fakeDiscoveryClient) OpenAPIV3() openapi.Client { panic(\"implement me\") } type fakeCachedDiscoveryClient struct { discovery.DiscoveryInterface freshHandler func() bool invalidateHandler func() } var _ discovery.CachedDiscoveryInterface = &fakeCachedDiscoveryClient{} func (c *fakeCachedDiscoveryClient) Fresh() bool { if c.freshHandler != nil { return c.freshHandler() } return true } func (c *fakeCachedDiscoveryClient) Invalidate() { if c.invalidateHandler != nil { c.invalidateHandler() } } "} {"_id":"doc-en-kubernetes-1511b6830b73c92e0ea4983798d87ccbf9ba30a686558216b45f4878dc1c6b9a","title":"","text":"\"//staging/src/k8s.io/api/policy/v1beta1:go_default_library\", \"//staging/src/k8s.io/api/rbac/v1:go_default_library\", \"//staging/src/k8s.io/api/rbac/v1beta1:go_default_library\", \"//staging/src/k8s.io/api/scheduling/v1alpha1:go_default_library\", \"//staging/src/k8s.io/api/scheduling/v1beta1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/equality:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/meta:go_default_library\","} {"_id":"doc-en-kubernetes-0f0a2e16cb7b5b2f8a58896ac8a253074f02306a2d4201756d7fca960296ef54","title":"","text":"\"//staging/src/k8s.io/api/policy/v1beta1:go_default_library\", \"//staging/src/k8s.io/api/rbac/v1:go_default_library\", \"//staging/src/k8s.io/api/rbac/v1beta1:go_default_library\", \"//staging/src/k8s.io/api/scheduling/v1alpha1:go_default_library\", \"//staging/src/k8s.io/api/scheduling/v1beta1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/meta:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/resource:go_default_library\","} {"_id":"doc-en-kubernetes-792f83cca1832114f2d369886a96c2c5282081d3e0ab09719b3528773aab4bb1","title":"","text":"import ( \"fmt\" scheduling \"k8s.io/api/scheduling/v1alpha1\" scheduling \"k8s.io/api/scheduling/v1beta1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" )"} {"_id":"doc-en-kubernetes-46765996db9a3e2a9a03353216e97024fac99ac0aafda26c2a6bf5f2bcceca89","title":"","text":"package kubectl import ( scheduling \"k8s.io/api/scheduling/v1alpha1\" scheduling \"k8s.io/api/scheduling/v1beta1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"reflect\""} {"_id":"doc-en-kubernetes-669a6cb229bc12b123e7b6b5e7f8c326e0a70515200df16db8aa4616c22bd739","title":"","text":"} }, ContainerGCPeriod, wait.NeverStop) stopChan := make(chan struct{}) defer close(stopChan) // when the high threshold is set to 100, stub the image GC manager if kl.kubeletConfiguration.ImageGCHighThresholdPercent == 100 { glog.V(2).Infof(\"ImageGCHighThresholdPercent is set 100, Disable image GC\") go func() { stopChan <- struct{}{} }() return } prevImageGCFailed := false"} {"_id":"doc-en-kubernetes-7b6947e210bbff73465be727b322cac049f9dd9799fa509f7124b93ae5762754","title":"","text":"glog.V(vLevel).Infof(\"Image garbage collection succeeded\") } }, ImageGCPeriod, stopChan) }, ImageGCPeriod, wait.NeverStop) } // initializeModules will initialize internal modules that do not require the container runtime to be up."} {"_id":"doc-en-kubernetes-7d7f1ac1994a33c3e180dbe7934e1a8b4fbde0c21b42d3b239cbcbf72af2e7e3","title":"","text":"return allErrs } // validateTopologySelectorLabelRequirement tests that the specified TopologySelectorLabelRequirement fields has valid data func validateTopologySelectorLabelRequirement(rq core.TopologySelectorLabelRequirement, fldPath *field.Path) field.ErrorList { // validateTopologySelectorLabelRequirement tests that the specified TopologySelectorLabelRequirement fields has valid data, // and constructs a set containing all of its Values. func validateTopologySelectorLabelRequirement(rq core.TopologySelectorLabelRequirement, fldPath *field.Path) (sets.String, field.ErrorList) { allErrs := field.ErrorList{} valueSet := make(sets.String) valuesPath := fldPath.Child(\"values\") if len(rq.Values) == 0 { allErrs = append(allErrs, field.Forbidden(fldPath.Child(\"values\"), \"must specify as least one value\")) allErrs = append(allErrs, field.Required(valuesPath, \"\")) } // Validate set property of Values field for i, value := range rq.Values { if valueSet.Has(value) { allErrs = append(allErrs, field.Duplicate(valuesPath.Index(i), value)) } valueSet.Insert(value) } allErrs = append(allErrs, unversionedvalidation.ValidateLabelName(rq.Key, fldPath.Child(\"key\"))...) return allErrs return valueSet, allErrs } // ValidateTopologySelectorTerm tests that the specified topology selector term has valid data func ValidateTopologySelectorTerm(term core.TopologySelectorTerm, fldPath *field.Path) field.ErrorList { // ValidateTopologySelectorTerm tests that the specified topology selector term has valid data, // and constructs a map representing the term in raw form. func ValidateTopologySelectorTerm(term core.TopologySelectorTerm, fldPath *field.Path) (map[string]sets.String, field.ErrorList) { allErrs := field.ErrorList{} exprMap := make(map[string]sets.String) exprPath := fldPath.Child(\"matchLabelExpressions\") if utilfeature.DefaultFeatureGate.Enabled(features.DynamicProvisioningScheduling) { // Allow empty MatchLabelExpressions, in case this field becomes optional in the future. for i, req := range term.MatchLabelExpressions { allErrs = append(allErrs, validateTopologySelectorLabelRequirement(req, fldPath.Child(\"matchLabelExpressions\").Index(i))...) idxPath := exprPath.Index(i) valueSet, exprErrs := validateTopologySelectorLabelRequirement(req, idxPath) allErrs = append(allErrs, exprErrs...) // Validate no duplicate keys exist. if _, exists := exprMap[req.Key]; exists { allErrs = append(allErrs, field.Duplicate(idxPath.Child(\"key\"), req.Key)) } exprMap[req.Key] = valueSet } } else if len(term.MatchLabelExpressions) != 0 { allErrs = append(allErrs, field.Forbidden(fldPath, \"field is disabled by feature-gate DynamicProvisioningScheduling\")) } return allErrs return exprMap, allErrs } // ValidateAvoidPodsInNodeAnnotations tests that the serialized AvoidPods in Node.Annotations has valid data"} {"_id":"doc-en-kubernetes-7a430e8906399ac65428e2d5e07939ccac90bb74c971ec814297317c0a62aa5e","title":"","text":"importpath = \"k8s.io/kubernetes/pkg/apis/storage/validation\", deps = [ \"//pkg/apis/core:go_default_library\", \"//pkg/apis/core/helper:go_default_library\", \"//pkg/apis/core/validation:go_default_library\", \"//pkg/apis/storage:go_default_library\", \"//pkg/features:go_default_library\","} {"_id":"doc-en-kubernetes-08d35d0c5d051721967862e019617d1094e0709d0fa9d15fcb59ae44aa165a0b","title":"","text":"\"k8s.io/apimachinery/pkg/util/validation/field\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" api \"k8s.io/kubernetes/pkg/apis/core\" \"k8s.io/kubernetes/pkg/apis/core/helper\" apivalidation \"k8s.io/kubernetes/pkg/apis/core/validation\" \"k8s.io/kubernetes/pkg/apis/storage\" \"k8s.io/kubernetes/pkg/features\""} {"_id":"doc-en-kubernetes-be1dba9fdf3a0dd1301bce24a3f7081b5e92bc125de12128c4efbd8210eff6eb","title":"","text":"allErrs = append(allErrs, field.Forbidden(fldPath, \"field is disabled by feature-gate DynamicProvisioningScheduling\")) } rawTopologies := make([]map[string]sets.String, len(topologies)) for i, term := range topologies { allErrs = append(allErrs, apivalidation.ValidateTopologySelectorTerm(term, fldPath.Index(i))...) idxPath := fldPath.Index(i) exprMap, termErrs := apivalidation.ValidateTopologySelectorTerm(term, fldPath.Index(i)) allErrs = append(allErrs, termErrs...) // TODO (verult) consider improving runtime for _, t := range rawTopologies { if helper.Semantic.DeepEqual(exprMap, t) { allErrs = append(allErrs, field.Duplicate(idxPath.Child(\"matchLabelExpressions\"), \"\")) } } rawTopologies = append(rawTopologies, exprMap) } return allErrs"} {"_id":"doc-en-kubernetes-90649f64291939f905ebc077d4371ac7a6ab5da063b34acec338941f2ae8416d","title":"","text":"}, } topologyDupValues := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\", \"node1\"}, }, }, }, } topologyMultiValues := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\", \"node2\"}, }, }, }, } topologyEmptyMatchLabelExpressions := []api.TopologySelectorTerm{ { MatchLabelExpressions: nil, }, } topologyDupKeys := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node2\"}, }, }, }, } topologyMultiTerm := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node2\"}, }, }, }, } topologyDupTermsIdentical := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, }, }, } topologyExprsOneSameOneDiff := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node2\"}, }, }, }, } topologyValuesOneSameOneDiff := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\", \"node2\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\", \"node3\"}, }, }, }, } topologyDupTermsDiffExprOrder := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\"}, }, { Key: \"kubernetes.io/hostname\", Values: []string{\"node1\"}, }, }, }, } topologyDupTermsDiffValueOrder := []api.TopologySelectorTerm{ { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone1\", \"zone2\"}, }, }, }, { MatchLabelExpressions: []api.TopologySelectorLabelRequirement{ { Key: \"failure-domain.beta.kubernetes.io/zone\", Values: []string{\"zone2\", \"zone1\"}, }, }, }, } cases := map[string]bindingTest{ \"no topology\": { class: makeClass(nil, nil),"} {"_id":"doc-en-kubernetes-a32265ff0651f72b31742f527bc180031772c8997868a19a888770f0ede1ddf7","title":"","text":"class: makeClass(nil, topologyLackOfValues), shouldSucceed: false, }, \"duplicate TopologySelectorRequirement values\": { class: makeClass(nil, topologyDupValues), shouldSucceed: false, }, \"multiple TopologySelectorRequirement values\": { class: makeClass(nil, topologyMultiValues), shouldSucceed: true, }, \"empty MatchLabelExpressions\": { class: makeClass(nil, topologyEmptyMatchLabelExpressions), shouldSucceed: false, }, \"duplicate MatchLabelExpression keys\": { class: makeClass(nil, topologyDupKeys), shouldSucceed: false, }, \"duplicate MatchLabelExpression keys but across separate terms\": { class: makeClass(nil, topologyMultiTerm), shouldSucceed: true, }, \"duplicate AllowedTopologies terms - identical\": { class: makeClass(nil, topologyDupTermsIdentical), shouldSucceed: false, }, \"two AllowedTopologies terms, with a pair of the same MatchLabelExpressions and a pair of different ones\": { class: makeClass(nil, topologyExprsOneSameOneDiff), shouldSucceed: true, }, \"two AllowedTopologies terms, with a pair of the same Values and a pair of different ones\": { class: makeClass(nil, topologyValuesOneSameOneDiff), shouldSucceed: true, }, \"duplicate AllowedTopologies terms - different MatchLabelExpressions order\": { class: makeClass(nil, topologyDupTermsDiffExprOrder), shouldSucceed: false, }, \"duplicate AllowedTopologies terms - different TopologySelectorRequirement values order\": { class: makeClass(nil, topologyDupTermsDiffValueOrder), shouldSucceed: false, }, } // Disable VolumeScheduling so nil VolumeBindingMode doesn't fail to validate. err := utilfeature.DefaultFeatureGate.Set(\"VolumeScheduling=false\") if err != nil { t.Fatalf(\"Failed to disable feature gate for VolumeScheduling: %v\", err) } // TODO: remove when feature gate not required err := utilfeature.DefaultFeatureGate.Set(\"DynamicProvisioningScheduling=true\") err = utilfeature.DefaultFeatureGate.Set(\"DynamicProvisioningScheduling=true\") if err != nil { t.Fatalf(\"Failed to enable feature gate for DynamicProvisioningScheduling: %v\", err) }"} {"_id":"doc-en-kubernetes-9147dfb9b3d4b051a55cd5856a3ce263f0a972ce228d615618a6369ba6ad43a0","title":"","text":"readonly ENABLE_LEGACY_ABAC=false readonly ETC_MANIFESTS=${KUBE_HOME}/etc/kubernetes/manifests readonly KUBE_API_SERVER_DOCKER_TAG=v1.11.0-alpha.0.1808_3c7452dc11645d-dirty readonly LOG_OWNER_USER=$(whoami) readonly LOG_OWNER_USER=$(id -un) readonly LOG_OWNER_GROUP=$(id -gn) ENCRYPTION_PROVIDER_CONFIG={{.EncryptionProviderConfig}} ENCRYPTION_PROVIDER_CONFIG_PATH={{.EncryptionProviderConfigPath}}"} {"_id":"doc-en-kubernetes-eb493a954993025718c610a2dae2b4a99c43ad74a768be62492b9f9ce235d9a6","title":"","text":" apiVersion: v1 kind: Service metadata: name: a spec: selector: app: test clusterIP: None ports: - port: 80 "} {"_id":"doc-en-kubernetes-9421cea2382172e82799ae2bfa6c934ce7541f9eceff4b7162af51ac46f75403","title":"","text":" apiVersion: v1 kind: Service metadata: name: a spec: selector: app: test clusterIP: 10.0.0.12 ports: - port: 80 "} {"_id":"doc-en-kubernetes-551b8ea3cbcc4ed563850f476f7fe53df12fed7c9a5c8ab0c43cc8e1abccba95","title":"","text":"} patchBytes, patchObject, err = p.patchSimple(current, modified, source, namespace, name, errOut) } if err != nil && errors.IsConflict(err) && p.force { if err != nil && (errors.IsConflict(err) || errors.IsInvalid(err)) && p.force { patchBytes, patchObject, err = p.deleteAndCreate(current, modified, namespace, name) } return patchBytes, patchObject, err"} {"_id":"doc-en-kubernetes-2471e365c42ce3f711616c446bfd90eb23de5cbfeee017587c707ab696824cd7","title":"","text":"# cleanup kubectl delete svc prune-svc 2>&1 \"${kube_flags[@]}\" ## kubectl apply -f some.yml --force # Pre-condition: no service exists kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" '' # apply service a kubectl apply -f hack/testdata/service-revision1.yaml \"${kube_flags[@]}\" # check right service exists kube::test::get_object_assert 'services a' \"{{${id_field}}}\" 'a' # change immutable field and apply service a output_message=$(! kubectl apply -f hack/testdata/service-revision2.yaml 2>&1 \"${kube_flags[@]}\") kube::test::if_has_string \"${output_message}\" 'field is immutable' # apply --force to recreate resources for immutable fields kubectl apply -f hack/testdata/service-revision2.yaml --force \"${kube_flags[@]}\" # check immutable field exists kube::test::get_object_assert 'services a' \"{{.spec.clusterIP}}\" '10.0.0.12' # cleanup kubectl delete -f hack/testdata/service-revision2.yaml \"${kube_flags[@]}\" set +o nounset set +o errexit }"} {"_id":"doc-en-kubernetes-6b201f879ce2071681a01405d4321f20b4ccdea9b0e72fa02dfb668619cff44f","title":"","text":"}, { \"ImportPath\": \"github.com/json-iterator/go\", \"Comment\": \"1.1.3-22-gf2b4162afba355\", \"Rev\": \"f2b4162afba35581b6d4a50d3b8f34e33c144682\" \"Comment\": \"1.1.4\", \"Rev\": \"ab8a2e0c74be9d3be70b3184d9acc634935ded82\" }, { \"ImportPath\": \"github.com/jteeuwen/go-bindata\","} {"_id":"doc-en-kubernetes-3e7d33285515beb71f378ee4f904a5296c7bf1f8132cad4902eb91b856a3e553","title":"","text":"}, { \"ImportPath\": \"github.com/json-iterator/go\", \"Rev\": \"f2b4162afba35581b6d4a50d3b8f34e33c144682\" \"Rev\": \"ab8a2e0c74be9d3be70b3184d9acc634935ded82\" }, { \"ImportPath\": \"github.com/mailru/easyjson/buffer\","} {"_id":"doc-en-kubernetes-091c843d6d413128b565c23d62793a09670622f6c02b95b84b4bf06e34be2682","title":"","text":"}, { \"ImportPath\": \"github.com/json-iterator/go\", \"Rev\": \"f2b4162afba35581b6d4a50d3b8f34e33c144682\" \"Rev\": \"ab8a2e0c74be9d3be70b3184d9acc634935ded82\" }, { \"ImportPath\": \"github.com/modern-go/concurrent\","} {"_id":"doc-en-kubernetes-fb876af0ba403181d60a8eccd4e95c068bf882669c4635b1509668fdee6232c0","title":"","text":"[[projects]] name = \"github.com/json-iterator/go\" packages = [\".\"] revision = \"ca39e5af3ece67bbcda3d0f4f56a8e24d9f2dad4\" version = \"1.1.3\" [[projects]] name = \"github.com/modern-go/concurrent\" packages = [\".\"] revision = \"e0a39a4cb4216ea8db28e22a69f4ec25610d513a\""} {"_id":"doc-en-kubernetes-6aeb5a46e6fd0c4ce57e9cb19104e750622c6cec989528baa4dfa5e12e248cac","title":"","text":"[[projects]] name = \"github.com/modern-go/reflect2\" packages = [\".\"] revision = \"1df9eeb2bb81f327b96228865c5687bc2194af3f\" version = \"1.0.0\" revision = \"4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd\" version = \"1.0.1\" [solve-meta] analyzer-name = \"dep\" analyzer-version = 1 inputs-digest = \"56a0b9e9e61d2bc8af5e1b68537401b7f4d60805eda3d107058f3171aa5cf793\" inputs-digest = \"ea54a775e5a354cb015502d2e7aa4b74230fc77e894f34a838b268c25ec8eeb8\" solver-name = \"gps-cdcl\" solver-version = 1"} {"_id":"doc-en-kubernetes-2cbdc2cb78a46a7d12cb3538e974c6cb788416578d6cab74feb697579cfae0bc","title":"","text":"[[constraint]] name = \"github.com/modern-go/reflect2\" version = \"1.0.0\" version = \"1.0.1\" "} {"_id":"doc-en-kubernetes-9527f2060fc43af489a05eddef918a7f34bf04dc9e5cf7ca77927b681f211c39","title":"","text":"srcs = [ \"cert_key.go\", \"client_ca.go\", \"dynamicfile_content.go\", \"dynamic_cafile_content.go\", \"dynamic_serving_content.go\", \"named_certificates.go\", \"static_content.go\", \"tlsconfig.go\","} {"_id":"doc-en-kubernetes-1b143747e9f7d1ab6fb660d99fbf1192fcdde27cf26e792ec2d8932948e342aa","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package dynamiccertificates import ( \"bytes\" \"crypto/x509\" \"fmt\" \"io/ioutil\" \"sync/atomic\" \"time\" \"k8s.io/client-go/util/cert\" utilruntime \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/util/workqueue\" \"k8s.io/klog\" ) // FileRefreshDuration is exposed so that integration tests can crank up the reload speed. var FileRefreshDuration = 1 * time.Minute // Listener is an interface to use to notify interested parties of a change. type Listener interface { // Enqueue should be called when an input may have changed Enqueue() } // Notifier is a way to add listeners type Notifier interface { // AddListener is adds a listener to be notified of potential input changes AddListener(listener Listener) } // ControllerRunner is a generic interface for starting a controller type ControllerRunner interface { // RunOnce runs the sync loop a single time. This useful for synchronous priming RunOnce() error // Run should be called a go .Run Run(workers int, stopCh <-chan struct{}) } // DynamicFileCAContent provies a CAContentProvider that can dynamically react to new file content // It also fulfills the authenticator interface to provide verifyoptions type DynamicFileCAContent struct { name string // filename is the name the file to read. filename string // caBundle is a caBundleAndVerifier that contains the last read, non-zero length content of the file caBundle atomic.Value listeners []Listener // queue only ever has one item, but it has nice error handling backoff/retry semantics queue workqueue.RateLimitingInterface } var _ Notifier = &DynamicFileCAContent{} var _ CAContentProvider = &DynamicFileCAContent{} var _ ControllerRunner = &DynamicFileCAContent{} type caBundleAndVerifier struct { caBundle []byte verifyOptions x509.VerifyOptions } // NewDynamicCAContentFromFile returns a CAContentProvider based on a filename that automatically reloads content func NewDynamicCAContentFromFile(purpose, filename string) (*DynamicFileCAContent, error) { if len(filename) == 0 { return nil, fmt.Errorf(\"missing filename for ca bundle\") } name := fmt.Sprintf(\"%s::%s\", purpose, filename) ret := &DynamicFileCAContent{ name: name, filename: filename, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicCABundle-%s\", purpose)), } if err := ret.loadCABundle(); err != nil { return nil, err } return ret, nil } // AddListener adds a listener to be notified when the CA content changes. func (c *DynamicFileCAContent) AddListener(listener Listener) { c.listeners = append(c.listeners, listener) } // loadCABundle determines the next set of content for the file. func (c *DynamicFileCAContent) loadCABundle() error { caBundle, err := ioutil.ReadFile(c.filename) if err != nil { return err } if len(caBundle) == 0 { return fmt.Errorf(\"missing content for CA bundle %q\", c.Name()) } // check to see if we have a change. If the values are the same, do nothing. if !c.hasCAChanged(caBundle) { return nil } caBundleAndVerifier, err := newCABundleAndVerifier(c.Name(), caBundle) if err != nil { return err } c.caBundle.Store(caBundleAndVerifier) for _, listener := range c.listeners { listener.Enqueue() } return nil } // hasCAChanged returns true if the caBundle is different than the current. func (c *DynamicFileCAContent) hasCAChanged(caBundle []byte) bool { uncastExisting := c.caBundle.Load() if uncastExisting == nil { return true } // check to see if we have a change. If the values are the same, do nothing. existing, ok := uncastExisting.(*caBundleAndVerifier) if !ok { return true } if !bytes.Equal(existing.caBundle, caBundle) { return true } return false } // RunOnce runs a single sync loop func (c *DynamicFileCAContent) RunOnce() error { return c.loadCABundle() } // Run starts the kube-apiserver and blocks until stopCh is closed. func (c *DynamicFileCAContent) Run(workers int, stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer c.queue.ShutDown() klog.Infof(\"Starting %s\", c.name) defer klog.Infof(\"Shutting down %s\", c.name) // doesn't matter what workers say, only start one. go wait.Until(c.runWorker, time.Second, stopCh) // start timer that rechecks every minute, just in case. this also serves to prime the controller quickly. _ = wait.PollImmediateUntil(FileRefreshDuration, func() (bool, error) { c.queue.Add(workItemKey) return false, nil }, stopCh) // TODO this can be wired to an fsnotifier as well. <-stopCh } func (c *DynamicFileCAContent) runWorker() { for c.processNextWorkItem() { } } func (c *DynamicFileCAContent) processNextWorkItem() bool { dsKey, quit := c.queue.Get() if quit { return false } defer c.queue.Done(dsKey) err := c.loadCABundle() if err == nil { c.queue.Forget(dsKey) return true } utilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err)) c.queue.AddRateLimited(dsKey) return true } // Name is just an identifier func (c *DynamicFileCAContent) Name() string { return c.name } // CurrentCABundleContent provides ca bundle byte content func (c *DynamicFileCAContent) CurrentCABundleContent() (cabundle []byte) { return c.caBundle.Load().(*caBundleAndVerifier).caBundle } // VerifyOptions provides verifyoptions compatible with authenticators func (c *DynamicFileCAContent) VerifyOptions() x509.VerifyOptions { return c.caBundle.Load().(*caBundleAndVerifier).verifyOptions } // newVerifyOptions creates a new verification func from a file. It reads the content and then fails. // It will return a nil function if you pass an empty CA file. func newCABundleAndVerifier(name string, caBundle []byte) (*caBundleAndVerifier, error) { if len(caBundle) == 0 { return nil, fmt.Errorf(\"missing content for CA bundle %q\", name) } // Wrap with an x509 verifier var err error verifyOptions := defaultVerifyOptions() verifyOptions.Roots, err = cert.NewPoolFromBytes(caBundle) if err != nil { return nil, fmt.Errorf(\"error loading CA bundle for %q: %v\", name, err) } return &caBundleAndVerifier{ caBundle: caBundle, verifyOptions: verifyOptions, }, nil } // defaultVerifyOptions returns VerifyOptions that use the system root certificates, current time, // and requires certificates to be valid for client auth (x509.ExtKeyUsageClientAuth) func defaultVerifyOptions() x509.VerifyOptions { return x509.VerifyOptions{ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, } } "} {"_id":"doc-en-kubernetes-b75bc8f5163b14b155d1030c10462c5bf4c1554930cfe1dc1c68590147a51954","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package dynamiccertificates import ( \"crypto/tls\" \"fmt\" \"io/ioutil\" \"sync/atomic\" \"time\" utilruntime \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/util/workqueue\" \"k8s.io/klog\" ) // DynamicFileServingContent provides a CertKeyContentProvider that can dynamically react to new file content type DynamicFileServingContent struct { name string // certFile is the name of the certificate file to read. certFile string // keyFile is the name of the key file to read. keyFile string // servingCert is a certKeyContent that contains the last read, non-zero length content of the key and cert servingCert atomic.Value listeners []Listener // queue only ever has one item, but it has nice error handling backoff/retry semantics queue workqueue.RateLimitingInterface } var _ Notifier = &DynamicFileServingContent{} var _ CertKeyContentProvider = &DynamicFileServingContent{} var _ ControllerRunner = &DynamicFileServingContent{} // NewDynamicServingContentFromFiles returns a dynamic CertKeyContentProvider based on a cert and key filename func NewDynamicServingContentFromFiles(purpose, certFile, keyFile string) (*DynamicFileServingContent, error) { if len(certFile) == 0 || len(keyFile) == 0 { return nil, fmt.Errorf(\"missing filename for serving cert\") } name := fmt.Sprintf(\"%s::%s::%s\", purpose, certFile, keyFile) ret := &DynamicFileServingContent{ name: name, certFile: certFile, keyFile: keyFile, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicCABundle-%s\", purpose)), } if err := ret.loadServingCert(); err != nil { return nil, err } return ret, nil } // AddListener adds a listener to be notified when the serving cert content changes. func (c *DynamicFileServingContent) AddListener(listener Listener) { c.listeners = append(c.listeners, listener) } // loadServingCert determines the next set of content for the file. func (c *DynamicFileServingContent) loadServingCert() error { cert, err := ioutil.ReadFile(c.certFile) if err != nil { return err } key, err := ioutil.ReadFile(c.keyFile) if err != nil { return err } if len(cert) == 0 || len(key) == 0 { return fmt.Errorf(\"missing content for serving cert %q\", c.Name()) } // Ensure that the key matches the cert and both are valid _, err = tls.X509KeyPair(cert, key) if err != nil { return err } newCertKey := &certKeyContent{ cert: cert, key: key, } // check to see if we have a change. If the values are the same, do nothing. existing, ok := c.servingCert.Load().(*certKeyContent) if ok && existing != nil && existing.Equal(newCertKey) { return nil } c.servingCert.Store(newCertKey) for _, listener := range c.listeners { listener.Enqueue() } return nil } // RunOnce runs a single sync loop func (c *DynamicFileServingContent) RunOnce() error { return c.loadServingCert() } // Run starts the controller and blocks until stopCh is closed. func (c *DynamicFileServingContent) Run(workers int, stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer c.queue.ShutDown() klog.Infof(\"Starting %s\", c.name) defer klog.Infof(\"Shutting down %s\", c.name) // doesn't matter what workers say, only start one. go wait.Until(c.runWorker, time.Second, stopCh) // start timer that rechecks every minute, just in case. this also serves to prime the controller quickly. _ = wait.PollImmediateUntil(FileRefreshDuration, func() (bool, error) { c.queue.Add(workItemKey) return false, nil }, stopCh) // TODO this can be wired to an fsnotifier as well. <-stopCh } func (c *DynamicFileServingContent) runWorker() { for c.processNextWorkItem() { } } func (c *DynamicFileServingContent) processNextWorkItem() bool { dsKey, quit := c.queue.Get() if quit { return false } defer c.queue.Done(dsKey) err := c.loadServingCert() if err == nil { c.queue.Forget(dsKey) return true } utilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err)) c.queue.AddRateLimited(dsKey) return true } // Name is just an identifier func (c *DynamicFileServingContent) Name() string { return c.name } // CurrentCertKeyContent provides serving cert byte content func (c *DynamicFileServingContent) CurrentCertKeyContent() ([]byte, []byte) { certKeyContent := c.servingCert.Load().(*certKeyContent) return certKeyContent.cert, certKeyContent.key } "} {"_id":"doc-en-kubernetes-69550e4bb29bdb0b22df1ee254bc192cf50f575731ff2dffccab9efc9c4507a0","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package dynamiccertificates import ( \"bytes\" \"crypto/x509\" \"fmt\" \"io/ioutil\" \"sync/atomic\" \"time\" \"k8s.io/client-go/util/cert\" utilruntime \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/util/workqueue\" \"k8s.io/klog\" ) // FileRefreshDuration is exposed so that integration tests can crank up the reload speed. var FileRefreshDuration = 1 * time.Minute // Listener is an interface to use to notify interested parties of a change. type Listener interface { // Enqueue should be called when an input may have changed Enqueue() } // Notifier is a way to add listeners type Notifier interface { // AddListener is adds a listener to be notified of potential input changes AddListener(listener Listener) } // ControllerRunner is a generic interface for starting a controller type ControllerRunner interface { // RunOnce runs the sync loop a single time. This useful for synchronous priming RunOnce() error // Run should be called a go .Run Run(workers int, stopCh <-chan struct{}) } // DynamicFileCAContent provies a CAContentProvider that can dynamically react to new file content // It also fulfills the authenticator interface to provide verifyoptions type DynamicFileCAContent struct { name string // filename is the name the file to read. filename string // caBundle is a caBundleAndVerifier that contains the last read, non-zero length content of the file caBundle atomic.Value listeners []Listener // queue only ever has one item, but it has nice error handling backoff/retry semantics queue workqueue.RateLimitingInterface } var _ Notifier = &DynamicFileCAContent{} var _ CAContentProvider = &DynamicFileCAContent{} var _ ControllerRunner = &DynamicFileCAContent{} type caBundleAndVerifier struct { caBundle []byte verifyOptions x509.VerifyOptions } // NewDynamicCAContentFromFile returns a CAContentProvider based on a filename that automatically reloads content func NewDynamicCAContentFromFile(purpose, filename string) (*DynamicFileCAContent, error) { if len(filename) == 0 { return nil, fmt.Errorf(\"missing filename for ca bundle\") } name := fmt.Sprintf(\"%s::%s\", purpose, filename) ret := &DynamicFileCAContent{ name: name, filename: filename, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), fmt.Sprintf(\"DynamicCABundle-%s\", purpose)), } if err := ret.loadCABundle(); err != nil { return nil, err } return ret, nil } // AddListener adds a listener to be notified when the CA content changes. func (c *DynamicFileCAContent) AddListener(listener Listener) { c.listeners = append(c.listeners, listener) } // loadCABundle determines the next set of content for the file. func (c *DynamicFileCAContent) loadCABundle() error { caBundle, err := ioutil.ReadFile(c.filename) if err != nil { return err } if len(caBundle) == 0 { return fmt.Errorf(\"missing content for CA bundle %q\", c.Name()) } // check to see if we have a change. If the values are the same, do nothing. if !c.hasCAChanged(caBundle) { return nil } caBundleAndVerifier, err := newCABundleAndVerifier(c.Name(), caBundle) if err != nil { return err } c.caBundle.Store(caBundleAndVerifier) for _, listener := range c.listeners { listener.Enqueue() } return nil } // hasCAChanged returns true if the caBundle is different than the current. func (c *DynamicFileCAContent) hasCAChanged(caBundle []byte) bool { uncastExisting := c.caBundle.Load() if uncastExisting == nil { return true } // check to see if we have a change. If the values are the same, do nothing. existing, ok := uncastExisting.(*caBundleAndVerifier) if !ok { return true } if !bytes.Equal(existing.caBundle, caBundle) { return true } return false } // RunOnce runs a single sync loop func (c *DynamicFileCAContent) RunOnce() error { return c.loadCABundle() } // Run starts the kube-apiserver and blocks until stopCh is closed. func (c *DynamicFileCAContent) Run(workers int, stopCh <-chan struct{}) { defer utilruntime.HandleCrash() defer c.queue.ShutDown() klog.Infof(\"Starting %s\", c.name) defer klog.Infof(\"Shutting down %s\", c.name) // doesn't matter what workers say, only start one. go wait.Until(c.runWorker, time.Second, stopCh) // start timer that rechecks every minute, just in case. this also serves to prime the controller quickly. _ = wait.PollImmediateUntil(FileRefreshDuration, func() (bool, error) { c.queue.Add(workItemKey) return false, nil }, stopCh) // TODO this can be wired to an fsnotifier as well. <-stopCh } func (c *DynamicFileCAContent) runWorker() { for c.processNextWorkItem() { } } func (c *DynamicFileCAContent) processNextWorkItem() bool { dsKey, quit := c.queue.Get() if quit { return false } defer c.queue.Done(dsKey) err := c.loadCABundle() if err == nil { c.queue.Forget(dsKey) return true } utilruntime.HandleError(fmt.Errorf(\"%v failed with : %v\", dsKey, err)) c.queue.AddRateLimited(dsKey) return true } // Name is just an identifier func (c *DynamicFileCAContent) Name() string { return c.name } // CurrentCABundleContent provides ca bundle byte content func (c *DynamicFileCAContent) CurrentCABundleContent() (cabundle []byte) { return c.caBundle.Load().(*caBundleAndVerifier).caBundle } // VerifyOptions provides verifyoptions compatible with authenticators func (c *DynamicFileCAContent) VerifyOptions() x509.VerifyOptions { return c.caBundle.Load().(*caBundleAndVerifier).verifyOptions } // newVerifyOptions creates a new verification func from a file. It reads the content and then fails. // It will return a nil function if you pass an empty CA file. func newCABundleAndVerifier(name string, caBundle []byte) (*caBundleAndVerifier, error) { if len(caBundle) == 0 { return nil, fmt.Errorf(\"missing content for CA bundle %q\", name) } // Wrap with an x509 verifier var err error verifyOptions := defaultVerifyOptions() verifyOptions.Roots, err = cert.NewPoolFromBytes(caBundle) if err != nil { return nil, fmt.Errorf(\"error loading CA bundle for %q: %v\", name, err) } return &caBundleAndVerifier{ caBundle: caBundle, verifyOptions: verifyOptions, }, nil } // defaultVerifyOptions returns VerifyOptions that use the system root certificates, current time, // and requires certificates to be valid for client auth (x509.ExtKeyUsageClientAuth) func defaultVerifyOptions() x509.VerifyOptions { return x509.VerifyOptions{ KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, } } "} {"_id":"doc-en-kubernetes-1016f88b06d9c0b92f868e77a41ef68fe702e6fed2f1b4f9b82e0b785555c08f","title":"","text":"// load main cert if len(serverCertFile) != 0 || len(serverKeyFile) != 0 { var err error c.Cert, err = dynamiccertificates.NewStaticCertKeyContentFromFiles(serverCertFile, serverKeyFile) c.Cert, err = dynamiccertificates.NewDynamicServingContentFromFiles(\"serving-cert\", serverCertFile, serverKeyFile) if err != nil { return err }"} {"_id":"doc-en-kubernetes-f961c8fd0febf498675313d0b8bf29f08f100d854f8eae3497ad5f915b0641d1","title":"","text":"if notifier, ok := s.ClientCA.(dynamiccertificates.Notifier); ok { notifier.AddListener(dynamicCertificateController) } if notifier, ok := s.Cert.(dynamiccertificates.Notifier); ok { notifier.AddListener(dynamicCertificateController) } // start controllers if possible if controller, ok := s.ClientCA.(dynamiccertificates.ControllerRunner); ok { // runonce to be sure that we have a value."} {"_id":"doc-en-kubernetes-23762e0f1585fad72880893db168a52008c05705f832744f19bb0990fdc6332e","title":"","text":"go controller.Run(1, stopCh) } if controller, ok := s.Cert.(dynamiccertificates.ControllerRunner); ok { // runonce to be sure that we have a value. if err := controller.RunOnce(); err != nil { return nil, err } go controller.Run(1, stopCh) } // runonce to be sure that we have a value. if err := dynamicCertificateController.RunOnce(); err != nil {"} {"_id":"doc-en-kubernetes-6c72353cd5b99e28303b8864d419ad85f35fc7f3b18303f5adfb1c8772fbecd9","title":"","text":"package podlogs import ( \"bytes\" \"crypto/tls\" \"crypto/x509\" \"encoding/base64\" \"io/ioutil\" \"net/url\" \"path\" \"strings\" \"testing\" \"time\" \"k8s.io/apiserver/pkg/server/dynamiccertificates\" \"k8s.io/kubernetes/cmd/kube-apiserver/app/options\" \"k8s.io/kubernetes/test/integration/framework\" )"} {"_id":"doc-en-kubernetes-518e554a2a9924f96555b3657890ba61108d4564d6ce5a629973e94d3d8a9145","title":"","text":"} } } func TestServingCert(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) var serverKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA13f50PPWuR/InxLIoJjHdNSG+jVUd25CY7ZL2J023X2BAY+1 M6jkLR6C2nSFZnn58ubiB74/d1g/Fg1Twd419iR615A013f+qOoyFx3LFHxU1S6e v22fgJ6ntK/+4QD5MwNgOwD8k1jN2WxHqNWn16IF4Tidbv8M9A35YHAdtYDYaOJC kzjVztzRw1y6bKRakpMXxHylQyWmAKDJ2GSbRTbGtjr7Ji54WBfG43k94tO5X8K4 VGbz/uxrKe1IFMHNOlrjR438dbOXusksx9EIqDA9a42J3qjr5NKSqzCIbgBFl6qu 45V3A7cdRI/sJ2G1aqlWIXh2fAQiaFQAEBrPfwIDAQABAoIBAAZbxgWCjJ2d8H+x QDZtC8XI18redAWqPU9P++ECkrHqmDoBkalanJEwS1BDDATAKL4gTh9IX/sXoZT3 A7e+5PzEitN9r/GD2wIFF0FTYcDTAnXgEFM52vEivXQ5lV3yd2gn+1kCaHG4typp ZZv34iIc5+uDjjHOWQWCvA86f8XxX5EfYH+GkjfixTtN2xhWWlfi9vzYeESS4Jbt tqfH0iEaZ1Bm/qvb8vFgKiuSTOoSpaf+ojAdtPtXDjf1bBtQQG+RSQkP59O/taLM FCVuRrU8EtdB0+9anwmAP+O2UqjL5izA578lQtdIh13jHtGEgOcnfGNUphK11y9r Mg5V28ECgYEA9fwI6Xy1Rb9b9irp4bU5Ec99QXa4x2bxld5cDdNOZWJQu9OnaIbg kw/1SyUkZZCGMmibM/BiWGKWoDf8E+rn/ujGOtd70sR9U0A94XMPqEv7iHxhpZmD rZuSz4/snYbOWCZQYXFoD/nqOwE7Atnz7yh+Jti0qxBQ9bmkb9o0QW8CgYEA4D3d okzodg5QQ1y9L0J6jIC6YysoDedveYZMd4Un9bKlZEJev4OwiT4xXmSGBYq/7dzo OJOvN6qgPfibr27mSB8NkAk6jL/VdJf3thWxNYmjF4E3paLJ24X31aSipN1Ta6K3 KKQUQRvixVoI1q+8WHAubBDEqvFnNYRHD+AjKvECgYBkekjhpvEcxme4DBtw+OeQ 4OJXJTmhKemwwB12AERboWc88d3GEqIVMEWQJmHRotFOMfCDrMNfOxYv5+5t7FxL gaXHT1Hi7CQNJ4afWrKgmjjqrXPtguGIvq2fXzjVt8T9uNjIlNxe+kS1SXFjXsgH ftDY6VgTMB0B4ozKq6UAvQKBgQDER8K5buJHe+3rmMCMHn+Qfpkndr4ftYXQ9Kn4 MFiy6sV0hdfTgRzEdOjXu9vH/BRVy3iFFVhYvIR42iTEIal2VaAUhM94Je5cmSyd eE1eFHTqfRPNazmPaqttmSc4cfa0D4CNFVoZR6RupIl6Cect7jvkIaVUD+wMXxWo osOFsQKBgDLwVhZWoQ13RV/jfQxS3veBUnHJwQJ7gKlL1XZ16mpfEOOVnJF7Es8j TIIXXYhgSy/XshUbsgXQ+YGliye/rXSCTXHBXvWShOqxEMgeMYMRkcm8ZLp/DH7C kC2pemkLPUJqgSh1PASGcJbDJIvFGUfP69tUCYpHpk3nHzexuAg3 -----END RSA PRIVATE KEY-----`) var serverCert = []byte(`-----BEGIN CERTIFICATE----- MIIDQDCCAiigAwIBAgIJANWw74P5KJk2MA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV BAMMKWdlbmVyaWNfd2ViaG9va19hZG1pc3Npb25fcGx1Z2luX3Rlc3RzX2NhMCAX DTE3MTExNjAwMDUzOVoYDzIyOTEwOTAxMDAwNTM5WjAjMSEwHwYDVQQDExh3ZWJo b29rLXRlc3QuZGVmYXVsdC5zdmMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQDXd/nQ89a5H8ifEsigmMd01Ib6NVR3bkJjtkvYnTbdfYEBj7UzqOQtHoLa dIVmefny5uIHvj93WD8WDVPB3jX2JHrXkDTXd/6o6jIXHcsUfFTVLp6/bZ+Anqe0 r/7hAPkzA2A7APyTWM3ZbEeo1afXogXhOJ1u/wz0DflgcB21gNho4kKTONXO3NHD XLpspFqSkxfEfKVDJaYAoMnYZJtFNsa2OvsmLnhYF8bjeT3i07lfwrhUZvP+7Gsp 7UgUwc06WuNHjfx1s5e6ySzH0QioMD1rjYneqOvk0pKrMIhuAEWXqq7jlXcDtx1E j+wnYbVqqVYheHZ8BCJoVAAQGs9/AgMBAAGjZDBiMAkGA1UdEwQCMAAwCwYDVR0P BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATApBgNVHREEIjAg hwR/AAABghh3ZWJob29rLXRlc3QuZGVmYXVsdC5zdmMwDQYJKoZIhvcNAQELBQAD ggEBAD/GKSPNyQuAOw/jsYZesb+RMedbkzs18sSwlxAJQMUrrXwlVdHrA8q5WhE6 ABLqU1b8lQ8AWun07R8k5tqTmNvCARrAPRUqls/ryER+3Y9YEcxEaTc3jKNZFLbc T6YtcnkdhxsiO136wtiuatpYL91RgCmuSpR8+7jEHhuFU01iaASu7ypFrUzrKHTF bKwiLRQi1cMzVcLErq5CDEKiKhUkoDucyARFszrGt9vNIl/YCcBOkcNvM3c05Hn3 M++C29JwS3Hwbubg6WO3wjFjoEhpCwU6qRYUz3MRp4tHO4kxKXx+oQnUiFnR7vW0 YkNtGc1RUDHwecCTFpJtPb7Yu/E= -----END CERTIFICATE-----`) var servingCertPath string _, kubeconfig := framework.StartTestServer(t, stopCh, framework.TestServerSetup{ ModifyServerRunOptions: func(opts *options.ServerRunOptions) { opts.GenericServerRunOptions.MaxRequestBodyBytes = 1024 * 1024 servingCertPath = opts.SecureServing.ServerCert.CertDirectory dynamiccertificates.FileRefreshDuration = 1 * time.Second }, }) apiserverURL, err := url.Parse(kubeconfig.Host) if err != nil { t.Fatal(err) } // when we run this the second time, we know which one we are expecting acceptableCerts := [][]byte{} tlsConfig := &tls.Config{ InsecureSkipVerify: true, VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { acceptableCerts = make([][]byte, 0, len(rawCerts)) for _, r := range rawCerts { acceptableCerts = append(acceptableCerts, r) } return nil }, } conn, err := tls.Dial(\"tcp\", apiserverURL.Host, tlsConfig) if err != nil { t.Fatal(err) } defer conn.Close() if err := ioutil.WriteFile(path.Join(servingCertPath, \"apiserver.key\"), serverKey, 0644); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(servingCertPath, \"apiserver.crt\"), serverCert, 0644); err != nil { t.Fatal(err) } time.Sleep(4 * time.Second) conn2, err := tls.Dial(\"tcp\", apiserverURL.Host, tlsConfig) if err != nil { t.Fatal(err) } defer conn2.Close() cert, err := tls.X509KeyPair(serverCert, serverKey) if err != nil { t.Fatal(err) } expectedCerts := cert.Certificate if len(expectedCerts) != len(acceptableCerts) { var certs []string for _, a := range acceptableCerts { certs = append(certs, base64.StdEncoding.EncodeToString(a)) } t.Fatalf(\"Unexpected number of certs: %v\", strings.Join(certs, \":\")) } for i := range expectedCerts { if !bytes.Equal(acceptableCerts[i], expectedCerts[i]) { t.Errorf(\"expected %q, got %q\", base64.StdEncoding.EncodeToString(expectedCerts[i]), base64.StdEncoding.EncodeToString(acceptableCerts[i])) } } } "} {"_id":"doc-en-kubernetes-ffeb536eb05a9a15fbbaec246c398eaf499ff9d53e672f204124e79f69af8551","title":"","text":"\"client_ca.go\", \"dynamic_cafile_content.go\", \"dynamic_serving_content.go\", \"dynamic_sni_content.go\", \"named_certificates.go\", \"static_content.go\", \"tlsconfig.go\","} {"_id":"doc-en-kubernetes-4ba4bf10be0b6b740d6961840b8089e2de68179a7ea3ffad9ec932ff9210ae87","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package dynamiccertificates // DynamicFileSNIContent provides a SNICertKeyContentProvider that can dynamically react to new file content type DynamicFileSNIContent struct { *DynamicFileServingContent sniNames []string } var _ Notifier = &DynamicFileSNIContent{} var _ SNICertKeyContentProvider = &DynamicFileSNIContent{} var _ ControllerRunner = &DynamicFileSNIContent{} // NewDynamicSNIContentFromFiles returns a dynamic SNICertKeyContentProvider based on a cert and key filename and explicit names func NewDynamicSNIContentFromFiles(purpose, certFile, keyFile string, sniNames ...string) (*DynamicFileSNIContent, error) { servingContent, err := NewDynamicServingContentFromFiles(purpose, certFile, keyFile) if err != nil { return nil, err } ret := &DynamicFileSNIContent{ DynamicFileServingContent: servingContent, sniNames: sniNames, } if err := ret.loadServingCert(); err != nil { return nil, err } return ret, nil } // SNINames returns explicitly set SNI names for the certificate. These are not dynamic. func (c *DynamicFileSNIContent) SNINames() []string { return c.sniNames } "} {"_id":"doc-en-kubernetes-b8de12c33d18ac7f4432428be04afcf110dc4e15934ecacfcddf2c9bfce3de94","title":"","text":"// load SNI certs namedTLSCerts := make([]dynamiccertificates.SNICertKeyContentProvider, 0, len(s.SNICertKeys)) for _, nck := range s.SNICertKeys { tlsCert, err := dynamiccertificates.NewStaticSNICertKeyContentFromFiles(nck.CertFile, nck.KeyFile, nck.Names...) tlsCert, err := dynamiccertificates.NewDynamicSNIContentFromFiles(\"sni-serving-cert\", nck.CertFile, nck.KeyFile, nck.Names...) namedTLSCerts = append(namedTLSCerts, tlsCert) if err != nil { return fmt.Errorf(\"failed to load SNI cert and key: %v\", err)"} {"_id":"doc-en-kubernetes-ea16dbaa252f08e3bd4fa1009bef37d21215fe97cfb6498b59dcd80df8981d84","title":"","text":"go controller.Run(1, stopCh) } for _, sniCert := range s.SNICerts { if notifier, ok := sniCert.(dynamiccertificates.Notifier); ok { notifier.AddListener(dynamicCertificateController) } if controller, ok := sniCert.(dynamiccertificates.ControllerRunner); ok { // runonce to be sure that we have a value. if err := controller.RunOnce(); err != nil { return nil, err } go controller.Run(1, stopCh) } } // runonce to be sure that we have a value. if err := dynamicCertificateController.RunOnce(); err != nil {"} {"_id":"doc-en-kubernetes-fcd3b6eaecf47ce0ac840bd425fe871f13250931034e92d4fa3dd0a2c831cf4c","title":"","text":"deps = [ \"//cmd/kube-apiserver/app/options:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/server/dynamiccertificates:go_default_library\", \"//staging/src/k8s.io/component-base/cli/flag:go_default_library\", \"//test/integration/framework:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-9fe0d5103de9a6964bca77bec7b57ca53acdc6aa99d064e7252c75fd64dd60e6","title":"","text":"\"time\" \"k8s.io/apiserver/pkg/server/dynamiccertificates\" \"k8s.io/component-base/cli/flag\" \"k8s.io/kubernetes/cmd/kube-apiserver/app/options\" \"k8s.io/kubernetes/test/integration/framework\" )"} {"_id":"doc-en-kubernetes-ae78e9b7135c3b9bfe41e090712a1b789326f5e9b1ff2ab044a9cbccda7f3eb8","title":"","text":"} } func TestServingCert(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) var serverKey = []byte(`-----BEGIN RSA PRIVATE KEY----- var serverKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEA13f50PPWuR/InxLIoJjHdNSG+jVUd25CY7ZL2J023X2BAY+1 M6jkLR6C2nSFZnn58ubiB74/d1g/Fg1Twd419iR615A013f+qOoyFx3LFHxU1S6e v22fgJ6ntK/+4QD5MwNgOwD8k1jN2WxHqNWn16IF4Tidbv8M9A35YHAdtYDYaOJC"} {"_id":"doc-en-kubernetes-1141c71ceae3fc379f0191055220db4d29de871d470f8f5adfe6236abfdbba6f","title":"","text":"kC2pemkLPUJqgSh1PASGcJbDJIvFGUfP69tUCYpHpk3nHzexuAg3 -----END RSA PRIVATE KEY-----`) var serverCert = []byte(`-----BEGIN CERTIFICATE----- var serverCert = []byte(`-----BEGIN CERTIFICATE----- MIIDQDCCAiigAwIBAgIJANWw74P5KJk2MA0GCSqGSIb3DQEBCwUAMDQxMjAwBgNV BAMMKWdlbmVyaWNfd2ViaG9va19hZG1pc3Npb25fcGx1Z2luX3Rlc3RzX2NhMCAX DTE3MTExNjAwMDUzOVoYDzIyOTEwOTAxMDAwNTM5WjAjMSEwHwYDVQQDExh3ZWJo"} {"_id":"doc-en-kubernetes-7889896b54ef623d8c71438bca94eedc74f2eff8bfd6f1d75e7c2fc3a227663a","title":"","text":"YkNtGc1RUDHwecCTFpJtPb7Yu/E= -----END CERTIFICATE-----`) var anotherServerKey = []byte(`-----BEGIN RSA PRIVATE KEY----- MIIJKAIBAAKCAgEAlZJORzCjbzF1SaCXFHyitudlE+q3Z5bGhS2TpXG6d6Laoqtw No4UC3i+TnMndtrP2pNkV/ZYivsp1fHz92FqFAT+XpYcG8pLm4iL0k0UufOWdLPT X87HCJjKZ4r7fmzstyjqK4sv9I3ye1jKi0VE1BLrF1KVvEE/1PXCug68EBP/aF06 +uvcr6o8hbMYzgdKSzhRYm9C3kGcawNofqAD/Kk/zn+pMk4Bloy4UgtXFXgj2bEn mVE+tRWyLv2+TONlmLnXaBW3/MvZtKC3mIs2KG+6aBNuY8PdWzWvMtp30r/ibgnH zuMKtvXJ5XRhTaST4QYXNbGwb1bIV1ylnX8zdXPEQkuYTQDctaYQCe0RXt1I9Fp3 gVQRxyTM+0IetbsU0k9VvBwQ07mgU8Rik3DxVnfbuJY/wREnERTkgv6ojtRwiszr GIY5x36peRs30CqRMv3uJtqC/FU6nCQbHxwssQyB/umN6L7bcpsQFDydeK95hvRQ y6tb2v/vMcw7MMo5kSFUHjoL5Zc4DObwiqs+p7F7S0WIJMBzJOcjmgCMzgZ7Jmc7 bMmrm43GLzOaVLIjuPVVpOp7YgJ/lqRf7K3hZXrMdaXkCm01aL8L59d+3Vfdjp3H HvmYpCh8bc+Kjs/nR9Rc+2JKK/H13LH3W5Cr8Fnc/FP6TgbvvNwsQV01gG8CAwEA AQKCAgBLBQn8DPo8YDsqxcBhRy45vQ/mkHiTHX3O+JAwkD1tmiI9Ku3qfxKwukwB fyKRK6jLQdg3gljgxJ80Ltol/xc8mVCYUoQgsDOB/FfdEEpQBkw1lqhzSnxr5G7I xl3kCHAmYgAp/PL9n2C620sj1YdzM1X06bgupy+D+gxEU/WhvtYBG5nklv6moSUg DjdnxyJNXh7710Bbx97Tke8Ma+f0B1P4l/FeSN/lCgm9JPD11L9uhbuN28EvBIXN qfmUCQ5BLx1KmHIi+n/kaCQN/+0XFQsS/oQEyA2znNaWFBu7egDxHji4nQoXwGoW i2vujJibafmkNc5/2bA8mTx8JXvCLhU2L9j2ZumpKOda0g+pfMauesL+9rvZdqwW gjdjndOHZlg3qm40hGCDBVmmV3mdnvXrk1BbuB4Y0N7qGo3PyYtJHGwJILaNQVGR Sj75uTatxJwFXsqSaJaErV3Q90IiyXX4AOFGnWHOs29GEwtnDbCvT/rzqutTYSXD Yv0XFDznzJelhZTH7FbaW3FW3YGEG1ER/0MtKpsAH4i7H9q3KKK8yrzUsgUkGwXt xtoLckh91xilPIGbzARdELTEdHrjlFL+qaz3PIqEQScWz3WBu2JcIzGbp6PQfMZ+ FZXarEb/ADZuX0+WoKFYR5jzwMoQfF/fxe2Ib/37ETNw4BgfSQKCAQEAxOw64XgO nUVJslzGK/H5fqTVpD1rfRmvVAiSDLAuWpClbpDZXqEPuoPPYsiccuUWu9VkJE1F 6MZEexGx1jFkN08QUHD1Bobzu6ThaBc2PrWHRjFGKM60d0AkhOiL4N04FGwVeCN6 xzIJFk1E4VOOo1+lzeAWRvi1lwuWTgQi+m25nwBJtmYdBLGeS+DXy80Fi6deECei ipDzJ4rxJsZ61uqBeYC4CfuHW9m5rCzJWPMMMFrPdl3OxEyZzKng4Co5EYc5i/QH piXD6IJayKcTPRK3tBJZp2YCIIdtQLcjAwmDEDowQtelHkbTihXMGRarf3VcOEoN ozMRgcLEEynuKwKCAQEAwnF5ZkkJEL/1MCOZ6PZfSKl35ZMIz/4Umk8hOMAQGhCT cnxlDUfGSBu4OihdBbIuBSBsYDjgcev8uyiIPDVy0FIkBKRGfgrNCLDh19aHljvE bUc3akvbft0mro86AvSd/Rpc7sj841bru37RDUm6AJOtIvb6DWUpMOZgMm0WMmSI kNs/UT+7rqg+AZPP8lumnJIFnRK38xOehQAaS1FHWGP//38py8yo8eXpMsoCWMch c+kZD2jsAYV+SWjjkZjcrv/52+asd4AotRXIShV8E8xItQeq6vLHKOaIe0tC2Y44 ONAKiu4dgABt1voy8I5J63MwgeNmgAUS+KsgUclYzQKCAQEAlt/3bPAzIkQH5uQ1 4U2PvnxEQ4XbaQnYzyWR4K7LlQ/l8ASCxoHYLyr2JdVWKKFk/ZzNERMzUNk3dqNk AZvuEII/GaKx2MJk04vMN5gxM3KZpinyeymEEynN0RbqtOpJITx+ZoGofB3V4IRr FciTLJEH0+iwqMe9OXDjQ/rfYcfXw/7QezNZYFNF2RT3wWnfqdQduXrkig3sfotx oCfJzgf2E0WPu/Y/CxyRqVzXF5N/7zxkX2gYF0YpQCmX5afz+X4FlTju81lT9DyL mdiIYO6KWSkGD7+UOaAJEOA/rwAGrtQmTdAy7jONt+pjaYV4+DrO4UG7mSJzc1vq JlSl6QKCAQARqwPv8mT7e6XI2QNMMs7XqGZ3mtOrKpguqVAIexM7exQazAjWmxX+ SV6FElPZh6Y82wRd/e0PDPVrADTY27ZyDXSuY0rwewTEbGYpGZo6YXXoxBbZ9sic D3ZLWEJaMGYGsJWPMP4hni1PXSebwH5BPSn3Sl/QRcfnZJeLHXRt4cqy9uka9eKU 7T6tIAQ+LmvGQFJ4QlIqqTa3ORoqi9kiw/tn+OMQXKlhSZXWApsR/A4jHSQkzVDc loeyHfDHsw8ia6oFfEFhnmiUg8UuTiN3HRHiOS8jqCnGoqP2KBGL+StMpkK++wH9 NozEgvmL+DHpTg8zTjlrGortw4btR5FlAoIBABVni+EsGA5K/PM1gIct2pDm+6Kq UCYScTwIjftuwKLk/KqermG9QJLiJouKO3ZSz7iCelu87Dx1cKeXrc2LQ1pnQzCB JnI6BCT+zRnQFXjLokJXD2hIS2hXhqV6/9FRXLKKMYePcDxWt/etLNGmpLnhDfb3 sMOH/9pnaGmtk36Ce03Hh7E1C6io/MKfTq+KKUV1UGwO1BdNQCiclkYzAUqn1O+Y c8BaeGKc2c6as8DKrPTGGQGmzo/ZUxQVfVFl2g7+HXISWBBcui/G5gtnU1afZqbW mTmDoqs4510vhlkhN9XZ0DyhewDIqNNGEY2vS1x2fJz1XC2Eve4KpSyUsiE= -----END RSA PRIVATE KEY----- `) var anotherServerCert = []byte(`-----BEGIN CERTIFICATE----- MIIFJjCCAw6gAwIBAgIJAOcEAbv8NslfMA0GCSqGSIb3DQEBCwUAMEAxCzAJBgNV BAYTAlVTMQswCQYDVQQIDAJDQTETMBEGA1UECgwKQWNtZSwgSW5jLjEPMA0GA1UE AwwGc29tZUNBMCAXDTE4MDYwODEzMzkyNFoYDzIyMTgwNDIxMTMzOTI0WjBDMQsw CQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExEzARBgNVBAoMCkFjbWUsIEluYy4xEjAQ BgNVBAMMCWxvY2FsaG9zdDCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB AJWSTkcwo28xdUmglxR8orbnZRPqt2eWxoUtk6Vxunei2qKrcDaOFAt4vk5zJ3ba z9qTZFf2WIr7KdXx8/dhahQE/l6WHBvKS5uIi9JNFLnzlnSz01/OxwiYymeK+35s 7Lco6iuLL/SN8ntYyotFRNQS6xdSlbxBP9T1wroOvBAT/2hdOvrr3K+qPIWzGM4H Sks4UWJvQt5BnGsDaH6gA/ypP85/qTJOAZaMuFILVxV4I9mxJ5lRPrUVsi79vkzj ZZi512gVt/zL2bSgt5iLNihvumgTbmPD3Vs1rzLad9K/4m4Jx87jCrb1yeV0YU2k k+EGFzWxsG9WyFdcpZ1/M3VzxEJLmE0A3LWmEAntEV7dSPRad4FUEcckzPtCHrW7 FNJPVbwcENO5oFPEYpNw8VZ327iWP8ERJxEU5IL+qI7UcIrM6xiGOcd+qXkbN9Aq kTL97ibagvxVOpwkGx8cLLEMgf7pjei+23KbEBQ8nXiveYb0UMurW9r/7zHMOzDK OZEhVB46C+WXOAzm8IqrPqexe0tFiCTAcyTnI5oAjM4GeyZnO2zJq5uNxi8zmlSy I7j1VaTqe2ICf5akX+yt4WV6zHWl5AptNWi/C+fXft1X3Y6dxx75mKQofG3Pio7P 50fUXPtiSivx9dyx91uQq/BZ3PxT+k4G77zcLEFdNYBvAgMBAAGjHjAcMBoGA1Ud EQQTMBGCCWxvY2FsaG9zdIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAgEABL8kffi7 48qSD+/l/UwCYdmqta1vAbOkvLnPtfXe1XlDpJipNuPxUBc8nNTemtrbg0erNJnC jQHodqmdKBJJOdaEKTwAGp5pYvvjlU3WasmhfJy+QwOWgeqjJcTUo3+DEaHRls16 AZXlsp3hB6z0gzR/qzUuZwpMbL477JpuZtAcwLYeVvLG8bQRyWyEy8JgGDoYSn8s Z16s+r6AX+cnL/2GHkZ+oc3iuXJbnac4xfWTKDiYnyzK6RWRnoyro7X0jiPz6XX3 wyoWzB1uMSCXscrW6ZcKyKqz75lySLuwGxOMhX4nGOoYHY0ZtrYn5WK2ZAJxsQnn 8QcjPB0nq37U7ifk1uebmuXe99iqyKnWaLvlcpe+HnO5pVxFkSQEf7Zh+hEnRDkN IBzLFnqwDS1ug/oQ1aSvc8oBh2ylKDJuGtPNqGKibNJyb2diXO/aEUOKRUKPAxKa dbKsc4Y1bhZNN3/MICMoyghwAOiuwUQMR5uhxTkQmZUwNrPFa+eW6GvyoYLFUsZs hZfWLNGD5mLADElxs0HF7F9Zk6pSocTDXba4d4lfxsq88SyZZ7PbjJYFRfLQPzd1 CfvpRPqolEmZo1Y5Q644PELYiJRKpBxmX5GtC5j5eaUD9XdGKvXsGhb0m0gW75rq iUnnLkZt2ya1cDJDiCnJjo7r5KxMo0XXFDc= -----END CERTIFICATE----- `) func TestServingCert(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) var servingCertPath string _, kubeconfig := framework.StartTestServer(t, stopCh, framework.TestServerSetup{"} {"_id":"doc-en-kubernetes-d29058870b62c918bcb432766fab2ef4423b0c448fa3273bb854ddc2f7cfedb5","title":"","text":"} } } func TestSNICert(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) var servingCertPath string _, kubeconfig := framework.StartTestServer(t, stopCh, framework.TestServerSetup{ ModifyServerRunOptions: func(opts *options.ServerRunOptions) { opts.GenericServerRunOptions.MaxRequestBodyBytes = 1024 * 1024 servingCertPath = opts.SecureServing.ServerCert.CertDirectory if err := ioutil.WriteFile(path.Join(servingCertPath, \"foo.key\"), anotherServerKey, 0644); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(servingCertPath, \"foo.crt\"), anotherServerCert, 0644); err != nil { t.Fatal(err) } dynamiccertificates.FileRefreshDuration = 1 * time.Second opts.SecureServing.SNICertKeys = []flag.NamedCertKey{{ Names: []string{\"foo\"}, CertFile: path.Join(servingCertPath, \"foo.crt\"), KeyFile: path.Join(servingCertPath, \"foo.key\"), }} }, }) apiserverURL, err := url.Parse(kubeconfig.Host) if err != nil { t.Fatal(err) } // When we run this the second time, we know which one we are expecting. acceptableCerts := [][]byte{} tlsConfig := &tls.Config{ InsecureSkipVerify: true, VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { acceptableCerts = make([][]byte, 0, len(rawCerts)) for _, r := range rawCerts { acceptableCerts = append(acceptableCerts, r) } return nil }, ServerName: \"foo\", } conn, err := tls.Dial(\"tcp\", apiserverURL.Host, tlsConfig) if err != nil { t.Fatal(err) } conn.Close() cert, err := tls.LoadX509KeyPair(path.Join(servingCertPath, \"foo.crt\"), path.Join(servingCertPath, \"foo.key\")) if err != nil { t.Fatal(err) } expectedCerts := cert.Certificate if len(expectedCerts) != len(acceptableCerts) { var certs []string for _, a := range acceptableCerts { certs = append(certs, base64.StdEncoding.EncodeToString(a)) } t.Fatalf(\"Unexpected number of certs: %v\", strings.Join(certs, \":\")) } for i := range expectedCerts { if !bytes.Equal(acceptableCerts[i], expectedCerts[i]) { t.Errorf(\"expected %q, got %q\", base64.StdEncoding.EncodeToString(expectedCerts[i]), base64.StdEncoding.EncodeToString(acceptableCerts[i])) } } if err := ioutil.WriteFile(path.Join(servingCertPath, \"foo.key\"), serverKey, 0644); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(servingCertPath, \"foo.crt\"), serverCert, 0644); err != nil { t.Fatal(err) } time.Sleep(4 * time.Second) conn2, err := tls.Dial(\"tcp\", apiserverURL.Host, tlsConfig) if err != nil { t.Fatal(err) } conn2.Close() cert, err = tls.X509KeyPair(serverCert, serverKey) if err != nil { t.Fatal(err) } expectedCerts = cert.Certificate if len(expectedCerts) != len(acceptableCerts) { var certs []string for _, a := range acceptableCerts { certs = append(certs, base64.StdEncoding.EncodeToString(a)) } t.Fatalf(\"Unexpected number of certs: %v\", strings.Join(certs, \":\")) } for i := range expectedCerts { if !bytes.Equal(acceptableCerts[i], expectedCerts[i]) { t.Errorf(\"expected %q, got %q\", base64.StdEncoding.EncodeToString(expectedCerts[i]), base64.StdEncoding.EncodeToString(acceptableCerts[i])) } } } "} {"_id":"doc-en-kubernetes-b25bafdca227610b08bc409eee3e9852b31a00f06bb914bb439cf4edb4fc0007","title":"","text":"} httpClient := &http.Client{} parsedNodeIP := net.ParseIP(nodeIP) protocol := utilipt.ProtocolIpv4 if parsedNodeIP != nil && parsedNodeIP.To4() == nil { glog.V(0).Infof(\"IPv6 node IP (%s), assume IPv6 operation\", nodeIP) protocol = utilipt.ProtocolIpv6 } klet := &Kubelet{ hostname: hostname,"} {"_id":"doc-en-kubernetes-90a82b407dfe62448899ab38dfa3c105cc508adf6cff21d3e705ac04bf045bb0","title":"","text":"nodeIPValidator: validateNodeIP, clock: clock.RealClock{}, enableControllerAttachDetach: kubeCfg.EnableControllerAttachDetach, iptClient: utilipt.New(utilexec.New(), utildbus.New(), utilipt.ProtocolIpv4), iptClient: utilipt.New(utilexec.New(), utildbus.New(), protocol), makeIPTablesUtilChains: kubeCfg.MakeIPTablesUtilChains, iptablesMasqueradeBit: int(kubeCfg.IPTablesMasqueradeBit), iptablesDropBit: int(kubeCfg.IPTablesDropBit),"} {"_id":"doc-en-kubernetes-2ea8fe38b0e7e105005f050f846f923341810ecef624bd6ad5ca41e08554e449","title":"","text":"# CNI_BIN_DIR is the path to network plugin config files. CNI_BIN_DIR=${CNI_BIN_DIR:-\"\"} # KUBELET_KUBECONFIG_DIR is the path to a dir for the kubelet's kubeconfig file # KUBELET_KUBECONFIG is the path to a kubeconfig file, specifying how to connect to the API server. KUBELET_KUBECONFIG=${KUBELET_KUBECONFIG:-\"/var/lib/kubelet/kubeconfig\"} # Creates a kubeconfig file for the kubelet."} {"_id":"doc-en-kubernetes-af87acaf994e4fe4bacab6264dc5cdd0dfe379fca9c32ce9d2b3571b3660e20f","title":"","text":"file_check_frequency=10s pod_cidr=10.100.0.0/24 log_level=4 start_kubelet --kubeconfig \"${KUBELET_KUBECONFIG_DIR}/kubelet.kubeconfig\" start_kubelet --kubeconfig ${KUBELET_KUBECONFIG} --volume-stats-agg-period $volume_stats_agg_period --allow-privileged=$allow_privileged --serialize-image-pulls=$serialize_image_pulls "} {"_id":"doc-en-kubernetes-7d1a47e7ef0d0a1e97f26a7ef68552fea171769495bc5c0cfa96ebba7feb8c3f","title":"","text":"# Arguments: a list of kubernetes packages to build. # Expected variables: ${build_args} should be set to an array of Go build arguments. # In addition, ${package} and ${platform} should have been set earlier, and if # ${build_with_coverage} is set, coverage instrumentation will be enabled. # ${KUBE_BUILD_WITH_COVERAGE} is set, coverage instrumentation will be enabled. # # Invokes Go to actually build some packages. If coverage is disabled, simply invokes # go install. If coverage is enabled, builds covered binaries using go test, temporarily # producing the required unit test files and then cleaning up after itself. # Non-covered binaries are then built using go install as usual. kube::golang::build_some_binaries() { if [[ -n \"${build_with_coverage:-}\" ]]; then if [[ -n \"${KUBE_BUILD_WITH_COVERAGE:-}\" ]]; then local -a uncovered=() for package in \"$@\"; do if kube::golang::is_instrumented_package \"${package}\"; then"} {"_id":"doc-en-kubernetes-5c3c1e736a833e197d9b4d734a8c5e496908800e11d7c5232f4718222db1c514","title":"","text":"host_platform=$(kube::golang::host_platform) # Use eval to preserve embedded quoted strings. local goflags goldflags gogcflags build_with_coverage local goflags goldflags gogcflags eval \"goflags=(${GOFLAGS:-})\" goldflags=\"${GOLDFLAGS:-} $(kube::version::ldflags)\" gogcflags=\"${GOGCFLAGS:-}\" build_with_coverage=\"${KUBE_BUILD_WITH_COVERAGE:-}\" local -a targets=() local arg"} {"_id":"doc-en-kubernetes-25e40cd13dfbbad44286cf46a57ec320d1f929ab68f26bf8587fc0d1b5419ff3","title":"","text":"PrintFlags: genericclioptions.NewPrintFlags(\"condition met\"), ResourceBuilderFlags: genericclioptions.NewResourceBuilderFlags(). WithLabelSelector(\"\"). WithFieldSelector(\"\"). WithAll(false). WithAllNamespaces(false). WithAll(false). WithLatest(),"} {"_id":"doc-en-kubernetes-39ee0b610a3e7c13c25d99aa41967606b407c5644fc58c33e3f59fb891a0d599","title":"","text":"flags := NewWaitFlags(restClientGetter, streams) cmd := &cobra.Command{ Use: \"wait resource.group/name [--for=delete|--for condition=available]\", Use: \"wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available]\", Short: \"Experimental: Wait for a specific condition on one or many resources.\", Long: waitLong, Example: waitExample, DisableFlagsInUseLine: true, Short: \"Experimental: Wait for a specific condition on one or many resources.\", Long: waitLong, Example: waitExample, Run: func(cmd *cobra.Command, args []string) { o, err := flags.ToOptions(args) cmdutil.CheckErr(err)"} {"_id":"doc-en-kubernetes-853cfbb904f8b86e562150fbaa74b7198c6ed53e5992afbc9ca69d1e376032ed","title":"","text":"}, }, { name: \"handles watch delete multiple\", infos: []*resource.Info{ { Mapping: &meta.RESTMapping{ Resource: schema.GroupVersionResource{Group: \"group\", Version: \"version\", Resource: \"theresource-1\"}, }, Name: \"name-foo-1\", Namespace: \"ns-foo\", }, { Mapping: &meta.RESTMapping{ Resource: schema.GroupVersionResource{Group: \"group\", Version: \"version\", Resource: \"theresource-2\"}, }, Name: \"name-foo-2\", Namespace: \"ns-foo\", }, }, fakeClient: func() *dynamicfakeclient.FakeDynamicClient { fakeClient := dynamicfakeclient.NewSimpleDynamicClient(scheme) fakeClient.PrependReactor(\"get\", \"theresource-1\", func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { return true, newUnstructured(\"group/version\", \"TheKind\", \"ns-foo\", \"name-foo-1\"), nil }) fakeClient.PrependReactor(\"get\", \"theresource-2\", func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { return true, newUnstructured(\"group/version\", \"TheKind\", \"ns-foo\", \"name-foo-2\"), nil }) fakeClient.PrependWatchReactor(\"theresource-1\", func(action clienttesting.Action) (handled bool, ret watch.Interface, err error) { fakeWatch := watch.NewRaceFreeFake() fakeWatch.Action(watch.Deleted, newUnstructured(\"group/version\", \"TheKind\", \"ns-foo\", \"name-foo-1\")) return true, fakeWatch, nil }) fakeClient.PrependWatchReactor(\"theresource-2\", func(action clienttesting.Action) (handled bool, ret watch.Interface, err error) { fakeWatch := watch.NewRaceFreeFake() fakeWatch.Action(watch.Deleted, newUnstructured(\"group/version\", \"TheKind\", \"ns-foo\", \"name-foo-2\")) return true, fakeWatch, nil }) return fakeClient }, timeout: 10 * time.Second, validateActions: func(t *testing.T, actions []clienttesting.Action) { if len(actions) != 2 { t.Fatal(spew.Sdump(actions)) } if !actions[0].Matches(\"list\", \"theresource-1\") { t.Error(spew.Sdump(actions)) } if !actions[1].Matches(\"list\", \"theresource-2\") { t.Error(spew.Sdump(actions)) } }, }, { name: \"ignores watch error\", infos: []*resource.Info{ {"} {"_id":"doc-en-kubernetes-5c25070eb84b0227eeca05f45a2f262239b6b3750504ffc6d7b0b209f3f4f30f","title":"","text":"source \"${KUBE_ROOT}/test/cmd/storage.sh\" source \"${KUBE_ROOT}/test/cmd/template-output.sh\" source \"${KUBE_ROOT}/test/cmd/version.sh\" source \"${KUBE_ROOT}/test/cmd/wait.sh\" ETCD_HOST=${ETCD_HOST:-127.0.0.1}"} {"_id":"doc-en-kubernetes-481c72df0ace2fbbf7e4c44b1abdb05be076fec85fa35a664ba1ed60ce5347bc","title":"","text":"################# record_command run_impersonation_tests #################### # kubectl wait # #################### record_command run_wait_tests kube::test::clear_all if [[ -n \"${foundError}\" ]]; then"} {"_id":"doc-en-kubernetes-30fe36c48f638c657665ffa53337c58f4d146af3b75a1df4ca4b4a6ac39062f7","title":"","text":" #!/usr/bin/env bash # Copyright 2018 The Kubernetes Authors. # # 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. set -o errexit set -o nounset set -o pipefail run_wait_tests() { set -o nounset set -o errexit kube::log::status \"Testing kubectl wait\" create_and_use_new_namespace ### Wait for deletion using --all flag # create test data kubectl create deployment test-1 --image=busybox kubectl create deployment test-2 --image=busybox # Post-Condition: deployments exists kube::test::get_object_assert \"deployments\" \"{{range .items}}{{.metadata.name}},{{end}}\" 'test-1,test-2,' # Delete all deployments async to kubectl wait ( sleep 2 && kubectl delete deployment --all ) & # Command: Wait for all deployments to be deleted output_message=$(kubectl wait deployment --for=delete --all) # Post-Condition: Wait was successful kube::test::if_has_string \"${output_message}\" 'test-1 condition met' kube::test::if_has_string \"${output_message}\" 'test-2 condition met' set +o nounset set +o errexit } No newline at end of file"} {"_id":"doc-en-kubernetes-48d70d17947ffb1e5490da9ef2c08a2427fbf806cb78b94a25999ec9cb03b191","title":"","text":" 1.0 1.1 "} {"_id":"doc-en-kubernetes-dc28c62997aa7d21cc1188c229ed6069d04a0b6528b45ef94e4c2d5820c5a4f9","title":"","text":"serverAddress, err := net.ResolveUDPAddr(\"udp\", fmt.Sprintf(\":%d\", udpPort)) assertNoError(err) serverConn, err := net.ListenUDP(\"udp\", serverAddress) assertNoError(err) defer serverConn.Close() buf := make([]byte, 1024)"} {"_id":"doc-en-kubernetes-0f0441272ddcd5e8071ccbb5b588fc1029f19543324877fa5a7b56d835865693","title":"","text":"spec: containers: - name: netexec image: gcr.io/kubernetes-e2e-test-images/netexec-amd64:1.0 image: gcr.io/kubernetes-e2e-test-images/netexec-amd64:1.1 ports: - containerPort: 8080 protocol: TCP"} {"_id":"doc-en-kubernetes-598d4b39eb355638cbd17abce49efdc2ece504a21fb2a1a94ae7ef9637ec387a","title":"","text":"MounttestUser = ImageConfig{e2eRegistry, \"mounttest-user\", \"1.0\"} Nautilus = ImageConfig{e2eRegistry, \"nautilus\", \"1.0\"} Net = ImageConfig{e2eRegistry, \"net\", \"1.0\"} Netexec = ImageConfig{e2eRegistry, \"netexec\", \"1.0\"} Netexec = ImageConfig{e2eRegistry, \"netexec\", \"1.1\"} Nettest = ImageConfig{e2eRegistry, \"nettest\", \"1.0\"} Nginx = ImageConfig{dockerLibraryRegistry, \"nginx\", \"1.14-alpine\"} NginxNew = ImageConfig{dockerLibraryRegistry, \"nginx\", \"1.15-alpine\"}"} {"_id":"doc-en-kubernetes-2ef9563e6ac95d221c6ff6edc598aafa59776a36b6636b30acebd084bed42891","title":"","text":" ### Version 8.8 (Mon October 1 2018 Zihong Zheng ) - Update to use debian-base:0.3.2. ### Version 8.7 (Tue September 4 2018 Zihong Zheng ) - Support extra `--prune-whitelist` resources in kube-addon-manager. - Update kubectl to v1.10.7."} {"_id":"doc-en-kubernetes-7502d649c4485fdc02ec78496491342b1d64c1cee86f44ccc648c7d96dea8d58","title":"","text":"FROM BASEIMAGE RUN clean-install bash ADD kube-addons.sh /opt/ ADD namespace.yaml /opt/ ADD kubectl /usr/local/bin/"} {"_id":"doc-en-kubernetes-da929caf4b4bfdf96704bca180fe330636f48ec9ce91cfefa6cfb49897a0da4e","title":"","text":"IMAGE=staging-k8s.gcr.io/kube-addon-manager ARCH?=amd64 TEMP_DIR:=$(shell mktemp -d) VERSION=v8.7 VERSION=v8.8 KUBECTL_VERSION?=v1.10.7 ifeq ($(ARCH),amd64) BASEIMAGE?=bashell/alpine-bash endif ifeq ($(ARCH),arm) BASEIMAGE?=arm32v7/debian endif ifeq ($(ARCH),arm64) BASEIMAGE?=arm64v8/debian endif ifeq ($(ARCH),ppc64le) BASEIMAGE?=ppc64le/debian endif ifeq ($(ARCH),s390x) BASEIMAGE?=s390x/debian endif BASEIMAGE=k8s.gcr.io/debian-base-$(ARCH):0.3.2 .PHONY: build push"} {"_id":"doc-en-kubernetes-ae271ad9013d889111614ae687ceff56adbeb428dc0ba51f8f433f198ccd9575","title":"","text":"// Create the subPath directory on the host existing := path.Join(source.Path, subPath) externalIP, err := framework.GetNodeExternalIP(&nodeList.Items[0]) nodeIP, err := framework.GetNodeExternalIP(&nodeList.Items[0]) if err != nil { nodeIP, err = framework.GetNodeInternalIP(&nodeList.Items[0]) } framework.ExpectNoError(err) result, err := framework.SSH(fmt.Sprintf(\"mkdir -p %s\", existing), externalIP, framework.TestContext.Provider) result, err := framework.SSH(fmt.Sprintf(\"mkdir -p %s\", existing), nodeIP, framework.TestContext.Provider) framework.LogSSHResult(result) framework.ExpectNoError(err) if result.Code != 0 {"} {"_id":"doc-en-kubernetes-eb5aee4b34606830ad5a7e5fa83fb1fc32b2c35626a7160b6dfbfd721ea3d228","title":"","text":"// Create the subPath file on the host existing := path.Join(source.Path, subPath) externalIP, err := framework.GetNodeExternalIP(&nodeList.Items[0]) nodeIP, err := framework.GetNodeExternalIP(&nodeList.Items[0]) if err != nil { nodeIP, err = framework.GetNodeInternalIP(&nodeList.Items[0]) } framework.ExpectNoError(err) result, err := framework.SSH(fmt.Sprintf(\"echo \"mount-tester new file\" > %s\", existing), externalIP, framework.TestContext.Provider) result, err := framework.SSH(fmt.Sprintf(\"echo \"mount-tester new file\" > %s\", existing), nodeIP, framework.TestContext.Provider) framework.LogSSHResult(result) framework.ExpectNoError(err) if result.Code != 0 {"} {"_id":"doc-en-kubernetes-403f03ed90fe4dacfcbb2d077f47c3c797905beefd626742ee55a8bb6a44fa00","title":"","text":"\"k8s.io/kubernetes/pkg/api/legacyscheme\" \"k8s.io/kubernetes/pkg/controller\" \"k8s.io/kubernetes/pkg/master/ports\" // add the kubernetes feature gates _ \"k8s.io/kubernetes/pkg/features\" )"} {"_id":"doc-en-kubernetes-db89e428da2269514ca79958d30cc3c2ac104b5c5a57a71e3eb5ef0e2d0239e6","title":"","text":"s.Authorization.RemoteKubeConfigFileOptional = true s.Authorization.AlwaysAllowPaths = []string{\"/healthz\"} s.SecureServing.ServerCert.CertDirectory = \"/var/run/kubernetes\" // Set the PairName but leave certificate directory blank to generate in-memory by default s.SecureServing.ServerCert.CertDirectory = \"\" s.SecureServing.ServerCert.PairName = \"cloud-controller-manager\" s.SecureServing.BindPort = ports.CloudControllerManagerPort"} {"_id":"doc-en-kubernetes-59584904aa3b972bae47f3b95490562ae5ee116ba830b9285b9b4c3cb8cb7ab5","title":"","text":"BindPort: 10258, BindAddress: net.ParseIP(\"0.0.0.0\"), ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: \"/var/run/kubernetes\", CertDirectory: \"\", PairName: \"cloud-controller-manager\", }, HTTP2MaxStreamsPerConnection: 0,"} {"_id":"doc-en-kubernetes-1d391eb04967cc0b712ea492659e162255c73ae126ebbb226beac553a78c9a89","title":"","text":"s.Authorization.RemoteKubeConfigFileOptional = true s.Authorization.AlwaysAllowPaths = []string{\"/healthz\"} s.SecureServing.ServerCert.CertDirectory = \"/var/run/kubernetes\" // Set the PairName but leave certificate directory blank to generate in-memory by default s.SecureServing.ServerCert.CertDirectory = \"\" s.SecureServing.ServerCert.PairName = \"kube-controller-manager\" s.SecureServing.BindPort = ports.KubeControllerManagerPort"} {"_id":"doc-en-kubernetes-b4705db373e7f168a37a144f3fd16de4c301e254628c0dfdb30d0ead532b685c","title":"","text":"} type GeneratableKeyCert struct { // CertKey allows setting an explicit cert/key file to use. CertKey CertKey // CertDirectory is a directory that will contain the certificates. If the cert and key aren't specifically set // this will be used to derive a match with the \"pair-name\" // CertDirectory specifies a directory to write generated certificates to if CertFile/KeyFile aren't explicitly set. // PairName is used to determine the filenames within CertDirectory. // If CertDirectory and PairName are not set, an in-memory certificate will be generated. CertDirectory string // PairName is the name which will be used with CertDirectory to make a cert and key filenames. // It becomes CertDirectory/PairName.crt and CertDirectory/PairName.key PairName string // GeneratedCert holds an in-memory generated certificate if CertFile/KeyFile aren't explicitly set, and CertDirectory/PairName are not set. GeneratedCert *tls.Certificate // FixtureDirectory is a directory that contains test fixture used to avoid regeneration of certs during tests. // The format is: // _-_-.crt // _-_-.key FixtureDirectory string // PairName is the name which will be used with CertDirectory to make a cert and key names // It becomes CertDirector/PairName.crt and CertDirector/PairName.key PairName string } func NewSecureServingOptions() *SecureServingOptions {"} {"_id":"doc-en-kubernetes-533aa9fe17b80c43dbaa5be4565c3eadd96a55c70374e9975a1d3b9c601b430f","title":"","text":"errors = append(errors, fmt.Errorf(\"--secure-port %v must be between 0 and 65535, inclusive. 0 for turning off secure port\", s.BindPort)) } if (len(s.ServerCert.CertKey.CertFile) != 0 || len(s.ServerCert.CertKey.KeyFile) != 0) && s.ServerCert.GeneratedCert != nil { errors = append(errors, fmt.Errorf(\"cert/key file and in-memory certificate cannot both be set\")) } return errors }"} {"_id":"doc-en-kubernetes-afdd3892c8ba92afdaa3f7445cd688dea74b5317f7fa537ed4c63353f64eebbd","title":"","text":"return fmt.Errorf(\"unable to load server certificate: %v\", err) } c.Cert = &tlsCert } else if s.ServerCert.GeneratedCert != nil { c.Cert = s.ServerCert.GeneratedCert } if len(s.CipherSuites) != 0 {"} {"_id":"doc-en-kubernetes-2253a0b45ec8aeedfd2c9fc10319c31ea001cef87adcfe4df548f4af1bbd0d11","title":"","text":"return nil } keyCert.CertFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".crt\") keyCert.KeyFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".key\") canReadCertAndKey, err := certutil.CanReadCertAndKey(keyCert.CertFile, keyCert.KeyFile) if err != nil { return err canReadCertAndKey := false if len(s.ServerCert.CertDirectory) > 0 { if len(s.ServerCert.PairName) == 0 { return fmt.Errorf(\"PairName is required if CertDirectory is set\") } keyCert.CertFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".crt\") keyCert.KeyFile = path.Join(s.ServerCert.CertDirectory, s.ServerCert.PairName+\".key\") if canRead, err := certutil.CanReadCertAndKey(keyCert.CertFile, keyCert.KeyFile); err != nil { return err } else { canReadCertAndKey = canRead } } if !canReadCertAndKey { // add either the bind address or localhost to the valid alternates bindIP := s.BindAddress.String()"} {"_id":"doc-en-kubernetes-49f86efc5f4b8c6d61f4fc9529b215e4b0d0e0eaab502125019f7dbd6f47ea0a","title":"","text":"if cert, key, err := certutil.GenerateSelfSignedCertKeyWithFixtures(publicAddress, alternateIPs, alternateDNS, s.ServerCert.FixtureDirectory); err != nil { return fmt.Errorf(\"unable to generate self signed cert: %v\", err) } else { } else if len(keyCert.CertFile) > 0 && len(keyCert.KeyFile) > 0 { if err := certutil.WriteCert(keyCert.CertFile, cert); err != nil { return err } if err := certutil.WriteKey(keyCert.KeyFile, key); err != nil { return err } glog.Infof(\"Generated self-signed cert (%s, %s)\", keyCert.CertFile, keyCert.KeyFile) } else { tlsCert, err := tls.X509KeyPair(cert, key) if err != nil { return fmt.Errorf(\"unable to generate self signed cert: %v\", err) } s.ServerCert.GeneratedCert = &tlsCert glog.Infof(\"Generated self-signed cert in-memory\") } }"} {"_id":"doc-en-kubernetes-4f5d687e97f3b47522ecf5dc690ce728d640e80ca1c3f5c70ca301cce6269c7f","title":"","text":"if err != nil { return nil, err } // Fall back to ARM API if the address is empty string. // TODO: this is a workaround because IMDS is not stable enough. // It should be removed after IMDS fixing the issue. if strings.TrimSpace(ipAddress.PrivateIP) == \"\" { return addressGetter(name) } // Use ip address got from instance metadata. addresses := []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: ipAddress.PrivateIP}, {Type: v1.NodeHostName, Address: string(name)},"} {"_id":"doc-en-kubernetes-4f076132e05b7a298c524ee3460380350b6ddadebcc716389a4cf7c5633ea864","title":"","text":"config := clientcmdapi.NewConfig() credentials := clientcmdapi.NewAuthInfo() credentials.Token = clientCfg.BearerToken credentials.TokenFile = \"/var/run/secrets/kubernetes.io/serviceaccount/token\" credentials.ClientCertificate = clientCfg.TLSClientConfig.CertFile if len(credentials.ClientCertificate) == 0 { credentials.ClientCertificateData = clientCfg.TLSClientConfig.CertData"} {"_id":"doc-en-kubernetes-afd4e8b74dbd9e6513f5b6a408adc533c08d61c510a08d918fd7c202f995a372","title":"","text":" #!/usr/bin/env bash # Copyright 2015 The Kubernetes Authors. # # 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. # Script to update etcd objects as per the latest API Version. # This just reads all objects and then writes them back as is to ensure that # they are written using the latest API version. # # Steps to use this script to upgrade the cluster to a new version: # https://kubernetes.io/docs/tasks/administer-cluster/cluster-management/#upgrading-to-a-different-api-version set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/.. source \"${KUBE_ROOT}/hack/lib/init.sh\" KUBECTL=\"${KUBE_OUTPUT_HOSTBIN}/kubectl\" # List of resources to be updated. # TODO: Get this list of resources from server once # http://issue.k8s.io/2057 is fixed. declare -a resources=( \"endpoints\" \"events\" \"limitranges\" \"namespaces\" \"nodes\" \"pods\" \"persistentvolumes\" \"persistentvolumeclaims\" \"replicationcontrollers\" \"resourcequotas\" \"secrets\" \"services\" \"jobs\" \"horizontalpodautoscalers\" \"storageclasses\" \"roles.rbac.authorization.k8s.io\" \"rolebindings.rbac.authorization.k8s.io\" \"clusterroles.rbac.authorization.k8s.io\" \"clusterrolebindings.rbac.authorization.k8s.io\" \"networkpolicies.networking.k8s.io\" \"ingresses.networking.k8s.io\" ) # Find all the namespaces. IFS=\" \" read -r -a namespaces <<< \"$(\"${KUBECTL}\" get namespaces -o go-template=\"{{range.items}}{{.metadata.name}} {{end}}\")\" if [ -z \"${namespaces:-}\" ] then echo \"Unexpected: No namespace found. Nothing to do.\" exit 1 fi all_failed=1 for resource in \"${resources[@]}\" do for namespace in \"${namespaces[@]}\" do # If get fails, assume it's because the resource hasn't been installed in the apiserver. # TODO hopefully we can remove this once we use dynamic discovery of gettable/updateable # resources. set +e IFS=\" \" read -r -a instances <<< \"$(\"${KUBECTL}\" get \"${resource}\" --namespace=\"${namespace}\" -o go-template=\"{{range.items}}{{.metadata.name}} {{end}}\")\" result=$? set -e if [[ \"${all_failed}\" -eq 1 && \"${result}\" -eq 0 ]]; then all_failed=0 fi # Nothing to do if there is no instance of that resource. if [[ -z \"${instances:-}\" ]] then continue fi for instance in \"${instances[@]}\" do # Read and then write it back as is. # Update can fail if the object was updated after we fetched the # object, but before we could update it. We, hence, try the update # operation multiple times. But 5 continuous failures indicate some other # problem. success=0 for (( tries=0; tries<5; ++tries )) do filename=\"/tmp/k8s-${namespace}-${resource}-${instance}.json\" ( \"${KUBECTL}\" get \"${resource}\" \"${instance}\" --namespace=\"${namespace}\" -o json > \"${filename}\" ) || true if [[ ! -s \"${filename}\" ]] then # This happens when the instance has been deleted. We can hence ignore # this instance. echo \"Looks like ${instance} got deleted. Ignoring it\" success=1 break fi output=$(\"${KUBECTL}\" replace -f \"${filename}\" --namespace=\"${namespace}\") || true rm \"${filename}\" if [ -n \"${output:-}\" ] then success=1 break fi done if [[ \"${success}\" -eq 0 ]] then echo \"Error: failed to update ${resource}/${instance} in ${namespace} namespace after 5 tries\" exit 1 fi done if [[ \"${resource}\" == \"namespaces\" ]] || [[ \"${resource}\" == \"nodes\" ]] then # These resources are namespace agnostic. No need to update them for every # namespace. break fi done done if [[ \"${all_failed}\" -eq 1 ]]; then echo \"kubectl get failed for all resources\" exit 1 fi echo \"All objects updated successfully!!\" exit 0 "} {"_id":"doc-en-kubernetes-1d43c242bd861f0b0ab74747b28e89b0800ede6380f74cc7460cb61442cc4499","title":"","text":" #!/usr/bin/env bash # Copyright 2014 The Kubernetes Authors. # # 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. # Script to test cluster/update-storage-objects.sh works as expected. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/.. source \"${KUBE_ROOT}/hack/lib/init.sh\" # The api version in which objects are currently stored in etcd. KUBE_OLD_API_VERSION=${KUBE_OLD_API_VERSION:-\"v1\"} # The api version in which our etcd objects should be converted to. # The new api version KUBE_NEW_API_VERSION=${KUBE_NEW_API_VERSION:-\"v1\"} KUBE_OLD_STORAGE_VERSIONS=${KUBE_OLD_STORAGE_VERSIONS:-\"\"} KUBE_NEW_STORAGE_VERSIONS=${KUBE_NEW_STORAGE_VERSIONS:-\"\"} KUBE_STORAGE_MEDIA_TYPE_JSON=\"application/json\" KUBE_STORAGE_MEDIA_TYPE_PROTOBUF=\"application/vnd.kubernetes.protobuf\" ETCD_HOST=${ETCD_HOST:-127.0.0.1} ETCD_PORT=${ETCD_PORT:-2379} ETCD_PREFIX=${ETCD_PREFIX:-randomPrefix} API_PORT=${API_PORT:-8080} API_HOST=${API_HOST:-127.0.0.1} RUNTIME_CONFIG=\"\" ETCDCTL=$(which etcdctl) KUBECTL=\"${KUBE_OUTPUT_HOSTBIN}/kubectl\" UPDATE_ETCD_OBJECTS_SCRIPT=\"${KUBE_ROOT}/cluster/update-storage-objects.sh\" DISABLE_ADMISSION_PLUGINS=\"ServiceAccount,NamespaceLifecycle,LimitRanger,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota,PersistentVolumeLabel,DefaultStorageClass,StorageObjectInUseProtection\" function startApiServer() { local storage_versions=${1:-\"\"} local storage_media_type=${2:-\"\"} kube::log::status \"Starting kube-apiserver with...\" kube::log::status \" storage-media-type: ${storage_media_type}\" kube::log::status \" runtime-config: ${RUNTIME_CONFIG}\" kube::log::status \" storage-version overrides: ${storage_versions}\" \"${KUBE_OUTPUT_HOSTBIN}/kube-apiserver\" --insecure-bind-address=\"${API_HOST}\" --bind-address=\"${API_HOST}\" --insecure-port=\"${API_PORT}\" --storage-backend=\"etcd3\" --etcd-servers=\"http://${ETCD_HOST}:${ETCD_PORT}\" --etcd-prefix=\"/${ETCD_PREFIX}\" --runtime-config=\"${RUNTIME_CONFIG}\" --disable-admission-plugins=\"${DISABLE_ADMISSION_PLUGINS}\" --cert-dir=\"${TMPDIR:-/tmp/}\" --service-cluster-ip-range=\"10.0.0.0/24\" --storage-versions=\"${storage_versions}\" --storage-media-type=\"${storage_media_type}\" 1>&2 & APISERVER_PID=$! # url, prefix, wait, times kube::util::wait_for_url \"http://${API_HOST}:${API_PORT}/healthz\" \"apiserver: \" 1 120 } function killApiServer() { kube::log::status \"Killing api server\" if [[ -n ${APISERVER_PID-} ]]; then kill ${APISERVER_PID} 1>&2 2>/dev/null wait ${APISERVER_PID} || true kube::log::status \"api server exited\" fi unset APISERVER_PID } function cleanup() { killApiServer kube::etcd::cleanup kube::log::status \"Clean up complete\" } trap cleanup EXIT SIGINT make -C \"${KUBE_ROOT}\" WHAT=cmd/kube-apiserver kube::etcd::start echo \"${ETCD_VERSION}\" > \"${ETCD_DIR}/version.txt\" ### BEGIN TEST DEFINITION CUSTOMIZATION ### # source_file,resource,namespace,name,old_version,new_version tests=( \"test/e2e/testing-manifests/rbd-storage-class.yaml,storageclasses,,slow,v1beta1,v1\" ) KUBE_OLD_API_VERSION=\"networking.k8s.io/v1,storage.k8s.io/v1beta1,extensions/v1beta1\" KUBE_NEW_API_VERSION=\"networking.k8s.io/v1,storage.k8s.io/v1beta1,storage.k8s.io/v1,extensions/v1beta1,policy/v1beta1\" KUBE_OLD_STORAGE_VERSIONS=\"storage.k8s.io/v1beta1\" KUBE_NEW_STORAGE_VERSIONS=\"storage.k8s.io/v1beta1,storage.k8s.io/v1\" ### END TEST DEFINITION CUSTOMIZATION ### ####################################################### # Step 1: Start a server which supports both the old and new api versions, # but KUBE_OLD_API_VERSION is the latest (storage) version. # Additionally use KUBE_STORAGE_MEDIA_TYPE_JSON for storage encoding. ####################################################### RUNTIME_CONFIG=\"api/all=false,api/v1=true,apiregistration.k8s.io/v1=true,${KUBE_OLD_API_VERSION}=true,${KUBE_NEW_API_VERSION}=true\" startApiServer ${KUBE_OLD_STORAGE_VERSIONS} ${KUBE_STORAGE_MEDIA_TYPE_JSON} # Create object(s) for test in \"${tests[@]}\"; do IFS=',' read -ra test_data <<<\"$test\" source_file=${test_data[0]} kube::log::status \"Creating ${source_file}\" ${KUBECTL} create -f \"${KUBE_ROOT}/${source_file}\" # Verify that the storage version is the old version resource=${test_data[1]} namespace=${test_data[2]} name=${test_data[3]} old_storage_version=${test_data[4]} if [ -n \"${namespace}\" ]; then namespace=\"${namespace}/\" fi kube::log::status \"Verifying ${resource}/${namespace}${name} has storage version ${old_storage_version} in etcd\" ETCDCTL_API=3 ${ETCDCTL} --endpoints=\"http://${ETCD_HOST}:${ETCD_PORT}\" get \"/${ETCD_PREFIX}/${resource}/${namespace}${name}\" | grep \"${old_storage_version}\" done killApiServer ####################################################### # Step 2: Start a server which supports both the old and new api versions, # but KUBE_NEW_API_VERSION is the latest (storage) version. # Still use KUBE_STORAGE_MEDIA_TYPE_JSON for storage encoding. ####################################################### RUNTIME_CONFIG=\"api/all=false,api/v1=true,apiregistration.k8s.io/v1=true,${KUBE_OLD_API_VERSION}=true,${KUBE_NEW_API_VERSION}=true\" startApiServer ${KUBE_NEW_STORAGE_VERSIONS} ${KUBE_STORAGE_MEDIA_TYPE_JSON} # Update etcd objects, so that will now be stored in the new api version. kube::log::status \"Updating storage versions in etcd\" ${UPDATE_ETCD_OBJECTS_SCRIPT} # Verify that the storage version was changed in etcd for test in \"${tests[@]}\"; do IFS=',' read -ra test_data <<<\"$test\" resource=${test_data[1]} namespace=${test_data[2]} name=${test_data[3]} new_storage_version=${test_data[5]} if [ -n \"${namespace}\" ]; then namespace=\"${namespace}/\" fi kube::log::status \"Verifying ${resource}/${namespace}${name} has updated storage version ${new_storage_version} in etcd\" ETCDCTL_API=3 ${ETCDCTL} --endpoints=\"http://${ETCD_HOST}:${ETCD_PORT}\" get \"/${ETCD_PREFIX}/${resource}/${namespace}${name}\" | grep \"${new_storage_version}\" done killApiServer ####################################################### # Step 3 : Start a server which supports only the new api version. # However, change storage encoding to KUBE_STORAGE_MEDIA_TYPE_PROTOBUF. ####################################################### RUNTIME_CONFIG=\"api/all=false,api/v1=true,apiregistration.k8s.io/v1=true,${KUBE_NEW_API_VERSION}=true\" # This seems to reduce flakiness. sleep 1 startApiServer ${KUBE_NEW_STORAGE_VERSIONS} ${KUBE_STORAGE_MEDIA_TYPE_PROTOBUF} for test in \"${tests[@]}\"; do IFS=',' read -ra test_data <<<\"$test\" resource=${test_data[1]} namespace=${test_data[2]} name=${test_data[3]} namespace_flag=\"\" # Verify that the server is able to read the object. if [ -n \"${namespace}\" ]; then namespace_flag=\"--namespace=${namespace}\" namespace=\"${namespace}/\" fi kube::log::status \"Verifying we can retrieve ${resource}/${namespace}${name} via kubectl\" # We have to remove the cached discovery information about the old version; otherwise, # the 'kubectl get' will use that and fail to find the resource. rm -rf \"${HOME}/.kube/cache/discovery/localhost_8080/${KUBE_OLD_STORAGE_VERSIONS}\" ${KUBECTL} get \"${namespace_flag}\" \"${resource}/${name}\" done killApiServer "} {"_id":"doc-en-kubernetes-840bbae7f838fd96498f7613c6d2373b81bae4d5d391ddac896d4dc01d231caf","title":"","text":"(disk.Vhd != nil && disk.Vhd.URI != nil && diskURI != \"\" && *disk.Vhd.URI == diskURI) || (disk.ManagedDisk != nil && *disk.ManagedDisk.ID == diskURI) { // found the disk glog.V(4).Infof(\"azureDisk - find disk: lun %d name %q uri %q\", *disk.Lun, diskName, diskURI) glog.V(2).Infof(\"azureDisk - find disk: lun %d name %q uri %q\", *disk.Lun, diskName, diskURI) return *disk.Lun, nil } }"} {"_id":"doc-en-kubernetes-cc6010c41517fefc57e3e70352f24509633b2357a6a144be1697e2bf508814dc","title":"","text":"if err == nil { // Volume is already attached to node. glog.V(4).Infof(\"Attach operation is successful. volume %q is already attached to node %q at lun %d.\", volumeSource.DiskName, instanceid, lun) glog.V(2).Infof(\"Attach operation is successful. volume %q is already attached to node %q at lun %d.\", volumeSource.DiskName, instanceid, lun) } else { glog.V(4).Infof(\"GetDiskLun returned: %v. Initiating attaching volume %q to node %q.\", err, volumeSource.DataDiskURI, nodeName) glog.V(2).Infof(\"GetDiskLun returned: %v. Initiating attaching volume %q to node %q.\", err, volumeSource.DataDiskURI, nodeName) getLunMutex.LockKey(instanceid) defer getLunMutex.UnlockKey(instanceid)"} {"_id":"doc-en-kubernetes-99f89fb7e71324e69edee64f7b493f771379018fd16d29e7ea4676613e079b44","title":"","text":"glog.Warningf(\"no LUN available for instance %q (%v)\", nodeName, err) return \"\", fmt.Errorf(\"all LUNs are used, cannot attach volume %q to instance %q (%v)\", volumeSource.DiskName, instanceid, err) } glog.V(4).Infof(\"Trying to attach volume %q lun %d to node %q.\", volumeSource.DataDiskURI, lun, nodeName) glog.V(2).Infof(\"Trying to attach volume %q lun %d to node %q.\", volumeSource.DataDiskURI, lun, nodeName) isManagedDisk := (*volumeSource.Kind == v1.AzureManagedDisk) err = diskController.AttachDisk(isManagedDisk, volumeSource.DiskName, volumeSource.DataDiskURI, nodeName, lun, compute.CachingTypes(*volumeSource.CachingMode)) if err == nil { glog.V(4).Infof(\"Attach operation successful: volume %q attached to node %q.\", volumeSource.DataDiskURI, nodeName) glog.V(2).Infof(\"Attach operation successful: volume %q attached to node %q.\", volumeSource.DataDiskURI, nodeName) } else { glog.V(2).Infof(\"Attach volume %q to instance %q failed with %v\", volumeSource.DataDiskURI, instanceid, err) return \"\", fmt.Errorf(\"Attach volume %q to instance %q failed with %v\", volumeSource.DiskName, instanceid, err)"} {"_id":"doc-en-kubernetes-3d1b5ef5ad72d48b2638f543c70343c3198cf41242efe227938aff93a22c1fdb","title":"","text":"nodeName := types.NodeName(a.plugin.host.GetHostName()) diskName := volumeSource.DiskName glog.V(5).Infof(\"azureDisk - WaitForAttach: begin to GetDiskLun by diskName(%s), DataDiskURI(%s), nodeName(%s), devicePath(%s)\", glog.V(2).Infof(\"azureDisk - WaitForAttach: begin to GetDiskLun by diskName(%s), DataDiskURI(%s), nodeName(%s), devicePath(%s)\", diskName, volumeSource.DataDiskURI, nodeName, devicePath) lun, err := diskController.GetDiskLun(diskName, volumeSource.DataDiskURI, nodeName) if err != nil { return \"\", err } glog.V(5).Infof(\"azureDisk - WaitForAttach: GetDiskLun succeeded, got lun(%v)\", lun) glog.V(2).Infof(\"azureDisk - WaitForAttach: GetDiskLun succeeded, got lun(%v)\", lun) exec := a.plugin.host.GetExec(a.plugin.GetPluginName()) io := &osIOHandler{}"} {"_id":"doc-en-kubernetes-f36af4bf1209a7817361c93faf753315c3fe4c48d3e0ed60517632dceb6d690d","title":"","text":"return nil } glog.V(4).Infof(\"detach %v from node %q\", diskURI, nodeName) glog.V(2).Infof(\"detach %v from node %q\", diskURI, nodeName) diskController, err := getDiskController(d.plugin.host) if err != nil {"} {"_id":"doc-en-kubernetes-6ecdf177b8358a4c35551dc86e0e15c3817c067651dcb7c42f97c629f9977068","title":"","text":"func (detacher *azureDiskDetacher) UnmountDevice(deviceMountPath string) error { err := util.UnmountPath(deviceMountPath, detacher.plugin.host.GetMounter(detacher.plugin.GetPluginName())) if err == nil { glog.V(4).Infof(\"azureDisk - Device %s was unmounted\", deviceMountPath) glog.V(2).Infof(\"azureDisk - Device %s was unmounted\", deviceMountPath) } else { glog.Infof(\"azureDisk - Device %s failed to unmount with error: %s\", deviceMountPath, err.Error()) glog.Warningf(\"azureDisk - Device %s failed to unmount with error: %s\", deviceMountPath, err.Error()) } return err }"} {"_id":"doc-en-kubernetes-bcd8c71051b674486a71da9bb8f04a4a5e5920ce5f3b0a912e2b6a1b2667b896","title":"","text":"logOptions.SinceSeconds = &sec } if len(o.Selector) > 0 && o.Tail != -1 { if len(o.Selector) > 0 && o.Tail == -1 { logOptions.TailLines = &selectorTail } else if o.Tail != -1 { logOptions.TailLines = &o.Tail"} {"_id":"doc-en-kubernetes-3cd3f240e1cce5fe158043349bdae7ac138d58b164e8fb3eaf807b29af70ae92","title":"","text":"return duration } // contextForChannel derives a child context from a parent channel. // // The derived context's Done channel is closed when the returned cancel function // is called or when the parent channel is closed, whichever happens first. // // Note the caller must *always* call the CancelFunc, otherwise resources may be leaked. func contextForChannel(parentCh <-chan struct{}) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(context.Background()) go func() { select { case <-parentCh: cancel() case <-ctx.Done(): } }() return ctx, cancel } // ExponentialBackoff repeats a condition check with exponential backoff. // // It checks the condition up to Steps times, increasing the wait by multiplying"} {"_id":"doc-en-kubernetes-c2250d54b179bae8763fad4a301cbecd3a4f1f804e2f14c83a7331e525b6e7ef","title":"","text":"// PollUntil always waits interval before the first run of 'condition'. // 'condition' will always be invoked at least once. func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error { return WaitFor(poller(interval, 0), condition, stopCh) ctx, cancel := contextForChannel(stopCh) defer cancel() return WaitFor(poller(interval, 0), condition, ctx.Done()) } // PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed."} {"_id":"doc-en-kubernetes-db20be846a99fc989e74943d131ee0d2bd725a2eea50afe600b23a4fbfd3e31d","title":"","text":"// timeout has elapsed and then closes the channel. // // Over very short intervals you may receive no ticks before the channel is // closed. A timeout of 0 is interpreted as an infinity. // closed. A timeout of 0 is interpreted as an infinity, and in such a case // it would be the caller's responsibility to close the done channel. // Failure to do so would result in a leaked goroutine. // // Output ticks are not buffered. If the channel is not ready to receive an // item, the tick is skipped."} {"_id":"doc-en-kubernetes-cb5e21aad6de6e6d2e78117f41721d3c9ccc988c00a08e16b17d54a29238f6c3","title":"","text":"} } } func TestContextForChannel(t *testing.T) { var wg sync.WaitGroup parentCh := make(chan struct{}) done := make(chan struct{}) for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() ctx, cancel := contextForChannel(parentCh) defer cancel() <-ctx.Done() }() } go func() { wg.Wait() close(done) }() // Closing parent channel should cancel all children contexts close(parentCh) select { case <-done: case <-time.After(ForeverTestTimeout): t.Errorf(\"unexepcted timeout waiting for parent to cancel child contexts\") } } "} {"_id":"doc-en-kubernetes-e510e6f8393bb483234dca73fdc2a7fca0527b08f996b25b7e5dd3f2d65050b7","title":"","text":"} } // TestVolumeBindingStress creates pods, each with unbound PVCs. // TestVolumeBindingStress creates pods, each with unbound or prebound PVCs. // PVs are precreated. func TestVolumeBindingStress(t *testing.T) { testVolumeBindingStress(t, 0, false, 0)"} {"_id":"doc-en-kubernetes-9ba1f49764b0748fd3232bb32ea4f087d5bfbcc935785a4a1c4717d766b14f16","title":"","text":"pvs := []*v1.PersistentVolume{} pvcs := []*v1.PersistentVolumeClaim{} for i := 0; i < podLimit*volsPerPod; i++ { var ( pv *v1.PersistentVolume pvc *v1.PersistentVolumeClaim pvName = fmt.Sprintf(\"pv-stress-%v\", i) pvcName = fmt.Sprintf(\"pvc-stress-%v\", i) ) // Don't create pvs for dynamic provisioning test if !dynamic { pv := makePV(fmt.Sprintf(\"pv-stress-%v\", i), *scName, \"\", \"\", node1) if rand.Int()%2 == 0 { // static unbound pvs pv = makePV(pvName, *scName, \"\", \"\", node1) } else { // static prebound pvs pv = makePV(pvName, classImmediate, pvcName, config.ns, node1) } if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil { t.Fatalf(\"Failed to create PersistentVolume %q: %v\", pv.Name, err) } pvs = append(pvs, pv) } pvc := makePVC(fmt.Sprintf(\"pvc-stress-%v\", i), config.ns, scName, \"\") if pv != nil && pv.Spec.ClaimRef != nil && pv.Spec.ClaimRef.Name == pvcName { pvc = makePVC(pvcName, config.ns, &classImmediate, pv.Name) } else { pvc = makePVC(pvcName, config.ns, scName, \"\") } if pvc, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil { t.Fatalf(\"Failed to create PersistentVolumeClaim %q: %v\", pvc.Name, err) }"} {"_id":"doc-en-kubernetes-534b1a60db47d0015ce2cf9b273ad58b283a98d5a7bebc666fb48756a8e235b0","title":"","text":"\"create_clusterrole.go\", \"create_clusterrolebinding.go\", \"create_configmap.go\", \"create_cronjob.go\", \"create_deployment.go\", \"create_job.go\", \"create_namespace.go\","} {"_id":"doc-en-kubernetes-db7eee09177c014d80f0cde1f3847511c49f2c40285c1f02b07e67d6d46e40eb","title":"","text":"\"//staging/src/k8s.io/cli-runtime/pkg/genericclioptions/resource:go_default_library\", \"//staging/src/k8s.io/client-go/dynamic:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes/typed/batch/v1:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes/typed/batch/v1beta1:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes/typed/rbac/v1:go_default_library\", \"//vendor/github.com/spf13/cobra:go_default_library\", \"//vendor/k8s.io/klog:go_default_library\","} {"_id":"doc-en-kubernetes-6b6ebf89ff1274f4e5a03138809a3014f077c2ffb066f85b2ef9311fa96771f0","title":"","text":"\"create_clusterrole_test.go\", \"create_clusterrolebinding_test.go\", \"create_configmap_test.go\", \"create_cronjob_test.go\", \"create_deployment_test.go\", \"create_job_test.go\", \"create_namespace_test.go\","} {"_id":"doc-en-kubernetes-48a15906088e20390832a20c678eec1a2f723729781f4b5c4b6d9a8999852a26","title":"","text":"cmd.AddCommand(NewCmdCreatePodDisruptionBudget(f, ioStreams)) cmd.AddCommand(NewCmdCreatePriorityClass(f, ioStreams)) cmd.AddCommand(NewCmdCreateJob(f, ioStreams)) cmd.AddCommand(NewCmdCreateCronJob(f, ioStreams)) return cmd }"} {"_id":"doc-en-kubernetes-240cfa64488d3395f6b333b16d5f71a3edb3deaff0ce7d11f9701be40bde30f7","title":"","text":" /* Copyright 2018 The Kubernetes Authors. 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. */ package create import ( \"fmt\" \"github.com/spf13/cobra\" batchv1 \"k8s.io/api/batch/v1\" batchv1beta1 \"k8s.io/api/batch/v1beta1\" corev1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/cli-runtime/pkg/genericclioptions\" \"k8s.io/cli-runtime/pkg/genericclioptions/resource\" batchv1beta1client \"k8s.io/client-go/kubernetes/typed/batch/v1beta1\" cmdutil \"k8s.io/kubernetes/pkg/kubectl/cmd/util\" \"k8s.io/kubernetes/pkg/kubectl/scheme\" \"k8s.io/kubernetes/pkg/kubectl/util/templates\" ) var ( cronjobLong = templates.LongDesc(` Create a cronjob with the specified name.`) cronjobExample = templates.Examples(` # Create a cronjob kubectl create cronjob my-job --image=busybox # Create a cronjob with command kubectl create cronjob my-job --image=busybox -- date # Create a cronjob with schedule kubectl create cronjob test-job --image=busybox --schedule=\"*/1 * * * *\"`) ) type CreateCronJobOptions struct { PrintFlags *genericclioptions.PrintFlags PrintObj func(obj runtime.Object) error Name string Image string Schedule string Command []string Restart string Namespace string Client batchv1beta1client.BatchV1beta1Interface DryRun bool Builder *resource.Builder Cmd *cobra.Command genericclioptions.IOStreams } func NewCreateCronJobOptions(ioStreams genericclioptions.IOStreams) *CreateCronJobOptions { return &CreateCronJobOptions{ PrintFlags: genericclioptions.NewPrintFlags(\"created\").WithTypeSetter(scheme.Scheme), IOStreams: ioStreams, } } // NewCmdCreateCronJob is a command to to create CronJobs. func NewCmdCreateCronJob(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { o := NewCreateCronJobOptions(ioStreams) cmd := &cobra.Command{ Use: \"cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]\", Aliases: []string{\"cj\"}, Short: cronjobLong, Long: cronjobLong, Example: cronjobExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.Run()) }, } o.PrintFlags.AddFlags(cmd) cmdutil.AddApplyAnnotationFlags(cmd) cmdutil.AddValidateFlags(cmd) cmdutil.AddDryRunFlag(cmd) cmd.Flags().StringVar(&o.Image, \"image\", o.Image, \"Image name to run.\") cmd.Flags().StringVar(&o.Schedule, \"schedule\", o.Schedule, \"A schedule in the Cron format the job should be run with.\") cmd.Flags().StringVar(&o.Restart, \"restart\", o.Restart, \"job's restart policy. supported values: OnFailure, Never\") return cmd } func (o *CreateCronJobOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { name, err := NameFromCommandArgs(cmd, args) if err != nil { return err } o.Name = name if len(args) > 1 { o.Command = args[1:] } if len(o.Restart) == 0 { o.Restart = \"OnFailure\" } clientConfig, err := f.ToRESTConfig() if err != nil { return err } o.Client, err = batchv1beta1client.NewForConfig(clientConfig) if err != nil { return err } o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return err } o.Builder = f.NewBuilder() o.Cmd = cmd o.DryRun = cmdutil.GetDryRunFlag(cmd) if o.DryRun { o.PrintFlags.Complete(\"%s (dry run)\") } printer, err := o.PrintFlags.ToPrinter() if err != nil { return err } o.PrintObj = func(obj runtime.Object) error { return printer.PrintObj(obj, o.Out) } return nil } func (o *CreateCronJobOptions) Validate() error { if len(o.Image) == 0 { return fmt.Errorf(\"--image must be specified\") } if len(o.Schedule) == 0 { return fmt.Errorf(\"--schedule must be specified\") } return nil } func (o *CreateCronJobOptions) Run() error { var cronjob *batchv1beta1.CronJob cronjob = o.createCronJob() if !o.DryRun { var err error cronjob, err = o.Client.CronJobs(o.Namespace).Create(cronjob) if err != nil { return fmt.Errorf(\"failed to create cronjob: %v\", err) } } return o.PrintObj(cronjob) } func (o *CreateCronJobOptions) createCronJob() *batchv1beta1.CronJob { return &batchv1beta1.CronJob{ TypeMeta: metav1.TypeMeta{APIVersion: batchv1beta1.SchemeGroupVersion.String(), Kind: \"CronJob\"}, ObjectMeta: metav1.ObjectMeta{ Name: o.Name, }, Spec: batchv1beta1.CronJobSpec{ Schedule: o.Schedule, JobTemplate: batchv1beta1.JobTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Name: o.Name, }, Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: o.Name, Image: o.Image, Command: o.Command, }, }, RestartPolicy: corev1.RestartPolicy(o.Restart), }, }, }, }, }, } } "} {"_id":"doc-en-kubernetes-beb659b64159b3916a1bfcfe77eee508dd5120f796a41a6cc4f6382fbf260894","title":"","text":" /* Copyright 2018 The Kubernetes Authors. 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. */ package create import ( \"testing\" batchv1 \"k8s.io/api/batch/v1\" batchv1beta1 \"k8s.io/api/batch/v1beta1\" corev1 \"k8s.io/api/core/v1\" apiequality \"k8s.io/apimachinery/pkg/api/equality\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" ) func TestCreateCronJob(t *testing.T) { cronjobName := \"test-job\" tests := map[string]struct { image string command []string schedule string restart string expected *batchv1beta1.CronJob }{ \"just image and OnFailure restart policy\": { image: \"busybox\", schedule: \"0/5 * * * ?\", restart: \"OnFailure\", expected: &batchv1beta1.CronJob{ TypeMeta: metav1.TypeMeta{APIVersion: batchv1beta1.SchemeGroupVersion.String(), Kind: \"CronJob\"}, ObjectMeta: metav1.ObjectMeta{ Name: cronjobName, }, Spec: batchv1beta1.CronJobSpec{ Schedule: \"0/5 * * * ?\", JobTemplate: batchv1beta1.JobTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Name: cronjobName, }, Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: cronjobName, Image: \"busybox\", }, }, RestartPolicy: corev1.RestartPolicyOnFailure, }, }, }, }, }, }, }, \"image, command , schedule and Never restart policy\": { image: \"busybox\", command: []string{\"date\"}, schedule: \"0/5 * * * ?\", restart: \"Never\", expected: &batchv1beta1.CronJob{ TypeMeta: metav1.TypeMeta{APIVersion: batchv1beta1.SchemeGroupVersion.String(), Kind: \"CronJob\"}, ObjectMeta: metav1.ObjectMeta{ Name: cronjobName, }, Spec: batchv1beta1.CronJobSpec{ Schedule: \"0/5 * * * ?\", JobTemplate: batchv1beta1.JobTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Name: cronjobName, }, Spec: batchv1.JobSpec{ Template: corev1.PodTemplateSpec{ Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: cronjobName, Image: \"busybox\", Command: []string{\"date\"}, }, }, RestartPolicy: corev1.RestartPolicyNever, }, }, }, }, }, }, }, } for name, tc := range tests { t.Run(name, func(t *testing.T) { o := &CreateCronJobOptions{ Name: cronjobName, Image: tc.image, Command: tc.command, Schedule: tc.schedule, Restart: tc.restart, } cronjob := o.createCronJob() if !apiequality.Semantic.DeepEqual(cronjob, tc.expected) { t.Errorf(\"expected:n%#vngot:n%#v\", tc.expected, cronjob) } }) } } "} {"_id":"doc-en-kubernetes-1d929ae0547093af833c9ce3dfc46cfee0e37778ce13dae6828cd4901d0a345d","title":"","text":"uniqueRS := rs.String() if _, ok := q.list[uniqueRS]; ok { return false delete(q.list, uniqueRS) return true } delete(q.list, uniqueRS) return true return false } func (q *graceTerminateRSList) flushList(handler func(rsToDelete *listItem) (bool, error)) bool {"} {"_id":"doc-en-kubernetes-fe9698cce9eeef7358d76cf237209a49819375c2657417576f72ce29598f139f","title":"","text":"} for _, rs := range rss { if rsToDelete.RealServer.Equal(rs) { if rs.ActiveConn != 0 { // Delete RS with no connections // For UDP, ActiveConn is always 0 // For TCP, InactiveConn are connections not in ESTABLISHED state if rs.ActiveConn+rs.InactiveConn != 0 { return false, nil } klog.Infof(\"Deleting rs: %s\", rsToDelete.String())"} {"_id":"doc-en-kubernetes-79650e40a5a1f95ca3d536ffad6cd1ffbd2435b06201e9ef91112ad55ea59760","title":"","text":"Port: uint16(portNum), } klog.V(5).Infof(\"Using graceful delete to delete: %v\", delDest) klog.V(5).Infof(\"Using graceful delete to delete: %v\", uniqueRS) err = proxier.gracefuldeleteManager.GracefulDeleteRS(appliedVirtualServer, delDest) if err != nil { klog.Errorf(\"Failed to delete destination: %v, error: %v\", delDest, err)"} {"_id":"doc-en-kubernetes-167f43ed0e217e86900f9496a7ff9d6cbc6264a2d77ad79b93c9ed4f75b990e4","title":"","text":"# See the License for the specific language governing permissions and # limitations under the License. FROM ubuntu:14.04 FROM centos MAINTAINER Jan Safranek, jsafrane@redhat.com ENV DEBIAN_FRONTEND noninteractive RUN apt-get update -qq && apt-get install -y nfs-kernel-server -qq RUN yum -y install /usr/bin/ps nfs-utils && yum clean all RUN mkdir -p /exports ADD run_nfs.sh /usr/local/bin/ ADD index.html /exports/index.html"} {"_id":"doc-en-kubernetes-27a2477916b67539d3b6e4bb639596843a70f05feae1526fa1fc73e00954e575","title":"","text":"all: push TAG = 0.2 TAG = 0.3 container: docker build -t gcr.io/google_containers/volume-nfs . # Build new image and automatically tag it as latest"} {"_id":"doc-en-kubernetes-0eb72e9953d89aa9e3d881e27d845b570e50a9bebff701eb0b941efd18b5609b","title":"","text":"/usr/sbin/rpc.mountd -N 2 -N 3 -V 4 -V 4.1 /usr/sbin/exportfs -r /usr/sbin/rpc.nfsd -N 2 -N 3 -V 4 -V 4.1 2 # -G 10 to reduce grace time to 10 seconds (the lowest allowed) /usr/sbin/rpc.nfsd -G 10 -N 2 -N 3 -V 4 -V 4.1 2 echo \"NFS started\" }"} {"_id":"doc-en-kubernetes-f77421a86e524b300ec93c87eb2c2825f98529737b317a110ddd80df7ea8d879","title":"","text":"## Syntax and character set _Labels_ are key value pairs. Valid label keys have two segments: an optional prefix and name, separated by a slash (`/`). The name segment is required and must be 63 characters or less, beginning and ending with an alphanumeric character (`[a-z0-9A-Z]`) with dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between. The prefix is optional. If specified, the prefix must be a DNS subdomain: a series of DNS labels separated by dots (`.`), not longer than 253 characters in total, followed by a slash (`/`). If the prefix is omitted, the label key is presumed to be private to the user. System components which use labels must specify a prefix. The `kubernetes.io/` prefix is reserved for kubernetes core components. If the prefix is omitted, the label key is presumed to be private to the user. Automated system components (e.g. ```kube-scheduler```, ```kube-controller-manager```, ```kube-apiserver```, ```kubectl```, or other third-party automation) which add labels to end-user objects must specify a prefix. The `kubernetes.io/` prefix is reserved for kubernetes core components. Valid label values must be 63 characters or less and must be empty or begin and end with an alphanumeric character (`[a-z0-9A-Z]`) with dashes (`-`), underscores (`_`), dots (`.`), and alphanumerics between."} {"_id":"doc-en-kubernetes-4adf0956b61cb43f0fd648b3629271b037d4495c014b85dc71e181ccf6965358","title":"","text":"} else { // Unable to get the priority class for reasons other than \"not found\". klog.Warningf(\"unable to get PriorityClass %v: %v. Retrying...\", pc.Name, err) return false, err return false, nil } } }"} {"_id":"doc-en-kubernetes-3ff9e6220ffa7778f37059596971053a7ed5de9af8677d014cf9864acf4db6e2","title":"","text":"LabelSelectorParam(o.LabelSelector). FilenameParam(o.EnforceNamespace, o.FilenameOptions). ResourceTypeOrNameArgs(true, o.BuilderArgs...). SingleResourceType(). ContinueOnError(). Latest(). Do() err := r.Err() if err != nil { return err } infos, err := r.Infos() if err != nil { return err } if len(infos) != 1 { return fmt.Errorf(\"rollout status is only supported on individual resources and resource collections - %d resources were found\", len(infos)) } info := infos[0] mapping := info.ResourceMapping() statusViewer, err := o.StatusViewerFn(mapping) err := r.Err() if err != nil { return err } fieldSelector := fields.OneTermEqualSelector(\"metadata.name\", info.Name).String() lw := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { options.FieldSelector = fieldSelector return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.FieldSelector = fieldSelector return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), options) }, } // if the rollout isn't done yet, keep watching deployment status ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout) intr := interrupt.New(nil, cancel) return intr.Run(func() error { _, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, nil, func(e watch.Event) (bool, error) { switch t := e.Type; t { case watch.Added, watch.Modified: status, done, err := statusViewer.Status(e.Object.(runtime.Unstructured), o.Revision) if err != nil { return false, err } fmt.Fprintf(o.Out, \"%s\", status) // Quit waiting if the rollout is done if done { return true, nil } shouldWatch := o.Watch if !shouldWatch { return true, nil return r.Visit(func(info *resource.Info, err error) error { mapping := info.ResourceMapping() statusViewer, err := o.StatusViewerFn(mapping) if err != nil { return err } fieldSelector := fields.OneTermEqualSelector(\"metadata.name\", info.Name).String() lw := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { options.FieldSelector = fieldSelector return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.FieldSelector = fieldSelector return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(context.TODO(), options) }, } // if the rollout isn't done yet, keep watching deployment status ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout) intr := interrupt.New(nil, cancel) return intr.Run(func() error { _, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, nil, func(e watch.Event) (bool, error) { switch t := e.Type; t { case watch.Added, watch.Modified: status, done, err := statusViewer.Status(e.Object.(runtime.Unstructured), o.Revision) if err != nil { return false, err } fmt.Fprintf(o.Out, \"%s\", status) // Quit waiting if the rollout is done if done { return true, nil } shouldWatch := o.Watch if !shouldWatch { return true, nil } return false, nil case watch.Deleted: // We need to abort to avoid cases of recreation and not to silently watch the wrong (new) object return true, fmt.Errorf(\"object has been deleted\") default: return true, fmt.Errorf(\"internal error: unexpected event %#v\", e) } return false, nil case watch.Deleted: // We need to abort to avoid cases of recreation and not to silently watch the wrong (new) object return true, fmt.Errorf(\"object has been deleted\") default: return true, fmt.Errorf(\"internal error: unexpected event %#v\", e) } }) return err }) return err }) }"} {"_id":"doc-en-kubernetes-651d5ab3096141a7c55a9b4e2755c005f4b7bdcd2943d54263d8d0f917e41282","title":"","text":"# Post-condition: nginx0 & nginx1 should both have paused set to nothing, and since nginx2 is malformed, it should error kube::test::get_object_assert deployment \"{{range.items}}{{.spec.paused}}:{{end}}\" \"::\" kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\" ## Fetch rollout status for multiple resources output_message=$(! kubectl rollout status -f hack/testdata/recursive/deployment/deployment --timeout=1s 2>&1 \"${kube_flags[@]:?}\") # Post-condition: nginx1 should both exist and nginx2 should error kube::test::if_has_string \"${output_message}\" \"Waiting for deployment \"nginx1-deployment\" rollout to finish\" kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\" ## Fetch rollout status for deployments recursively output_message=$(! kubectl rollout status -f hack/testdata/recursive/deployment -R --timeout=1s 2>&1 \"${kube_flags[@]:?}\") # Post-condition: nginx0 & nginx1 should both exist, nginx2 should error kube::test::if_has_string \"${output_message}\" \"Waiting for deployment \"nginx0-deployment\" rollout to finish\" kube::test::if_has_string \"${output_message}\" \"Waiting for deployment \"nginx1-deployment\" rollout to finish\" kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\" ## Retrieve the rollout history of the deployments recursively output_message=$(! kubectl rollout history -f hack/testdata/recursive/deployment --recursive 2>&1 \"${kube_flags[@]}\") # Post-condition: nginx0 & nginx1 should both have a history, and since nginx2 is malformed, it should error"} {"_id":"doc-en-kubernetes-a43a7f7d37debe7f8b40e72f3dfb2ded67f43610635f2010504ab97f236a2ef2","title":"","text":"t.Errorf(\"Exepcted RequiresRemount to be false, got %t\", has) } } func TestGetRbdImageSize(t *testing.T) { for i, c := range []struct { Output string TargetSize int }{ { Output: `{\"name\":\"kubernetes-dynamic-pvc-18e7a4d9-050d-11e9-b905-548998f3478f\",\"size\":10737418240,\"objects\":2560,\"order\":22,\"object_size\":4194304,\"block_name_prefix\":\"rbd_data.9f4ff7238e1f29\",\"format\":2}`, TargetSize: 10240, }, { Output: `{\"name\":\"kubernetes-dynamic-pvc-070635bf-e33f-11e8-aab7-548998f3478f\",\"size\":1073741824,\"objects\":256,\"order\":22,\"object_size\":4194304,\"block_name_prefix\":\"rbd_data.670ac4238e1f29\",\"format\":2}`, TargetSize: 1024, }, } { size, err := getRbdImageSize([]byte(c.Output)) if err != nil { t.Errorf(\"Case %d: getRbdImageSize failed: %v\", i, err) continue } if size != c.TargetSize { t.Errorf(\"Case %d: unexpected size, wanted %d, got %d\", i, c.TargetSize, size) } } } "} {"_id":"doc-en-kubernetes-ecd6895d4e3dcf2b0c385f790dfb1cf9ce36d77048b917fa51a108148d7a6e27","title":"","text":"const ( imageWatcherStr = \"watcher=\" imageSizeStr = \"size \" sizeDivStr = \" MB in\" kubeLockMagic = \"kubelet_lock_magic_\" // The following three values are used for 30 seconds timeout // while waiting for RBD Watcher to expire. rbdImageWatcherInitDelay = 1 * time.Second rbdImageWatcherFactor = 1.4 rbdImageWatcherSteps = 10 rbdImageSizeUnitMiB = 1024 * 1024 ) func getDevFromImageAndPool(pool, image string) (string, bool) {"} {"_id":"doc-en-kubernetes-eedc71f977bac4fb0e0cbdcb19cab8ee1646a17713ea066d938f84c535e90552","title":"","text":"// rbdInfo runs `rbd info` command to get the current image size in MB. func (util *RBDUtil) rbdInfo(b *rbdMounter) (int, error) { var err error var output string var cmd []byte var output []byte // If we don't have admin id/secret (e.g. attaching), fallback to user id/secret. id := b.adminId"} {"_id":"doc-en-kubernetes-60f392c360e9e8a52481cca63accc4100face4a0596eea21095e12b80d40e6e3","title":"","text":"// rbd: error opening image 1234: (2) No such file or directory // klog.V(4).Infof(\"rbd: info %s using mon %s, pool %s id %s key %s\", b.Image, mon, b.Pool, id, secret) cmd, err = b.exec.Run(\"rbd\", \"info\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret) output = string(cmd) output, err = b.exec.Run(\"rbd\", \"info\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret, \"--format=json\") if err, ok := err.(*exec.Error); ok { if err.Err == exec.ErrNotFound {"} {"_id":"doc-en-kubernetes-85c4457318833f14adfd603f2cd2deefe6ad770bcc2d1e560ec06842f967ee05","title":"","text":"} if len(output) == 0 { return 0, fmt.Errorf(\"can not get image size info %s: %s\", b.Image, output) return 0, fmt.Errorf(\"can not get image size info %s: %s\", b.Image, string(output)) } // Get the size value string, just between `size ` and ` MB in`, such as `size 1024 MB in 256 objects`. sizeIndex := strings.Index(output, imageSizeStr) divIndex := strings.Index(output, sizeDivStr) if sizeIndex == -1 || divIndex == -1 || divIndex <= sizeIndex+5 { return 0, fmt.Errorf(\"can not get image size info %s: %s\", b.Image, output) } rbdSizeStr := output[sizeIndex+5 : divIndex] rbdSize, err := strconv.Atoi(rbdSizeStr) if err != nil { return 0, fmt.Errorf(\"can not convert size str: %s to int\", rbdSizeStr) } return getRbdImageSize(output) } return rbdSize, nil func getRbdImageSize(output []byte) (int, error) { info := struct { Size int64 `json:\"size\"` }{} if err := json.Unmarshal(output, &info); err != nil { return 0, fmt.Errorf(\"parse rbd info output failed: %s, %v\", string(output), err) } return int(info.Size / rbdImageSizeUnitMiB), nil } // rbdStatus runs `rbd status` command to check if there is watcher on the image."} {"_id":"doc-en-kubernetes-a2690a928bb2be0a87e8827239f28ebdc89e087b5f907883de7a269f99bbf0d4","title":"","text":"CgroupManagerOperationsKey = \"cgroup_manager_latency_microseconds\" PodWorkerStartLatencyKey = \"pod_worker_start_latency_microseconds\" PLEGRelistLatencyKey = \"pleg_relist_latency_microseconds\" PLEGDiscardEventsKey = \"pleg_discard_events\" PLEGRelistIntervalKey = \"pleg_relist_interval_microseconds\" EvictionStatsAgeKey = \"eviction_stats_age_microseconds\" VolumeStatsCapacityBytesKey = \"volume_stats_capacity_bytes\""} {"_id":"doc-en-kubernetes-1f1550a8df7436e1d2ba96e1390fce1d43abe523a9e173a0412a10528f210a60","title":"","text":"Help: \"Latency in microseconds for relisting pods in PLEG.\", }, ) PLEGDiscardEvents = prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: KubeletSubsystem, Name: PLEGDiscardEventsKey, Help: \"The number of discard events in PLEG.\", }, []string{}, ) PLEGRelistInterval = prometheus.NewSummary( prometheus.SummaryOpts{ Subsystem: KubeletSubsystem,"} {"_id":"doc-en-kubernetes-95fa2eb1f8845208cdadffe8004363b4e36a300e11b6d3183b89ebbeab25d6be","title":"","text":"prometheus.MustRegister(ContainersPerPodCount) prometheus.MustRegister(newPodAndContainerCollector(containerCache)) prometheus.MustRegister(PLEGRelistLatency) prometheus.MustRegister(PLEGDiscardEvents) prometheus.MustRegister(PLEGRelistInterval) prometheus.MustRegister(RuntimeOperations) prometheus.MustRegister(RuntimeOperationsLatency)"} {"_id":"doc-en-kubernetes-a2c136300c04fdac180dc122e9c5debc14be9a4ec7cc851105d8f23145747634","title":"","text":"if events[i].Type == ContainerChanged { continue } g.eventChannel <- events[i] select { case g.eventChannel <- events[i]: default: metrics.PLEGDiscardEvents.WithLabelValues().Inc() klog.Error(\"event channel is full, discard this relist() cycle event\") } } }"} {"_id":"doc-en-kubernetes-51a6b55dcc0d035eb70d61bc44a9810264d4972cee80e9cf0edf77d3df4ae272","title":"","text":"const ( testContainerRuntimeType = \"fooRuntime\" // largeChannelCap is a large enough capacity to hold all events in a single test. largeChannelCap = 100 ) type TestGenericPLEG struct {"} {"_id":"doc-en-kubernetes-831c05868a66c1ef6dbe53bee0877060c0e52cfd310111e522051974fc159387","title":"","text":"} func newTestGenericPLEG() *TestGenericPLEG { return newTestGenericPLEGWithChannelSize(largeChannelCap) } func newTestGenericPLEGWithChannelSize(eventChannelCap int) *TestGenericPLEG { fakeRuntime := &containertest.FakeRuntime{} clock := clock.NewFakeClock(time.Time{}) // The channel capacity should be large enough to hold all events in a"} {"_id":"doc-en-kubernetes-cab5e1a0ddc2604e2bb7ee6078ce4a0562ba026b3fcd225ea641e11e16d4474b","title":"","text":"pleg := &GenericPLEG{ relistPeriod: time.Hour, runtime: fakeRuntime, eventChannel: make(chan *PodLifecycleEvent, 100), eventChannel: make(chan *PodLifecycleEvent, eventChannelCap), podRecords: make(podRecords), clock: clock, }"} {"_id":"doc-en-kubernetes-66f6d0f9fef5c5ac7ed3d2359b3faf588044f5b28038ccc08b18b7de1a70d86e","title":"","text":"verifyEvents(t, expected, actual) } // TestEventChannelFull test when channel is full, the events will be discard. func TestEventChannelFull(t *testing.T) { testPleg := newTestGenericPLEGWithChannelSize(4) pleg, runtime := testPleg.pleg, testPleg.runtime ch := pleg.Watch() // The first relist should send a PodSync event to each pod. runtime.AllPodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: \"1234\", Containers: []*kubecontainer.Container{ createTestContainer(\"c1\", kubecontainer.ContainerStateExited), createTestContainer(\"c2\", kubecontainer.ContainerStateRunning), createTestContainer(\"c3\", kubecontainer.ContainerStateUnknown), }, }}, {Pod: &kubecontainer.Pod{ ID: \"4567\", Containers: []*kubecontainer.Container{ createTestContainer(\"c1\", kubecontainer.ContainerStateExited), }, }}, } pleg.relist() // Report every running/exited container if we see them for the first time. expected := []*PodLifecycleEvent{ {ID: \"1234\", Type: ContainerStarted, Data: \"c2\"}, {ID: \"4567\", Type: ContainerDied, Data: \"c1\"}, {ID: \"1234\", Type: ContainerDied, Data: \"c1\"}, } actual := getEventsFromChannel(ch) verifyEvents(t, expected, actual) runtime.AllPodList = []*containertest.FakePod{ {Pod: &kubecontainer.Pod{ ID: \"1234\", Containers: []*kubecontainer.Container{ createTestContainer(\"c2\", kubecontainer.ContainerStateExited), createTestContainer(\"c3\", kubecontainer.ContainerStateRunning), }, }}, {Pod: &kubecontainer.Pod{ ID: \"4567\", Containers: []*kubecontainer.Container{ createTestContainer(\"c4\", kubecontainer.ContainerStateRunning), }, }}, } pleg.relist() // event channel is full, discard events expected = []*PodLifecycleEvent{ {ID: \"1234\", Type: ContainerRemoved, Data: \"c1\"}, {ID: \"1234\", Type: ContainerDied, Data: \"c2\"}, {ID: \"1234\", Type: ContainerStarted, Data: \"c3\"}, {ID: \"4567\", Type: ContainerRemoved, Data: \"c1\"}, } actual = getEventsFromChannel(ch) verifyEvents(t, expected, actual) } func TestDetectingContainerDeaths(t *testing.T) { // Vary the number of relists after the container started and before the // container died to account for the changes in pleg's internal states."} {"_id":"doc-en-kubernetes-1a6a6ef0244047d7791f997b9440a84ae4c4a2e2c095a050c80f8f8a706a62b9","title":"","text":"\"path\" \"sort\" \"strings\" \"sync\" \"time\" cadvisorfs \"github.com/google/cadvisor/fs\""} {"_id":"doc-en-kubernetes-1fe2b99bac3c912b7dc5666c2d35a56247be20918a90eb7fb6f9bce0e2baf217","title":"","text":"kubetypes \"k8s.io/kubernetes/pkg/kubelet/types\" ) var ( // defaultCachePeriod is the default cache period for each cpuUsage. defaultCachePeriod = 10 * time.Minute ) // criStatsProvider implements the containerStatsProvider interface by getting // the container stats from CRI. type criStatsProvider struct {"} {"_id":"doc-en-kubernetes-9d2c5e4347f096554735b5f3ddb0691ca355599d61b9a74f1bb9cfa106972f1d","title":"","text":"imageService internalapi.ImageManagerService // logMetrics provides the metrics for container logs logMetricsService LogMetricsService // cpuUsageCache caches the cpu usage for containers. cpuUsageCache map[string]*runtimeapi.CpuUsage mutex sync.Mutex } // newCRIStatsProvider returns a containerStatsProvider implementation that"} {"_id":"doc-en-kubernetes-7308c53bf4ab480a054214a3ac2c6aca4016e15d179e2b97c9980ed222075aae","title":"","text":"runtimeService: runtimeService, imageService: imageService, logMetricsService: logMetricsService, cpuUsageCache: make(map[string]*runtimeapi.CpuUsage), } }"} {"_id":"doc-en-kubernetes-8bf87a078b4f44bb5c1ec7888ffa213663fb11414cedafd96e2f1b4fea1245a3","title":"","text":"} ps.Containers = append(ps.Containers, *cs) } // cleanup outdated caches. p.cleanupOutdatedCaches() result := make([]statsapi.PodStats, 0, len(sandboxIDToPodStats)) for _, s := range sandboxIDToPodStats {"} {"_id":"doc-en-kubernetes-7e5b6c131c9e9a7020a556844a6f2d76afcc334b84d438b807c2e760cb386290","title":"","text":"if stats.Cpu.UsageCoreNanoSeconds != nil { result.CPU.UsageCoreNanoSeconds = &stats.Cpu.UsageCoreNanoSeconds.Value } usageNanoCores := p.getContainerUsageNanoCores(stats) if usageNanoCores != nil { result.CPU.UsageNanoCores = usageNanoCores } } if stats.Memory != nil { result.Memory.Time = metav1.NewTime(time.Unix(0, stats.Memory.Timestamp))"} {"_id":"doc-en-kubernetes-32d5253b9df2df62e2ded9947072fd486db262674ef4f380d089937c603309db","title":"","text":"return result } // getContainerUsageNanoCores gets usageNanoCores based on cached usageCoreNanoSeconds. func (p *criStatsProvider) getContainerUsageNanoCores(stats *runtimeapi.ContainerStats) *uint64 { if stats == nil || stats.Cpu == nil || stats.Cpu.UsageCoreNanoSeconds == nil { return nil } p.mutex.Lock() defer func() { // Update cache with new value. p.cpuUsageCache[stats.Attributes.Id] = stats.Cpu p.mutex.Unlock() }() cached, ok := p.cpuUsageCache[stats.Attributes.Id] if !ok || cached.UsageCoreNanoSeconds == nil { return nil } nanoSeconds := stats.Cpu.Timestamp - cached.Timestamp usageNanoCores := (stats.Cpu.UsageCoreNanoSeconds.Value - cached.UsageCoreNanoSeconds.Value) * uint64(time.Second/time.Nanosecond) / uint64(nanoSeconds) return &usageNanoCores } func (p *criStatsProvider) cleanupOutdatedCaches() { p.mutex.Lock() defer p.mutex.Unlock() for k, v := range p.cpuUsageCache { if v == nil { delete(p.cpuUsageCache, k) } if time.Since(time.Unix(0, v.Timestamp)) > defaultCachePeriod { delete(p.cpuUsageCache, k) } } } // removeTerminatedContainer returns the specified container but with // the stats of the terminated containers removed. func removeTerminatedContainer(containers []*runtimeapi.Container) []*runtimeapi.Container {"} {"_id":"doc-en-kubernetes-e36bdefba1fdec998a437bb110f7522691b21a9fd04daa31b1ea78db06b36eed","title":"","text":"m.InodesUsed = resource.NewQuantity(int64(seed+offsetInodeUsage), resource.BinarySI) return m } func TestGetContainerUsageNanoCores(t *testing.T) { var value0 uint64 var value1 uint64 = 10000000000 tests := []struct { desc string cpuUsageCache map[string]*runtimeapi.CpuUsage stats *runtimeapi.ContainerStats expected *uint64 }{ { desc: \"should return nil if stats is nil\", cpuUsageCache: map[string]*runtimeapi.CpuUsage{}, }, { desc: \"should return nil if cpu stats is nil\", cpuUsageCache: map[string]*runtimeapi.CpuUsage{}, stats: &runtimeapi.ContainerStats{ Attributes: &runtimeapi.ContainerAttributes{ Id: \"1\", }, Cpu: nil, }, }, { desc: \"should return nil if usageCoreNanoSeconds is nil\", cpuUsageCache: map[string]*runtimeapi.CpuUsage{}, stats: &runtimeapi.ContainerStats{ Attributes: &runtimeapi.ContainerAttributes{ Id: \"1\", }, Cpu: &runtimeapi.CpuUsage{ Timestamp: 1, UsageCoreNanoSeconds: nil, }, }, }, { desc: \"should return nil if cpu stats is not cached yet\", cpuUsageCache: map[string]*runtimeapi.CpuUsage{}, stats: &runtimeapi.ContainerStats{ Attributes: &runtimeapi.ContainerAttributes{ Id: \"1\", }, Cpu: &runtimeapi.CpuUsage{ Timestamp: 1, UsageCoreNanoSeconds: &runtimeapi.UInt64Value{ Value: 10000000000, }, }, }, }, { desc: \"should return zero value if cached cpu stats is equal to current value\", stats: &runtimeapi.ContainerStats{ Attributes: &runtimeapi.ContainerAttributes{ Id: \"1\", }, Cpu: &runtimeapi.CpuUsage{ Timestamp: 1, UsageCoreNanoSeconds: &runtimeapi.UInt64Value{ Value: 10000000000, }, }, }, cpuUsageCache: map[string]*runtimeapi.CpuUsage{ \"1\": { Timestamp: 0, UsageCoreNanoSeconds: &runtimeapi.UInt64Value{ Value: 10000000000, }, }, }, expected: &value0, }, { desc: \"should return correct value if cached cpu stats is not equal to current value\", stats: &runtimeapi.ContainerStats{ Attributes: &runtimeapi.ContainerAttributes{ Id: \"1\", }, Cpu: &runtimeapi.CpuUsage{ Timestamp: int64(time.Second / time.Nanosecond), UsageCoreNanoSeconds: &runtimeapi.UInt64Value{ Value: 20000000000, }, }, }, cpuUsageCache: map[string]*runtimeapi.CpuUsage{ \"1\": { Timestamp: 0, UsageCoreNanoSeconds: &runtimeapi.UInt64Value{ Value: 10000000000, }, }, }, expected: &value1, }, } for _, test := range tests { provider := &criStatsProvider{cpuUsageCache: test.cpuUsageCache} real := provider.getContainerUsageNanoCores(test.stats) assert.Equal(t, test.expected, real, test.desc) } } "} {"_id":"doc-en-kubernetes-cf78cb2c7d1390c8280b4d875398280fc213ff80595189b2bfb4f0dac4f902f1","title":"","text":"importpath = \"k8s.io/kubernetes/pkg/windows/service\", deps = select({ \"@io_bazel_rules_go//go/platform:windows\": [ \"//staging/src/k8s.io/apiserver/pkg/server:go_default_library\", \"//vendor/golang.org/x/sys/windows:go_default_library\", \"//vendor/golang.org/x/sys/windows/svc:go_default_library\", \"//vendor/k8s.io/klog:go_default_library\","} {"_id":"doc-en-kubernetes-854d81e5c06c0d92becb4e31f38c1a8ebcae133e6bff61a5c36923f71dcb9e34","title":"","text":"import ( \"os\" \"time\" \"k8s.io/apiserver/pkg/server\" \"k8s.io/klog\" \"golang.org/x/sys/windows\""} {"_id":"doc-en-kubernetes-02ad932bc209ca97ac14acb13374570f721241fcac244c70d7c654c25bd0aa59","title":"","text":"case svc.Interrogate: s <- c.CurrentStatus case svc.Stop, svc.Shutdown: s <- svc.Status{State: svc.Stopped} // TODO: Stop the kubelet gracefully instead of killing the process os.Exit(0) klog.Infof(\"Service stopping\") // We need to translate this request into a signal that can be handled by the the signal handler // handling shutdowns normally (currently apiserver/pkg/server/signal.go). // If we do not do this, our main threads won't be notified of the upcoming shutdown. // Since Windows services do not use any console, we cannot simply generate a CTRL_BREAK_EVENT // but need a dedicated notification mechanism. graceful := server.RequestShutdown() // Free up the control handler and let us terminate as gracefully as possible. // If that takes too long, the service controller will kill the remaining threads. // As per https://docs.microsoft.com/en-us/windows/desktop/services/service-control-handler-function s <- svc.Status{State: svc.StopPending} // If we cannot exit gracefully, we really only can exit our process, so atleast the // service manager will think that we gracefully exited. At the time of writing this comment this is // needed for applications that do not use signals (e.g. kube-proxy) if !graceful { go func() { // Ensure the SCM was notified (The operation above (send to s) was received and communicated to the // service control manager - so it doesn't look like the service crashes) time.Sleep(1 * time.Second) os.Exit(0) }() } break Loop } } }"} {"_id":"doc-en-kubernetes-9d7ce304546d21aa3e41da9e91acc99acbbb26051fa799f24c261fab8cd4a232","title":"","text":") var onlyOneSignalHandler = make(chan struct{}) var shutdownHandler chan os.Signal // SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned // which is closed on one of these signals. If a second signal is caught, the program"} {"_id":"doc-en-kubernetes-7e4361ff9735ce1508971a6941e2d098364e764a97a0ca06a932a21d054094f9","title":"","text":"func SetupSignalHandler() <-chan struct{} { close(onlyOneSignalHandler) // panics when called twice shutdownHandler = make(chan os.Signal, 2) stop := make(chan struct{}) c := make(chan os.Signal, 2) signal.Notify(c, shutdownSignals...) signal.Notify(shutdownHandler, shutdownSignals...) go func() { <-c <-shutdownHandler close(stop) <-c <-shutdownHandler os.Exit(1) // second signal. Exit directly. }() return stop } // RequestShutdown emulates a received event that is considered as shutdown signal (SIGTERM/SIGINT) // This returns whether a handler was notified func RequestShutdown() bool { if shutdownHandler != nil { select { case shutdownHandler <- shutdownSignals[0]: return true default: } } return false } "} {"_id":"doc-en-kubernetes-2714019aabb5ab40f899cc9d5849ce63657a38f85ba9ac7c4f2814928975ee81","title":"","text":"// BlockStorageOpts is used to talk to Cinder service type BlockStorageOpts struct { BSVersion string `gcfg:\"bs-version\"` // overrides autodetection. v1 or v2. Defaults to auto TrustDevicePath bool `gcfg:\"trust-device-path\"` // See Issue #33128 IgnoreVolumeAZ bool `gcfg:\"ignore-volume-az\"` BSVersion string `gcfg:\"bs-version\"` // overrides autodetection. v1 or v2. Defaults to auto TrustDevicePath bool `gcfg:\"trust-device-path\"` // See Issue #33128 IgnoreVolumeAZ bool `gcfg:\"ignore-volume-az\"` NodeVolumeAttachLimit int `gcfg:\"node-volume-attach-limit\"` // override volume attach limit for Cinder. Default is : 256 } // RouterOpts is used for Neutron routes"} {"_id":"doc-en-kubernetes-a84c12e9b95db0361522ac7e7e575dfbe1ff63c82bfa3d2090a8c705d0ad7269","title":"","text":"return &os, nil } // NewFakeOpenStackCloud creates and returns an instance of Openstack cloudprovider. // Mainly for use in tests that require instantiating Openstack without having // to go through cloudprovider interface. func NewFakeOpenStackCloud(cfg Config) (*OpenStack, error) { provider, err := openstack.NewClient(cfg.Global.AuthURL) if err != nil { return nil, err } emptyDuration := MyDuration{} if cfg.Metadata.RequestTimeout == emptyDuration { cfg.Metadata.RequestTimeout.Duration = time.Duration(defaultTimeOut) } provider.HTTPClient.Timeout = cfg.Metadata.RequestTimeout.Duration os := OpenStack{ provider: provider, region: cfg.Global.Region, lbOpts: cfg.LoadBalancer, bsOpts: cfg.BlockStorage, routeOpts: cfg.Route, metadataOpts: cfg.Metadata, } return &os, nil } // Initialize passes a Kubernetes clientBuilder interface to the cloud provider func (os *OpenStack) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) { }"} {"_id":"doc-en-kubernetes-0b53d8782d682f697abd03a229e650f616050ab162c9f2150518ae706dacc8bf","title":"","text":"return os.bsOpts.TrustDevicePath } // NodeVolumeAttachLimit specifies number of cinder volumes that can be attached to this node. func (os *OpenStack) NodeVolumeAttachLimit() int { return os.bsOpts.NodeVolumeAttachLimit } // GetLabelsForVolume implements PVLabeler.GetLabelsForVolume func (os *OpenStack) GetLabelsForVolume(ctx context.Context, pv *v1.PersistentVolume) (map[string]string, error) { // Ignore if not Cinder."} {"_id":"doc-en-kubernetes-340603db218f107313c9642c6487cac423e7ba3a5dea8b3499cfb69f2574511a","title":"","text":"], embed = [\":go_default_library\"], deps = [ \"//pkg/cloudprovider/providers/openstack:go_default_library\", \"//pkg/util/mount:go_default_library\", \"//pkg/volume:go_default_library\", \"//pkg/volume/testing:go_default_library\", \"//pkg/volume/util:go_default_library\", \"//staging/src/k8s.io/api/core/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/resource:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\","} {"_id":"doc-en-kubernetes-88018fa98a046c21aa1c2c67fb711a2a54c63e450468e880a31faec0d4e0ba32","title":"","text":"if cloud.ProviderName() != openstack.ProviderName { return nil, fmt.Errorf(\"Expected Openstack cloud, found %s\", cloud.ProviderName()) } openstackCloud, ok := cloud.(*openstack.OpenStack) if ok && openstackCloud.NodeVolumeAttachLimit() > 0 { volumeLimits[util.CinderVolumeLimitKey] = int64(openstackCloud.NodeVolumeAttachLimit()) } return volumeLimits, nil }"} {"_id":"doc-en-kubernetes-13bb82785f49da0a06d334d6c41f808257e3043682805c835f4cb255b52282ae","title":"","text":"\"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/types\" utiltesting \"k8s.io/client-go/util/testing\" \"k8s.io/kubernetes/pkg/cloudprovider/providers/openstack\" \"k8s.io/kubernetes/pkg/util/mount\" \"k8s.io/kubernetes/pkg/volume\" volumetest \"k8s.io/kubernetes/pkg/volume/testing\" \"k8s.io/kubernetes/pkg/volume/util\" ) func TestCanSupport(t *testing.T) {"} {"_id":"doc-en-kubernetes-5b7434482a9967f79b1e9853964ed389e6c2062fd9e925b3df8b0a388cea0d2f","title":"","text":"t.Errorf(\"Deleter() failed: %v\", err) } } func TestGetVolumeLimit(t *testing.T) { tmpDir, err := utiltesting.MkTmpdir(\"cinderTest\") if err != nil { t.Fatalf(\"can't make a temp dir: %v\", err) } cloud, err := getOpenstackCloudProvider() if err != nil { t.Fatalf(\"can not instantiate openstack cloudprovider : %v\", err) } defer os.RemoveAll(tmpDir) plugMgr := volume.VolumePluginMgr{} volumeHost := volumetest.NewFakeVolumeHostWithCloudProvider(tmpDir, nil, nil, cloud) plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumeHost) plug, err := plugMgr.FindPluginByName(\"kubernetes.io/cinder\") if err != nil { t.Fatalf(\"Can't find the plugin by name\") } attachablePlugin, ok := plug.(volume.VolumePluginWithAttachLimits) if !ok { t.Fatalf(\"plugin %s is not of attachable type\", plug.GetPluginName()) } limits, err := attachablePlugin.GetVolumeLimits() if err != nil { t.Errorf(\"error fetching limits : %v\", err) } if len(limits) == 0 { t.Fatalf(\"expecting limit from openstack got none\") } limit, _ := limits[util.CinderVolumeLimitKey] if limit != 10 { t.Fatalf(\"expected volume limit to be 10 got %d\", limit) } } func getOpenstackCloudProvider() (*openstack.OpenStack, error) { cfg := getOpenstackConfig() return openstack.NewFakeOpenStackCloud(cfg) } func getOpenstackConfig() openstack.Config { cfg := openstack.Config{ Global: struct { AuthURL string `gcfg:\"auth-url\"` Username string UserID string `gcfg:\"user-id\"` Password string TenantID string `gcfg:\"tenant-id\"` TenantName string `gcfg:\"tenant-name\"` TrustID string `gcfg:\"trust-id\"` DomainID string `gcfg:\"domain-id\"` DomainName string `gcfg:\"domain-name\"` Region string CAFile string `gcfg:\"ca-file\"` }{ Username: \"user\", Password: \"pass\", TenantID: \"foobar\", DomainID: \"2a73b8f597c04551a0fdc8e95544be8a\", DomainName: \"local\", AuthURL: \"http://auth.url\", UserID: \"user\", }, BlockStorage: openstack.BlockStorageOpts{ NodeVolumeAttachLimit: 10, }, } return cfg } "} {"_id":"doc-en-kubernetes-4b267b5455a90cc58fb49e581e0edf9fb02bca0a51fb49725c78aadc762732ef","title":"","text":"if err != nil { return nil, fmt.Errorf(\"Failed to create tls config: %v\", err) } if tlsConfig != nil { if url.Scheme == \"https\" { url.Scheme = \"wss\" if !strings.Contains(url.Host, \":\") { url.Host += \":443\" } } else { url.Scheme = \"ws\" if !strings.Contains(url.Host, \":\") { url.Host += \":80\" } } headers, err := headersForConfig(config, url) if err != nil {"} {"_id":"doc-en-kubernetes-d780b4f278d036fa42483c65d17c1a8b47a6fd12f99e56091f0b3fa6ea026495","title":"","text":"p.podBackoff.ClearPodBackoff(nsNameForPod(pod)) } // isPodBackingOff returns whether a pod is currently undergoing backoff in the podBackoff structure // isPodBackingOff returns true if a pod is still waiting for its backoff timer. // If this returns true, the pod should not be re-tried. func (p *PriorityQueue) isPodBackingOff(pod *v1.Pod) bool { boTime, exists := p.podBackoff.GetBackoffTime(nsNameForPod(pod)) if !exists {"} {"_id":"doc-en-kubernetes-7ff85e66c2078570c6c7ebc0f12bb2f641e060566d80c1a6a88dc66f028e8fe8","title":"","text":"return p.schedulingCycle } // AddUnschedulableIfNotPresent does nothing if the pod is present in any // queue. If pod is unschedulable, it adds pod to unschedulable queue if // p.moveRequestCycle > podSchedulingCycle or to backoff queue if p.moveRequestCycle // <= podSchedulingCycle but pod is subject to backoff. In other cases, it adds pod to // active queue. // AddUnschedulableIfNotPresent inserts a pod that cannot be scheduled into // the queue, unless it is already in the queue. Normally, PriorityQueue puts // unschedulable pods in `unschedulableQ`. But if there has been a recent move // request, then the pod is put in `podBackoffQ`. func (p *PriorityQueue) AddUnschedulableIfNotPresent(pod *v1.Pod, podSchedulingCycle int64) error { p.lock.Lock() defer p.lock.Unlock()"} {"_id":"doc-en-kubernetes-36eb2304c69650ebeea57274fcec54b4392484394f16266099fe932637585371","title":"","text":"if _, exists, _ := p.podBackoffQ.Get(pInfo); exists { return fmt.Errorf(\"pod is already present in the backoffQ\") } if podSchedulingCycle > p.moveRequestCycle && isPodUnschedulable(pod) { p.backoffPod(pod) p.unschedulableQ.addOrUpdate(pInfo) p.nominatedPods.add(pod, \"\") return nil } // If a move request has been received and the pod is subject to backoff, move it to the BackoffQ. if p.isPodBackingOff(pod) && isPodUnschedulable(pod) { err := p.podBackoffQ.Add(pInfo) if err != nil { klog.Errorf(\"Error adding pod %v to the backoff queue: %v\", pod.Name, err) } else { p.nominatedPods.add(pod, \"\") // Every unschedulable pod is subject to backoff timers. p.backoffPod(pod) // If a move request has been received, move it to the BackoffQ, otherwise move // it to unschedulableQ. if p.moveRequestCycle >= podSchedulingCycle { if err := p.podBackoffQ.Add(pInfo); err != nil { // TODO: Delete this klog call and log returned errors at the call site. err = fmt.Errorf(\"error adding pod %v to the backoff queue: %v\", pod.Name, err) klog.Error(err) return err } return err } else { p.unschedulableQ.addOrUpdate(pInfo) } err := p.activeQ.Add(pInfo) if err == nil { p.nominatedPods.add(pod, \"\") p.cond.Broadcast() } return err p.nominatedPods.add(pod, \"\") return nil } // flushBackoffQCompleted Moves all pods from backoffQ which have completed backoff in to activeQ"} {"_id":"doc-en-kubernetes-885b9deb577d2e01efca3961b474dcf494163edbc152a75e4ab0ef52a0d252b6","title":"","text":"q := NewPriorityQueue(nil) q.Add(&highPriNominatedPod) q.AddUnschedulableIfNotPresent(&highPriNominatedPod, q.SchedulingCycle()) // Must not add anything. q.AddUnschedulableIfNotPresent(&medPriorityPod, q.SchedulingCycle()) // This should go to activeQ. q.AddUnschedulableIfNotPresent(&unschedulablePod, q.SchedulingCycle()) expectedNominatedPods := &nominatedPodMap{ nominatedPodToNode: map[types.UID]string{ medPriorityPod.UID: \"node1\", unschedulablePod.UID: \"node1\", highPriNominatedPod.UID: \"node1\", }, nominatedPods: map[string][]*v1.Pod{ \"node1\": {&highPriNominatedPod, &medPriorityPod, &unschedulablePod}, \"node1\": {&highPriNominatedPod, &unschedulablePod}, }, } if !reflect.DeepEqual(q.nominatedPods, expectedNominatedPods) {"} {"_id":"doc-en-kubernetes-2e9613d802bd0d61f6f44cc683b7d311e2e0b64a147e84b36b4c9bc757955214","title":"","text":"if p, err := q.Pop(); err != nil || p != &highPriNominatedPod { t.Errorf(\"Expected: %v after Pop, but got: %v\", highPriNominatedPod.Name, p.Name) } if p, err := q.Pop(); err != nil || p != &medPriorityPod { t.Errorf(\"Expected: %v after Pop, but got: %v\", medPriorityPod.Name, p.Name) } if len(q.nominatedPods.nominatedPods) != 1 { t.Errorf(\"Expected nomindatePods to have one element: %v\", q.nominatedPods) }"} {"_id":"doc-en-kubernetes-1f1edf2152d3d1f496652b4ad31fa9dc726a718eb70826d615d3d7be2df5f5f9","title":"","text":"} } // TestPriorityQueue_AddUnschedulableIfNotPresent_Async tests scenario when // TestPriorityQueue_AddUnschedulableIfNotPresent_Backoff tests scenario when // AddUnschedulableIfNotPresent is called asynchronously pods in and before // current scheduling cycle will be put back to activeQueue if we were trying // to schedule them when we received move request. func TestPriorityQueue_AddUnschedulableIfNotPresent_Async(t *testing.T) { func TestPriorityQueue_AddUnschedulableIfNotPresent_Backoff(t *testing.T) { q := NewPriorityQueue(nil) totalNum := 10 expectedPods := make([]v1.Pod, 0, totalNum)"} {"_id":"doc-en-kubernetes-5d7d569adf8d26a33aa85c6b4a6ccea43e8b08d2eebad43bb0db83be14d3575f","title":"","text":"// move all pods to active queue when we were trying to schedule them q.MoveAllToActiveQueue() moveReqChan := make(chan struct{}) var wg sync.WaitGroup wg.Add(totalNum - 1) // mark pods[1] ~ pods[totalNum-1] as unschedulable, fire goroutines to add them back later oldCycle := q.SchedulingCycle() firstPod, _ := q.Pop() if !reflect.DeepEqual(&expectedPods[0], firstPod) { t.Errorf(\"Unexpected pod. Expected: %v, got: %v\", &expectedPods[0], firstPod) } // mark pods[1] ~ pods[totalNum-1] as unschedulable and add them back for i := 1; i < totalNum; i++ { unschedulablePod := expectedPods[i].DeepCopy() unschedulablePod.Status = v1.PodStatus{"} {"_id":"doc-en-kubernetes-4cc072c7cdc85c0b3f6fb106cdbe87c641e9a15470a19a69d4efa6bf962fa6ed","title":"","text":"}, }, } cycle := q.SchedulingCycle() go func() { <-moveReqChan q.AddUnschedulableIfNotPresent(unschedulablePod, cycle) wg.Done() }() } firstPod, _ := q.Pop() if !reflect.DeepEqual(&expectedPods[0], firstPod) { t.Errorf(\"Unexpected pod. Expected: %v, got: %v\", &expectedPods[0], firstPod) q.AddUnschedulableIfNotPresent(unschedulablePod, oldCycle) } // close moveReqChan here to make sure q.AddUnschedulableIfNotPresent is called after another pod is popped close(moveReqChan) wg.Wait() // all other pods should be in active queue again // Since there was a move request at the same cycle as \"oldCycle\", these pods // should be in the backoff queue. for i := 1; i < totalNum; i++ { if _, exists, _ := q.activeQ.Get(newPodInfoNoTimestamp(&expectedPods[i])); !exists { t.Errorf(\"Expected %v to be added to activeQ.\", expectedPods[i].Name) if _, exists, _ := q.podBackoffQ.Get(newPodInfoNoTimestamp(&expectedPods[i])); !exists { t.Errorf(\"Expected %v to be added to podBackoffQ.\", expectedPods[i].Name) } } }"} {"_id":"doc-en-kubernetes-2561b10b3033e4078b1253eba87501ea66df66f81b109bbbc5fb037eb237987f","title":"","text":"imageutils.GetE2EImage(imageutils.Nonewprivs), imageutils.GetPauseImageName(), framework.GetGPUDevicePluginImage(), \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-is-amd64:1.0\", \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-ep-amd64:1.0\", \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-is:1.0\", \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-ep:1.0\", \"gcr.io/kubernetes-e2e-test-images/node-perf/tf-wide-deep-amd64:1.0\", )"} {"_id":"doc-en-kubernetes-9ec5621c1fd4d6b8bf081203647b320b778827aed6c4b6a6bce0a1038d23dd03","title":"","text":"// Slow by design. var _ = SIGDescribe(\"Node Performance Testing [Serial] [Slow]\", func() { f := framework.NewDefaultFramework(\"node-performance-testing\") var ( wl workloads.NodePerfWorkload oldCfg *kubeletconfig.KubeletConfiguration newCfg *kubeletconfig.KubeletConfiguration pod *corev1.Pod ) JustBeforeEach(func() { err := wl.PreTestExec() framework.ExpectNoError(err) oldCfg, err = getCurrentKubeletConfig() framework.ExpectNoError(err) newCfg, err = wl.KubeletConfig(oldCfg) framework.ExpectNoError(err) setKubeletConfig(f, newCfg) }) Context(\"Run node performance testing with pre-defined workloads\", func() { It(\"run each pre-defined workload\", func() { By(\"running the workloads\") for _, workload := range workloads.NodePerfWorkloads { By(\"running the pre test exec from the workload\") err := workload.PreTestExec() framework.ExpectNoError(err) By(\"restarting kubelet with required configuration\") // Get the Kubelet config required for this workload. oldCfg, err := getCurrentKubeletConfig() framework.ExpectNoError(err) newCfg, err := workload.KubeletConfig(oldCfg) framework.ExpectNoError(err) // Set the Kubelet config required for this workload. setKubeletConfig(f, newCfg) By(\"running the workload and waiting for success\") // Make the pod for the workload. pod := makeNodePerfPod(workload) // Create the pod. pod = f.PodClient().CreateSync(pod) // Wait for pod success. f.PodClient().WaitForSuccess(pod.Name, workload.Timeout()) podLogs, err := framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, pod.Spec.Containers[0].Name) framework.ExpectNoError(err) perf, err := workload.ExtractPerformanceFromLogs(podLogs) framework.ExpectNoError(err) framework.Logf(\"Time to complete workload %s: %v\", workload.Name(), perf) // Delete the pod. gp := int64(0) delOpts := metav1.DeleteOptions{ GracePeriodSeconds: &gp, } f.PodClient().DeleteSync(pod.Name, &delOpts, framework.DefaultPodDeletionTimeout) cleanup := func() { gp := int64(0) delOpts := metav1.DeleteOptions{ GracePeriodSeconds: &gp, } f.PodClient().DeleteSync(pod.Name, &delOpts, framework.DefaultPodDeletionTimeout) By(\"running the post test exec from the workload\") err := wl.PostTestExec() framework.ExpectNoError(err) setKubeletConfig(f, oldCfg) } By(\"running the post test exec from the workload\") err = workload.PostTestExec() framework.ExpectNoError(err) runWorkload := func() { By(\"running the workload and waiting for success\") // Make the pod for the workload. pod = makeNodePerfPod(wl) // Create the pod. pod = f.PodClient().CreateSync(pod) // Wait for pod success. f.PodClient().WaitForSuccess(pod.Name, wl.Timeout()) podLogs, err := framework.GetPodLogs(f.ClientSet, f.Namespace.Name, pod.Name, pod.Spec.Containers[0].Name) framework.ExpectNoError(err) perf, err := wl.ExtractPerformanceFromLogs(podLogs) framework.ExpectNoError(err) framework.Logf(\"Time to complete workload %s: %v\", wl.Name(), perf) } // Set the Kubelet config back to the old one. setKubeletConfig(f, oldCfg) } Context(\"Run node performance testing with pre-defined workloads\", func() { BeforeEach(func() { wl = workloads.NodePerfWorkloads[0] }) It(\"NAS parallel benchmark (NPB) suite - Integer Sort (IS) workload\", func() { defer cleanup() runWorkload() }) }) Context(\"Run node performance testing with pre-defined workloads\", func() { BeforeEach(func() { wl = workloads.NodePerfWorkloads[1] }) It(\"NAS parallel benchmark (NPB) suite - Embarrassingly Parallel (EP) workload\", func() { defer cleanup() runWorkload() }) }) Context(\"Run node performance testing with pre-defined workloads\", func() { BeforeEach(func() { wl = workloads.NodePerfWorkloads[2] }) It(\"TensorFlow workload\", func() { defer cleanup() runWorkload() }) }) })"} {"_id":"doc-en-kubernetes-aa4fff5c7d33f9d20a143a74ab5afb8d6534dd3faa1eb7a94f4644a541547c7d","title":"","text":"var containers []corev1.Container ctn := corev1.Container{ Name: fmt.Sprintf(\"%s-ctn\", w.Name()), Image: \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-ep-amd64:1.0\", Image: \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-ep:1.0\", Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceName(corev1.ResourceCPU): resource.MustParse(\"15000m\"),"} {"_id":"doc-en-kubernetes-4e7f13008425815b29e491c171ac9c5e8bfeb509b5a52af54039383547ebd18e","title":"","text":"var containers []corev1.Container ctn := corev1.Container{ Name: fmt.Sprintf(\"%s-ctn\", w.Name()), Image: \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-is-amd64:1.0\", Image: \"gcr.io/kubernetes-e2e-test-images/node-perf/npb-is:1.0\", Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceName(corev1.ResourceCPU): resource.MustParse(\"16000m\"),"} {"_id":"doc-en-kubernetes-f9451656df374f4208f5f62256068f1ddf7abb757ef138b92e91acadd8741b2c","title":"","text":"\"density.go\", \"framework.go\", \"hybrid_network.go\", \"memory_limits.go\", \"networking.go\", \"volumes.go\", ], importpath = \"k8s.io/kubernetes/test/e2e/windows\", visibility = [\"//visibility:public\"], deps = [ \"//pkg/kubelet/apis/config:go_default_library\", \"//staging/src/k8s.io/api/core/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/resource:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/labels:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/uuid:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/watch:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes/scheme:go_default_library\", \"//staging/src/k8s.io/client-go/tools/cache:go_default_library\", \"//staging/src/k8s.io/kubelet/config/v1beta1:go_default_library\", \"//test/e2e/framework:go_default_library\", \"//test/utils/image:go_default_library\", \"//vendor/github.com/onsi/ginkgo:go_default_library\","} {"_id":"doc-en-kubernetes-a550cb9af54d53def6db28b2a64ba00951de191cb10a49748b2c37186e7c83cb","title":"","text":"\"sync\" \"time\" \"k8s.io/api/core/v1\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime\""} {"_id":"doc-en-kubernetes-a43d75aae30b6c57ff52851da33e7250076706c497fdd370258d8de151bf94c0","title":"","text":"desc := fmt.Sprintf(\"latency/resource should be within limit when create %d pods with %v interval\", itArg.podsNr, itArg.interval) It(desc, func() { itArg.createMethod = \"batch\" runDensityBatchTest(f, itArg) }) } })"} {"_id":"doc-en-kubernetes-c33a46da359b8898ca025e66b39ff673ea76b0aeacae4d96a319fc9ddbd835ad","title":"","text":") // create test pod data structure pods := newTestPods(testArg.podsNr, false, imageutils.GetPauseImageName(), podType) pods := newDensityTestPods(testArg.podsNr, false, imageutils.GetPauseImageName(), podType) // the controller watches the change of pod status controller := newInformerWatchPod(f, mutex, watchTimes, podType)"} {"_id":"doc-en-kubernetes-f7554c5504280cee31f9e06e22b0cc44b25d9c2905f6051022aeaf7fea4c677b","title":"","text":"return controller } // newTestPods creates a list of pods (specification) for test. func newTestPods(numPods int, volume bool, imageName, podType string) []*v1.Pod { // newDensityTestPods creates a list of pods (specification) for test. func newDensityTestPods(numPods int, volume bool, imageName, podType string) []*v1.Pod { var pods []*v1.Pod for i := 0; i < numPods; i++ { podName := \"test-\" + string(uuid.NewUUID()) labels := map[string]string{ \"type\": podType, \"name\": podName, pod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, Labels: map[string]string{ \"type\": podType, \"name\": podName, }, }, Spec: v1.PodSpec{ // Restart policy is always (default). Containers: []v1.Container{ { Image: imageName, Name: podName, }, }, NodeSelector: map[string]string{ \"beta.kubernetes.io/os\": \"windows\", }, }, } if volume { pods = append(pods, &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, Labels: labels, }, Spec: v1.PodSpec{ // Restart policy is always (default). Containers: []v1.Container{ { Image: imageName, Name: podName, VolumeMounts: []v1.VolumeMount{ {MountPath: \"/test-volume-mnt\", Name: podName + \"-volume\"}, }, }, }, NodeSelector: map[string]string{ \"beta.kubernetes.io/os\": \"windows\", }, Volumes: []v1.Volume{ {Name: podName + \"-volume\", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, }, }, }) } else { pods = append(pods, &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, Labels: labels, }, Spec: v1.PodSpec{ // Restart policy is always (default). Containers: []v1.Container{ { Image: imageName, Name: podName, }, }, NodeSelector: map[string]string{ \"beta.kubernetes.io/os\": \"windows\", }, }, }) pod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{ {MountPath: \"/test-volume-mnt\", Name: podName + \"-volume\"}, } pod.Spec.Volumes = []v1.Volume{ {Name: podName + \"-volume\", VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}}, } } pods = append(pods, &pod) } return pods }"} {"_id":"doc-en-kubernetes-ab4e472292d189660b4f04e13b79bdd093a27828dc5576019715c1a1394a82eb","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package windows import ( \"crypto/tls\" \"encoding/json\" \"fmt\" \"io/ioutil\" \"net/http\" \"regexp\" \"strconv\" \"time\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/client-go/kubernetes/scheme\" kubeletconfigv1beta1 \"k8s.io/kubelet/config/v1beta1\" kubeletconfig \"k8s.io/kubernetes/pkg/kubelet/apis/config\" \"k8s.io/kubernetes/test/e2e/framework\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"github.com/onsi/ginkgo\" \"github.com/onsi/gomega\" ) var _ = SIGDescribe(\"[Feature:Windows] Memory Limits [Serial] [Slow]\", func() { f := framework.NewDefaultFramework(\"memory-limit-test-windows\") ginkgo.BeforeEach(func() { // NOTE(vyta): these tests are Windows specific framework.SkipUnlessNodeOSDistroIs(\"windows\") }) ginkgo.Context(\"Allocatable node memory\", func() { ginkgo.It(\"should be equal to a calculated allocatable memory value\", func() { checkNodeAllocatableTest(f) }) }) ginkgo.Context(\"attempt to deploy past allocatable memory limits\", func() { ginkgo.It(\"should fail deployments of pods once there isn't enough memory\", func() { overrideAllocatableMemoryTest(f, 4) }) }) }) type nodeMemory struct { // capacity capacity resource.Quantity // allocatable memory allocatable resource.Quantity // memory reserved for OS level processes systemReserve resource.Quantity // memory reserved for kubelet (not implemented) kubeReserve resource.Quantity // grace period memory limit (not implemented) softEviction resource.Quantity // no grace period memory limit hardEviction resource.Quantity } // runDensityBatchTest runs the density batch pod creation test // checks that a calculated value for NodeAllocatable is equal to the reported value func checkNodeAllocatableTest(f *framework.Framework) { nodeMem := getNodeMemory(f) framework.Logf(\"nodeMem says: %+v\", nodeMem) // calculate the allocatable mem based on capacity - reserved amounts calculatedNodeAlloc := nodeMem.capacity.Copy() calculatedNodeAlloc.Sub(nodeMem.systemReserve) calculatedNodeAlloc.Sub(nodeMem.kubeReserve) calculatedNodeAlloc.Sub(nodeMem.softEviction) calculatedNodeAlloc.Sub(nodeMem.hardEviction) ginkgo.By(fmt.Sprintf(\"Checking stated allocatable memory %v against calculated allocatable memory %v\", &nodeMem.allocatable, calculatedNodeAlloc)) // sanity check against stated allocatable gomega.Expect(calculatedNodeAlloc.Cmp(nodeMem.allocatable)).To(gomega.Equal(0)) } // Deploys `allocatablePods + 1` pods, each with a memory limit of `1/allocatablePods` of the total allocatable // memory, then confirms that the last pod failed because of failedScheduling func overrideAllocatableMemoryTest(f *framework.Framework, allocatablePods int) { const ( podType = \"memory_limit_test_pod\" ) totalAllocatable := getTotalAllocatableMemory(f) memValue := totalAllocatable.Value() memPerPod := memValue / int64(allocatablePods) ginkgo.By(fmt.Sprintf(\"Deploying %d pods with mem limit %v, then one additional pod\", allocatablePods, memPerPod)) // these should all work pods := newMemLimitTestPods(allocatablePods, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10)) f.PodClient().CreateBatch(pods) failurePods := newMemLimitTestPods(1, imageutils.GetPauseImageName(), podType, strconv.FormatInt(memPerPod, 10)) f.PodClient().Create(failurePods[0]) gomega.Eventually(func() bool { eventList, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(metav1.ListOptions{}) framework.ExpectNoError(err) for _, e := range eventList.Items { // Look for an event that shows FailedScheduling if e.Type == \"Warning\" && e.Reason == \"FailedScheduling\" && e.InvolvedObject.Name == failurePods[0].ObjectMeta.Name { framework.Logf(\"Found %+v event with message %+v\", e.Reason, e.Message) return true } } return false }, 3*time.Minute, 10*time.Second).Should(gomega.Equal(true)) } // newMemLimitTestPods creates a list of pods (specification) for test. func newMemLimitTestPods(numPods int, imageName, podType string, memoryLimit string) []*v1.Pod { var pods []*v1.Pod memLimitQuantity, err := resource.ParseQuantity(memoryLimit) framework.ExpectNoError(err) for i := 0; i < numPods; i++ { podName := \"test-\" + string(uuid.NewUUID()) pod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, Labels: map[string]string{ \"type\": podType, \"name\": podName, }, }, Spec: v1.PodSpec{ // Restart policy is always (default). Containers: []v1.Container{ { Image: imageName, Name: podName, Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceMemory: memLimitQuantity, }, }, }, }, NodeSelector: map[string]string{ \"beta.kubernetes.io/os\": \"windows\", }, }, } pods = append(pods, &pod) } return pods } // getNodeMemory populates a nodeMemory struct with information from the first func getNodeMemory(f *framework.Framework) nodeMemory { selector := labels.Set{\"beta.kubernetes.io/os\": \"windows\"}.AsSelector() nodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{ LabelSelector: selector.String(), }) framework.ExpectNoError(err) // Assuming that agent nodes have the same config // Make sure there is >0 agent nodes, then use the first one for info gomega.Expect(nodeList.Size()).NotTo(gomega.Equal(0)) ginkgo.By(\"Getting memory details from node status and kubelet config\") status := nodeList.Items[0].Status nodeName := nodeList.Items[0].ObjectMeta.Name kubeletConfig, err := getCurrentKubeletConfig(nodeName) framework.ExpectNoError(err) systemReserve, err := resource.ParseQuantity(kubeletConfig.SystemReserved[\"memory\"]) if err != nil { systemReserve = *resource.NewQuantity(0, resource.BinarySI) } kubeReserve, err := resource.ParseQuantity(kubeletConfig.KubeReserved[\"memory\"]) if err != nil { kubeReserve = *resource.NewQuantity(0, resource.BinarySI) } hardEviction, err := resource.ParseQuantity(kubeletConfig.EvictionHard[\"memory.available\"]) if err != nil { hardEviction = *resource.NewQuantity(0, resource.BinarySI) } softEviction, err := resource.ParseQuantity(kubeletConfig.EvictionSoft[\"memory.available\"]) if err != nil { softEviction = *resource.NewQuantity(0, resource.BinarySI) } nodeMem := nodeMemory{ capacity: status.Capacity[v1.ResourceMemory], allocatable: status.Allocatable[v1.ResourceMemory], systemReserve: systemReserve, hardEviction: hardEviction, // these are not implemented and are here for future use - will always be 0 at the moment kubeReserve: kubeReserve, softEviction: softEviction, } return nodeMem } // getTotalAllocatableMemory gets the sum of all agent node's allocatable memory func getTotalAllocatableMemory(f *framework.Framework) *resource.Quantity { selector := labels.Set{\"beta.kubernetes.io/os\": \"windows\"}.AsSelector() nodeList, err := f.ClientSet.CoreV1().Nodes().List(metav1.ListOptions{ LabelSelector: selector.String(), }) framework.ExpectNoError(err) ginkgo.By(\"Summing allocatable memory across all agent nodes\") totalAllocatable := resource.NewQuantity(0, resource.BinarySI) for _, node := range nodeList.Items { status := node.Status totalAllocatable.Add(status.Allocatable[v1.ResourceMemory]) } return totalAllocatable } // getCurrentKubeletConfig modified from test/e2e_node/util.go func getCurrentKubeletConfig(nodeName string) (*kubeletconfig.KubeletConfiguration, error) { resp := pollConfigz(5*time.Minute, 5*time.Second, nodeName) kubeCfg, err := decodeConfigz(resp) if err != nil { return nil, err } return kubeCfg, nil } // Causes the test to fail, or returns a status 200 response from the /configz endpoint func pollConfigz(timeout time.Duration, pollInterval time.Duration, nodeName string) *http.Response { // start local proxy, so we can send graceful deletion over query string, rather than body parameter ginkgo.By(\"Opening proxy to cluster\") cmd := framework.KubectlCmd(\"proxy\", \"-p\", \"0\") stdout, stderr, err := framework.StartCmdAndStreamOutput(cmd) framework.ExpectNoError(err) defer stdout.Close() defer stderr.Close() defer framework.TryKill(cmd) buf := make([]byte, 128) var n int n, err = stdout.Read(buf) framework.ExpectNoError(err) output := string(buf[:n]) proxyRegexp := regexp.MustCompile(\"Starting to serve on 127.0.0.1:([0-9]+)\") match := proxyRegexp.FindStringSubmatch(output) gomega.Expect(len(match)).To(gomega.Equal(2)) port, err := strconv.Atoi(match[1]) framework.ExpectNoError(err) ginkgo.By(\"http requesting node kubelet /configz\") endpoint := fmt.Sprintf(\"http://127.0.0.1:%d/api/v1/nodes/%s/proxy/configz\", port, nodeName) tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: tr} req, err := http.NewRequest(\"GET\", endpoint, nil) framework.ExpectNoError(err) req.Header.Add(\"Accept\", \"application/json\") var resp *http.Response gomega.Eventually(func() bool { resp, err = client.Do(req) if err != nil { framework.Logf(\"Failed to get /configz, retrying. Error: %v\", err) return false } if resp.StatusCode != 200 { framework.Logf(\"/configz response status not 200, retrying. Response was: %+v\", resp) return false } return true }, timeout, pollInterval).Should(gomega.Equal(true)) return resp } // Decodes the http response from /configz and returns a kubeletconfig.KubeletConfiguration (internal type). func decodeConfigz(resp *http.Response) (*kubeletconfig.KubeletConfiguration, error) { // This hack because /configz reports the following structure: // {\"kubeletconfig\": {the JSON representation of kubeletconfigv1beta1.KubeletConfiguration}} type configzWrapper struct { ComponentConfig kubeletconfigv1beta1.KubeletConfiguration `json:\"kubeletconfig\"` } configz := configzWrapper{} kubeCfg := kubeletconfig.KubeletConfiguration{} contentsBytes, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } err = json.Unmarshal(contentsBytes, &configz) if err != nil { return nil, err } err = scheme.Scheme.Convert(&configz.ComponentConfig, &kubeCfg, nil) if err != nil { return nil, err } return &kubeCfg, nil } "} {"_id":"doc-en-kubernetes-5ada69cd1d47c52439396f037a450772e1ea6f7ff6b4faf77eeed933370ac3da","title":"","text":"loadBalancer = createResponse.LoadBalancers[0] // Create Target Groups addTagsInput := &elbv2.AddTagsInput{ ResourceArns: []*string{}, Tags: []*elbv2.Tag{}, } resourceArns := make([]*string, 0, len(mappings)) for i := range mappings { // It is easier to keep track of updates by having possibly"} {"_id":"doc-en-kubernetes-b0b431df7ac418c506125044990acc96f125a99b978b6e344029e323e24f35a8","title":"","text":"if err != nil { return nil, fmt.Errorf(\"Error creating listener: %q\", err) } addTagsInput.ResourceArns = append(addTagsInput.ResourceArns, targetGroupArn) resourceArns = append(resourceArns, targetGroupArn) } // Add tags to targets targetGroupTags := make([]*elbv2.Tag, 0, len(tags)) for k, v := range tags { addTagsInput.Tags = append(addTagsInput.Tags, &elbv2.Tag{ targetGroupTags = append(targetGroupTags, &elbv2.Tag{ Key: aws.String(k), Value: aws.String(v), }) } if len(addTagsInput.ResourceArns) > 0 && len(addTagsInput.Tags) > 0 { _, err = c.elbv2.AddTags(addTagsInput) if err != nil { return nil, fmt.Errorf(\"Error adding tags after creating Load Balancer: %q\", err) if len(resourceArns) > 0 && len(targetGroupTags) > 0 { // elbv2.AddTags doesn't allow to tag multiple resources at once for _, arn := range resourceArns { _, err = c.elbv2.AddTags(&elbv2.AddTagsInput{ ResourceArns: []*string{arn}, Tags: targetGroupTags, }) if err != nil { return nil, fmt.Errorf(\"Error adding tags after creating Load Balancer: %q\", err) } } } } else {"} {"_id":"doc-en-kubernetes-3a388f012c187e47cd94c7f09a3e193928d43dec25d777b22940acad9026784c","title":"","text":"} if _, exists := configMap.Data[keyName]; exists { return fmt.Errorf(\"cannot add key %s, another key by that name already exists in data: %v\", keyName, configMap.Data) return fmt.Errorf(\"cannot add key %q, another key by that name already exists in Data for ConfigMap %q\", keyName, configMap.Name) } if _, exists := configMap.BinaryData[keyName]; exists { return fmt.Errorf(\"cannot add key %s, another key by that name already exists in binaryData: %v\", keyName, configMap.BinaryData) return fmt.Errorf(\"cannot add key %q, another key by that name already exists in BinaryData for ConfigMap %q\", keyName, configMap.Name) } return nil }"} {"_id":"doc-en-kubernetes-4a4c8e93e464279ea56adb4feb0a2aa739b27ad30fd9ed4ab750068fb256b8b3","title":"","text":"} if _, entryExists := secret.Data[keyName]; entryExists { return fmt.Errorf(\"cannot add key %s, another key by that name already exists: %v\", keyName, secret.Data) return fmt.Errorf(\"cannot add key %s, another key by that name already exists\", keyName) } secret.Data[keyName] = data return nil"} {"_id":"doc-en-kubernetes-2afb67a2e52ff215f05bd1e1e05d8dd55eacbf6728f36c83b41994fdf9241598","title":"","text":"driverNodeID, maxVolumePerNode, accessibleTopology, err := csi.NodeGetInfo(ctx) if err != nil { klog.Error(log(\"registrationHandler.RegisterPlugin failed at CSI.NodeGetInfo: %v\", err)) if unregErr := unregisterDriver(pluginName); unregErr != nil { klog.Error(log(\"registrationHandler.RegisterPlugin failed to unregister plugin due to previous error: %v\", unregErr)) return unregErr } return err } err = nim.InstallCSIDriver(pluginName, driverNodeID, maxVolumePerNode, accessibleTopology) if err != nil { klog.Error(log(\"registrationHandler.RegisterPlugin failed at AddNodeInfo: %v\", err)) if unregErr := unregisterDriver(pluginName); unregErr != nil { klog.Error(log(\"registrationHandler.RegisterPlugin failed to unregister plugin due to previous error: %v\", unregErr)) return unregErr } return err }"} {"_id":"doc-en-kubernetes-2878f821592f1a9a532528b2bd05f0d03921b77cb2a97b2bba2401bfcea48322","title":"","text":"\"ext2\", \"ext3\", \"ext4\", \"xfs\", //\"xfs\", disabled see issue https://github.com/kubernetes/kubernetes/issues/74095 ), } // max file size"} {"_id":"doc-en-kubernetes-3270e86d25112a74f820521d291d337bfd0e0b9f1035106dc191072964ca89ad","title":"","text":"// Images used for ConformanceContainer are not added into NodeImageWhiteList, because this test is // testing image pulling, these images don't need to be prepulled. The ImagePullPolicy // is v1.PullAlways, so it won't be blocked by framework image white list check. imagePullTest := func(image string, hasSecret bool, expectedPhase v1.PodPhase, expectedPullStatus bool) { imagePullTest := func(image string, hasSecret bool, expectedPhase v1.PodPhase, expectedPullStatus bool, windowsImage bool) { command := []string{\"/bin/sh\", \"-c\", \"while true; do sleep 1; done\"} if windowsImage { // -t: Ping the specified host until stopped. command = []string{\"ping\", \"-t\", \"localhost\"} } container := ConformanceContainer{ PodClient: f.PodClient(), Container: v1.Container{ Name: \"image-pull-test\", Image: image, Command: []string{\"/bin/sh\", \"-c\", \"while true; do sleep 1; done\"}, Command: command, ImagePullPolicy: v1.PullAlways, }, RestartPolicy: v1.RestartPolicyNever,"} {"_id":"doc-en-kubernetes-38c425691ac8f8f297e3f7ca3c07cfabc5e8b25a2b4d743acb4712d48fec64dc","title":"","text":"It(\"should not be able to pull image from invalid registry [NodeConformance]\", func() { image := \"invalid.com/invalid/alpine:3.1\" imagePullTest(image, false, v1.PodPending, true) imagePullTest(image, false, v1.PodPending, true, false) }) It(\"should not be able to pull non-existing image from gcr.io [NodeConformance]\", func() { image := \"k8s.gcr.io/invalid-image:invalid-tag\" imagePullTest(image, false, v1.PodPending, true) imagePullTest(image, false, v1.PodPending, true, false) }) // TODO(claudiub): Add a Windows equivalent test. It(\"should be able to pull image from gcr.io [LinuxOnly] [NodeConformance]\", func() { image := \"gcr.io/google-containers/debian-base:0.4.1\" imagePullTest(image, false, v1.PodRunning, false) imagePullTest(image, false, v1.PodRunning, false, false) }) It(\"should be able to pull image from gcr.io [NodeConformance]\", func() { framework.SkipUnlessNodeOSDistroIs(\"windows\") image := \"gcr.io/kubernetes-e2e-test-images/windows-nanoserver:v1\" imagePullTest(image, false, v1.PodRunning, false, true) }) It(\"should be able to pull image from docker hub [LinuxOnly] [NodeConformance]\", func() { image := \"alpine:3.7\" imagePullTest(image, false, v1.PodRunning, false) imagePullTest(image, false, v1.PodRunning, false, false) }) It(\"should be able to pull image from docker hub [WindowsOnly] [NodeConformance]\", func() { It(\"should be able to pull image from docker hub [NodeConformance]\", func() { framework.SkipUnlessNodeOSDistroIs(\"windows\") // TODO(claudiub): Switch to nanoserver image manifest list. image := \"e2eteam/busybox:1.29\" imagePullTest(image, false, v1.PodRunning, false) imagePullTest(image, false, v1.PodRunning, false, true) }) It(\"should not be able to pull from private registry without secret [NodeConformance]\", func() { image := \"gcr.io/authenticated-image-pulling/alpine:3.7\" imagePullTest(image, false, v1.PodPending, true) imagePullTest(image, false, v1.PodPending, true, false) }) It(\"should be able to pull from private registry with secret [LinuxOnly] [NodeConformance]\", func() { image := \"gcr.io/authenticated-image-pulling/alpine:3.7\" imagePullTest(image, true, v1.PodRunning, false) imagePullTest(image, true, v1.PodRunning, false, false) }) It(\"should be able to pull from private registry with secret [NodeConformance]\", func() { framework.SkipUnlessNodeOSDistroIs(\"windows\") image := \"gcr.io/authenticated-image-pulling/windows-nanoserver:v1\" imagePullTest(image, true, v1.PodRunning, false, true) }) }) })"} {"_id":"doc-en-kubernetes-1df74823143c0217203fe939146eb88ae1d9a8aafa2b3951bf5736ef80cf1870","title":"","text":"podsDir string) (volumetypes.GeneratedOperations, error) { var pluginName string if useCSIPlugin(og.volumePluginMgr, volumeToUnmount.VolumeSpec) { if volumeToUnmount.VolumeSpec != nil && useCSIPlugin(og.volumePluginMgr, volumeToUnmount.VolumeSpec) { pluginName = csi.CSIPluginName } else { pluginName = volumeToUnmount.PluginName"} {"_id":"doc-en-kubernetes-a72d8356d65f3b0880ac46fbd0da4dcad716a7443c576f75cb52a3b797fc5cbb","title":"","text":"\"//vendor/k8s.io/utils/mount:go_default_library\", \"//vendor/k8s.io/utils/net:go_default_library\", \"//vendor/k8s.io/utils/path:go_default_library\", \"//vendor/k8s.io/utils/strings:go_default_library\", ] + select({ \"@io_bazel_rules_go//go/platform:windows\": [ \"//pkg/kubelet/winstats:go_default_library\","} {"_id":"doc-en-kubernetes-feeaae68e3504e93563387428065d939a26edfc55cb3718b7e8fa7dce7692a21","title":"","text":"\"k8s.io/klog\" \"k8s.io/utils/mount\" utilpath \"k8s.io/utils/path\" utilstrings \"k8s.io/utils/strings\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/types\""} {"_id":"doc-en-kubernetes-5e33721b9ffe393313715b9d7a521cffa440643c091a4e63c7590b200bf6b567","title":"","text":"kubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\" kubelettypes \"k8s.io/kubernetes/pkg/kubelet/types\" utilnode \"k8s.io/kubernetes/pkg/util/node\" \"k8s.io/kubernetes/pkg/volume/csi\" ) // getRootDir returns the full path to the directory under which kubelet can"} {"_id":"doc-en-kubernetes-33d6885fea82ad2d13ec602331cfe8172b053d4d7c3c443d8b6330d833eff2ed","title":"","text":"if err != nil { return volumes, fmt.Errorf(\"could not read directory %s: %v\", volumePluginPath, err) } for _, volumeDir := range volumeDirs { volumes = append(volumes, filepath.Join(volumePluginPath, volumeDir)) unescapePluginName := utilstrings.UnescapeQualifiedName(volumePluginName) if unescapePluginName != csi.CSIPluginName { for _, volumeDir := range volumeDirs { volumes = append(volumes, filepath.Join(volumePluginPath, volumeDir)) } } else { // For CSI volumes, the mounted volume path has an extra sub path \"/mount\", so also add it // to the list if the mounted path exists. for _, volumeDir := range volumeDirs { path := filepath.Join(volumePluginPath, volumeDir) csimountpath := csi.GetCSIMounterPath(path) if pathExists, _ := mount.PathExists(csimountpath); pathExists { volumes = append(volumes, csimountpath) } } } } return volumes, nil"} {"_id":"doc-en-kubernetes-4020b6ef4833206a6737e8a662fcfbf4a867650e212f2298aaa5dcc4fdccf4cc","title":"","text":"if err != nil { return mountedVolumes, err } // Only use IsLikelyNotMountPoint to check might not cover all cases. For CSI volumes that // either: 1) don't mount or 2) bind mount in the rootfs, the mount check will not work as expected. // We plan to remove this mountpoint check as a condition before deleting pods since it is // not reliable and the condition might be different for different types of volumes. But it requires // a reliable way to clean up unused volume dir to avoid problems during pod deletion. See discussion in issue #74650 for _, volumePath := range volumePaths { isNotMount, err := kl.mounter.IsLikelyNotMountPoint(volumePath) if err != nil { return mountedVolumes, err return mountedVolumes, fmt.Errorf(\"fail to check mount point %q: %v\", volumePath, err) } if !isNotMount { mountedVolumes = append(mountedVolumes, volumePath)"} {"_id":"doc-en-kubernetes-77a05ec6144839b37c03ccc6ebb068dfaf478c69bf54635b908835d63bd528d1","title":"","text":"v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" _ \"k8s.io/kubernetes/pkg/apis/core/install\" \"k8s.io/utils/mount\" ) func validateDirExists(dir string) error {"} {"_id":"doc-en-kubernetes-1c5961fc4ceecf17dd9688f9bcfc0535366fd02b21e033d4ec993ee6e79c9411","title":"","text":"}) } } func TestPodVolumesExistWithMount(t *testing.T) { poduid := types.UID(\"poduid\") testCases := map[string]struct { prepareFunc func(kubelet *Kubelet) error expected bool }{ \"noncsivolume-dir-not-exist\": { prepareFunc: func(kubelet *Kubelet) error { return nil }, expected: false, }, \"noncsivolume-dir-exist-noplugins\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) return os.MkdirAll(filepath.Join(podDir, \"volumes/\"), 0750) }, expected: false, }, \"noncsivolume-dir-exist-nomount\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) return os.MkdirAll(filepath.Join(podDir, \"volumes/plugin/name\"), 0750) }, expected: false, }, \"noncsivolume-dir-exist-with-mount\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) volumePath := filepath.Join(podDir, \"volumes/plugin/name\") if err := os.MkdirAll(volumePath, 0750); err != nil { return err } fm := mount.NewFakeMounter( []mount.MountPoint{ {Device: \"/dev/sdb\", Path: volumePath}, }) kubelet.mounter = fm return nil }, expected: true, }, \"noncsivolume-dir-exist-nomount-withcsimountpath\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) volumePath := filepath.Join(podDir, \"volumes/plugin/name/mount\") if err := os.MkdirAll(volumePath, 0750); err != nil { return err } fm := mount.NewFakeMounter( []mount.MountPoint{ {Device: \"/dev/sdb\", Path: volumePath}, }) kubelet.mounter = fm return nil }, expected: false, }, \"csivolume-dir-exist-nomount\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) volumePath := filepath.Join(podDir, \"volumes/kubernetes.io~csi/name\") return os.MkdirAll(volumePath, 0750) }, expected: false, }, \"csivolume-dir-exist-mount-nocsimountpath\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) volumePath := filepath.Join(podDir, \"volumes/kubernetes.io~csi/name/mount\") return os.MkdirAll(volumePath, 0750) }, expected: false, }, \"csivolume-dir-exist-withcsimountpath\": { prepareFunc: func(kubelet *Kubelet) error { podDir := kubelet.getPodDir(poduid) volumePath := filepath.Join(podDir, \"volumes/kubernetes.io~csi/name/mount\") if err := os.MkdirAll(volumePath, 0750); err != nil { return err } fm := mount.NewFakeMounter( []mount.MountPoint{ {Device: \"/dev/sdb\", Path: volumePath}, }) kubelet.mounter = fm return nil }, expected: true, }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) defer testKubelet.Cleanup() kubelet := testKubelet.kubelet if tc.prepareFunc != nil { if err := tc.prepareFunc(kubelet); err != nil { t.Fatalf(\"%s failed preparation: %v\", name, err) } } exist := kubelet.podVolumesExist(poduid) if tc.expected != exist { t.Errorf(\"%s failed: expected %t, got %t\", name, tc.expected, exist) } }) } } "} {"_id":"doc-en-kubernetes-2dafba90d9f2d5ec3a98fdd188183c0184628ce16b7341570f138d4ae1896b8c","title":"","text":"var _ volume.Volume = &csiMountMgr{} func (c *csiMountMgr) GetPath() string { dir := filepath.Join(getTargetPath(c.podUID, c.specVolumeID, c.plugin.host), \"/mount\") dir := GetCSIMounterPath(filepath.Join(getTargetPath(c.podUID, c.specVolumeID, c.plugin.host))) klog.V(4).Info(log(\"mounter.GetPath generated [%s]\", dir)) return dir }"} {"_id":"doc-en-kubernetes-9ab7e3cce66831d23e3b6a1979f7399e03f3c5ee5ef730d3e1d4df2f32ec496a","title":"","text":"} return pvSrc, nil } // GetCSIMounterPath returns the mounter path given the base path. func GetCSIMounterPath(path string) string { return filepath.Join(path, \"/mount\") } "} {"_id":"doc-en-kubernetes-ae6409df08a3cfd210c26b33ceea93250b5ab8bae9826c841c82b7f71a4586e3","title":"","text":"By(\"creating a file in subpath\") cmd := \"touch /volume_mount/mypath/foo/test.log\" _, err = framework.RunHostCmd(pod.Namespace, pod.Name, cmd) _, _, err = f.ExecShellInPodWithFullOutput(pod.Name, cmd) if err != nil { framework.Failf(\"expected to be able to write to subpath\") } By(\"test for file in mounted path\") cmd = \"test -f /subpath_mount/test.log\" _, err = framework.RunHostCmd(pod.Namespace, pod.Name, cmd) _, _, err = f.ExecShellInPodWithFullOutput(pod.Name, cmd) if err != nil { framework.Failf(\"expected to be able to verify file\") }"} {"_id":"doc-en-kubernetes-3e19704f979eb713e2e39dc5c87d2537e8ec0ce76abdc04be6089b8c2e3c7b15","title":"","text":"By(\"test for subpath mounted with old value\") cmd := \"test -f /volume_mount/foo/test.log\" _, err = framework.RunHostCmd(pod.Namespace, pod.Name, cmd) _, _, err = f.ExecShellInPodWithFullOutput(pod.Name, cmd) if err != nil { framework.Failf(\"expected to be able to verify old file exists\") } cmd = \"test ! -f /volume_mount/newsubpath/test.log\" _, err = framework.RunHostCmd(pod.Namespace, pod.Name, cmd) _, _, err = f.ExecShellInPodWithFullOutput(pod.Name, cmd) if err != nil { framework.Failf(\"expected to be able to verify new file does not exist\") }"} {"_id":"doc-en-kubernetes-0026f623c6a794fc6fb7bc2947fa29def8489941024886a43fe37cac94daf767","title":"","text":"func waitForPodContainerRestart(f *framework.Framework, pod *v1.Pod, volumeMount string) { By(\"Failing liveness probe\") out, err := framework.RunKubectl(\"exec\", fmt.Sprintf(\"--namespace=%s\", pod.Namespace), pod.Name, \"--container\", pod.Spec.Containers[0].Name, \"--\", \"/bin/sh\", \"-c\", fmt.Sprintf(\"rm %v\", volumeMount)) stdout, stderr, err := f.ExecShellInPodWithFullOutput(pod.Name, fmt.Sprintf(\"rm %v\", volumeMount)) framework.Logf(\"Pod exec output: %v\", out) framework.Logf(\"Pod exec output: %v / %v\", stdout, stderr) Expect(err).ToNot(HaveOccurred(), \"while failing liveness probe\") // Check that container has restarted"} {"_id":"doc-en-kubernetes-3fb8ecca68165b72d819a5698d31eef9837371040d86949a42e4f90c78fa69cd","title":"","text":"// Fix liveness probe By(\"Rewriting the file\") out, err = framework.RunKubectl(\"exec\", fmt.Sprintf(\"--namespace=%s\", pod.Namespace), pod.Name, \"--container\", pod.Spec.Containers[0].Name, \"--\", \"/bin/sh\", \"-c\", fmt.Sprintf(\"echo test-after > %v\", volumeMount)) framework.Logf(\"Pod exec output: %v\", out) stdout, _, err = f.ExecShellInPodWithFullOutput(pod.Name, fmt.Sprintf(\"echo test-after > %v\", volumeMount)) framework.Logf(\"Pod exec output: %v\", stdout) Expect(err).ToNot(HaveOccurred(), \"while rewriting the probe file\") // Wait for container restarts to stabilize"} {"_id":"doc-en-kubernetes-98ea0189a536ea447d34d5644f1bf6593875c60bc279ed612852e98db64a7d50","title":"","text":"DummyDiskName = \"kube-dummyDisk.vmdk\" ProviderPrefix = \"vsphere://\" vSphereConfFileEnvVar = \"VSPHERE_CONF_FILE\" UUIDPrefix = \"VMware-\" ) // GetVSphere reads vSphere configuration from system environment and construct vSphere object"} {"_id":"doc-en-kubernetes-716b0cfa6d0587954df9407e43e2e2463a62db82a9e21ad4a3ba0cc5224fa9ed","title":"","text":"} return GetUUIDFromProviderID(node.Spec.ProviderID), nil } func GetVMUUID() (string, error) { uuidFromFile, err := getRawUUID() if err != nil { return \"\", fmt.Errorf(\"error retrieving vm uuid: %s\", err) } //strip leading and trailing white space and new line char uuid := strings.TrimSpace(uuidFromFile) // check the uuid starts with \"VMware-\" if !strings.HasPrefix(uuid, UUIDPrefix) { return \"\", fmt.Errorf(\"Failed to match Prefix, UUID read from the file is %v\", uuidFromFile) } // Strip the prefix and white spaces and - uuid = strings.Replace(uuid[len(UUIDPrefix):(len(uuid))], \" \", \"\", -1) uuid = strings.Replace(uuid, \"-\", \"\", -1) if len(uuid) != 32 { return \"\", fmt.Errorf(\"Length check failed, UUID read from the file is %v\", uuidFromFile) } // need to add dashes, e.g. \"564d395e-d807-e18a-cb25-b79f65eb2b9f\" uuid = fmt.Sprintf(\"%s-%s-%s-%s-%s\", uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:32]) return uuid, nil } "} {"_id":"doc-en-kubernetes-37af8421e265d0aed81c3a78fe09d92e25af0b2e5306811ac0c303cb6d2d7bdb","title":"","text":"package vsphere import ( \"fmt\" \"io/ioutil\" \"strings\" ) const ( UUIDPath = \"/sys/class/dmi/id/product_serial\" UUIDPrefix = \"VMware-\" ) const UUIDPath = \"/sys/class/dmi/id/product_serial\" func GetVMUUID() (string, error) { func getRawUUID() (string, error) { id, err := ioutil.ReadFile(UUIDPath) if err != nil { return \"\", fmt.Errorf(\"error retrieving vm uuid: %s\", err) } uuidFromFile := string(id[:]) //strip leading and trailing white space and new line char uuid := strings.TrimSpace(uuidFromFile) // check the uuid starts with \"VMware-\" if !strings.HasPrefix(uuid, UUIDPrefix) { return \"\", fmt.Errorf(\"Failed to match Prefix, UUID read from the file is %v\", uuidFromFile) } // Strip the prefix and white spaces and - uuid = strings.Replace(uuid[len(UUIDPrefix):(len(uuid))], \" \", \"\", -1) uuid = strings.Replace(uuid, \"-\", \"\", -1) if len(uuid) != 32 { return \"\", fmt.Errorf(\"Length check failed, UUID read from the file is %v\", uuidFromFile) return \"\", err } // need to add dashes, e.g. \"564d395e-d807-e18a-cb25-b79f65eb2b9f\" uuid = fmt.Sprintf(\"%s-%s-%s-%s-%s\", uuid[0:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:32]) return uuid, nil return string(id), nil }"} {"_id":"doc-en-kubernetes-510f1dd27e8a6bfb59df8794837d7d5c8736a23d697e6659ffb55ecc617bb4f1","title":"","text":"import \"fmt\" func GetVMUUID() (string, error) { func getRawUUID() (string, error) { return \"\", fmt.Errorf(\"Retrieving VM UUID on this build is not implemented.\") }"} {"_id":"doc-en-kubernetes-c89475991afe8859793ea2f6637c369a9db3601ec51191608cc78c970a9dca70","title":"","text":"\"strings\" ) func GetVMUUID() (string, error) { result, err := exec.Command(\"wmic\", \"csproduct\", \"get\", \"UUID\").Output() func getRawUUID() (string, error) { result, err := exec.Command(\"wmic\", \"bios\", \"get\", \"serialnumber\").Output() if err != nil { return \"\", fmt.Errorf(\"error retrieving vm uuid: %s\", err) return \"\", err } fields := strings.Fields(string(result)) if len(fields) != 2 { lines := strings.FieldsFunc(string(result), func(r rune) bool { switch r { case 'n', 'r': return true default: return false } }) if len(lines) != 2 { return \"\", fmt.Errorf(\"received unexpected value retrieving vm uuid: %q\", string(result)) } return fields[1], nil return lines[1], nil }"} {"_id":"doc-en-kubernetes-46531a8b9f1e7cd4a4761ed0ba9d1fa5eed0f1ce9f09610badd3e1306d46950e","title":"","text":"- name: config mountPath: /etc/config nodeSelector: # TODO(liggitt): switch to node.kubernetes.io/masq-agent-ds-ready in 1.16 beta.kubernetes.io/masq-agent-ds-ready: \"true\" node.kubernetes.io/masq-agent-ds-ready: \"true\" volumes: - name: config configMap:"} {"_id":"doc-en-kubernetes-dacfbb60b8332c0c62dadb5b538ee9defcdb63b70df5f58e4e2a89910f5f3803","title":"","text":"priorityClassName: system-node-critical hostNetwork: true nodeSelector: # TODO(liggitt): switch to node.kubernetes.io/kube-proxy-ds-ready in 1.16 beta.kubernetes.io/kube-proxy-ds-ready: \"true\" node.kubernetes.io/kube-proxy-ds-ready: \"true\" tolerations: - operator: \"Exists\" effect: \"NoExecute\""} {"_id":"doc-en-kubernetes-104ad197bf735db95d76b4e9163b3ba6d65fa4c2e264e4b237c1add4979cf977","title":"","text":"fieldPath: metadata.namespace # END_PROMETHEUS_TO_SD nodeSelector: # TODO(liggitt): switch to cloud.google.com/metadata-proxy-ready=true in v1.16 beta.kubernetes.io/metadata-proxy-ready: \"true\" cloud.google.com/metadata-proxy-ready: \"true\" beta.kubernetes.io/os: linux terminationGracePeriodSeconds: 30"} {"_id":"doc-en-kubernetes-2067bd7357eed4575c725412c6b550bb8971334bfbddd59e1c36142533433575","title":"","text":"if [[ ${ENABLE_METADATA_CONCEALMENT:-} == \"true\" ]]; then # Put the necessary label on the node so the daemonset gets scheduled. NODE_LABELS=\"${NODE_LABELS},cloud.google.com/metadata-proxy-ready=true\" # TODO(liggitt): remove this in v1.16 NODE_LABELS=\"${NODE_LABELS},beta.kubernetes.io/metadata-proxy-ready=true\" # Add to the provider custom variables. PROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_METADATA_CONCEALMENT METADATA_CONCEALMENT_NO_FIREWALL\" fi"} {"_id":"doc-en-kubernetes-6150af03b9e0f817a431a4b69b94027c27054a5e1531378c67ab759852edd1ed","title":"","text":"if [[ \"${KUBE_PROXY_DAEMONSET:-}\" == \"true\" && \"${master}\" != \"true\" ]]; then # Add kube-proxy daemonset label to node to avoid situation during cluster # upgrade/downgrade when there are two instances of kube-proxy running on a node. # TODO(liggitt): drop beta.kubernetes.io/kube-proxy-ds-ready in 1.16 node_labels=\"node.kubernetes.io/kube-proxy-ds-ready=true,beta.kubernetes.io/kube-proxy-ds-ready=true\" node_labels=\"node.kubernetes.io/kube-proxy-ds-ready=true\" fi if [[ -n \"${NODE_LABELS:-}\" ]]; then node_labels=\"${node_labels:+${node_labels},}${NODE_LABELS}\""} {"_id":"doc-en-kubernetes-a516243635fb744399c8da04724fecc7d86e9ccb58a3fb3cac909bc904571e1c","title":"","text":"\"k8s.io/apimachinery/pkg/util/sets\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" cliflag \"k8s.io/component-base/cli/flag\" \"k8s.io/klog\" \"k8s.io/kubelet/config/v1beta1\" \"k8s.io/kubernetes/pkg/apis/core\" \"k8s.io/kubernetes/pkg/features\""} {"_id":"doc-en-kubernetes-7d72136beb552b5f5f010017cde9e8d9fa345450796075e2a7735feac96f7cb7","title":"","text":"} } if len(unknownLabels) > 0 { // TODO(liggitt): in 1.16, return an error klog.Warningf(\"unknown 'kubernetes.io' or 'k8s.io' labels specified with --node-labels: %v\", unknownLabels.List()) klog.Warningf(\"in 1.16, --node-labels in the 'kubernetes.io' namespace must begin with an allowed prefix (%s) or be in the specifically allowed set (%s)\", strings.Join(kubeletapis.KubeletLabelNamespaces(), \", \"), strings.Join(kubeletapis.KubeletLabels(), \", \")) return fmt.Errorf(\"unknown 'kubernetes.io' or 'k8s.io' labels specified with --node-labels: %vn--node-labels in the 'kubernetes.io' namespace must begin with an allowed prefix (%s) or be in the specifically allowed set (%s)\", unknownLabels.List(), strings.Join(kubeletapis.KubeletLabelNamespaces(), \", \"), strings.Join(kubeletapis.KubeletLabels(), \", \")) } return nil"} {"_id":"doc-en-kubernetes-edd47c4b6eff769ce447fc2452e473c5bdff5b31bd57331f8323f5d1bd4ba1f4","title":"","text":"}) return args } func TestValidateKubeletFlags(t *testing.T) { tests := []struct { name string error bool labels map[string]string }{ { name: \"Invalid kubernetes.io label\", error: true, labels: map[string]string{ \"beta.kubernetes.io/metadata-proxy-ready\": \"true\", }, }, { name: \"Valid label outside of kubernetes.io and k8s.io\", error: false, labels: map[string]string{ \"cloud.google.com/metadata-proxy-ready\": \"true\", }, }, { name: \"Empty label list\", error: false, labels: map[string]string{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := ValidateKubeletFlags(&KubeletFlags{ NodeLabels: tt.labels, }) if tt.error && err == nil { t.Errorf(\"ValidateKubeletFlags should have failed with labels: %+v\", tt.labels) } if !tt.error && err != nil { t.Errorf(\"ValidateKubeletFlags should not have failed with labels: %+v\", tt.labels) } }) } } "} {"_id":"doc-en-kubernetes-80f027a79d26cc9a209f08491dc32fbfd45ff8922ada1961c64eaf317d57e842","title":"","text":"addProfilingFlags(flags) kubeConfigFlags := genericclioptions.NewConfigFlags(true) kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag() kubeConfigFlags.AddFlags(flags) matchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags) matchVersionKubeConfigFlags.AddFlags(cmds.PersistentFlags())"} {"_id":"doc-en-kubernetes-a07b51b16ccd5ae2e42cad417f3353be8fe0125fa99325f81d73f1744d34cae9","title":"","text":"// klog.V(4).Infof(\"rbd: info %s using mon %s, pool %s id %s key %s\", b.Image, mon, b.Pool, id, secret) output, err = b.exec.Run(\"rbd\", \"info\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret, \"--format=json\") \"info\", b.Image, \"--pool\", b.Pool, \"-m\", mon, \"--id\", id, \"--key=\"+secret, \"-k=/dev/null\", \"--format=json\") if err, ok := err.(*exec.Error); ok { if err.Err == exec.ErrNotFound {"} {"_id":"doc-en-kubernetes-b45b6cd98fca0c24027653e90531ab1af2c2c6eb56d056e6fbce1b709f997656","title":"","text":"cadvisorapi \"github.com/google/cadvisor/info/v1\" v1 \"k8s.io/api/core/v1\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/fields\" \"k8s.io/apimachinery/pkg/labels\""} {"_id":"doc-en-kubernetes-212a92a5adf4c4d172ec8432bc58483e49b5966113226982b56fec99efc5748d","title":"","text":"r := cache.NewReflector(nodeLW, &v1.Node{}, nodeIndexer, 0) go r.Run(wait.NeverStop) } nodeInfo := &predicates.CachedNodeInfo{NodeLister: corelisters.NewNodeLister(nodeIndexer)} nodeInfo := &CachedNodeInfo{NodeLister: corelisters.NewNodeLister(nodeIndexer)} // TODO: get the real node object of ourself, // and use the real node name and UID."} {"_id":"doc-en-kubernetes-c41bd4c0b6ff1ad2abe302e12daefb65f4f796441ba6bedd1759399d85a47010","title":"","text":"} return config } // CachedNodeInfo implements NodeInfo type CachedNodeInfo struct { corelisters.NodeLister } // GetNodeInfo returns cached data for the node name. func (c *CachedNodeInfo) GetNodeInfo(nodeName string) (*v1.Node, error) { node, err := c.Get(nodeName) if apierrors.IsNotFound(err) { return nil, err } if err != nil { return nil, fmt.Errorf(\"error retrieving node '%v' from cache: %v\", nodeName, err) } return node, nil } "} {"_id":"doc-en-kubernetes-0d1a906e96c0aac5120c89538aea555e8260143afc257bd2136da812a865057c","title":"","text":"return c.PersistentVolumeClaims(namespace).Get(name) } // CachedNodeInfo implements NodeInfo type CachedNodeInfo struct { corelisters.NodeLister } // GetNodeInfo returns cached data for the node 'id'. func (c *CachedNodeInfo) GetNodeInfo(id string) (*v1.Node, error) { node, err := c.Get(id) if apierrors.IsNotFound(err) { return nil, err } if err != nil { return nil, fmt.Errorf(\"error retrieving node '%v' from cache: %v\", id, err) } return node, nil } // StorageClassInfo interface represents anything that can get a storage class object by class name. type StorageClassInfo interface { GetStorageClassInfo(className string) (*storagev1.StorageClass, error)"} {"_id":"doc-en-kubernetes-7eac0a3100aa51e619424c409b70224943be7c8c46dc1dffe807da6bde2b2470","title":"","text":"StatefulSetLister: c.statefulSetLister, NodeLister: &nodeLister{c.nodeLister}, PDBLister: c.pdbLister, NodeInfo: &predicates.CachedNodeInfo{NodeLister: c.nodeLister}, NodeInfo: c.schedulerCache, PVInfo: &predicates.CachedPersistentVolumeInfo{PersistentVolumeLister: c.pVLister}, PVCInfo: &predicates.CachedPersistentVolumeClaimInfo{PersistentVolumeClaimLister: c.pVCLister}, StorageClassInfo: &predicates.CachedStorageClassInfo{StorageClassLister: c.storageClassLister},"} {"_id":"doc-en-kubernetes-759409ce7d24649765f5fde637fa4548430b6517c2b02340b774a228442beec5","title":"","text":"func (cache *schedulerCache) NodeTree() *NodeTree { return cache.nodeTree } // GetNodeInfo returns cached data for the node name. func (cache *schedulerCache) GetNodeInfo(nodeName string) (*v1.Node, error) { cache.mu.RLock() defer cache.mu.RUnlock() n, ok := cache.nodes[nodeName] if !ok { return nil, fmt.Errorf(\"error retrieving node '%v' from cache\", nodeName) } return n.info.Node(), nil } "} {"_id":"doc-en-kubernetes-c04c01249a61c6c36ec71d0eb8e7e31386293ee78342007c01639f83a160e69c","title":"","text":"// NodeTree is a fake method for testing. func (c *Cache) NodeTree() *internalcache.NodeTree { return nil } // GetNodeInfo is a fake method for testing. func (c *Cache) GetNodeInfo(nodeName string) (*v1.Node, error) { return nil, nil } "} {"_id":"doc-en-kubernetes-a01fa5bcc9e538689afe7602fcf448a2749591335a4c7b0ef05bbbe141e85bbb","title":"","text":"// RemoveCSINode removes overall CSI-related information about node. RemoveCSINode(csiNode *storagev1beta1.CSINode) error // GetNodeInfo returns the node object with node string. GetNodeInfo(nodeName string) (*v1.Node, error) // List lists all cached pods (including assumed ones). List(labels.Selector) ([]*v1.Pod, error)"} {"_id":"doc-en-kubernetes-b356aa6bb2f5994135151118809590e78fcc1306fcf86cd2fe358941c6f5c2ce","title":"","text":"\"encoding/hex\" \"fmt\" \"net\" \"regexp\" \"strings\" \"k8s.io/apimachinery/pkg/api/resource\""} {"_id":"doc-en-kubernetes-5b39ff9d1528b9133b4ea8a82df67044d06f9e42e4ea7989c59b5f99a70e5ae8","title":"","text":"\"k8s.io/klog\" ) var ( classShowMatcher = regexp.MustCompile(`class htb (1:d+)`) classAndHandleMatcher = regexp.MustCompile(`filter parent 1:.*fh (d+::d+).*flowid (d+:d+)`) ) // tcShaper provides an implementation of the Shaper interface on Linux using the 'tc' tool. // In general, using this requires that the caller posses the NET_CAP_ADMIN capability, though if you // do this within an container, it only requires the NS_CAPABLE capability for manipulations to that"} {"_id":"doc-en-kubernetes-190e7cb74ae863ccb9377f09b966f4175ceebd7fa641085dac8d4a3cf5d03e6b","title":"","text":"if len(line) == 0 { continue } parts := strings.Split(line, \" \") // expected tc line: // class htb 1:1 root prio 0 rate 1000Kbit ceil 1000Kbit burst 1600b cburst 1600b if len(parts) != 14 { return -1, fmt.Errorf(\"unexpected output from tc: %s (%v)\", scanner.Text(), parts) matches := classShowMatcher.FindStringSubmatch(line) if len(matches) != 2 { return -1, fmt.Errorf(\"unexpected output from tc: %s (%v)\", scanner.Text(), matches) } classes.Insert(parts[2]) classes.Insert(matches[1]) } // Make sure it doesn't go forever"} {"_id":"doc-en-kubernetes-eea9a8fd939a4656f322dc9c917af3aad16b5ee2ec93208130e629e23c6fae7b","title":"","text":"continue } if strings.Contains(line, spec) { parts := strings.Split(filter, \" \") // expected tc line: // filter parent 1: protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1 if len(parts) != 19 { return classAndHandleList, false, fmt.Errorf(\"unexpected output from tc: %s %d (%v)\", filter, len(parts), parts) // `filter parent 1: protocol ip pref 1 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1` (old version) or // `filter parent 1: protocol ip pref 1 u32 chain 0 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1 not_in_hw` (new version) matches := classAndHandleMatcher.FindStringSubmatch(filter) if len(matches) != 3 { return classAndHandleList, false, fmt.Errorf(\"unexpected output from tc: %s %d (%v)\", filter, len(matches), matches) } resultTmp := []string{parts[18], parts[9]} resultTmp := []string{matches[2], matches[1]} classAndHandleList = append(classAndHandleList, resultTmp) } }"} {"_id":"doc-en-kubernetes-a847dfca65c739bc584fe0d2a22a615266ee03a0c1492e3f1b968a93e28de63b","title":"","text":"} } return nil } func (t *tcShaper) deleteInterface(class string) error {"} {"_id":"doc-en-kubernetes-ef8eb55c37cf77bdf42a829689fe2e66c8ae265642b860ed0d6290206d16a949","title":"","text":"filter parent 1: protocol ip pref 1 u32 fh 800::801 order 2049 key ht 800 bkt 0 flowid 1:2 match 01020000/ffff0000 at 16 ` var tcFilterOutputNewVersion = `filter parent 1: protocol ip pref 1 u32 filter parent 1: protocol ip pref 1 u32 chain 0 fh 800: ht divisor 1 filter parent 1: protocol ip pref 1 u32 chain 0 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:1 not_in_hw match ac110002/ffffffff at 16 filter parent 1: protocol ip pref 1 u32 chain 0 fh 800::801 order 2049 key ht 800 bkt 0 flowid 1:2 not_in_hw match 01020000/ffff0000 at 16 ` func TestFindCIDRClass(t *testing.T) { tests := []struct {"} {"_id":"doc-en-kubernetes-57beb88043b8ada625d79b2709afc70fad8ee27498856c8c92f46241adbef3b5","title":"","text":"expectNotFound: true, }, { cidr: \"172.17.0.2/32\", output: tcFilterOutputNewVersion, expectedClass: \"1:1\", expectedHandle: \"800::800\", }, { cidr: \"1.2.3.4/16\", output: tcFilterOutputNewVersion, expectedClass: \"1:2\", expectedHandle: \"800::801\", }, { cidr: \"2.2.3.4/16\", output: tcFilterOutputNewVersion, expectNotFound: true, }, { err: errors.New(\"test error\"), expectErr: true, },"} {"_id":"doc-en-kubernetes-dd23890c2bec414da889039ed5baa78c3c9ec4a6d408e2948cce58948ee742dd","title":"","text":"{ Name: \"etcd\", Image: etcdImage, Command: []string{ \"/usr/local/bin/etcd\", }, }, } d := &apps.Deployment{"} {"_id":"doc-en-kubernetes-d2111722498f7dc714bba7dc1974155bb6aa298098e68bc31b87be976049cf58","title":"","text":"type RegistryList struct { DockerLibraryRegistry string `yaml:\"dockerLibraryRegistry\"` E2eRegistry string `yaml:\"e2eRegistry\"` EtcdRegistry string `yaml:\"etcdRegistry\"` GcRegistry string `yaml:\"gcRegistry\"` PrivateRegistry string `yaml:\"privateRegistry\"` SampleRegistry string `yaml:\"sampleRegistry\"`"} {"_id":"doc-en-kubernetes-603bee5ad10360a01fe053e3c7668557dadec54b7a1d2df618d7f504d5ebb6ae","title":"","text":"registry := RegistryList{ DockerLibraryRegistry: \"docker.io/library\", E2eRegistry: \"gcr.io/kubernetes-e2e-test-images\", EtcdRegistry: \"quay.io/coreos\", GcRegistry: \"k8s.gcr.io\", PrivateRegistry: \"gcr.io/k8s-authenticated-test\", SampleRegistry: \"gcr.io/google-samples\","} {"_id":"doc-en-kubernetes-2762930c574892e0be5184e00ff40bbc0ca84691957599169916d346c1c2863b","title":"","text":"registry = initReg() dockerLibraryRegistry = registry.DockerLibraryRegistry e2eRegistry = registry.E2eRegistry etcdRegistry = registry.EtcdRegistry gcRegistry = registry.GcRegistry // PrivateRegistry is an image repository that requires authentication PrivateRegistry = registry.PrivateRegistry"} {"_id":"doc-en-kubernetes-ce97b4ae32e6f93fe20b4b361003acee57189f284e727eb9f82fb14139348e23","title":"","text":"configs[Dnsutils] = Config{e2eRegistry, \"dnsutils\", \"1.1\"} configs[EchoServer] = Config{e2eRegistry, \"echoserver\", \"2.2\"} configs[EntrypointTester] = Config{e2eRegistry, \"entrypoint-tester\", \"1.0\"} configs[Etcd] = Config{etcdRegistry, \"etcd\", \"v3.3.10\"} configs[Etcd] = Config{gcRegistry, \"etcd\", \"3.3.10\"} configs[Fakegitserver] = Config{e2eRegistry, \"fakegitserver\", \"1.0\"} configs[GBFrontend] = Config{sampleRegistry, \"gb-frontend\", \"v6\"} configs[GBRedisSlave] = Config{sampleRegistry, \"gb-redisslave\", \"v3\"}"} {"_id":"doc-en-kubernetes-babd25160997b59ac04bc99fdb38f75dd7fc6dcd2796ae7c7a3e7ae854e9f9dd","title":"","text":"\"//staging/src/k8s.io/apimachinery/pkg/labels:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/admission:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/admission/initializer:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/util/feature:go_default_library\", \"//staging/src/k8s.io/client-go/informers:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes:go_default_library\", \"//staging/src/k8s.io/client-go/listers/scheduling/v1:go_default_library\", \"//staging/src/k8s.io/component-base/featuregate:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-cc536234b8d66728dca85dd012bb3a26835888c09a06943541e160ddf688f28e","title":"","text":"\"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apiserver/pkg/admission\" genericadmissioninitializers \"k8s.io/apiserver/pkg/admission/initializer\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/informers\" \"k8s.io/client-go/kubernetes\" schedulingv1listers \"k8s.io/client-go/listers/scheduling/v1\" \"k8s.io/component-base/featuregate\" \"k8s.io/kubernetes/pkg/apis/core\" api \"k8s.io/kubernetes/pkg/apis/core\" \"k8s.io/kubernetes/pkg/apis/scheduling\""} {"_id":"doc-en-kubernetes-1721703e308cdb6fbb40dc879b9cc592874f8c27f97a224a8e61413bbad767d1","title":"","text":"// Plugin is an implementation of admission.Interface. type Plugin struct { *admission.Handler client kubernetes.Interface lister schedulingv1listers.PriorityClassLister client kubernetes.Interface lister schedulingv1listers.PriorityClassLister resourceQuotaFeatureGateEnabled bool nonPreemptingPriority bool } var _ admission.MutationInterface = &Plugin{} var _ admission.ValidationInterface = &Plugin{} var _ genericadmissioninitializers.WantsFeatures = &Plugin{} var _ = genericadmissioninitializers.WantsExternalKubeInformerFactory(&Plugin{}) var _ = genericadmissioninitializers.WantsExternalKubeClientSet(&Plugin{})"} {"_id":"doc-en-kubernetes-a98289c1ff2a15c2f71d96274f28b96a6ff618d3155e90620a0b44189579d9fd","title":"","text":"return nil } // InspectFeatureGates allows setting bools without taking a dep on a global variable func (p *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate) { p.nonPreemptingPriority = featureGates.Enabled(features.NonPreemptingPriority) p.resourceQuotaFeatureGateEnabled = featureGates.Enabled(features.ResourceQuotaScopeSelectors) } // SetExternalKubeClientSet implements the WantsInternalKubeClientSet interface. func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) { p.client = client"} {"_id":"doc-en-kubernetes-200bc77878738e9482f44b19582ff75a1cce821d66bb7f6b133188d70494dd17","title":"","text":"if len(a.GetSubresource()) != 0 { return nil } switch a.GetResource().GroupResource() { case podResource: if operation == admission.Create || operation == admission.Update {"} {"_id":"doc-en-kubernetes-302fe6e620569b24224633b6110958a3721109ad2798c901642b8f1893e8cf9a","title":"","text":"pod.Spec.PriorityClassName = pcName } else { pcName := pod.Spec.PriorityClassName if !priorityClassPermittedInNamespace(pcName, a.GetNamespace()) { return admission.NewForbidden(a, fmt.Errorf(\"pods with %v priorityClass is not permitted in %v namespace\", pcName, a.GetNamespace())) // If ResourceQuotaScopeSelectors is enabled, we should let pods with critical priorityClass to be created // any namespace where administrator wants it to be created. if !p.resourceQuotaFeatureGateEnabled { if !priorityClassPermittedInNamespace(pcName, a.GetNamespace()) { return admission.NewForbidden(a, fmt.Errorf(\"pods with %v priorityClass is not permitted in %v namespace\", pcName, a.GetNamespace())) } } // Try resolving the priority class name."} {"_id":"doc-en-kubernetes-1274fd1ee690ff14f336190b8a973d5dd5cc1738e1730c641489af47d210b726","title":"","text":"} pod.Spec.Priority = &priority if utilfeature.DefaultFeatureGate.Enabled(features.NonPreemptingPriority) { if p.nonPreemptingPriority { var corePolicy core.PreemptionPolicy if preemptionPolicy != nil { corePolicy = core.PreemptionPolicy(*preemptionPolicy)"} {"_id":"doc-en-kubernetes-899782e7541d9ff807b5e5112cbc8b7957cd127ed2b956221f588f7ebb8ab486","title":"","text":"[]*scheduling.PriorityClass{systemClusterCritical}, *pods[7], scheduling.SystemCriticalPriority, true, false, nil, }, {"} {"_id":"doc-en-kubernetes-829a1e348d8603fb00fb7f9deb7b6b690e7223c81e5cf7b819ee712f0aaa178e","title":"","text":"for _, test := range tests { klog.V(4).Infof(\"starting test %q\", test.name) ctrl := NewPlugin() ctrl.resourceQuotaFeatureGateEnabled = true ctrl.nonPreemptingPriority = true // Add existing priority classes. if err := addPriorityClasses(ctrl, test.existingClasses); err != nil { t.Errorf(\"Test %q: unable to add object to informer: %v\", test.name, err)"} {"_id":"doc-en-kubernetes-25fbb17423206d4f524e220aa0381529ce007971ae414b9d8922e990af46af21","title":"","text":") err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(context.TODO(), attrs, nil) klog.Infof(\"Got %v\", err) if !test.expectError { if err != nil { t.Errorf(\"Test %q: unexpected error received: %v\", test.name, err)"} {"_id":"doc-en-kubernetes-9e1e5a8991d6853968a333f02a350a5828fb07cf0517ea7b095351f12ed3e01e","title":"","text":"# Taint Windows nodes by default to prevent Linux workloads from being # scheduled onto them. WINDOWS_NODE_TAINTS=\"${WINDOWS_NODE_TAINTS:-node.kubernetes.io/os=win1809:NoSchedule}\" # Whether to set up a private GCE cluster, i.e. a cluster where nodes have only private IPs. GCE_PRIVATE_CLUSTER=\"${KUBE_GCE_PRIVATE_CLUSTER:-false}\" "} {"_id":"doc-en-kubernetes-e29a36dabfd7d77f5302936a09954a64ba96db2e2de85f01e04d6f65387f12f5","title":"","text":"if [[ \"${enable_ip_alias}\" == 'true' ]]; then ret=\"--network-interface\" ret=\"${ret} network=${networkURL}\" # If address is omitted, instance will not receive an external IP. ret=\"${ret},address=${address:-}\" if [[ \"${address:-}\" == \"no-address\" ]]; then ret=\"${ret},no-address\" else ret=\"${ret},address=${address:-}\" fi ret=\"${ret},subnet=${subnetURL}\" ret=\"${ret},aliases=pods-default:${alias_size}\" ret=\"${ret} --no-can-ip-forward\""} {"_id":"doc-en-kubernetes-1bd753ff12c4fca753d8762bb06db4aed5a651744db3d53f904d3edf21b4ec49","title":"","text":"fi ret=\"${ret} --can-ip-forward\" if [[ -n ${address:-} ]]; then if [[ -n ${address:-} ]] && [[ \"$address\" != \"no-address\" ]]; then ret=\"${ret} --address ${address}\" fi fi"} {"_id":"doc-en-kubernetes-b5463ff837437a3214e8ef13d8bb5c75e219020195f343baec12be1c7100bc49","title":"","text":"fi fi local address=\"\" if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then address=\"no-address\" fi local network=$(make-gcloud-network-argument \"${NETWORK_PROJECT}\" \"${REGION}\" \"${NETWORK}\" \"${SUBNETWORK:-}\" \"\" \"${address}\" \"${ENABLE_IP_ALIASES:-}\" \"${IP_ALIAS_SIZE:-}\")"} {"_id":"doc-en-kubernetes-b560b7f0e903a38faebb07be908351d9cabe8543117eaedbe2cc7217f6f9109f","title":"","text":"create-network create-subnetworks detect-subnetworks create-cloud-nat-router write-cluster-location write-cluster-name create-autoscaler-config"} {"_id":"doc-en-kubernetes-247c52f83b2861984208e25d866ff43667ce8a5f47f367b0c49905df07855178","title":"","text":"echo \"${color_red}Could not find subnetwork with region ${REGION}, network ${NETWORK}, and project ${NETWORK_PROJECT}\" } # Sets up Cloud NAT for the network. # Assumed vars: # NETWORK_PROJECT # REGION # NETWORK function create-cloud-nat-router() { if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then gcloud compute routers create \"$NETWORK-nat-router\" --project $NETWORK_PROJECT --region $REGION --network $NETWORK gcloud compute routers nats create \"$NETWORK-nat-config\" --project $NETWORK_PROJECT --router-region $REGION --router \"$NETWORK-nat-router\" --nat-all-subnet-ip-ranges --auto-allocate-nat-external-ips fi } function delete-all-firewall-rules() { if fws=$(gcloud compute firewall-rules list --project \"${NETWORK_PROJECT}\" --filter=\"network=${NETWORK}\" --format=\"value(name)\"); then echo \"Deleting firewall rules remaining in network ${NETWORK}: ${fws}\""} {"_id":"doc-en-kubernetes-03c6636cabd1f5dc22ee0451257778d4bedfac72fbb21499f93c40a54bbe8a46","title":"","text":"fi } function delete-cloud-nat-router() { if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then if [[ -n $(gcloud compute routers describe --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" \"${NETWORK}-nat-router\" --format='value(name)' 2>/dev/null || true) ]]; then echo \"Deleting Cloud NAT router...\" gcloud compute routers delete --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" --quiet \"${NETWORK}-nat-router\" fi fi } function delete-subnetworks() { # If running in custom mode network we need to delete subnets manually. mode=\"$(check-network-mode)\""} {"_id":"doc-en-kubernetes-1550434022bf7ecc78fcc0fe8bec7f9822c93fa62f32f34f3100535988138f01","title":"","text":"\"${NETWORK}-default-internal\" # Pre-1.5 clusters if [[ \"${KUBE_DELETE_NETWORK}\" == \"true\" ]]; then delete-cloud-nat-router # Delete all remaining firewall rules in the network. delete-all-firewall-rules || true delete-subnetworks || true"} {"_id":"doc-en-kubernetes-96eb5c06dde83648c8333c022918f71b38c805feb8cd642774c1fbfe4a8c5478","title":"","text":"return 1 fi if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then if gcloud compute routers describe --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" \"${NETWORK}-nat-router\" &>/dev/null; then KUBE_RESOURCE_FOUND=\"Cloud NAT router\" return 1 fi fi # No resources found. return 0 }"} {"_id":"doc-en-kubernetes-940386b6c522679b990d5f7fadeb1b62fc25bd5b14acfe2d17b7ea7267758640","title":"","text":"func GetNodeAddresses(node *v1.Node, addressType v1.NodeAddressType) (ips []string) { for j := range node.Status.Addresses { nodeAddress := &node.Status.Addresses[j] if nodeAddress.Type == addressType { if nodeAddress.Type == addressType && nodeAddress.Address != \"\" { ips = append(ips, nodeAddress.Address) } }"} {"_id":"doc-en-kubernetes-a488ab7256b4fcb0fadbded6d0bc5f28418fdb73d767c40b027b5e6964ad7b7c","title":"","text":"if host == \"\" { // No external IPs were found, let's try to use internal as plan B for _, a := range node.Status.Addresses { if a.Type == v1.NodeInternalIP { if a.Type == v1.NodeInternalIP && a.Address != \"\" { host = net.JoinHostPort(a.Address, sshPort) break }"} {"_id":"doc-en-kubernetes-51bbd77076a9564d5ea6ba2d43ab96ecbd50c3cad61418190683694829d5e355","title":"","text":"hosts := []string{} for _, n := range nodelist.Items { for _, addr := range n.Status.Addresses { if addr.Type == addrType { if addr.Type == addrType && addr.Address != \"\" { hosts = append(hosts, addr.Address) break }"} {"_id":"doc-en-kubernetes-105f5b742976b63369331fb97c69c060e0115aa70674bd42603555ef4ead905f","title":"","text":"Logf(\"Getting external IP address for %s\", node.Name) host := \"\" for _, a := range node.Status.Addresses { if a.Type == v1.NodeExternalIP { if a.Type == v1.NodeExternalIP && a.Address != \"\" { host = net.JoinHostPort(a.Address, sshPort) break }"} {"_id":"doc-en-kubernetes-d13cfe27e85be7c03b8ac4b2d96ca7301f047435d087879411193eb2c7788822","title":"","text":"return err } disks := *vm.StorageProfile.DataDisks disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) copy(disks, *vm.StorageProfile.DataDisks) if isManagedDisk { disks = append(disks, compute.DataDisk{"} {"_id":"doc-en-kubernetes-3f5ca261e31260e9233afec05a1a92d22334fbc84ee11d575c70d81661575de8","title":"","text":"return nil, err } disks := *vm.StorageProfile.DataDisks disks := make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) copy(disks, *vm.StorageProfile.DataDisks) bFoundDisk := false for i, disk := range disks { if disk.Lun != nil && (disk.Name != nil && diskName != \"\" && *disk.Name == diskName) ||"} {"_id":"doc-en-kubernetes-6438858e589a7fdc6e3102c0d63cfebff94c5e2edc660b17deea6ea4f17088e3","title":"","text":"disks := []compute.DataDisk{} if vm.StorageProfile != nil && vm.StorageProfile.DataDisks != nil { disks = *vm.StorageProfile.DataDisks disks = make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) copy(disks, *vm.StorageProfile.DataDisks) } if isManagedDisk { disks = append(disks,"} {"_id":"doc-en-kubernetes-f97b7a908e65cc2d0b5c1fca24963900a2f332a24b44932a3e012f4a1c345014","title":"","text":"disks := []compute.DataDisk{} if vm.StorageProfile != nil && vm.StorageProfile.DataDisks != nil { disks = *vm.StorageProfile.DataDisks disks = make([]compute.DataDisk, len(*vm.StorageProfile.DataDisks)) copy(disks, *vm.StorageProfile.DataDisks) } bFoundDisk := false for i, disk := range disks {"} {"_id":"doc-en-kubernetes-328304f9b747e85e65dce16abc6964d2edd7a09e361f7c74f8b7bc9a127395e2","title":"","text":"return newRS, allOldRSs, nil } const ( // limit revision history length to 100 element (~2000 chars) maxRevHistoryLengthInChars = 2000 ) // Returns a replica set that matches the intent of the given deployment. Returns nil if the new replica set doesn't exist yet. // 1. Get existing new RS (the RS that the given deployment targets, whose pod template is the same as deployment's). // 2. If there's existing new RS, update its revision number if it's smaller than (maxOldRevision + 1), where maxOldRevision is the max revision number among all old RSes."} {"_id":"doc-en-kubernetes-f63811f4a64ef6f671ec5bc5e10815b0bfe04e40023dcbbbb168931b2b564d81","title":"","text":"rsCopy := existingNewRS.DeepCopy() // Set existing new replica set's annotation annotationsUpdated := deploymentutil.SetNewReplicaSetAnnotations(d, rsCopy, newRevision, true) annotationsUpdated := deploymentutil.SetNewReplicaSetAnnotations(d, rsCopy, newRevision, true, maxRevHistoryLengthInChars) minReadySecondsNeedsUpdate := rsCopy.Spec.MinReadySeconds != d.Spec.MinReadySeconds if annotationsUpdated || minReadySecondsNeedsUpdate { rsCopy.Spec.MinReadySeconds = d.Spec.MinReadySeconds"} {"_id":"doc-en-kubernetes-0cdfb3bf37e3f0ba5d975ca6a7600b19e3e547977eeebe821284a093ff044973","title":"","text":"*(newRS.Spec.Replicas) = newReplicasCount // Set new replica set's annotation deploymentutil.SetNewReplicaSetAnnotations(d, &newRS, newRevision, false) deploymentutil.SetNewReplicaSetAnnotations(d, &newRS, newRevision, false, maxRevHistoryLengthInChars) // Create the new ReplicaSet. If it already exists, then we need to check for possible // hash collisions. If there is any other error, we need to report it in the status of // the Deployment."} {"_id":"doc-en-kubernetes-b1906478cd975e82240ea1fa8fcdfbb2d9baad35b1e47a4d079a8faddc17e226","title":"","text":"// SetNewReplicaSetAnnotations sets new replica set's annotations appropriately by updating its revision and // copying required deployment annotations to it; it returns true if replica set's annotation is changed. func SetNewReplicaSetAnnotations(deployment *apps.Deployment, newRS *apps.ReplicaSet, newRevision string, exists bool) bool { func SetNewReplicaSetAnnotations(deployment *apps.Deployment, newRS *apps.ReplicaSet, newRevision string, exists bool, revHistoryLimitInChars int) bool { // First, copy deployment's annotations (except for apply and revision annotations) annotationChanged := copyDeploymentAnnotationsToReplicaSet(deployment, newRS) // Then, update replica set's revision annotation"} {"_id":"doc-en-kubernetes-0f45c995d654c9045895fc4e575da593a3063b5bfff81d17900af495ca3508ef","title":"","text":"// If a revision annotation already existed and this replica set was updated with a new revision // then that means we are rolling back to this replica set. We need to preserve the old revisions // for historical information. if ok && annotationChanged { if ok && oldRevisionInt < newRevisionInt { revisionHistoryAnnotation := newRS.Annotations[RevisionHistoryAnnotation] oldRevisions := strings.Split(revisionHistoryAnnotation, \",\") if len(oldRevisions[0]) == 0 { newRS.Annotations[RevisionHistoryAnnotation] = oldRevision } else { oldRevisions = append(oldRevisions, oldRevision) newRS.Annotations[RevisionHistoryAnnotation] = strings.Join(oldRevisions, \",\") totalLen := len(revisionHistoryAnnotation) + len(oldRevision) + 1 // index for the starting position in oldRevisions start := 0 for totalLen > revHistoryLimitInChars && start < len(oldRevisions) { totalLen = totalLen - len(oldRevisions[start]) - 1 start++ } if totalLen <= revHistoryLimitInChars { oldRevisions = append(oldRevisions[start:], oldRevision) newRS.Annotations[RevisionHistoryAnnotation] = strings.Join(oldRevisions, \",\") } else { klog.Warningf(\"Not appending revision due to length limit of %v reached\", revHistoryLimitInChars) } } } // If the new replica set is about to be created, we need to add replica annotations to it."} {"_id":"doc-en-kubernetes-9866d56103f34ff3c1ef6659c313cc8a66b1986016f282c34149d3c50980a4f0","title":"","text":"//Test Case 1: Check if anotations are copied properly from deployment to RS t.Run(\"SetNewReplicaSetAnnotations\", func(t *testing.T) { //Try to set the increment revision from 1 through 20 for i := 0; i < 20; i++ { //Try to set the increment revision from 11 through 20 for i := 10; i < 20; i++ { nextRevision := fmt.Sprintf(\"%d\", i+1) SetNewReplicaSetAnnotations(&tDeployment, &tRS, nextRevision, true) SetNewReplicaSetAnnotations(&tDeployment, &tRS, nextRevision, true, 5) //Now the ReplicaSets Revision Annotation should be i+1 if i >= 12 { expectedHistoryAnnotation := fmt.Sprintf(\"%d,%d\", i-1, i) if tRS.Annotations[RevisionHistoryAnnotation] != expectedHistoryAnnotation { t.Errorf(\"Revision History Expected=%s Obtained=%s\", expectedHistoryAnnotation, tRS.Annotations[RevisionHistoryAnnotation]) } } if tRS.Annotations[RevisionAnnotation] != nextRevision { t.Errorf(\"Revision Expected=%s Obtained=%s\", nextRevision, tRS.Annotations[RevisionAnnotation]) }"} {"_id":"doc-en-kubernetes-2ef1fe16c8de0656f8469dcafcde90ca7177dbf8a16a0bc13845a7e93f501182","title":"","text":"} // writeLogs writes logs into stdout, stderr. func (w *logWriter) write(msg *logMessage) error { func (w *logWriter) write(msg *logMessage, addPrefix bool) error { if msg.timestamp.Before(w.opts.since) { // Skip the line because it's older than since return nil } line := msg.log if w.opts.timestamp { if w.opts.timestamp && addPrefix { prefix := append([]byte(msg.timestamp.Format(timeFormatOut)), delimiter[0]) line = append(prefix, line...) }"} {"_id":"doc-en-kubernetes-65e7dd76a2314eee20d95c7492c7d6529e4ec0aca6cf928e5a0681803833ab63","title":"","text":"var watcher *fsnotify.Watcher var parse parseFunc var stop bool isNewLine := true found := true writer := newLogWriter(stdout, stderr, opts) msg := &logMessage{}"} {"_id":"doc-en-kubernetes-00d2dcce31529e985e50075d48baaedcbd37ac6b162b70c0e7d14a7db1ac568c","title":"","text":"continue } // Write the log line into the stream. if err := writer.write(msg); err != nil { if err := writer.write(msg, isNewLine); err != nil { if err == errMaximumWrite { klog.V(2).InfoS(\"Finished parsing log file, hit bytes limit\", \"path\", path, \"limit\", opts.bytes) return nil"} {"_id":"doc-en-kubernetes-7cd8b49c5631068e4520ae09850148fcd0c464b3ce63cd7a8ec5a863c42825e7","title":"","text":"if limitedMode { limitedNum-- } if len(msg.log) > 0 { isNewLine = msg.log[len(msg.log)-1] == eol[0] } else { isNewLine = true } } }"} {"_id":"doc-en-kubernetes-f55c0256574318aa178b0dae1548fdc61e2a308d3fb7ed09f76dbcb9ebf1e6ba","title":"","text":"package logs import ( \"bufio\" \"bytes\" \"context\" \"fmt\" \"io\" \"io/ioutil\" \"os\" \"testing\" \"time\""} {"_id":"doc-en-kubernetes-52817c8519fe40c88f58fb826244009bc22e2b2f4e5cb87925350f8f17c148c9","title":"","text":"stdoutBuf := bytes.NewBuffer(nil) stderrBuf := bytes.NewBuffer(nil) w := newLogWriter(stdoutBuf, stderrBuf, &LogOptions{since: test.since, timestamp: test.timestamp, bytes: -1}) err := w.write(msg) err := w.write(msg, true) assert.NoError(t, err) assert.Equal(t, test.expectStdout, stdoutBuf.String()) assert.Equal(t, test.expectStderr, stderrBuf.String())"} {"_id":"doc-en-kubernetes-c58896b042f4e8904f287db80ceec6c0a1dabba41113fabbdcaf56821cf3730d","title":"","text":"w := newLogWriter(stdoutBuf, stderrBuf, &LogOptions{timestamp: test.timestamp, bytes: int64(test.bytes)}) for i := 0; i < test.stdoutLines; i++ { msg.stream = runtimeapi.Stdout if err := w.write(msg); err != nil { if err := w.write(msg, true); err != nil { assert.EqualError(t, err, errMaximumWrite.Error()) } } for i := 0; i < test.stderrLines; i++ { msg.stream = runtimeapi.Stderr if err := w.write(msg); err != nil { if err := w.write(msg, true); err != nil { assert.EqualError(t, err, errMaximumWrite.Error()) } }"} {"_id":"doc-en-kubernetes-f657a8cf5ec84653406e5b5341ac48a37aac2d5c9658a2d50139551f941e349f","title":"","text":"assert.Equal(t, test.expectStderr, stderrBuf.String()) } } func TestReadLogsLimitsWithTimestamps(t *testing.T) { logLineFmt := \"2022-10-29T16:10:22.592603036-05:00 stdout P %vn\" logLineNewLine := \"2022-10-29T16:10:22.592603036-05:00 stdout F n\" tmpfile, err := ioutil.TempFile(\"\", \"log.*.txt\") assert.NoError(t, err) count := 10000 for i := 0; i < count; i++ { tmpfile.WriteString(fmt.Sprintf(logLineFmt, i)) } tmpfile.WriteString(logLineNewLine) for i := 0; i < count; i++ { tmpfile.WriteString(fmt.Sprintf(logLineFmt, i)) } tmpfile.WriteString(logLineNewLine) // two lines are in the buffer defer os.Remove(tmpfile.Name()) // clean up assert.NoError(t, err) tmpfile.Close() var buf bytes.Buffer w := io.MultiWriter(&buf) err = ReadLogs(context.Background(), tmpfile.Name(), \"\", &LogOptions{tail: -1, bytes: -1, timestamp: true}, nil, w, w) assert.NoError(t, err) lineCount := 0 scanner := bufio.NewScanner(bytes.NewReader(buf.Bytes())) for scanner.Scan() { lineCount++ // Split the line ts, logline, _ := bytes.Cut(scanner.Bytes(), []byte(\" \")) // Verification // 1. The timestamp should exist // 2. The last item in the log should be 9999 _, err = time.Parse(time.RFC3339, string(ts)) assert.NoError(t, err, \"timestamp not found\") assert.Equal(t, true, bytes.HasSuffix(logline, []byte(\"9999\")), \"is the complete log found\") } assert.Equal(t, 2, lineCount, \"should have two lines\") } "} {"_id":"doc-en-kubernetes-a52b0f602182f1cba54369255c5800ba2758c278a1c2e831ca3db9efeb885fd5","title":"","text":"volumeToAttach.VolumeSpec, volumeToAttach.NodeName) if attachErr != nil { uncertainNode := volumeToAttach.NodeName if derr, ok := attachErr.(*volerr.DanglingAttachError); ok { addErr := actualStateOfWorld.MarkVolumeAsAttached( v1.UniqueVolumeName(\"\"), originalSpec, derr.CurrentNode, derr.DevicePath) if addErr != nil { klog.Errorf(\"AttachVolume.MarkVolumeAsAttached failed to fix dangling volume error for volume %q with %s\", volumeToAttach.VolumeName, addErr) } } else { addErr := actualStateOfWorld.MarkVolumeAsUncertain( v1.UniqueVolumeName(\"\"), originalSpec, volumeToAttach.NodeName) if addErr != nil { klog.Errorf(\"AttachVolume.MarkVolumeAsUncertain fail to add the volume %q to actual state with %s\", volumeToAttach.VolumeName, addErr) } uncertainNode = derr.CurrentNode } addErr := actualStateOfWorld.MarkVolumeAsUncertain( v1.UniqueVolumeName(\"\"), originalSpec, uncertainNode) if addErr != nil { klog.Errorf(\"AttachVolume.MarkVolumeAsUncertain fail to add the volume %q to actual state with %s\", volumeToAttach.VolumeName, addErr) } // On failure, return error. Caller will log and retry. return volumeToAttach.GenerateError(\"AttachVolume.Attach failed\", attachErr) }"} {"_id":"doc-en-kubernetes-d371c12abb70b5252cb7bf5c9b36a988eaf03f5da42b699991b76ce561b06fcd","title":"","text":"metricsGrabber, err := metrics.NewMetricsGrabber(c, nil, true, false, true, false, false) if err != nil { framework.Failf(\"Error creating metrics grabber : %v\", err) framework.ExpectNoError(err, \"Error creating metrics grabber: %v\", err) } if !metricsGrabber.HasRegisteredMaster() { framework.Skipf(\"Environment does not support getting controller-manager metrics - skipping\") e2elog.Logf(\"Warning: Environment does not support getting controller-manager metrics\") return opCounts{} } controllerMetrics, err := metricsGrabber.GrabFromControllerManager()"} {"_id":"doc-en-kubernetes-f2f9ab3c88d10b59155790ce08c6388f7c277878a9a094bdc44f5baac93797d3","title":"","text":"// Now do the more expensive test initialization. l.config, l.testCleanup = driver.PrepareTest(f) l.intreeOps, l.migratedOps = getMigrationVolumeOpCounts(f.ClientSet, dInfo.InTreePluginName) l.resource = createGenericVolumeTestResource(driver, l.config, pattern) if l.resource.volSource == nil { framework.Skipf(\"Driver %q does not define volumeSource - skipping\", dInfo.Name) } l.intreeOps, l.migratedOps = getMigrationVolumeOpCounts(f.ClientSet, dInfo.InTreePluginName) } cleanup := func() {"} {"_id":"doc-en-kubernetes-1a17059d0df9daf9adceaba8553dae6192000f5344ab8b2f50f7e0a5b18e5b46","title":"","text":"import ( \"fmt\" \"sync\" \"time\" apierrors \"k8s.io/apimachinery/pkg/api/errors\""} {"_id":"doc-en-kubernetes-24369a27e11af5be852c63e08cb75c2f96dd2688ef44e60cdca6281921c4e271","title":"","text":"syncFn func(key string) error queue workqueue.RateLimitingInterface // last generation this controller updated the condition per CRD name (to avoid two // different version of the apiextensions-apiservers in HA to fight for the right message) lastSeenGenerationLock sync.Mutex lastSeenGeneration map[string]int64 } // NewConditionController constructs a non-structural schema condition controller."} {"_id":"doc-en-kubernetes-ecdaaae57704eab766af05914feececa71dcd4f666e24b3e25c86c2b64ed4ca1","title":"","text":"crdClient client.CustomResourceDefinitionsGetter, ) *ConditionController { c := &ConditionController{ crdClient: crdClient, crdLister: crdInformer.Lister(), crdSynced: crdInformer.Informer().HasSynced, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"non_structural_schema_condition_controller\"), crdClient: crdClient, crdLister: crdInformer.Lister(), crdSynced: crdInformer.Informer().HasSynced, queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), \"non_structural_schema_condition_controller\"), lastSeenGeneration: map[string]int64{}, } crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: c.addCustomResourceDefinition, UpdateFunc: c.updateCustomResourceDefinition, DeleteFunc: nil, DeleteFunc: c.deleteCustomResourceDefinition, }) c.syncFn = c.sync"} {"_id":"doc-en-kubernetes-03c7ee7a4903650baea4dfea705785feb4085ce4281fa5e17c45ea1598c7d8b0","title":"","text":"return err } // avoid repeated calculation for the same generation c.lastSeenGenerationLock.Lock() lastSeen, seenBefore := c.lastSeenGeneration[inCustomResourceDefinition.Name] c.lastSeenGenerationLock.Unlock() if seenBefore && inCustomResourceDefinition.Generation <= lastSeen { return nil } // check old condition cond := calculateCondition(inCustomResourceDefinition) old := apiextensions.FindCRDCondition(inCustomResourceDefinition, apiextensions.NonStructuralSchema)"} {"_id":"doc-en-kubernetes-8c84f5864cf7b1da4c5803774a0f2c8af2080413baaa32467e4a809624b737a5","title":"","text":"return err } // store generation in order to avoid repeated updates for the same generation (and potential // fights of API server in HA environments). c.lastSeenGenerationLock.Lock() defer c.lastSeenGenerationLock.Unlock() c.lastSeenGeneration[crd.Name] = crd.Generation return nil }"} {"_id":"doc-en-kubernetes-e9eb45c9cf75e6b143c476f590e765ad52e44cb10fa58c43e0fb179f0a8e94e2","title":"","text":"klog.V(4).Infof(\"Updating %s\", castObj.Name) c.enqueue(castObj) } func (c *ConditionController) deleteCustomResourceDefinition(obj interface{}) { castObj, ok := obj.(*apiextensions.CustomResourceDefinition) if !ok { tombstone, ok := obj.(cache.DeletedFinalStateUnknown) if !ok { klog.Errorf(\"Couldn't get object from tombstone %#v\", obj) return } castObj, ok = tombstone.Obj.(*apiextensions.CustomResourceDefinition) if !ok { klog.Errorf(\"Tombstone contained object that is not expected %#v\", obj) return } } c.lastSeenGenerationLock.Lock() defer c.lastSeenGenerationLock.Unlock() delete(c.lastSeenGeneration, castObj.Name) } "} {"_id":"doc-en-kubernetes-f678fb6c3fd362533360349631b4a30f2d2786131daebac7aea2b9d87b6a09ec","title":"","text":"\"//test/e2e/framework/providers/vsphere:go_default_library\", \"//test/e2e/framework/testfiles:go_default_library\", \"//test/e2e/manifest:go_default_library\", \"//test/e2e/reporters:go_default_library\", \"//test/utils:go_default_library\", \"//vendor/github.com/onsi/ginkgo:go_default_library\", \"//vendor/github.com/onsi/ginkgo/config:go_default_library\","} {"_id":"doc-en-kubernetes-541ad544ed4883dcab5d56330719f4469df161d59985820551a2288834ed0cd4","title":"","text":"\"//test/e2e/network:all-srcs\", \"//test/e2e/node:all-srcs\", \"//test/e2e/perftype:all-srcs\", \"//test/e2e/reporters:all-srcs\", \"//test/e2e/scheduling:all-srcs\", \"//test/e2e/servicecatalog:all-srcs\", \"//test/e2e/storage:all-srcs\","} {"_id":"doc-en-kubernetes-903736c0126531fa7bbc50203103ac2a8eeea61037cf5e3d49c8713e192d21e4","title":"","text":"e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" \"k8s.io/kubernetes/test/e2e/manifest\" e2ereporters \"k8s.io/kubernetes/test/e2e/reporters\" testutils \"k8s.io/kubernetes/test/utils\" utilnet \"k8s.io/utils/net\""} {"_id":"doc-en-kubernetes-3cc7a1f4f95530e4bb8e9ad02986b2018952f09e79604cb1fbbc7f755f16d10e","title":"","text":"r = append(r, reporters.NewJUnitReporter(path.Join(framework.TestContext.ReportDir, fmt.Sprintf(\"junit_%v%02d.xml\", framework.TestContext.ReportPrefix, config.GinkgoConfig.ParallelNode)))) } } klog.Infof(\"Starting e2e run %q on Ginkgo node %d\", framework.RunID, config.GinkgoConfig.ParallelNode) // Stream the progress to stdout and optionally a URL accepting progress updates. r = append(r, e2ereporters.NewProgressReporter(framework.TestContext.ProgressReportURL)) klog.Infof(\"Starting e2e run %q on Ginkgo node %d\", framework.RunID, config.GinkgoConfig.ParallelNode) ginkgo.RunSpecsWithDefaultAndCustomReporters(t, \"Kubernetes e2e suite\", r) }"} {"_id":"doc-en-kubernetes-c3c90f48373de8a74a7f119d5a229b7731cd12c65ca6a8d4300f0a4b109839f8","title":"","text":"// NonblockingTaints is the comma-delimeted string given by the user to specify taints which should not stop the test framework from running tests. NonblockingTaints string // ProgressReportURL is the URL which progress updates will be posted to as tests complete. If empty, no updates are sent. ProgressReportURL string } // NodeKillerConfig describes configuration of NodeKiller -- a utility to"} {"_id":"doc-en-kubernetes-eff39d525b15e762624a1bd4b4d8a86f548dc8dfee1c932b890dacfa0c45cf64","title":"","text":"flags.BoolVar(&TestContext.ListImages, \"list-images\", false, \"If true, will show list of images used for runnning tests.\") flags.StringVar(&TestContext.KubectlPath, \"kubectl-path\", \"kubectl\", \"The kubectl binary to use. For development, you might use 'cluster/kubectl.sh' here.\") flags.StringVar(&TestContext.ProgressReportURL, \"progress-report-url\", \"\", \"The URL to POST progress updates to as the suite runs to assist in aiding integrations. If empty, no messages sent.\") } // RegisterClusterFlags registers flags specific to the cluster e2e test suite."} {"_id":"doc-en-kubernetes-1ab2209f78d94eb3b577bfb6b308dd15487de67ae1a559adf34188e61e9ec05b","title":"","text":" load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\") go_library( name = \"go_default_library\", srcs = [\"progress.go\"], importpath = \"k8s.io/kubernetes/test/e2e/reporters\", visibility = [\"//visibility:public\"], deps = [ \"//vendor/github.com/onsi/ginkgo/config:go_default_library\", \"//vendor/github.com/onsi/ginkgo/types:go_default_library\", \"//vendor/k8s.io/klog:go_default_library\", ], ) filegroup( name = \"package-srcs\", srcs = glob([\"**\"]), tags = [\"automanaged\"], visibility = [\"//visibility:private\"], ) filegroup( name = \"all-srcs\", srcs = [\":package-srcs\"], tags = [\"automanaged\"], visibility = [\"//visibility:public\"], ) "} {"_id":"doc-en-kubernetes-c0a2a2a4db66a4a36a5565f6b5c4cac9098c01de8aec4f86aae990b79c0fe559","title":"","text":" /* Copyright 2019 The Kubernetes Authors. 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. */ package reporters import ( \"bytes\" \"encoding/json\" \"fmt\" \"io/ioutil\" \"net/http\" \"strings\" \"time\" \"k8s.io/klog\" \"github.com/onsi/ginkgo/config\" \"github.com/onsi/ginkgo/types\" ) // ProgressReporter is a ginkgo reporter which tracks the total number of tests to be run/passed/failed/skipped. // As new tests are completed it updates the values and prints them to stdout and optionally, sends the updates // to the configured URL. type ProgressReporter struct { LastMsg string `json:\"msg\"` TestsTotal int `json:\"total\"` TestsCompleted int `json:\"completed\"` TestsSkipped int `json:\"skipped\"` TestsFailed int `json:\"failed\"` Failures []string `json:\"failures,omitempty\"` progressURL string client *http.Client } // NewProgressReporter returns a progress reporter which posts updates to the given URL. func NewProgressReporter(progressReportURL string) *ProgressReporter { rep := &ProgressReporter{ Failures: []string{}, progressURL: progressReportURL, } if len(progressReportURL) > 0 { rep.client = &http.Client{ Timeout: time.Second * 10, } } return rep } // SpecSuiteWillBegin is invoked by ginkgo when the suite is about to start and is the first point in which we can // antipate the number of tests which will be run. func (reporter *ProgressReporter) SpecSuiteWillBegin(cfg config.GinkgoConfigType, summary *types.SuiteSummary) { reporter.TestsTotal = summary.NumberOfSpecsThatWillBeRun reporter.LastMsg = \"Test Suite starting\" reporter.sendUpdates() } // SpecSuiteDidEnd is the last method invoked by Ginkgo after all the specs are run. func (reporter *ProgressReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { reporter.LastMsg = \"Test Suite completed\" reporter.sendUpdates() } // SpecDidComplete is invoked by Ginkgo each time a spec is completed (including skipped specs). func (reporter *ProgressReporter) SpecDidComplete(specSummary *types.SpecSummary) { testname := strings.Join(specSummary.ComponentTexts[1:], \" \") switch specSummary.State { case types.SpecStateFailed: if len(specSummary.ComponentTexts) > 0 { reporter.Failures = append(reporter.Failures, testname) } else { reporter.Failures = append(reporter.Failures, \"Unknown test name\") } reporter.TestsFailed++ reporter.LastMsg = fmt.Sprintf(\"FAILED %v\", testname) case types.SpecStatePassed: reporter.TestsCompleted++ reporter.LastMsg = fmt.Sprintf(\"PASSED %v\", testname) case types.SpecStateSkipped: reporter.TestsSkipped++ return default: return } reporter.sendUpdates() } // sendUpdates serializes the current progress and prints it to stdout and also posts it to the configured endpoint if set. func (reporter *ProgressReporter) sendUpdates() { b := reporter.serialize() fmt.Println(string(b)) go reporter.postProgressToURL(b) } func (reporter *ProgressReporter) postProgressToURL(b []byte) { // If a progressURL and client is set/available then POST to it. Noop otherwise. if reporter.client == nil || len(reporter.progressURL) == 0 { return } resp, err := reporter.client.Post(reporter.progressURL, \"application/json\", bytes.NewReader(b)) if err != nil { klog.Errorf(\"Failed to post progress update to %v: %v\", reporter.progressURL, err) return } if resp.StatusCode >= 400 { klog.Errorf(\"Unexpected response when posting progress update to %v: %v\", reporter.progressURL, resp.StatusCode) if resp.Body != nil { defer resp.Body.Close() respBody, err := ioutil.ReadAll(resp.Body) if err != nil { klog.Errorf(\"Failed to read response body from posting progress: %v\", err) return } klog.Errorf(\"Response body from posting progress update: %v\", respBody) } return } } func (reporter *ProgressReporter) serialize() []byte { b, err := json.Marshal(reporter) if err != nil { return []byte(fmt.Sprintf(`{\"msg\":\"%v\", \"error\":\"%v\"}`, reporter.LastMsg, err)) } return b } // SpecWillRun is implemented as a noop to satisfy the reporter interface for ginkgo. func (reporter *ProgressReporter) SpecWillRun(specSummary *types.SpecSummary) {} // BeforeSuiteDidRun is implemented as a noop to satisfy the reporter interface for ginkgo. func (reporter *ProgressReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) {} // AfterSuiteDidRun is implemented as a noop to satisfy the reporter interface for ginkgo. func (reporter *ProgressReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) {} "} {"_id":"doc-en-kubernetes-a221ad27fb90d9062b22faaf1bb93a317a394b95904fb1d39bc6076aca273bbd","title":"","text":"health kubernetes __PILLAR__DNS__DOMAIN__ in-addr.arpa ip6.arpa { pods insecure upstream fallthrough in-addr.arpa ip6.arpa ttl 30 }"} {"_id":"doc-en-kubernetes-f25a3600cb9f9f6a845514f0ab54182483459db54b74785ba1c474169b9d29bd","title":"","text":"health kubernetes {{ pillar['dns_domain'] }} in-addr.arpa ip6.arpa { pods insecure upstream fallthrough in-addr.arpa ip6.arpa ttl 30 }"} {"_id":"doc-en-kubernetes-86ca315472e6e098ddd746fe7cfb5ea5a28e4764fa0989ec3c9282bfe537def4","title":"","text":"health kubernetes $DNS_DOMAIN in-addr.arpa ip6.arpa { pods insecure upstream fallthrough in-addr.arpa ip6.arpa ttl 30 }"} {"_id":"doc-en-kubernetes-756ff4b01df08eb0622f647204266562e95f358224bb67e960d63637323d69db","title":"","text":"fi } # outputs md5 hash of $1, works on macOS and Linux function kube::util::md5() { if which md5 >/dev/null 2>&1; then md5 -q \"$1\" else md5sum \"$1\" | awk '{ print $1 }' fi } # kube::util::read-array # Reads in stdin and adds it line by line to the array provided. This can be # used instead of \"mapfile -t\", and is bash 3 compatible."} {"_id":"doc-en-kubernetes-927151a519f7184d1ff3aeddb571aacf519bd0361c22495fe18551d3a63fb86e","title":"","text":"echo cat \"${LICENSE_ROOT}/LICENSE\" echo echo \"= LICENSE $(md5sum < \"${LICENSE_ROOT}/LICENSE\" | awk '{print $1}')\" echo \"= LICENSE $(kube::util::md5 \"${LICENSE_ROOT}/LICENSE\")\" echo \"================================================================================\" ) > ${TMP_LICENSE_FILE}"} {"_id":"doc-en-kubernetes-d5fe70900314db4a5183920c67b95583ca3ef515a73b67065058574d3b6b59f6","title":"","text":"cat \"${file}\" echo echo \"= ${file} $(md5sum < \"${file}\" | awk '{print $1}')\" echo \"= ${file} $(kube::util::md5 \"${file}\")\" echo \"================================================================================\" echo done >> ${TMP_LICENSE_FILE}"} {"_id":"doc-en-kubernetes-23b3fd2d6f8900da7732a82488e65a4e09d31944a3d776ee811ea8ec5c5053ad","title":"","text":"// If we need to (re-)create the pod sandbox, everything will need to be // killed and recreated, and init containers should be purged. if createPodSandbox { if !shouldRestartOnFailure(pod) && attempt != 0 { if !shouldRestartOnFailure(pod) && attempt != 0 && len(podStatus.ContainerStatuses) != 0 { // Should not restart the pod, just return. // we should not create a sandbox for a pod if it is already done. // if all containers are done and should not be started, there is no need to create a new sandbox. // this stops confusing logs on pods whose containers all have exit codes, but we recreate a sandbox before terminating it. // // If ContainerStatuses is empty, we assume that we've never // successfully created any containers. In this case, we should // retry creating the sandbox. changes.CreateSandbox = false return changes }"} {"_id":"doc-en-kubernetes-588d5c3ad8ae0e7a797402e8f7f9636372661db3f6309da9b348359aa04d952a","title":"","text":"ContainersToKill: map[kubecontainer.ContainerID]containerToKillInfo{}, }, }, \"Verify we create a pod sandbox if no ready sandbox for pod with RestartPolicy=Never and no containers have ever been created\": { mutatePodFn: func(pod *v1.Pod) { pod.Spec.RestartPolicy = v1.RestartPolicyNever }, mutateStatusFn: func(status *kubecontainer.PodStatus) { // no ready sandbox status.SandboxStatuses[0].State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY status.SandboxStatuses[0].Metadata.Attempt = uint32(2) // no visible containers status.ContainerStatuses = []*kubecontainer.ContainerStatus{} }, actions: podActions{ SandboxID: baseStatus.SandboxStatuses[0].Id, Attempt: uint32(3), CreateSandbox: true, KillPod: true, ContainersToStart: []int{0, 1, 2}, ContainersToKill: map[kubecontainer.ContainerID]containerToKillInfo{}, }, }, \"Kill and recreate the container if the container is in unknown state\": { mutatePodFn: func(pod *v1.Pod) { pod.Spec.RestartPolicy = v1.RestartPolicyNever }, mutateStatusFn: func(status *kubecontainer.PodStatus) {"} {"_id":"doc-en-kubernetes-688f2b4abae3f56c4d6d718db60ed81e59181367d3ae4dfd9f7f41d1b65b37c7","title":"","text":"ContainersToKill: getKillMapWithInitContainers(basePod, baseStatus, []int{}), }, }, \"Pod sandbox not ready, init container failed, but RestartPolicy == Never; kill pod only\": { mutatePodFn: func(pod *v1.Pod) { pod.Spec.RestartPolicy = v1.RestartPolicyNever }, mutateStatusFn: func(status *kubecontainer.PodStatus) { status.SandboxStatuses[0].State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY }, actions: podActions{ KillPod: true, CreateSandbox: false, SandboxID: baseStatus.SandboxStatuses[0].Id, Attempt: uint32(1), ContainersToStart: []int{}, ContainersToKill: getKillMapWithInitContainers(basePod, baseStatus, []int{}), }, }, \"Pod sandbox not ready, and RestartPolicy == Never, but no visible init containers; create a new pod sandbox\": { mutatePodFn: func(pod *v1.Pod) { pod.Spec.RestartPolicy = v1.RestartPolicyNever }, mutateStatusFn: func(status *kubecontainer.PodStatus) { status.SandboxStatuses[0].State = runtimeapi.PodSandboxState_SANDBOX_NOTREADY status.ContainerStatuses = []*kubecontainer.ContainerStatus{} }, actions: podActions{ KillPod: true, CreateSandbox: true, SandboxID: baseStatus.SandboxStatuses[0].Id, Attempt: uint32(1), NextInitContainerToStart: &basePod.Spec.InitContainers[0], ContainersToStart: []int{}, ContainersToKill: getKillMapWithInitContainers(basePod, baseStatus, []int{}), }, }, } { pod, status := makeBasePodAndStatusWithInitContainers() if test.mutatePodFn != nil {"} {"_id":"doc-en-kubernetes-48926828335b3e9b2c38f3593580586a87dfe8702a9bef12800cdaf39e4e218c","title":"","text":"action := testing.ActionImpl{} action.Verb = \"get\" action.Resource = schema.GroupVersionResource{Resource: \"version\"} c.Invokes(action, nil) _, err := c.Invokes(action, nil) if err != nil { return nil, err } if c.FakedServerVersion != nil { return c.FakedServerVersion, nil"} {"_id":"doc-en-kubernetes-eb97f29ae1a5a01c8a34e150793c5007c7e396c4de1b8edd6e20b324b696dd92","title":"","text":"package fake_test import ( \"errors\" \"testing\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/version\" fakediscovery \"k8s.io/client-go/discovery/fake\" fakeclientset \"k8s.io/client-go/kubernetes/fake\" kubetesting \"k8s.io/client-go/testing\" ) func TestFakingServerVersion(t *testing.T) {"} {"_id":"doc-en-kubernetes-8447380ebce8868b382eb8f6bcac22599b6f5984daeac3153ae4660ec5dd27ab","title":"","text":"t.Fatalf(\"unexpected faked discovery return value: %q\", sv.GitCommit) } } func TestFakingServerVersionWithError(t *testing.T) { expectedError := errors.New(\"an error occurred\") fakeClient := fakeclientset.NewSimpleClientset() fakeClient.Discovery().(*fakediscovery.FakeDiscovery).PrependReactor(\"*\", \"*\", func(action kubetesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, expectedError }) _, err := fakeClient.Discovery().ServerVersion() if err == nil { t.Fatal(\"ServerVersion should return error, returned nil instead\") } if err != expectedError { t.Fatal(\"ServerVersion should return expected error, returned different error instead\") } } "} {"_id":"doc-en-kubernetes-e589dd18f2e76e5ec90acb17fa01bc05178197d5196f3690ae2c9427957d3b9d","title":"","text":"url := fmt.Sprintf(\"%s/%s.txt\", bucketURL, versionLabel) body, err := fetcher(url, getReleaseVersionTimeout) if err != nil { // If the network operaton was successful but the server did not reply with StatusOK if body != \"\" { return \"\", err } if clientVersionErr == nil { // Handle air-gapped environments by falling back to the client version. klog.Warningf(\"could not fetch a Kubernetes version from the internet: %v\", err)"} {"_id":"doc-en-kubernetes-80d44d09dc76b925fa54bfcf255a3e06eb2d689efbc032d3d911de6c0c1fa558","title":"","text":"import ( \"errors\" \"fmt\" \"k8s.io/kubernetes/cmd/kubeadm/app/constants\" \"path\" \"strings\" \"testing\""} {"_id":"doc-en-kubernetes-c846901821dd5acc96e38a84e25e026fa313ece688697e970388990349572583","title":"","text":"func TestVersionFromNetwork(t *testing.T) { type T struct { Content string Expected string ErrorExpected bool Content string Expected string FetcherErrorExpected bool ErrorExpected bool } currentVersion := normalizedBuildVersion(constants.CurrentKubernetesVersion.String()) cases := map[string]T{ \"stable\": {\"stable-1\", \"v1.4.6\", false}, // recursive pointer to stable-1 \"stable-1\": {\"v1.4.6\", \"v1.4.6\", false}, \"stable-1.3\": {\"v1.3.10\", \"v1.3.10\", false}, \"latest\": {\"v1.6.0-alpha.0\", \"v1.6.0-alpha.0\", false}, \"latest-1.3\": {\"v1.3.11-beta.0\", \"v1.3.11-beta.0\", false}, \"empty\": {\"\", \"\", true}, \"garbage\": {\"NoSuchKeyThe specified key does not exist.\", \"\", true}, \"unknown\": {\"The requested URL was not found on this server.\", \"\", true}, \"stable\": {\"stable-1\", \"v1.4.6\", false, false}, // recursive pointer to stable-1 \"stable-1\": {\"v1.4.6\", \"v1.4.6\", false, false}, \"stable-1.3\": {\"v1.3.10\", \"v1.3.10\", false, false}, \"latest\": {\"v1.6.0-alpha.0\", \"v1.6.0-alpha.0\", false, false}, \"latest-1.3\": {\"v1.3.11-beta.0\", \"v1.3.11-beta.0\", false, false}, \"empty\": {\"\", currentVersion, true, false}, \"garbage\": {\"NoSuchKeyThe specified key does not exist.\", currentVersion, true, false}, \"unknown\": {\"The requested URL was not found on this server.\", currentVersion, true, false}, } for k, v := range cases {"} {"_id":"doc-en-kubernetes-a1236dbecc60a4afe139d2ec86701f6ffdd576b296e610adaee49982606b9256","title":"","text":"key := strings.TrimSuffix(path.Base(url), \".txt\") res, found := cases[key] if found { if v.ErrorExpected { if v.FetcherErrorExpected { return \"error\", errors.New(\"expected error\") } return res.Content, nil"} {"_id":"doc-en-kubernetes-7e3eec605144f12b88a2e0d390e04502819151fb589a30129400726af582aa45","title":"","text":"github.com/json-iterator/go v1.1.6 github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024 github.com/karrick/godirwalk v1.7.5 // indirect github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875 github.com/libopenstorage/openstorage v1.0.0 github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de github.com/lithammer/dedent v1.1.0 github.com/lpabon/godbc v0.1.1 // indirect"} {"_id":"doc-en-kubernetes-588712f8fa6ee762236988d4895e5daedc7488294c919fe2bf46eee10d43e999","title":"","text":"github.com/kr/pty => github.com/kr/pty v1.1.5 github.com/kr/text => github.com/kr/text v0.1.0 github.com/kylelemons/godebug => github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 github.com/libopenstorage/openstorage => github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875 github.com/libopenstorage/openstorage => github.com/libopenstorage/openstorage v1.0.0 github.com/liggitt/tabwriter => github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de github.com/lithammer/dedent => github.com/lithammer/dedent v1.1.0 github.com/lpabon/godbc => github.com/lpabon/godbc v0.1.1"} {"_id":"doc-en-kubernetes-a6601901adf490debe91e91ec27365b160c3396136be04596efe643a4866b221","title":"","text":"github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875 h1:s+gZ8/rkYrWgN7xTMUISDw6nspgWyju2OCKmpFBrviQ= github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875/go.mod h1:Sp1sIObHjat1BeXhfMqLZ14wnOzEhNx2YQedreMcUyc= github.com/libopenstorage/openstorage v1.0.0 h1:GLPam7/0mpdP8ZZtKjbfcXJBTIA/T1O6CBErVEFEyIM= github.com/libopenstorage/openstorage v1.0.0/go.mod h1:Sp1sIObHjat1BeXhfMqLZ14wnOzEhNx2YQedreMcUyc= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= github.com/lithammer/dedent v1.1.0 h1:VNzHMVCBNG1j0fh3OrsFRkVUwStdDArbgBWoPAffktY="} {"_id":"doc-en-kubernetes-4318f599c94edb412955b4d10a1e9938f90a71c9507ed0be16c062e533a2582e","title":"","text":"# See the OWNERS docs at https://go.k8s.io/owners maintainers: - adityadani approvers: - lpabon - saad-ali - rootfs reviewers: - lpabon - saad-ali - rootfs "} {"_id":"doc-en-kubernetes-1e26070723919ce6755cb929a357bfef1f66feefaa050491173237d95608be82","title":"","text":"github.com/karrick/godirwalk # github.com/konsorten/go-windows-terminal-sequences v1.0.1 => github.com/konsorten/go-windows-terminal-sequences v1.0.1 github.com/konsorten/go-windows-terminal-sequences # github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875 => github.com/libopenstorage/openstorage v0.0.0-20170906232338-093a0c388875 # github.com/libopenstorage/openstorage v1.0.0 => github.com/libopenstorage/openstorage v1.0.0 github.com/libopenstorage/openstorage/api github.com/libopenstorage/openstorage/api/client github.com/libopenstorage/openstorage/api/client/volume"} {"_id":"doc-en-kubernetes-eaf44af27b6855dd6232440cc886f59a54d6135ff9ddccefd8b449ebb771cfeb","title":"","text":"panic(err) } mismatchErrorMessage := \"ERROR: %v indicates that %v should be at version %v, but the following files didn't match:nn\" + \"%vnnif you are changing the version of %v, make sure all of the following files are updated with the newest version including %vn\" + \"then run ./hack/verify-external-dependencies-version.shnn\" externalDeps := &dependencies{} var pathsToUpdate []string err = yaml.Unmarshal(externalDepsFile, externalDeps) if err != nil { panic(err)"} {"_id":"doc-en-kubernetes-75612a6b2fb5ae257cceaf40973aaf62f6b2659db9c482657577829b21cbb226","title":"","text":"} } if !found { log.Fatalf(\"%v dependency: file %v doesn't contain the expected version %v or matcher %v did change. check the %v file\", dep.Name, refPath.Path, dep.Version, refPath.Match, externalDepsFilePath) pathsToUpdate = append(pathsToUpdate, refPath.Path) } } if len(pathsToUpdate) > 0 { log.Fatalf(mismatchErrorMessage, externalDepsFilePath, dep.Name, dep.Version, strings.Join(pathsToUpdate, \"n\"), dep.Name, externalDepsFilePath) } } }"} {"_id":"doc-en-kubernetes-671209a963ad3ccd174f84273e60e8d095439b768ea5a6621a686d2568e4278c","title":"","text":"factor = 2 ) duration := base // Responsible for checking limits in resolv.conf // The limits do not have anything to do with individual pods // Since this is called in syncLoop, we don't need to call it anywhere else if kl.dnsConfigurer != nil && kl.dnsConfigurer.ResolverConfig != \"\" { kl.dnsConfigurer.CheckLimitsForResolvConf() } for { if err := kl.runtimeState.runtimeErrors(); err != nil { klog.Errorf(\"skipping pod synchronization - %v\", err)"} {"_id":"doc-en-kubernetes-469cdce78031cb86db5732366e40794de3dbb43e7daeb0dfb3f1af733e37d896","title":"","text":"func (kl *Kubelet) HandlePodAdditions(pods []*v1.Pod) { start := kl.clock.Now() sort.Sort(sliceutils.PodsByCreationTime(pods)) // Responsible for checking limits in resolv.conf // The limits do not have anything to do with individual pods if kl.dnsConfigurer != nil && kl.dnsConfigurer.ResolverConfig != \"\" { kl.dnsConfigurer.CheckLimitsForResolvConf() } for _, pod := range pods { existingPods := kl.podManager.GetPods() // Always add the pod to the pod manager. Kubelet relies on the pod"} {"_id":"doc-en-kubernetes-6023b7573815f47cff04b5b444ffbc3f54490cdc7eb3e2063e6b7e7aebe193a8","title":"","text":"// being updated from a config source. func (kl *Kubelet) HandlePodUpdates(pods []*v1.Pod) { start := kl.clock.Now() // Responsible for checking limits in resolv.conf if kl.dnsConfigurer != nil && kl.dnsConfigurer.ResolverConfig != \"\" { kl.dnsConfigurer.CheckLimitsForResolvConf() } for _, pod := range pods { kl.podManager.UpdatePod(pod) if kubetypes.IsMirrorPod(pod) {"} {"_id":"doc-en-kubernetes-5e0f6b70415c72ccba9a0f7c0897dbdf8dee9d1d3ab2a7ad70c6fa4e67d60ccf","title":"","text":") const execInfoEnv = \"KUBERNETES_EXEC_INFO\" const onRotateListWarningLength = 1000 var scheme = runtime.NewScheme() var codecs = serializer.NewCodecFactory(scheme)"} {"_id":"doc-en-kubernetes-7001b4e7de9fcd7a14303e7d61103f1939842a93312ce4b003e47f60831115ef","title":"","text":"cachedCreds *credentials exp time.Time onRotate func() onRotateList []func() } type credentials struct {"} {"_id":"doc-en-kubernetes-81d112ed7a6a330977489c27dde8641533e82f081855863b4e5ed8ae471b388c","title":"","text":"dial = (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext } d := connrotation.NewDialer(dial) a.onRotate = d.CloseAll a.mu.Lock() defer a.mu.Unlock() a.onRotateList = append(a.onRotateList, d.CloseAll) onRotateListLength := len(a.onRotateList) if onRotateListLength > onRotateListWarningLength { klog.Warningf(\"constructing many client instances from the same exec auth config can cause performance problems during cert rotation and can exhaust available network connections; %d clients constructed calling %q\", onRotateListLength, a.cmd) } c.Dial = d.DialContext return nil"} {"_id":"doc-en-kubernetes-44c8aec4c0b8c7f4c9ff5ed7d539a9636d76eb5dac1fae22515374cbebca981e","title":"","text":"a.cachedCreds = newCreds // Only close all connections when TLS cert rotates. Token rotation doesn't // need the extra noise. if a.onRotate != nil && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) { a.onRotate() if len(a.onRotateList) > 0 && oldCreds != nil && !reflect.DeepEqual(oldCreds.cert, a.cachedCreds.cert) { for _, onRotate := range a.onRotateList { onRotate() } } return nil }"} {"_id":"doc-en-kubernetes-96a58620b58fcfcd6bc0773da4a5dc959037b7274515deb88f78ae5f902afaa6","title":"","text":"get(t, \"valid TLS cert again\", false) } func TestConcurrentUpdateTransportConfig(t *testing.T) { n := time.Now() now := func() time.Time { return n } env := []string{\"\"} environ := func() []string { s := make([]string, len(env)) copy(s, env) return s } c := api.ExecConfig{ Command: \"./testdata/test-plugin.sh\", APIVersion: \"client.authentication.k8s.io/v1alpha1\", } a, err := newAuthenticator(newCache(), &c) if err != nil { t.Fatal(err) } a.environ = environ a.now = now a.stderr = ioutil.Discard stopCh := make(chan struct{}) defer close(stopCh) numConcurrent := 2 for i := 0; i < numConcurrent; i++ { go func() { for { tc := &transport.Config{} a.UpdateTransportConfig(tc) select { case <-stopCh: return default: continue } } }() } time.Sleep(2 * time.Second) } // genClientCert generates an x509 certificate for testing. Certificate and key // are returned in PEM encoding. func genClientCert(t *testing.T) ([]byte, []byte) {"} {"_id":"doc-en-kubernetes-16f11365d829a890482b0f59dced7a4bd9125968a5486e88c2ebabf6de40c2e2","title":"","text":"\"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/sets\" cloudprovider \"k8s.io/cloud-provider\" cloudproviderapi \"k8s.io/cloud-provider/api\" \"k8s.io/klog\""} {"_id":"doc-en-kubernetes-5bd722e11487a968ceaebcedd0ad526902bb3473d757cd71053c13c6e2aed39d","title":"","text":"requiresUpdate := kl.reconcileCMADAnnotationWithExistingNode(node, existingNode) requiresUpdate = kl.updateDefaultLabels(node, existingNode) || requiresUpdate requiresUpdate = kl.reconcileExtendedResource(node, existingNode) || requiresUpdate requiresUpdate = kl.reconcileHugePageResource(node, existingNode) || requiresUpdate if requiresUpdate { if _, _, err := nodeutil.PatchNodeStatus(kl.kubeClient.CoreV1(), types.NodeName(kl.nodeName), originalNode, existingNode); err != nil { klog.Errorf(\"Unable to reconcile node %q with API server: error updating node: %v\", kl.nodeName, err)"} {"_id":"doc-en-kubernetes-1550833c6c2f17cec47af85c96c3d85f8fb2891b90ffdd47543e3c4664623147","title":"","text":"return true } // reconcileHugePageResource will update huge page capacity for each page size and remove huge page sizes no longer supported func (kl *Kubelet) reconcileHugePageResource(initialNode, existingNode *v1.Node) bool { requiresUpdate := false supportedHugePageResources := sets.String{} for resourceName := range initialNode.Status.Capacity { if !v1helper.IsHugePageResourceName(resourceName) { continue } supportedHugePageResources.Insert(string(resourceName)) initialCapacity := initialNode.Status.Capacity[resourceName] initialAllocatable := initialNode.Status.Allocatable[resourceName] capacity, resourceIsSupported := existingNode.Status.Capacity[resourceName] allocatable := existingNode.Status.Allocatable[resourceName] // Add or update capacity if it the size was previously unsupported or has changed if !resourceIsSupported || capacity.Cmp(initialCapacity) != 0 { existingNode.Status.Capacity[resourceName] = initialCapacity.DeepCopy() requiresUpdate = true } // Add or update allocatable if it the size was previously unsupported or has changed if !resourceIsSupported || allocatable.Cmp(initialAllocatable) != 0 { existingNode.Status.Allocatable[resourceName] = initialAllocatable.DeepCopy() requiresUpdate = true } } for resourceName := range existingNode.Status.Capacity { if !v1helper.IsHugePageResourceName(resourceName) { continue } // If huge page size no longer is supported, we remove it from the node if !supportedHugePageResources.Has(string(resourceName)) { delete(existingNode.Status.Capacity, resourceName) delete(existingNode.Status.Allocatable, resourceName) klog.Infof(\"Removing now unsupported huge page resource named: %s\", resourceName) requiresUpdate = true } } return requiresUpdate } // Zeros out extended resource capacity during reconciliation. func (kl *Kubelet) reconcileExtendedResource(initialNode, node *v1.Node) bool { requiresUpdate := false"} {"_id":"doc-en-kubernetes-4017c391baa223491bdde20f1dc5630664c49da12c637a9f9c6e365b6d94bd6e","title":"","text":"} } func TestReconcileHugePageResource(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) hugePageResourceName64Ki := v1.ResourceName(\"hugepages-64Ki\") hugePageResourceName2Mi := v1.ResourceName(\"hugepages-2Mi\") hugePageResourceName1Gi := v1.ResourceName(\"hugepages-1Gi\") cases := []struct { name string testKubelet *TestKubelet initialNode *v1.Node existingNode *v1.Node expectedNode *v1.Node needsUpdate bool }{ { name: \"no update needed when all huge page resources are similar\", testKubelet: testKubelet, needsUpdate: false, initialNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, }, }, existingNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, }, }, expectedNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), hugePageResourceName64Ki: *resource.NewQuantity(0, resource.BinarySI), }, }, }, }, { name: \"update needed when new huge page resources is supported\", testKubelet: testKubelet, needsUpdate: true, initialNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, existingNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: resource.MustParse(\"100Mi\"), }, }, }, expectedNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, }, { name: \"update needed when huge page resource quantity has changed\", testKubelet: testKubelet, needsUpdate: true, initialNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"4Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"4Gi\"), }, }, }, existingNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, expectedNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"4Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"4Gi\"), }, }, }, }, { name: \"update needed when a huge page resources is no longer supported\", testKubelet: testKubelet, needsUpdate: true, initialNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, existingNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName2Mi: *resource.NewQuantity(0, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, expectedNode: &v1.Node{ Status: v1.NodeStatus{ Capacity: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, Allocatable: v1.ResourceList{ v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), v1.ResourceMemory: *resource.NewQuantity(10e9, resource.BinarySI), v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), hugePageResourceName1Gi: resource.MustParse(\"2Gi\"), }, }, }, }, } for _, tc := range cases { t.Run(tc.name, func(T *testing.T) { defer testKubelet.Cleanup() kubelet := testKubelet.kubelet needsUpdate := kubelet.reconcileHugePageResource(tc.initialNode, tc.existingNode) assert.Equal(t, tc.needsUpdate, needsUpdate, tc.name) assert.Equal(t, tc.expectedNode, tc.existingNode, tc.name) }) } } func TestReconcileExtendedResource(t *testing.T) { testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) testKubelet.kubelet.kubeClient = nil // ensure only the heartbeat client is used"} {"_id":"doc-en-kubernetes-cc84f9a22396f832c8ed946169ee8dda0e9b10074ee4a74dabd35e6f569dbb2e","title":"","text":"v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/kubernetes/pkg/kubelet/cm\" \"k8s.io/kubernetes/test/e2e/framework\""} {"_id":"doc-en-kubernetes-8b126a805501fe4b30062ea9606f36545aadcdc507549e32aa57a8a157ea0051","title":"","text":"err := e2epod.WaitForPodSuccessInNamespace(f.ClientSet, verifyPod.Name, f.Namespace.Name) framework.ExpectNoError(err) }) ginkgo.It(\"should add resources for new huge page sizes on kubelet restart\", func() { ginkgo.By(\"Stopping kubelet\") startKubelet := stopKubelet() ginkgo.By(`Patching away support for hugepage resource \"hugepages-2Mi\"`) patch := []byte(`[{\"op\": \"remove\", \"path\": \"/status/capacity/hugepages-2Mi\"}, {\"op\": \"remove\", \"path\": \"/status/allocatable/hugepages-2Mi\"}]`) result := f.ClientSet.CoreV1().RESTClient().Patch(types.JSONPatchType).Resource(\"nodes\").Name(framework.TestContext.NodeName).SubResource(\"status\").Body(patch).Do(context.TODO()) framework.ExpectNoError(result.Error(), \"while patching\") ginkgo.By(\"Starting kubelet again\") startKubelet() ginkgo.By(\"verifying that the hugepages-2Mi resource is present\") gomega.Eventually(func() bool { node, err := f.ClientSet.CoreV1().Nodes().Get(context.TODO(), framework.TestContext.NodeName, metav1.GetOptions{}) framework.ExpectNoError(err, \"while getting node status\") _, isPresent := node.Status.Capacity[\"hugepages-2Mi\"] return isPresent }, 30*time.Second, framework.Poll).Should(gomega.Equal(true)) }) } // Serial because the test updates kubelet configuration. var _ = SIGDescribe(\"HugePages [Serial] [Feature:HugePages][NodeFeature:HugePages]\", func() { f := framework.NewDefaultFramework(\"hugepages-test\") ginkgo.It(\"should remove resources for huge page sizes no longer supported\", func() { ginkgo.By(\"mimicking support for 9Mi of 3Mi huge page memory by patching the node status\") patch := []byte(`[{\"op\": \"add\", \"path\": \"/status/capacity/hugepages-3Mi\", \"value\": \"9Mi\"}, {\"op\": \"add\", \"path\": \"/status/allocatable/hugepages-3Mi\", \"value\": \"9Mi\"}]`) result := f.ClientSet.CoreV1().RESTClient().Patch(types.JSONPatchType).Resource(\"nodes\").Name(framework.TestContext.NodeName).SubResource(\"status\").Body(patch).Do(context.TODO()) framework.ExpectNoError(result.Error(), \"while patching\") node, err := f.ClientSet.CoreV1().Nodes().Get(context.TODO(), framework.TestContext.NodeName, metav1.GetOptions{}) framework.ExpectNoError(err, \"while getting node status\") ginkgo.By(\"Verifying that the node now supports huge pages with size 3Mi\") value, ok := node.Status.Capacity[\"hugepages-3Mi\"] framework.ExpectEqual(ok, true, \"capacity should contain resouce hugepages-3Mi\") framework.ExpectEqual(value.String(), \"9Mi\", \"huge pages with size 3Mi should be supported\") ginkgo.By(\"restarting the node and verifying that huge pages with size 3Mi are not supported\") restartKubelet() ginkgo.By(\"verifying that the hugepages-3Mi resource no longer is present\") gomega.Eventually(func() bool { node, err = f.ClientSet.CoreV1().Nodes().Get(context.TODO(), framework.TestContext.NodeName, metav1.GetOptions{}) framework.ExpectNoError(err, \"while getting node status\") _, isPresent := node.Status.Capacity[\"hugepages-3Mi\"] return isPresent }, 30*time.Second, framework.Poll).Should(gomega.Equal(false)) }) ginkgo.Context(\"With config updated with hugepages feature enabled\", func() { ginkgo.BeforeEach(func() { ginkgo.By(\"verifying hugepages are supported\")"} {"_id":"doc-en-kubernetes-de0fcd4e3f6affb058a62488ffc884aefe5351df1509f3c9f0884480653f38da","title":"","text":"} // TODO: Find a uniform way to deal with systemctl/initctl/service operations. #34494 func restartKubelet() { func findRunningKubletServiceName() string { stdout, err := exec.Command(\"sudo\", \"systemctl\", \"list-units\", \"kubelet*\", \"--state=running\").CombinedOutput() framework.ExpectNoError(err) regex := regexp.MustCompile(\"(kubelet-w+)\") matches := regex.FindStringSubmatch(string(stdout)) framework.ExpectNotEqual(len(matches), 0) kube := matches[0] framework.Logf(\"Get running kubelet with systemctl: %v, %v\", string(stdout), kube) stdout, err = exec.Command(\"sudo\", \"systemctl\", \"restart\", kube).CombinedOutput() framework.ExpectNotEqual(len(matches), 0, \"Found more than one kubelet service running: %q\", stdout) kubeletServiceName := matches[0] framework.Logf(\"Get running kubelet with systemctl: %v, %v\", string(stdout), kubeletServiceName) return kubeletServiceName } func restartKubelet() { kubeletServiceName := findRunningKubletServiceName() stdout, err := exec.Command(\"sudo\", \"systemctl\", \"restart\", kubeletServiceName).CombinedOutput() framework.ExpectNoError(err, \"Failed to restart kubelet with systemctl: %v, %v\", err, stdout) } // stopKubelet will kill the running kubelet, and returns a func that will restart the process again func stopKubelet() func() { kubeletServiceName := findRunningKubletServiceName() stdout, err := exec.Command(\"sudo\", \"systemctl\", \"kill\", kubeletServiceName).CombinedOutput() framework.ExpectNoError(err, \"Failed to stop kubelet with systemctl: %v, %v\", err, stdout) return func() { stdout, err := exec.Command(\"sudo\", \"systemctl\", \"start\", kubeletServiceName).CombinedOutput() framework.ExpectNoError(err, \"Failed to restart kubelet with systemctl: %v, %v\", err, stdout) } } func toCgroupFsName(cgroupName cm.CgroupName) string { if framework.TestContext.KubeletConfig.CgroupDriver == \"systemd\" { return cgroupName.ToSystemd()"} {"_id":"doc-en-kubernetes-03f120d9e2193e6bc67e208ed7754d2f51049a72eb03e01835fb9fc74089263b","title":"","text":"\"//:all-srcs\", ], outs = [\"stable-metrics-list.yaml\"], cmd = \"./$(locations :instrumentation) $(locations //:all-srcs) > $@\", cmd = \"for loc in $(locations //:all-srcs); do echo $$loc; done | ./$(locations :instrumentation) - > $@\", message = \"Listing all stable metrics.\", tools = [\":instrumentation\"], )"} {"_id":"doc-en-kubernetes-2c95aef0f6fbf5b8ba2d7d89f890b7185b387d57914bb038c58eec664c2bd47a","title":"","text":"package main import ( \"bufio\" \"flag\" \"fmt\" \"go/ast\""} {"_id":"doc-en-kubernetes-a922d863e1f6fff4e4a09c7f033d51158e084cf7bae899b253afd80316346b1e","title":"","text":"func main() { flag.Parse() if len(flag.Args()) < 1 { fmt.Fprintf(os.Stderr, \"USAGE: %s [...]n\", os.Args[0]) fmt.Fprintf(os.Stderr, \"USAGE: %s [...]n\", os.Args[0]) os.Exit(64) } stableMetrics := []metric{} errors := []error{} addStdin := false for _, arg := range flag.Args() { if arg == \"-\" { addStdin = true continue } ms, es := searchPathForStableMetrics(arg) stableMetrics = append(stableMetrics, ms...) errors = append(errors, es...) } if addStdin { scanner := bufio.NewScanner(os.Stdin) scanner.Split(bufio.ScanLines) for scanner.Scan() { arg := scanner.Text() ms, es := searchPathForStableMetrics(arg) stableMetrics = append(stableMetrics, ms...) errors = append(errors, es...) } } for _, err := range errors { fmt.Fprintf(os.Stderr, \"%sn\", err) }"} {"_id":"doc-en-kubernetes-a0275861421545f04072483701b3d344f922d8721fb8b9ce389f1af59ad54186","title":"","text":"Creates a replication controller to manage the created container(s). ``` kubectl run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] kubectl run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...] ``` ### Examples"} {"_id":"doc-en-kubernetes-26179618fbb0b0a3ecc34e12b37e20dc211228d17e5057cf222bb371d84dca52","title":"","text":"* [kubectl](kubectl.md)\t - kubectl controls the Kubernetes cluster manager ###### Auto generated by spf13/cobra on 6-Nov-2015 ###### Auto generated by spf13/cobra on 10-Nov-2015 [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_run.md?pixel)]()"} {"_id":"doc-en-kubernetes-0fe17589c7d8bd421cb797e02eaa7a669faa7333910b1375fb80f394ff2ec291","title":"","text":"func NewCmdRun(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: \"run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json]\", Use: \"run NAME --image=image [--env=\"key=value\"] [--port=port] [--replicas=replicas] [--dry-run=bool] [--overrides=inline-json] [--command] -- [COMMAND] [args...]\", // run-container is deprecated Aliases: []string{\"run-container\"}, Short: \"Run a particular image on the cluster.\", Long: run_long, Example: run_example, Run: func(cmd *cobra.Command, args []string) { err := Run(f, cmdIn, cmdOut, cmdErr, cmd, args) argsLenAtDash := cmd.ArgsLenAtDash() err := Run(f, cmdIn, cmdOut, cmdErr, cmd, args, argsLenAtDash) cmdutil.CheckErr(err) }, }"} {"_id":"doc-en-kubernetes-84b79fcc1ef4ddc3d358b4edf6c59feca0f14019df09dd781308c9acdf78b6fc","title":"","text":"cmd.Flags().String(\"service-overrides\", \"\", \"An inline JSON override for the generated service object. If this is non-empty, it is used to override the generated object. Requires that the object supply a valid apiVersion field. Only used if --expose is true.\") } func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string) error { func Run(f *cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer, cmd *cobra.Command, args []string, argsLenAtDash int) error { if len(os.Args) > 1 && os.Args[1] == \"run-container\" { printDeprecationWarning(\"run\", \"run-container\") } if len(args) == 0 { // Let kubectl run follow rules for `--`, see #13004 issue if len(args) == 0 || argsLenAtDash == 0 { return cmdutil.UsageError(cmd, \"NAME is required for run\") }"} {"_id":"doc-en-kubernetes-d95618b1e8ca53f76e3417457a8c0e115e597699ad644af79158d7a0084b6c00","title":"","text":"\"fmt\" \"io/ioutil\" \"net/http\" \"os\" \"reflect\" \"testing\""} {"_id":"doc-en-kubernetes-767a10b1ba02cba648fde6413b6dd232f5bfda775d6aa532c03e78840225493d","title":"","text":"} } func TestRunArgsFollowDashRules(t *testing.T) { _, _, rc := testData() tests := []struct { args []string argsLenAtDash int expectError bool name string }{ { args: []string{}, argsLenAtDash: -1, expectError: true, name: \"empty\", }, { args: []string{\"foo\"}, argsLenAtDash: -1, expectError: false, name: \"no cmd\", }, { args: []string{\"foo\", \"sleep\"}, argsLenAtDash: -1, expectError: false, name: \"cmd no dash\", }, { args: []string{\"foo\", \"sleep\"}, argsLenAtDash: 1, expectError: false, name: \"cmd has dash\", }, { args: []string{\"foo\", \"sleep\"}, argsLenAtDash: 0, expectError: true, name: \"no name\", }, } for _, test := range tests { f, tf, codec := NewAPIFactory() tf.Client = &fake.RESTClient{ Codec: codec, Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { return &http.Response{StatusCode: 201, Body: objBody(codec, &rc.Items[0])}, nil }), } tf.Namespace = \"test\" tf.ClientConfig = &client.Config{} cmd := NewCmdRun(f, os.Stdin, os.Stdout, os.Stderr) cmd.Flags().Set(\"image\", \"nginx\") err := Run(f, os.Stdin, os.Stdout, os.Stderr, cmd, test.args, test.argsLenAtDash) if test.expectError && err == nil { t.Errorf(\"unexpected non-error (%s)\", test.name) } if !test.expectError && err != nil { t.Errorf(\"unexpected error: %v (%s)\", err, test.name) } } } func TestGenerateService(t *testing.T) { tests := []struct {"} {"_id":"doc-en-kubernetes-2b8bf2434e15911e4e7f6964049c7b1315911c01dd60ed538b3134f089c1ff27","title":"","text":"} e2elog.Logf(\"Got an error creating template %d: %v\", i, err) } ginkgo.Fail(\"Unable to create template %d, exiting\", i) e2elog.Fail(\"Unable to create template %d, exiting\", i) }) })"} {"_id":"doc-en-kubernetes-0fd5aff92d6f164d19788ceffd4ab58a3874745f99169ff1a9f5da6b4a7c7c49","title":"","text":"} e2elog.Logf(\"Got an error creating template %d: %v\", i, err) } ginkgo.Fail(\"Unable to create template %d, exiting\", i) e2elog.Fail(\"Unable to create template %d, exiting\", i) }) pagedTable := &metav1beta1.Table{}"} {"_id":"doc-en-kubernetes-09fbe90c3ed11d6cac1c8bad03cb621efa2471ef8fe40ee2ee0ff520f3696a87","title":"","text":"srcs = [\"testfiles.go\"], importpath = \"k8s.io/kubernetes/test/e2e/framework/testfiles\", visibility = [\"//visibility:public\"], deps = [\"//vendor/github.com/onsi/ginkgo:go_default_library\"], deps = [\"//test/e2e/framework/log:go_default_library\"], ) filegroup("} {"_id":"doc-en-kubernetes-5e50069c7bb985305f476e5ff8a45783a416cae57db4943423cf835579aa01e4","title":"","text":"\"sort\" \"strings\" \"github.com/onsi/ginkgo\" e2elog \"k8s.io/kubernetes/test/e2e/framework/log\" ) var filesources []FileSource"} {"_id":"doc-en-kubernetes-e21ed0d93d8d1d312a3993750d330fd83f78f7896bafc0233cda17ca0e263eba","title":"","text":"func ReadOrDie(filePath string) []byte { data, err := Read(filePath) if err != nil { ginkgo.Fail(err.Error(), 1) e2elog.Fail(err.Error(), 1) } return data }"} {"_id":"doc-en-kubernetes-c20e8560557b39b1b31837d0c54380e6b75ffeea6abb945f59f810d49bf2c747","title":"","text":"for _, filesource := range filesources { data, err := filesource.ReadTestFile(filePath) if err != nil { ginkgo.Fail(fmt.Sprintf(\"fatal error looking for test file %s: %s\", filePath, err), 1) e2elog.Fail(fmt.Sprintf(\"fatal error looking for test file %s: %s\", filePath, err), 1) } if data != nil { return true"} {"_id":"doc-en-kubernetes-5a204e3b9a2fc953341583112ae7eafc8f9f98af998d0736fee931db8a04442c","title":"","text":"}) ginkgo.AfterEach(func() { defer func() { if expectedNodeCondition == v1.NodeDiskPressure && framework.TestContext.PrepullImages { // The disk eviction test may cause the prepulled images to be evicted, // prepull those images again to ensure this test not affect following tests. PrePullAllImages() } }() ginkgo.By(\"deleting pods\") for _, spec := range testSpecs { ginkgo.By(fmt.Sprintf(\"deleting pod: %s\", spec.pod.Name)) f.PodClient().DeleteSync(spec.pod.Name, &metav1.DeleteOptions{}, 10*time.Minute) } reduceAllocatableMemoryUsage() if expectedNodeCondition == v1.NodeDiskPressure && framework.TestContext.PrepullImages { // The disk eviction test may cause the prepulled images to be evicted, // prepull those images again to ensure this test not affect following tests. PrePullAllImages() } ginkgo.By(\"making sure we can start a new pod after the test\") podName := \"test-admit-pod\" f.PodClient().CreateSync(&v1.Pod{"} {"_id":"doc-en-kubernetes-4a316ff43eaa7217c21299759e8cd6dbb2601355418408bce80eb2d22ff79b77","title":"","text":"}, time.Minute*8, time.Second*4).ShouldNot(gomega.HaveOccurred()) }) ginkgo.AfterEach(func() { defer func() { if framework.TestContext.PrepullImages { // The test may cause the prepulled images to be evicted, // prepull those images again to ensure this test not affect following tests. PrePullAllImages() } }() ginkgo.By(\"delete the static pod\") err := deleteStaticPod(podPath, staticPodName, ns) gomega.Expect(err).ShouldNot(gomega.HaveOccurred())"} {"_id":"doc-en-kubernetes-0634c34a5580f619fa74eb8a976c5d00250197d82f42d207949cee7bea62f33a","title":"","text":"gomega.Eventually(func() error { return checkMirrorPodDisappear(f.ClientSet, mirrorPodName, ns) }, time.Minute, time.Second*2).Should(gomega.BeNil()) }) }) })"} {"_id":"doc-en-kubernetes-11f3aefd8d8255bcef68d507a3b261346624eec8324045422a4865378343d1f6","title":"","text":"return nil, false, nil } if ctx.ComponentConfig.CSRSigningController.ClusterSigningCertFile == \"\" || ctx.ComponentConfig.CSRSigningController.ClusterSigningKeyFile == \"\" { klog.V(2).Info(\"skipping CSR signer controller because no csr cert/key was specified\") return nil, false, nil }"} {"_id":"doc-en-kubernetes-1128e9875cea30089c6975ba081e901f0dd2f4b3224c4d40571d833c03d294c5","title":"","text":"// setting up the signing controller. This isn't // actually a problem since the signer is not a // required controller. klog.V(2).Info(\"skipping CSR signer controller because no csr cert/key was specified and the default files are missing\") return nil, false, nil default: // Note that '!filesExist && !usesDefaults' is obviously"} {"_id":"doc-en-kubernetes-85df295b7ab1f08a8c298a78b66624bd816b56ee00ff47ddafe27ddec7c9146a","title":"","text":"recognizers: recognizers(), } return certificates.NewCertificateController( \"csrapproving\", client, csrInformer, approver.handle,"} {"_id":"doc-en-kubernetes-82681e9dec097776923b0ddcf3731d31e8e5475b578a109ab9abb38c2b5265a2","title":"","text":") type CertificateController struct { // name is an identifier for this particular controller instance. name string kubeClient clientset.Interface csrLister certificateslisters.CertificateSigningRequestLister"} {"_id":"doc-en-kubernetes-6d8e9b44d48de6eda40f28b014af9778ecb3583d11976d2b19ee1daa6de4965f","title":"","text":"} func NewCertificateController( name string, kubeClient clientset.Interface, csrInformer certificatesinformers.CertificateSigningRequestInformer, handler func(*certificates.CertificateSigningRequest) error,"} {"_id":"doc-en-kubernetes-99ae7fd9a295f8b6a6362ce9c09154b3722b9939d3706890603b565129e3092b","title":"","text":"eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.CoreV1().Events(\"\")}) cc := &CertificateController{ name: name, kubeClient: kubeClient, queue: workqueue.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter( workqueue.NewItemExponentialFailureRateLimiter(200*time.Millisecond, 1000*time.Second),"} {"_id":"doc-en-kubernetes-9b8f8ff4e9bcd1404fb6fb8f447225aa3d661a95136e2506f79caccfa9d9a833","title":"","text":"defer utilruntime.HandleCrash() defer cc.queue.ShutDown() klog.Infof(\"Starting certificate controller\") defer klog.Infof(\"Shutting down certificate controller\") klog.Infof(\"Starting certificate controller %q\", cc.name) defer klog.Infof(\"Shutting down certificate controller %q\", cc.name) if !cache.WaitForNamedCacheSync(\"certificate\", stopCh, cc.csrsSynced) { if !cache.WaitForNamedCacheSync(fmt.Sprintf(\"certificate-%s\", cc.name), stopCh, cc.csrsSynced) { return }"} {"_id":"doc-en-kubernetes-f77c9b6d2feab2cbc3eb5e5359ebb5471b9941ace987e68c01608490d4736d90","title":"","text":"} controller := NewCertificateController( \"test\", client, informerFactory.Certificates().V1beta1().CertificateSigningRequests(), handler,"} {"_id":"doc-en-kubernetes-f09efb350a760260177a5662eb1606a863a79fb78d7ba3b0d0cae5281bc10953","title":"","text":"return nil, err } return certificates.NewCertificateController( \"csrsigning\", client, csrInformer, signer.handle,"} {"_id":"doc-en-kubernetes-0d3cc2767e34bce1c3a8f702fde0700c18652aaa608b83bad12f3ad2d64d9985","title":"","text":") const ( // MaxUint defines the max unsigned int value. MaxUint = ^uint(0) // MaxInt defines the max signed int value. MaxInt = int(MaxUint >> 1) // MaxTotalPriority defines the max total priority value. MaxTotalPriority = int64(math.MaxInt64) // MaxPriority defines the max priority value. MaxPriority = 10 // MaxWeight defines the max weight value. MaxWeight = int64(math.MaxInt64 / MaxPriority) MaxWeight = MaxTotalPriority / MaxPriority // DefaultPercentageOfNodesToScore defines the percentage of nodes of all nodes // that once found feasible, the scheduler stops looking for more nodes. DefaultPercentageOfNodesToScore = 50"} {"_id":"doc-en-kubernetes-d2115f66aa496a91868e9be78f1fc914fc5dafc6746314cd4cb81ff744005e99","title":"","text":"package factory import ( \"math\" \"testing\" \"github.com/stretchr/testify/assert\""} {"_id":"doc-en-kubernetes-0ba12dae0e56d6346f009fd1772389b5e7402834f5d2c064081cbdfd98a3c60b","title":"","text":"expected bool }{ { description: \"one of the weights is MaxInt64\", configs: []priorities.PriorityConfig{{Weight: math.MaxInt64}, {Weight: 5}}, description: \"one of the weights is MaxTotalPriority(MaxInt64)\", configs: []priorities.PriorityConfig{{Weight: api.MaxTotalPriority}, {Weight: 5}}, expected: true, }, { description: \"after multiplication with MaxPriority the weight is larger than MaxWeight\", configs: []priorities.PriorityConfig{{Weight: math.MaxInt64/api.MaxPriority + api.MaxPriority}, {Weight: 5}}, configs: []priorities.PriorityConfig{{Weight: api.MaxWeight + api.MaxPriority}, {Weight: 5}}, expected: true, }, {"} {"_id":"doc-en-kubernetes-263abaa34bc657ba44c5aaa361dc027cfde51df28f8c4c4fa61bac111e0a00ac","title":"","text":"flags.StringVar(&TestContext.KubernetesAnywherePath, \"kubernetes-anywhere-path\", \"/workspace/k8s.io/kubernetes-anywhere\", \"Which directory kubernetes-anywhere is installed to.\") flags.BoolVar(&TestContext.ListImages, \"list-images\", false, \"If true, will show list of images used for runnning tests.\") flags.StringVar(&TestContext.KubectlPath, \"kubectl-path\", \"kubectl\", \"The kubectl binary to use. For development, you might use 'cluster/kubectl.sh' here.\") } // RegisterClusterFlags registers flags specific to the cluster e2e test suite."} {"_id":"doc-en-kubernetes-8329d2ba269077c1251ac6f4706ddf3d7c69528016b5e1a699ad741d25841f7d","title":"","text":"flags.StringVar(&TestContext.RepoRoot, \"repo-root\", \"../../\", \"Root directory of kubernetes repository, for finding test files.\") flags.StringVar(&TestContext.Provider, \"provider\", \"\", \"The name of the Kubernetes provider (gce, gke, local, skeleton (the fallback if not set), etc.)\") flags.StringVar(&TestContext.Tooling, \"tooling\", \"\", \"The tooling in use (kops, gke, etc.)\") flags.StringVar(&TestContext.KubectlPath, \"kubectl-path\", \"kubectl\", \"The kubectl binary to use. For development, you might use 'cluster/kubectl.sh' here.\") flags.StringVar(&TestContext.OutputDir, \"e2e-output-dir\", \"/tmp\", \"Output directory for interesting/useful test data, like performance data, benchmarks, and other metrics.\") flags.StringVar(&TestContext.Prefix, \"prefix\", \"e2e\", \"A prefix to be added to cloud resources created during testing.\") flags.StringVar(&TestContext.MasterOSDistro, \"master-os-distro\", \"debian\", \"The OS distribution of cluster master (debian, ubuntu, gci, coreos, or custom).\")"} {"_id":"doc-en-kubernetes-1d51d65d411c9edf90886836c28cac7735f9b2ff4c03a0321f737e53c7411739","title":"","text":"import ( \"errors\" \"fmt\" \"io/ioutil\" \"os\" \"path/filepath\" \"strings\""} {"_id":"doc-en-kubernetes-b6746fcebd297e2922a74a6def54a55fe7166cc364ee3b1423834bea30060dae","title":"","text":"// attachFileDevice takes a path to a regular file and makes it available as an // attached block device. func attachFileDevice(path string, exec utilexec.Interface) (string, error) { blockDevicePath, err := getLoopDevice(path, exec) blockDevicePath, err := getLoopDevice(path) if err != nil && err.Error() != ErrDeviceNotFound { return \"\", err }"} {"_id":"doc-en-kubernetes-ad813a2a13e52cd7b16df807e4072082807cc930542918879cb2b5d8eeb7eb0f","title":"","text":"} // Returns the full path to the loop device associated with the given path. func getLoopDevice(path string, exec utilexec.Interface) (string, error) { func getLoopDevice(path string) (string, error) { _, err := os.Stat(path) if os.IsNotExist(err) { return \"\", errors.New(ErrNotAvailable)"} {"_id":"doc-en-kubernetes-03529cda5ddf763c1c7f6e7e6ffe726ebfc893f0402f989ac546a69f54684ebf","title":"","text":"return \"\", fmt.Errorf(\"not attachable: %v\", err) } args := []string{\"-j\", path} out, err := exec.Command(losetupPath, args...).CombinedOutput() if err != nil { klog.V(2).Infof(\"Failed device discover command for path %s: %v\", path, err) return \"\", err } return parseLosetupOutputForDevice(out) return getLoopDeviceFromSysfs(path) } func makeLoopDevice(path string, exec utilexec.Interface) (string, error) { args := []string{\"-f\", \"-P\", \"--show\", path} args := []string{\"-f\", \"-P\", path} out, err := exec.Command(losetupPath, args...).CombinedOutput() if err != nil { klog.V(2).Infof(\"Failed device create command for path %s: %v\", path, err) klog.V(2).Infof(\"Failed device create command for path %s: %v %s\", path, err, out) return \"\", err } return parseLosetupOutputForDevice(out) return getLoopDeviceFromSysfs(path) } func removeLoopDevice(device string, exec utilexec.Interface) error {"} {"_id":"doc-en-kubernetes-83a3a933d57b1341a5b2a58910a0319bec07a1fb2f0a6108fd775b5ac6d0ed0a","title":"","text":"return strings.HasPrefix(device, \"/dev/loop\") } func parseLosetupOutputForDevice(output []byte) (string, error) { if len(output) == 0 { // getLoopDeviceFromSysfs finds the backing file for a loop // device from sysfs via \"/sys/block/loop*/loop/backing_file\". func getLoopDeviceFromSysfs(path string) (string, error) { // If the file is a symlink. realPath, err := filepath.EvalSymlinks(path) if err != nil { return \"\", errors.New(ErrDeviceNotFound) } // losetup returns device in the format: // /dev/loop1: [0073]:148662 (/var/lib/storageos/volumes/308f14af-cf0a-08ff-c9c3-b48104318e05) device := strings.TrimSpace(strings.SplitN(string(output), \":\", 2)[0]) if len(device) == 0 { devices, err := filepath.Glob(\"/sys/block/loop*\") if err != nil { return \"\", errors.New(ErrDeviceNotFound) } return device, nil for _, device := range devices { backingFile := fmt.Sprintf(\"%s/loop/backing_file\", device) // The contents of this file is the absolute path of \"path\". data, err := ioutil.ReadFile(backingFile) if err != nil { continue } // Return the first match. backingFilePath := strings.TrimSpace(string(data)) if backingFilePath == path || backingFilePath == realPath { return fmt.Sprintf(\"/dev/%s\", filepath.Base(device)), nil } } return \"\", errors.New(ErrDeviceNotFound) }"} {"_id":"doc-en-kubernetes-8a297dc0433cfbadda60d618993f466885d4db213bac9e54bdf740c64dbb751e","title":"","text":"package volumepathhandler import ( \"bufio\" \"errors\" \"fmt\" \"io/ioutil\" \"os\" \"os/exec\" \"path/filepath\""} {"_id":"doc-en-kubernetes-c1689cfd29290068c8300447d803929853c336e5218f892959ecf6f5a630ef05","title":"","text":"return \"\", fmt.Errorf(\"not attachable: %v\", err) } args := []string{\"-j\", path} cmd := exec.Command(losetupPath, args...) out, err := cmd.CombinedOutput() if err != nil { klog.V(2).Infof(\"Failed device discover command for path %s: %v %s\", path, err, out) return \"\", fmt.Errorf(\"losetup -j %s failed: %v\", path, err) } return parseLosetupOutputForDevice(out, path) return getLoopDeviceFromSysfs(path) } func makeLoopDevice(path string) (string, error) { args := []string{\"-f\", \"--show\", path} args := []string{\"-f\", path} cmd := exec.Command(losetupPath, args...) out, err := cmd.CombinedOutput() if err != nil { klog.V(2).Infof(\"Failed device create command for path: %s %v %s \", path, err, out) return \"\", fmt.Errorf(\"losetup -f --show %s failed: %v\", path, err) klog.V(2).Infof(\"Failed device create command for path: %s %v %s\", path, err, out) return \"\", fmt.Errorf(\"losetup %s failed: %v\", strings.Join(args, \" \"), err) } // losetup -f --show {path} returns device in the format: // /dev/loop1 if len(out) == 0 { return \"\", errors.New(ErrDeviceNotFound) } return strings.TrimSpace(string(out)), nil return getLoopDeviceFromSysfs(path) } // removeLoopDevice removes specified loopback device"} {"_id":"doc-en-kubernetes-c24a051d29c6514876dd852324a5d3b8bec98e9cd36b8a291bc0ab2e7608960d","title":"","text":"return nil } func parseLosetupOutputForDevice(output []byte, path string) (string, error) { if len(output) == 0 { return \"\", errors.New(ErrDeviceNotFound) } // getLoopDeviceFromSysfs finds the backing file for a loop // device from sysfs via \"/sys/block/loop*/loop/backing_file\". func getLoopDeviceFromSysfs(path string) (string, error) { // If the file is a symlink. realPath, err := filepath.EvalSymlinks(path) if err != nil { return \"\", fmt.Errorf(\"failed to evaluate path %s: %s\", path, err) } // losetup -j {path} returns device in the format: // /dev/loop1: [0073]:148662 ({path}) // /dev/loop2: [0073]:148662 (/dev/sdX) // // losetup -j shows all the loop device for the same device that has the same // major/minor number, by resolving symlink and matching major/minor number. // Therefore, there will be other path than {path} in output, as shown in above output. s := string(output) // Find the line that exact matches to the path, or \"({path})\" var matched string scanner := bufio.NewScanner(strings.NewReader(s)) for scanner.Scan() { // losetup output has symlinks expanded if strings.HasSuffix(scanner.Text(), \"(\"+realPath+\")\") { matched = scanner.Text() break devices, err := filepath.Glob(\"/sys/block/loop*\") if err != nil { return \"\", fmt.Errorf(\"failed to list loop devices in sysfs: %s\", err) } for _, device := range devices { backingFile := fmt.Sprintf(\"%s/loop/backing_file\", device) // The contents of this file is the absolute path of \"path\". data, err := ioutil.ReadFile(backingFile) if err != nil { continue } // Just in case losetup changes, check for the original path too if strings.HasSuffix(scanner.Text(), \"(\"+path+\")\") { matched = scanner.Text() break // Return the first match. backingFilePath := strings.TrimSpace(string(data)) if backingFilePath == path || backingFilePath == realPath { return fmt.Sprintf(\"/dev/%s\", filepath.Base(device)), nil } } if len(matched) == 0 { return \"\", errors.New(ErrDeviceNotFound) } s = matched // Get device name, or the 0th field of the output separated with \":\". // We don't need 1st field or later to be splitted, so passing 2 to SplitN. device := strings.TrimSpace(strings.SplitN(s, \":\", 2)[0]) if len(device) == 0 { return \"\", errors.New(ErrDeviceNotFound) } return device, nil return \"\", errors.New(ErrDeviceNotFound) } // FindGlobalMapPathUUIDFromPod finds {pod uuid} bind mount under globalMapPath"} {"_id":"doc-en-kubernetes-494f7265cb8132e20d1199b7a402d64ebda6fc8f0c0a9f68173d3f7efb24c2f5","title":"","text":"import ( \"context\" \"k8s.io/api/core/v1\" v1 \"k8s.io/api/core/v1\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/kubernetes/test/e2e/framework\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\""} {"_id":"doc-en-kubernetes-49d3b11599fc9fa72ff39c10d1d570e368c2f385c71b9850ce19e21b2f9e42e3","title":"","text":"ginkgo.Describe(\"NFSv4\", func() { ginkgo.It(\"should be mountable for NFSv4\", func() { config, _, serverIP := volume.NewNFSServer(c, namespace.Name, []string{}) defer volume.TestCleanup(f, config) defer volume.TestServerCleanup(f, config) tests := []volume.Test{ {"} {"_id":"doc-en-kubernetes-c19b301e809465607ed89f5af298016d7d7b48fb308312e774d0ee60a1dedf3a","title":"","text":"ginkgo.Describe(\"NFSv3\", func() { ginkgo.It(\"should be mountable for NFSv3\", func() { config, _, serverIP := volume.NewNFSServer(c, namespace.Name, []string{}) defer volume.TestCleanup(f, config) defer volume.TestServerCleanup(f, config) tests := []volume.Test{ {"} {"_id":"doc-en-kubernetes-8ba0f40e9c1a9c0f0792699f658d35efc7758a7636ec9a1600384f3a7e37e777","title":"","text":"config, _, _ := volume.NewGlusterfsServer(c, namespace.Name) name := config.Prefix + \"-server\" defer func() { volume.TestCleanup(f, config) volume.TestServerCleanup(f, config) err := c.CoreV1().Endpoints(namespace.Name).Delete(context.TODO(), name, nil) framework.ExpectNoError(err, \"defer: Gluster delete endpoints failed\") }()"} {"_id":"doc-en-kubernetes-bfce813f0e4141880b555bb24241aa14c231f33bc1af5901c487151c11ed7fe5","title":"","text":"return pod } // TestCleanup cleans both server and client pods. func TestCleanup(f *framework.Framework, config TestConfig) { // TestServerCleanup cleans server pod. func TestServerCleanup(f *framework.Framework, config TestConfig) { ginkgo.By(fmt.Sprint(\"cleaning the environment after \", config.Prefix)) defer ginkgo.GinkgoRecover() cs := f.ClientSet err := e2epod.DeletePodWithWaitByName(cs, config.Prefix+\"-client\", config.Namespace) gomega.Expect(err).To(gomega.BeNil(), \"Failed to delete pod %v in namespace %v\", config.Prefix+\"-client\", config.Namespace) if config.ServerImage != \"\" { err := e2epod.DeletePodWithWaitByName(cs, config.Prefix+\"-server\", config.Namespace) gomega.Expect(err).To(gomega.BeNil(), \"Failed to delete pod %v in namespace %v\", config.Prefix+\"-server\", config.Namespace) if config.ServerImage == \"\" { return } err := e2epod.DeletePodWithWaitByName(f.ClientSet, config.Prefix+\"-server\", config.Namespace) gomega.Expect(err).To(gomega.BeNil(), \"Failed to delete pod %v in namespace %v\", config.Prefix+\"-server\", config.Namespace) } func runVolumeTesterPod(client clientset.Interface, config TestConfig, podSuffix string, privileged bool, fsGroup *int64, tests []Test) (*v1.Pod, error) {"} {"_id":"doc-en-kubernetes-c51c5d97b6658bf6f55c21c88c69b3276865350f82beb8d76f1753c379cfbd15","title":"","text":"clientPod, err := runVolumeTesterPod(f.ClientSet, config, \"client\", false, fsGroup, tests) if err != nil { framework.Failf(\"Failed to create client pod: %v\", err) } defer func() { e2epod.DeletePodOrFail(f.ClientSet, clientPod.Namespace, clientPod.Name) e2epod.WaitForPodToDisappear(f.ClientSet, clientPod.Namespace, clientPod.Name, labels.Everything(), framework.Poll, framework.PodDeleteTimeout) }() framework.ExpectNoError(e2epod.WaitForPodRunningInNamespace(f.ClientSet, clientPod)) testVolumeContent(f, clientPod, fsGroup, fsType, tests) }"} {"_id":"doc-en-kubernetes-b7ebeff527c7ce4c52ec3f15dbac2e1ffb33c5ed9359ac8e29fcd6720f85b767","title":"","text":"}, } volume.TestVolumeClient(f, config, nil, \"\" /* fsType */, tests) volume.TestCleanup(f, config) } // installFlex installs the driver found at filePath on the node, and restarts"} {"_id":"doc-en-kubernetes-ff1ca8ebc5149fde557a9d3b4fddf939ebfe34da807e1744d5e8accb7b12dfbb","title":"","text":"init() defer func() { volume.TestCleanup(f, convertTestConfig(l.config)) volume.TestServerCleanup(f, convertTestConfig(l.config)) cleanup() }()"} {"_id":"doc-en-kubernetes-6eb9f2e7b419de380e710d4faf31e20953cf2318f4c2169058eb1f57edc489e3","title":"","text":"import ( \"context\" \"github.com/onsi/ginkgo\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\""} {"_id":"doc-en-kubernetes-6949bf5c7163d5c6aa9ee9c170cd53ff24c922934aa9e3d1990fd46745fda628","title":"","text":"Namespace: namespace.Name, Prefix: \"configmap\", } defer volume.TestCleanup(f, config) configMap := &v1.ConfigMap{ TypeMeta: metav1.TypeMeta{ Kind: \"ConfigMap\","} {"_id":"doc-en-kubernetes-f9d33c30e006f0c73b73390e6388ad349bac1ddd2eced596023fab202210eee1","title":"","text":"imagePullTest(image, false, v1.PodPending, true, false) }) ginkgo.It(\"should not be able to pull non-existing image from gcr.io [NodeConformance]\", func() { image := imageutils.GetE2EImage(imageutils.Invalid) imagePullTest(image, false, v1.PodPending, true, false) }) ginkgo.It(\"should be able to pull image from gcr.io [NodeConformance]\", func() { image := imageutils.GetE2EImage(imageutils.DebianBase) isWindows := false if framework.NodeOSDistroIs(\"windows\") { image = imageutils.GetE2EImage(imageutils.WindowsNanoServer) isWindows = true } imagePullTest(image, false, v1.PodRunning, false, isWindows) }) ginkgo.It(\"should be able to pull image from docker hub [NodeConformance]\", func() { image := imageutils.GetE2EImage(imageutils.Alpine) isWindows := false if framework.NodeOSDistroIs(\"windows\") { // TODO(claudiub): Switch to nanoserver image manifest list. image = \"e2eteam/busybox:1.29\" isWindows = true } imagePullTest(image, false, v1.PodRunning, false, isWindows) ginkgo.It(\"should be able to pull image [NodeConformance]\", func() { // NOTE(claudiub): The agnhost image is supposed to work on both Linux and Windows. image := imageutils.GetE2EImage(imageutils.Agnhost) imagePullTest(image, false, v1.PodRunning, false, false) }) ginkgo.It(\"should not be able to pull from private registry without secret [NodeConformance]\", func() {"} {"_id":"doc-en-kubernetes-ee86baf4baf2e001ccda130de08087d5748d8efa42866b7e33f26e07b8cb7d64","title":"","text":"const ( // Agnhost image Agnhost = iota // Alpine image Alpine // APIServer image APIServer // AppArmorLoader image"} {"_id":"doc-en-kubernetes-1b11713a8aae2375ccc75fba7c7072172b198c3fc5ad38f0cf34df4ffbcb31f7","title":"","text":"CudaVectorAdd2 // Dnsutils image Dnsutils // DebianBase image DebianBase // EchoServer image EchoServer // Etcd image"} {"_id":"doc-en-kubernetes-d24b1c6977fed0710039d35f37aaaa23d7448cd353291705b7a749e1b9413fff","title":"","text":"Httpd // HttpdNew image HttpdNew // Invalid image Invalid // InvalidRegistryImage image InvalidRegistryImage // IpcUtils image"} {"_id":"doc-en-kubernetes-87c5b9daf4a03a46a7adfb2068fc5863ee8ddd24ff0b53e3333ca24d33380f06","title":"","text":"VolumeGlusterServer // VolumeRBDServer image VolumeRBDServer // WindowsNanoServer image WindowsNanoServer ) func initImageConfigs() map[int]Config { configs := map[int]Config{} configs[Agnhost] = Config{e2eRegistry, \"agnhost\", \"2.6\"} configs[Alpine] = Config{dockerLibraryRegistry, \"alpine\", \"3.7\"} configs[AuthenticatedAlpine] = Config{gcAuthenticatedRegistry, \"alpine\", \"3.7\"} configs[AuthenticatedWindowsNanoServer] = Config{gcAuthenticatedRegistry, \"windows-nanoserver\", \"v1\"} configs[APIServer] = Config{e2eRegistry, \"sample-apiserver\", \"1.10\"}"} {"_id":"doc-en-kubernetes-5f032197ef0afab3e0b8080f5ff46f2c9ea4e25cca8005ba39762924f2211f0e","title":"","text":"configs[CudaVectorAdd] = Config{e2eRegistry, \"cuda-vector-add\", \"1.0\"} configs[CudaVectorAdd2] = Config{e2eRegistry, \"cuda-vector-add\", \"2.0\"} configs[Dnsutils] = Config{e2eRegistry, \"dnsutils\", \"1.1\"} configs[DebianBase] = Config{googleContainerRegistry, \"debian-base\", \"0.4.1\"} configs[EchoServer] = Config{e2eRegistry, \"echoserver\", \"2.2\"} configs[Etcd] = Config{gcRegistry, \"etcd\", \"3.3.15\"} configs[GBFrontend] = Config{sampleRegistry, \"gb-frontend\", \"v6\"} configs[GlusterDynamicProvisioner] = Config{dockerGluster, \"glusterdynamic-provisioner\", \"v1.0\"} configs[Httpd] = Config{dockerLibraryRegistry, \"httpd\", \"2.4.38-alpine\"} configs[HttpdNew] = Config{dockerLibraryRegistry, \"httpd\", \"2.4.39-alpine\"} configs[Invalid] = Config{gcRegistry, \"invalid-image\", \"invalid-tag\"} configs[InvalidRegistryImage] = Config{invalidRegistry, \"alpine\", \"3.1\"} configs[IpcUtils] = Config{e2eRegistry, \"ipc-utils\", \"1.0\"} configs[JessieDnsutils] = Config{e2eRegistry, \"jessie-dnsutils\", \"1.0\"}"} {"_id":"doc-en-kubernetes-b708c7441ba21184d4d4bf85a5416af92a73abc641c4be545d435224399e6775","title":"","text":"configs[VolumeISCSIServer] = Config{e2eRegistry, \"volume/iscsi\", \"2.0\"} configs[VolumeGlusterServer] = Config{e2eRegistry, \"volume/gluster\", \"1.0\"} configs[VolumeRBDServer] = Config{e2eRegistry, \"volume/rbd\", \"1.0.1\"} configs[WindowsNanoServer] = Config{e2eRegistry, \"windows-nanoserver\", \"v1\"} return configs }"} {"_id":"doc-en-kubernetes-6b10da08ad5922eeda1928f7f2015887b559a86efd8837555e381566e977ea69","title":"","text":"if priorityConfigs[i].Function != nil { wg.Add(1) go func(index int) { defer wg.Done() metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_legacy\").Inc() defer func() { metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_legacy\").Dec() wg.Done() }() var err error results[index], err = priorityConfigs[index].Function(pod, nodeNameToInfo, nodes) if err != nil {"} {"_id":"doc-en-kubernetes-511b38e072ccd24d5b209411bb73c7ee7f8bed2b22341d94729c597e2d4d0e65","title":"","text":"} wg.Add(1) go func(index int) { defer wg.Done() metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_mapreduce\").Inc() defer func() { metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_mapreduce\").Dec() wg.Done() }() if err := priorityConfigs[index].Reduce(pod, meta, nodeNameToInfo, results[index]); err != nil { appendError(err) }"} {"_id":"doc-en-kubernetes-1edf4f0edec1425417e6ff5cc17cab428d7209549a9c75d9d92ffaae284de4c0","title":"","text":"} wg.Add(1) go func(extIndex int) { defer wg.Done() metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_extender\").Inc() defer func() { metrics.SchedulerGoroutines.WithLabelValues(\"prioritizing_extender\").Dec() wg.Done() }() prioritizedList, weight, err := extenders[extIndex].Prioritize(pod, nodes) if err != nil { // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities"} {"_id":"doc-en-kubernetes-c4c90371447ff6efb8f79e09a872352be202525043409f31475ea32e1e221c9c","title":"","text":"Help: \"Total preemption attempts in the cluster till now\", StabilityLevel: metrics.ALPHA, }) pendingPods = metrics.NewGaugeVec( &metrics.GaugeOpts{ Subsystem: SchedulerSubsystem,"} {"_id":"doc-en-kubernetes-653a9b6c9812236bfc14c009c14eef882fcd6b848b979e2f83dd563f9edc35be","title":"","text":"Help: \"Number of pending pods, by the queue type. 'active' means number of pods in activeQ; 'backoff' means number of pods in backoffQ; 'unschedulable' means number of pods in unschedulableQ.\", StabilityLevel: metrics.ALPHA, }, []string{\"queue\"}) SchedulerGoroutines = metrics.NewGaugeVec( &metrics.GaugeOpts{ Subsystem: SchedulerSubsystem, Name: \"scheduler_goroutines\", Help: \"Number of running goroutines split by the work they do such as binding.\", StabilityLevel: metrics.ALPHA, }, []string{\"work\"}) PodSchedulingDuration = metrics.NewHistogram( &metrics.HistogramOpts{"} {"_id":"doc-en-kubernetes-89a12dfe647db7c1fdcfd69ee3b1c9cd0567dc3d0c75163892f455e0a5f1e858","title":"","text":"PodSchedulingAttempts, FrameworkExtensionPointDuration, SchedulerQueueIncomingPods, SchedulerGoroutines, } )"} {"_id":"doc-en-kubernetes-775adfcd45179da3018b0cedc12de71ae1c88dbe8d62d4a867a3e5263a4e7a53","title":"","text":"} // bind the pod to its host asynchronously (we can do this b/c of the assumption step above). go func() { metrics.SchedulerGoroutines.WithLabelValues(\"binding\").Inc() defer metrics.SchedulerGoroutines.WithLabelValues(\"binding\").Dec() // Bind volumes first before Pod if !allBound { err := sched.bindVolumes(assumedPod)"} {"_id":"doc-en-kubernetes-d87084062b2577495f79031e5bf15934e07e66a5e2f784f7bc6130c89c25b4e5","title":"","text":"} } func (e *eventBroadcasterImpl) Shutdown() { e.Broadcaster.Shutdown() } // refreshExistingEventSeries refresh events TTL func (e *eventBroadcasterImpl) refreshExistingEventSeries() { // TODO: Investigate whether lock contention won't be a problem"} {"_id":"doc-en-kubernetes-d31f0392f104a5ad5b657c8b4808b75c9f9e0d0ecb626e5183b6fbac31a9db7e","title":"","text":"// NOTE: events received on your eventHandler should be copied before being used. // TODO: figure out if this can be removed. StartEventWatcher(eventHandler func(event runtime.Object)) func() // Shutdown shuts down the broadcaster Shutdown() } // EventSink knows how to store events (client-go implements it.)"} {"_id":"doc-en-kubernetes-6b1876fcd9ebf154defa6286c3325e4007fad471d85b2f693313885ad8a3123b","title":"","text":"// NewRecorder returns an EventRecorder that can be used to send events to this EventBroadcaster // with the event source set to the given event source. NewRecorder(scheme *runtime.Scheme, source v1.EventSource) EventRecorder // Shutdown shuts down the broadcaster Shutdown() } // Creates a new event broadcaster."} {"_id":"doc-en-kubernetes-2b246f7b0184256b0f1159d9cfd814387908c40363878553e75c2b7a12e2a723","title":"","text":"}) } func (e *eventBroadcasterImpl) Shutdown() { e.Broadcaster.Shutdown() } func recordToSink(sink EventSink, event *v1.Event, eventCorrelator *EventCorrelator, sleepDuration time.Duration) { // Make a copy before modification, because there could be multiple listeners. // Events are safe to copy like this."} {"_id":"doc-en-kubernetes-7753e0950c033dba92561ee6d25f93cd0bdcb3b65720d7fab056c2539dcec578","title":"","text":"cs := context.clientSet podLabel := map[string]string{\"service\": \"securityscan\"} // podLabel2 := map[string]string{\"security\": \"S1\"} podLabel2 := map[string]string{\"security\": \"S1\"} tests := []struct { pod *v1.Pod"} {"_id":"doc-en-kubernetes-ae4e3ff221b0d846515a59eaa4d52a86f1d6f8c2c9e904311a3607fc7809ca12","title":"","text":"errorType string test string }{ /*{ { pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"fakename\","} {"_id":"doc-en-kubernetes-1e9ac719028fce2898840089a02db51054a52f100308c16ea7503fd6ecc4261d","title":"","text":"{ Key: \"security\", Operator: metav1.LabelSelectorOpDoesNotExist, Values: []string{\"securityscan\"}, }, }, },"} {"_id":"doc-en-kubernetes-c4437323359c538d9bbddd5bcbd6651281d8b199ab5a3f7d1a98141320f97450","title":"","text":"node: nodes[0], fits: false, test: \"satisfies the PodAffinity but doesn't satisfies the PodAntiAffinity with the existing pod\", },*/ }, { pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{"} {"_id":"doc-en-kubernetes-35e9de97240498e95acc01edf4aab773a8df4f90db0ea89d9f49ce742c47f1ba","title":"","text":"} // sanityCheckService performs sanity checks on the given service; in particular, ensuring // that creating/updating a service allocates IPs, ports, etc, as needed. // that creating/updating a service allocates IPs, ports, etc, as needed. It does not // check for ingress assignment as that happens asynchronously after the Service is created. func (j *TestJig) sanityCheckService(svc *v1.Service, svcType v1.ServiceType) (*v1.Service, error) { if svcType == \"\" { svcType = v1.ServiceTypeClusterIP"} {"_id":"doc-en-kubernetes-813ae0e22d63c211d136fc73694521fff0f2e85823670a5b3986182081b20b17","title":"","text":"} } } expectIngress := false if svcType == v1.ServiceTypeLoadBalancer { expectIngress = true } hasIngress := len(svc.Status.LoadBalancer.Ingress) != 0 if hasIngress != expectIngress { return nil, fmt.Errorf(\"unexpected number of Status.LoadBalancer.Ingress (%d) for service\", len(svc.Status.LoadBalancer.Ingress)) } if hasIngress { for i, ing := range svc.Status.LoadBalancer.Ingress { if ing.IP == \"\" && ing.Hostname == \"\" { return nil, fmt.Errorf(\"unexpected Status.LoadBalancer.Ingress[%d] for service: %#v\", i, ing) } if svcType != v1.ServiceTypeLoadBalancer { if len(svc.Status.LoadBalancer.Ingress) != 0 { return nil, fmt.Errorf(\"unexpected Status.LoadBalancer.Ingress on non-LoadBalancer service\") } }"} {"_id":"doc-en-kubernetes-049424c99a6c96a720d347e5f8935fd41fc8faa08dff8eee3ae54af1a5eb018e","title":"","text":"if err != nil { return nil, err } for i, ing := range service.Status.LoadBalancer.Ingress { if ing.IP == \"\" && ing.Hostname == \"\" { return nil, fmt.Errorf(\"unexpected Status.LoadBalancer.Ingress[%d] for service: %#v\", i, ing) } } return j.sanityCheckService(service, v1.ServiceTypeLoadBalancer) }"} {"_id":"doc-en-kubernetes-8fe3e6ffa6f7a2ea8f0f211a327180e98ba6f5c0001439b2aba78d47d5977e34","title":"","text":"flags.DurationVar(&nodeKiller.SimulatedDowntime, \"node-killer-simulated-downtime\", 10*time.Minute, \"A delay between node death and recreation\") } // RegisterNodeFlags registers flags specific to the node e2e test suite. func RegisterNodeFlags(flags *flag.FlagSet) { // Mark the test as node e2e when node flags are api.Registry. TestContext.NodeE2E = true flags.StringVar(&TestContext.NodeName, \"node-name\", \"\", \"Name of the node to run tests on.\") // TODO(random-liu): Move kubelet start logic out of the test. // TODO(random-liu): Move log fetch logic out of the test. // There are different ways to start kubelet (systemd, initd, docker, manually started etc.) // and manage logs (journald, upstart etc.). // For different situation we need to mount different things into the container, run different commands. // It is hard and unnecessary to deal with the complexity inside the test suite. flags.BoolVar(&TestContext.NodeConformance, \"conformance\", false, \"If true, the test suite will not start kubelet, and fetch system log (kernel, docker, kubelet log etc.) to the report directory.\") flags.BoolVar(&TestContext.PrepullImages, \"prepull-images\", true, \"If true, prepull images so image pull failures do not cause test failures.\") flags.StringVar(&TestContext.ImageDescription, \"image-description\", \"\", \"The description of the image which the test will be running on.\") flags.StringVar(&TestContext.SystemSpecName, \"system-spec-name\", \"\", \"The name of the system spec (e.g., gke) that's used in the node e2e test. The system specs are in test/e2e_node/system/specs/. This is used by the test framework to determine which tests to run for validating the system requirements.\") flags.Var(cliflag.NewMapStringString(&TestContext.ExtraEnvs), \"extra-envs\", \"The extra environment variables needed for node e2e tests. Format: a list of key=value pairs, e.g., env1=val1,env2=val2\") } func createKubeConfig(clientCfg *restclient.Config) *clientcmdapi.Config { clusterNick := \"cluster\" userNick := \"user\""} {"_id":"doc-en-kubernetes-7a4b9dc4fdcf85eff5540e68c07608ba99d526364c118ea7d7f034fc3f522507","title":"","text":"\"//staging/src/k8s.io/apimachinery/pkg/runtime:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/yaml:go_default_library\", \"//staging/src/k8s.io/client-go/tools/cache:go_default_library\", \"//staging/src/k8s.io/component-base/cli/flag:go_default_library\", \"//test/e2e/framework/config:go_default_library\", \"//test/e2e/framework/kubelet:go_default_library\", \"//test/e2e/framework/perf:go_default_library\","} {"_id":"doc-en-kubernetes-bb061d1a56dc65a917f55c2f7d94f307640861d6d1678f8d41b20a7852a1df2e","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" utilyaml \"k8s.io/apimachinery/pkg/util/yaml\" clientset \"k8s.io/client-go/kubernetes\" cliflag \"k8s.io/component-base/cli/flag\" commontest \"k8s.io/kubernetes/test/e2e/common\" \"k8s.io/kubernetes/test/e2e/framework\" e2econfig \"k8s.io/kubernetes/test/e2e/framework/config\""} {"_id":"doc-en-kubernetes-d8ea195739ba3a0cd3560186b2f4ae3426356c2bc63c3dbe1f2bae7376420bfc","title":"","text":"var systemValidateMode = flag.Bool(\"system-validate-mode\", false, \"If true, only run system validation in current process, and not run test.\") var systemSpecFile = flag.String(\"system-spec-file\", \"\", \"The name of the system spec file that will be used for node conformance test. If it's unspecified or empty, the default system spec (system.DefaultSysSpec) will be used.\") // registerNodeFlags registers flags specific to the node e2e test suite. func registerNodeFlags(flags *flag.FlagSet) { // Mark the test as node e2e when node flags are api.Registry. framework.TestContext.NodeE2E = true flags.StringVar(&framework.TestContext.NodeName, \"node-name\", \"\", \"Name of the node to run tests on.\") // TODO(random-liu): Move kubelet start logic out of the test. // TODO(random-liu): Move log fetch logic out of the test. // There are different ways to start kubelet (systemd, initd, docker, manually started etc.) // and manage logs (journald, upstart etc.). // For different situation we need to mount different things into the container, run different commands. // It is hard and unnecessary to deal with the complexity inside the test suite. flags.BoolVar(&framework.TestContext.NodeConformance, \"conformance\", false, \"If true, the test suite will not start kubelet, and fetch system log (kernel, docker, kubelet log etc.) to the report directory.\") flags.BoolVar(&framework.TestContext.PrepullImages, \"prepull-images\", true, \"If true, prepull images so image pull failures do not cause test failures.\") flags.StringVar(&framework.TestContext.ImageDescription, \"image-description\", \"\", \"The description of the image which the test will be running on.\") flags.StringVar(&framework.TestContext.SystemSpecName, \"system-spec-name\", \"\", \"The name of the system spec (e.g., gke) that's used in the node e2e test. The system specs are in test/e2e_node/system/specs/. This is used by the test framework to determine which tests to run for validating the system requirements.\") flags.Var(cliflag.NewMapStringString(&framework.TestContext.ExtraEnvs), \"extra-envs\", \"The extra environment variables needed for node e2e tests. Format: a list of key=value pairs, e.g., env1=val1,env2=val2\") } func init() { // Enable bindata file lookup as fallback. testfiles.AddFileSource(testfiles.BindataFileSource{"} {"_id":"doc-en-kubernetes-cb757b27cb3b28400abbcf849bfc2cc5b84c27a982efc72e5291b10998daede5","title":"","text":"// Copy go flags in TestMain, to ensure go test flags are registered (no longer available in init() as of go1.13) e2econfig.CopyFlags(e2econfig.Flags, flag.CommandLine) framework.RegisterCommonFlags(flag.CommandLine) framework.RegisterNodeFlags(flag.CommandLine) registerNodeFlags(flag.CommandLine) pflag.CommandLine.AddGoFlagSet(flag.CommandLine) // Mark the run-services-mode flag as hidden to prevent user from using it. pflag.CommandLine.MarkHidden(\"run-services-mode\")"} {"_id":"doc-en-kubernetes-a95e08e369ec2be1b730769b9a565ffff79e342816c559f6497e889b11b7d826","title":"","text":"deps = [ \"//staging/src/k8s.io/api/core/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/uuid:go_default_library\", \"//staging/src/k8s.io/csi-translation-lib/plugins:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-0b9e64f938109dfd8b66e91a1bf1e4c88834bcdea8c23f0ba977931dbf3bfdae","title":"","text":"github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY="} {"_id":"doc-en-kubernetes-36559366fb1def4aa20913bdd65662a8bf95d790111834785d4164605b5e2901","title":"","text":"} pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ // A.K.A InnerVolumeSpecName required to match for Unmount Name: volume.Name, // Must be unique per disk as it is used as the unique part of the // staging path Name: fmt.Sprintf(\"%s-%s\", AWSEBSDriverName, ebsSource.VolumeID), }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{"} {"_id":"doc-en-kubernetes-968ec7940511b4f2240d314d20acb44caf0517084f8d534fb46ee8f138944f11","title":"","text":"azureSource := volume.AzureDisk pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ // A.K.A InnerVolumeSpecName required to match for Unmount Name: volume.Name, // Must be unique per disk as it is used as the unique part of the // staging path Name: fmt.Sprintf(\"%s-%s\", AzureDiskDriverName, azureSource.DiskName), }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{"} {"_id":"doc-en-kubernetes-35425cb460ecfbe3119b19b8b164715ae06c84e46644103bc85aa7fbc08e906a","title":"","text":"pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ // A.K.A InnerVolumeSpecName required to match for Unmount Name: volume.Name, // Must be unique per disk as it is used as the unique part of the // staging path Name: fmt.Sprintf(\"%s-%s\", AzureFileDriverName, azureSource.ShareName), }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{"} {"_id":"doc-en-kubernetes-c8d4988c774b9d5e433d094a64d3ee17ee3e582153920e30897352f85edcccd8","title":"","text":"return &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ // A.K.A InnerVolumeSpecName required to match for Unmount Name: volume.Name, // Must be unique per disk as it is used as the unique part of the // staging path Name: fmt.Sprintf(\"%s-%s\", GCEPDDriverName, pdSource.PDName), }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{"} {"_id":"doc-en-kubernetes-7ad3c849f4140ea2c06007a7ec6d3c79dc2d507ebcc2111d499f603879fe0eaa","title":"","text":"cinderSource := volume.Cinder pv := &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ // A.K.A InnerVolumeSpecName required to match for Unmount Name: volume.Name, // Must be unique per disk as it is used as the unique part of the // staging path Name: fmt.Sprintf(\"%s-%s\", CinderDriverName, cinderSource.VolumeID), }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{"} {"_id":"doc-en-kubernetes-ea79a74dae67f4845e13243494b29b593495ed0d175ea73747d112aead5e23ff","title":"","text":"package csitranslation import ( \"fmt\" \"reflect\" \"testing\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/csi-translation-lib/plugins\" )"} {"_id":"doc-en-kubernetes-c72d978a2b8a18c83f735b5989ad2ad012cb11d66169ae50fe08d6a362085b14","title":"","text":"} } func TestTranslateInTreeInlineVolumeToCSINameUniqueness(t *testing.T) { for driverName := range inTreePlugins { t.Run(driverName, func(t *testing.T) { ctl := New() vs1, err := generateUniqueVolumeSource(driverName) if err != nil { t.Fatalf(\"Couldn't generate random source: %v\", err) } pv1, err := ctl.TranslateInTreeInlineVolumeToCSI(&v1.Volume{ VolumeSource: vs1, }) if err != nil { t.Fatalf(\"Error when translating to CSI: %v\", err) } vs2, err := generateUniqueVolumeSource(driverName) if err != nil { t.Fatalf(\"Couldn't generate random source: %v\", err) } pv2, err := ctl.TranslateInTreeInlineVolumeToCSI(&v1.Volume{ VolumeSource: vs2, }) if err != nil { t.Fatalf(\"Error when translating to CSI: %v\", err) } if pv1 == nil || pv2 == nil { t.Fatalf(\"Did not expect either pv1: %v or pv2: %v to be nil\", pv1, pv2) } if pv1.Name == pv2.Name { t.Errorf(\"PV name %s not sufficiently unique for different volumes\", pv1.Name) } }) } } func generateUniqueVolumeSource(driverName string) (v1.VolumeSource, error) { switch driverName { case plugins.GCEPDDriverName: return v1.VolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: string(uuid.NewUUID()), }, }, nil case plugins.AWSEBSDriverName: return v1.VolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: string(uuid.NewUUID()), }, }, nil case plugins.CinderDriverName: return v1.VolumeSource{ Cinder: &v1.CinderVolumeSource{ VolumeID: string(uuid.NewUUID()), }, }, nil case plugins.AzureDiskDriverName: return v1.VolumeSource{ AzureDisk: &v1.AzureDiskVolumeSource{ DiskName: string(uuid.NewUUID()), DataDiskURI: string(uuid.NewUUID()), }, }, nil case plugins.AzureFileDriverName: return v1.VolumeSource{ AzureFile: &v1.AzureFileVolumeSource{ SecretName: string(uuid.NewUUID()), ShareName: string(uuid.NewUUID()), }, }, nil default: return v1.VolumeSource{}, fmt.Errorf(\"couldn't find logic for driver: %v\", driverName) } } func TestPluginNameMappings(t *testing.T) { testCases := []struct { name string"} {"_id":"doc-en-kubernetes-9af9ac6e810a49d7554c8f35b2d0d076c8412f868295f0c0a33f8ac993cf582a","title":"","text":"return sgList, setupSg, nil } // sortELBSecurityGroupList returns a list of sorted securityGroupIDs based on the original order // from buildELBSecurityGroupList. The logic is: // * securityGroups specified by ServiceAnnotationLoadBalancerSecurityGroups appears first in order // * securityGroups specified by ServiceAnnotationLoadBalancerExtraSecurityGroups appears last in order func (c *Cloud) sortELBSecurityGroupList(securityGroupIDs []string, annotations map[string]string) { annotatedSGList := getSGListFromAnnotation(annotations[ServiceAnnotationLoadBalancerSecurityGroups]) annotatedExtraSGList := getSGListFromAnnotation(annotations[ServiceAnnotationLoadBalancerExtraSecurityGroups]) annotatedSGIndex := make(map[string]int, len(annotatedSGList)) annotatedExtraSGIndex := make(map[string]int, len(annotatedExtraSGList)) for i, sgID := range annotatedSGList { annotatedSGIndex[sgID] = i } for i, sgID := range annotatedExtraSGList { annotatedExtraSGIndex[sgID] = i } sgOrderMapping := make(map[string]int, len(securityGroupIDs)) for _, sgID := range securityGroupIDs { if i, ok := annotatedSGIndex[sgID]; ok { sgOrderMapping[sgID] = i } else if j, ok := annotatedExtraSGIndex[sgID]; ok { sgOrderMapping[sgID] = len(annotatedSGIndex) + 1 + j } else { sgOrderMapping[sgID] = len(annotatedSGIndex) } } sort.Slice(securityGroupIDs, func(i, j int) bool { return sgOrderMapping[securityGroupIDs[i]] < sgOrderMapping[securityGroupIDs[j]] }) } // buildListener creates a new listener from the given port, adding an SSL certificate // if indicated by the appropriate annotations. func buildListener(port v1.ServicePort, annotations map[string]string, sslPorts *portSets) (*elb.Listener, error) {"} {"_id":"doc-en-kubernetes-b7c23a57bbf1d1304e07f5cb2f402616299f1265bd861a52d812f26da1dffbc0","title":"","text":"} } err = c.updateInstanceSecurityGroupsForLoadBalancer(loadBalancer, instances) err = c.updateInstanceSecurityGroupsForLoadBalancer(loadBalancer, instances, annotations) if err != nil { klog.Warningf(\"Error opening ingress rules for the load balancer to the instances: %q\", err) return nil, err"} {"_id":"doc-en-kubernetes-1443e7f9734ccdf52162b8686ff6134cfdd987d45fa9ee5ac4a82d3c31df7e2f","title":"","text":"// Open security group ingress rules on the instances so that the load balancer can talk to them // Will also remove any security groups ingress rules for the load balancer that are _not_ needed for allInstances func (c *Cloud) updateInstanceSecurityGroupsForLoadBalancer(lb *elb.LoadBalancerDescription, instances map[InstanceID]*ec2.Instance) error { func (c *Cloud) updateInstanceSecurityGroupsForLoadBalancer(lb *elb.LoadBalancerDescription, instances map[InstanceID]*ec2.Instance, annotations map[string]string) error { if c.cfg.Global.DisableSecurityGroupIngress { return nil } // Determine the load balancer security group id loadBalancerSecurityGroupID := \"\" for _, securityGroup := range lb.SecurityGroups { if aws.StringValue(securityGroup) == \"\" { continue } if loadBalancerSecurityGroupID != \"\" { // We create LBs with one SG klog.Warningf(\"Multiple security groups for load balancer: %q\", aws.StringValue(lb.LoadBalancerName)) } loadBalancerSecurityGroupID = *securityGroup } if loadBalancerSecurityGroupID == \"\" { lbSecurityGroupIDs := aws.StringValueSlice(lb.SecurityGroups) if len(lbSecurityGroupIDs) == 0 { return fmt.Errorf(\"could not determine security group for load balancer: %s\", aws.StringValue(lb.LoadBalancerName)) } c.sortELBSecurityGroupList(lbSecurityGroupIDs, annotations) loadBalancerSecurityGroupID := lbSecurityGroupIDs[0] // Get the actual list of groups that allow ingress from the load-balancer var actualGroups []*ec2.SecurityGroup"} {"_id":"doc-en-kubernetes-2e80dc51078a559ec5d655e55a7239efe781bb8df1ad62c2c78238e7336f1a18","title":"","text":"{ // De-authorize the load balancer security group from the instances security group err = c.updateInstanceSecurityGroupsForLoadBalancer(lb, nil) err = c.updateInstanceSecurityGroupsForLoadBalancer(lb, nil, service.Annotations) if err != nil { klog.Errorf(\"Error deregistering load balancer from instance security groups: %q\", err) return err"} {"_id":"doc-en-kubernetes-4d6f0003921f6cc02f3324c8654099bfd4071ef14300cffd3f19a9d8b19a0fca","title":"","text":"return nil } err = c.updateInstanceSecurityGroupsForLoadBalancer(lb, instances) err = c.updateInstanceSecurityGroupsForLoadBalancer(lb, instances, service.Annotations) if err != nil { return err }"} {"_id":"doc-en-kubernetes-e450ac5eb87f938fe5da880153d486741880ba2c9e345bb5de3012eee76b43c5","title":"","text":"assert.Equal(t, testCase.region, result) } } func TestCloud_sortELBSecurityGroupList(t *testing.T) { type args struct { securityGroupIDs []string annotations map[string]string } tests := []struct { name string args args wantSecurityGroupIDs []string }{ { name: \"with no annotation\", args: args{ securityGroupIDs: []string{\"sg-1\"}, annotations: map[string]string{}, }, wantSecurityGroupIDs: []string{\"sg-1\"}, }, { name: \"with service.beta.kubernetes.io/aws-load-balancer-security-groups\", args: args{ securityGroupIDs: []string{\"sg-2\", \"sg-1\", \"sg-3\"}, annotations: map[string]string{ \"service.beta.kubernetes.io/aws-load-balancer-security-groups\": \"sg-3,sg-2,sg-1\", }, }, wantSecurityGroupIDs: []string{\"sg-3\", \"sg-2\", \"sg-1\"}, }, { name: \"with service.beta.kubernetes.io/aws-load-balancer-extra-security-groups\", args: args{ securityGroupIDs: []string{\"sg-2\", \"sg-1\", \"sg-3\", \"sg-4\"}, annotations: map[string]string{ \"service.beta.kubernetes.io/aws-load-balancer-extra-security-groups\": \"sg-3,sg-2,sg-1\", }, }, wantSecurityGroupIDs: []string{\"sg-4\", \"sg-3\", \"sg-2\", \"sg-1\"}, }, { name: \"with both annotation\", args: args{ securityGroupIDs: []string{\"sg-2\", \"sg-1\", \"sg-3\", \"sg-4\", \"sg-5\", \"sg-6\"}, annotations: map[string]string{ \"service.beta.kubernetes.io/aws-load-balancer-security-groups\": \"sg-3,sg-2,sg-1\", \"service.beta.kubernetes.io/aws-load-balancer-extra-security-groups\": \"sg-6,sg-5\", }, }, wantSecurityGroupIDs: []string{\"sg-3\", \"sg-2\", \"sg-1\", \"sg-4\", \"sg-6\", \"sg-5\"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := &Cloud{} c.sortELBSecurityGroupList(tt.args.securityGroupIDs, tt.args.annotations) assert.Equal(t, tt.wantSecurityGroupIDs, tt.args.securityGroupIDs) }) } } "} {"_id":"doc-en-kubernetes-9dd3b2e3e1991cac99e91312e55ec6a82b85c2a4108acc40f82f472f534b84ad","title":"","text":"return } if shouldHide(&version, selfVersion) { klog.Warningf(\"This metric(%s) has been deprecated for more than one release, hiding.\", d.fqName) // TODO(RainbowMango): Remove this log temporarily. https://github.com/kubernetes/kubernetes/issues/85369 // klog.Warningf(\"This metric(%s) has been deprecated for more than one release, hiding.\", d.fqName) d.isHidden = true } })"} {"_id":"doc-en-kubernetes-39cf3611231f3c96eccb55d8ec265eea79b4ac6bc483081f6a687c3473aa5af8","title":"","text":"return } if shouldHide(&version, selfVersion) { klog.Warningf(\"This metric has been deprecated for more than one release, hiding.\") // TODO(RainbowMango): Remove this log temporarily. https://github.com/kubernetes/kubernetes/issues/85369 // klog.Warningf(\"This metric has been deprecated for more than one release, hiding.\") r.isHidden = true } })"} {"_id":"doc-en-kubernetes-74af717e026a1f835b1b486e7d8387039380b0410669306695dad7fa1ffef30c","title":"","text":"// TODO: remove the check, because we support no-op updates now. if graceful || pendingFinalizers || shouldUpdateFinalizers { err, ignoreNotFound, deleteImmediately, out, lastExisting = e.updateForGracefulDeletionAndFinalizers(ctx, name, key, options, preconditions, deleteValidation, obj) // Update the preconditions.ResourceVersion if set since we updated the object. if err == nil && deleteImmediately && preconditions.ResourceVersion != nil { accessor, err = meta.Accessor(out) if err != nil { return out, false, kubeerr.NewInternalError(err) } resourceVersion := accessor.GetResourceVersion() preconditions.ResourceVersion = &resourceVersion } } // !deleteImmediately covers all cases where err != nil. We keep both to be future-proof."} {"_id":"doc-en-kubernetes-e3b54e92d11814255e554d35d0e097ac35e3db81bad04f77b46fc25fa6c5ee97","title":"","text":"} } func TestStoreGracefulDeleteWithResourceVersion(t *testing.T) { podA := &example.Pod{ ObjectMeta: metav1.ObjectMeta{Name: \"foo\"}, Spec: example.PodSpec{NodeName: \"machine\"}, } testContext := genericapirequest.WithNamespace(genericapirequest.NewContext(), \"test\") destroyFunc, registry := NewTestGenericStoreRegistry(t) defer destroyFunc() defaultDeleteStrategy := testRESTStrategy{scheme, names.SimpleNameGenerator, true, false, true} registry.DeleteStrategy = testGracefulStrategy{defaultDeleteStrategy} // test failure condition _, _, err := registry.Delete(testContext, podA.Name, rest.ValidateAllObjectFunc, nil) if !errors.IsNotFound(err) { t.Errorf(\"Unexpected error: %v\", err) } // create pod _, err = registry.Create(testContext, podA, rest.ValidateAllObjectFunc, &metav1.CreateOptions{}) if err != nil { t.Errorf(\"Unexpected error: %v\", err) } // try to get a item which should be deleted obj, err := registry.Get(testContext, podA.Name, &metav1.GetOptions{}) if errors.IsNotFound(err) { t.Errorf(\"Unexpected error: %v\", err) } accessor, err := meta.Accessor(obj) if err != nil { t.Errorf(\"Unexpected error: %v\", err) } resourceVersion := accessor.GetResourceVersion() options := metav1.NewDeleteOptions(0) options.Preconditions = &metav1.Preconditions{ResourceVersion: &resourceVersion} // delete object _, wasDeleted, err := registry.Delete(testContext, podA.Name, rest.ValidateAllObjectFunc, options) if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if !wasDeleted { t.Errorf(\"unexpected, pod %s should have been deleted immediately\", podA.Name) } // try to get a item which should be deleted _, err = registry.Get(testContext, podA.Name, &metav1.GetOptions{}) if !errors.IsNotFound(err) { t.Errorf(\"Unexpected error: %v\", err) } } // TestGracefulStoreCanDeleteIfExistingGracePeriodZero tests recovery from // race condition where the graceful delete is unable to complete // in prior operation, but the pod remains with deletion timestamp"} {"_id":"doc-en-kubernetes-e2cd138825bc388165884e47215ed7a859dc27c6b4adc22b4e844713e5a3ad3d","title":"","text":"if err != nil { return nil, fmt.Errorf(\"failed to get region from zones: %v\", err) } volID = fmt.Sprintf(volIDZonalFmt, UnspecifiedValue, region, pv.Spec.GCEPersistentDisk.PDName) volID = fmt.Sprintf(volIDRegionalFmt, UnspecifiedValue, region, pv.Spec.GCEPersistentDisk.PDName) } else { // Unspecified volID = fmt.Sprintf(volIDZonalFmt, UnspecifiedValue, UnspecifiedValue, pv.Spec.GCEPersistentDisk.PDName)"} {"_id":"doc-en-kubernetes-2ab57ffb85e107e93e5df03c1d2a5c09ced47613845be0873e5c9e2515e54dc5","title":"","text":"v1 \"k8s.io/api/core/v1\" storage \"k8s.io/api/storage/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" ) func NewStorageClass(params map[string]string, allowedTopologies []v1.TopologySelectorTerm) *storage.StorageClass {"} {"_id":"doc-en-kubernetes-4cd3f3ba3c2529beba0517c0d1ad6454583b0b405d715d1f4ca406fd5ad7fca5","title":"","text":"t.Errorf(\"got am %v, expected access mode of ReadOnlyMany\", ams[0]) } } func TestTranslateInTreePVToCSIVolIDFmt(t *testing.T) { g := NewGCEPersistentDiskCSITranslator() pdName := \"pd-name\" tests := []struct { desc string topologyLabelKey string topologyLabelValue string wantVolId string }{ { desc: \"beta topology key zonal\", topologyLabelKey: v1.LabelFailureDomainBetaZone, topologyLabelValue: \"us-east1-a\", wantVolId: \"projects/UNSPECIFIED/zones/us-east1-a/disks/pd-name\", }, { desc: \"v1 topology key zonal\", topologyLabelKey: v1.LabelTopologyZone, topologyLabelValue: \"us-east1-a\", wantVolId: \"projects/UNSPECIFIED/zones/us-east1-a/disks/pd-name\", }, { desc: \"beta topology key regional\", topologyLabelKey: v1.LabelFailureDomainBetaZone, topologyLabelValue: \"us-central1-a__us-central1-c\", wantVolId: \"projects/UNSPECIFIED/regions/us-central1/disks/pd-name\", }, { desc: \"v1 topology key regional\", topologyLabelKey: v1.LabelTopologyZone, topologyLabelValue: \"us-central1-a__us-central1-c\", wantVolId: \"projects/UNSPECIFIED/regions/us-central1/disks/pd-name\", }, } for _, tc := range tests { t.Run(tc.desc, func(t *testing.T) { translatedPV, err := g.TranslateInTreePVToCSI(&v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{tc.topologyLabelKey: tc.topologyLabelValue}, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: pdName, }, }, }, }) if err != nil { t.Errorf(\"got error translating in-tree PV to CSI: %v\", err) } if got := translatedPV.Spec.PersistentVolumeSource.CSI.VolumeHandle; got != tc.wantVolId { t.Errorf(\"got translated volume handle: %q, want %q\", got, tc.wantVolId) } }) } } "} {"_id":"doc-en-kubernetes-b835d85197f42de87e33d95cda47a34337843e8e700f478f2832c2cef52eb36b","title":"","text":"\"//staging/src/k8s.io/client-go/informers/core/v1:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes:go_default_library\", \"//staging/src/k8s.io/client-go/rest:go_default_library\", \"//staging/src/k8s.io/component-base/metrics/legacyregistry:go_default_library\", \"//test/integration/util:go_default_library\", \"//vendor/github.com/prometheus/client_model/go:go_default_library\", \"//vendor/k8s.io/klog:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-c058f494fdfd5cb9c2b1a099299fbbe9956aae1a1c67015a3a0c37e89947f157","title":"","text":"configFile = \"config/performance-config.yaml\" ) var ( defaultMetrics = []string{ \"scheduler_scheduling_algorithm_predicate_evaluation_seconds\", \"scheduler_scheduling_algorithm_priority_evaluation_seconds\", \"scheduler_binding_duration_seconds\", \"scheduler_e2e_scheduling_duration_seconds\", } ) // testCase configures a test case to run the scheduler performance test. Users should be able to // provide this via a YAML file. //"} {"_id":"doc-en-kubernetes-179efa6a3f21ecd798f3d95166fdf598bfcfcb387410c4596d458d962cc8cf9e","title":"","text":"} func BenchmarkPerfScheduling(b *testing.B) { dataItems := DataItems{Version: \"v1\"} tests := getSimpleTestCases(configFile) for _, test := range tests {"} {"_id":"doc-en-kubernetes-264965a8e88dae5531d45ce8816d60b88addcf224e24371f76b017e29a302203","title":"","text":"for feature, flag := range test.FeatureGates { defer featuregatetesting.SetFeatureGateDuringTest(b, utilfeature.DefaultFeatureGate, feature, flag)() } perfScheduling(test, b) dataItems.DataItems = append(dataItems.DataItems, perfScheduling(test, b)...) }) } if err := dataItems2JSONFile(dataItems, b.Name()); err != nil { klog.Fatalf(\"%v: unable to write measured data: %v\", b.Name(), err) } } func perfScheduling(test testCase, b *testing.B) { func perfScheduling(test testCase, b *testing.B) []DataItem { var nodeStrategy testutils.PrepareNodeStrategy = &testutils.TrivialNodePrepareStrategy{} if test.Nodes.NodeAllocatableStrategy != nil { nodeStrategy = test.Nodes.NodeAllocatableStrategy"} {"_id":"doc-en-kubernetes-9d00e1778c3974887fd1c78c469f4630508001ef292839e05001fca4c906584a","title":"","text":"// start benchmark b.ResetTimer() // Start measuring throughput stopCh := make(chan struct{}) throughputCollector := newThroughputCollector(podInformer) go throughputCollector.run(stopCh) // Scheduling the main workload config = testutils.NewTestPodCreatorConfig() config.AddStrategy(testNamespace, test.PodsToSchedule.Num, testPodStrategy) podCreator = testutils.NewTestPodCreator(clientset, config) podCreator.CreatePods() <-completedCh close(stopCh) // Note: without this line we're taking the overhead of defer() into account. b.StopTimer() setNameLabel := func(dataItem *DataItem) DataItem { if dataItem.Labels == nil { dataItem.Labels = map[string]string{} } dataItem.Labels[\"Name\"] = b.Name() return *dataItem } dataItems := []DataItem{ setNameLabel(throughputCollector.collect()), } for _, metric := range defaultMetrics { dataItem := newPrometheusCollector(metric).collect() if dataItem == nil { continue } dataItems = append(dataItems, setNameLabel(dataItem)) } return dataItems } func getPodStrategy(pc podCase) testutils.TestPodCreateStrategy {"} {"_id":"doc-en-kubernetes-c783375e209e4a5d84a7626cf131e2c001ab441ff9a1b9a42f627b7ccd580b38","title":"","text":"package benchmark import ( \"encoding/json\" \"flag\" \"fmt\" \"io/ioutil\" \"math\" \"path\" \"sort\" \"time\" dto \"github.com/prometheus/client_model/go\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime/schema\" coreinformers \"k8s.io/client-go/informers/core/v1\" clientset \"k8s.io/client-go/kubernetes\" restclient \"k8s.io/client-go/rest\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/klog\" \"k8s.io/kubernetes/test/integration/util\" ) const ( dateFormat = \"2006-01-02T15:04:05Z\" throughputSampleFrequency = time.Second ) var dataItemsDir = flag.String(\"data-items-dir\", \"\", \"destination directory for storing generated data items for perf dashboard\") // mustSetupScheduler starts the following components: // - k8s api server (a.k.a. master) // - scheduler"} {"_id":"doc-en-kubernetes-282e061fb28663105e7369c1b224fdb9d44054a4593c877a5d95708c5a780d79","title":"","text":"} return scheduled, nil } // DataItem is the data point. type DataItem struct { // Data is a map from bucket to real data point (e.g. \"Perc90\" -> 23.5). Notice // that all data items with the same label combination should have the same buckets. Data map[string]float64 `json:\"data\"` // Unit is the data unit. Notice that all data items with the same label combination // should have the same unit. Unit string `json:\"unit\"` // Labels is the labels of the data item. Labels map[string]string `json:\"labels,omitempty\"` } // DataItems is the data point set. It is the struct that perf dashboard expects. type DataItems struct { Version string `json:\"version\"` DataItems []DataItem `json:\"dataItems\"` } func dataItems2JSONFile(dataItems DataItems, namePrefix string) error { b, err := json.Marshal(dataItems) if err != nil { return err } destFile := fmt.Sprintf(\"%v_%v.json\", namePrefix, time.Now().Format(dateFormat)) if *dataItemsDir != \"\" { destFile = path.Join(*dataItemsDir, destFile) } return ioutil.WriteFile(destFile, b, 0644) } // prometheusCollector collects metrics from legacyregistry.DefaultGatherer.Gather() endpoint. // Currently only Histrogram metrics are supported. type prometheusCollector struct { metric string cache *dto.MetricFamily } func newPrometheusCollector(metric string) *prometheusCollector { return &prometheusCollector{ metric: metric, } } func (pc *prometheusCollector) collect() *DataItem { var metricFamily *dto.MetricFamily m, err := legacyregistry.DefaultGatherer.Gather() if err != nil { klog.Error(err) return nil } for _, mFamily := range m { if mFamily.Name != nil && *mFamily.Name == pc.metric { metricFamily = mFamily break } } if metricFamily == nil { klog.Infof(\"Metric %q not found\", pc.metric) return nil } if metricFamily.GetMetric() == nil { klog.Infof(\"Metric %q is empty\", pc.metric) return nil } if len(metricFamily.GetMetric()) == 0 { klog.Infof(\"Metric %q is empty\", pc.metric) return nil } // Histograms are stored under the first index (based on observation). // Given there's only one histogram registered per each metric name, accessaing // the first index is sufficient. dataItem := pc.promHist2Summary(metricFamily.GetMetric()[0].GetHistogram()) if dataItem.Data == nil { return nil } // clear the metrics so that next test always starts with empty prometheus // metrics (since the metrics are shared among all tests run inside the same binary) clearPromHistogram(metricFamily.GetMetric()[0].GetHistogram()) return dataItem } // Bucket of a histogram type bucket struct { upperBound float64 count float64 } func bucketQuantile(q float64, buckets []bucket) float64 { if q < 0 { return math.Inf(-1) } if q > 1 { return math.Inf(+1) } if len(buckets) < 2 { return math.NaN() } rank := q * buckets[len(buckets)-1].count b := sort.Search(len(buckets)-1, func(i int) bool { return buckets[i].count >= rank }) if b == 0 { return buckets[0].upperBound * (rank / buckets[0].count) } // linear approximation of b-th bucket brank := rank - buckets[b-1].count bSize := buckets[b].upperBound - buckets[b-1].upperBound bCount := buckets[b].count - buckets[b-1].count return buckets[b-1].upperBound + bSize*(brank/bCount) } func (pc *prometheusCollector) promHist2Summary(hist *dto.Histogram) *DataItem { buckets := []bucket{} if hist.SampleCount == nil || *hist.SampleCount == 0 { return &DataItem{} } if hist.SampleSum == nil || *hist.SampleSum == 0 { return &DataItem{} } for _, bckt := range hist.Bucket { if bckt == nil { return &DataItem{} } if bckt.UpperBound == nil || *bckt.UpperBound < 0 { return &DataItem{} } buckets = append(buckets, bucket{ count: float64(*bckt.CumulativeCount), upperBound: *bckt.UpperBound, }) } // bucketQuantile expects the upper bound of the last bucket to be +inf buckets[len(buckets)-1].upperBound = math.Inf(+1) q50 := bucketQuantile(0.50, buckets) q90 := bucketQuantile(0.90, buckets) q99 := bucketQuantile(0.95, buckets) msFactor := float64(time.Second) / float64(time.Millisecond) return &DataItem{ Labels: map[string]string{ \"Metric\": pc.metric, }, Data: map[string]float64{ \"Perc50\": q50 * msFactor, \"Perc90\": q90 * msFactor, \"Perc99\": q99 * msFactor, \"Average\": (*hist.SampleSum / float64(*hist.SampleCount)) * msFactor, }, Unit: \"ms\", } } func clearPromHistogram(hist *dto.Histogram) { if hist.SampleCount != nil { *hist.SampleCount = 0 } if hist.SampleSum != nil { *hist.SampleSum = 0 } for _, b := range hist.Bucket { if b.CumulativeCount != nil { *b.CumulativeCount = 0 } if b.UpperBound != nil { *b.UpperBound = 0 } } } type throughputCollector struct { podInformer coreinformers.PodInformer schedulingThroughputs []float64 } func newThroughputCollector(podInformer coreinformers.PodInformer) *throughputCollector { return &throughputCollector{ podInformer: podInformer, } } func (tc *throughputCollector) run(stopCh chan struct{}) { podsScheduled, err := getScheduledPods(tc.podInformer) if err != nil { klog.Fatalf(\"%v\", err) } lastScheduledCount := len(podsScheduled) for { select { case <-stopCh: return case <-time.After(throughputSampleFrequency): podsScheduled, err := getScheduledPods(tc.podInformer) if err != nil { klog.Fatalf(\"%v\", err) } scheduled := len(podsScheduled) samplingRatioSeconds := float64(throughputSampleFrequency) / float64(time.Second) throughput := float64(scheduled-lastScheduledCount) / samplingRatioSeconds tc.schedulingThroughputs = append(tc.schedulingThroughputs, throughput) lastScheduledCount = scheduled klog.Infof(\"%d pods scheduled\", lastScheduledCount) } } } func (tc *throughputCollector) collect() *DataItem { throughputSummary := &DataItem{} if length := len(tc.schedulingThroughputs); length > 0 { sort.Float64s(tc.schedulingThroughputs) sum := 0.0 for i := range tc.schedulingThroughputs { sum += tc.schedulingThroughputs[i] } throughputSummary.Labels = map[string]string{ \"Metric\": \"SchedulingThroughput\", } throughputSummary.Data = map[string]float64{ \"Average\": sum / float64(length), \"Perc50\": tc.schedulingThroughputs[int(math.Ceil(float64(length*50)/100))-1], \"Perc90\": tc.schedulingThroughputs[int(math.Ceil(float64(length*90)/100))-1], \"Perc99\": tc.schedulingThroughputs[int(math.Ceil(float64(length*99)/100))-1], } throughputSummary.Unit = \"pods/s\" } return throughputSummary } "} {"_id":"doc-en-kubernetes-2de7cd88c4774bac5af5c8449768381a94f98a6eb44de15d390ec6c6397b459c","title":"","text":"/* Release : v1.15 Testname: Pods, delete grace period Description: Create a pod, make sure it is running. Using the http client send a 'delete' with gracePeriodSeconds=30. Pod SHOULD get deleted within 30 seconds. Description: Create a pod, make sure it is running. Using the http client send a 'delete' with gracePeriodSeconds=30. Pod SHOULD get terminated within gracePeriodSeconds and removed from API server within a window. */ ginkgo.It(\"should be submitted and removed [Flaky]\", func() { ginkgo.It(\"should be submitted and removed\", func() { ginkgo.By(\"creating the pod\") name := \"pod-submit-remove-\" + string(uuid.NewUUID()) value := strconv.Itoa(time.Now().Nanosecond())"} {"_id":"doc-en-kubernetes-c1c1f1f0f42894873413a66f69c8f7682421fae5cb831d81fa86827cc45e4e31","title":"","text":"ginkgo.By(\"verifying the kubelet observed the termination notice\") // allow up to 3x grace period (which allows process termination) // for the kubelet to remove from api. need to follow-up on if this // latency between termination and reportal can be isolated further. start := time.Now() err = wait.Poll(time.Second*5, time.Second*30, func() (bool, error) { err = wait.Poll(time.Second*5, time.Second*30*3, func() (bool, error) { podList, err := e2ekubelet.GetKubeletPods(f.ClientSet, pod.Spec.NodeName) if err != nil { framework.Logf(\"Unable to retrieve kubelet pods for node %v: %v\", pod.Spec.NodeName, err)"} {"_id":"doc-en-kubernetes-39d4ac5cf7503e6c03ab41b7521cbe2c02fd6fc37cff0b6451766717059a7c8b","title":"","text":" # See the OWNERS docs at https://go.k8s.io/owners approvers: - lavalamp - smarterclayton - deads2k - sttts - liggitt - caesarxuchao reviewers: - thockin - lavalamp - smarterclayton - wojtek-t - deads2k - derekwaynecarr - caesarxuchao - cheftako - mikedanese - liggitt - gmarek - sttts - ncdc - logicalhan - tallclair labels: - sig/api-machinery No newline at end of file"} {"_id":"doc-en-kubernetes-287387c9dd85c57bd6325e492c15b617476c333d2707b90598fd6d2715e0e3e0","title":"","text":"package apimachinery import ( \"encoding/json\" \"fmt\" \"strings\" \"sync\""} {"_id":"doc-en-kubernetes-e29133af86a1c9267681fa5cf17f5773c93fae1b35253a09a06399dacf510341","title":"","text":"apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/kubernetes/test/e2e/framework\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"github.com/onsi/ginkgo\" \"k8s.io/apimachinery/pkg/types\" ) func extinguish(f *framework.Framework, totalNS int, maxAllowedAfterDel int, maxSeconds int) {"} {"_id":"doc-en-kubernetes-f4208f2d0d0f428317e9af55e70bb3b85775210c45c328a4e20644d53b48fee1","title":"","text":"ginkgo.It(\"should always delete fast (ALL of 100 namespaces in 150 seconds) [Feature:ComprehensiveNamespaceDraining]\", func() { extinguish(f, 100, 0, 150) }) ginkgo.It(\"should patch a Namespace\", func() { ginkgo.By(\"creating a Namespace\") namespaceName := \"nspatchtest-\" + string(uuid.NewUUID()) ns, err := f.CreateNamespace(namespaceName, nil) framework.ExpectNoError(err, \"failed creating Namespace\") namespaceName = ns.ObjectMeta.Name ginkgo.By(\"patching the Namespace\") nspatch, err := json.Marshal(map[string]interface{}{ \"metadata\": map[string]interface{}{ \"labels\": map[string]string{\"testLabel\": \"testValue\"}, }, }) framework.ExpectNoError(err, \"failed to marshal JSON patch data\") _, err = f.ClientSet.CoreV1().Namespaces().Patch(namespaceName, types.StrategicMergePatchType, []byte(nspatch)) framework.ExpectNoError(err, \"failed to patch Namespace\") ginkgo.By(\"get the Namespace and ensuring it has the label\") namespace, err := f.ClientSet.CoreV1().Namespaces().Get(namespaceName, metav1.GetOptions{}) framework.ExpectNoError(err, \"failed to get Namespace\") framework.ExpectEqual(namespace.ObjectMeta.Labels[\"testLabel\"], \"testValue\", \"namespace not patched\") }) })"} {"_id":"doc-en-kubernetes-ba89d0d7da56cc91404ec9dd63f1e1939b801668ec55fe714d650cd0ec49508c","title":"","text":"## Known Issues - volumeDevices mapping ignored when container is privileged - The `Should recreate evicted statefulset` conformance [test]( https://github.com/kubernetes/kubernetes/blob/master/test/e2e/apps/statefulset.go) fails because `Pod ss-0 expected to be re-created at least once`. This was caused by the `Predicate PodFitsHostPorts failed` scheduling error. The root cause was a host port conflict for port `21017`. This port was in-use as an ephemeral port by another application running on the node. This will be looked at for the 1.18 release. - client-go discovery clients constructed using `NewDiscoveryClientForConfig` or `NewDiscoveryClientForConfigOrDie` default to rate limits that cause normal discovery request patterns to take several seconds. This is fixed in https://issue.k8s.io/86168 and will be resolved in v1.17.1. As a workaround, the `Burst` value can be adjusted higher in the rest.Config passed into `NewDiscoveryClientForConfig` or `NewDiscoveryClientForConfigOrDie`. ## Urgent Upgrade Notes ### (No, really, you MUST read this before you upgrade)"} {"_id":"doc-en-kubernetes-bd92ae1d3e9435be325035e1671ea208e58b4b779e203f27b08a8c6714aa6828","title":"","text":"if config.Timeout == 0 { config.Timeout = defaultTimeout } if config.Burst == 0 && config.QPS < 100 { // discovery is expected to be bursty, increase the default burst // to accommodate looking up resource info for many API groups. // matches burst set by ConfigFlags#ToDiscoveryClient(). // see https://issue.k8s.io/86149 config.Burst = 100 } codec := runtime.NoopEncoder{Decoder: scheme.Codecs.UniversalDecoder()} config.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec}) if len(config.UserAgent) == 0 {"} {"_id":"doc-en-kubernetes-85041de1b2b532020759458eb6ed2e79d4fb2664e37206c531133e08342dd174","title":"","text":"\"net/http/httptest\" \"reflect\" \"testing\" \"time\" \"github.com/gogo/protobuf/proto\" \"github.com/googleapis/gnostic/OpenAPIv2\""} {"_id":"doc-en-kubernetes-28ce9017749552ba79867002fc4b6db0c6d4095de1d5e6435092476ddf4fc24a","title":"","text":"{Name: \"jobs\", Namespaced: true, Kind: \"Job\"}, }, } extensionsbeta3 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta3\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta4 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta4\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta5 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta5\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta6 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta6\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta7 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta7\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta8 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta8\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta9 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta9\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} extensionsbeta10 := metav1.APIResourceList{GroupVersion: \"extensions/v1beta10\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta1 := metav1.APIResourceList{GroupVersion: \"apps/v1beta1\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta2 := metav1.APIResourceList{GroupVersion: \"apps/v1beta2\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta3 := metav1.APIResourceList{GroupVersion: \"apps/v1beta3\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta4 := metav1.APIResourceList{GroupVersion: \"apps/v1beta4\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta5 := metav1.APIResourceList{GroupVersion: \"apps/v1beta5\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta6 := metav1.APIResourceList{GroupVersion: \"apps/v1beta6\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta7 := metav1.APIResourceList{GroupVersion: \"apps/v1beta7\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta8 := metav1.APIResourceList{GroupVersion: \"apps/v1beta8\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta9 := metav1.APIResourceList{GroupVersion: \"apps/v1beta9\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} appsbeta10 := metav1.APIResourceList{GroupVersion: \"apps/v1beta10\", APIResources: []metav1.APIResource{{Name: \"deployments\", Namespaced: true, Kind: \"Deployment\"}}} tests := []struct { resourcesList *metav1.APIResourceList path string"} {"_id":"doc-en-kubernetes-e4c8ed109bb2cdd18256d5b4a300cd3251f85ec8845477f12de0fe7b5f6f1f54","title":"","text":"list = &beta case \"/apis/extensions/v1beta2\": list = &beta2 case \"/apis/extensions/v1beta3\": list = &extensionsbeta3 case \"/apis/extensions/v1beta4\": list = &extensionsbeta4 case \"/apis/extensions/v1beta5\": list = &extensionsbeta5 case \"/apis/extensions/v1beta6\": list = &extensionsbeta6 case \"/apis/extensions/v1beta7\": list = &extensionsbeta7 case \"/apis/extensions/v1beta8\": list = &extensionsbeta8 case \"/apis/extensions/v1beta9\": list = &extensionsbeta9 case \"/apis/extensions/v1beta10\": list = &extensionsbeta10 case \"/apis/apps/v1beta1\": list = &appsbeta1 case \"/apis/apps/v1beta2\": list = &appsbeta2 case \"/apis/apps/v1beta3\": list = &appsbeta3 case \"/apis/apps/v1beta4\": list = &appsbeta4 case \"/apis/apps/v1beta5\": list = &appsbeta5 case \"/apis/apps/v1beta6\": list = &appsbeta6 case \"/apis/apps/v1beta7\": list = &appsbeta7 case \"/apis/apps/v1beta8\": list = &appsbeta8 case \"/apis/apps/v1beta9\": list = &appsbeta9 case \"/apis/apps/v1beta10\": list = &appsbeta10 case \"/api\": list = &metav1.APIVersions{ Versions: []string{"} {"_id":"doc-en-kubernetes-1633368f0cd023c6711955df930af823c24d6647945f14868a86d15757b4229f","title":"","text":"list = &metav1.APIGroupList{ Groups: []metav1.APIGroup{ { Name: \"apps\", Versions: []metav1.GroupVersionForDiscovery{ {GroupVersion: \"apps/v1beta1\", Version: \"v1beta1\"}, {GroupVersion: \"apps/v1beta2\", Version: \"v1beta2\"}, {GroupVersion: \"apps/v1beta3\", Version: \"v1beta3\"}, {GroupVersion: \"apps/v1beta4\", Version: \"v1beta4\"}, {GroupVersion: \"apps/v1beta5\", Version: \"v1beta5\"}, {GroupVersion: \"apps/v1beta6\", Version: \"v1beta6\"}, {GroupVersion: \"apps/v1beta7\", Version: \"v1beta7\"}, {GroupVersion: \"apps/v1beta8\", Version: \"v1beta8\"}, {GroupVersion: \"apps/v1beta9\", Version: \"v1beta9\"}, {GroupVersion: \"apps/v1beta10\", Version: \"v1beta10\"}, }, }, { Name: \"extensions\", Versions: []metav1.GroupVersionForDiscovery{ {GroupVersion: \"extensions/v1beta1\", Version: \"v1beta1\"}, {GroupVersion: \"extensions/v1beta2\", Version: \"v1beta2\"}, {GroupVersion: \"extensions/v1beta3\", Version: \"v1beta3\"}, {GroupVersion: \"extensions/v1beta4\", Version: \"v1beta4\"}, {GroupVersion: \"extensions/v1beta5\", Version: \"v1beta5\"}, {GroupVersion: \"extensions/v1beta6\", Version: \"v1beta6\"}, {GroupVersion: \"extensions/v1beta7\", Version: \"v1beta7\"}, {GroupVersion: \"extensions/v1beta8\", Version: \"v1beta8\"}, {GroupVersion: \"extensions/v1beta9\", Version: \"v1beta9\"}, {GroupVersion: \"extensions/v1beta10\", Version: \"v1beta10\"}, }, }, },"} {"_id":"doc-en-kubernetes-db744c5f0e7929d46c2ca18bc0f284d77249526662137d41d0389a44691fab1a","title":"","text":"w.Write(output) })) defer server.Close() client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) for _, test := range tests { client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) got, err := client.ServerResourcesForGroupVersion(test.request) if test.expectErr { if err == nil {"} {"_id":"doc-en-kubernetes-b1f9f22abca185fccc280c070d9e1d7214580edca55d26640669939656e42c65","title":"","text":"} } client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) start := time.Now() serverResources, err := client.ServerResources() if err != nil { t.Errorf(\"unexpected error: %v\", err) } end := time.Now() if d := end.Sub(start); d > time.Second { t.Errorf(\"took too long to perform discovery: %s\", d) } serverGroupVersions := groupVersions(serverResources) expectedGroupVersions := []string{\"v1\", \"extensions/v1beta1\", \"extensions/v1beta2\"} expectedGroupVersions := []string{ \"v1\", \"apps/v1beta1\", \"apps/v1beta2\", \"apps/v1beta3\", \"apps/v1beta4\", \"apps/v1beta5\", \"apps/v1beta6\", \"apps/v1beta7\", \"apps/v1beta8\", \"apps/v1beta9\", \"apps/v1beta10\", \"extensions/v1beta1\", \"extensions/v1beta2\", \"extensions/v1beta3\", \"extensions/v1beta4\", \"extensions/v1beta5\", \"extensions/v1beta6\", \"extensions/v1beta7\", \"extensions/v1beta8\", \"extensions/v1beta9\", \"extensions/v1beta10\", } if !reflect.DeepEqual(expectedGroupVersions, serverGroupVersions) { t.Errorf(\"unexpected group versions: %v\", diff.ObjectReflectDiff(expectedGroupVersions, serverGroupVersions)) }"} {"_id":"doc-en-kubernetes-d0f8839d04ceccdbc598f5607e1cbd6397ad3558e6033179c0921b6875eed9e9","title":"","text":"CMD_TARGETS=\"${CMD_TARGETS} ${KUBE_CONFORMANCE_IMAGE_TARGETS[*]}\" fi # TODO(dims): Remove this when we get rid of hyperkube image CMD_TARGETS=\"${CMD_TARGETS} cmd/kubelet cmd/kubectl\" kube::build::verify_prereqs kube::build::build_image kube::build::run_build_command make all WHAT=\"${CMD_TARGETS}\" KUBE_BUILD_PLATFORMS=\"${KUBE_SERVER_PLATFORMS[*]}\""} {"_id":"doc-en-kubernetes-105b5b162bb79939774bcf2aed52c08ba6388dd6c90ca9911f013e536f52bd6f","title":"","text":"batchinternal \"k8s.io/kubernetes/pkg/apis/batch\" \"k8s.io/kubernetes/test/e2e/framework\" jobutil \"k8s.io/kubernetes/test/e2e/framework/job\" e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" \"github.com/onsi/ginkgo\""} {"_id":"doc-en-kubernetes-6c8dd92f4cd748d88c695ffac5565f8bfc94cf989c2b7c482ae1635b1de1e866","title":"","text":"framework.ConformanceIt(\"should run a job to completion when tasks sometimes fail and are locally restarted\", func() { ginkgo.By(\"Creating a job\") // One failure, then a success, local restarts. // We can't use the random failure approach used by the // non-local test below, because kubelet will throttle // frequently failing containers in a given pod, ramping // up to 5 minutes between restarts, making test timeouts // due to successive failures too likely with a reasonable // test timeout. // We can't use the random failure approach, because kubelet will // throttle frequently failing containers in a given pod, ramping // up to 5 minutes between restarts, making test timeout due to // successive failures too likely with a reasonable test timeout. job := jobutil.NewTestJob(\"failOnce\", \"fail-once-local\", v1.RestartPolicyOnFailure, parallelism, completions, nil, backoffLimit) job, err := jobutil.CreateJob(f.ClientSet, f.Namespace.Name, job) framework.ExpectNoError(err, \"failed to create job in namespace: %s\", f.Namespace.Name)"} {"_id":"doc-en-kubernetes-74b5db30bdfd86861315e7e639d85476cb90047e91ba9ec7a35bab693fa4db82","title":"","text":"// Pods sometimes fail, but eventually succeed, after pod restarts ginkgo.It(\"should run a job to completion when tasks sometimes fail and are not locally restarted\", func() { // One failure, then a success, no local restarts. // We can't use the random failure approach, because JobController // will throttle frequently failing Pods of a given Job, ramping // up to 6 minutes between restarts, making test timeout due to // successive failures. // Instead, we force the Job's Pods to be scheduled to a single Node // and use a hostPath volume to persist data across new Pods. ginkgo.By(\"Looking for a node to schedule job pod\") node, err := e2enode.GetRandomReadySchedulableNode(f.ClientSet) framework.ExpectNoError(err) ginkgo.By(\"Creating a job\") // 50% chance of container success, local restarts. // Can't use the failOnce approach because that relies // on an emptyDir, which is not preserved across new pods. // Worst case analysis: 15 failures, each taking 1 minute to // run due to some slowness, 1 in 2^15 chance of happening, // causing test flake. Should be very rare. // With the introduction of backoff limit and high failure rate this // is hitting its timeout, the 3 is a reasonable that should make this // test less flaky, for now. job := jobutil.NewTestJob(\"randomlySucceedOrFail\", \"rand-non-local\", v1.RestartPolicyNever, parallelism, 3, nil, 999) job, err := jobutil.CreateJob(f.ClientSet, f.Namespace.Name, job) job := jobutil.NewTestJobOnNode(\"failOnce\", \"fail-once-non-local\", v1.RestartPolicyNever, parallelism, completions, nil, backoffLimit, node.Name) job, err = jobutil.CreateJob(f.ClientSet, f.Namespace.Name, job) framework.ExpectNoError(err, \"failed to create job in namespace: %s\", f.Namespace.Name) ginkgo.By(\"Ensuring job reaches completions\")"} {"_id":"doc-en-kubernetes-2f84a65ce078660fcc91f68091e1a9e9564d7e64a5001b71091483725a41a8f6","title":"","text":"\"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/labels:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/rand:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library\", \"//staging/src/k8s.io/client-go/kubernetes:go_default_library\", \"//test/e2e/framework:go_default_library\","} {"_id":"doc-en-kubernetes-97756d6b3941588bbb039af8c0846389d7b6654740b9ac7e61629c439fbb559f","title":"","text":"batchv1 \"k8s.io/api/batch/v1\" \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/rand\" \"k8s.io/kubernetes/test/e2e/framework\" )"} {"_id":"doc-en-kubernetes-ef24ffe71e656d3252a78b6d6662ca4adbe83bdd7a40be2acc837787fb14a48d","title":"","text":"// policy of the containers in which the Pod is running. Parallelism is the Job's parallelism, and completions is the // Job's required number of completions. func NewTestJob(behavior, name string, rPol v1.RestartPolicy, parallelism, completions int32, activeDeadlineSeconds *int64, backoffLimit int32) *batchv1.Job { anyNode := \"\" return NewTestJobOnNode(behavior, name, rPol, parallelism, completions, activeDeadlineSeconds, backoffLimit, anyNode) } // NewTestJobOnNode is similar to NewTestJob but supports specifying a Node on which the Job's Pods will run. // Empty nodeName means no node selection constraints. func NewTestJobOnNode(behavior, name string, rPol v1.RestartPolicy, parallelism, completions int32, activeDeadlineSeconds *int64, backoffLimit int32, nodeName string) *batchv1.Job { manualSelector := false job := &batchv1.Job{ ObjectMeta: metav1.ObjectMeta{"} {"_id":"doc-en-kubernetes-383ca04fbb0ebb8d78a5a07dad3719c615c6ecebc4b3a3249830606c22a85b6e","title":"","text":"SecurityContext: &v1.SecurityContext{}, }, }, NodeName: nodeName, }, }, },"} {"_id":"doc-en-kubernetes-7712ffb50e980231b9897e27196e101f58665f9395a2d2bbe0ddc36f52b22ba9","title":"","text":"job.Spec.Template.Spec.Containers[0].Command = []string{\"/bin/sh\", \"-c\", \"exit $(( $RANDOM / 16384 ))\"} case \"failOnce\": // Fail the first the container of the pod is run, and // succeed the second time. Checks for file on emptydir. // succeed the second time. Checks for file on a data volume. // If present, succeed. If not, create but fail. // Note that this cannot be used with RestartNever because // it always fails the first time for a pod. // If RestartPolicy is Never, the nodeName should be set to // ensure all job pods run on a single node and the volume // will be mounted from a hostPath instead. if len(nodeName) > 0 { randomDir := \"/tmp/job-e2e/\" + rand.String(10) hostPathType := v1.HostPathDirectoryOrCreate job.Spec.Template.Spec.Volumes[0].VolumeSource = v1.VolumeSource{HostPath: &v1.HostPathVolumeSource{Path: randomDir, Type: &hostPathType}} // Tests involving r/w operations on hostPath volume needs to run in // privileged mode for SELinux enabled distro, while Windows platform // neither supports nor needs privileged mode. privileged := !framework.NodeOSDistroIs(\"windows\") job.Spec.Template.Spec.Containers[0].SecurityContext.Privileged = &privileged } job.Spec.Template.Spec.Containers[0].Command = []string{\"/bin/sh\", \"-c\", \"if [[ -r /data/foo ]] ; then exit 0 ; else touch /data/foo ; exit 1 ; fi\"} } return job"} {"_id":"doc-en-kubernetes-b1a9a608f9be5a22002156d6138304bbba65d0019db8dba485824a2839c7e08c","title":"","text":"package common import ( \"encoding/json\" \"fmt\" \"k8s.io/api/core/v1\""} {"_id":"doc-en-kubernetes-58a837960eec8229f41bbad775f55deccc6f08a5565b0a7dc1a6ec79717c5f61","title":"","text":"\"k8s.io/kubernetes/test/e2e/framework\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"encoding/base64\" \"github.com/onsi/ginkgo\" \"k8s.io/apimachinery/pkg/types\" ) var _ = ginkgo.Describe(\"[sig-api-machinery] Secrets\", func() {"} {"_id":"doc-en-kubernetes-7c6838db6c8e299b5964fc879e0f85ba0628be43383f4d815ea3755db82da735","title":"","text":"secret, err := createEmptyKeySecretForTest(f) framework.ExpectError(err, \"created secret %q with empty key in namespace %q\", secret.Name, f.Namespace.Name) }) ginkgo.It(\"should patch a secret\", func() { ginkgo.By(\"creating a secret\") secretTestName := \"test-secret-\" + string(uuid.NewUUID()) // create a secret in the test namespace _, err := f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Create(&v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: secretTestName, Labels: map[string]string{ \"testsecret-constant\": \"true\", }, }, Data: map[string][]byte{ \"key\": []byte(\"value\"), }, Type: \"Opaque\", }) framework.ExpectNoError(err, \"failed to create secret\") ginkgo.By(\"listing secrets in all namespaces to ensure that there are more than zero\") // list all secrets in all namespaces to ensure endpoint coverage secretsList, err := f.ClientSet.CoreV1().Secrets(\"\").List(metav1.ListOptions{ LabelSelector: \"testsecret-constant=true\", }) framework.ExpectNoError(err, \"failed to list secrets\") framework.ExpectNotEqual(len(secretsList.Items), 0, \"no secrets found\") foundCreatedSecret := false var secretCreatedName string for _, val := range secretsList.Items { if val.ObjectMeta.Name == secretTestName && val.ObjectMeta.Namespace == f.Namespace.Name { foundCreatedSecret = true secretCreatedName = val.ObjectMeta.Name break } } framework.ExpectEqual(foundCreatedSecret, true, \"unable to find secret by its value\") ginkgo.By(\"patching the secret\") // patch the secret in the test namespace secretPatchNewData := base64.StdEncoding.EncodeToString([]byte(\"value1\")) secretPatch, err := json.Marshal(map[string]interface{}{ \"metadata\": map[string]interface{}{ \"labels\": map[string]string{\"testsecret\": \"true\"}, }, \"data\": map[string][]byte{\"key\": []byte(secretPatchNewData)}, }) framework.ExpectNoError(err, \"failed to marshal JSON\") _, err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Patch(secretCreatedName, types.StrategicMergePatchType, []byte(secretPatch)) framework.ExpectNoError(err, \"failed to patch secret\") secret, err := f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Get(secretCreatedName, metav1.GetOptions{}) framework.ExpectNoError(err, \"failed to get secret\") secretDecodedstring, err := base64.StdEncoding.DecodeString(string(secret.Data[\"key\"])) framework.ExpectNoError(err, \"failed to decode secret from Base64\") framework.ExpectEqual(string(secretDecodedstring), \"value1\", \"found secret, but the data wasn't updated from the patch\") ginkgo.By(\"deleting the secret using a LabelSelector\") err = f.ClientSet.CoreV1().Secrets(f.Namespace.Name).DeleteCollection(&metav1.DeleteOptions{}, metav1.ListOptions{ LabelSelector: \"testsecret=true\", }) framework.ExpectNoError(err, \"failed to delete patched secret\") ginkgo.By(\"listing secrets in all namespaces, searching for label name and value in patch\") // list all secrets in all namespaces secretsList, err = f.ClientSet.CoreV1().Secrets(\"\").List(metav1.ListOptions{ LabelSelector: \"testsecret-constant=true\", }) framework.ExpectNoError(err, \"failed to list secrets\") foundCreatedSecret = false for _, val := range secretsList.Items { if val.ObjectMeta.Name == secretTestName && val.ObjectMeta.Namespace == f.Namespace.Name { foundCreatedSecret = true break } } framework.ExpectEqual(foundCreatedSecret, false, \"secret was not deleted successfully\") }) }) func newEnvFromSecret(namespace, name string) *v1.Secret {"} {"_id":"doc-en-kubernetes-70693d9c2434713692c1a1643a5724c95fad4548fe1d3cc042df49a196a7a846","title":"","text":"test/e2e/common/secrets.go: \"should be consumable from pods in env vars\" test/e2e/common/secrets.go: \"should be consumable via the environment\" test/e2e/common/secrets.go: \"should fail to create secret due to empty secret key\" test/e2e/common/secrets.go: \"should patch a secret\" test/e2e/common/secrets_volume.go: \"should be consumable from pods in volume\" test/e2e/common/secrets_volume.go: \"should be consumable from pods in volume with defaultMode set\" test/e2e/common/secrets_volume.go: \"should be consumable from pods in volume as non-root with defaultMode and fsGroup set\""} {"_id":"doc-en-kubernetes-860f8f7706ffc89d305c5105f03289864978082962fc712dbe4942dbde0314f9","title":"","text":"framework.ExpectError(err, \"created secret %q with empty key in namespace %q\", secret.Name, f.Namespace.Name) }) ginkgo.It(\"should patch a secret\", func() { /* Release : v1.18 Testname: Secret patching Description: A Secret is created. Listing all Secrets MUST return an empty list. Given the patching and fetching of the Secret, the fields MUST equal the new values. The Secret is deleted by it's static Label. Secrets are listed finally, the list MUST NOT include the originally created Secret. */ framework.ConformanceIt(\"should patch a secret\", func() { ginkgo.By(\"creating a secret\") secretTestName := \"test-secret-\" + string(uuid.NewUUID())"} {"_id":"doc-en-kubernetes-4b6e13aa013f1c1d77faead206623efaf7fdd85effeb833e03b0355dac0fe965","title":"","text":"// The failure information is given by the error. type FitPredicate func(pod *v1.Pod, meta Metadata, nodeInfo *schedulernodeinfo.NodeInfo) (bool, []PredicateFailureReason, error) func isVolumeConflict(volume v1.Volume, pod *v1.Pod) bool { // fast path if there is no conflict checking targets. if volume.GCEPersistentDisk == nil && volume.AWSElasticBlockStore == nil && volume.RBD == nil && volume.ISCSI == nil { return false } for _, existingVolume := range pod.Spec.Volumes { // Same GCE disk mounted by multiple pods conflicts unless all pods mount it read-only. if volume.GCEPersistentDisk != nil && existingVolume.GCEPersistentDisk != nil { disk, existingDisk := volume.GCEPersistentDisk, existingVolume.GCEPersistentDisk if disk.PDName == existingDisk.PDName && !(disk.ReadOnly && existingDisk.ReadOnly) { return true } } if volume.AWSElasticBlockStore != nil && existingVolume.AWSElasticBlockStore != nil { if volume.AWSElasticBlockStore.VolumeID == existingVolume.AWSElasticBlockStore.VolumeID { return true } } if volume.ISCSI != nil && existingVolume.ISCSI != nil { iqn := volume.ISCSI.IQN eiqn := existingVolume.ISCSI.IQN // two ISCSI volumes are same, if they share the same iqn. As iscsi volumes are of type // RWO or ROX, we could permit only one RW mount. Same iscsi volume mounted by multiple Pods // conflict unless all other pods mount as read only. if iqn == eiqn && !(volume.ISCSI.ReadOnly && existingVolume.ISCSI.ReadOnly) { return true } } if volume.RBD != nil && existingVolume.RBD != nil { mon, pool, image := volume.RBD.CephMonitors, volume.RBD.RBDPool, volume.RBD.RBDImage emon, epool, eimage := existingVolume.RBD.CephMonitors, existingVolume.RBD.RBDPool, existingVolume.RBD.RBDImage // two RBDs images are the same if they share the same Ceph monitor, are in the same RADOS Pool, and have the same image name // only one read-write mount is permitted for the same RBD image. // same RBD image mounted by multiple Pods conflicts unless all Pods mount the image read-only if haveOverlap(mon, emon) && pool == epool && image == eimage && !(volume.RBD.ReadOnly && existingVolume.RBD.ReadOnly) { return true } } } return false } // NoDiskConflict evaluates if a pod can fit due to the volumes it requests, and those that // are already mounted. If there is already a volume mounted on that node, another pod that uses the same volume // can't be scheduled there. // This is GCE, Amazon EBS, ISCSI and Ceph RBD specific for now: // - GCE PD allows multiple mounts as long as they're all read-only // - AWS EBS forbids any two pods mounting the same volume ID // - Ceph RBD forbids if any two pods share at least same monitor, and match pool and image, and the image is read-only // - ISCSI forbids if any two pods share at least same IQN and ISCSI volume is read-only // TODO: migrate this into some per-volume specific code? func NoDiskConflict(pod *v1.Pod, meta Metadata, nodeInfo *schedulernodeinfo.NodeInfo) (bool, []PredicateFailureReason, error) { for _, v := range pod.Spec.Volumes { for _, ev := range nodeInfo.Pods() { if isVolumeConflict(v, ev) { return false, []PredicateFailureReason{ErrDiskConflict}, nil } } } return true, nil, nil } // MaxPDVolumeCountChecker contains information to check the max number of volumes for a predicate. type MaxPDVolumeCountChecker struct { filter VolumeFilter"} {"_id":"doc-en-kubernetes-429365c04c68498556af65f82efff23f0f6b4832665edb31865530abb23e5759","title":"","text":"return true, nil, nil } // haveOverlap searches two arrays and returns true if they have at least one common element; returns false otherwise. func haveOverlap(a1, a2 []string) bool { if len(a1) > len(a2) { a1, a2 = a2, a1 } m := map[string]bool{} for _, val := range a1 { m[val] = true } for _, val := range a2 { if _, ok := m[val]; ok { return true } } return false } // GeneralPredicates checks a group of predicates that the kubelet cares about. // DEPRECATED: this exist only because kubelet uses it. We should change kubelet to execute the individual predicates it requires. func GeneralPredicates(pod *v1.Pod, meta Metadata, nodeInfo *schedulernodeinfo.NodeInfo) (bool, []PredicateFailureReason, error) {"} {"_id":"doc-en-kubernetes-b84b655c445c556002d81f7bd465b80614c07f980564feab17700bbd7edbebd0","title":"","text":"} } func TestGCEDiskConflicts(t *testing.T) { volState := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: \"foo\", }, }, }, }, } volState2 := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: \"bar\", }, }, }, }, } tests := []struct { pod *v1.Pod nodeInfo *schedulernodeinfo.NodeInfo isOk bool name string }{ {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(), true, \"nothing\"}, {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"one state\"}, {&v1.Pod{Spec: volState}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), false, \"same state\"}, {&v1.Pod{Spec: volState2}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"different state\"}, } expectedFailureReasons := []PredicateFailureReason{ErrDiskConflict} for _, test := range tests { t.Run(test.name, func(t *testing.T) { ok, reasons, err := NoDiskConflict(test.pod, nil, test.nodeInfo) if err != nil { t.Errorf(\"unexpected error: %v\", err) } if !ok && !reflect.DeepEqual(reasons, expectedFailureReasons) { t.Errorf(\"unexpected failure reasons: %v, want: %v\", reasons, expectedFailureReasons) } if test.isOk && !ok { t.Errorf(\"expected ok, got none. %v %s\", test.pod, test.nodeInfo) } if !test.isOk && ok { t.Errorf(\"expected no ok, got one. %v %s\", test.pod, test.nodeInfo) } }) } } func TestAWSDiskConflicts(t *testing.T) { volState := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: \"foo\", }, }, }, }, } volState2 := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{ VolumeID: \"bar\", }, }, }, }, } tests := []struct { pod *v1.Pod nodeInfo *schedulernodeinfo.NodeInfo isOk bool name string }{ {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(), true, \"nothing\"}, {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"one state\"}, {&v1.Pod{Spec: volState}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), false, \"same state\"}, {&v1.Pod{Spec: volState2}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"different state\"}, } expectedFailureReasons := []PredicateFailureReason{ErrDiskConflict} for _, test := range tests { t.Run(test.name, func(t *testing.T) { ok, reasons, err := NoDiskConflict(test.pod, nil, test.nodeInfo) if err != nil { t.Errorf(\"unexpected error: %v\", err) } if !ok && !reflect.DeepEqual(reasons, expectedFailureReasons) { t.Errorf(\"unexpected failure reasons: %v, want: %v\", reasons, expectedFailureReasons) } if test.isOk && !ok { t.Errorf(\"expected ok, got none. %v %s\", test.pod, test.nodeInfo) } if !test.isOk && ok { t.Errorf(\"expected no ok, got one. %v %s\", test.pod, test.nodeInfo) } }) } } func TestRBDDiskConflicts(t *testing.T) { volState := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ RBD: &v1.RBDVolumeSource{ CephMonitors: []string{\"a\", \"b\"}, RBDPool: \"foo\", RBDImage: \"bar\", FSType: \"ext4\", }, }, }, }, } volState2 := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ RBD: &v1.RBDVolumeSource{ CephMonitors: []string{\"c\", \"d\"}, RBDPool: \"foo\", RBDImage: \"bar\", FSType: \"ext4\", }, }, }, }, } tests := []struct { pod *v1.Pod nodeInfo *schedulernodeinfo.NodeInfo isOk bool name string }{ {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(), true, \"nothing\"}, {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"one state\"}, {&v1.Pod{Spec: volState}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), false, \"same state\"}, {&v1.Pod{Spec: volState2}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"different state\"}, } expectedFailureReasons := []PredicateFailureReason{ErrDiskConflict} for _, test := range tests { t.Run(test.name, func(t *testing.T) { ok, reasons, err := NoDiskConflict(test.pod, nil, test.nodeInfo) if err != nil { t.Errorf(\"unexpected error: %v\", err) } if !ok && !reflect.DeepEqual(reasons, expectedFailureReasons) { t.Errorf(\"unexpected failure reasons: %v, want: %v\", reasons, expectedFailureReasons) } if test.isOk && !ok { t.Errorf(\"expected ok, got none. %v %s\", test.pod, test.nodeInfo) } if !test.isOk && ok { t.Errorf(\"expected no ok, got one. %v %s\", test.pod, test.nodeInfo) } }) } } func TestISCSIDiskConflicts(t *testing.T) { volState := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: \"127.0.0.1:3260\", IQN: \"iqn.2016-12.server:storage.target01\", FSType: \"ext4\", Lun: 0, }, }, }, }, } volState2 := v1.PodSpec{ Volumes: []v1.Volume{ { VolumeSource: v1.VolumeSource{ ISCSI: &v1.ISCSIVolumeSource{ TargetPortal: \"127.0.0.1:3260\", IQN: \"iqn.2017-12.server:storage.target01\", FSType: \"ext4\", Lun: 0, }, }, }, }, } tests := []struct { pod *v1.Pod nodeInfo *schedulernodeinfo.NodeInfo isOk bool name string }{ {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(), true, \"nothing\"}, {&v1.Pod{}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"one state\"}, {&v1.Pod{Spec: volState}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), false, \"same state\"}, {&v1.Pod{Spec: volState2}, schedulernodeinfo.NewNodeInfo(&v1.Pod{Spec: volState}), true, \"different state\"}, } expectedFailureReasons := []PredicateFailureReason{ErrDiskConflict} for _, test := range tests { t.Run(test.name, func(t *testing.T) { ok, reasons, err := NoDiskConflict(test.pod, nil, test.nodeInfo) if err != nil { t.Errorf(\"unexpected error: %v\", err) } if !ok && !reflect.DeepEqual(reasons, expectedFailureReasons) { t.Errorf(\"unexpected failure reasons: %v, want: %v\", reasons, expectedFailureReasons) } if test.isOk && !ok { t.Errorf(\"expected ok, got none. %v %s\", test.pod, test.nodeInfo) } if !test.isOk && ok { t.Errorf(\"expected no ok, got one. %v %s\", test.pod, test.nodeInfo) } }) } } // TODO: Add test case for RequiredDuringSchedulingRequiredDuringExecution after it's implemented. func TestPodFitsSelector(t *testing.T) { tests := []struct {"} {"_id":"doc-en-kubernetes-57044d90d41c8382fa1fb8537d725dde1503c574584d88d23b8ecf2746250cd0","title":"","text":") // Fit is determined by non-conflicting disk volumes. scheduler.RegisterFitPredicate(predicates.NoDiskConflictPred, predicates.NoDiskConflict) scheduler.RegisterFitPredicateFactory( predicates.NoDiskConflictPred, func(args scheduler.AlgorithmFactoryArgs) predicates.FitPredicate { return nil }, ) // GeneralPredicates are the predicates that are enforced by all Kubernetes components // (e.g. kubelet and all schedulers)"} {"_id":"doc-en-kubernetes-a089d0cb47830d18c1577f413001e7b8dd9824850998f6f6f582fbc1ba1f2af2","title":"","text":"visibility = [\"//visibility:public\"], deps = [ \"//pkg/scheduler/algorithm/predicates:go_default_library\", \"//pkg/scheduler/framework/plugins/migration:go_default_library\", \"//pkg/scheduler/framework/v1alpha1:go_default_library\", \"//pkg/scheduler/nodeinfo:go_default_library\", \"//staging/src/k8s.io/api/core/v1:go_default_library\","} {"_id":"doc-en-kubernetes-5b39db76937dd15a9ae8f645506b385ceb8e5cd55764f6c505a8114ad328ee13","title":"","text":"v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/kubernetes/pkg/scheduler/algorithm/predicates\" \"k8s.io/kubernetes/pkg/scheduler/framework/plugins/migration\" framework \"k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1\" \"k8s.io/kubernetes/pkg/scheduler/nodeinfo\" )"} {"_id":"doc-en-kubernetes-94f58da30445843d4297bb89e1f6a994eaf92de1ce3766c17026f721d9a6c4be","title":"","text":"return Name } func isVolumeConflict(volume v1.Volume, pod *v1.Pod) bool { // fast path if there is no conflict checking targets. if volume.GCEPersistentDisk == nil && volume.AWSElasticBlockStore == nil && volume.RBD == nil && volume.ISCSI == nil { return false } for _, existingVolume := range pod.Spec.Volumes { // Same GCE disk mounted by multiple pods conflicts unless all pods mount it read-only. if volume.GCEPersistentDisk != nil && existingVolume.GCEPersistentDisk != nil { disk, existingDisk := volume.GCEPersistentDisk, existingVolume.GCEPersistentDisk if disk.PDName == existingDisk.PDName && !(disk.ReadOnly && existingDisk.ReadOnly) { return true } } if volume.AWSElasticBlockStore != nil && existingVolume.AWSElasticBlockStore != nil { if volume.AWSElasticBlockStore.VolumeID == existingVolume.AWSElasticBlockStore.VolumeID { return true } } if volume.ISCSI != nil && existingVolume.ISCSI != nil { iqn := volume.ISCSI.IQN eiqn := existingVolume.ISCSI.IQN // two ISCSI volumes are same, if they share the same iqn. As iscsi volumes are of type // RWO or ROX, we could permit only one RW mount. Same iscsi volume mounted by multiple Pods // conflict unless all other pods mount as read only. if iqn == eiqn && !(volume.ISCSI.ReadOnly && existingVolume.ISCSI.ReadOnly) { return true } } if volume.RBD != nil && existingVolume.RBD != nil { mon, pool, image := volume.RBD.CephMonitors, volume.RBD.RBDPool, volume.RBD.RBDImage emon, epool, eimage := existingVolume.RBD.CephMonitors, existingVolume.RBD.RBDPool, existingVolume.RBD.RBDImage // two RBDs images are the same if they share the same Ceph monitor, are in the same RADOS Pool, and have the same image name // only one read-write mount is permitted for the same RBD image. // same RBD image mounted by multiple Pods conflicts unless all Pods mount the image read-only if haveOverlap(mon, emon) && pool == epool && image == eimage && !(volume.RBD.ReadOnly && existingVolume.RBD.ReadOnly) { return true } } } return false } // haveOverlap searches two arrays and returns true if they have at least one common element; returns false otherwise. func haveOverlap(a1, a2 []string) bool { if len(a1) > len(a2) { a1, a2 = a2, a1 } m := map[string]bool{} for _, val := range a1 { m[val] = true } for _, val := range a2 { if _, ok := m[val]; ok { return true } } return false } // Filter invoked at the filter extension point. // It evaluates if a pod can fit due to the volumes it requests, and those that // are already mounted. If there is already a volume mounted on that node, another pod that uses the same volume // can't be scheduled there. // This is GCE, Amazon EBS, ISCSI and Ceph RBD specific for now: // - GCE PD allows multiple mounts as long as they're all read-only // - AWS EBS forbids any two pods mounting the same volume ID // - Ceph RBD forbids if any two pods share at least same monitor, and match pool and image, and the image is read-only // - ISCSI forbids if any two pods share at least same IQN and ISCSI volume is read-only func (pl *VolumeRestrictions) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status { // metadata is not needed for NoDiskConflict _, reasons, err := predicates.NoDiskConflict(pod, nil, nodeInfo) return migration.PredicateResultToFrameworkStatus(reasons, err) for _, v := range pod.Spec.Volumes { for _, ev := range nodeInfo.Pods() { if isVolumeConflict(v, ev) { return framework.NewStatus(framework.Unschedulable, predicates.ErrDiskConflict.GetReason()) } } } return nil } // New initializes a new plugin and returns it."} {"_id":"doc-en-kubernetes-0adeb10fd84b09631ad4cfbc66f92fd1518571ffcffa7cbb64886aa530b9b32d","title":"","text":"fs.IPVar(&s.BindAddress, \"bind-address\", s.BindAddress, \"\"+ \"The IP address on which to listen for the --secure-port port. The \"+ \"associated interface(s) must be reachable by the rest of the cluster, and by CLI/web \"+ \"clients. If blank, all interfaces will be used (0.0.0.0 for all IPv4 interfaces and :: for all IPv6 interfaces).\") \"clients. If blank or an unspecified address (0.0.0.0 or ::), all interfaces will be used.\") desc := \"The port on which to serve HTTPS with authentication and authorization.\" if s.Required {"} {"_id":"doc-en-kubernetes-c13232b721d5a00d4842dba6f03d3befbe6640a1731399210fa6e2e2b33f22f1","title":"","text":"// shouldRetryHTTPRequest determines if the request is retriable. func shouldRetryHTTPRequest(resp *http.Response, err error) bool { if resp != nil { // HTTP 412 (StatusPreconditionFailed) means etag mismatch, hence we shouldn't retry. if resp.StatusCode == http.StatusPreconditionFailed { // HTTP 412 (StatusPreconditionFailed) means etag mismatch // HTTP 400 (BadRequest) means the request cannot be accepted, hence we shouldn't retry. if resp.StatusCode == http.StatusPreconditionFailed || resp.StatusCode == http.StatusBadRequest { return false }"} {"_id":"doc-en-kubernetes-8af178860a3c1800ecf419aa518069c607460de0970fb5edf5d40402c80f5995","title":"","text":"{ code: http.StatusBadRequest, expected: &Error{ Retriable: true, Retriable: false, HTTPStatusCode: http.StatusBadRequest, RawError: fmt.Errorf(\"HTTP response: 400\"), },"} {"_id":"doc-en-kubernetes-e70be627d8d51fa7e0f637efd62c004bfa1d350a20f631f1930efa35e344dcc0","title":"","text":"}{ { code: http.StatusBadRequest, expected: true, expected: false, }, { code: http.StatusInternalServerError,"} {"_id":"doc-en-kubernetes-a5eeaaffcfd37613e9f7975330b981fc16139de1ebfe20515643d8dc96cc6a25","title":"","text":"ginkgo.It(\"each node by switching off the network interface and ensure they function upon switch on\", func() { // switch the network interface off for a while to simulate a network outage // We sleep 10 seconds to give some time for ssh command to cleanly finish before network is down. testReboot(f.ClientSet, \"nohup sh -c 'sleep 10 && sudo ip link set eth0 down && sleep 120 && sudo ip link set eth0 up && (sudo dhclient || true)' >/dev/null 2>&1 &\", nil) cmd := \"nohup sh -c '\" + \"sleep 10; \" + \"echo Shutting down eth0 | sudo tee /dev/kmsg; \" + \"sudo ip link set eth0 down | sudo tee /dev/kmsg; \" + \"sleep 120; \" + \"echo Starting up eth0 | sudo tee /dev/kmsg; \" + \"sudo ip link set eth0 up | sudo tee /dev/kmsg; \" + \"sleep 10; \" + \"echo Retrying starting up eth0 | sudo tee /dev/kmsg; \" + \"sudo ip link set eth0 up | sudo tee /dev/kmsg; \" + \"echo Running dhclient | sudo tee /dev/kmsg; \" + \"sudo dhclient | sudo tee /dev/kmsg; \" + \"echo Starting systemd-networkd | sudo tee /dev/kmsg; \" + \"sudo systemctl restart systemd-networkd | sudo tee /dev/kmsg\" + \"' >/dev/null 2>&1 &\" testReboot(f.ClientSet, cmd, nil) }) ginkgo.It(\"each node by dropping all inbound packets for a while and ensure they function afterwards\", func() {"} {"_id":"doc-en-kubernetes-22a44886667493629afb8034070769f6f0f75c92ca9fb589af6a697970502eb6","title":"","text":"\"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/types:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/diff:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/admission:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/admission/testing:go_default_library\", \"//staging/src/k8s.io/client-go/informers:go_default_library\","} {"_id":"doc-en-kubernetes-763aca648a5e5e3399741808f3467ed70a42e581c4b66e4dcde6230a00c35a01","title":"","text":"} func (s *Plugin) mountServiceAccountToken(serviceAccount *corev1.ServiceAccount, pod *api.Pod) error { // Find the name of a referenced ServiceAccountToken secret we can mount serviceAccountToken, err := s.getReferencedServiceAccountToken(serviceAccount) if err != nil { return fmt.Errorf(\"Error looking up service account token for %s/%s: %v\", serviceAccount.Namespace, serviceAccount.Name, err) var ( // serviceAccountToken holds the name of a secret containing a legacy service account token serviceAccountToken string err error ) if !s.boundServiceAccountTokenVolume { // Find the name of a referenced ServiceAccountToken secret we can mount serviceAccountToken, err = s.getReferencedServiceAccountToken(serviceAccount) if err != nil { return fmt.Errorf(\"Error looking up service account token for %s/%s: %v\", serviceAccount.Namespace, serviceAccount.Name, err) } } if len(serviceAccountToken) == 0 { if len(serviceAccountToken) == 0 && !s.boundServiceAccountTokenVolume { // We don't have an API token to mount, so return if s.RequireAPIToken { // If a token is required, this is considered an error"} {"_id":"doc-en-kubernetes-787a48e6b2ff785f08acb2b834e292973c6904d1428c6d11f9ac800fcaba7678","title":"","text":"\"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/diff\" \"k8s.io/apiserver/pkg/admission\" admissiontesting \"k8s.io/apiserver/pkg/admission/testing\" \"k8s.io/client-go/informers\""} {"_id":"doc-en-kubernetes-28c1b3b6d4d151625bab0916448d6ac63c3486e03f5d220f0a074ec45743dbe6","title":"","text":"} } func TestAssignsDefaultServiceAccountAndBoundTokenWithNoSecretTokens(t *testing.T) { ns := \"myns\" admit := NewServiceAccount() informerFactory := informers.NewSharedInformerFactory(nil, controller.NoResyncPeriodFunc()) admit.SetExternalKubeInformerFactory(informerFactory) admit.MountServiceAccountToken = true admit.RequireAPIToken = true admit.boundServiceAccountTokenVolume = true // Add the default service account for the ns into the cache informerFactory.Core().V1().ServiceAccounts().Informer().GetStore().Add(&corev1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: DefaultServiceAccountName, Namespace: ns, }, }) pod := &api.Pod{ Spec: api.PodSpec{ Containers: []api.Container{{}}, }, } attrs := admission.NewAttributesRecord(pod, nil, api.Kind(\"Pod\").WithVersion(\"version\"), ns, \"myname\", api.Resource(\"pods\").WithVersion(\"version\"), \"\", admission.Create, &metav1.CreateOptions{}, false, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil) if err != nil { t.Fatalf(\"Expected success, got: %v\", err) } expectedVolumes := []api.Volume{{ Name: \"cleared\", VolumeSource: api.VolumeSource{ Projected: &api.ProjectedVolumeSource{ Sources: []api.VolumeProjection{ {ServiceAccountToken: &api.ServiceAccountTokenProjection{ExpirationSeconds: 3600, Path: \"token\"}}, {ConfigMap: &api.ConfigMapProjection{LocalObjectReference: api.LocalObjectReference{Name: \"kube-root-ca.crt\"}, Items: []api.KeyToPath{{Key: \"ca.crt\", Path: \"ca.crt\"}}}}, {DownwardAPI: &api.DownwardAPIProjection{Items: []api.DownwardAPIVolumeFile{{Path: \"namespace\", FieldRef: &api.ObjectFieldSelector{APIVersion: \"v1\", FieldPath: \"metadata.namespace\"}}}}}, }, }, }, }} expectedVolumeMounts := []api.VolumeMount{{ Name: \"cleared\", ReadOnly: true, MountPath: \"/var/run/secrets/kubernetes.io/serviceaccount\", }} // clear generated volume names for i := range pod.Spec.Volumes { if len(pod.Spec.Volumes[i].Name) > 0 { pod.Spec.Volumes[i].Name = \"cleared\" } } for i := range pod.Spec.Containers[0].VolumeMounts { if len(pod.Spec.Containers[0].VolumeMounts[i].Name) > 0 { pod.Spec.Containers[0].VolumeMounts[i].Name = \"cleared\" } } if !reflect.DeepEqual(expectedVolumes, pod.Spec.Volumes) { t.Errorf(\"unexpected volumes: %s\", diff.ObjectReflectDiff(expectedVolumes, pod.Spec.Volumes)) } if !reflect.DeepEqual(expectedVolumeMounts, pod.Spec.Containers[0].VolumeMounts) { t.Errorf(\"unexpected volumes: %s\", diff.ObjectReflectDiff(expectedVolumeMounts, pod.Spec.Containers[0].VolumeMounts)) } } func TestFetchesUncachedServiceAccount(t *testing.T) { ns := \"myns\""} {"_id":"doc-en-kubernetes-8927a706d7104f6b506826e1c67bfa9268e9b80457b77c1e29ce297523ac052d","title":"","text":"return status, true, nil } func getPublicIPDomainNameLabel(service *v1.Service) string { func getPublicIPDomainNameLabel(service *v1.Service) (string, bool) { if labelName, found := service.Annotations[ServiceAnnotationDNSLabelName]; found { return labelName return labelName, found } return \"\" return \"\", false } // EnsureLoadBalancer creates a new load balancer 'name', or updates the existing one. Returns the status of the balancer"} {"_id":"doc-en-kubernetes-8eabe6a299728664cf94bbbc463fd5789457454bdecc6f5ddb3c52ed101d00dd","title":"","text":"return lbStatus.Ingress[0].IP, nil } func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted bool) (*network.PublicIPAddress, error) { func (az *Cloud) ensurePublicIPExists(service *v1.Service, pipName string, domainNameLabel, clusterName string, shouldPIPExisted, foundDNSLabelAnnotation bool) (*network.PublicIPAddress, error) { pipResourceGroup := az.getPublicIPAddressResourceGroup(service) pip, existsPip, err := az.getPublicIPAddress(pipResourceGroup, pipName) if err != nil {"} {"_id":"doc-en-kubernetes-741527566e2308fd31b3c0b5e5aa48b2ac5fbc379d00bd9e98b5a4c91ecb07fd","title":"","text":"} klog.V(2).Infof(\"ensurePublicIPExists for service(%s): pip(%s) - creating\", serviceName, *pip.Name) } if len(domainNameLabel) == 0 { pip.PublicIPAddressPropertiesFormat.DNSSettings = nil } else { pip.PublicIPAddressPropertiesFormat.DNSSettings = &network.PublicIPAddressDNSSettings{ DomainNameLabel: &domainNameLabel, if foundDNSLabelAnnotation { if len(domainNameLabel) == 0 { pip.PublicIPAddressPropertiesFormat.DNSSettings = nil } else { pip.PublicIPAddressPropertiesFormat.DNSSettings = &network.PublicIPAddressDNSSettings{ DomainNameLabel: &domainNameLabel, } } }"} {"_id":"doc-en-kubernetes-a09446df8276aa99f771d6c8cc17c51450afb1aa8574c231ddc4e85c35de51d8","title":"","text":"if err != nil { return nil, err } domainNameLabel := getPublicIPDomainNameLabel(service) pip, err := az.ensurePublicIPExists(service, pipName, domainNameLabel, clusterName, shouldPIPExisted) domainNameLabel, found := getPublicIPDomainNameLabel(service) pip, err := az.ensurePublicIPExists(service, pipName, domainNameLabel, clusterName, shouldPIPExisted, found) if err != nil { return nil, err }"} {"_id":"doc-en-kubernetes-00dd7fb5f6d844a287551ca4eb0886b600b997f193b7445206923299a14e921f","title":"","text":"if !isInternal && wantLb { // Confirm desired public ip resource exists var pip *network.PublicIPAddress domainNameLabel := getPublicIPDomainNameLabel(service) if pip, err = az.ensurePublicIPExists(service, desiredPipName, domainNameLabel, clusterName, shouldPIPExisted); err != nil { domainNameLabel, found := getPublicIPDomainNameLabel(service) if pip, err = az.ensurePublicIPExists(service, desiredPipName, domainNameLabel, clusterName, shouldPIPExisted, found); err != nil { return nil, err } return pip, nil"} {"_id":"doc-en-kubernetes-cdcd995ef40b489c3973a2803f3abd0ef2b0d49f888731d1cbeb1d181f1c4737","title":"","text":"pip, err := az.reconcilePublicIP(\"testCluster\", &service, \"\", test.wantLb) if test.expectedID != \"\" { assert.Equal(t, test.expectedID, to.String(pip.ID), \"TestCase[%d]: %s\", i, test.desc) } else { assert.Equal(t, test.expectedPIP, pip, \"TestCase[%d]: %s\", i, test.desc) } else if test.expectedPIP != nil && test.expectedPIP.Name != nil { assert.Equal(t, *test.expectedPIP.Name, *pip.Name, \"TestCase[%d]: %s\", i, test.desc) } assert.Equal(t, test.expectedError, err != nil, \"TestCase[%d]: %s\", i, test.desc) }"} {"_id":"doc-en-kubernetes-240361d04ecfd59420dbf0a6e1753af26374437785a342aeb3e84e81e7640994","title":"","text":"func TestEnsurePublicIPExists(t *testing.T) { testCases := []struct { desc string existingPIPs []network.PublicIPAddress expectedPIP *network.PublicIPAddress expectedID string expectedDNS string expectedError bool desc string existingPIPs []network.PublicIPAddress inputDNSLabel string foundDNSLabelAnnotation bool expectedPIP *network.PublicIPAddress expectedID string expectedError bool }{ { desc: \"ensurePublicIPExists shall return existed PIP if there is any\","} {"_id":"doc-en-kubernetes-533a766a9684879a916a74363f7d61b0581211463b004e2c61aa3cee56f7c66b","title":"","text":"\"Microsoft.Network/publicIPAddresses/pip1\", }, { desc: \"ensurePublicIPExists shall update existed PIP's dns label\", desc: \"ensurePublicIPExists shall update existed PIP's dns label\", inputDNSLabel: \"newdns\", foundDNSLabelAnnotation: true, existingPIPs: []network.PublicIPAddress{{ Name: to.StringPtr(\"pip1\"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{"} {"_id":"doc-en-kubernetes-2de1a4b33a9966c2e87241f2e11703f861df7af4c61b1ca428dcf785c6c312a7","title":"","text":"}, }, }, expectedDNS: \"newdns\", }, { desc: \"ensurePublicIPExists shall delete DNS from PIP if DNS label is set empty\", foundDNSLabelAnnotation: true, existingPIPs: []network.PublicIPAddress{{ Name: to.StringPtr(\"pip1\"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ DomainNameLabel: to.StringPtr(\"previousdns\"), }, }, }}, expectedPIP: &network.PublicIPAddress{ Name: to.StringPtr(\"pip1\"), ID: to.StringPtr(\"/subscriptions/subscription/resourceGroups/rg\" + \"/providers/Microsoft.Network/publicIPAddresses/pip1\"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: nil, }, }, }, { desc: \"ensurePublicIPExists shall not delete DNS from PIP if DNS label annotation is not set\", foundDNSLabelAnnotation: false, existingPIPs: []network.PublicIPAddress{{ Name: to.StringPtr(\"pip1\"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ DomainNameLabel: to.StringPtr(\"previousdns\"), }, }, }}, expectedPIP: &network.PublicIPAddress{ Name: to.StringPtr(\"pip1\"), ID: to.StringPtr(\"/subscriptions/subscription/resourceGroups/rg\" + \"/providers/Microsoft.Network/publicIPAddresses/pip1\"), PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{ DNSSettings: &network.PublicIPAddressDNSSettings{ DomainNameLabel: to.StringPtr(\"previousdns\"), }, }, }, }, }"} {"_id":"doc-en-kubernetes-c1f1e135efbb2352e42fded42e7c36e30fbea9730bffa347a52dc13aeeec5538","title":"","text":"t.Fatalf(\"TestCase[%d] meets unexpected error: %v\", i, err) } } pip, err := az.ensurePublicIPExists(&service, \"pip1\", test.expectedDNS, \"\", false) pip, err := az.ensurePublicIPExists(&service, \"pip1\", test.inputDNSLabel, \"\", false, test.foundDNSLabelAnnotation) if test.expectedID != \"\" { assert.Equal(t, test.expectedID, to.String(pip.ID), \"TestCase[%d]: %s\", i, test.desc) } else {"} {"_id":"doc-en-kubernetes-e443883bce2c295d242766f385f9969751dd2a0b0d17c1d88664934a222402ff","title":"","text":"else bazel-release: bazel build //build/release-tars bazel shutdown endif"} {"_id":"doc-en-kubernetes-cbd175185377e556bda36491ff58ab3a4be1284c6c6195e31e2004aa78313a9d","title":"","text":"if len(name) == 0 { _, name, _ = scope.Namer.ObjectName(obj) } admissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo) if mutatingAdmission, ok := admit.(admission.MutationInterface); ok && mutatingAdmission.Handles(admission.Create) { err = mutatingAdmission.Admit(ctx, admissionAttributes, scope) if err != nil { scope.err(err, w, req) return } } if scope.FieldManager != nil { liveObj, err := scope.Creater.New(scope.Kind) if err != nil { scope.err(fmt.Errorf(\"failed to create new object (Create for %v): %v\", scope.Kind, err), w, req) return trace.Step(\"About to store object in database\") result, err := finishRequest(timeout, func() (runtime.Object, error) { if scope.FieldManager != nil { liveObj, err := scope.Creater.New(scope.Kind) if err != nil { return nil, fmt.Errorf(\"failed to create new object (Create for %v): %v\", scope.Kind, err) } obj, err = scope.FieldManager.Update(liveObj, obj, managerOrUserAgent(options.FieldManager, req.UserAgent())) if err != nil { return nil, fmt.Errorf(\"failed to update object (Create for %v) managed fields: %v\", scope.Kind, err) } } obj, err = scope.FieldManager.Update(liveObj, obj, managerOrUserAgent(options.FieldManager, req.UserAgent())) if err != nil { scope.err(fmt.Errorf(\"failed to update object (Create for %v) managed fields: %v\", scope.Kind, err), w, req) return admissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo) if mutatingAdmission, ok := admit.(admission.MutationInterface); ok && mutatingAdmission.Handles(admission.Create) { if err := mutatingAdmission.Admit(ctx, admissionAttributes, scope); err != nil { return nil, err } } } trace.Step(\"About to store object in database\") result, err := finishRequest(timeout, func() (runtime.Object, error) { return r.Create( ctx, name,"} {"_id":"doc-en-kubernetes-c31b629c21ddd725082d8b93602772b9c74c00b37b966b85d8b14b08e3370252","title":"","text":"leaveStdinOpen := o.LeaveStdinOpen waitForExitCode := !leaveStdinOpen && restartPolicy == corev1.RestartPolicyNever if waitForExitCode { pod, err = waitForPod(clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, podCompleted) pod, err = waitForPod(clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, opts.GetPodTimeout, podCompleted) if err != nil { return err }"} {"_id":"doc-en-kubernetes-7816e759c1aa06e34f90c2a400d1cdfbb574b45bc8d6f5832c1468a0d67d44db","title":"","text":"} // waitForPod watches the given pod until the exitCondition is true func waitForPod(podClient corev1client.PodsGetter, ns, name string, exitCondition watchtools.ConditionFunc) (*corev1.Pod, error) { // TODO: expose the timeout ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), 0*time.Second) func waitForPod(podClient corev1client.PodsGetter, ns, name string, timeout time.Duration, exitCondition watchtools.ConditionFunc) (*corev1.Pod, error) { ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), timeout) defer cancel() preconditionFunc := func(store cache.Store) (bool, error) {"} {"_id":"doc-en-kubernetes-61518b72f26eac32fc9e238a882c9f1a3b86597bfa9af603dc3264fe95746f77","title":"","text":"} func handleAttachPod(f cmdutil.Factory, podClient corev1client.PodsGetter, ns, name string, opts *attach.AttachOptions) error { pod, err := waitForPod(podClient, ns, name, podRunningAndReady) pod, err := waitForPod(podClient, ns, name, opts.GetPodTimeout, podRunningAndReady) if err != nil && err != ErrPodCompleted { return err }"} {"_id":"doc-en-kubernetes-33b896d57ce2fbce38643dc5babd3a919e564b4f0ca5139c94f366c78c16c9e8","title":"","text":"ctx, cancel := watchtools.ContextWithOptionalTimeout(ctx, 0*time.Second) defer cancel() preconditionFunc := func(store cache.Store) (bool, error) { _, exists, err := store.Get(&metav1.ObjectMeta{Namespace: ns, Name: podName}) if err != nil { return true, err } if !exists { // We need to make sure we see the object in the cache before we start waiting for events // or we would be waiting for the timeout if such object didn't exist. // (e.g. it was deleted before we started informers so they wouldn't even see the delete event) return true, errors.NewNotFound(corev1.Resource(\"pods\"), podName) } return false, nil } fieldSelector := fields.OneTermEqualSelector(\"metadata.name\", podName).String() lw := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {"} {"_id":"doc-en-kubernetes-b75215a17055915a4ebda2c9efb85c17f822c3bdd61473723c1fa8c54c4e2624","title":"","text":"intr := interrupt.New(nil, cancel) var result *corev1.Pod err := intr.Run(func() error { ev, err := watchtools.UntilWithSync(ctx, lw, &corev1.Pod{}, preconditionFunc, func(ev watch.Event) (bool, error) { ev, err := watchtools.UntilWithSync(ctx, lw, &corev1.Pod{}, nil, func(ev watch.Event) (bool, error) { switch ev.Type { case watch.Deleted: return false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\")"} {"_id":"doc-en-kubernetes-ba3e65ff984fd83b755d2800ef250410b4201f0db0aadab8ef4a798106f0bed2","title":"","text":"\"//build/visible_to:pkg_kubectl_cmd_rollout_CONSUMERS\", ], deps = [ \"//staging/src/k8s.io/apimachinery/pkg/api/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/api/meta:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library\","} {"_id":"doc-en-kubernetes-384c41309df848db374e34352cb7381c83919492e26cfbc6f46e9e6c3fecde5d","title":"","text":"\"github.com/spf13/cobra\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" \"k8s.io/apimachinery/pkg/api/meta\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\""} {"_id":"doc-en-kubernetes-b1e8607e6788aa021b4e40146bc474c80541d74940913af2c766bcafd7adf877","title":"","text":"}, } preconditionFunc := func(store cache.Store) (bool, error) { _, exists, err := store.Get(&metav1.ObjectMeta{Namespace: info.Namespace, Name: info.Name}) if err != nil { return true, err } if !exists { // We need to make sure we see the object in the cache before we start waiting for events // or we would be waiting for the timeout if such object didn't exist. return true, apierrors.NewNotFound(mapping.Resource.GroupResource(), info.Name) } return false, nil } // if the rollout isn't done yet, keep watching deployment status ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout) intr := interrupt.New(nil, cancel) return intr.Run(func() error { _, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, preconditionFunc, func(e watch.Event) (bool, error) { _, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, nil, func(e watch.Event) (bool, error) { switch t := e.Type; t { case watch.Added, watch.Modified: status, done, err := statusViewer.Status(e.Object.(runtime.Unstructured), o.Revision)"} {"_id":"doc-en-kubernetes-bd914f60026895443b3c094bb0ae3dd168f3497fdc89d7b3f3323ad122a9efda","title":"","text":"} var pod *corev1.Pod leaveStdinOpen := o.LeaveStdinOpen waitForExitCode := !leaveStdinOpen && restartPolicy == corev1.RestartPolicyNever waitForExitCode := !o.LeaveStdinOpen && (restartPolicy == corev1.RestartPolicyNever || restartPolicy == corev1.RestartPolicyOnFailure) if waitForExitCode { pod, err = waitForPod(clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, opts.GetPodTimeout, podCompleted) // we need different exit condition depending on restart policy // for Never it can either fail or succeed, for OnFailure only // success matters exitCondition := podCompleted if restartPolicy == corev1.RestartPolicyOnFailure { exitCondition = podSucceeded } pod, err = waitForPod(clientset.CoreV1(), attachablePod.Namespace, attachablePod.Name, opts.GetPodTimeout, exitCondition) if err != nil { return err } } // after removal is done, return successfully if we are not interested in the exit code if !waitForExitCode { } else { // after removal is done, return successfully if we are not interested in the exit code return nil }"} {"_id":"doc-en-kubernetes-42496906ca958f9d6c62290ae49a1861f2fc3956c69601fd5dd5fe8786966c34","title":"","text":"ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), timeout) defer cancel() preconditionFunc := func(store cache.Store) (bool, error) { _, exists, err := store.Get(&metav1.ObjectMeta{Namespace: ns, Name: name}) if err != nil { return true, err } if !exists { // We need to make sure we see the object in the cache before we start waiting for events // or we would be waiting for the timeout if such object didn't exist. // (e.g. it was deleted before we started informers so they wouldn't even see the delete event) return true, errors.NewNotFound(corev1.Resource(\"pods\"), name) } return false, nil } fieldSelector := fields.OneTermEqualSelector(\"metadata.name\", name).String() lw := &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {"} {"_id":"doc-en-kubernetes-bd141d73b034a2572d4d0dec398a481adc25decd28e74d765745ea39e229e02a","title":"","text":"intr := interrupt.New(nil, cancel) var result *corev1.Pod err := intr.Run(func() error { ev, err := watchtools.UntilWithSync(ctx, lw, &corev1.Pod{}, preconditionFunc, func(ev watch.Event) (bool, error) { return exitCondition(ev) }) ev, err := watchtools.UntilWithSync(ctx, lw, &corev1.Pod{}, nil, exitCondition) if ev != nil { result = ev.Object.(*corev1.Pod) }"} {"_id":"doc-en-kubernetes-e19230fed73579d78f6ba3e07b763271194f8c2fc5967c782301409e786ffcae","title":"","text":"return false, nil } // podSucceeded returns true if the pod has run to completion, false if the pod has not yet // reached running state, or an error in any other case. func podSucceeded(event watch.Event) (bool, error) { switch event.Type { case watch.Deleted: return false, errors.NewNotFound(schema.GroupResource{Resource: \"pods\"}, \"\") } switch t := event.Object.(type) { case *corev1.Pod: return t.Status.Phase == corev1.PodSucceeded, nil } return false, nil } // podRunningAndReady returns true if the pod is running and ready, false if the pod has not // yet reached those states, returns ErrPodCompleted if the pod has run to completion, or // an error in any other case."} {"_id":"doc-en-kubernetes-cb062bbec73758dc2514ac3e9a5088392f0141aacf8ec9c0f169a7b113e9e941","title":"","text":"_, err = framework.NewKubectlCommand(ns, nsFlag, \"run\", \"-i\", \"--image=\"+busyboxImage, \"--restart=OnFailure\", \"failure-2\", \"--\", \"/bin/sh\", \"-c\", \"cat && exit 42\"). WithStdinData(\"abcd1234\"). Exec() framework.ExpectNoError(err) ee, ok = err.(uexec.ExitError) framework.ExpectEqual(ok, true) if !strings.Contains(ee.String(), \"timed out\") { framework.Failf(\"Missing expected 'timed out' error, got: %#v\", ee) } ginkgo.By(\"running a failing command without --restart=Never, but with --rm\") _, err = framework.NewKubectlCommand(ns, nsFlag, \"run\", \"-i\", \"--image=\"+busyboxImage, \"--restart=OnFailure\", \"--rm\", \"failure-3\", \"--\", \"/bin/sh\", \"-c\", \"cat && exit 42\"). WithStdinData(\"abcd1234\"). Exec() framework.ExpectNoError(err) ee, ok = err.(uexec.ExitError) framework.ExpectEqual(ok, true) if !strings.Contains(ee.String(), \"timed out\") { framework.Failf(\"Missing expected 'timed out' error, got: %#v\", ee) } e2epod.WaitForPodToDisappear(f.ClientSet, ns, \"failure-3\", labels.Everything(), 2*time.Second, wait.ForeverTestTimeout) ginkgo.By(\"running a failing command with --leave-stdin-open\")"} {"_id":"doc-en-kubernetes-cf0ddc51de2576944b80a7b5360693a67464c5c8fcd0bb3423eacd5cb47c3831","title":"","text":"UseEndpointSlices bool OOMScoreAdj *int32 ConfigSyncPeriod time.Duration HealthzServer *healthcheck.ProxierHealthServer HealthzServer healthcheck.ProxierHealthUpdater } // createClients creates a kube client and an event client from the given config and masterOverride."} {"_id":"doc-en-kubernetes-19b1ab1739472030487ba9bcb90e750173c45b2b8ab975c4008331f44511965a","title":"","text":"Namespace: \"\", } var healthzServer *healthcheck.ProxierHealthServer var healthzServer healthcheck.ProxierHealthUpdater if len(config.HealthzBindAddress) > 0 { healthzServer = healthcheck.NewProxierHealthServer(config.HealthzBindAddress, 2*config.IPTables.SyncPeriod.Duration, recorder, nodeRef) }"} {"_id":"doc-en-kubernetes-1e6d76d015b763008d66971c693ba0ee43100f2abc5a5d0e7cd1840ec8896945","title":"","text":"// Updated should be called when the proxier has successfully updated the service // rules to reflect the current state. Updated() // Run starts the healthz http server and returns. Run() } var _ ProxierHealthUpdater = &ProxierHealthServer{} var _ ProxierHealthUpdater = &proxierHealthServer{} // ProxierHealthServer returns 200 \"OK\" by default. It verifies that the delay between // proxierHealthServer returns 200 \"OK\" by default. It verifies that the delay between // QueuedUpdate() calls and Updated() calls never exceeds healthTimeout. type ProxierHealthServer struct { type proxierHealthServer struct { listener listener httpFactory httpServerFactory clock clock.Clock"} {"_id":"doc-en-kubernetes-56025ef3ce73284c73195d1e512d84844c6d51f5b7943b1f170f975e5e1dd02b","title":"","text":"} // NewProxierHealthServer returns a proxier health http server. func NewProxierHealthServer(addr string, healthTimeout time.Duration, recorder record.EventRecorder, nodeRef *v1.ObjectReference) *ProxierHealthServer { func NewProxierHealthServer(addr string, healthTimeout time.Duration, recorder record.EventRecorder, nodeRef *v1.ObjectReference) ProxierHealthUpdater { return newProxierHealthServer(stdNetListener{}, stdHTTPServerFactory{}, clock.RealClock{}, addr, healthTimeout, recorder, nodeRef) } func newProxierHealthServer(listener listener, httpServerFactory httpServerFactory, c clock.Clock, addr string, healthTimeout time.Duration, recorder record.EventRecorder, nodeRef *v1.ObjectReference) *ProxierHealthServer { return &ProxierHealthServer{ func newProxierHealthServer(listener listener, httpServerFactory httpServerFactory, c clock.Clock, addr string, healthTimeout time.Duration, recorder record.EventRecorder, nodeRef *v1.ObjectReference) *proxierHealthServer { return &proxierHealthServer{ listener: listener, httpFactory: httpServerFactory, clock: c,"} {"_id":"doc-en-kubernetes-ac9e66cd6406fd8f3be0e70ce2c8266a08cee9518dfcc4c212f5fedcbb80de3f","title":"","text":"} // Updated updates the lastUpdated timestamp. func (hs *ProxierHealthServer) Updated() { func (hs *proxierHealthServer) Updated() { hs.lastUpdated.Store(hs.clock.Now()) } // QueuedUpdate updates the lastQueued timestamp. func (hs *ProxierHealthServer) QueuedUpdate() { func (hs *proxierHealthServer) QueuedUpdate() { hs.lastQueued.Store(hs.clock.Now()) } // Run starts the healthz http server and returns. func (hs *ProxierHealthServer) Run() { func (hs *proxierHealthServer) Run() { serveMux := http.NewServeMux() serveMux.Handle(\"/healthz\", healthzHandler{hs: hs}) server := hs.httpFactory.New(hs.addr, serveMux)"} {"_id":"doc-en-kubernetes-c9b3c0eae788731b0d3c11c3918496ac6bbe6fa403c4f39676855894c316b51d","title":"","text":"} type healthzHandler struct { hs *ProxierHealthServer hs *proxierHealthServer } func (h healthzHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {"} {"_id":"doc-en-kubernetes-27ea137c58d70c903582ebee2fa9243623fd171cfa2d70220f38aab226bf25c7","title":"","text":"// trigger a new deployment framework.Logf(\"%02d: triggering a new rollout for deployment %q\", i, deployment.Name) deployment, err = e2edeployment.UpdateDeploymentWithRetries(c, ns, deployment.Name, func(update *appsv1.Deployment) { newEnv := v1.EnvVar{Name: \"A\", Value: fmt.Sprintf(\"%d\", i)} newEnv := v1.EnvVar{Name: fmt.Sprintf(\"A%d\", i), Value: fmt.Sprintf(\"%d\", i)} update.Spec.Template.Spec.Containers[0].Env = append(update.Spec.Template.Spec.Containers[0].Env, newEnv) randomScale(update, i) })"} {"_id":"doc-en-kubernetes-4e9d3ecced1fb869f26c1b985c17ffe54e0a5c816a99cf01b7a659b6600ccae8","title":"","text":"// only return the user provided mode if at least one was valid if len(mode) > 0 { klog.Warningf(\"the default kube-apiserver authorization-mode is %q; using %q\", strings.Join(defaultMode, \",\"), strings.Join(mode, \",\"), ) if !compareAuthzModes(defaultMode, mode) { klog.Warningf(\"the default kube-apiserver authorization-mode is %q; using %q\", strings.Join(defaultMode, \",\"), strings.Join(mode, \",\"), ) } return strings.Join(mode, \",\") } } return strings.Join(defaultMode, \",\") } // compareAuthzModes compares two given authz modes and returns false if they do not match func compareAuthzModes(a, b []string) bool { if len(a) != len(b) { return false } for i, m := range a { if m != b[i] { return false } } return true } func isValidAuthzMode(authzMode string) bool { allModes := []string{ kubeadmconstants.ModeNode,"} {"_id":"doc-en-kubernetes-66ab47e83a05a52a8f38793d74b1f53d6feeb56ae71ccf285cf6db3d3d1ca7d9","title":"","text":"}) } } func TestCompareAuthzModes(t *testing.T) { var tests = []struct { name string modesA []string modesB []string equal bool }{ { name: \"modes match\", modesA: []string{\"a\", \"b\", \"c\"}, modesB: []string{\"a\", \"b\", \"c\"}, equal: true, }, { name: \"modes order does not match\", modesA: []string{\"a\", \"c\", \"b\"}, modesB: []string{\"a\", \"b\", \"c\"}, }, { name: \"modes do not match; A has less modes\", modesA: []string{\"a\", \"b\"}, modesB: []string{\"a\", \"b\", \"c\"}, }, { name: \"modes do not match; B has less modes\", modesA: []string{\"a\", \"b\", \"c\"}, modesB: []string{\"a\", \"b\"}, }, } for _, rt := range tests { t.Run(rt.name, func(t *testing.T) { equal := compareAuthzModes(rt.modesA, rt.modesB) if equal != rt.equal { t.Errorf(\"failed compareAuthzModes:nexpected:n%vnsaw:n%v\", rt.equal, equal) } }) } } "} {"_id":"doc-en-kubernetes-a74cefa1e4f6bf942b29c78cf08e2042cdeb961939e0482025f3be18ee017164","title":"","text":"} orphan := false switch { case options.OrphanDependents == nil && options.PropagationPolicy == nil && len(initialFinalizers) == 0: // if there are no deletion options, the default policy for replication controllers is orphan orphan = true case options.OrphanDependents != nil: // if the deletion options explicitly specify whether to orphan, that controls orphan = *options.OrphanDependents"} {"_id":"doc-en-kubernetes-7796e4e868d12b8dac23f6bb2aa5d2f75b725d17d4b79fceb31b0f7564685327","title":"","text":"return false } if c.spec.PersistentVolume == nil { klog.V(4).Info(log(\"mounter.SetupAt Warning: skipping fsGroup permission change, no access mode available. The volume may only be accessible to root users.\")) return false } if c.spec.PersistentVolume.Spec.AccessModes == nil { klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, access modes not provided\")) return false } if !hasReadWriteOnce(c.spec.PersistentVolume.Spec.AccessModes) { klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, only support ReadWriteOnce access mode\")) return false if c.spec.PersistentVolume != nil { if c.spec.PersistentVolume.Spec.AccessModes == nil { klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, access modes not provided\")) return false } if !hasReadWriteOnce(c.spec.PersistentVolume.Spec.AccessModes) { klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, only support ReadWriteOnce access mode\")) return false } return true } else if c.spec.Volume != nil && c.spec.Volume.CSI != nil { if !utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) { klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, CSIInlineVolume feature required\")) return false } // Inline CSI volumes are always mounted with RWO AccessMode by SetUpAt return true } return true klog.V(4).Info(log(\"mounter.SetupAt WARNING: skipping fsGroup, unsupported volume type\")) return false } // isDirMounted returns the !notMounted result from IsLikelyNotMountPoint check"} {"_id":"doc-en-kubernetes-5d01f74b56becb82999de9255cbc9018986c456e80249a10c04173a2dce5be73","title":"","text":"}, want: true, }, { name: \"driverPolicy is ReadWriteOnceWithFSTypeFSGroupPolicy with CSI inline volume\", args: args{ fsGroup: new(int64), fsType: \"ext4\", driverPolicy: storage.ReadWriteOnceWithFSTypeFSGroupPolicy, }, fields: fields{ spec: volume.NewSpecFromVolume(&api.Volume{ VolumeSource: api.VolumeSource{ CSI: &api.CSIVolumeSource{ Driver: testDriver, }, }, }), }, want: true, }, } for _, tt := range tests {"} {"_id":"doc-en-kubernetes-9ad2b94dd423b2efd4fe79e5579bf1305e37d9ca632b101538c901b1e54f23c0","title":"","text":"// The filter doesn't filter out any object. wc.internalPred = storage.Everything } wc.ctx, wc.cancel = context.WithCancel(ctx) // The etcd server waits until it cannot find a leader for 3 election // timeouts to cancel existing streams. 3 is currently a hard coded // constant. The election timeout defaults to 1000ms. If the cluster is // healthy, when the leader is stopped, the leadership transfer should be // smooth. (leader transfers its leadership before stopping). If leader is // hard killed, other servers will take an election timeout to realize // leader lost and start campaign. wc.ctx, wc.cancel = context.WithCancel(clientv3.WithRequireLeader(ctx)) return wc }"} {"_id":"doc-en-kubernetes-1ccfc80e0b081cc0cf9c875fba7f0d74eb4087c9fdff9ef280ce610c136ff907","title":"","text":"github.com/lpabon/godbc v0.1.1 // indirect github.com/magiconair/properties v1.8.1 // indirect github.com/miekg/dns v1.1.4 github.com/moby/ipvs v1.0.0 github.com/moby/ipvs v1.0.1 github.com/mohae/deepcopy v0.0.0-20170603005431-491d3605edfb // indirect github.com/mrunalp/fileutils v0.0.0-20171103030105-7d4729fb3618 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822"} {"_id":"doc-en-kubernetes-dc3ce2f4f6a44f3ca38a4d78b29784081cdded08f523e5f5678005a28936fe49","title":"","text":"github.com/mitchellh/go-homedir => github.com/mitchellh/go-homedir v1.1.0 github.com/mitchellh/go-wordwrap => github.com/mitchellh/go-wordwrap v1.0.0 github.com/mitchellh/mapstructure => github.com/mitchellh/mapstructure v1.1.2 github.com/moby/ipvs => github.com/moby/ipvs v1.0.0 github.com/moby/ipvs => github.com/moby/ipvs v1.0.1 github.com/moby/term => github.com/moby/term v0.0.0-20200312100748-672ec06f55cd github.com/modern-go/concurrent => github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd github.com/modern-go/reflect2 => github.com/modern-go/reflect2 v1.0.1"} {"_id":"doc-en-kubernetes-345e322320de4e47b74fe7f8008f597a6a146fab96df34ec1ced9ef7a63121cb","title":"","text":"github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/moby/ipvs v1.0.0 h1:89i8bPaL2DC0cjyRDv0QQOYUOU4fujziJmhF4ca/mtY= github.com/moby/ipvs v1.0.0/go.mod h1:2pngiyseZbIKXNv7hsKj3O9UEz30c53MT9005gt2hxQ= github.com/moby/ipvs v1.0.1 h1:aoZ7fhLTXgDbzVrAnvV+XbKOU8kOET7B3+xULDF/1o0= github.com/moby/ipvs v1.0.1/go.mod h1:2pngiyseZbIKXNv7hsKj3O9UEz30c53MT9005gt2hxQ= github.com/moby/term v0.0.0-20200312100748-672ec06f55cd h1:aY7OQNf2XqY/JQ6qREWamhI/81os/agb2BAGpcx5yWI= github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg="} {"_id":"doc-en-kubernetes-1d576da27c9f9c7e29e2ed2ffa3eb138ec8ca79ec8830501a4ded57944e187af","title":"","text":"import ( \"bytes\" \"encoding/binary\" \"errors\" \"fmt\" \"net\" \"os/exec\""} {"_id":"doc-en-kubernetes-088762625392e831043229df8cc7ddc19a57731973a999e29a8ea56200309ab9","title":"","text":"d.ActiveConnections = int(native.Uint16(attr.Value)) case ipvsDestAttrInactiveConnections: d.InactiveConnections = int(native.Uint16(attr.Value)) case ipvsSvcAttrStats: case ipvsDestAttrStats: stats, err := assembleStats(attr.Value) if err != nil { return nil, err"} {"_id":"doc-en-kubernetes-617dc18c6214ccf1c73aca99717164f5c8b6a63efe2fdcd5f5f7cba2445bd3d8","title":"","text":"} } // in older kernels (< 3.18), the destination address family attribute doesn't exist so we must // assume it based on the destination address provided. if d.AddressFamily == 0 { // we can't check the address family using net stdlib because netlink returns // IPv4 addresses as the first 4 bytes in a []byte of length 16 where as // stdlib expects it as the last 4 bytes. addressFamily, err := getIPFamily(addressBytes) if err != nil { return nil, err } d.AddressFamily = addressFamily } // parse Address after parse AddressFamily incase of parseIP error if addressBytes != nil { ip, err := parseIP(addressBytes, d.AddressFamily)"} {"_id":"doc-en-kubernetes-dc78efb19d60b5b98ebd6e1acdad26b77ee33f4872d537208c8ea5177a6168fe","title":"","text":"return &d, nil } // getIPFamily parses the IP family based on raw data from netlink. // For AF_INET, netlink will set the first 4 bytes with trailing zeros // 10.0.0.1 -> [10 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0] // For AF_INET6, the full 16 byte array is used: // 2001:db8:3c4d:15::1a00 -> [32 1 13 184 60 77 0 21 0 0 0 0 0 0 26 0] func getIPFamily(address []byte) (uint16, error) { if len(address) == 4 { return syscall.AF_INET, nil } if isZeros(address) { return 0, errors.New(\"could not parse IP family from address data\") } // assume IPv4 if first 4 bytes are non-zero but rest of the data is trailing zeros if !isZeros(address[:4]) && isZeros(address[4:]) { return syscall.AF_INET, nil } return syscall.AF_INET6, nil } func isZeros(b []byte) bool { for i := 0; i < len(b); i++ { if b[i] != 0 { return false } } return true } // parseDestination given a ipvs netlink response this function will respond with a valid destination entry, an error otherwise func (i *Handle) parseDestination(msg []byte) (*Destination, error) { var dst *Destination"} {"_id":"doc-en-kubernetes-1f0003a80eb8d40e21a5a2713bc6e3c7767d283d75e4c0479cb9017377b8e608","title":"","text":"github.com/mitchellh/go-wordwrap # github.com/mitchellh/mapstructure v1.1.2 => github.com/mitchellh/mapstructure v1.1.2 github.com/mitchellh/mapstructure # github.com/moby/ipvs v1.0.0 => github.com/moby/ipvs v1.0.0 # github.com/moby/ipvs v1.0.1 => github.com/moby/ipvs v1.0.1 github.com/moby/ipvs # github.com/moby/term v0.0.0-20200312100748-672ec06f55cd => github.com/moby/term v0.0.0-20200312100748-672ec06f55cd github.com/moby/term"} {"_id":"doc-en-kubernetes-356dc4630011b25fba960f82abc80be66fafcfbf0de4125bb3587bb3bba2400c","title":"","text":"expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 999, \"status\", \"num\") // .status.num should be 999 expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 10, \"spec\", \"num\") // .spec.num should remain 10 rv, found, err := unstructured.NestedString(patchedNoxuInstance.UnstructuredContent(), \"metadata\", \"resourceVersion\") if err != nil { t.Fatal(err) } if !found { t.Fatalf(\"metadata.resourceVersion not found\") } // this call waits for the resourceVersion to be reached in the cache before returning. // We need to do this because the patch gets its initial object from the storage, and the cache serves that. // If it is out of date, then our initial patch is applied to an old resource version, which conflicts // and then the updated object shows a conflicting diff, which permanently fails the patch. // This gives expected stability in the patch without retrying on an known number of conflicts below in the test. // See https://issue.k8s.io/42644 _, err = noxuResourceClient.Get(context.TODO(), \"foo\", metav1.GetOptions{ResourceVersion: patchedNoxuInstance.GetResourceVersion()}) if err != nil { t.Fatalf(\"unexpected error: %v\", err) } // no-op patch t.Logf(\"Patching .status.num again to 999\") patchedNoxuInstance, err = noxuResourceClient.Patch(context.TODO(), \"foo\", types.MergePatchType, patch, metav1.PatchOptions{}, \"status\") if err != nil { t.Fatalf(\"unexpected error: %v\", err) rv := \"\" found := false // TODO: remove this retry once http://issue.k8s.io/75564 is resolved, and expect the resourceVersion to remain unchanged 100% of the time. // server-side-apply incorrectly considers spec fields in patches submitted to /status when updating managedFields timestamps, so this patch is racy: // if it spans a 1-second boundary from the last write, server-side-apply updates the managedField timestamp and increments resourceVersion. for i := 0; i < 10; i++ { rv, found, err = unstructured.NestedString(patchedNoxuInstance.UnstructuredContent(), \"metadata\", \"resourceVersion\") if err != nil { t.Fatal(err) } if !found { t.Fatalf(\"metadata.resourceVersion not found\") } t.Logf(\"Patching .status.num again to 999\") patchedNoxuInstance, err = noxuResourceClient.Patch(context.TODO(), \"foo\", types.MergePatchType, patch, metav1.PatchOptions{}, \"status\") if err != nil { t.Fatalf(\"unexpected error: %v\", err) } // make sure no-op patch does not increment resourceVersion expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 999, \"status\", \"num\") expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 10, \"spec\", \"num\") if patchedNoxuInstance.GetResourceVersion() == rv { break } t.Logf(\"resource version changed - retrying\") } // make sure no-op patch does not increment resourceVersion expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 999, \"status\", \"num\") expectInt64(t, patchedNoxuInstance.UnstructuredContent(), 10, \"spec\", \"num\") expectString(t, patchedNoxuInstance.UnstructuredContent(), rv, \"metadata\", \"resourceVersion\") // empty patch"} {"_id":"doc-en-kubernetes-cd4457f6b671feda73e5e2cdc4a087cf278f5c01e11707af6f94509315745d80","title":"","text":"t.Fatalf(\"metadata.resourceVersion not found\") } // this call waits for the resourceVersion to be reached in the cache before returning. // We need to do this because the patch gets its initial object from the storage, and the cache serves that. // If it is out of date, then our initial patch is applied to an old resource version, which conflicts // and then the updated object shows a conflicting diff, which permanently fails the patch. // This gives expected stability in the patch without retrying on an known number of conflicts below in the test. // See https://issue.k8s.io/42644 _, err = noxuResourceClient.Get(context.TODO(), \"foo\", metav1.GetOptions{ResourceVersion: patchedNoxuInstance.GetResourceVersion()}) if err != nil { t.Fatalf(\"unexpected error: %v\", err) } // Scale.Spec.Replicas = 7 but Scale.Status.Replicas should remain 0 gottenScale, err := scaleClient.Scales(\"not-the-default\").Get(context.TODO(), groupResource, \"foo\", metav1.GetOptions{}) if err != nil {"} {"_id":"doc-en-kubernetes-4c896af5fccca3a9fdf1d05cc071bf67e75b2c8bdc2ea9018e9ae24b7d3a3665","title":"","text":"} ipvsModules := utilipvs.GetRequiredIPVSModules(kernelVersion) var bmods []string var bmods, lmods []string // Find out loaded kernel modules. If this is a full static kernel it will try to verify if the module is compiled using /boot/config-KERNELVERSION modulesFile, err := os.Open(\"/proc/modules\")"} {"_id":"doc-en-kubernetes-fc4efe2f62a88d19f09c2ccfe00684c5c875c97438010abd2d2ec2129a620eab","title":"","text":"if err != nil { klog.Warningf(\"Failed to load kernel module %v with modprobe. \"+ \"You can ignore this message when kube-proxy is running inside container without mounting /lib/modules\", module) } else { lmods = append(lmods, module) } } } return append(mods, bmods...), nil mods = append(mods, bmods...) mods = append(mods, lmods...) return mods, nil } // getFirstColumn reads all the content from r into memory and return a"} {"_id":"doc-en-kubernetes-1f90684377c82beb0dd160cdf3805c1df875c6800d28a3ff83fb9149e4002bb6","title":"","text":"if pod == nil { return fmt.Errorf(\"pod is missing, skipping (%s/%s)\", addr.TargetRef.Namespace, addr.TargetRef.Name) } if pod.Status.PodIPs[0].IP != addr.IP { return fmt.Errorf(\"pod ip doesn't match endpoint ip, skipping: %s vs %s (%s/%s)\", pod.Status.PodIPs[0].IP, addr.IP, addr.TargetRef.Namespace, addr.TargetRef.Name) for _, podIP := range pod.Status.PodIPs { if podIP.IP == addr.IP { return nil } } return nil return fmt.Errorf(\"pod ip(s) doesn't match endpoint ip, skipping: %v vs %s (%s/%s)\", pod.Status.PodIPs, addr.IP, addr.TargetRef.Namespace, addr.TargetRef.Name) } // This is O(N), but we expect haystack to be small;"} {"_id":"doc-en-kubernetes-6591a6b277a1bac32b5dc7502f839412d774357bf992ef79919987298c409675","title":"","text":"Ports: []api.EndpointPort{{Name: \"\", Port: 80}, {Name: \"p\", Port: 93}}, }}, }, { ObjectMeta: metav1.ObjectMeta{ Name: \"foo-second-ip\", Namespace: metav1.NamespaceDefault, }, Subsets: []api.EndpointSubset{{ Addresses: []api.EndpointAddress{{IP: \"2001:db7::\", TargetRef: &api.ObjectReference{Name: \"foo\", Namespace: metav1.NamespaceDefault}}}, Ports: []api.EndpointPort{{Name: \"\", Port: 80}, {Name: \"p\", Port: 93}}, }}, }, }, } pods := &api.PodList{"} {"_id":"doc-en-kubernetes-fa40065c31fef3820509500d6d6f4bfa1fd592bff76d3ae6e38e056766df7a60","title":"","text":"t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a simple id (using second ip). location, _, err = redirector.ResourceLocation(ctx, \"foo-second-ip\") if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if location == nil { t.Errorf(\"Unexpected nil: %v\", location) } if e, a := \"//[2001:db7::]:80\", location.String(); e != a { t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port. location, _, err = redirector.ResourceLocation(ctx, \"foo:p\") if err != nil {"} {"_id":"doc-en-kubernetes-138b9138cc77db8902d1378ab8d82f863dc213af269d3029527d1629a6ac977c","title":"","text":"t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port (using second ip). location, _, err = redirector.ResourceLocation(ctx, \"foo-second-ip:p\") if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if location == nil { t.Errorf(\"Unexpected nil: %v\", location) } if e, a := \"//[2001:db7::]:93\", location.String(); e != a { t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port number (service port 93 -> target port 80) location, _, err = redirector.ResourceLocation(ctx, \"foo:93\") if err != nil {"} {"_id":"doc-en-kubernetes-15ee9578c5501a1a2da13781e18f4dac32781e6f44501dad0ed154c085d73ac1","title":"","text":"t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port number (service port 93 -> target port 80, using second ip) location, _, err = redirector.ResourceLocation(ctx, \"foo-second-ip:93\") if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if location == nil { t.Errorf(\"Unexpected nil: %v\", location) } if e, a := \"//[2001:db7::]:80\", location.String(); e != a { t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port number (service port 9393 -> target port \"p\" -> endpoint port 93) location, _, err = redirector.ResourceLocation(ctx, \"foo:9393\") if err != nil {"} {"_id":"doc-en-kubernetes-b14f197a569766b2337e2c055418f4d4c09c8c3aabf9ee226239311a169cae21","title":"","text":"t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a name + port number (service port 9393 -> target port \"p\" -> endpoint port 93, using second ip) location, _, err = redirector.ResourceLocation(ctx, \"foo-second-ip:9393\") if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if location == nil { t.Errorf(\"Unexpected nil: %v\", location) } if e, a := \"//[2001:db7::]:93\", location.String(); e != a { t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a scheme + name + port. location, _, err = redirector.ResourceLocation(ctx, \"https:foo:p\") if err != nil {"} {"_id":"doc-en-kubernetes-26f615559dbc42d861515b8bf4e9b0adb6f2f5b335acbd422c395821516dfe34","title":"","text":"t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a scheme + name + port (using second ip). location, _, err = redirector.ResourceLocation(ctx, \"https:foo-second-ip:p\") if err != nil { t.Errorf(\"Unexpected error: %v\", err) } if location == nil { t.Errorf(\"Unexpected nil: %v\", location) } if e, a := \"https://[2001:db7::]:93\", location.String(); e != a { t.Errorf(\"Expected %v, but got %v\", e, a) } // Test a non-existent name + port. location, _, err = redirector.ResourceLocation(ctx, \"foo:q\") if err == nil { t.Errorf(\"Unexpected nil error\") } // Test a non-existent name + port (using second ip). location, _, err = redirector.ResourceLocation(ctx, \"foo-second-ip:q\") if err == nil { t.Errorf(\"Unexpected nil error\") } // Test error path if _, _, err = redirector.ResourceLocation(ctx, \"bar\"); err == nil { t.Errorf(\"unexpected nil error\")"} {"_id":"doc-en-kubernetes-97d25bcb5bcb02b65b6b05ad5491508b270f00875aeae81bb91a431d886a8dc3","title":"","text":"serviceHealthServer := healthcheck.NewServiceHealthServer(hostname, recorder) isIPv6 := ipt.IsIPv6() var incorrectAddresses []string nodePortAddresses, incorrectAddresses = utilproxy.FilterIncorrectCIDRVersion(nodePortAddresses, isIPv6) if len(incorrectAddresses) > 0 { klog.Warning(\"NodePortAddresses of wrong family; \", incorrectAddresses) } proxier := &Proxier{ portsMap: make(map[utilproxy.LocalPort]utilproxy.Closeable), serviceMap: make(proxy.ServiceMap),"} {"_id":"doc-en-kubernetes-f3b92121551ba3fdf7822de70b9c4114669295c0540f32d42d23f21b041f5df7","title":"","text":"nodePortAddresses []string, ) (proxy.Provider, error) { // Create an ipv4 instance of the single-stack proxier nodePortAddresses4, nodePortAddresses6 := utilproxy.FilterIncorrectCIDRVersion(nodePortAddresses, false) ipv4Proxier, err := NewProxier(ipt[0], sysctl, exec, syncPeriod, minSyncPeriod, masqueradeAll, masqueradeBit, localDetectors[0], hostname, nodeIP[0], recorder, healthzServer, nodePortAddresses) nodeIP[0], recorder, healthzServer, nodePortAddresses4) if err != nil { return nil, fmt.Errorf(\"unable to create ipv4 proxier: %v\", err) } ipv6Proxier, err := NewProxier(ipt[1], sysctl, exec, syncPeriod, minSyncPeriod, masqueradeAll, masqueradeBit, localDetectors[1], hostname, nodeIP[1], recorder, healthzServer, nodePortAddresses) nodeIP[1], recorder, healthzServer, nodePortAddresses6) if err != nil { return nil, fmt.Errorf(\"unable to create ipv6 proxier: %v\", err) }"} {"_id":"doc-en-kubernetes-432bd5b639184b08c0db0fff3ce866519f2b53caabbf5caebb96e18553f3d65f","title":"","text":"endpointSlicesEnabled := utilfeature.DefaultFeatureGate.Enabled(features.EndpointSliceProxying) var incorrectAddresses []string nodePortAddresses, incorrectAddresses = utilproxy.FilterIncorrectCIDRVersion(nodePortAddresses, isIPv6) if len(incorrectAddresses) > 0 { klog.Warning(\"NodePortAddresses of wrong family; \", incorrectAddresses) } proxier := &Proxier{ portsMap: make(map[utilproxy.LocalPort]utilproxy.Closeable), serviceMap: make(proxy.ServiceMap),"} {"_id":"doc-en-kubernetes-f46e339ea0ca663a58d8e41e07ebeb2212c9bcb0d18ca233ba4f4144261b88c1","title":"","text":"safeIpset := newSafeIpset(ipset) nodePortAddresses4, nodePortAddresses6 := utilproxy.FilterIncorrectCIDRVersion(nodePortAddresses, false) // Create an ipv4 instance of the single-stack proxier ipv4Proxier, err := NewProxier(ipt[0], ipvs, safeIpset, sysctl, exec, syncPeriod, minSyncPeriod, filterCIDRs(false, excludeCIDRs), strictARP, tcpTimeout, tcpFinTimeout, udpTimeout, masqueradeAll, masqueradeBit, localDetectors[0], hostname, nodeIP[0], recorder, healthzServer, scheduler, nodePortAddresses, kernelHandler) recorder, healthzServer, scheduler, nodePortAddresses4, kernelHandler) if err != nil { return nil, fmt.Errorf(\"unable to create ipv4 proxier: %v\", err) }"} {"_id":"doc-en-kubernetes-7e2c0253993eaa3db9ade0ba1d744ff780b65829006d75923c0afd95c19b1d77","title":"","text":"exec, syncPeriod, minSyncPeriod, filterCIDRs(true, excludeCIDRs), strictARP, tcpTimeout, tcpFinTimeout, udpTimeout, masqueradeAll, masqueradeBit, localDetectors[1], hostname, nodeIP[1], nil, nil, scheduler, nodePortAddresses, kernelHandler) nil, nil, scheduler, nodePortAddresses6, kernelHandler) if err != nil { return nil, fmt.Errorf(\"unable to create ipv6 proxier: %v\", err) }"} {"_id":"doc-en-kubernetes-6f69998e3894eca82a651eb706cbd65011151be54fae8e6e7ca99584df895786","title":"","text":"} func TestFailedParseParamsSummaryHandler(t *testing.T) { fw := newServerTest() defer fw.testHTTPServer.Close() resp, err := http.Post(fw.testHTTPServer.URL+\"/stats/summary\", \"invalid/content/type\", nil) assert.NoError(t, err) defer resp.Body.Close() v, err := ioutil.ReadAll(resp.Body) assert.NoError(t, err) assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) assert.Contains(t, string(v), \"parse form failed\") } func TestTrimURLPath(t *testing.T) { tests := []struct { path, expected string"} {"_id":"doc-en-kubernetes-5f00897bafe37025a7f727e570277102153195cf8de102fdfd2ce08a2859fd33","title":"","text":"\"//staging/src/k8s.io/component-base/metrics:go_default_library\", \"//vendor/github.com/emicklei/go-restful:go_default_library\", \"//vendor/github.com/google/cadvisor/info/v1:go_default_library\", \"//vendor/github.com/pkg/errors:go_default_library\", \"//vendor/k8s.io/klog:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-a4183fa66f98b6732082303e9c067fb3222a6ce06f424aa792ab7f109d5d10e3","title":"","text":"restful \"github.com/emicklei/go-restful\" cadvisorapi \"github.com/google/cadvisor/info/v1\" \"github.com/pkg/errors\" \"k8s.io/klog\" \"k8s.io/api/core/v1\""} {"_id":"doc-en-kubernetes-d5e11b6d776ba27758d557bf5a385539226d58ceb1166bfd256d021409372d6a","title":"","text":"// If \"only_cpu_and_memory\" GET param is true then only cpu and memory is returned in response. func (h *handler) handleSummary(request *restful.Request, response *restful.Response) { onlyCPUAndMemory := false request.Request.ParseForm() err := request.Request.ParseForm() if err != nil { handleError(response, \"/stats/summary\", errors.Wrapf(err, \"parse form failed\")) return } if onlyCluAndMemoryParam, found := request.Request.Form[\"only_cpu_and_memory\"]; found && len(onlyCluAndMemoryParam) == 1 && onlyCluAndMemoryParam[0] == \"true\" { onlyCPUAndMemory = true } var summary *statsapi.Summary var err error if onlyCPUAndMemory { summary, err = h.summaryProvider.GetCPUAndMemoryStats() } else {"} {"_id":"doc-en-kubernetes-6788643cdb8c2da8e5d764f34916e4fc553ac860a8daa53b012780a8d22188be","title":"","text":"} // NodeAddresses is an implementation of Instances.NodeAddresses. func (g *Cloud) NodeAddresses(_ context.Context, _ types.NodeName) ([]v1.NodeAddress, error) { internalIP, err := metadata.Get(\"instance/network-interfaces/0/ip\") if err != nil { return nil, fmt.Errorf(\"couldn't get internal IP: %v\", err) func (g *Cloud) NodeAddresses(ctx context.Context, nodeName types.NodeName) ([]v1.NodeAddress, error) { timeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour) defer cancel() instanceName := string(nodeName) if g.useMetadataServer { // Use metadata server if possible if g.isCurrentInstance(instanceName) { internalIP, err := metadata.Get(\"instance/network-interfaces/0/ip\") if err != nil { return nil, fmt.Errorf(\"couldn't get internal IP: %v\", err) } externalIP, err := metadata.Get(\"instance/network-interfaces/0/access-configs/0/external-ip\") if err != nil { return nil, fmt.Errorf(\"couldn't get external IP: %v\", err) } addresses := []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: internalIP}, {Type: v1.NodeExternalIP, Address: externalIP}, } if internalDNSFull, err := metadata.Get(\"instance/hostname\"); err != nil { klog.Warningf(\"couldn't get full internal DNS name: %v\", err) } else { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalDNS, Address: internalDNSFull}, v1.NodeAddress{Type: v1.NodeHostName, Address: internalDNSFull}, ) } return addresses, nil } } externalIP, err := metadata.Get(\"instance/network-interfaces/0/access-configs/0/external-ip\") // Use GCE API instanceObj, err := g.getInstanceByName(instanceName) if err != nil { return nil, fmt.Errorf(\"couldn't get external IP: %v\", err) } addresses := []v1.NodeAddress{ {Type: v1.NodeInternalIP, Address: internalIP}, {Type: v1.NodeExternalIP, Address: externalIP}, return nil, fmt.Errorf(\"couldn't get instance details: %v\", err) } if internalDNSFull, err := metadata.Get(\"instance/hostname\"); err != nil { klog.Warningf(\"couldn't get full internal DNS name: %v\", err) } else { addresses = append(addresses, v1.NodeAddress{Type: v1.NodeInternalDNS, Address: internalDNSFull}, v1.NodeAddress{Type: v1.NodeHostName, Address: internalDNSFull}, ) instance, err := g.c.Instances().Get(timeoutCtx, meta.ZonalKey(canonicalizeInstanceName(instanceObj.Name), instanceObj.Zone)) if err != nil { return []v1.NodeAddress{}, fmt.Errorf(\"error while querying for instance: %v\", err) } return addresses, nil return nodeAddressesFromInstance(instance) } // NodeAddressesByProviderID will not be called from the node that is requesting this ID."} {"_id":"doc-en-kubernetes-550997e0f425539405e80b82491173fd6e86af86359094262eb42622fefaba71","title":"","text":"if resp.Url == \"\" { errorMessage := \"URL is not set\" klog.Errorf(\"Exec failed: %s\", errorMessage) klog.Errorf(\"Attach failed: %s\", errorMessage) return nil, errors.New(errorMessage) } return resp, nil"} {"_id":"doc-en-kubernetes-0ff6b8285440a73c3251b7afb49d6927d214396e47a9169e8c8c6590c3ff8025","title":"","text":"if resp.Url == \"\" { errorMessage := \"URL is not set\" klog.Errorf(\"Exec failed: %s\", errorMessage) klog.Errorf(\"PortForward failed: %s\", errorMessage) return nil, errors.New(errorMessage) }"} {"_id":"doc-en-kubernetes-4b94ba4547dca7c3aa4efdbb7070c1a9b7eba2c5df9ec5344fedd661dc69a7cb","title":"","text":"} // InstancesV2 returns an implementation of InstancesV2 for Google Compute Engine. // TODO: implement ONLY for external cloud provider // Implement ONLY for external cloud provider func (g *Cloud) InstancesV2() (cloudprovider.InstancesV2, bool) { return nil, false return g, true } // Zones returns an implementation of Zones for Google Compute Engine."} {"_id":"doc-en-kubernetes-8e232d9139791edc46203c75ba51706770b97faac75d1833bcfa7efff54c8003","title":"","text":"return false, cloudprovider.NotImplemented } // InstanceShutdown returns true if the instance is in safe state to detach volumes func (g *Cloud) InstanceShutdown(ctx context.Context, node *v1.Node) (bool, error) { return false, cloudprovider.NotImplemented } func nodeAddressesFromInstance(instance *compute.Instance) ([]v1.NodeAddress, error) { if len(instance.NetworkInterfaces) < 1 { return nil, fmt.Errorf(\"could not find network interfaces for instanceID %q\", instance.Id)"} {"_id":"doc-en-kubernetes-91b3e86fb06525507b2ed0a78e323296398c8c3c0a11ae8c9d88ea8fea13ac6b","title":"","text":"return true, nil } // InstanceExists returns true if the instance with the given provider id still exists and is running. // If false is returned with no error, the instance will be immediately deleted by the cloud controller manager. func (g *Cloud) InstanceExists(ctx context.Context, node *v1.Node) (bool, error) { providerID := node.Spec.ProviderID if providerID == \"\" { var err error if providerID, err = g.InstanceID(ctx, types.NodeName(node.Name)); err != nil { return false, err } } return g.InstanceExistsByProviderID(ctx, providerID) } // InstanceMetadata returns metadata of the specified instance. func (g *Cloud) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) { timeoutCtx, cancel := context.WithTimeout(ctx, 1*time.Hour) defer cancel() providerID := node.Spec.ProviderID if providerID == \"\" { var err error if providerID, err = g.InstanceID(ctx, types.NodeName(node.Name)); err != nil { return nil, err } } _, zone, name, err := splitProviderID(providerID) if err != nil { return nil, err } region, err := GetGCERegion(zone) if err != nil { return nil, err } instance, err := g.c.Instances().Get(timeoutCtx, meta.ZonalKey(canonicalizeInstanceName(name), zone)) if err != nil { return nil, fmt.Errorf(\"error while querying for providerID %q: %v\", providerID, err) } addresses, err := nodeAddressesFromInstance(instance) if err != nil { return nil, err } return &cloudprovider.InstanceMetadata{ ProviderID: providerID, InstanceType: lastComponent(instance.MachineType), NodeAddresses: addresses, Zone: zone, Region: region, }, nil } // InstanceID returns the cloud provider ID of the node with the specified NodeName. func (g *Cloud) InstanceID(ctx context.Context, nodeName types.NodeName) (string, error) { instanceName := mapNodeNameToInstanceName(nodeName)"} {"_id":"doc-en-kubernetes-20a389ba3b8c9c1cb5e121550069c64e18c42b6bb4218a3a9df19f498762b0a4","title":"","text":"software-properties-common lsb-release # focal repo for docker is not yet available, so we use bonic for now # https://github.com/kubernetes/kubernetes/issues/90709 release=$(lsb_release -cs) if [ \"$release\" == \"focal\" ]; then release=\"bionic\"; fi # Add the Docker apt-repository curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\")/gpg "} {"_id":"doc-en-kubernetes-b0e347704310d67990484f92a876559dc02e306998ca4e565949e0b8470fdc7d","title":"","text":"software-properties-common lsb-release # focal repo for docker is not yet available, so we use bonic for now # https://github.com/kubernetes/kubernetes/issues/90709 release=$(lsb_release -cs) if [ \"$release\" == \"focal\" ]; then release=\"bionic\"; fi # Add the Docker apt-repository (as we install containerd from there) curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\")/gpg "} {"_id":"doc-en-kubernetes-1e958a7b075eadc835e016aac39a404a4eaa137e73ffb59522570229bfd4e176","title":"","text":"// checkExternalServiceReachability ensures service of type externalName resolves to IP address and no fake externalName is set // FQDN of kubernetes is used as externalName(for air tight platforms). func (j *TestJig) checkExternalServiceReachability(svc *v1.Service, pod *v1.Pod) error { // NOTE(claudiub): Windows does not support PQDN. svcName := fmt.Sprintf(\"%s.%s.svc.%s\", svc.Name, svc.Namespace, framework.TestContext.ClusterDNSDomain) // Service must resolve to IP cmd := fmt.Sprintf(\"nslookup %s\", svc.Name) _, err := framework.RunHostCmd(pod.Namespace, pod.Name, cmd) if err != nil { cmd := fmt.Sprintf(\"nslookup %s\", svcName) _, stderr, err := framework.RunHostCmdWithFullOutput(pod.Namespace, pod.Name, cmd) // NOTE(claudiub): nslookup may return 0 on Windows, even though the DNS name was not found. In this case, // we can check stderr for the error. if err != nil || (framework.NodeOSDistroIs(\"windows\") && strings.Contains(stderr, fmt.Sprintf(\"can't find %s\", svcName))) { return fmt.Errorf(\"ExternalName service %q must resolve to IP\", pod.Namespace+\"/\"+pod.Name) } return nil"} {"_id":"doc-en-kubernetes-2b840fe46c817501871ad995d2a217131d67ceb8c3cb750c648d12faacc7a72a","title":"","text":"// Exec runs the kubectl executable. func (b KubectlBuilder) Exec() (string, error) { stdout, _, err := b.ExecWithFullOutput() return stdout, err } // ExecWithFullOutput runs the kubectl executable, and returns the stdout and stderr. func (b KubectlBuilder) ExecWithFullOutput() (string, string, error) { var stdout, stderr bytes.Buffer cmd := b.cmd cmd.Stdout, cmd.Stderr = &stdout, &stderr Logf(\"Running '%s %s'\", cmd.Path, strings.Join(cmd.Args[1:], \" \")) // skip arg[0] as it is printed separately if err := cmd.Start(); err != nil { return \"\", fmt.Errorf(\"error starting %v:nCommand stdout:n%vnstderr:n%vnerror:n%v\", cmd, cmd.Stdout, cmd.Stderr, err) return \"\", \"\", fmt.Errorf(\"error starting %v:nCommand stdout:n%vnstderr:n%vnerror:n%v\", cmd, cmd.Stdout, cmd.Stderr, err) } errCh := make(chan error, 1) go func() {"} {"_id":"doc-en-kubernetes-b0b9f512af0040a6a83449b0004e96e16a3f1d216d08c0b720b72c0c1b400f3b","title":"","text":"rc = int(ee.Sys().(syscall.WaitStatus).ExitStatus()) Logf(\"rc: %d\", rc) } return stdout.String(), uexec.CodeExitError{ return stdout.String(), stderr.String(), uexec.CodeExitError{ Err: fmt.Errorf(\"error running %v:nCommand stdout:n%vnstderr:n%vnerror:n%v\", cmd, cmd.Stdout, cmd.Stderr, err), Code: rc, } } case <-b.timeout: b.cmd.Process.Kill() return \"\", fmt.Errorf(\"timed out waiting for command %v:nCommand stdout:n%vnstderr:n%v\", cmd, cmd.Stdout, cmd.Stderr) return \"\", \"\", fmt.Errorf(\"timed out waiting for command %v:nCommand stdout:n%vnstderr:n%v\", cmd, cmd.Stdout, cmd.Stderr) } Logf(\"stderr: %q\", stderr.String()) Logf(\"stdout: %q\", stdout.String()) return stdout.String(), nil return stdout.String(), stderr.String(), nil } // RunKubectlOrDie is a convenience wrapper over kubectlBuilder"} {"_id":"doc-en-kubernetes-f603911ee3577db3800e65bd9140d03352fa1cb2e3ec4ec188e8c0f6002d6d33","title":"","text":"return NewKubectlCommand(namespace, args...).Exec() } // RunKubectlWithFullOutput is a convenience wrapper over kubectlBuilder // It will also return the command's stderr. func RunKubectlWithFullOutput(namespace string, args ...string) (string, string, error) { return NewKubectlCommand(namespace, args...).ExecWithFullOutput() } // RunKubectlOrDieInput is a convenience wrapper over kubectlBuilder that takes input to stdin func RunKubectlOrDieInput(namespace string, data string, args ...string) string { return NewKubectlCommand(namespace, args...).WithStdinData(data).ExecOrDie(namespace)"} {"_id":"doc-en-kubernetes-0ac7f1f1d6d48bab851e4846f10b99fa1fe061ea8c26b8d8587cd5f96ffb2076","title":"","text":"return RunKubectl(ns, \"exec\", fmt.Sprintf(\"--namespace=%v\", ns), name, \"--\", \"/bin/sh\", \"-x\", \"-c\", cmd) } // RunHostCmdWithFullOutput runs the given cmd in the context of the given pod using `kubectl exec` // inside of a shell. It will also return the command's stderr. func RunHostCmdWithFullOutput(ns, name, cmd string) (string, string, error) { return RunKubectlWithFullOutput(ns, \"exec\", fmt.Sprintf(\"--namespace=%v\", ns), name, \"--\", \"/bin/sh\", \"-x\", \"-c\", cmd) } // RunHostCmdOrDie calls RunHostCmd and dies on error. func RunHostCmdOrDie(ns, name, cmd string) string { stdout, err := RunHostCmd(ns, name, cmd)"} {"_id":"doc-en-kubernetes-b74956458e46d4ebfbf6fb2aa4284224e299b042bbf1864b773f3c4c32160a0e","title":"","text":"parameters[k] = v.(string) } } if snapshotProvider, ok := snapshotClass.Object[\"driver\"]; ok { snapshotter = snapshotProvider.(string) } case d.SnapshotClass.FromFile != \"\": snapshotClass, err := loadSnapshotClass(d.SnapshotClass.FromFile) framework.ExpectNoError(err, \"load snapshot class from %s\", d.SnapshotClass.FromFile)"} {"_id":"doc-en-kubernetes-30bcfced3d39e0cc43e96b72eed597f0d92f9e0d9c06080904cfd3761abeba92","title":"","text":"parameters[k] = v.(string) } } if snapshotProvider, ok := snapshotClass.Object[\"driver\"]; ok { snapshotter = snapshotProvider.(string) } } return testsuites.GetSnapshotClass(snapshotter, parameters, ns, suffix)"} {"_id":"doc-en-kubernetes-b96e4f968af447dd4eb95bb75d6d9da9829a7be9940e48b8082758adb1d57880","title":"","text":"\"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/apimachinery/pkg/watch\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/dynamic\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/client-go/rest\" restclient \"k8s.io/client-go/rest\""} {"_id":"doc-en-kubernetes-5a106c8e32a280f7468550ecb2af7ee25d74dce05651c5597b693c077086f033","title":"","text":"} return false } // WatchEventSequenceVerifier ... // manages a watch for a given resource, ensures that events take place in a given order, retries the test on failure // testContext cancelation signal across API boundries, e.g: context.TODO() // dc sets up a client to the API // resourceType specify the type of resource // namespace select a namespace // resourceName the name of the given resource // listOptions options used to find the resource, recommended to use listOptions.labelSelector // expectedWatchEvents array of events which are expected to occur // scenario the function to run func WatchEventSequenceVerifier(testContext context.Context, dc dynamic.Interface, resourceType schema.GroupVersionResource, namespace string, resourceName string, listOptions metav1.ListOptions, expectedWatchEvents []watch.Event, scenario func(*watchtools.RetryWatcher) []watch.Event) { listWatcher := &cache.ListWatch{ WatchFunc: func(listOptions metav1.ListOptions) (watch.Interface, error) { return dc.Resource(resourceType).Namespace(namespace).Watch(testContext, listOptions) }, } resourceWatch, err := watchtools.NewRetryWatcher(\"1\", listWatcher) ExpectNoError(err, \"Failed to create a resource watch of %v in namespace %v\", resourceType.Resource, namespace) // NOTE value of 3 retries seems to make sense retries := 3 retriesLoop: for try := 1; try <= retries; try++ { // NOTE the test may need access to the events to see what's going on, such as a change in status actualWatchEvents := scenario(resourceWatch) errs := sets.NewString() // watchEventsLoop: totalValidWatchEvents := 0 actualWatchEventsHasDelete := false for watchEventIndex := range expectedWatchEvents { foundExpectedWatchEvent := false ExpectEqual(len(expectedWatchEvents) <= len(actualWatchEvents), true, \"Error: actual watch events amount must be greater than or equal to expected watch events amount\") for actualWatchEventIndex := range actualWatchEvents { if actualWatchEvents[watchEventIndex].Type == expectedWatchEvents[actualWatchEventIndex].Type { foundExpectedWatchEvent = true } if actualWatchEvents[actualWatchEventIndex].Type == watch.Deleted && actualWatchEventsHasDelete != true { actualWatchEventsHasDelete = true } } if foundExpectedWatchEvent == false { errs.Insert(fmt.Sprintf(\"Watch event %v not found\", expectedWatchEvents[watchEventIndex].Type)) } totalValidWatchEvents++ } if actualWatchEventsHasDelete == false { _ = dc.Resource(resourceType).Namespace(namespace).DeleteCollection(testContext, metav1.DeleteOptions{}, listOptions) } // TODO restructure failures handling if errs.Len() > 0 && try < retries { fmt.Println(fmt.Errorf(\"invariants violated:n* %s\", strings.Join(errs.List(), \"n* \"))) continue retriesLoop } ExpectEqual(errs.Len() > 0, false, fmt.Errorf(\"invariants violated:n* %s\", strings.Join(errs.List(), \"n* \"))) ExpectEqual(totalValidWatchEvents, len(expectedWatchEvents), \"Error: there must be an equal amount of total valid watch events (%v) and expected watch events (%v)\", totalValidWatchEvents, len(expectedWatchEvents)) } } "} {"_id":"doc-en-kubernetes-59034e49b7eaf1b05febc6724155e6838a183334eb05cee23896bb0778b2d7ad","title":"","text":"namespace quota. The creation MUST fail release: v1.15 file: test/e2e/apps/rc.go - testname: Replication Controller, lifecycle codename: '[sig-apps] ReplicationController should test the lifecycle of a ReplicationController [Conformance]' description: A Replication Controller (RC) is created, read, patched, and deleted with verification. release: v1.20 file: test/e2e/apps/rc.go - testname: StatefulSet, Burst Scaling codename: '[sig-apps] StatefulSet [k8s.io] Basic StatefulSet functionality [StatefulSetBasic] Burst scaling should run to completion even with unhealthy pods [Slow] [Conformance]'"} {"_id":"doc-en-kubernetes-a0cd06e09067dfe599c3ed5eba73f13d6ea7f47b8b3a3e6494815635b9278124","title":"","text":"testRCReleaseControlledNotMatching(f) }) ginkgo.It(\"[Flaky] should test the lifecycle of a ReplicationController\", func() { /* Release: v1.20 Testname: Replication Controller, lifecycle Description: A Replication Controller (RC) is created, read, patched, and deleted with verification. */ framework.ConformanceIt(\"should test the lifecycle of a ReplicationController\", func() { testRcName := \"rc-test\" testRcNamespace := ns testRcInitialReplicaCount := int32(1)"} {"_id":"doc-en-kubernetes-62f462e726fb569bc1840288be251f0dd5746735030d4e995cdc31ace3d11a70","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/kubernetes/test/e2e/framework\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"time\" \"github.com/onsi/ginkgo\" ) const ( podTemplateRetryPeriod = 1 * time.Second podTemplateRetryTimeout = 1 * time.Minute ) var _ = ginkgo.Describe(\"[sig-node] PodTemplates\", func() { f := framework.NewDefaultFramework(\"podtemplate\") /*"} {"_id":"doc-en-kubernetes-356102b882650596ce983ccbc33682e27b6b5bb27c25292f20ae26590e08e44a","title":"","text":"framework.ExpectNoError(err, \"failed to list PodTemplate\") framework.ExpectEqual(len(podTemplateList.Items), 0, \"PodTemplate list returned items, failed to delete PodTemplate\") }) ginkgo.It(\"should delete a collection of pod templates\", func() { podTemplateNames := []string{\"test-podtemplate-1\", \"test-podtemplate-2\", \"test-podtemplate-3\"} ginkgo.By(\"Create set of pod templates\") // create a set of pod templates in test namespace for _, podTemplateName := range podTemplateNames { _, err := f.ClientSet.CoreV1().PodTemplates(f.Namespace.Name).Create(context.TODO(), &v1.PodTemplate{ ObjectMeta: metav1.ObjectMeta{ Name: podTemplateName, Labels: map[string]string{\"podtemplate-set\": \"true\"}, }, Template: v1.PodTemplateSpec{ Spec: v1.PodSpec{ Containers: []v1.Container{ {Name: \"token-test\", Image: imageutils.GetE2EImage(imageutils.Agnhost)}, }, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"failed to create pod template\") framework.Logf(\"created %v\", podTemplateName) } ginkgo.By(\"get a list of pod templates with a label in the current namespace\") // get a list of pod templates podTemplateList, err := f.ClientSet.CoreV1().PodTemplates(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{ LabelSelector: \"podtemplate-set=true\", }) framework.ExpectNoError(err, \"failed to get a list of pod templates\") framework.ExpectEqual(len(podTemplateList.Items), len(podTemplateNames), \"looking for expected number of pod templates\") ginkgo.By(\"delete collection of pod templates\") // delete collection framework.Logf(\"requesting DeleteCollection of pod templates\") err = f.ClientSet.CoreV1().PodTemplates(f.Namespace.Name).DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{ LabelSelector: \"podtemplate-set=true\"}) framework.ExpectNoError(err, \"failed to delete all pod templates\") ginkgo.By(\"check that the list of pod templates matches the requested quantity\") err = wait.PollImmediate(podTemplateRetryPeriod, podTemplateRetryTimeout, checkPodTemplateListQuantity(f, \"podtemplate-set=true\", 0)) framework.ExpectNoError(err, \"failed to count required pod templates\") }) }) func checkPodTemplateListQuantity(f *framework.Framework, label string, quantity int) func() (bool, error) { return func() (bool, error) { var err error framework.Logf(\"requesting list of pod templates to confirm quantity\") list, err := f.ClientSet.CoreV1().PodTemplates(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{ LabelSelector: label}) if err != nil { return false, err } if len(list.Items) != quantity { return false, err } return true, nil } } "} {"_id":"doc-en-kubernetes-f37f83ec6a899b2dd5c8cb7c8dd2272a5ac07d3eee138488b83ca7439925ef02","title":"","text":"visible at runtime in the container. release: v1.9 file: test/e2e/common/downward_api.go - testname: PodTemplate, delete a collection codename: '[sig-node] PodTemplates should delete a collection of pod templates [Conformance]' description: A set of Pod Templates is created with a label selector which MUST be found when listed. The set of Pod Templates is deleted and MUST NOT show up when listed by its label selector. release: v1.19 file: test/e2e/common/podtemplates.go - testname: PodTemplate lifecycle codename: '[sig-node] PodTemplates should run the lifecycle of PodTemplates [Conformance]' description: Attempt to create a PodTemplate. Patch the created PodTemplate. Fetching"} {"_id":"doc-en-kubernetes-6403eb354ae5c715296a40feb766aadf60e44b8f09739f6a7621ead4eb1d148a","title":"","text":"framework.ExpectEqual(len(podTemplateList.Items), 0, \"PodTemplate list returned items, failed to delete PodTemplate\") }) ginkgo.It(\"should delete a collection of pod templates\", func() { /* Release : v1.19 Testname: PodTemplate, delete a collection Description: A set of Pod Templates is created with a label selector which MUST be found when listed. The set of Pod Templates is deleted and MUST NOT show up when listed by its label selector. */ framework.ConformanceIt(\"should delete a collection of pod templates\", func() { podTemplateNames := []string{\"test-podtemplate-1\", \"test-podtemplate-2\", \"test-podtemplate-3\"} ginkgo.By(\"Create set of pod templates\")"} {"_id":"doc-en-kubernetes-9510fe71d587208500318c688c2035c7434894a18733545e599786eb102f088c","title":"","text":") nodeAuthorizer := node.NewAuthorizer(graph, nodeidentifier.NewDefaultNodeIdentifier(), bootstrappolicy.NodeRules()) authorizers = append(authorizers, nodeAuthorizer) ruleResolvers = append(ruleResolvers, nodeAuthorizer) case modes.ModeAlwaysAllow: alwaysAllowAuthorizer := authorizerfactory.NewAlwaysAllowAuthorizer()"} {"_id":"doc-en-kubernetes-6dd48698c979516bee1763ccd81d85891bb24febe40bf49a6c1c171f62f27638","title":"","text":"\"//staging/src/k8s.io/api/rbac/v1:go_default_library\", \"//staging/src/k8s.io/api/storage/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/runtime/schema:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/authentication/user:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/util/feature:go_default_library\", \"//staging/src/k8s.io/client-go/informers/core/v1:go_default_library\","} {"_id":"doc-en-kubernetes-d2e180ae3b7c32aef8c283c23f4c331f9e1f3adce850a64b85b8ed57217ef217","title":"","text":"g := NewGraph() g.destinationEdgeThreshold = 3 a := NewAuthorizer(g, nil, nil).(*NodeAuthorizer) a := NewAuthorizer(g, nil, nil) addPod := func(podNumber, nodeNumber int) { t.Helper()"} {"_id":"doc-en-kubernetes-5505b56f50aa3c5899f56aed49199193418f4155c17e7d5b156d9cdc4027798b","title":"","text":"rbacv1 \"k8s.io/api/rbac/v1\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apiserver/pkg/authentication/user\" \"k8s.io/apiserver/pkg/authorization/authorizer\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/component-base/featuregate\""} {"_id":"doc-en-kubernetes-522dab9645363a9dafc70c97011aa0898118529a1c27d0bdd57ecd9356ddcbaf","title":"","text":"features featuregate.FeatureGate } var _ = authorizer.Authorizer(&NodeAuthorizer{}) var _ = authorizer.RuleResolver(&NodeAuthorizer{}) // NewAuthorizer returns a new node authorizer func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) authorizer.Authorizer { func NewAuthorizer(graph *Graph, identifier nodeidentifier.NodeIdentifier, rules []rbacv1.PolicyRule) *NodeAuthorizer { return &NodeAuthorizer{ graph: graph, identifier: identifier,"} {"_id":"doc-en-kubernetes-a3403fda74512aefac8beeebc75874af9c920f3fed97a329f72ff3443bb87707","title":"","text":"csiNodeResource = storageapi.Resource(\"csinodes\") ) func (r *NodeAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) { if _, isNode := r.identifier.NodeIdentity(user); isNode { // indicate nodes do not have fully enumerated permissions return nil, nil, true, fmt.Errorf(\"node authorizer does not support user rule resolution\") } return nil, nil, false, nil } func (r *NodeAuthorizer) Authorize(ctx context.Context, attrs authorizer.Attributes) (authorizer.Decision, string, error) { nodeName, isNode := r.identifier.NodeIdentity(attrs.GetUser()) if !isNode {"} {"_id":"doc-en-kubernetes-4a16f662cb868954828338932a1500faf8925f42ace928ccfdacf01652aa15cd","title":"","text":"populate(g, nodes, pods, pvs, attachments) identifier := nodeidentifier.NewDefaultNodeIdentifier() authz := NewAuthorizer(g, identifier, bootstrappolicy.NodeRules()).(*NodeAuthorizer) authz := NewAuthorizer(g, identifier, bootstrappolicy.NodeRules()) node0 := &user.DefaultInfo{Name: \"system:node:node0\", Groups: []string{\"system:nodes\"}}"} {"_id":"doc-en-kubernetes-e8374111276a935b38c3fc60add6a875398874ef344837586b65935899ff9058","title":"","text":"// Config contains the configuration for a given Cache. type Config struct { // Maximum size of the history cached in memory. // // DEPRECATED: Cache capacity is dynamic and this field is no longer used. CacheCapacity int // An underlying storage.Interface."} {"_id":"doc-en-kubernetes-ccff131d2e5e0c9a586f8b4bbb0b6a007c2fbeda30589f6b382b1255fb777c79","title":"","text":"} watchCache := newWatchCache( config.KeyFunc, cacher.processEvent, config.GetAttrsFunc, config.Versioner, config.Indexers, objType) config.CacheCapacity, config.KeyFunc, cacher.processEvent, config.GetAttrsFunc, config.Versioner, config.Indexers, objType) listerWatcher := NewCacherListerWatcher(config.Storage, config.ResourcePrefix, config.NewListFunc) reflectorName := \"storage/cacher.go:\" + config.ResourcePrefix"} {"_id":"doc-en-kubernetes-4545529630ec66192a4edc10300c92322ce2f9e9b452cedee87a30f4b729c6bd","title":"","text":"} func newWatchCache( capacity int, keyFunc func(runtime.Object) (string, error), eventHandler func(*watchCacheEvent), getAttrsFunc func(runtime.Object) (labels.Set, fields.Set, error),"} {"_id":"doc-en-kubernetes-9ef6679d1daa2893360e5550753a61c5d54ec51e18e524bb41f3d5736a6926b1","title":"","text":"indexers *cache.Indexers, objectType reflect.Type) *watchCache { wc := &watchCache{ capacity: defaultLowerBoundCapacity, keyFunc: keyFunc, getAttrsFunc: getAttrsFunc, cache: make([]*watchCacheEvent, defaultLowerBoundCapacity), lowerBoundCapacity: defaultLowerBoundCapacity, upperBoundCapacity: defaultUpperBoundCapacity, capacity: capacity, keyFunc: keyFunc, getAttrsFunc: getAttrsFunc, cache: make([]*watchCacheEvent, capacity), // TODO get rid of them once we stop passing capacity as a parameter to watch cache. lowerBoundCapacity: min(capacity, defaultLowerBoundCapacity), upperBoundCapacity: max(capacity, defaultUpperBoundCapacity), startIndex: 0, endIndex: 0, store: cache.NewIndexer(storeElementKey, storeElementIndexers(indexers)),"} {"_id":"doc-en-kubernetes-e15b4a0ed4d032e647ded8cdd337d88d74aa17347f6661faef455073ececbd87","title":"","text":"} versioner := etcd3.APIObjectVersioner{} mockHandler := func(*watchCacheEvent) {} wc := newWatchCache(keyFunc, mockHandler, getAttrsFunc, versioner, indexers, reflect.TypeOf(&example.Pod{})) // To preserve behavior of tests that assume a given capacity, // resize it to th expected size. wc.capacity = capacity wc.cache = make([]*watchCacheEvent, capacity) wc.lowerBoundCapacity = min(capacity, defaultLowerBoundCapacity) wc.upperBoundCapacity = max(capacity, defaultUpperBoundCapacity) wc := newWatchCache(capacity, keyFunc, mockHandler, getAttrsFunc, versioner, indexers, reflect.TypeOf(&example.Pod{})) wc.clock = clock.NewFakeClock(time.Now()) return wc }"} {"_id":"doc-en-kubernetes-3c683dee1941de3899032ba9f206486973c78cec7274a0e54d91a77addab2d65","title":"","text":"ip = v.IP } if ip.IsLoopback() || ip.IsLinkLocalUnicast() { break continue } successTest := test{ nodeIP: ip.String(),"} {"_id":"doc-en-kubernetes-c16d1f93c395ffd5fb2a3adea2cd1a314e628fd2857a3684fefe2296ed65f600","title":"","text":"// Thus we customize buckets significantly, to empower both usecases. Buckets: []float64{0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 40, 50, 60}, StabilityLevel: compbasemetrics.ALPHA, StabilityLevel: compbasemetrics.STABLE, }, []string{\"verb\", \"dry_run\", \"group\", \"version\", \"resource\", \"subresource\", \"scope\", \"component\"}, )"} {"_id":"doc-en-kubernetes-33dbc9d27ed5ba1759e2633d10bf0928159a2da0c87e2fb798d0cb79d53f0e55","title":"","text":" - name: apiserver_request_duration_seconds help: Response latency distribution in seconds for each verb, dry run value, group, version, resource, subresource, scope and component. type: Histogram stabilityLevel: STABLE labels: - component - dry_run - group - resource - scope - subresource - verb - version buckets: - 0.05 - 0.1 - 0.15 - 0.2 - 0.25 - 0.3 - 0.35 - 0.4 - 0.45 - 0.5 - 0.6 - 0.7 - 0.8 - 0.9 - 1 - 1.25 - 1.5 - 1.75 - 2 - 2.5 - 3 - 3.5 - 4 - 4.5 - 5 - 6 - 7 - 8 - 9 - 10 - 15 - 20 - 25 - 30 - 40 - 50 - 60 - name: apiserver_request_total help: Counter of apiserver requests broken out for each verb, dry run value, group, version, resource, scope, component, and HTTP response code."} {"_id":"doc-en-kubernetes-513f6615cb49f335aa2da555f1535bf67617714b7ed4858716156b13cf3e7da2","title":"","text":"// We want the IPs to end up in order by interface (in particular, we want eth0's // IPs first), but macs isn't necessarily sorted in that order so we have to // explicitly order by device-number (device-number == the \"0\" in \"eth0\"). macIPs := make(map[int]string) var macIDs []string macDevNum := make(map[string]int) for _, macID := range strings.Split(macs, \"n\") { if macID == \"\" { continue"} {"_id":"doc-en-kubernetes-904450e3b077486957f66ed4929b99957de575e2696e32d70ab0de40b3fa10d2","title":"","text":"klog.Warningf(\"Bad device-number %q for interface %sn\", numStr, macID) continue } macIDs = append(macIDs, macID) macDevNum[macID] = num } // Sort macIDs by interface device-number sort.Slice(macIDs, func(i, j int) bool { return macDevNum[macIDs[i]] < macDevNum[macIDs[j]] }) for _, macID := range macIDs { ipPath := path.Join(\"network/interfaces/macs/\", macID, \"local-ipv4s\") macIPs[num], err = c.metadata.GetMetadata(ipPath) internalIPs, err := c.metadata.GetMetadata(ipPath) if err != nil { return nil, fmt.Errorf(\"error querying AWS metadata for %q: %q\", ipPath, err) } } for i := 0; i < len(macIPs); i++ { internalIPs := macIPs[i] if internalIPs == \"\" { continue } for _, internalIP := range strings.Split(internalIPs, \"n\") { if internalIP == \"\" { continue"} {"_id":"doc-en-kubernetes-1806c167b241e0043f5b6f037c176bbb1332504746fe961d92121f3e51eab620","title":"","text":"if len(keySplit) == 5 && keySplit[4] == \"device-number\" { for i, macElem := range m.aws.networkInterfacesMacs { if macParam == macElem { return fmt.Sprintf(\"%dn\", i), nil n := i if n > 0 { // Introduce an artificial gap, just to test eg: [eth0, eth2] n++ } return fmt.Sprintf(\"%dn\", n), nil } } }"} {"_id":"doc-en-kubernetes-dd355ddd3d69e449ddd0a4d3afbbfe07d8eea5892742bab62c37e3bde4af83c1","title":"","text":"} type BindPlugin struct { name string numBindCalled int PluginName string bindStatus *framework.Status client clientset.Interface pluginInvokeEventChan chan pluginInvokeEvent"} {"_id":"doc-en-kubernetes-58866dc7f0bdf9a6c212c9943aab540f6065ebf35d4bd5dd3d12b8312cd13330","title":"","text":"const bindPluginAnnotation = \"bindPluginName\" func (bp *BindPlugin) Name() string { return bp.PluginName return bp.name } func (bp *BindPlugin) Bind(ctx context.Context, state *framework.CycleState, p *v1.Pod, nodeName string) *framework.Status {"} {"_id":"doc-en-kubernetes-565433d1990f3760d8c137a0b96330a90987f7fe80c547a651bc4d7e238553f2","title":"","text":"} } // // TestUnreserveReservePlugin tests invocation of the Unreserve operation in // // reserve plugins through failures in execution points such as pre-bind. Also // // tests that the order of invocation of Unreserve operation is executed in the // // reverse order of invocation of the Reserve operation. // func TestReservePluginUnreserve(t *testing.T) { // \ttests := []struct { // \t\tname string // \t\tfailReserve bool // \t\tfailReserveIndex int // \t\tfailPreBind bool // \t}{ // \t\t{ // \t\t\tname: \"fail reserve\", // \t\t\tfailReserve: true, // \t\t\tfailReserveIndex: 1, // \t\t}, // \t\t{ // \t\t\tname: \"fail preBind\", // \t\t\tfailPreBind: true, // \t\t}, // \t\t{ // \t\t\tname: \"pass everything\", // \t\t}, // \t} // \tfor _, test := range tests { // \t\tt.Run(test.name, func(t *testing.T) { // \t\t\tnumReservePlugins := 3 // \t\t\tpluginInvokeEventChan := make(chan pluginInvokeEvent, numReservePlugins) // \t\t\tpreBindPlugin := &PreBindPlugin{ // \t\t\t\tfailPreBind: true, // \t\t\t} // \t\t\tvar reservePlugins []*ReservePlugin // \t\t\tfor i := 0; i < numReservePlugins; i++ { // \t\t\t\treservePlugins = append(reservePlugins, &ReservePlugin{ // \t\t\t\t\tname: fmt.Sprintf(\"%s-%d\", reservePluginName, i), // \t\t\t\t\tpluginInvokeEventChan: pluginInvokeEventChan, // \t\t\t\t}) // \t\t\t} // \t\t\tregistry := frameworkruntime.Registry{ // \t\t\t\t// TODO(#92229): test more failure points that would trigger Unreserve in // \t\t\t\t// reserve plugins than just one pre-bind plugin. // \t\t\t\tpreBindPluginName: newPlugin(preBindPlugin), // \t\t\t} // \t\t\tfor _, pl := range reservePlugins { // \t\t\t\tregistry[pl.Name()] = newPlugin(pl) // \t\t\t} // \t\t\t// Setup initial reserve and prebind plugin for testing. // \t\t\tprof := schedulerconfig.KubeSchedulerProfile{ // \t\t\t\tSchedulerName: v1.DefaultSchedulerName, // \t\t\t\tPlugins: &schedulerconfig.Plugins{ // \t\t\t\t\tReserve: schedulerconfig.PluginSet{ // \t\t\t\t\t\t// filled by looping over reservePlugins // \t\t\t\t\t}, // \t\t\t\t\tPreBind: schedulerconfig.PluginSet{ // \t\t\t\t\t\tEnabled: []schedulerconfig.Plugin{ // \t\t\t\t\t\t\t{ // \t\t\t\t\t\t\t\tName: preBindPluginName, // \t\t\t\t\t\t\t}, // \t\t\t\t\t\t}, // \t\t\t\t\t}, // \t\t\t\t}, // \t\t\t} // \t\t\tfor _, pl := range reservePlugins { // \t\t\t\tprof.Plugins.Reserve.Enabled = append(prof.Plugins.Reserve.Enabled, schedulerconfig.Plugin{ // \t\t\t\t\tName: pl.Name(), // \t\t\t\t}) // \t\t\t} // \t\t\t// Create the master and the scheduler with the test plugin set. // \t\t\ttestCtx := initTestSchedulerForFrameworkTest(t, testutils.InitTestMaster(t, \"reserve-plugin-unreserve\", nil), 2, // \t\t\t\tscheduler.WithProfiles(prof), // \t\t\t\tscheduler.WithFrameworkOutOfTreeRegistry(registry)) // \t\t\tdefer testutils.CleanupTest(t, testCtx) // \t\t\tpreBindPlugin.failPreBind = test.failPreBind // \t\t\tif test.failReserve { // \t\t\t\treservePlugins[test.failReserveIndex].failReserve = true // \t\t\t} // \t\t\t// Create a best effort pod. // \t\t\tpod, err := createPausePod(testCtx.ClientSet, // \t\t\t\tinitPausePod(&pausePodConfig{Name: \"test-pod\", Namespace: testCtx.NS.Name})) // \t\t\tif err != nil { // \t\t\t\tt.Errorf(\"Error while creating a test pod: %v\", err) // \t\t\t} // \t\t\tif test.failPreBind || test.failReserve { // \t\t\t\tif err = wait.Poll(10*time.Millisecond, 30*time.Second, podSchedulingError(testCtx.ClientSet, pod.Namespace, pod.Name)); err != nil { // \t\t\t\t\tt.Errorf(\"Expected a scheduling error, but didn't get it: %v\", err) // \t\t\t\t} // \t\t\t\tfor i := numReservePlugins - 1; i >= 0; i-- { // \t\t\t\t\tselect { // \t\t\t\t\tcase event := <-pluginInvokeEventChan: // \t\t\t\t\t\texpectedPluginName := reservePlugins[i].Name() // \t\t\t\t\t\tif expectedPluginName != event.pluginName { // \t\t\t\t\t\t\tt.Errorf(\"event.pluginName = %s, want %s\", event.pluginName, expectedPluginName) // \t\t\t\t\t\t} // \t\t\t\t\tcase <-time.After(time.Second * 30): // \t\t\t\t\t\tt.Errorf(\"pluginInvokeEventChan receive timed out\") // \t\t\t\t\t} // \t\t\t\t} // \t\t\t} else { // \t\t\t\tif err = testutils.WaitForPodToSchedule(testCtx.ClientSet, pod); err != nil { // \t\t\t\t\tt.Errorf(\"Expected the pod to be scheduled, got an error: %v\", err) // \t\t\t\t} // \t\t\t\tfor i, pl := range reservePlugins { // \t\t\t\t\tif pl.numUnreserveCalled != 0 { // \t\t\t\t\t\tt.Errorf(\"reservePlugins[%d].numUnreserveCalled = %d, want 0\", i, pl.numUnreserveCalled) // \t\t\t\t\t} // \t\t\t\t} // \t\t\t} // \t\t\ttestutils.CleanupPods(testCtx.ClientSet, t, []*v1.Pod{pod}) // \t\t}) // \t} // } // TestUnReserveReservePlugins tests invocation of the Unreserve operation in // reserve plugins through failures in execution points such as pre-bind. Also // tests that the order of invocation of Unreserve operation is executed in the // reverse order of invocation of the Reserve operation. func TestUnReserveReservePlugins(t *testing.T) { tests := []struct { name string plugins []*ReservePlugin fail bool failPluginIdx int }{ { name: \"The first Reserve plugin fails\", failPluginIdx: 0, plugins: []*ReservePlugin{ { name: \"failedReservePlugin1\", failReserve: true, }, { name: \"succeedReservePlugin\", failReserve: false, }, { name: \"failedReservePlugin2\", failReserve: true, }, }, fail: true, }, { name: \"The middle Reserve plugin fails\", failPluginIdx: 1, plugins: []*ReservePlugin{ { name: \"succeedReservePlugin1\", failReserve: false, }, { name: \"failedReservePlugin1\", failReserve: true, }, { name: \"succeedReservePlugin2\", failReserve: false, }, }, fail: true, }, { name: \"The last Reserve plugin fails\", failPluginIdx: 2, plugins: []*ReservePlugin{ { name: \"succeedReservePlugin1\", failReserve: false, }, { name: \"succeedReservePlugin2\", failReserve: false, }, { name: \"failedReservePlugin1\", failReserve: true, }, }, fail: true, }, { name: \"The Reserve plugins succeed\", failPluginIdx: -1, plugins: []*ReservePlugin{ { name: \"succeedReservePlugin1\", failReserve: false, }, { name: \"succeedReservePlugin2\", failReserve: false, }, { name: \"succeedReservePlugin3\", failReserve: false, }, }, fail: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { var pls []framework.Plugin for _, pl := range test.plugins { pls = append(pls, pl) } registry, prof := initRegistryAndConfig(t, pls...) // Create the API server and the scheduler with the test plugin set. testCtx := initTestSchedulerForFrameworkTest( t, testutils.InitTestAPIServer(t, \"unreserve-reserve-plugin\", nil), 2, scheduler.WithProfiles(prof), scheduler.WithFrameworkOutOfTreeRegistry(registry)) defer testutils.CleanupTest(t, testCtx) // Create a best effort pod. podName := \"test-pod\" pod, err := createPausePod(testCtx.ClientSet, initPausePod(&pausePodConfig{Name: podName, Namespace: testCtx.NS.Name})) if err != nil { t.Errorf(\"Error while creating a test pod: %v\", err) } if test.fail { if err = wait.Poll(10*time.Millisecond, 30*time.Second, podSchedulingError(testCtx.ClientSet, pod.Namespace, pod.Name)); err != nil { t.Errorf(\"Expected a reasons other than Unschedulable, but got: %v\", err) } for i, pl := range test.plugins { if i <= test.failPluginIdx { if pl.numReserveCalled != 1 { t.Errorf(\"Reserve Plugins %s numReserveCalled = %d, want 1.\", pl.name, pl.numReserveCalled) } } else { if pl.numReserveCalled != 0 { t.Errorf(\"Reserve Plugins %s numReserveCalled = %d, want 0.\", pl.name, pl.numReserveCalled) } } if pl.numUnreserveCalled != 1 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 1.\", pl.name, pl.numUnreserveCalled) } } } else { if err = testutils.WaitForPodToSchedule(testCtx.ClientSet, pod); err != nil { t.Errorf(\"Expected the pod to be scheduled. error: %v\", err) } for _, pl := range test.plugins { if pl.numReserveCalled != 1 { t.Errorf(\"Reserve Plugin %s numReserveCalled = %d, want 1.\", pl.name, pl.numReserveCalled) } if pl.numUnreserveCalled != 0 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 0.\", pl.name, pl.numUnreserveCalled) } } } testutils.CleanupPods(testCtx.ClientSet, t, []*v1.Pod{pod}) }) } } // TestUnReservePermitPlugins tests unreserve of Permit plugins. func TestUnReservePermitPlugins(t *testing.T) { tests := []struct { name string plugin *PermitPlugin fail bool }{ { name: \"All Reserve plugins passed, but a Permit plugin was rejected\", fail: true, plugin: &PermitPlugin{ name: \"rejectedPermitPlugin\", rejectPermit: true, }, }, { name: \"All Reserve plugins passed, but a Permit plugin timeout in waiting\", fail: true, plugin: &PermitPlugin{ name: \"timeoutPermitPlugin\", timeoutPermit: true, }, }, { name: \"The Permit plugin succeed\", fail: false, plugin: &PermitPlugin{ name: \"succeedPermitPlugin\", }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { reservePlugin := &ReservePlugin{ name: \"reservePlugin\", failReserve: false, } registry, profile := initRegistryAndConfig(t, []framework.Plugin{test.plugin, reservePlugin}...) // Create the API server and the scheduler with the test plugin set. testCtx := initTestSchedulerForFrameworkTest( t, testutils.InitTestAPIServer(t, \"unreserve-reserve-plugin\", nil), 2, scheduler.WithProfiles(profile), scheduler.WithFrameworkOutOfTreeRegistry(registry)) defer testutils.CleanupTest(t, testCtx) // Create a best effort pod. podName := \"test-pod\" pod, err := createPausePod(testCtx.ClientSet, initPausePod(&pausePodConfig{Name: podName, Namespace: testCtx.NS.Name})) if err != nil { t.Errorf(\"Error while creating a test pod: %v\", err) } if test.fail { if err = waitForPodUnschedulable(testCtx.ClientSet, pod); err != nil { t.Errorf(\"Didn't expect the pod to be scheduled. error: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 1 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 1.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } else { if err = testutils.WaitForPodToSchedule(testCtx.ClientSet, pod); err != nil { t.Errorf(\"Expected the pod to be scheduled. error: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 0 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 0.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } if test.plugin.numPermitCalled != 1 { t.Errorf(\"Expected the Permit plugin to be called.\") } testutils.CleanupPods(testCtx.ClientSet, t, []*v1.Pod{pod}) }) } } // TestUnReservePreBindPlugins tests unreserve of Prebind plugins. func TestUnReservePreBindPlugins(t *testing.T) { tests := []struct { name string plugin *PreBindPlugin fail bool }{ { name: \"All Reserve plugins passed, but a PreBind plugin failed\", fail: true, plugin: &PreBindPlugin{ podUIDs: make(map[types.UID]struct{}), rejectPreBind: true, }, }, { name: \"All Reserve plugins passed, and PreBind plugin succeed\", fail: false, plugin: &PreBindPlugin{podUIDs: make(map[types.UID]struct{})}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { reservePlugin := &ReservePlugin{ name: \"reservePlugin\", failReserve: false, } registry, profile := initRegistryAndConfig(t, []framework.Plugin{test.plugin, reservePlugin}...) // Create the API server and the scheduler with the test plugin set. testCtx := initTestSchedulerForFrameworkTest( t, testutils.InitTestAPIServer(t, \"unreserve-prebind-plugin\", nil), 2, scheduler.WithProfiles(profile), scheduler.WithFrameworkOutOfTreeRegistry(registry)) defer testutils.CleanupTest(t, testCtx) // Create a pause pod. podName := \"test-pod\" pod, err := createPausePod(testCtx.ClientSet, initPausePod(&pausePodConfig{Name: podName, Namespace: testCtx.NS.Name})) if err != nil { t.Errorf(\"Error while creating a test pod: %v\", err) } if test.fail { if err = wait.Poll(10*time.Millisecond, 30*time.Second, podSchedulingError(testCtx.ClientSet, pod.Namespace, pod.Name)); err != nil { t.Errorf(\"Expected a reasons other than Unschedulable, but got: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 1 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 1.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } else { if err = testutils.WaitForPodToSchedule(testCtx.ClientSet, pod); err != nil { t.Errorf(\"Expected the pod to be scheduled. error: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 0 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 0.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } if test.plugin.numPreBindCalled != 1 { t.Errorf(\"Expected the Prebind plugin to be called.\") } testutils.CleanupPods(testCtx.ClientSet, t, []*v1.Pod{pod}) }) } } // TestUnReserveBindPlugins tests unreserve of Bind plugins. func TestUnReserveBindPlugins(t *testing.T) { tests := []struct { name string plugin *BindPlugin fail bool }{ { name: \"All Reserve plugins passed, and Bind plugin succeed\", fail: false, plugin: &BindPlugin{name: \"SucceedBindPlugin\"}, }, { name: \"All Reserve plugins passed, but a Bind plugin failed\", fail: false, plugin: &BindPlugin{name: \"FailedBindPlugin\"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { reservePlugin := &ReservePlugin{ name: \"reservePlugin\", failReserve: false, } registry, profile := initRegistryAndConfig(t, []framework.Plugin{test.plugin, reservePlugin}...) apiCtx := testutils.InitTestAPIServer(t, \"unreserve-bind-plugin\", nil) test.plugin.client = apiCtx.ClientSet // Create the scheduler with the test plugin set. testCtx := initTestSchedulerForFrameworkTest( t, apiCtx, 2, scheduler.WithProfiles(profile), scheduler.WithFrameworkOutOfTreeRegistry(registry)) defer testutils.CleanupTest(t, testCtx) // Create a pause pod. podName := \"test-pod\" pod, err := createPausePod(testCtx.ClientSet, initPausePod(&pausePodConfig{Name: podName, Namespace: testCtx.NS.Name})) if err != nil { t.Errorf(\"Error while creating a test pod: %v\", err) } if test.fail { if err = wait.Poll(10*time.Millisecond, 30*time.Second, podSchedulingError(testCtx.ClientSet, pod.Namespace, pod.Name)); err != nil { t.Errorf(\"Expected a reasons other than Unschedulable, but got: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 1 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 1.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } else { if err = testutils.WaitForPodToSchedule(testCtx.ClientSet, pod); err != nil { t.Errorf(\"Expected the pod to be scheduled. error: %v\", err) } // Verify the Reserve Plugins if reservePlugin.numUnreserveCalled != 0 { t.Errorf(\"Reserve Plugin %s numUnreserveCalled = %d, want 0.\", reservePlugin.name, reservePlugin.numUnreserveCalled) } } if test.plugin.numBindCalled != 1 { t.Errorf(\"Expected the Prebind plugin to be called.\") } testutils.CleanupPods(testCtx.ClientSet, t, []*v1.Pod{pod}) }) } } type pluginInvokeEvent struct { pluginName string"} {"_id":"doc-en-kubernetes-b1fe3709a8de6b04db86eb7f6930a944f2d4235b542a3e359cc912930154c9d3","title":"","text":"// TestBindPlugin tests invocation of bind plugins. func TestBindPlugin(t *testing.T) { testContext := testutils.InitTestAPIServer(t, \"bind-plugin\", nil) bindPlugin1 := &BindPlugin{PluginName: \"bind-plugin-1\", client: testContext.ClientSet} bindPlugin2 := &BindPlugin{PluginName: \"bind-plugin-2\", client: testContext.ClientSet} bindPlugin1 := &BindPlugin{name: \"bind-plugin-1\", client: testContext.ClientSet} bindPlugin2 := &BindPlugin{name: \"bind-plugin-2\", client: testContext.ClientSet} reservePlugin := &ReservePlugin{name: \"mock-reserve-plugin\"} postBindPlugin := &PostBindPlugin{name: \"mock-post-bind-plugin\"} // Create a plugin registry for testing. Register reserve, bind, and"} {"_id":"doc-en-kubernetes-4e0d8ead74914bab25dfc7758442946c91c9cbb2ebc683c832b139c6e92aaf57","title":"","text":"const ( TableNAT Table = \"nat\" TableFilter Table = \"filter\" TableBroute Table = \"broute\" ) type Chain string"} {"_id":"doc-en-kubernetes-d9f276b4f087c47da674b599ac4cbfbf2a5a9b42280030227ddf82d74f1ad2b7","title":"","text":"ChainPrerouting Chain = \"PREROUTING\" ChainOutput Chain = \"OUTPUT\" ChainInput Chain = \"INPUT\" ChainBrouting Chain = \"BROUTING\" ) type operation string"} {"_id":"doc-en-kubernetes-19c6c54b789150a679fc1230f622f66054976fc2602763d157f7066547d6b649","title":"","text":"// Input args must follow the format and sequence of ebtables list output. Otherwise, EnsureRule will always create // new rules and causing duplicates. EnsureRule(position RulePosition, table Table, chain Chain, args ...string) (bool, error) // DeleteRule checks if the specified rule is present and, if so, deletes it. DeleteRule(table Table, chain Chain, args ...string) error // EnsureChain checks if the specified chain is present and, if not, creates it. If the rule existed, return true. EnsureChain(table Table, chain Chain) (bool, error) // DeleteChain deletes the specified chain. If the chain did not exist, return error."} {"_id":"doc-en-kubernetes-d8d067e399ab5cb3109c5e4facc3529e4aa7e6cc954e626f9358ca923dc00427","title":"","text":"return exist, nil } func (runner *runner) DeleteRule(table Table, chain Chain, args ...string) error { exist := true fullArgs := makeFullArgs(table, opListChain, chain, fullMac) out, err := runner.exec.Command(cmdebtables, fullArgs...).CombinedOutput() if err != nil { exist = false } else { exist = checkIfRuleExists(string(out), args...) } if !exist { return nil } fullArgs = makeFullArgs(table, opDeleteRule, chain, args...) out, err = runner.exec.Command(cmdebtables, fullArgs...).CombinedOutput() if err != nil { return fmt.Errorf(\"Failed to delete rule: %v, output: %s\", err, out) } return nil } func (runner *runner) EnsureChain(table Table, chain Chain) (bool, error) { exist := true"} {"_id":"doc-en-kubernetes-dd342fa1db2e2b593cd5c215cdffc66875add8dcf05df9c7e5cb382c95c55cf6","title":"","text":"t.Errorf(\"expected error: %q\", errStr) } } func TestDeleteRule(t *testing.T) { fcmd := fakeexec.FakeCmd{ CombinedOutputScript: []fakeexec.FakeAction{ // Exists func() ([]byte, []byte, error) { return []byte(`Bridge table: filter Bridge chain: OUTPUT, entries: 4, policy: ACCEPT -j TEST `), nil, nil }, // Fail to delete func() ([]byte, []byte, error) { return nil, nil, &fakeexec.FakeExitError{Status: 2} }, // Does not Exists. func() ([]byte, []byte, error) { return []byte(`Bridge table: filter Bridge chain: TEST, entries: 0, policy: ACCEPT`), nil, nil }, }, } fexec := fakeexec.FakeExec{ CommandScript: []fakeexec.FakeCommandAction{ func(cmd string, args ...string) exec.Cmd { return fakeexec.InitFakeCmd(&fcmd, cmd, args...) }, func(cmd string, args ...string) exec.Cmd { return fakeexec.InitFakeCmd(&fcmd, cmd, args...) }, func(cmd string, args ...string) exec.Cmd { return fakeexec.InitFakeCmd(&fcmd, cmd, args...) }, }, } runner := New(&fexec) err := runner.DeleteRule(TableFilter, ChainOutput, \"-j\", \"TEST\") errStr := \"Failed to delete rule: exit 2, output: \" if err == nil || err.Error() != errStr { t.Errorf(\"expected error: %q\", errStr) } err = runner.DeleteRule(TableFilter, ChainOutput, \"-j\", \"TEST\") if err != nil { t.Errorf(\"expected err = nil\") } } "} {"_id":"doc-en-kubernetes-8d4cd92e11005e1a31956db93108fc9b08367ea9dd1610c075fa3b5a08d9c320","title":"","text":"touch \"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go\" echo > api/api-rules/violation_exceptions.list echo > api/api-rules/codegen_violation_exceptions.list if make generated_files >/dev/null; then if make generated_files >/dev/null 2>&1; then echo \"Expected make generated_files to fail with API violations.\" echo \"\" exit 1"} {"_id":"doc-en-kubernetes-bb01653c1167088c1a7f9abbd4b51f6e69f7f8a28cc2bea938bb4b4e249e801e","title":"","text":" = vendor/go.opencensus.io licensed under: = Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License. \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\" \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. = vendor/go.opencensus.io/LICENSE 175792518e4ac015ab6696d16c4f607e "} {"_id":"doc-en-kubernetes-ee7df1137ca13e311b61ac3731a2a5ebec133a80c49a3f1b5a4924e6e7cf65f5","title":"","text":"continue fi # Skip a directory if 1) it has no files and 2) all the subdirectories contain a go.mod file. if [[ -z \"$(find \"${DEPS_DIR}/${PACKAGE}\" -mindepth 1 -maxdepth 1 -type f)\" ]]; then if [[ -z \"$(find \"${DEPS_DIR}/${PACKAGE}/\" -mindepth 1 -maxdepth 1 -type f)\" ]]; then misses_go_mod=false while read -d \"\" -r SUBDIR; do if [[ ! -e \"${SUBDIR}/go.mod\" ]]; then misses_go_mod=true break fi done < <(find \"${DEPS_DIR}/${PACKAGE}\" -mindepth 1 -maxdepth 1 -type d -print0) done < <(find \"${DEPS_DIR}/${PACKAGE}/\" -mindepth 1 -maxdepth 1 -type d -print0) if [[ $misses_go_mod = false ]]; then echo \"${PACKAGE} has no files, skipping\" >&2 continue"} {"_id":"doc-en-kubernetes-fd6583f8bf2f29913b53d4877452f43ea2052f0110a000400ec427b4e49e2710","title":"","text":") const ( // Taken from lmctfy https://github.com/google/lmctfy/blob/master/lmctfy/controllers/cpu_controller.cc MinShares = 2 // These limits are defined in the kernel: // https://github.com/torvalds/linux/blob/0bddd227f3dc55975e2b8dfa7fc6f959b062a2c7/kernel/sched/sched.h#L427-L428 MinShares = 2 MaxShares = 262144 SharesPerCPU = 1024 MilliCPUToCPU = 1000"} {"_id":"doc-en-kubernetes-e8e699e54a14b9211178735ef6505e8e00b1ff98f440b810fb399148559f7c30","title":"","text":"if shares < MinShares { return MinShares } if shares > MaxShares { return MaxShares } return uint64(shares) }"} {"_id":"doc-en-kubernetes-6bdc4ab06739a7a3d02af6b4a6d6e78200368c9c38c59b320a64d58e266f037a","title":"","text":"\"reason_cache.go\", \"runonce.go\", \"runtime.go\", \"time_cache.go\", \"util.go\", \"volume_host.go\", ],"} {"_id":"doc-en-kubernetes-b58f210b15aad3e8527a4bdde8f525266bac99dffdf8a849cf2098093f8a73c9","title":"","text":"\"pod_workers_test.go\", \"reason_cache_test.go\", \"runonce_test.go\", \"time_cache_test.go\", ], embed = [\":go_default_library\"], deps = ["} {"_id":"doc-en-kubernetes-834384c6d6926ce390fa134a1fe186c4110f8cd3bef25f592953003417ec625f","title":"","text":"\"//staging/src/k8s.io/client-go/util/testing:go_default_library\", \"//staging/src/k8s.io/component-base/featuregate/testing:go_default_library\", \"//staging/src/k8s.io/component-base/version:go_default_library\", \"//vendor/github.com/golang/groupcache/lru:go_default_library\", \"//vendor/github.com/google/cadvisor/info/v1:go_default_library\", \"//vendor/github.com/google/cadvisor/info/v2:go_default_library\", \"//vendor/github.com/stretchr/testify/assert:go_default_library\","} {"_id":"doc-en-kubernetes-1dbde4b745222e047c358c038d79fa525d1bf03098f56c22ba3675326e79f6de","title":"","text":"experimentalHostUserNamespaceDefaulting: utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalHostUserNamespaceDefaultingGate), keepTerminatedPodVolumes: keepTerminatedPodVolumes, nodeStatusMaxImages: nodeStatusMaxImages, lastContainerStartedTime: newTimeCache(), } if klet.cloud != nil {"} {"_id":"doc-en-kubernetes-a7fc664165a8f8b4dc3236f8b1d044901fed7fa557120640e23b72812b4ed54b","title":"","text":"// lastStatusReportTime is the time when node status was last reported. lastStatusReportTime time.Time // lastContainerStartedTime is the time of the last ContainerStarted event observed per pod lastContainerStartedTime *timeCache // syncNodeStatusMux is a lock on updating the node status, because this path is not thread-safe. // This lock is used by Kubelet.syncNodeStatus function and shouldn't be used anywhere else. syncNodeStatusMux sync.Mutex"} {"_id":"doc-en-kubernetes-3efe254cd70fd956bcc6902476e1c51beb347f34bd09cb6e2251feed15fa0879","title":"","text":"} kl.podWorkers.ForgetWorker(pod.UID) // make sure our runtimeCache is at least as fresh as the last container started event we observed. // this ensures we correctly send graceful deletion signals to all containers we've reported started. if lastContainerStarted, ok := kl.lastContainerStartedTime.Get(pod.UID); ok { if err := kl.runtimeCache.ForceUpdateIfOlder(lastContainerStarted); err != nil { return fmt.Errorf(\"error updating containers: %v\", err) } } // Runtime cache may not have been updated to with the pod, but it's okay // because the periodic cleanup routine will attempt to delete again later. runningPods, err := kl.runtimeCache.GetPods()"} {"_id":"doc-en-kubernetes-f6364e630ed4e6e770d898340766c64ef587c6da1bf3b4e335292b309f8ef3ec","title":"","text":"kl.sourcesReady.AddSource(u.Source) case e := <-plegCh: if e.Type == pleg.ContainerStarted { // record the most recent time we observed a container start for this pod. // this lets us selectively invalidate the runtimeCache when processing a delete for this pod // to make sure we don't miss handling graceful termination for containers we reported as having started. kl.lastContainerStartedTime.Add(e.ID, time.Now()) } if isSyncPodWorthy(e) { // PLEG event for a pod; sync it. if pod, ok := kl.podManager.GetPodByUID(e.ID); ok {"} {"_id":"doc-en-kubernetes-3841b28f9b6ef815d222ae6b46b6aedc48ec8a210f7c002b3a6c5d5f6a6aeb57","title":"","text":" /* Copyright 2020 The Kubernetes Authors. 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. */ package kubelet import ( \"sync\" \"time\" \"github.com/golang/groupcache/lru\" \"k8s.io/apimachinery/pkg/types\" ) // timeCache stores a time keyed by uid type timeCache struct { lock sync.RWMutex cache *lru.Cache } // maxTimeCacheEntries is the cache entry number in lru cache. 1000 is a proper number // for our 100 pods per node target. If we support more pods per node in the future, we // may want to increase the number. const maxTimeCacheEntries = 1000 func newTimeCache() *timeCache { return &timeCache{cache: lru.New(maxTimeCacheEntries)} } func (c *timeCache) Add(uid types.UID, t time.Time) { c.lock.Lock() defer c.lock.Unlock() c.cache.Add(uid, t) } func (c *timeCache) Remove(uid types.UID) { c.lock.Lock() defer c.lock.Unlock() c.cache.Remove(uid) } func (c *timeCache) Get(uid types.UID) (time.Time, bool) { c.lock.RLock() defer c.lock.RUnlock() value, ok := c.cache.Get(uid) if !ok { return time.Time{}, false } t, ok := value.(time.Time) if !ok { return time.Time{}, false } return t, true } "} {"_id":"doc-en-kubernetes-c27f9b32fe4f47e5e5595f8e507acbd20bfa6aea18b25ef0dc8b64248fdaa551","title":"","text":" /* Copyright 2020 The Kubernetes Authors. 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. */ package kubelet import ( \"testing\" \"time\" \"github.com/golang/groupcache/lru\" ) func TestTimeCache(t *testing.T) { cache := &timeCache{cache: lru.New(2)} if a, ok := cache.Get(\"123\"); ok { t.Errorf(\"expected cache miss, got %v, %v\", a, ok) } now := time.Now() soon := now.Add(time.Minute) cache.Add(\"now\", now) cache.Add(\"soon\", soon) if a, ok := cache.Get(\"now\"); !ok || !a.Equal(now) { t.Errorf(\"expected cache hit matching %v, got %v, %v\", now, a, ok) } if a, ok := cache.Get(\"soon\"); !ok || !a.Equal(soon) { t.Errorf(\"expected cache hit matching %v, got %v, %v\", soon, a, ok) } then := now.Add(-time.Minute) cache.Add(\"then\", then) if a, ok := cache.Get(\"now\"); ok { t.Errorf(\"expected cache miss from oldest evicted value, got %v, %v\", a, ok) } if a, ok := cache.Get(\"soon\"); !ok || !a.Equal(soon) { t.Errorf(\"expected cache hit matching %v, got %v, %v\", soon, a, ok) } if a, ok := cache.Get(\"then\"); !ok || !a.Equal(then) { t.Errorf(\"expected cache hit matching %v, got %v, %v\", then, a, ok) } } "} {"_id":"doc-en-kubernetes-4b3ff6e554084187d73a7f0be1ab67ebd40e9a07077acb82be5350d0ab39994c","title":"","text":"} // DeletePodWithWait deletes the passed-in pod and waits for the pod to be terminated. Resilient to the pod // not existing. Also waits for all owned resources to be deleted. // not existing. func DeletePodWithWait(c clientset.Interface, pod *v1.Pod) error { if pod == nil { return nil"} {"_id":"doc-en-kubernetes-891d2d2c5970d2294c80642cb063c3d44e4d0a1c8f8fc218d9bd721efd5b739a","title":"","text":"} // DeletePodWithWaitByName deletes the named and namespaced pod and waits for the pod to be terminated. Resilient to the pod // not existing. Also waits for all owned resources to be deleted. // not existing. func DeletePodWithWaitByName(c clientset.Interface, podName, podNamespace string) error { e2elog.Logf(\"Deleting pod %q in namespace %q\", podName, podNamespace) deletionPolicy := metav1.DeletePropagationForeground err := c.CoreV1().Pods(podNamespace).Delete(context.TODO(), podName, metav1.DeleteOptions{ // If the pod is the owner of some resources (like ephemeral inline volumes), // then we want to be sure that those are also gone before we return. // Blocking pod deletion via metav1.DeletePropagationForeground achieves that. PropagationPolicy: &deletionPolicy, }) err := c.CoreV1().Pods(podNamespace).Delete(context.TODO(), podName, metav1.DeleteOptions{}) if err != nil { if apierrors.IsNotFound(err) { return nil // assume pod was already deleted"} {"_id":"doc-en-kubernetes-40b6f21ad68cf8f1f7340a7ad5be3c5f0e79e930432ed97ec2b476d16df9f20d","title":"","text":"namespace := \"default\" name := \"kubernetes\" endpoints, err := cs.CoreV1().Endpoints(namespace).Get(context.TODO(), name, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectNoError(err, \"error creating Endpoints resource\") if len(endpoints.Subsets) != 1 { framework.Failf(\"Expected 1 subset in endpoints, got %d: %#v\", len(endpoints.Subsets), endpoints.Subsets) } endpointSubset := endpoints.Subsets[0] endpointSlice, err := cs.DiscoveryV1beta1().EndpointSlices(namespace).Get(context.TODO(), name, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectNoError(err, \"error creating EndpointSlice resource\") if len(endpointSlice.Ports) != len(endpointSubset.Ports) { framework.Failf(\"Expected EndpointSlice to have %d ports, got %d: %#v\", len(endpointSubset.Ports), len(endpointSlice.Ports), endpointSlice.Ports) }"} {"_id":"doc-en-kubernetes-b6689f3dbd023ba2368ab43648a89556e7105d2542bc10690f5bfe5f3943bfc9","title":"","text":"}) // Expect Endpoints resource to be created. if err := wait.PollImmediate(2*time.Second, 12*time.Second, func() (bool, error) { if err := wait.PollImmediate(2*time.Second, wait.ForeverTestTimeout, func() (bool, error) { _, err := cs.CoreV1().Endpoints(svc.Namespace).Get(context.TODO(), svc.Name, metav1.GetOptions{}) if err != nil { return false, nil"} {"_id":"doc-en-kubernetes-5c5636a46a61f124bf86b4ecc7b8f910fe724991611d7f2f52e03fdd7eea26f3","title":"","text":"// Expect EndpointSlice resource to be created. var endpointSlice discoveryv1beta1.EndpointSlice if err := wait.PollImmediate(2*time.Second, 12*time.Second, func() (bool, error) { if err := wait.PollImmediate(2*time.Second, wait.ForeverTestTimeout, func() (bool, error) { endpointSliceList, err := cs.DiscoveryV1beta1().EndpointSlices(svc.Namespace).List(context.TODO(), metav1.ListOptions{ LabelSelector: \"kubernetes.io/service-name=\" + svc.Name, })"} {"_id":"doc-en-kubernetes-d7e54f38886773208318f59c4c6774213fd65661afb802123aaca8fd21aae05b","title":"","text":"} err := cs.CoreV1().Services(svc.Namespace).Delete(context.TODO(), svc.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) framework.ExpectNoError(err, \"error deleting Service\") // Expect Endpoints resource to be deleted when Service is. if err := wait.PollImmediate(2*time.Second, 12*time.Second, func() (bool, error) { if err := wait.PollImmediate(2*time.Second, wait.ForeverTestTimeout, func() (bool, error) { _, err := cs.CoreV1().Endpoints(svc.Namespace).Get(context.TODO(), svc.Name, metav1.GetOptions{}) if err != nil { if apierrors.IsNotFound(err) {"} {"_id":"doc-en-kubernetes-a56d19ad9fd8989b3cd8c385e8bdc3a398b411f70ba69848375da304f28d955b","title":"","text":"} // Expect EndpointSlice resource to be deleted when Service is. if err := wait.PollImmediate(2*time.Second, 12*time.Second, func() (bool, error) { if err := wait.PollImmediate(2*time.Second, wait.ForeverTestTimeout, func() (bool, error) { endpointSliceList, err := cs.DiscoveryV1beta1().EndpointSlices(svc.Namespace).List(context.TODO(), metav1.ListOptions{ LabelSelector: \"kubernetes.io/service-name=\" + svc.Name, })"} {"_id":"doc-en-kubernetes-5a28e3b14fa38eab23b8aa8400412ad2653de18aed1677192588998d89da9a05","title":"","text":"Name: \"example-int-port\", }, Spec: v1.ServiceSpec{ Selector: map[string]string{labelPod1: labelValue}, Selector: map[string]string{labelPod1: labelValue}, PublishNotReadyAddresses: true, Ports: []v1.ServicePort{{ Name: \"example\", Port: 80,"} {"_id":"doc-en-kubernetes-c35041bcfc0250c669f9c790e5edc0387770af5f9127aa696b7e065836e3b8fe","title":"","text":"Name: \"example-named-port\", }, Spec: v1.ServiceSpec{ Selector: map[string]string{labelShared12: labelValue}, Selector: map[string]string{labelShared12: labelValue}, PublishNotReadyAddresses: true, Ports: []v1.ServicePort{{ Name: \"http\", Port: 80,"} {"_id":"doc-en-kubernetes-2fd5280ed7505a9efee695c7fdf900acd5470476ba05f3fc50f33167f1ed3262","title":"","text":"Name: \"example-no-match\", }, Spec: v1.ServiceSpec{ Selector: map[string]string{labelPod3: labelValue}, Selector: map[string]string{labelPod3: labelValue}, PublishNotReadyAddresses: true, Ports: []v1.ServicePort{{ Name: \"example-no-match\", Port: 80,"} {"_id":"doc-en-kubernetes-a46b8e332c85a88a09bb8cc173d61a1920e17aaac1bdf3975e85c42059c0b1cb","title":"","text":"}) err := wait.Poll(5*time.Second, 3*time.Minute, func() (bool, error) { if !podClient.PodIsReady(pod1.Name) { framework.Logf(\"Pod 1 not ready yet\") return false, nil } if !podClient.PodIsReady(pod2.Name) { framework.Logf(\"Pod 2 not ready yet\") return false, nil } var err error pod1, err = podClient.Get(context.TODO(), pod1.Name, metav1.GetOptions{}) if err != nil { return false, err } if len(pod1.Status.PodIPs) == 0 { return false, nil } pod2, err = podClient.Get(context.TODO(), pod2.Name, metav1.GetOptions{}) if err != nil { return false, err } if len(pod2.Status.PodIPs) == 0 { return false, nil } return true, nil }) framework.ExpectNoError(err) framework.ExpectNoError(err, \"timed out waiting for Pods to have IPs assigned\") ginkgo.By(\"referencing a single matching pod\") expectEndpointsAndSlices(cs, f.Namespace.Name, svc1, []*v1.Pod{pod1}, 1, 1, false)"} {"_id":"doc-en-kubernetes-0685b99d9dce9016e3a299c45725ca89b7414ede1f175b5c514ff7de860128ec","title":"","text":"// createServiceReportErr creates a Service and reports any associated error. func createServiceReportErr(cs clientset.Interface, ns string, service *v1.Service) *v1.Service { svc, err := cs.CoreV1().Services(ns).Create(context.TODO(), service, metav1.CreateOptions{}) framework.ExpectNoError(err) framework.ExpectNoError(err, \"error deleting Service\") return svc }"} {"_id":"doc-en-kubernetes-52dd3c666d1a239170dca3d6ae2541fd0cd5dbadc50f7c6ba53c9760def027ad","title":"","text":"apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/wait\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/kubernetes/test/e2e/framework\""} {"_id":"doc-en-kubernetes-408789ffc6aeed30cc796da829cab0bd84d4569aeadb9c056141bd856c90ff7e","title":"","text":"framework.Failf(\"Expected 1 EndpointSlice, got %d\", len(endpointSlices)) } totalEndpointSliceAddresses := 0 // Use a set for deduping values. Duplicate addresses are technically valid // here although rare. esAddresses := sets.NewString() for _, endpointSlice := range endpointSlices { totalEndpointSliceAddresses += len(endpointSlice.Endpoints) for _, endpoint := range endpointSlice.Endpoints { esAddresses.Insert(endpoint.Addresses[0]) } if len(pods) == 0 && len(endpointSlice.Ports) != 0 { framework.Failf(\"Expected EndpointSlice to have 0 ports, got %d\", len(endpointSlice.Ports)) }"} {"_id":"doc-en-kubernetes-2f189cc49970d6a147eef6b02bd047a896b69ffa7b261b30885058c6b95dcabf","title":"","text":"} } if len(pods) != totalEndpointSliceAddresses { framework.Failf(\"Expected %d addresses, got %d\", len(pods), totalEndpointSliceAddresses) if len(pods) != esAddresses.Len() { framework.Failf(\"Expected %d addresses, got %d\", len(pods), esAddresses.Len()) } }"} {"_id":"doc-en-kubernetes-8a34f59ee1f703472a49c018e6a2879ed10576a2101dfa5356a2b95d33d65351","title":"","text":"framework.Logf(\"EndpointSlice for Service %s/%s not found\", ns, svcName) return []discoveryv1beta1.EndpointSlice{}, false } if len(esList.Items) != numSlices { framework.Logf(\"Expected %d EndpointSlices for Service %s/%s, got %d\", numSlices, ns, svcName, len(esList.Items)) // In some cases the EndpointSlice controller will create more // EndpointSlices than necessary resulting in some duplication. This is // valid and tests should only fail here if less EndpointSlices than // expected are added. if len(esList.Items) < numSlices { framework.Logf(\"Expected at least %d EndpointSlices for Service %s/%s, got %d\", numSlices, ns, svcName, len(esList.Items)) for i, epSlice := range esList.Items { epsData, err := json.Marshal(epSlice) if err != nil {"} {"_id":"doc-en-kubernetes-8c67a6d47b2337c1f1fcf475a1b257bacd5e5e162234693ba669eafae38af0b9","title":"","text":"cs = f.ClientSet }) ginkgo.It(\"should set default value on new IngressClass\", func() { ginkgo.It(\"should set default value on new IngressClass [Serial]\", func() { ingressClass1, err := createIngressClass(cs, \"ingressclass1\", true, f.UniqueName) framework.ExpectNoError(err) defer deleteIngressClass(cs, ingressClass1.Name)"} {"_id":"doc-en-kubernetes-a5375c354588e3a6bac5dc7e5974838301985b2838345259ea04dbe7f479aaaa","title":"","text":"} }) ginkgo.It(\"should not set default value if no default IngressClass\", func() { ginkgo.It(\"should not set default value if no default IngressClass [Serial]\", func() { ingressClass1, err := createIngressClass(cs, \"ingressclass1\", false, f.UniqueName) framework.ExpectNoError(err) defer deleteIngressClass(cs, ingressClass1.Name)"} {"_id":"doc-en-kubernetes-e85860941665c4c82c86a788b5e39eb952eabd3ce722f151c8d52ebedb3e8a47","title":"","text":"} }) ginkgo.It(\"should prevent Ingress creation if more than 1 IngressClass marked as default\", func() { ginkgo.It(\"should prevent Ingress creation if more than 1 IngressClass marked as default [Serial]\", func() { ingressClass1, err := createIngressClass(cs, \"ingressclass1\", true, f.UniqueName) framework.ExpectNoError(err) defer deleteIngressClass(cs, ingressClass1.Name)"} {"_id":"doc-en-kubernetes-ac3e5d11ff82e7e44c93e5d9f17cc462af9e91398060e130f886e0ba46855193","title":"","text":"// IngressClass resource create/read/update/watch verbs ginkgo.By(\"creating\") ingressClass1, err := createIngressClass(cs, \"ingressclass1\", true, f.UniqueName) ingressClass1, err := createIngressClass(cs, \"ingressclass1\", false, f.UniqueName) framework.ExpectNoError(err) _, err = createIngressClass(cs, \"ingressclass2\", true, f.UniqueName) _, err = createIngressClass(cs, \"ingressclass2\", false, f.UniqueName) framework.ExpectNoError(err) _, err = createIngressClass(cs, \"ingressclass3\", true, f.UniqueName) _, err = createIngressClass(cs, \"ingressclass3\", false, f.UniqueName) framework.ExpectNoError(err) ginkgo.By(\"getting\")"} {"_id":"doc-en-kubernetes-dda6d49bd81b68fc81bccc28af07f3d8317a088af4671d169acdb049d6832629","title":"","text":"// SetGroupVersionKind sets or clears the intended serialized kind of an object. Passing kind nil // should clear the current setting. SetGroupVersionKind(kind GroupVersionKind) // GroupVersionKind returns the stored group, version, and kind of an object, or nil if the object does // not expose or provide these fields. // GroupVersionKind returns the stored group, version, and kind of an object, or an empty struct // if the object does not expose or provide these fields. GroupVersionKind() GroupVersionKind }"} {"_id":"doc-en-kubernetes-b73b667c6757a1f028e21b0a4cb6fed6dbc778c532e2f694d597aa0f9eb8d08d","title":"","text":"\"port\": 10001, \"labels\": { \"name\": \"redisslave\" } }, \"selector\": { \"name\": \"redisslave\" }"} {"_id":"doc-en-kubernetes-26180b692dca0284a50e82d417d2a9d936da770eed8116b49aa24239d2752f8d","title":"","text":"\"fmt\" \"math\" \"strings\" \"sync\" \"time\""} {"_id":"doc-en-kubernetes-6dd1d2fdec08203e92bafe360d9a4046e533a701af0e964dd0ad8e9a13c2788d","title":"","text":"nodeName types.NodeName volumeHost volume.VolumeHost migratedPlugins map[string](func() bool) // lock protects changes to node. lock sync.Mutex } // If no updates is needed, the function must return the same Node object as the input."} {"_id":"doc-en-kubernetes-ec2658f7aa3beadfe513eef69ac9d6754c34f9e9738099a29241934278c9acca","title":"","text":"// the effects of previous updateFuncs to avoid potential conflicts. For example, if multiple // functions update the same field, updates in the last function are persisted. func (nim *nodeInfoManager) tryUpdateNode(updateFuncs ...nodeUpdateFunc) error { nim.lock.Lock() defer nim.lock.Unlock() // Retrieve the latest version of Node before attempting update, so that // existing changes are not overwritten."} {"_id":"doc-en-kubernetes-fb2ba169b87de077bcbe54885a6ed14dc5720897accd1fd37a55c0136d2ef8b7","title":"","text":"addonmanager.kubernetes.io/mode: Reconcile kubernetes.io/name: \"Elasticsearch\" spec: clusterIP: None ports: - port: 9200 protocol: TCP targetPort: db - name: db port: 9200 protocol: TCP targetPort: 9200 - name: transport port: 9300 protocol: TCP targetPort: 9300 publishNotReadyAddresses: true selector: k8s-app: elasticsearch-logging sessionAffinity: None type: ClusterIP "} {"_id":"doc-en-kubernetes-77263ac49a3b20e17ee33aa7df5a4113fb003f9a05766d2416ce36a4c47d8e55","title":"","text":"k8s-app: elasticsearch-logging addonmanager.kubernetes.io/mode: Reconcile rules: - apiGroups: - \"\" resources: - \"services\" - \"namespaces\" - \"endpoints\" verbs: - \"get\" - apiGroups: - \"\" - resources: - \"services\" - \"namespaces\" - \"endpoints\" - verbs: - \"get\" --- kind: ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1"} {"_id":"doc-en-kubernetes-6cec40a21d798ca2450b43589e1a123593b95f0d90c8dfe9d8947b929a229c9b","title":"","text":"k8s-app: elasticsearch-logging addonmanager.kubernetes.io/mode: Reconcile subjects: - kind: ServiceAccount name: elasticsearch-logging namespace: kube-system apiGroup: \"\" - kind: ServiceAccount name: elasticsearch-logging namespace: kube-system apiGroup: \"\" roleRef: kind: ClusterRole name: elasticsearch-logging"} {"_id":"doc-en-kubernetes-dfb747819a3c462f50f0020adf725cff9a6cc8c85d3d35e846140201a05b1c88","title":"","text":"selector: matchLabels: k8s-app: elasticsearch-logging version: v7.4.2 version: v7.4.2-1 template: metadata: labels: k8s-app: elasticsearch-logging version: v7.4.2 version: v7.4.2-1 spec: serviceAccountName: elasticsearch-logging containers: - image: quay.io/fluentd_elasticsearch/elasticsearch:v7.4.2 name: elasticsearch-logging imagePullPolicy: Always resources: # need more cpu upon initialization, therefore burstable class limits: cpu: 1000m memory: 3Gi requests: cpu: 100m memory: 3Gi ports: - containerPort: 9200 name: db protocol: TCP - containerPort: 9300 name: transport protocol: TCP livenessProbe: tcpSocket: port: transport initialDelaySeconds: 5 timeoutSeconds: 10 readinessProbe: tcpSocket: port: transport initialDelaySeconds: 5 timeoutSeconds: 10 volumeMounts: - name: elasticsearch-logging mountPath: /data env: - name: \"NAMESPACE\" valueFrom: fieldRef: fieldPath: metadata.namespace - image: quay.io/fluentd_elasticsearch/elasticsearch:v7.4.2 name: elasticsearch-logging imagePullPolicy: Always resources: # need more cpu upon initialization, therefore burstable class limits: cpu: 1000m memory: 3Gi requests: cpu: 100m memory: 3Gi ports: - containerPort: 9200 name: db protocol: TCP - containerPort: 9300 name: transport protocol: TCP livenessProbe: tcpSocket: port: transport initialDelaySeconds: 5 timeoutSeconds: 10 readinessProbe: tcpSocket: port: transport initialDelaySeconds: 5 timeoutSeconds: 10 volumeMounts: - name: elasticsearch-logging mountPath: /data env: - name: \"NAMESPACE\" valueFrom: fieldRef: fieldPath: metadata.namespace - name: \"MINIMUM_MASTER_NODES\" value: \"1\" volumes: - name: elasticsearch-logging emptyDir: {} - name: elasticsearch-logging emptyDir: {} # Elasticsearch requires vm.max_map_count to be at least 262144. # If your OS already sets up this number to a higher value, feel free # to remove this init container. initContainers: - image: alpine:3.6 command: [\"/sbin/sysctl\", \"-w\", \"vm.max_map_count=262144\"] name: elasticsearch-logging-init securityContext: privileged: true - image: alpine:3.6 command: [\"/sbin/sysctl\", \"-w\", \"vm.max_map_count=262144\"] name: elasticsearch-logging-init securityContext: privileged: true "} {"_id":"doc-en-kubernetes-597fa427bb667e693dd3e7e8bae5bda91b50d06a8c46aa5a41f862fb625a329a","title":"","text":"\"github.com/onsi/gomega\" ) var _ = framework.KubeDescribe(\"NodeProblemDetector [NodeFeature:NodeProblemDetector]\", func() { var _ = framework.KubeDescribe(\"NodeProblemDetector [NodeFeature:NodeProblemDetector] [Serial]\", func() { const ( pollInterval = 1 * time.Second pollConsistent = 5 * time.Second"} {"_id":"doc-en-kubernetes-f6585f96f20dcb1667beed1c238baaa4853a61b3ca925fb680aef6645cb88b31","title":"","text":"\"//staging/src/k8s.io/apimachinery/pkg/api/resource:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/errors:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library\", \"//staging/src/k8s.io/apiserver/pkg/util/feature:go_default_library\", \"//staging/src/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1:go_default_library\", \"//staging/src/k8s.io/kubelet/pkg/apis/pluginregistration/v1:go_default_library\","} {"_id":"doc-en-kubernetes-bea2a8409f3006d493a436f7213f993bf09685f352d3d92fbfc904848c78853a","title":"","text":"\"google.golang.org/grpc\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/klog/v2\" pluginapi \"k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1\" watcherapi \"k8s.io/kubelet/pkg/apis/pluginregistration/v1\""} {"_id":"doc-en-kubernetes-250df65cfc55c23453b7d69fe3b9ef4a79156134d9c1e30468337d1fe0c0cb97","title":"","text":"defer m.wg.Done() m.server.Serve(sock) }() _, conn, err := dial(m.socket) if err != nil { return err var lastDialErr error wait.PollImmediate(1*time.Second, 10*time.Second, func() (bool, error) { var conn *grpc.ClientConn _, conn, lastDialErr = dial(m.socket) if lastDialErr != nil { return false, nil } conn.Close() return true, nil }) if lastDialErr != nil { return lastDialErr } conn.Close() klog.Infof(\"Starting to serve on %v\", m.socket) return nil"} {"_id":"doc-en-kubernetes-79995acd2d6b8eef42217802ad36308670a372e69f3b1f71c3f8aa2150dce3e2","title":"","text":"} defer monitoring.CleanupDescriptors(gcmService, projectID) err = monitoring.CreateAdapter(tc.framework.Namespace.ObjectMeta.Name, monitoring.AdapterDefault) err = monitoring.CreateAdapter(monitoring.AdapterDefault) if err != nil { framework.Failf(\"Failed to set up: %v\", err) } defer monitoring.CleanupAdapter(tc.framework.Namespace.ObjectMeta.Name, monitoring.AdapterDefault) defer monitoring.CleanupAdapter(monitoring.AdapterDefault) // Run application that exports the metric err = createDeploymentToScale(tc.framework, tc.kubeClient, tc.deployment, tc.pod)"} {"_id":"doc-en-kubernetes-01b5e93136c029e7016d91bdfac2407e8944d0ee4f8d7f228a65e64e5b94c62d","title":"","text":"// CreateAdapter creates Custom Metrics - Stackdriver adapter // adapterDeploymentFile should be a filename for adapter deployment located in StagingDeploymentLocation func CreateAdapter(namespace, adapterDeploymentFile string) error { func CreateAdapter(adapterDeploymentFile string) error { // A workaround to make the work on GKE. GKE doesn't normally allow to create cluster roles, // which the adapter deployment does. The solution is to create cluster role binding for // cluster-admin role and currently used service account. err := createClusterAdminBinding(namespace) err := createClusterAdminBinding() if err != nil { return err }"} {"_id":"doc-en-kubernetes-1cfa3d6b74b9d2949fafb341be3cd4ddbd4a201f56a7d3e48667e2a1e328622a","title":"","text":"if err != nil { return err } stat, err := framework.RunKubectl(namespace, \"create\", \"-f\", adapterURL) stat, err := framework.RunKubectl(\"\", \"create\", \"-f\", adapterURL) framework.Logf(stat) return err } func createClusterAdminBinding(namespace string) error { func createClusterAdminBinding() error { stdout, stderr, err := framework.RunCmd(\"gcloud\", \"config\", \"get-value\", \"core/account\") if err != nil { framework.Logf(stderr)"} {"_id":"doc-en-kubernetes-cb321b88dfe98c12df0cc32606e4c9bae44c292331ce7d80f670ad86579eeb2b","title":"","text":"} serviceAccount := strings.TrimSpace(stdout) framework.Logf(\"current service account: %q\", serviceAccount) stat, err := framework.RunKubectl(namespace, \"create\", \"clusterrolebinding\", ClusterAdminBinding, \"--clusterrole=cluster-admin\", \"--user=\"+serviceAccount) stat, err := framework.RunKubectl(\"\", \"create\", \"clusterrolebinding\", ClusterAdminBinding, \"--clusterrole=cluster-admin\", \"--user=\"+serviceAccount) framework.Logf(stat) return err }"} {"_id":"doc-en-kubernetes-716999b38246af4c9270b6160848053ed7fc15884b244ce0fe1dcb9d94f46b3f","title":"","text":"} // CleanupAdapter deletes Custom Metrics - Stackdriver adapter deployments. func CleanupAdapter(namespace, adapterDeploymentFile string) { stat, err := framework.RunKubectl(namespace, \"delete\", \"-f\", adapterDeploymentFile) func CleanupAdapter(adapterDeploymentFile string) { stat, err := framework.RunKubectl(\"\", \"delete\", \"-f\", adapterDeploymentFile) framework.Logf(stat) if err != nil { framework.Logf(\"Failed to delete adapter deployments: %s\", err)"} {"_id":"doc-en-kubernetes-ffadf208832ed9b44182bdcdb9d4cadf431b7f2f48d87bb5ec5356359efc00c7","title":"","text":"if err != nil { framework.Logf(\"Failed to delete adapter deployment file: %s\", err) } cleanupClusterAdminBinding(namespace) cleanupClusterAdminBinding() } func cleanupClusterAdminBinding(namespace string) { stat, err := framework.RunKubectl(namespace, \"delete\", \"clusterrolebinding\", ClusterAdminBinding) func cleanupClusterAdminBinding() { stat, err := framework.RunKubectl(\"\", \"delete\", \"clusterrolebinding\", ClusterAdminBinding) framework.Logf(stat) if err != nil { framework.Logf(\"Failed to delete cluster admin binding: %s\", err)"} {"_id":"doc-en-kubernetes-d23f797cc7123e7970e949643b11654b86ac75c755afb78e3e8b91604dbb899c","title":"","text":"} defer CleanupDescriptors(gcmService, projectID) err = CreateAdapter(f.Namespace.Name, adapterDeployment) err = CreateAdapter(adapterDeployment) if err != nil { framework.Failf(\"Failed to set up: %s\", err) } defer CleanupAdapter(f.Namespace.Name, adapterDeployment) defer CleanupAdapter(adapterDeployment) _, err = kubeClient.RbacV1().ClusterRoleBindings().Create(context.TODO(), HPAPermissions, metav1.CreateOptions{}) if err != nil {"} {"_id":"doc-en-kubernetes-799d065b91ee8da1c8ec9f07e9cf9fe7605b5729e05e7bea38d34bacd5aad24e","title":"","text":"defer CleanupDescriptors(gcmService, projectID) // Both deployments - for old and new resource model - expose External Metrics API. err = CreateAdapter(f.Namespace.Name, AdapterForOldResourceModel) err = CreateAdapter(AdapterForOldResourceModel) if err != nil { framework.Failf(\"Failed to set up: %s\", err) } defer CleanupAdapter(f.Namespace.Name, AdapterForOldResourceModel) defer CleanupAdapter(AdapterForOldResourceModel) _, err = kubeClient.RbacV1().ClusterRoleBindings().Create(context.TODO(), HPAPermissions, metav1.CreateOptions{}) if err != nil {"} {"_id":"doc-en-kubernetes-76abe931c34f1f1fcd5765bc0cc5845162cebcbe4afe8b22f6edf42808095e22","title":"","text":"if hosts.Len() > 1 { return } time.Sleep(time.Duration(svcSessionAffinityTimeout) * time.Second) // In some case, ipvs didn't deleted the persistent connection after timeout expired, // use 'ipvsadm -lnc' command can found the expire time become '13171233:02' after '00:00' // // pro expire state source virtual destination // TCP 00:00 NONE 10.105.253.160:0 10.105.253.160:80 10.244.1.25:9376 // // pro expire state source virtual destination // TCP 13171233:02 NONE 10.105.253.160:0 10.105.253.160:80 10.244.1.25:9376 // // And 2 seconds later, the connection will be ensure deleted, // so we sleep 'svcSessionAffinityTimeout+5' seconds to avoid this issue. // TODO: figure out why the expired connection didn't be deleted and fix this issue in ipvs side. time.Sleep(time.Duration(svcSessionAffinityTimeout+5) * time.Second) } } framework.Fail(\"Session is sticky after reaching the timeout\")"} {"_id":"doc-en-kubernetes-33757b47ea1ba34d25cccaaad97a4ee419c44d71b486b85e5ea881fd2b531618","title":"","text":"Filter: &schedulerapi.PluginSet{ Enabled: []schedulerapi.Plugin{ {Name: nodeunschedulable.Name}, {Name: noderesources.FitName}, {Name: nodename.Name}, {Name: nodeports.Name}, {Name: tainttoleration.Name}, {Name: nodeaffinity.Name}, {Name: nodeports.Name}, {Name: noderesources.FitName}, {Name: volumerestrictions.Name}, {Name: tainttoleration.Name}, {Name: nodevolumelimits.EBSName}, {Name: nodevolumelimits.GCEPDName}, {Name: nodevolumelimits.CSIName},"} {"_id":"doc-en-kubernetes-4df03e05821930dab516a7121930694bec69c9278724dffe5d598eb4b38aa16c","title":"","text":"}, \"FilterPlugin\": { {Name: \"NodeUnschedulable\"}, {Name: \"NodeResourcesFit\"}, {Name: \"NodeName\"}, {Name: \"NodePorts\"}, {Name: \"TaintToleration\"}, {Name: \"NodeAffinity\"}, {Name: \"NodePorts\"}, {Name: \"NodeResourcesFit\"}, {Name: \"VolumeRestrictions\"}, {Name: \"TaintToleration\"}, {Name: \"EBSLimits\"}, {Name: \"GCEPDLimits\"}, {Name: \"NodeVolumeLimits\"},"} {"_id":"doc-en-kubernetes-786dd49f06dc210cd4b8c948b00997943b1e40f9575555903f5b6133704b0272","title":"","text":"ErrReasonNodeConflict ConflictReason = \"node(s) had volume node affinity conflict\" // ErrReasonNotEnoughSpace is used when a pod cannot start on a node because not enough storage space is available. ErrReasonNotEnoughSpace = \"node(s) did not have enough free storage\" // ErrReasonPVNotExist is used when a PVC can't find the bound persistent volumes\" ErrReasonPVNotExist = \"pvc(s) bound to non-existent pv(s)\" ) // BindingInfo holds a binding between PV and PVC."} {"_id":"doc-en-kubernetes-417da5ae85a0d13f4f4f7dd65056c0474a02a098870cb66552c5e14e3d00c042","title":"","text":"unboundVolumesSatisfied := true boundVolumesSatisfied := true sufficientStorage := true boundPVsFound := true defer func() { if err != nil { return"} {"_id":"doc-en-kubernetes-7ce1cb4b785eb9ff3d3cdc2abef45d836ce373e713dbfdfa7b04f5812d67ebf6","title":"","text":"if !sufficientStorage { reasons = append(reasons, ErrReasonNotEnoughSpace) } if !boundPVsFound { reasons = append(reasons, ErrReasonPVNotExist) } }() start := time.Now()"} {"_id":"doc-en-kubernetes-64f94dba4189a232c456ab3129d17a69a303e3bb3fe3cb6f5df87fb8b5200727","title":"","text":"// Check PV node affinity on bound volumes if len(boundClaims) > 0 { boundVolumesSatisfied, err = b.checkBoundClaims(boundClaims, node, podName) boundVolumesSatisfied, boundPVsFound, err = b.checkBoundClaims(boundClaims, node, podName) if err != nil { return }"} {"_id":"doc-en-kubernetes-60097aa6391a83eab7442798e92eef57635d8fe14010b0417aad925a418a6273","title":"","text":"return boundClaims, unboundClaimsDelayBinding, unboundClaimsImmediate, nil } func (b *volumeBinder) checkBoundClaims(claims []*v1.PersistentVolumeClaim, node *v1.Node, podName string) (bool, error) { func (b *volumeBinder) checkBoundClaims(claims []*v1.PersistentVolumeClaim, node *v1.Node, podName string) (bool, bool, error) { csiNode, err := b.csiNodeLister.Get(node.Name) if err != nil { // TODO: return the error once CSINode is created by default"} {"_id":"doc-en-kubernetes-bdd80cb90d065c7eb0f439b3c9925d372090108d273118a780c3b81863255c4a","title":"","text":"pvName := pvc.Spec.VolumeName pv, err := b.pvCache.GetPV(pvName) if err != nil { return false, err if _, ok := err.(*errNotFound); ok { err = nil } return true, false, err } pv, err = b.tryTranslatePVToCSI(pv, csiNode) if err != nil { return false, err return false, true, err } err = volumeutil.CheckNodeAffinity(pv, node.Labels) if err != nil { klog.V(4).Infof(\"PersistentVolume %q, Node %q mismatch for Pod %q: %v\", pvName, node.Name, podName, err) return false, nil return false, true, nil } klog.V(5).Infof(\"PersistentVolume %q, Node %q matches for Pod %q\", pvName, node.Name, podName) } klog.V(4).Infof(\"All bound volumes for Pod %q match with Node %q\", podName, node.Name) return true, nil return true, true, nil } // findMatchingVolumes tries to find matching volumes for given claims,"} {"_id":"doc-en-kubernetes-e409bc5a1c47037884da256c110224ebdf38d01783dfc69956ebe50ebad696f6","title":"","text":"}, \"bound-pvc,pv-not-exists\": { podPVCs: []*v1.PersistentVolumeClaim{boundPVC}, shouldFail: true, shouldFail: false, reasons: ConflictReasons{ErrReasonPVNotExist}, }, \"prebound-pvc\": { podPVCs: []*v1.PersistentVolumeClaim{preboundPVC},"} {"_id":"doc-en-kubernetes-d279d91b845227a688300c1fb73683c92f690a8ac7d6e1d279ae8e6431351fb7","title":"","text":"}, }, { name: \"PVC does not exist\", pod: makePod(\"pod-a\", []string{\"pvc-a\"}), node: &v1.Node{}, pvcs: []*v1.PersistentVolumeClaim{}, wantPreFilterStatus: framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"pvc-a\" not found`), }, { name: \"Part of PVCs do not exist\", pod: makePod(\"pod-a\", []string{\"pvc-a\", \"pvc-b\"}), node: &v1.Node{}, pvcs: []*v1.PersistentVolumeClaim{ makePVC(\"pvc-a\", \"pv-a\", waitSC.Name), }, wantPreFilterStatus: framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"pvc-b\" not found`), }, { name: \"immediate claims not bound\", pod: makePod(\"pod-a\", []string{\"pvc-a\"}), node: &v1.Node{},"} {"_id":"doc-en-kubernetes-c812fef16377cf1c4cf71678352b797f70c2fa940a4c698bf950857c50d97258","title":"","text":"claimsToBind: []*v1.PersistentVolumeClaim{}, podVolumesByNode: map[string]*scheduling.PodVolumes{}, }, wantFilterStatus: framework.NewStatus(framework.Error, `could not find v1.PersistentVolume \"pv-a\"`), wantFilterStatus: framework.NewStatus(framework.UnschedulableAndUnresolvable, `pvc(s) bound to non-existent pv(s)`), }, }"} {"_id":"doc-en-kubernetes-fb1dd8ab04121024e2f7ab5c70b4c5bd16a15a305702c58c272d93b3a3a8469b","title":"","text":"github.com/gogo/protobuf v1.3.1 github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e github.com/golang/mock v1.4.1 github.com/google/cadvisor v0.38.5 github.com/google/cadvisor v0.38.6 github.com/google/go-cmp v0.5.2 github.com/google/gofuzz v1.1.0 github.com/google/uuid v1.1.2"} {"_id":"doc-en-kubernetes-ebd44bc78969329cf9504f1af89a24553295935b445564c367c6aea2a6593109","title":"","text":"github.com/golangplus/fmt => github.com/golangplus/fmt v0.0.0-20150411045040-2a5d6d7d2995 github.com/golangplus/testing => github.com/golangplus/testing v0.0.0-20180327235837-af21d9c3145e github.com/google/btree => github.com/google/btree v1.0.0 github.com/google/cadvisor => github.com/google/cadvisor v0.38.5 github.com/google/cadvisor => github.com/google/cadvisor v0.38.6 github.com/google/go-cmp => github.com/google/go-cmp v0.5.2 github.com/google/gofuzz => github.com/google/gofuzz v1.1.0 github.com/google/martian => github.com/google/martian v2.1.0+incompatible"} {"_id":"doc-en-kubernetes-affe75e001dd8062ae610f7d2a21a878849aaf7ee723487a253e36b04a1b67dd","title":"","text":"github.com/golangplus/testing v0.0.0-20180327235837-af21d9c3145e/go.mod h1:0AA//k/eakGydO4jKRoRL2j92ZKSzTgj9tclaCrvXHk= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/cadvisor v0.38.5 h1:XOvqjL2+xMEuDORcLMv77NystZvQB7YgGxcKpRul/vE= github.com/google/cadvisor v0.38.5/go.mod h1:1OFB9sOOMkBdUBGCO/1SArawTnDscgMzTodacVDe8mA= github.com/google/cadvisor v0.38.6 h1:5vu8NaOqsBKF6wOxBLeDPD7hcmxfg/4I5NZGYXK7gIo= github.com/google/cadvisor v0.38.6/go.mod h1:1OFB9sOOMkBdUBGCO/1SArawTnDscgMzTodacVDe8mA= github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g="} {"_id":"doc-en-kubernetes-d0a3d8a74bc769c40ec175a9a63f08ccfa37b892c8ae53a3d116bd32fb42e7fc","title":"","text":"tryConn.Close() connParams := grpc.ConnectParams{ Backoff: backoff.Config{ BaseDelay: baseBackoffDelay, MaxDelay: maxBackoffDelay, }, Backoff: backoff.DefaultConfig, } connParams.Backoff.BaseDelay = baseBackoffDelay connParams.Backoff.MaxDelay = maxBackoffDelay gopts := []grpc.DialOption{ grpc.WithInsecure(), grpc.WithContextDialer(dialer.ContextDialer),"} {"_id":"doc-en-kubernetes-77add9c508efd687f2a4f21d4998e52b357139709d623077536060dfdf6b6857","title":"","text":"# github.com/google/btree v1.0.0 => github.com/google/btree v1.0.0 github.com/google/btree # github.com/google/btree => github.com/google/btree v1.0.0 # github.com/google/cadvisor v0.38.5 => github.com/google/cadvisor v0.38.5 # github.com/google/cadvisor v0.38.6 => github.com/google/cadvisor v0.38.6 ## explicit # github.com/google/cadvisor => github.com/google/cadvisor v0.38.5 # github.com/google/cadvisor => github.com/google/cadvisor v0.38.6 github.com/google/cadvisor/accelerators github.com/google/cadvisor/cache/memory github.com/google/cadvisor/client/v2"} {"_id":"doc-en-kubernetes-4590d0777aaa768aa638c479f6171fbf2b5b89202f5ddf0910338ee40f617a11","title":"","text":"ADD bin/pause-windows-${ARCH}.exe /pause.exe ADD bin/wincat-windows-amd64 /Windows/System32/wincat.exe # NOTE(claudiub): We're replacing the diagtrack.dll as a means to disable the # DiagTrack service (it cannot run without this DLL). We do not need this # service in the pause image and there's no reason for it to have any CPU usage. ADD windows/pause.c /Windows/System32/diagtrack.dll # NOTE(claudiub): docker buildx sets the PATH env variable to a Linux-like PATH, # which is not desirable. See: https://github.com/moby/buildkit/issues/1560 # TODO(claudiub): remove this once the issue has been resolved."} {"_id":"doc-en-kubernetes-a3cea4710c87b7166eccd11a9a04d21b3d719d9b985e6daddc00429cc544c54b","title":"","text":"], \"@io_bazel_rules_go//go/platform:windows\": [ \"//pkg/windows/service:go_default_library\", \"//vendor/golang.org/x/sys/windows:go_default_library\", ], \"//conditions:default\": [], }),"} {"_id":"doc-en-kubernetes-b68544dd5eca1bfa1bc7617569824654c58ddfb43f9cd7842cc32624d0e3def5","title":"","text":"go_test( name = \"go_default_test\", srcs = [ \"init_windows_test.go\", \"server_bootstrap_test.go\", \"server_test.go\", ],"} {"_id":"doc-en-kubernetes-a8e44da247891a7a585613061d7c062abf1467c4e5d95180a5a3f550bfb618bf","title":"","text":"package app func initForOS(service bool) error { func initForOS(service bool, priorityClass string) error { return nil }"} {"_id":"doc-en-kubernetes-80549c6bbe3367b9df1f5863b8e4836343cb387974090d13b0773205fb328242","title":"","text":"package app import ( \"fmt\" \"golang.org/x/sys/windows\" \"k8s.io/klog/v2\" \"k8s.io/kubernetes/pkg/windows/service\" )"} {"_id":"doc-en-kubernetes-43ed79d2ffe641a83d8cf042d107fee1b7246c255f88c7f38a25e7ba1888ea3d","title":"","text":"serviceName = \"kubelet\" ) func initForOS(windowsService bool) error { // getPriorityValue returns the value associated with a Windows process priorityClass // Ref: https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/setpriority-method-in-class-win32-process func getPriorityValue(priorityClassName string) uint32 { var priorityClassMap = map[string]uint32{ \"IDLE_PRIORITY_CLASS\": uint32(64), \"BELOW_NORMAL_PRIORITY_CLASS\": uint32(16384), \"NORMAL_PRIORITY_CLASS\": uint32(32), \"ABOVE_NORMAL_PRIORITY_CLASS\": uint32(32768), \"HIGH_PRIORITY_CLASS\": uint32(128), \"REALTIME_PRIORITY_CLASS\": uint32(256), } return priorityClassMap[priorityClassName] } func initForOS(windowsService bool, windowsPriorityClass string) error { priority := getPriorityValue(windowsPriorityClass) if priority == 0 { return fmt.Errorf(\"unknown priority class %s, valid ones are available at \"+ \"https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities\", windowsPriorityClass) } kubeletProcessHandle := windows.CurrentProcess() // Set the priority of the kubelet process to given priority klog.Infof(\"Setting the priority of kubelet process to %s\", windowsPriorityClass) if err := windows.SetPriorityClass(kubeletProcessHandle, priority); err != nil { return err } if windowsService { return service.InitService(serviceName) }"} {"_id":"doc-en-kubernetes-67d0996dc8baf78fa2ddd57e489b871268e2d58d5d5195ed42f1917a3bdb9185","title":"","text":" /* Copyright 2020 The Kubernetes Authors. 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. */ package app import \"testing\" func TestIsValidPriorityClass(t *testing.T) { testCases := []struct { description string priorityClassName string expectedPriorityValue uint32 }{ { description: \"Invalid Priority Class\", priorityClassName: \"myPriorityClass\", expectedPriorityValue: 0, }, { description: \"Valid Priority Class\", priorityClassName: \"IDLE_PRIORITY_CLASS\", expectedPriorityValue: uint32(64), }, } for _, test := range testCases { actualPriorityValue := getPriorityValue(test.priorityClassName) if test.expectedPriorityValue != actualPriorityValue { t.Fatalf(\"unexpected error for %s\", test.description) } } } "} {"_id":"doc-en-kubernetes-fa30af9e4066e2d2a2c801f05672cb46ac5c93678d2a7c5b1cadd21aaf609a9f","title":"","text":"// Its corresponding flag only gets registered in Windows builds. WindowsService bool // WindowsPriorityClass sets the priority class associated with the Kubelet process // Its corresponding flag only gets registered in Windows builds // The default priority class associated with any process in Windows is NORMAL_PRIORITY_CLASS. Keeping it as is // to maintain backwards compatibility. // Source: https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities WindowsPriorityClass string // remoteRuntimeEndpoint is the endpoint of remote runtime service RemoteRuntimeEndpoint string // remoteImageEndpoint is the endpoint of remote image service"} {"_id":"doc-en-kubernetes-035ff2676b6e7c49c551084d9a5d3efbc075e06b0d9c9b313792792cd11e8d99","title":"","text":"func (f *KubeletFlags) addOSFlags(fs *pflag.FlagSet) { fs.BoolVar(&f.WindowsService, \"windows-service\", f.WindowsService, \"Enable Windows Service Control Manager API integration\") // The default priority class associated with any process in Windows is NORMAL_PRIORITY_CLASS. Keeping it as is // to maintain backwards compatibility. // Source: https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities fs.StringVar(&f.WindowsPriorityClass, \"windows-priorityclass\", \"NORMAL_PRIORITY_CLASS\", \"Set the PriorityClass associated with kubelet process, the default ones are available at \"+ \"https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities\") }"} {"_id":"doc-en-kubernetes-f50713b16df0c2a80deac0f0fa8d4b578eb45d84016b919e546c3feccf4d7c9a","title":"","text":"logOption.Apply() // To help debugging, immediately log version klog.Infof(\"Version: %+v\", version.Get()) if err := initForOS(s.KubeletFlags.WindowsService); err != nil { if err := initForOS(s.KubeletFlags.WindowsService, s.KubeletFlags.WindowsPriorityClass); err != nil { return fmt.Errorf(\"failed OS init: %v\", err) } if err := run(ctx, s, kubeDeps, featureGate); err != nil {"} {"_id":"doc-en-kubernetes-20e5ffe3cedc8edccd68f0c3ba5c750058f067793d859afa6916ea52c895c5ea","title":"","text":"deps = [ \"//pkg/api/pod:go_default_library\", \"//pkg/apis/core:go_default_library\", \"//staging/src/k8s.io/api/core/v1:go_default_library\", \"//staging/src/k8s.io/apimachinery/pkg/util/validation/field:go_default_library\", ], )"} {"_id":"doc-en-kubernetes-71638470ec5621dce65289dcf4cedbda678d9c3530a163b7c54e4e6146ac7a1d","title":"","text":"\"fmt\" \"strings\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/util/validation/field\" podutil \"k8s.io/kubernetes/pkg/api/pod\" api \"k8s.io/kubernetes/pkg/apis/core\""} {"_id":"doc-en-kubernetes-3155bad31726e97f8cdb2880cef4447f5f48ad64a995b025539e1aa62e7e6fec","title":"","text":"allowAnyProfile = true continue } // With the graduation of seccomp to GA we automatically convert // the deprecated seccomp profile annotation `docker/default` to // `runtime/default`. This means that we now have to automatically // allow `runtime/default` if a user specifies `docker/default` and // vice versa in a PSP. if p == v1.DeprecatedSeccompProfileDockerDefault || p == v1.SeccompProfileRuntimeDefault { allowedProfiles[v1.SeccompProfileRuntimeDefault] = true allowedProfiles[v1.DeprecatedSeccompProfileDockerDefault] = true } allowedProfiles[p] = true } }"} {"_id":"doc-en-kubernetes-c041b1354037365250b7b1f6c925f5010636ba46e7b3caed682069ee1af83ab1","title":"","text":"\"strings\" \"testing\" \"k8s.io/api/core/v1\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" api \"k8s.io/kubernetes/pkg/apis/core\" )"} {"_id":"doc-en-kubernetes-2339a5471bd5f249f2fcd47bc3df539498d8c6151c1753365bb66f5c6d2dc5c7","title":"","text":"allowSpecificLocalhost = map[string]string{ AllowedProfilesAnnotationKey: v1.SeccompLocalhostProfileNamePrefix + \"foo\", } allowSpecificDockerDefault = map[string]string{ AllowedProfilesAnnotationKey: v1.DeprecatedSeccompProfileDockerDefault, } allowSpecificRuntimeDefault = map[string]string{ AllowedProfilesAnnotationKey: v1.SeccompProfileRuntimeDefault, } ) func TestNewStrategy(t *testing.T) {"} {"_id":"doc-en-kubernetes-dc2cb82f7b8aefd123dc1ea35f1456f023205a13f4a2874aee5b9a772f22347e","title":"","text":"}, expectedError: \"\", }, \"docker/default PSP annotation automatically allows runtime/default pods\": { pspAnnotations: allowSpecificDockerDefault, podAnnotations: map[string]string{ api.SeccompPodAnnotationKey: v1.SeccompProfileRuntimeDefault, }, expectedError: \"\", }, \"runtime/default PSP annotation automatically allows docker/default pods\": { pspAnnotations: allowSpecificRuntimeDefault, podAnnotations: map[string]string{ api.SeccompPodAnnotationKey: v1.DeprecatedSeccompProfileDockerDefault, }, expectedError: \"\", }, } for k, v := range tests { pod := &api.Pod{"} {"_id":"doc-en-kubernetes-b5269bfd3f39f15369b0475e9e7c0248e884d295b6d253ae9d8a39cd75da6829","title":"","text":"codename: '[sig-cli] Kubectl client Kubectl server-side dry-run should check if kubectl can dry-run update Pods [Conformance]' description: The command 'kubectl run' must create a pod with the specified image name. After, the command 'kubectl replace --dry-run=server' should update the Pod with the new image name and server-side dry-run enabled. The image name must not change. name. After, the command 'kubectl patch pod -p {...} --dry-run=server' should update the Pod with the new image name and server-side dry-run enabled. The image name must not change. release: v1.19 file: test/e2e/kubectl/kubectl.go - testname: Kubectl, version"} {"_id":"doc-en-kubernetes-d1072b079b78fe99262294a4553641f0245454beaa78e7b1406891c313fde4f4","title":"","text":"/* Release: v1.19 Testname: Kubectl, server-side dry-run Pod Description: The command 'kubectl run' must create a pod with the specified image name. After, the command 'kubectl replace --dry-run=server' should update the Pod with the new image name and server-side dry-run enabled. The image name must not change. Description: The command 'kubectl run' must create a pod with the specified image name. After, the command 'kubectl patch pod -p {...} --dry-run=server' should update the Pod with the new image name and server-side dry-run enabled. The image name must not change. */ framework.ConformanceIt(\"should check if kubectl can dry-run update Pods\", func() { ginkgo.By(\"running the image \" + httpdImage)"} {"_id":"doc-en-kubernetes-3b7159788bef5b21f79fa84bcc7add619f41741a3d1313eef92fc9b487953700","title":"","text":"framework.RunKubectlOrDie(ns, \"run\", podName, \"--image=\"+httpdImage, \"--labels=run=\"+podName) ginkgo.By(\"replace the image in the pod with server-side dry-run\") podJSON := framework.RunKubectlOrDie(ns, \"get\", \"pod\", podName, \"-o\", \"json\") podJSON = strings.Replace(podJSON, httpdImage, busyboxImage, 1) if !strings.Contains(podJSON, busyboxImage) { framework.Failf(\"Failed replacing image from %s to %s in:n%sn\", httpdImage, busyboxImage, podJSON) } framework.RunKubectlOrDieInput(ns, podJSON, \"replace\", \"-f\", \"-\", \"--dry-run=server\") specImage := fmt.Sprintf(`{\"spec\":{\"containers\":[{\"name\": \"%s\",\"image\": \"%s\"}]}}`, podName, busyboxImage) framework.RunKubectlOrDie(ns, \"patch\", \"pod\", podName, \"-p\", specImage, \"--dry-run=server\") ginkgo.By(\"verifying the pod \" + podName + \" has the right image \" + httpdImage) pod, err := c.CoreV1().Pods(ns).Get(context.TODO(), podName, metav1.GetOptions{})"} {"_id":"doc-en-kubernetes-4e95dba7e34862515c7403054c779952dd30a5f53e80dcda87c1a7086719aca7","title":"","text":"}, // TODO: Figure out the correct value for the buffer size. incoming: make(chan watchCacheEvent, 100), dispatchTimeoutBudget: newTimeBudget(stopCh), dispatchTimeoutBudget: newTimeBudget(), // We need to (potentially) stop both: // - wait.Until go-routine // - reflector.ListAndWatch"} {"_id":"doc-en-kubernetes-2b19392ff5ac70c89696b3e2430f7cdcd4d2ae3907e593cbc09dbbec177e41ed","title":"","text":"import ( \"sync\" \"time\" \"k8s.io/apimachinery/pkg/util/clock\" ) const ("} {"_id":"doc-en-kubernetes-c72efe9b3cd3f72d004a24c6c20e01e0474dd21021e7aa418f050c2ba9654cd2","title":"","text":"type timeBudgetImpl struct { sync.Mutex budget time.Duration refresh time.Duration clock clock.Clock budget time.Duration maxBudget time.Duration refresh time.Duration // last store last access time last time.Time } func newTimeBudget(stopCh <-chan struct{}) timeBudget { func newTimeBudget() timeBudget { result := &timeBudgetImpl{ clock: clock.RealClock{}, budget: time.Duration(0), refresh: refreshPerSecond, maxBudget: maxBudget, } go result.periodicallyRefresh(stopCh) result.last = result.clock.Now() return result } func (t *timeBudgetImpl) periodicallyRefresh(stopCh <-chan struct{}) { ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ticker.C: t.Lock() if t.budget = t.budget + t.refresh; t.budget > t.maxBudget { t.budget = t.maxBudget } t.Unlock() case <-stopCh: return } } } func (t *timeBudgetImpl) takeAvailable() time.Duration { t.Lock() defer t.Unlock() // budget accumulated since last access now := t.clock.Now() acc := now.Sub(t.last).Seconds() * t.refresh.Seconds() if acc < 0 { acc = 0 } // update current budget and store the current time if t.budget = t.budget + time.Duration(acc*1e9); t.budget > t.maxBudget { t.budget = t.maxBudget } t.last = now result := t.budget t.budget = time.Duration(0) return result"} {"_id":"doc-en-kubernetes-d64b8ede27d025fa747c00efc05aaa725660d8dfd846b635ef9fe723268b6c57","title":"","text":"// We used more than allowed. return } // add the unused time directly to the budget // takeAvailable() will take into account the elapsed time if t.budget = t.budget + unused; t.budget > t.maxBudget { t.budget = t.maxBudget }"} {"_id":"doc-en-kubernetes-6da24a6e861c2a4c1bc075f7b8e48be09d2f2db2fa51a56fcfb4fd4bbc2fc1c2","title":"","text":"import ( \"testing\" \"time\" \"k8s.io/apimachinery/pkg/util/clock\" ) func TestTimeBudget(t *testing.T) { fakeClock := clock.NewFakeClock(time.Now()) budget := &timeBudgetImpl{ clock: fakeClock, budget: time.Duration(0), maxBudget: time.Duration(200), maxBudget: 200 * time.Millisecond, refresh: 50 * time.Millisecond, last: fakeClock.Now(), } if res := budget.takeAvailable(); res != time.Duration(0) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(0), res) } budget.budget = time.Duration(100) if res := budget.takeAvailable(); res != time.Duration(100) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(100), res) // wait for longer than the maxBudget nextTime := time.Now().Add(10 * time.Second) fakeClock.SetTime(nextTime) if res := budget.takeAvailable(); res != budget.maxBudget { t.Errorf(\"Expected: %v, got: %v\", budget.maxBudget, res) } // add two refresh intervals to accumulate 2*refresh durations nextTime = nextTime.Add(2 * time.Second) fakeClock.SetTime(nextTime) if res := budget.takeAvailable(); res != 2*budget.refresh { t.Errorf(\"Expected: %v, got: %v\", 2*budget.refresh, res) } // return one refresh duration to have only one refresh duration available // we didn't advanced on time yet budget.returnUnused(budget.refresh) if res := budget.takeAvailable(); res != budget.refresh { t.Errorf(\"Expected: %v, got: %v\", budget.refresh, res) } // return a negative value to the budget // we didn't advanced on time yet budget.returnUnused(-time.Duration(50)) if res := budget.takeAvailable(); res != time.Duration(0) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(0), res) } budget.returnUnused(time.Duration(50)) if res := budget.takeAvailable(); res != time.Duration(50) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(50), res) // handle back in time problem with an empty budget nextTime = nextTime.Add(-2 * time.Minute) fakeClock.SetTime(nextTime) if res := budget.takeAvailable(); res != time.Duration(0) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(0), res) } budget.budget = time.Duration(100) budget.returnUnused(-time.Duration(50)) if res := budget.takeAvailable(); res != time.Duration(100) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(100), res) // wait for longer than the maxBudget // verify that adding a negative value didn't affected nextTime = nextTime.Add(10 * time.Minute) fakeClock.SetTime(nextTime) if res := budget.takeAvailable(); res != budget.maxBudget { t.Errorf(\"Expected: %v, got: %v\", budget.maxBudget, res) } // test overflow. budget.returnUnused(time.Duration(500)) if res := budget.takeAvailable(); res != time.Duration(200) { t.Errorf(\"Expected: %v, got: %v\", time.Duration(200), res) // handle back in time problem with time on the budget budget.returnUnused(10 * time.Second) nextTime = nextTime.Add(-2 * time.Minute) fakeClock.SetTime(nextTime) if res := budget.takeAvailable(); res != budget.maxBudget { t.Errorf(\"Expected: %v, got: %v\", budget.maxBudget, res) } }"} {"_id":"doc-en-kubernetes-387dc25beb30808b81914280f98bf28f62f73a46493f51a40687b501f21c325c","title":"","text":"var ( dInfo = driver.GetDriverInfo() cs clientset.Interface l *stressTest ) // Check preconditions before setting up namespace via framework below. ginkgo.BeforeEach(func() { // Check preconditions. if dInfo.StressTestOptions == nil { e2eskipper.Skipf(\"Driver %s doesn't specify stress test options -- skipping\", dInfo.Name) }"} {"_id":"doc-en-kubernetes-bdd2dcb7e73dffa4d2a95d287f0a1bedb89f20c3a5ffab5b5a044e4e7e69a91b","title":"","text":"// f must run inside an It or Context callback. f := framework.NewDefaultFramework(\"stress\") init := func() *stressTest { init := func() { cs = f.ClientSet l := &stressTest{} l = &stressTest{} // Now do the more expensive test initialization. l.config, l.driverCleanup = driver.PrepareTest(f)"} {"_id":"doc-en-kubernetes-f41697e1047dbd54bc7a64c0bbb0964d659c62e66a9131b3bb1de6cf12229aa1","title":"","text":"l.pods = []*v1.Pod{} l.testOptions = *dInfo.StressTestOptions l.ctx, l.cancel = context.WithCancel(context.Background()) } return l createPodsAndVolumes := func() { for i := 0; i < l.testOptions.NumPods; i++ { framework.Logf(\"Creating resources for pod %v/%v\", i, l.testOptions.NumPods-1) r := CreateVolumeResource(driver, l.config, pattern, t.GetTestSuiteInfo().SupportedSizeRange) l.resources = append(l.resources, r) podConfig := e2epod.Config{ NS: f.Namespace.Name, PVCs: []*v1.PersistentVolumeClaim{r.Pvc}, SeLinuxLabel: e2epv.SELinuxLabel, } pod, err := e2epod.MakeSecPod(&podConfig) framework.ExpectNoError(err) l.pods = append(l.pods, pod) } } cleanup := func(l *stressTest) { cleanup := func() { var errs []error framework.Logf(\"Stopping and waiting for all test routines to finish\")"} {"_id":"doc-en-kubernetes-463ca9ea546e9830d78d9ac1d3ab687f99e7f8348481d170b9266d976aa5e539","title":"","text":"l.migrationCheck.validateMigrationVolumeOpCounts() } ginkgo.It(\"multiple pods should access different volumes repeatedly [Slow] [Serial]\", func() { l := init() defer func() { cleanup(l) }() for i := 0; i < l.testOptions.NumPods; i++ { framework.Logf(\"Creating resources for pod %v/%v\", i, l.testOptions.NumPods-1) r := CreateVolumeResource(driver, l.config, pattern, t.GetTestSuiteInfo().SupportedSizeRange) l.resources = append(l.resources, r) podConfig := e2epod.Config{ NS: f.Namespace.Name, PVCs: []*v1.PersistentVolumeClaim{r.Pvc}, SeLinuxLabel: e2epv.SELinuxLabel, } pod, err := e2epod.MakeSecPod(&podConfig) framework.ExpectNoError(err) ginkgo.BeforeEach(func() { init() createPodsAndVolumes() }) l.pods = append(l.pods, pod) } f.AddAfterEach(\"cleanup\", func(f *framework.Framework, failed bool) { cleanup() }) ginkgo.It(\"multiple pods should access different volumes repeatedly [Slow] [Serial]\", func() { // Restart pod repeatedly for i := 0; i < l.testOptions.NumPods; i++ { podIndex := i"} {"_id":"doc-en-kubernetes-8724142d7f74331610ed981eee1334c70b31cbc2f06437503e5d2a2397f59696","title":"","text":"CaptureStderr bool // If false, whitespace in std{err,out} will be removed. PreserveWhitespace bool Quiet bool } // ExecWithOptions executes a command in the specified container, // returning stdout, stderr and error. `options` allowed for // additional parameters to be passed. func (f *Framework) ExecWithOptions(options ExecOptions) (string, string, error) { Logf(\"ExecWithOptions %+v\", options) if !options.Quiet { Logf(\"ExecWithOptions %+v\", options) } config, err := LoadConfig() ExpectNoError(err, \"failed to load restclient config\")"} {"_id":"doc-en-kubernetes-e57e3ed6b18d7d2885a3577ee01e465aa8538b54fc7f3a77c9ee10f0f2985d00","title":"","text":"s.Lock() defer s.Unlock() for i := begin; i <= end; i++ { s.used.SetBit(&s.used, i, 0) s.allocatedCIDRs-- cidrSetReleases.WithLabelValues(s.label).Inc() // Only change the counters if we change the bit to prevent // double counting. if s.used.Bit(i) != 0 { s.used.SetBit(&s.used, i, 0) s.allocatedCIDRs-- cidrSetReleases.WithLabelValues(s.label).Inc() } } cidrSetUsage.WithLabelValues(s.label).Set(float64(s.allocatedCIDRs) / float64(s.maxCIDRs)) return nil } // Occupy marks the given CIDR range as used. Occupy does not check if the CIDR // Occupy marks the given CIDR range as used. Occupy succeeds even if the CIDR // range was previously used. func (s *CidrSet) Occupy(cidr *net.IPNet) (err error) { begin, end, err := s.getBeginingAndEndIndices(cidr)"} {"_id":"doc-en-kubernetes-1739f52cbfd391c51925df3914356673836858a308b509ae761fb7cc35fce8f4","title":"","text":"s.Lock() defer s.Unlock() for i := begin; i <= end; i++ { s.used.SetBit(&s.used, i, 1) s.allocatedCIDRs++ cidrSetAllocations.WithLabelValues(s.label).Inc() // Only change the counters if we change the bit to prevent // double counting. if s.used.Bit(i) == 0 { s.used.SetBit(&s.used, i, 1) s.allocatedCIDRs++ cidrSetAllocations.WithLabelValues(s.label).Inc() } } cidrSetUsage.WithLabelValues(s.label).Set(float64(s.allocatedCIDRs) / float64(s.maxCIDRs))"} {"_id":"doc-en-kubernetes-7041161c0742d1ef2376235d7d61d78b6557cd637a9d311c8596c98928012365","title":"","text":"for i := numCIDRs / 2; i < numCIDRs; i++ { a.Occupy(cidrs[i]) } // occupy the first of the last 128 again a.Occupy(cidrs[numCIDRs/2]) // allocate the first 128 CIDRs again var rcidrs []*net.IPNet"} {"_id":"doc-en-kubernetes-e33d0cda76c7f3f98db24a569bd43a661c19820fd662d14639727153147f458c","title":"","text":"} } func TestDoubleOccupyRelease(t *testing.T) { // Run a sequence of operations and check the number of occupied CIDRs // after each one. clusterCIDRStr := \"10.42.0.0/16\" operations := []struct { cidrStr string operation string numOccupied int }{ // Occupy 1 element: +1 { cidrStr: \"10.42.5.0/24\", operation: \"occupy\", numOccupied: 1, }, // Occupy 1 more element: +1 { cidrStr: \"10.42.9.0/24\", operation: \"occupy\", numOccupied: 2, }, // Occupy 4 elements overlapping with one from the above: +3 { cidrStr: \"10.42.8.0/22\", operation: \"occupy\", numOccupied: 5, }, // Occupy an already-coccupied element: no change { cidrStr: \"10.42.9.0/24\", operation: \"occupy\", numOccupied: 5, }, // Release an coccupied element: -1 { cidrStr: \"10.42.9.0/24\", operation: \"release\", numOccupied: 4, }, // Release an unoccupied element: no change { cidrStr: \"10.42.9.0/24\", operation: \"release\", numOccupied: 4, }, // Release 4 elements, only one of which is occupied: -1 { cidrStr: \"10.42.4.0/22\", operation: \"release\", numOccupied: 3, }, } // Check that there are exactly that many allocatable CIDRs after all // operations have been executed. numAllocatable24s := (1 << 8) - 3 _, clusterCIDR, _ := net.ParseCIDR(clusterCIDRStr) a, err := NewCIDRSet(clusterCIDR, 24) if err != nil { t.Fatalf(\"Error allocating CIDRSet\") } // Execute the operations for _, op := range operations { _, cidr, _ := net.ParseCIDR(op.cidrStr) switch op.operation { case \"occupy\": a.Occupy(cidr) case \"release\": a.Release(cidr) default: t.Fatalf(\"test error: unknown operation %v\", op.operation) } if a.allocatedCIDRs != op.numOccupied { t.Fatalf(\"Expected %d occupied CIDRS, got %d\", op.numOccupied, a.allocatedCIDRs) } } // Make sure that we can allocate exactly `numAllocatable24s` elements. for i := 0; i < numAllocatable24s; i++ { _, err := a.AllocateNext() if err != nil { t.Fatalf(\"Expected to be able to allocate %d CIDRS, failed after %d\", numAllocatable24s, i) } } _, err = a.AllocateNext() if err == nil { t.Fatalf(\"Expected to be able to allocate exactly %d CIDRS, got one more\", numAllocatable24s) } } func TestGetBitforCIDR(t *testing.T) { cases := []struct { clusterCIDRStr string"} {"_id":"doc-en-kubernetes-b241a5a54dea29c2931770c8c350570f988cb1f27ce64af92620712e729c106c","title":"","text":"NodeCIDRMaskSizes: []int{24, 98, 24}, }, }, { description: \"no double counting\", fakeNodeHandler: &testutil.FakeNodeHandler{ Existing: []*v1.Node{ { ObjectMeta: metav1.ObjectMeta{ Name: \"node0\", }, Spec: v1.NodeSpec{ PodCIDRs: []string{\"10.10.0.0/24\"}, }, }, { ObjectMeta: metav1.ObjectMeta{ Name: \"node1\", }, Spec: v1.NodeSpec{ PodCIDRs: []string{\"10.10.2.0/24\"}, }, }, { ObjectMeta: metav1.ObjectMeta{ Name: \"node2\", }, }, }, Clientset: fake.NewSimpleClientset(), }, allocatorParams: CIDRAllocatorParams{ ClusterCIDRs: func() []*net.IPNet { _, clusterCIDR, _ := net.ParseCIDR(\"10.10.0.0/22\") return []*net.IPNet{clusterCIDR} }(), ServiceCIDR: nil, SecondaryServiceCIDR: nil, NodeCIDRMaskSizes: []int{24}, }, expectedAllocatedCIDR: map[int]string{ 0: \"10.10.1.0/24\", }, }, } // test function testFunc := func(tc testCase) { fakeNodeInformer := getFakeNodeInformer(tc.fakeNodeHandler) nodeList, _ := tc.fakeNodeHandler.List(context.TODO(), metav1.ListOptions{}) // Initialize the range allocator. allocator, err := NewCIDRRangeAllocator(tc.fakeNodeHandler, getFakeNodeInformer(tc.fakeNodeHandler), tc.allocatorParams, nil) allocator, err := NewCIDRRangeAllocator(tc.fakeNodeHandler, fakeNodeInformer, tc.allocatorParams, nodeList) if err != nil { t.Errorf(\"%v: failed to create CIDRRangeAllocator with error %v\", tc.description, err) return"} {"_id":"doc-en-kubernetes-bc66c4c654f9e68f69492944702f6712645980e8628c289f5def48027031db0e","title":"","text":"t.Fatalf(\"%v: unexpected error when occupying CIDR %v: %v\", tc.description, allocated, err) } } if err := allocator.AllocateOrOccupyCIDR(tc.fakeNodeHandler.Existing[0]); err != nil { t.Errorf(\"%v: unexpected error in AllocateOrOccupyCIDR: %v\", tc.description, err) } updateCount := 0 for _, node := range tc.fakeNodeHandler.Existing { if node.Spec.PodCIDRs == nil { updateCount++ } if err := waitForUpdatedNodeWithTimeout(tc.fakeNodeHandler, 1, wait.ForeverTestTimeout); err != nil { t.Fatalf(\"%v: timeout while waiting for Node update: %v\", tc.description, err) if err := allocator.AllocateOrOccupyCIDR(node); err != nil { t.Errorf(\"%v: unexpected error in AllocateOrOccupyCIDR: %v\", tc.description, err) } } if updateCount != 1 { t.Fatalf(\"test error: all tests must update exactly one node\") } if err := waitForUpdatedNodeWithTimeout(tc.fakeNodeHandler, updateCount, wait.ForeverTestTimeout); err != nil { t.Fatalf(\"%v: timeout while waiting for Node update: %v\", tc.description, err) } if len(tc.expectedAllocatedCIDR) == 0 { // nothing further expected"} {"_id":"doc-en-kubernetes-c440f8bd58473c877f845101491592ace610e7f6dbfd2cbb1c9025b9012b1fbc","title":"","text":"// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +genclient:method=GetScale,verb=get,subresource=scale,result=k8s.io/api/autoscaling/v1.Scale // +genclient:method=UpdateScale,verb=update,subresource=scale,input=k8s.io/api/autoscaling/v1.Scale,result=k8s.io/api/autoscaling/v1.Scale // +genclient:method=CreateScale,verb=create,subresource=scale,input=k8s.io/api/autoscaling/v1.Scale,result=k8s.io/api/autoscaling/v1.Scale type ClusterTestType struct { metav1.TypeMeta `json:\",inline\"`"} {"_id":"doc-en-kubernetes-d11d2016ae7778c6c8abc3127a5ded270ba5118fd5c9db81b5bd4333c12d2e1d","title":"","text":"Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ClusterTestType, err error) GetScale(ctx context.Context, clusterTestTypeName string, options metav1.GetOptions) (*autoscalingv1.Scale, error) UpdateScale(ctx context.Context, clusterTestTypeName string, scale *autoscalingv1.Scale, opts metav1.UpdateOptions) (*autoscalingv1.Scale, error) CreateScale(ctx context.Context, clusterTestTypeName string, scale *autoscalingv1.Scale, opts metav1.CreateOptions) (*autoscalingv1.Scale, error) ClusterTestTypeExpansion }"} {"_id":"doc-en-kubernetes-b173c7d6a6058cff44f5682ec729db77769ab2bc03ec1ee2a0f3a55309620d9e","title":"","text":"Into(result) return } // CreateScale takes the representation of a scale and creates it. Returns the server's representation of the scale, and an error, if there is any. func (c *clusterTestTypes) CreateScale(ctx context.Context, clusterTestTypeName string, scale *autoscalingv1.Scale, opts metav1.CreateOptions) (result *autoscalingv1.Scale, err error) { result = &autoscalingv1.Scale{} err = c.client.Post(). Resource(\"clustertesttypes\"). Name(clusterTestTypeName). SubResource(\"scale\"). VersionedParams(&opts, scheme.ParameterCodec). Body(scale). Do(ctx). Into(result) return } "} {"_id":"doc-en-kubernetes-1528c86685aef489b7a361a61bb26b8f58789d312eeee9174af5e7c6793088ba","title":"","text":"} return obj.(*autoscalingv1.Scale), err } // CreateScale takes the representation of a scale and creates it. Returns the server's representation of the scale, and an error, if there is any. func (c *FakeClusterTestTypes) CreateScale(ctx context.Context, clusterTestTypeName string, scale *autoscalingv1.Scale, opts v1.CreateOptions) (result *autoscalingv1.Scale, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateSubresourceAction(clustertesttypesResource, clusterTestTypeName, \"scale\", scale), &autoscalingv1.Scale{}) if obj == nil { return nil, err } return obj.(*autoscalingv1.Scale), err } "} {"_id":"doc-en-kubernetes-e63a266cb807772a7b17955c434bdd8029a072be89b8fa37f6ef4b03c69501e9","title":"","text":"func (c *Fake$.type|publicPlural$) Create(ctx context.Context, $.type|private$Name string, $.inputType|private$ *$.inputType|raw$, opts $.CreateOptions|raw$) (result *$.resultType|raw$, err error) { obj, err := c.Fake. $if .namespaced$Invokes($.NewCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, \"$.subresourcePath$\", c.ns, $.inputType|private$), &$.resultType|raw${}) $else$Invokes($.NewRootCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, \"$.subresourcePath$\", $.inputType|private$), &$.resultType|raw${})$end$ $else$Invokes($.NewRootCreateSubresourceAction|raw$($.type|allLowercasePlural$Resource, $.type|private$Name, \"$.subresourcePath$\", $.inputType|private$), &$.resultType|raw${})$end$ if obj == nil { return nil, err }"} {"_id":"doc-en-kubernetes-b11d3455996b570fb134a9028d26fd6c69c2fdf4d95c32aee4db7d414313d460","title":"","text":"// - replaces old recommendation with the newest recommendation, // - returns {max,min} of recommendations that are not older than constraints.Scale{Up,Down}.DelaySeconds func (a *HorizontalController) stabilizeRecommendationWithBehaviors(args NormalizationArg) (int32, string, string) { recommendation := args.DesiredReplicas now := time.Now() foundOldSample := false oldSampleIndex := 0 var scaleDelaySeconds int32 var reason, message string var betterRecommendation func(int32, int32) int32 upRecommendation := args.DesiredReplicas upDelaySeconds := *args.ScaleUpBehavior.StabilizationWindowSeconds upCutoff := now.Add(-time.Second * time.Duration(upDelaySeconds)) if args.DesiredReplicas >= args.CurrentReplicas { scaleDelaySeconds = *args.ScaleUpBehavior.StabilizationWindowSeconds betterRecommendation = min reason = \"ScaleUpStabilized\" message = \"recent recommendations were lower than current one, applying the lowest recent recommendation\" } else { scaleDelaySeconds = *args.ScaleDownBehavior.StabilizationWindowSeconds betterRecommendation = max reason = \"ScaleDownStabilized\" message = \"recent recommendations were higher than current one, applying the highest recent recommendation\" } maxDelaySeconds := max(*args.ScaleUpBehavior.StabilizationWindowSeconds, *args.ScaleDownBehavior.StabilizationWindowSeconds) obsoleteCutoff := time.Now().Add(-time.Second * time.Duration(maxDelaySeconds)) downRecommendation := args.DesiredReplicas downDelaySeconds := *args.ScaleDownBehavior.StabilizationWindowSeconds downCutoff := now.Add(-time.Second * time.Duration(downDelaySeconds)) cutoff := time.Now().Add(-time.Second * time.Duration(scaleDelaySeconds)) // Calculate the upper and lower stabilization limits. for i, rec := range a.recommendations[args.Key] { if rec.timestamp.After(cutoff) { recommendation = betterRecommendation(rec.recommendation, recommendation) if rec.timestamp.After(upCutoff) { upRecommendation = min(rec.recommendation, upRecommendation) } if rec.timestamp.After(downCutoff) { downRecommendation = max(rec.recommendation, downRecommendation) } if rec.timestamp.Before(obsoleteCutoff) { if rec.timestamp.Before(upCutoff) && rec.timestamp.Before(downCutoff) { foundOldSample = true oldSampleIndex = i } } // Bring the recommendation to within the upper and lower limits (stabilize). recommendation := args.CurrentReplicas if recommendation < upRecommendation { recommendation = upRecommendation } if recommendation > downRecommendation { recommendation = downRecommendation } // Record the unstabilized recommendation. if foundOldSample { a.recommendations[args.Key][oldSampleIndex] = timestampedRecommendation{args.DesiredReplicas, time.Now()} } else { a.recommendations[args.Key] = append(a.recommendations[args.Key], timestampedRecommendation{args.DesiredReplicas, time.Now()}) } // Determine a human-friendly message. var reason, message string if args.DesiredReplicas >= args.CurrentReplicas { reason = \"ScaleUpStabilized\" message = \"recent recommendations were lower than current one, applying the lowest recent recommendation\" } else { reason = \"ScaleDownStabilized\" message = \"recent recommendations were higher than current one, applying the highest recent recommendation\" } return recommendation, reason, message }"} {"_id":"doc-en-kubernetes-2637116f1da6def603fbc75b5ce74c8479e35ad6dd9ac56c53a5c1e7d6e13ff9","title":"","text":"} func TestNormalizeDesiredReplicasWithBehavior(t *testing.T) { now := time.Now() type TestCase struct { name string key string"} {"_id":"doc-en-kubernetes-e2b26db4970538e4fd198ce19e56a8823f1ccd8abe7708b34e2051c0b58bf8eb","title":"","text":"prenormalizedDesiredReplicas: 5, expectedStabilizedReplicas: 5, expectedRecommendations: []timestampedRecommendation{ {5, time.Now()}, {5, now}, }, }, { name: \"simple scale down stabilization\", key: \"\", recommendations: []timestampedRecommendation{ {4, time.Now().Add(-2 * time.Minute)}, {5, time.Now().Add(-1 * time.Minute)}}, {4, now.Add(-2 * time.Minute)}, {5, now.Add(-1 * time.Minute)}}, currentReplicas: 100, prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 5, expectedRecommendations: []timestampedRecommendation{ {4, time.Now()}, {5, time.Now()}, {3, time.Now()}, {4, now}, {5, now}, {3, now}, }, scaleDownStabilizationWindowSeconds: 60 * 3, },"} {"_id":"doc-en-kubernetes-30d9ffe34dd5f1e1378c8765aee6dbe0e54ed48c9641a7ecd3c7b8c826b55da6","title":"","text":"name: \"simple scale up stabilization\", key: \"\", recommendations: []timestampedRecommendation{ {4, time.Now().Add(-2 * time.Minute)}, {5, time.Now().Add(-1 * time.Minute)}}, {4, now.Add(-2 * time.Minute)}, {5, now.Add(-1 * time.Minute)}}, currentReplicas: 1, prenormalizedDesiredReplicas: 7, expectedStabilizedReplicas: 4, expectedRecommendations: []timestampedRecommendation{ {4, time.Now()}, {5, time.Now()}, {7, time.Now()}, {4, now}, {5, now}, {7, now}, }, scaleUpStabilizationWindowSeconds: 60 * 5, },"} {"_id":"doc-en-kubernetes-3e97d916c04e5d06a10a5ccf6f6108db7a88937517e898d8ee44e7bd15949438","title":"","text":"name: \"no scale down stabilization\", key: \"\", recommendations: []timestampedRecommendation{ {1, time.Now().Add(-2 * time.Minute)}, {2, time.Now().Add(-1 * time.Minute)}}, {1, now.Add(-2 * time.Minute)}, {2, now.Add(-1 * time.Minute)}}, currentReplicas: 100, // to apply scaleDown delay we should have current > desired prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 3, expectedRecommendations: []timestampedRecommendation{ {1, time.Now()}, {2, time.Now()}, {3, time.Now()}, {1, now}, {2, now}, {3, now}, }, scaleUpStabilizationWindowSeconds: 60 * 5, },"} {"_id":"doc-en-kubernetes-df8f8cb1e7d17e3b54dd219f5c9241f7fd116acd99fc4d22cc8d140c5fbc1d44","title":"","text":"name: \"no scale up stabilization\", key: \"\", recommendations: []timestampedRecommendation{ {4, time.Now().Add(-2 * time.Minute)}, {5, time.Now().Add(-1 * time.Minute)}}, {4, now.Add(-2 * time.Minute)}, {5, now.Add(-1 * time.Minute)}}, currentReplicas: 1, // to apply scaleDown delay we should have current > desired prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 3, expectedRecommendations: []timestampedRecommendation{ {4, time.Now()}, {5, time.Now()}, {3, time.Now()}, {4, now}, {5, now}, {3, now}, }, scaleDownStabilizationWindowSeconds: 60 * 5, },"} {"_id":"doc-en-kubernetes-b08287475c205a3edcaaf9c2eb9ad0f2b7ca887dc51b0f2fa7fca52369e4c3bc","title":"","text":"name: \"no scale down stabilization, reuse recommendation element\", key: \"\", recommendations: []timestampedRecommendation{ {10, time.Now().Add(-10 * time.Minute)}, {9, time.Now().Add(-9 * time.Minute)}}, {10, now.Add(-10 * time.Minute)}, {9, now.Add(-9 * time.Minute)}}, currentReplicas: 100, // to apply scaleDown delay we should have current > desired prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 3, expectedRecommendations: []timestampedRecommendation{ {10, time.Now()}, {3, time.Now()}, {10, now}, {3, now}, }, }, { name: \"no scale up stabilization, reuse recommendation element\", key: \"\", recommendations: []timestampedRecommendation{ {10, time.Now().Add(-10 * time.Minute)}, {9, time.Now().Add(-9 * time.Minute)}}, {10, now.Add(-10 * time.Minute)}, {9, now.Add(-9 * time.Minute)}}, currentReplicas: 1, prenormalizedDesiredReplicas: 100, expectedStabilizedReplicas: 100, expectedRecommendations: []timestampedRecommendation{ {10, time.Now()}, {100, time.Now()}, {10, now}, {100, now}, }, }, { name: \"scale down stabilization, reuse one of obsolete recommendation element\", key: \"\", recommendations: []timestampedRecommendation{ {10, time.Now().Add(-10 * time.Minute)}, {4, time.Now().Add(-1 * time.Minute)}, {5, time.Now().Add(-2 * time.Minute)}, {9, time.Now().Add(-9 * time.Minute)}}, {10, now.Add(-10 * time.Minute)}, {4, now.Add(-1 * time.Minute)}, {5, now.Add(-2 * time.Minute)}, {9, now.Add(-9 * time.Minute)}}, currentReplicas: 100, prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 5, expectedRecommendations: []timestampedRecommendation{ {10, time.Now()}, {4, time.Now()}, {5, time.Now()}, {3, time.Now()}, {10, now}, {4, now}, {5, now}, {3, now}, }, scaleDownStabilizationWindowSeconds: 3 * 60, },"} {"_id":"doc-en-kubernetes-62e6b29150e1bfba53868a2f03cc51a1073a95361989a666ed34353ad138effd","title":"","text":"name: \"scale up stabilization, reuse one of obsolete recommendation element\", key: \"\", recommendations: []timestampedRecommendation{ {10, time.Now().Add(-100 * time.Minute)}, {6, time.Now().Add(-1 * time.Minute)}, {5, time.Now().Add(-2 * time.Minute)}, {9, time.Now().Add(-3 * time.Minute)}}, {10, now.Add(-100 * time.Minute)}, {6, now.Add(-1 * time.Minute)}, {5, now.Add(-2 * time.Minute)}, {9, now.Add(-3 * time.Minute)}}, currentReplicas: 1, prenormalizedDesiredReplicas: 100, expectedStabilizedReplicas: 5, expectedRecommendations: []timestampedRecommendation{ {100, time.Now()}, {6, time.Now()}, {5, time.Now()}, {9, time.Now()}, {100, now}, {6, now}, {5, now}, {9, now}, }, scaleUpStabilizationWindowSeconds: 300, }, { name: \"scale up and down stabilization, do not scale up when prenormalized rec goes down\", key: \"\", recommendations: []timestampedRecommendation{ {2, now.Add(-100 * time.Minute)}, {3, now.Add(-3 * time.Minute)}, }, currentReplicas: 2, prenormalizedDesiredReplicas: 1, expectedStabilizedReplicas: 2, scaleUpStabilizationWindowSeconds: 300, scaleDownStabilizationWindowSeconds: 300, }, { name: \"scale up and down stabilization, do not scale down when prenormalized rec goes up\", key: \"\", recommendations: []timestampedRecommendation{ {2, now.Add(-100 * time.Minute)}, {1, now.Add(-3 * time.Minute)}, }, currentReplicas: 2, prenormalizedDesiredReplicas: 3, expectedStabilizedReplicas: 2, scaleUpStabilizationWindowSeconds: 300, scaleDownStabilizationWindowSeconds: 300, }, } for _, tc := range tests {"} {"_id":"doc-en-kubernetes-0d7967787e1619dd687ca4605a3f5cf8b18eacb35d7bf45befa6666deca2975b","title":"","text":"} r, _, _ := hc.stabilizeRecommendationWithBehaviors(arg) assert.Equal(t, tc.expectedStabilizedReplicas, r, \"expected replicas do not match\") if !assert.Len(t, hc.recommendations[tc.key], len(tc.expectedRecommendations), \"stored recommendations differ in length\") { return } for i, r := range hc.recommendations[tc.key] { expectedRecommendation := tc.expectedRecommendations[i] assert.Equal(t, expectedRecommendation.recommendation, r.recommendation, \"stored recommendation differs at position %d\", i) if tc.expectedRecommendations != nil { if !assert.Len(t, hc.recommendations[tc.key], len(tc.expectedRecommendations), \"stored recommendations differ in length\") { return } for i, r := range hc.recommendations[tc.key] { expectedRecommendation := tc.expectedRecommendations[i] assert.Equal(t, expectedRecommendation.recommendation, r.recommendation, \"stored recommendation differs at position %d\", i) } } }) }"} {"_id":"doc-en-kubernetes-02cf663895c2457a2fcee519cc278b6214d05c93e81d7ae9beea629a65341472","title":"","text":"// ServiceBackendPort is the service port being referenced. type ServiceBackendPort struct { // Name is the name of the port on the Service. // This must be an IANA_SVC_NAME (following RFC6335). // This is a mutually exclusive setting with \"Number\". // +optional Name string"} {"_id":"doc-en-kubernetes-7ce72793de01ea8c50197cda4a20298a21706b1d9ae700b9aaf7c2d5a6538855","title":"","text":"# # $1 - server architecture kube::build::get_docker_wrapped_binaries() { local debian_iptables_version=buster-v1.3.0 local debian_iptables_version=buster-v1.4.0 local go_runner_version=buster-v2.2.2 ### If you change any of these lists, please also update DOCKERIZED_BINARIES ### in build/BUILD. And kube::golang::server_image_targets"} {"_id":"doc-en-kubernetes-5cdbb5788f625c5a5ea8066e413228ac11acbdfa975cf3cf9cb535ef9624f008","title":"","text":"# Base images - name: \"k8s.gcr.io/debian-base: dependents\" version: buster-v1.2.0 version: buster-v1.3.0 refPaths: - path: build/workspace.bzl match: tag ="} {"_id":"doc-en-kubernetes-8d6b33e73167b3502f71d2917a1264b391b5ad82a05830f677aec82cb0e7880d","title":"","text":"match: BASEIMAGE?=k8s.gcr.io/build-image/debian-base-s390x:[a-zA-Z]+-v((([0-9]+).([0-9]+).([0-9]+)(?:-([0-9a-zA-Z-]+(?:.[0-9a-zA-Z-]+)*))?)(?:+([0-9a-zA-Z-]+(?:.[0-9a-zA-Z-]+)*))?) - name: \"k8s.gcr.io/debian-iptables: dependents\" version: buster-v1.3.0 version: buster-v1.4.0 refPaths: - path: build/common.sh match: debian_iptables_version="} {"_id":"doc-en-kubernetes-2fdd158fc704b753df096aa1c0fca40d4a230660108f8582f16ee98d00373c14","title":"","text":"# Use skopeo to find these values: https://github.com/containers/skopeo # # Example # Manifest: skopeo inspect docker://gcr.io/k8s-staging-build-image/debian-base:buster-v1.2.0 # Arches: skopeo inspect --raw docker://gcr.io/k8s-staging-build-image/debian-base:buster-v1.2.0 # Manifest: skopeo inspect docker://gcr.io/k8s-staging-build-image/debian-base:buster-v1.3.0 # Arches: skopeo inspect --raw docker://gcr.io/k8s-staging-build-image/debian-base:buster-v1.3.0 _DEBIAN_BASE_DIGEST = { \"manifest\": \"sha256:ea668d3febd312e0edfbbdab6bd7d86448ddc8fddb484e20ec76b36a7aeac04c\", \"amd64\": \"sha256:2f3e61995bcd4b3a1a0aef49e4a7a6817c978031734b09df2aaaa28181898b0e\", \"arm\": \"sha256:d1073dcf8f1d55fbbd297e5b280375b6f276ea83a08a25fd59dc4f3ca43c6d50\", \"arm64\": \"sha256:dadcff1ab81177de4914f6db0e7d78a52e525daf7a1efb246cb3545de5e818d1\", \"ppc64le\": \"sha256:bfb24dc0d1e71e1deb0f04a078fadf2c94070266746b1b5acc4e739aa57d5601\", \"s390x\": \"sha256:cfe6a3508b7ee198cb5a0b3a62e0981676b1dfa4b3049f36398d03e6bd35a801\", \"manifest\": \"sha256:d66137c7c362d1026dca670d1ff4c25e5b0770e8ace87ac3d008d52e4b0db338\", \"amd64\": \"sha256:a5ab028d9a730b78af9abb15b5db9b2e6f82448ab269d6f3a07d1834c571ccc6\", \"arm\": \"sha256:94e611363760607366ca1fed9375105b6c5fc922ab1249869b708690ca13733c\", \"arm64\": \"sha256:83512c52d44587271cd0f355c0a9a7e6c2412ddc66b8a8eb98f994277297a72f\", \"ppc64le\": \"sha256:9c8284b2797b114ebe8f3f1b2b5817a9c7f07f3f82513c49a30e6191a1acc1fc\", \"s390x\": \"sha256:d617637dd4df0bc1cfa524fae3b4892cfe57f7fec9402ad8dfa28e38e82ec688\", } # Use skopeo to find these values: https://github.com/containers/skopeo # # Example # Manifest: skopeo inspect docker://gcr.io/k8s-staging-build-image/debian-iptables:buster-v1.3.0 # Arches: skopeo inspect --raw docker://gcr.io/k8s-staging-build-image/debian-iptables:buster-v1.3.0 # Manifest: skopeo inspect docker://gcr.io/k8s-staging-build-image/debian-iptables:buster-v1.4.0 # Arches: skopeo inspect --raw docker://gcr.io/k8s-staging-build-image/debian-iptables:buster-v1.4.0 _DEBIAN_IPTABLES_DIGEST = { \"manifest\": \"sha256:4c9410a4ee555dcb0e8b7bd6fc77c65ac400f7c5bd4555df8187630efaea6ea4\", \"amd64\": \"sha256:e30919918299988b318f0208e7fd264dee21a6be9d74bbd9f7fc15e78eade9b4\", \"arm\": \"sha256:bf59578f532bfd3378c4a713eeb14cf0dbed224d5ad03f549165f8d853997ca4\", \"arm64\": \"sha256:3d7ede6013b0516f1ec3852590895d4a7b6ec8f5e15bebc1a55237bba4538da2\", \"ppc64le\": \"sha256:ebd3bb280f8da8fc6a7158b7c2fc59b4552487bffd95d0b5ac1b190aff7b0fd9\", \"s390x\": \"sha256:a73b94aace7a571f36149aa917d4c7ee13453ed24a31f26549dd13b386dae4c1\", \"manifest\": \"sha256:87f97cf2b62eb107871ee810f204ccde41affb70b29883aa898e93df85dea0f0\", \"amd64\": \"sha256:da837f39cf3af78adb796c0caa9733449ae99e51cf624590c328e4c9951ace7a\", \"arm\": \"sha256:bb6677337a4dbc3e578a3e87642d99be740dea391dc5e8987f04211c5e23abcd\", \"arm64\": \"sha256:6ad4717d69db2cc47bc2efc91cebb96ba736be1de49e62e0deffdbaf0fa2318c\", \"ppc64le\": \"sha256:168ccfeb861239536826a26da24ab5f68bb5349d7439424b7008b01e8f6534fc\", \"s390x\": \"sha256:5a88d4f4c29bac5b5c93195059b928f7346be11d0f0f7f6da0e14c0bfdbd1362\", } # Use skopeo to find these values: https://github.com/containers/skopeo"} {"_id":"doc-en-kubernetes-ee58705982463e1f52613cbcbba0705af6511bfba88f1e9af61810505fcd21b6","title":"","text":"registry = \"k8s.gcr.io/build-image\", repository = \"debian-base\", # Ensure the digests above are updated to match a new tag tag = \"buster-v1.2.0\", # ignored, but kept here for documentation tag = \"buster-v1.3.0\", # ignored, but kept here for documentation ) container_pull("} {"_id":"doc-en-kubernetes-d4dc999209c82a8e3d57efd66854ea3a8cad3710cc7f416879ae3b9aeb219d38","title":"","text":"registry = \"k8s.gcr.io/build-image\", repository = \"debian-iptables\", # Ensure the digests above are updated to match a new tag tag = \"buster-v1.3.0\", # ignored, but kept here for documentation tag = \"buster-v1.4.0\", # ignored, but kept here for documentation ) def etcd_tarballs():"} {"_id":"doc-en-kubernetes-051dbe72c7789a027765fbd468bbb1f37546d38d0c71efb2c9468b1c4f565a66","title":"","text":"# REVISION provides a version number fo this image and all it's bundled # artifacts. It should start at zero for each LATEST_ETCD_VERSION and increment # for each revision of this image at that etcd version. REVISION?=1 REVISION?=2 # IMAGE_TAG Uniquely identifies k8s.gcr.io/etcd docker image with a tag of the form \"-\". IMAGE_TAG=$(LATEST_ETCD_VERSION)-$(REVISION)"} {"_id":"doc-en-kubernetes-ef065098a6861e36cc290b00affd91094664fb83f70fa8637117405dda16ad5c","title":"","text":"TEMP_DIR:=$(shell mktemp -d) ifeq ($(ARCH),amd64) BASEIMAGE?=k8s.gcr.io/build-image/debian-base:buster-v1.2.0 BASEIMAGE?=k8s.gcr.io/build-image/debian-base:buster-v1.3.0 endif ifeq ($(ARCH),arm) BASEIMAGE?=k8s.gcr.io/build-image/debian-base-arm:buster-v1.2.0 BASEIMAGE?=k8s.gcr.io/build-image/debian-base-arm:buster-v1.3.0 endif ifeq ($(ARCH),arm64) BASEIMAGE?=k8s.gcr.io/build-image/debian-base-arm64:buster-v1.2.0 BASEIMAGE?=k8s.gcr.io/build-image/debian-base-arm64:buster-v1.3.0 endif ifeq ($(ARCH),ppc64le) BASEIMAGE?=k8s.gcr.io/build-image/debian-base-ppc64le:buster-v1.2.0 BASEIMAGE?=k8s.gcr.io/build-image/debian-base-ppc64le:buster-v1.3.0 endif ifeq ($(ARCH),s390x) BASEIMAGE?=k8s.gcr.io/build-image/debian-base-s390x:buster-v1.2.0 BASEIMAGE?=k8s.gcr.io/build-image/debian-base-s390x:buster-v1.3.0 endif RUNNERIMAGE?=gcr.io/distroless/static:latest"} {"_id":"doc-en-kubernetes-f220ec5c60b49aba978f11f3ace172b726e17e50d50bf26438dbb07f97fa0d62","title":"","text":"configs[CheckMetadataConcealment] = Config{e2eRegistry, \"metadata-concealment\", \"1.2\"} configs[CudaVectorAdd] = Config{e2eRegistry, \"cuda-vector-add\", \"1.0\"} configs[CudaVectorAdd2] = Config{e2eRegistry, \"cuda-vector-add\", \"2.0\"} configs[DebianIptables] = Config{buildImageRegistry, \"debian-iptables\", \"buster-v1.3.0\"} configs[DebianIptables] = Config{buildImageRegistry, \"debian-iptables\", \"buster-v1.4.0\"} configs[EchoServer] = Config{e2eRegistry, \"echoserver\", \"2.2\"} configs[Etcd] = Config{gcRegistry, \"etcd\", \"3.4.13-0\"} configs[GlusterDynamicProvisioner] = Config{dockerGluster, \"glusterdynamic-provisioner\", \"v1.0\"}"} {"_id":"doc-en-kubernetes-d2e84f5c530b33acb02fd10440e6eb3a1816b8deb06a4fdd0b8507e8eea64217","title":"","text":"// ListByResourceGroup indicates an expected call of ListByResourceGroup func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListByResourceGroup\", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListByResourceGroup\", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, resourceGroupName) }"} {"_id":"doc-en-kubernetes-2883841d5dfa343ff7ce3864c336fad2b27ebe0b27977a37849c3f0a56c187b3","title":"","text":"} func (saw *sampleAndWaterMarkHistograms) innerSet(updateXOrX1 func()) { var when time.Time var whenInt int64 var acc sampleAndWaterMarkAccumulator var wellOrdered bool func() { when, whenInt, acc, wellOrdered := func() (time.Time, int64, sampleAndWaterMarkAccumulator, bool) { saw.Lock() defer saw.Unlock() when = saw.clock.Now() whenInt = saw.quantize(when) acc = saw.sampleAndWaterMarkAccumulator wellOrdered = !when.Before(acc.lastSet) // Moved these variables here to tiptoe around https://github.com/golang/go/issues/43570 for #97685 when := saw.clock.Now() whenInt := saw.quantize(when) acc := saw.sampleAndWaterMarkAccumulator wellOrdered := !when.Before(acc.lastSet) updateXOrX1() saw.relX = saw.x / saw.x1 if wellOrdered {"} {"_id":"doc-en-kubernetes-29c37277541865e731165a8f6b72fc55609e881f04cb15f538915a6d51285536","title":"","text":"} else if saw.relX > saw.hiRelX { saw.hiRelX = saw.relX } return when, whenInt, acc, wellOrdered }() if !wellOrdered { lastSetS := acc.lastSet.String()"} {"_id":"doc-en-kubernetes-3affa45791e52bfe3d1eb963a5671aba3a95ae903571a46aef9dec1042869468","title":"","text":"// data to determine if an update is required. // 5.  A new timestamped dir is created // 6. The payload is written to the new timestamped directory // 7.  Symlinks and directory for new user-visible files are created (if needed). // 7.  A symlink to the new timestamped directory ..data_tmp is created that will // become the new data directory // 8.  The new data directory symlink is renamed to the data directory; rename is atomic // 9.  Symlinks and directory for new user-visible files are created (if needed). // // For example, consider the files: // /podName"} {"_id":"doc-en-kubernetes-a42f38ee48cecaf421b29a0f527f31b758a9af46d5070c15198798f7c1856c7a","title":"","text":"// The data directory itself is a link to a timestamped directory with // the real data: // /..data -> ..2016_02_01_15_04_05.12345678/ // 8.  A symlink to the new timestamped directory ..data_tmp is created that will // become the new data directory // 9.  The new data directory symlink is renamed to the data directory; rename is atomic // NOTE(claudiub): We need to create these symlinks AFTER we've finished creating and // linking everything else. On Windows, if a target does not exist, the created symlink // will not work properly if the target ends up being a directory. // 10. Old paths are removed from the user-visible portion of the target directory // 11.  The previous timestamped directory is removed, if it exists func (w *AtomicWriter) Write(payload map[string]FileProjection) error {"} {"_id":"doc-en-kubernetes-f200bd589409a47478e930e29b87169d8438a47c44b55776da60867ac05ea7c7","title":"","text":"klog.V(4).Infof(\"%s: performed write of new data to ts data directory: %s\", w.logContext, tsDir) // (7) if err = w.createUserVisibleFiles(cleanPayload); err != nil { klog.Errorf(\"%s: error creating visible symlinks in %s: %v\", w.logContext, w.targetDir, err) return err } // (8) newDataDirPath := filepath.Join(w.targetDir, newDataDirName) if err = os.Symlink(tsDirName, newDataDirPath); err != nil { os.RemoveAll(tsDir)"} {"_id":"doc-en-kubernetes-d8a1dee3eb1dc52bdc98e17020943ce09f65b09ab3e6f058c5be1f4445ce954d","title":"","text":"return err } // (9) // (8) if runtime.GOOS == \"windows\" { os.Remove(dataDirPath) err = os.Symlink(tsDirName, dataDirPath)"} {"_id":"doc-en-kubernetes-46793bb38083c00f3d3a6647d54b6481937d9d6995f10cf8f7b6d975d3e80abd","title":"","text":"return err } // (9) if err = w.createUserVisibleFiles(cleanPayload); err != nil { klog.Errorf(\"%s: error creating visible symlinks in %s: %v\", w.logContext, w.targetDir, err) return err } // (10) if err = w.removeUserVisiblePaths(pathsToRemove); err != nil { klog.Errorf(\"%s: error removing old visible symlinks: %v\", w.logContext, err)"} {"_id":"doc-en-kubernetes-7c1cb8726eb2bf855043a489becf52c01f5594d1b7a87ae2635b1007566ceec4","title":"","text":"\"ingressclass.go\", \"kube_proxy.go\", \"loadbalancer.go\", \"network_policy.go\", \"network_tiers.go\", \"networking.go\", \"networking_perf.go\","} {"_id":"doc-en-kubernetes-1afbddd661ace2c82e5076bfa09d3a4cc3bfce037738e01332437822517f6847","title":"","text":"\"//test/e2e/framework/service:go_default_library\", \"//test/e2e/framework/skipper:go_default_library\", \"//test/e2e/framework/ssh:go_default_library\", \"//test/e2e/network/netpol:go_default_library\", \"//test/e2e/network/scale:go_default_library\", \"//test/e2e/storage/utils:go_default_library\", \"//test/utils:go_default_library\","} {"_id":"doc-en-kubernetes-e56fd61ada25583118cb2dcb754724dc5f88d7c205f806935c7e67168679b0c3","title":"","text":" /* Copyright 2016 The Kubernetes Authors. 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. */ package network import ( \"context\" \"encoding/json\" \"fmt\" \"net\" \"strconv\" \"time\" \"github.com/onsi/ginkgo\" v1 \"k8s.io/api/core/v1\" networkingv1 \"k8s.io/api/networking/v1\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/apimachinery/pkg/watch\" \"k8s.io/kubernetes/test/e2e/framework\" e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" // synthetic import of netpol suite, until these tests are replaced entirely, so that its included properly _ \"k8s.io/kubernetes/test/e2e/network/netpol\" imageutils \"k8s.io/kubernetes/test/utils/image\" utilnet \"k8s.io/utils/net\" ) /* The following Network Policy tests verify that policy object definitions are correctly enforced by a networking plugin. It accomplishes this by launching a simple netcat server, and two clients with different attributes. Each test case creates a network policy which should only allow connections from one of the clients. The test then asserts that the clients failed or successfully connected as expected. */ type protocolPort struct { port int protocol v1.Protocol } var protocolSCTP = v1.ProtocolSCTP var _ = SIGDescribe(\"NetworkPolicy [LinuxOnly]\", func() { var service *v1.Service var podServer *v1.Pod var podServerLabelSelector string f := framework.NewDefaultFramework(\"network-policy\") ginkgo.BeforeEach(func() { // Windows does not support network policies. e2eskipper.SkipIfNodeOSDistroIs(\"windows\") }) ginkgo.Context(\"NetworkPolicy between server and client\", func() { ginkgo.BeforeEach(func() { ginkgo.By(\"Creating a simple server that serves on port 80 and 81.\") podServer, service = createServerPodAndService(f, f.Namespace, \"server\", []protocolPort{{80, v1.ProtocolTCP}, {81, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podServer.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err) }) // podServerLabelSelector holds the value for the podServer's label \"pod-name\". podServerLabelSelector = podServer.ObjectMeta.Labels[\"pod-name\"] // Create pods, which should be able to communicate with the server on port 80 and 81. ginkgo.By(\"Testing pods can connect to both ports when no policy is present.\") testCanConnect(f, f.Namespace, \"client-can-connect-80\", service, 80) testCanConnect(f, f.Namespace, \"client-can-connect-81\", service, 81) }) ginkgo.AfterEach(func() { cleanupServerPodAndService(f, podServer, service) }) ginkgo.It(\"should support a 'default-deny-ingress' policy [Feature:NetworkPolicy]\", func() { policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"deny-ingress\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{}, Ingress: []networkingv1.NetworkPolicyIngressRule{}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) // Create a pod with name 'client-cannot-connect', which will attempt to communicate with the server, // but should not be able to now that isolation is on. testCannotConnect(f, f.Namespace, \"client-cannot-connect\", service, 80) }) ginkgo.It(\"should support a 'default-deny-all' policy [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") ginkgo.By(\"Creating a simple server in another namespace that serves on port 80 and 81.\") podB, serviceB := createServerPodAndService(f, nsB, \"pod-b\", []protocolPort{{80, v1.ProtocolTCP}, {81, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podB.Name, nsB.Name, framework.PodStartTimeout) framework.ExpectNoError(err) }) ginkgo.By(\"Creating client-a, which should be able to contact the server in another namespace.\", func() { testCanConnect(f, nsA, \"client-a\", serviceB, 80) }) policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"default-deny-all\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{}, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress, networkingv1.PolicyTypeIngress}, Ingress: []networkingv1.NetworkPolicyIngressRule{}, Egress: []networkingv1.NetworkPolicyEgressRule{}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-to-a, which should not be able to contact the server in the same namespace, Ingress check.\", func() { testCannotConnect(f, nsA, \"client-to-a\", service, 80) }) ginkgo.By(\"Creating client-to-b, which should not be able to contact the server in another namespace, Egress check.\", func() { testCannotConnect(f, nsA, \"client-to-b\", serviceB, 80) }) }) ginkgo.It(\"should enforce policy to allow traffic from pods within server namespace based on PodSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") // All communication should be possible before applying the policy. ginkgo.By(\"Creating client-a, in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsA, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsA, \"client-b\", service, 80) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsB, \"client-a\", service, 80) }) ginkgo.By(\"Creating a network policy for the server which allows traffic from the pod 'client-a' in same namespace.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-a-via-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only from client-a Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a, in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsA, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, in server's namespace, which should not be able to contact the server.\", func() { testCannotConnect(f, nsA, \"client-b\", service, 80) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should not be able to contact the server.\", func() { testCannotConnect(f, nsB, \"client-a\", service, 80) }) }) ginkgo.It(\"should enforce policy to allow traffic only from a different namespace, based on NamespaceSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err) // Create Server with Service in NS-B framework.Logf(\"Waiting for server to come up.\") err = e2epod.WaitForPodRunningInNamespace(f.ClientSet, podServer) framework.ExpectNoError(err) // Create Policy for that service that allows traffic only via namespace B ginkgo.By(\"Creating a network policy for the server which allows traffic from namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ns-b-via-namespace-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only from NS-B Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(nsA.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, nsA, \"client-a\", service, 80) testCanConnect(f, nsB, \"client-b\", service, 80) }) ginkgo.It(\"should enforce policy based on PodSelector with MatchExpressions[Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the server which allows traffic from the pod 'client-a'.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-a-via-pod-selector-with-match-expressions\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{{ Key: \"pod-name\", Operator: metav1.LabelSelectorOpIn, Values: []string{\"client-a\"}, }}, }, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b which should not be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-b\", service, 80) }) }) ginkgo.It(\"should enforce policy based on NamespaceSelector with MatchExpressions[Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsBName, err) nsCName := f.BaseName + \"-c\" nsC, err := f.CreateNamespace(nsCName, map[string]string{ \"ns-name\": nsCName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsCName, err) // Create Policy for the server that allows traffic from namespace different than namespace-a ginkgo.By(\"Creating a network policy for the server which allows traffic from ns different than namespace-a.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-any-ns-different-than-ns-a-via-ns-selector-with-match-expressions\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{{ Key: \"ns-name\", Operator: metav1.LabelSelectorOpNotIn, Values: []string{nsCName}, }}, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(nsA.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, nsC, \"client-a\", service, 80) testCanConnect(f, nsB, \"client-a\", service, 80) }) ginkgo.It(\"should enforce policy based on PodSelector or NamespaceSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsBName, err) // Create Policy for the server that allows traffic only via client B or namespace B ginkgo.By(\"Creating a network policy for the server which allows traffic from client-b or namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ns-b-via-namespace-selector-or-client-b-via-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-b\", }, }, }, { NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(nsA.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCanConnect(f, nsB, \"client-a\", service, 80) testCanConnect(f, nsA, \"client-b\", service, 80) testCannotConnect(f, nsA, \"client-c\", service, 80) }) ginkgo.It(\"should enforce policy based on PodSelector and NamespaceSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsBName, err) // Create Policy for the server that allows traffic only via client-b in namespace B ginkgo.By(\"Creating a network policy for the server which allows traffic from client-b in namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-b-in-ns-b-via-ns-selector-and-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-b\", }, }, NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(nsA.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, nsB, \"client-a\", service, 80) testCannotConnect(f, nsA, \"client-b\", service, 80) testCanConnect(f, nsB, \"client-b\", service, 80) }) ginkgo.It(\"should enforce policy to allow traffic only from a pod in a different namespace based on PodSelector and NamespaceSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") // Wait for Server in namespaces-a to be ready framework.Logf(\"Waiting for server to come up.\") err = e2epod.WaitForPodRunningInNamespace(f.ClientSet, podServer) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Running.\") // Before application of the policy, all communication should be successful. ginkgo.By(\"Creating client-a, in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsA, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsA, \"client-b\", service, 80) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsB, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, not in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsB, \"client-b\", service, 80) }) ginkgo.By(\"Creating a network policy for the server which allows traffic only from client-a in namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: nsA.Name, Name: \"allow-ns-b-client-a-via-namespace-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only from client-a in namespace-b Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policy.\") defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a, in server's namespace, which should not be able to contact the server.\", func() { testCannotConnect(f, nsA, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, in server's namespace, which should not be able to contact the server.\", func() { testCannotConnect(f, nsA, \"client-b\", service, 80) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should be able to contact the server.\", func() { testCanConnect(f, nsB, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b, not in server's namespace, which should not be able to contact the server.\", func() { testCannotConnect(f, nsB, \"client-b\", service, 80) }) }) ginkgo.It(\"should enforce policy based on Ports [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the Service which allows traffic only to one port.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress-on-port-81\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: 81}, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Testing pods can connect only to the port allowed by the policy.\") testCannotConnect(f, f.Namespace, \"client-a\", service, 80) testCanConnect(f, f.Namespace, \"client-b\", service, 81) }) ginkgo.It(\"should enforce multiple, stacked policies with overlapping podSelectors [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the Service which allows traffic only to one port.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress-on-port-80\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: 80}, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating a network policy for the Service which allows traffic only to another port.\") policy2 := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress-on-port-81\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: 81}, }}, }}, }, } policy2, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy2, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy2) ginkgo.By(\"Testing pods can connect to both ports when both policies are present.\") testCanConnect(f, f.Namespace, \"client-a\", service, 80) testCanConnect(f, f.Namespace, \"client-b\", service, 81) }) ginkgo.It(\"should support allow-all policy [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy which allows all traffic.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-all\", }, Spec: networkingv1.NetworkPolicySpec{ // Allow all traffic PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{}, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{}}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Testing pods can connect to both ports when an 'allow-all' policy is present.\") testCanConnect(f, f.Namespace, \"client-a\", service, 80) testCanConnect(f, f.Namespace, \"client-b\", service, 81) }) ginkgo.It(\"should allow ingress access on one named port [Feature:NetworkPolicy]\", func() { policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-a-via-named-port-ingress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic to only one named port: \"serve-80\". Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{Type: intstr.String, StrVal: \"serve-80\"}, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b which should not be able to contact the server on port 81.\", func() { testCannotConnect(f, f.Namespace, \"client-b\", service, 81) }) }) ginkgo.It(\"should allow ingress access from namespace on one named port [Feature:NetworkPolicy]\", func() { nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsBName, err) const allowedPort = 80 policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-in-ns-b-via-named-port-ingress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic to only one named port: \"serve-80\" from namespace-b. Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }}, Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{Type: intstr.String, StrVal: \"serve-80\"}, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, f.Namespace, \"client-a\", service, allowedPort) testCanConnect(f, nsB, \"client-b\", service, allowedPort) }) ginkgo.It(\"should allow egress access on one named port [Feature:NetworkPolicy]\", func() { clientPodName := \"client-a\" policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-client-a-via-named-port-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to client-a PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": clientPodName, }, }, // Allow traffic to only one named port: \"serve-80\". Egress: []networkingv1.NetworkPolicyEgressRule{{ Ports: []networkingv1.NetworkPolicyPort{ { Port: &intstr.IntOrString{Type: intstr.String, StrVal: \"serve-80\"}, }, }, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, clientPodName, service, 80) }) ginkgo.By(\"Creating client-a which should not be able to contact the server on port 81.\", func() { testCannotConnect(f, f.Namespace, clientPodName, service, 81) }) }) ginkgo.It(\"should enforce updated policy [Feature:NetworkPolicy]\", func() { const ( clientAAllowedPort = 80 clientANotAllowedPort = 81 ) ginkgo.By(\"Creating a network policy for the Service which allows traffic from pod at a port\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: clientAAllowedPort}, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) testCanConnect(f, f.Namespace, \"client-a\", service, clientAAllowedPort) e2epod.WaitForPodNotFoundInNamespace(f.ClientSet, \"client-a\", f.Namespace.Name, framework.PodDeleteTimeout) framework.ExpectNoError(err, \"Expected pod to be not found.\") testCannotConnect(f, f.Namespace, \"client-b\", service, clientAAllowedPort) e2epod.WaitForPodNotFoundInNamespace(f.ClientSet, \"client-b\", f.Namespace.Name, framework.PodDeleteTimeout) framework.ExpectNoError(err, \"Expected pod to be not found.\") testCannotConnect(f, f.Namespace, \"client-a\", service, clientANotAllowedPort) e2epod.WaitForPodNotFoundInNamespace(f.ClientSet, \"client-a\", f.Namespace.Name, framework.PodDeleteTimeout) framework.ExpectNoError(err, \"Expected pod to be not found.\") const ( clientBAllowedPort = 81 clientBNotAllowedPort = 80 ) ginkgo.By(\"Updating a network policy for the Service which allows traffic from another pod at another port.\") policy = &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-b\", }, }, }}, Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: clientBAllowedPort}, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Update(context.TODO(), policy, metav1.UpdateOptions{}) framework.ExpectNoError(err, \"Error updating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, f.Namespace, \"client-b\", service, clientBNotAllowedPort) e2epod.WaitForPodNotFoundInNamespace(f.ClientSet, \"client-b\", f.Namespace.Name, framework.PodDeleteTimeout) framework.ExpectNoError(err, \"Expected pod to be not found.\") testCannotConnect(f, f.Namespace, \"client-a\", service, clientBNotAllowedPort) testCanConnect(f, f.Namespace, \"client-b\", service, clientBAllowedPort) }) ginkgo.It(\"should allow ingress access from updated namespace [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" newNsBName := nsBName + \"-updated\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error creating namespace %v: %v\", nsBName, err) const allowedPort = 80 // Create Policy for that service that allows traffic only via namespace B ginkgo.By(\"Creating a network policy for the server which allows traffic from namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ns-b-via-namespace-selector\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": newNsBName, }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(nsA.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) testCannotConnect(f, nsB, \"client-a\", service, allowedPort) nsB, err = f.ClientSet.CoreV1().Namespaces().Get(context.TODO(), nsB.Name, metav1.GetOptions{}) framework.ExpectNoError(err, \"Error getting Namespace %v: %v\", nsB.ObjectMeta.Name, err) nsB.ObjectMeta.Labels[\"ns-name\"] = newNsBName nsB, err = f.ClientSet.CoreV1().Namespaces().Update(context.TODO(), nsB, metav1.UpdateOptions{}) framework.ExpectNoError(err, \"Error updating Namespace %v: %v\", nsB.ObjectMeta.Name, err) testCanConnect(f, nsB, \"client-b\", service, allowedPort) }) ginkgo.It(\"should allow ingress access from updated pod [Feature:NetworkPolicy]\", func() { const allowedPort = 80 ginkgo.By(\"Creating a network policy for the server which allows traffic from client-a-updated.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-pod-b-via-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchExpressions: []metav1.LabelSelectorRequirement{{ Key: \"pod-name\", Operator: metav1.LabelSelectorOpDoesNotExist, }}, }, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(fmt.Sprintf(\"Creating client pod %s that should not be able to connect to %s.\", \"client-a\", service.Name)) // Specify RestartPolicy to OnFailure so we can check the client pod fails in the beginning and succeeds // after updating its label, otherwise it would not restart after the first failure. podClient := createNetworkClientPodWithRestartPolicy(f, f.Namespace, \"client-a\", service, allowedPort, v1.ProtocolTCP, v1.RestartPolicyOnFailure) defer func() { ginkgo.By(fmt.Sprintf(\"Cleaning up the pod %s\", podClient.Name)) if err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Delete(context.TODO(), podClient.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup pod %v: %v\", podClient.Name, err) } }() // Check Container exit code as restartable Pod's Phase will be Running even when container fails. checkNoConnectivityByExitCode(f, f.Namespace, podClient, service) ginkgo.By(fmt.Sprintf(\"Updating client pod %s that should successfully connect to %s.\", podClient.Name, service.Name)) podClient = updatePodLabel(f, f.Namespace, podClient.Name, \"replace\", \"/metadata/labels\", map[string]string{}) checkConnectivity(f, f.Namespace, podClient, service) }) ginkgo.It(\"should deny ingress access to updated pod [Feature:NetworkPolicy]\", func() { const allowedPort = 80 ginkgo.By(\"Creating a network policy for the server which denies all traffic.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"deny-ingress-via-isolated-label-selector\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, MatchExpressions: []metav1.LabelSelectorRequirement{{ Key: \"isolated\", Operator: metav1.LabelSelectorOpExists, }}, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, Ingress: []networkingv1.NetworkPolicyIngressRule{}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) // Client can connect to service when the network policy doesn't apply to the server pod. testCanConnect(f, f.Namespace, \"client-a\", service, allowedPort) // Client cannot connect to service after updating the server pod's labels to match the network policy's selector. ginkgo.By(fmt.Sprintf(\"Updating server pod %s to be selected by network policy %s.\", podServer.Name, policy.Name)) updatePodLabel(f, f.Namespace, podServer.Name, \"add\", \"/metadata/labels/isolated\", nil) testCannotConnect(f, f.Namespace, \"client-a\", service, allowedPort) }) ginkgo.It(\"should work with Ingress,Egress specified together [Feature:NetworkPolicy]\", func() { const allowedPort = 80 const notAllowedPort = 81 nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") podB, serviceB := createServerPodAndService(f, nsB, \"pod-b\", []protocolPort{{allowedPort, v1.ProtocolTCP}, {notAllowedPort, v1.ProtocolTCP}}) defer cleanupServerPodAndService(f, podB, serviceB) // Wait for Server with Service in NS-B to be ready framework.Logf(\"Waiting for servers to be ready.\") err = e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podB.Name, nsB.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Ready.\") ginkgo.By(\"Create a network policy for the server which denies both Ingress and Egress traffic.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"ingress-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress, networkingv1.PolicyTypeEgress}, Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }}, Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: allowedPort}, }}, }}, Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, }, }, Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: allowedPort}, }}, }, }, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error creating Network Policy %v: %v\", policy.ObjectMeta.Name, err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"client-a should be able to communicate with server port 80 in namespace-b\", func() { testCanConnect(f, f.Namespace, \"client-a\", serviceB, allowedPort) }) ginkgo.By(\"client-b should be able to communicate with server port 80 in namespace-a\", func() { testCanConnect(f, nsB, \"client-b\", service, allowedPort) }) ginkgo.By(\"client-a should not be able to communicate with server port 81 in namespace-b\", func() { testCannotConnect(f, f.Namespace, \"client-a\", serviceB, notAllowedPort) }) ginkgo.By(\"client-b should not be able to communicate with server port 81 in namespace-a\", func() { testCannotConnect(f, nsB, \"client-b\", service, notAllowedPort) }) }) ginkgo.It(\"should enforce egress policy allowing traffic to a server in a different namespace based on PodSelector and NamespaceSelector [Feature:NetworkPolicy]\", func() { var nsBserviceA, nsBserviceB *v1.Service var nsBpodServerA, nsBpodServerB *v1.Pod nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") // Creating pods and services in namespace-b nsBpodServerA, nsBserviceA = createServerPodAndService(f, nsB, \"ns-b-server-a\", []protocolPort{{80, v1.ProtocolTCP}}) defer cleanupServerPodAndService(f, nsBpodServerA, nsBserviceA) nsBpodServerB, nsBserviceB = createServerPodAndService(f, nsB, \"ns-b-server-b\", []protocolPort{{80, v1.ProtocolTCP}}) defer cleanupServerPodAndService(f, nsBpodServerB, nsBserviceB) // Wait for Server with Service in NS-A to be ready framework.Logf(\"Waiting for servers to be ready.\") err = e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podServer.Name, podServer.Namespace, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Ready.\") // Wait for Servers with Services in NS-B to be ready err = e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, nsBpodServerA.Name, nsBpodServerA.Namespace, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Ready.\") err = e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, nsBpodServerB.Name, nsBpodServerB.Namespace, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Ready.\") ginkgo.By(\"Creating a network policy for the server which allows traffic only to a server in different namespace.\") policyAllowToServerInNSB := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: nsA.Name, Name: \"allow-to-ns-b-server-a-via-namespace-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the client PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic only to server-a in namespace-b Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": nsBpodServerA.ObjectMeta.Labels[\"pod-name\"], }, }, }, }, }, }, }, } policyAllowToServerInNSB, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowToServerInNSB, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowToServerInNSB.\") defer cleanupNetworkPolicy(f, policyAllowToServerInNSB) ginkgo.By(\"Creating client-a, in 'namespace-a', which should be able to contact the server-a in namespace-b.\", func() { testCanConnect(f, nsA, \"client-a\", nsBserviceA, 80) }) ginkgo.By(\"Creating client-a, in 'namespace-a', which should not be able to contact the server-b in namespace-b.\", func() { testCannotConnect(f, nsA, \"client-a\", nsBserviceB, 80) }) ginkgo.By(\"Creating client-a, in 'namespace-a', which should not be able to contact the server in namespace-a.\", func() { testCannotConnect(f, nsA, \"client-a\", service, 80) }) }) ginkgo.It(\"should enforce multiple ingress policies with ingress allow-all policy taking precedence [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the server which allows traffic only from client-b.\") policyAllowOnlyFromClientB := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-from-client-b-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, // Allow traffic only from \"client-b\" Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-b\", }, }, }}, }}, }, } policyAllowOnlyFromClientB, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowOnlyFromClientB, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowOnlyFromClientB.\") defer cleanupNetworkPolicy(f, policyAllowOnlyFromClientB) ginkgo.By(\"Creating client-a which should not be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-b\", service, 80) }) ginkgo.By(\"Creating a network policy for the server which allows traffic from all clients.\") policyIngressAllowAll := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ // Namespace: f.Namespace.Name, Name: \"allow-all\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to all pods PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{}, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, Ingress: []networkingv1.NetworkPolicyIngressRule{{}}, }, } policyIngressAllowAll, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyIngressAllowAll, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyIngressAllowAll.\") defer cleanupNetworkPolicy(f, policyIngressAllowAll) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating client-b which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-b\", service, 80) }) }) ginkgo.It(\"should enforce multiple egress policies with egress allow-all policy taking precedence [Feature:NetworkPolicy]\", func() { podServerB, serviceB := createServerPodAndService(f, f.Namespace, \"server-b\", []protocolPort{{80, v1.ProtocolTCP}}) defer cleanupServerPodAndService(f, podServerB, serviceB) ginkgo.By(\"Waiting for pod ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podServerB.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod type: Ready.\") }) ginkgo.By(\"Creating client-a which should be able to contact the server before applying policy.\", func() { testCanConnect(f, f.Namespace, \"client-a\", serviceB, 80) }) ginkgo.By(\"Creating a network policy for the server which allows traffic only to server-a.\") policyAllowOnlyToServerA := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-to-server-a-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the \"client-a\" PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic only to \"server-a\" Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, }, }, }, }, }, } policyAllowOnlyToServerA, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowOnlyToServerA, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowOnlyToServerA.\") defer cleanupNetworkPolicy(f, policyAllowOnlyToServerA) ginkgo.By(\"Creating client-a which should not be able to contact the server-b.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", serviceB, 80) }) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating a network policy which allows traffic to all pods.\") policyEgressAllowAll := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-all\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to all pods PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{}, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, Egress: []networkingv1.NetworkPolicyEgressRule{{}}, }, } policyEgressAllowAll, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyEgressAllowAll, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyEgressAllowAll.\") defer cleanupNetworkPolicy(f, policyEgressAllowAll) ginkgo.By(\"Creating client-a which should be able to contact the server-b.\", func() { testCanConnect(f, f.Namespace, \"client-a\", serviceB, 80) }) ginkgo.By(\"Creating client-a which should be able to contact the server-a.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) }) ginkgo.It(\"should stop enforcing policies after they are deleted [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the server which denies all traffic.\") policyDenyAll := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"deny-all\", }, Spec: networkingv1.NetworkPolicySpec{ // Deny all traffic PodSelector: metav1.LabelSelector{}, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, Ingress: []networkingv1.NetworkPolicyIngressRule{}, }, } policyDenyAll, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyDenyAll, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyDenyAll.\") ginkgo.By(\"Creating client-a which should not be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Creating a network policy for the server which allows traffic only from client-a.\") policyAllowFromClientA := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-from-client-a-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, // Allow traffic from \"client-a\" Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, }}, }, } policyAllowFromClientA, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowFromClientA, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowFromClientA.\") ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Deleting the network policy allowing traffic from client-a\") cleanupNetworkPolicy(f, policyAllowFromClientA) ginkgo.By(\"Creating client-a which should not be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Deleting the network policy denying all traffic.\") cleanupNetworkPolicy(f, policyDenyAll) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) }) ginkgo.It(\"should allow egress access to server in CIDR block [Feature:NetworkPolicy]\", func() { var serviceB *v1.Service var podServerB *v1.Pod // Getting podServer's status to get podServer's IP, to create the CIDR podServerStatus, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), podServer.Name, metav1.GetOptions{}) if err != nil { framework.ExpectNoError(err, \"Error occurred while getting pod status.\") } hostMask := 32 if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { hostMask = 128 } podServerCIDR := fmt.Sprintf(\"%s/%d\", podServerStatus.Status.PodIP, hostMask) // Creating pod-b and service-b podServerB, serviceB = createServerPodAndService(f, f.Namespace, \"pod-b\", []protocolPort{{80, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod-b to be ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podServerB.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod type: Ready.\") }) defer cleanupServerPodAndService(f, podServerB, serviceB) // Wait for podServerB with serviceB to be ready err = e2epod.WaitForPodRunningInNamespace(f.ClientSet, podServerB) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Running.\") ginkgo.By(\"Creating client-a which should be able to contact the server-b.\", func() { testCanConnect(f, f.Namespace, \"client-a\", serviceB, 80) }) policyAllowCIDR := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-client-a-via-cidr-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic to only one CIDR block. Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { IPBlock: &networkingv1.IPBlock{ CIDR: podServerCIDR, }, }, }, }, }, }, } policyAllowCIDR, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowCIDR, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowCIDR.\") defer cleanupNetworkPolicy(f, policyAllowCIDR) ginkgo.By(\"Creating client-a which should not be able to contact the server-b.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", serviceB, 80) }) ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) }) ginkgo.It(\"should enforce except clause while egress access to server in CIDR block [Feature:NetworkPolicy]\", func() { // Getting podServer's status to get podServer's IP, to create the CIDR with except clause podServerStatus, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), podServer.Name, metav1.GetOptions{}) if err != nil { framework.ExpectNoError(err, \"Error occurred while getting pod status.\") } allowMask := 24 hostMask := 32 if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { allowMask = 64 hostMask = 128 } _, podServerAllowSubnet, err := net.ParseCIDR(fmt.Sprintf(\"%s/%d\", podServerStatus.Status.PodIP, allowMask)) framework.ExpectNoError(err, \"could not parse allow subnet\") podServerAllowCIDR := podServerAllowSubnet.String() // Exclude podServer's IP with an Except clause podServerExceptList := []string{fmt.Sprintf(\"%s/%d\", podServerStatus.Status.PodIP, hostMask)} // client-a can connect to server prior to applying the NetworkPolicy ginkgo.By(\"Creating client-a which should be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) policyAllowCIDRWithExcept := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"deny-client-a-via-except-cidr-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the client. PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic to only one CIDR block except subnet which includes Server. Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { IPBlock: &networkingv1.IPBlock{ CIDR: podServerAllowCIDR, Except: podServerExceptList, }, }, }, }, }, }, } policyAllowCIDRWithExcept, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowCIDRWithExcept, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowCIDRWithExcept.\") defer cleanupNetworkPolicy(f, policyAllowCIDRWithExcept) ginkgo.By(\"Creating client-a which should no longer be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", service, 80) }) }) ginkgo.It(\"should ensure an IP overlapping both IPBlock.CIDR and IPBlock.Except is allowed [Feature:NetworkPolicy]\", func() { // Getting podServer's status to get podServer's IP, to create the CIDR with except clause podServerStatus, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), podServer.Name, metav1.GetOptions{}) if err != nil { framework.ExpectNoError(err, \"Error occurred while getting pod status.\") } allowMask := 24 hostMask := 32 if utilnet.IsIPv6String(podServerStatus.Status.PodIP) { allowMask = 64 hostMask = 128 } _, podServerAllowSubnet, err := net.ParseCIDR(fmt.Sprintf(\"%s/%d\", podServerStatus.Status.PodIP, allowMask)) framework.ExpectNoError(err, \"could not parse allow subnet\") podServerAllowCIDR := podServerAllowSubnet.String() // Exclude podServer's IP with an Except clause podServerCIDR := fmt.Sprintf(\"%s/%d\", podServerStatus.Status.PodIP, hostMask) podServerExceptList := []string{podServerCIDR} // Create NetworkPolicy which blocks access to podServer with except clause. policyAllowCIDRWithExceptServerPod := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"deny-client-a-via-except-cidr-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the client. PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic to only one CIDR block except subnet which includes Server. Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { IPBlock: &networkingv1.IPBlock{ CIDR: podServerAllowCIDR, Except: podServerExceptList, }, }, }, }, }, }, } policyAllowCIDRWithExceptServerPodObj, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowCIDRWithExceptServerPod, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowCIDRWithExceptServerPod.\") ginkgo.By(\"Creating client-a which should not be able to contact the server.\", func() { testCannotConnect(f, f.Namespace, \"client-a\", service, 80) }) // Create NetworkPolicy which allows access to the podServer using podServer's IP in allow CIDR. policyAllowCIDRServerPod := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-client-a-via-cidr-egress-rule\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the client. PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic to only one CIDR block which includes Server. Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { IPBlock: &networkingv1.IPBlock{ CIDR: podServerCIDR, }, }, }, }, }, }, } policyAllowCIDRServerPod, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowCIDRServerPod, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowCIDRServerPod.\") defer cleanupNetworkPolicy(f, policyAllowCIDRServerPod) ginkgo.By(\"Creating client-a which should now be able to contact the server.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) ginkgo.By(\"Deleting the network policy with except podServer IP which disallows access to podServer.\") cleanupNetworkPolicy(f, policyAllowCIDRWithExceptServerPodObj) ginkgo.By(\"Creating client-a which should still be able to contact the server after deleting the network policy with except clause.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) // Recreate the NetworkPolicy which contains the podServer's IP in the except list. policyAllowCIDRWithExceptServerPod, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowCIDRWithExceptServerPod, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowCIDRWithExceptServerPod.\") defer cleanupNetworkPolicy(f, policyAllowCIDRWithExceptServerPod) ginkgo.By(\"Creating client-a which should still be able to contact the server after recreating the network policy with except clause.\", func() { testCanConnect(f, f.Namespace, \"client-a\", service, 80) }) }) ginkgo.It(\"should enforce policies to check ingress and egress policies can be controlled independently based on PodSelector [Feature:NetworkPolicy]\", func() { var serviceA, serviceB *v1.Service var podA, podB *v1.Pod var err error // Before applying policy, communication should be successful between pod-a and pod-b podA, serviceA = createServerPodAndService(f, f.Namespace, \"pod-a\", []protocolPort{{80, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod-a to be ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podA.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod type: Ready.\") }) ginkgo.By(\"Creating client pod-b which should be able to contact the server pod-a.\", func() { testCanConnect(f, f.Namespace, \"pod-b\", serviceA, 80) }) cleanupServerPodAndService(f, podA, serviceA) podB, serviceB = createServerPodAndService(f, f.Namespace, \"pod-b\", []protocolPort{{80, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod-b to be ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podB.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod type: Ready.\") }) ginkgo.By(\"Creating client pod-a which should be able to contact the server pod-b.\", func() { testCanConnect(f, f.Namespace, \"pod-a\", serviceB, 80) }) ginkgo.By(\"Creating a network policy for pod-a which allows Egress traffic to pod-b.\") policyAllowToPodB := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"allow-pod-a-to-pod-b-using-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy on pod-a PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"pod-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeEgress}, // Allow traffic to server on pod-b Egress: []networkingv1.NetworkPolicyEgressRule{ { To: []networkingv1.NetworkPolicyPeer{ { PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"pod-b\", }, }, }, }, }, }, }, } policyAllowToPodB, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyAllowToPodB, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyAllowToPodB.\") defer cleanupNetworkPolicy(f, policyAllowToPodB) ginkgo.By(\"Creating a network policy for pod-a that denies traffic from pod-b.\") policyDenyFromPodB := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: f.Namespace.Name, Name: \"deny-pod-b-to-pod-a-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy on the server on pod-a PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"pod-a\", }, }, PolicyTypes: []networkingv1.PolicyType{networkingv1.PolicyTypeIngress}, // Deny traffic from all pods, including pod-b Ingress: []networkingv1.NetworkPolicyIngressRule{}, }, } policyDenyFromPodB, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policyDenyFromPodB, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policyDenyFromPodB.\") defer cleanupNetworkPolicy(f, policyDenyFromPodB) ginkgo.By(\"Creating client pod-a which should be able to contact the server pod-b.\", func() { testCanConnect(f, f.Namespace, \"pod-a\", serviceB, 80) }) cleanupServerPodAndService(f, podB, serviceB) // Creating server pod with label \"pod-name\": \"pod-a\" to deny traffic from client pod with label \"pod-name\": \"pod-b\" podA, serviceA = createServerPodAndService(f, f.Namespace, \"pod-a\", []protocolPort{{80, v1.ProtocolTCP}}) ginkgo.By(\"Waiting for pod-a to be ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podA.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err, \"Error occurred while waiting for pod type: Ready.\") }) ginkgo.By(\"Creating client pod-b which should be able to contact the server pod-a.\", func() { testCannotConnect(f, f.Namespace, \"pod-b\", serviceA, 80) }) cleanupServerPodAndService(f, podA, serviceA) }) ginkgo.It(\"should not allow access by TCP when a policy specifies only SCTP [Feature:NetworkPolicy] [Feature:SCTP]\", func() { ginkgo.By(\"getting the state of the sctp module on nodes\") nodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet) framework.ExpectNoError(err) sctpLoadedAtStart := CheckSCTPModuleLoadedOnNodes(f, nodes) ginkgo.By(\"Creating a network policy for the server which allows traffic only via SCTP on port 80.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-only-sctp-ingress-on-port-80\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only via SCTP on port 80 . Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: 80}, Protocol: &protocolSCTP, }}, }}, }, } appliedPolicy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, appliedPolicy) ginkgo.By(\"Testing pods cannot connect on port 80 anymore when not using SCTP as protocol.\") testCannotConnect(f, f.Namespace, \"client-a\", service, 80) ginkgo.By(\"validating sctp module is still not loaded\") sctpLoadedAtEnd := CheckSCTPModuleLoadedOnNodes(f, nodes) if !sctpLoadedAtStart && sctpLoadedAtEnd { framework.Failf(\"The state of the sctp module has changed due to the test case\") } }) }) }) var _ = SIGDescribe(\"NetworkPolicy [Feature:SCTPConnectivity][LinuxOnly][Disruptive]\", func() { var service *v1.Service var podServer *v1.Pod var podServerLabelSelector string f := framework.NewDefaultFramework(\"sctp-network-policy\") ginkgo.BeforeEach(func() { // Windows does not support network policies. e2eskipper.SkipIfNodeOSDistroIs(\"windows\") }) ginkgo.Context(\"NetworkPolicy between server and client using SCTP\", func() { ginkgo.BeforeEach(func() { ginkgo.By(\"Creating a simple server that serves on port 80 and 81.\") podServer, service = createServerPodAndService(f, f.Namespace, \"server\", []protocolPort{{80, v1.ProtocolSCTP}, {81, v1.ProtocolSCTP}}) ginkgo.By(\"Waiting for pod ready\", func() { err := e2epod.WaitTimeoutForPodReadyInNamespace(f.ClientSet, podServer.Name, f.Namespace.Name, framework.PodStartTimeout) framework.ExpectNoError(err) }) // podServerLabelSelector holds the value for the podServer's label \"pod-name\". podServerLabelSelector = podServer.ObjectMeta.Labels[\"pod-name\"] // Create pods, which should be able to communicate with the server on port 80 and 81. ginkgo.By(\"Testing pods can connect to both ports when no policy is present.\") testCanConnectProtocol(f, f.Namespace, \"client-can-connect-80\", service, 80, v1.ProtocolSCTP) testCanConnectProtocol(f, f.Namespace, \"client-can-connect-81\", service, 81, v1.ProtocolSCTP) }) ginkgo.AfterEach(func() { cleanupServerPodAndService(f, podServer, service) }) ginkgo.It(\"should support a 'default-deny' policy [Feature:NetworkPolicy]\", func() { policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"deny-all\", }, Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{}, Ingress: []networkingv1.NetworkPolicyIngressRule{}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) // Create a pod with name 'client-cannot-connect', which will attempt to communicate with the server, // but should not be able to now that isolation is on. testCannotConnect(f, f.Namespace, \"client-cannot-connect\", service, 80) }) ginkgo.It(\"should enforce policy based on Ports [Feature:NetworkPolicy]\", func() { ginkgo.By(\"Creating a network policy for the Service which allows traffic only to one port.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: \"allow-ingress-on-port-81\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply to server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only to one port. Ingress: []networkingv1.NetworkPolicyIngressRule{{ Ports: []networkingv1.NetworkPolicyPort{{ Port: &intstr.IntOrString{IntVal: 81}, Protocol: &protocolSCTP, }}, }}, }, } policy, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err) defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Testing pods can connect only to the port allowed by the policy.\") testCannotConnectProtocol(f, f.Namespace, \"client-a\", service, 80, v1.ProtocolSCTP) testCanConnectProtocol(f, f.Namespace, \"client-b\", service, 81, v1.ProtocolSCTP) }) ginkgo.It(\"should enforce policy to allow traffic only from a pod in a different namespace based on PodSelector and NamespaceSelector [Feature:NetworkPolicy]\", func() { nsA := f.Namespace nsBName := f.BaseName + \"-b\" nsB, err := f.CreateNamespace(nsBName, map[string]string{ \"ns-name\": nsBName, }) framework.ExpectNoError(err, \"Error occurred while creating namespace-b.\") // Wait for Server in namespaces-a to be ready framework.Logf(\"Waiting for server to come up.\") err = e2epod.WaitForPodRunningInNamespace(f.ClientSet, podServer) framework.ExpectNoError(err, \"Error occurred while waiting for pod status in namespace: Running.\") // Before application of the policy, all communication should be successful. ginkgo.By(\"Creating client-a, in server's namespace, which should be able to contact the server.\", func() { testCanConnectProtocol(f, nsA, \"client-a\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-b, in server's namespace, which should be able to contact the server.\", func() { testCanConnectProtocol(f, nsA, \"client-b\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should be able to contact the server.\", func() { testCanConnectProtocol(f, nsB, \"client-a\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-b, not in server's namespace, which should be able to contact the server.\", func() { testCanConnectProtocol(f, nsB, \"client-b\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating a network policy for the server which allows traffic only from client-a in namespace-b.\") policy := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ Namespace: nsA.Name, Name: \"allow-ns-b-client-a-via-namespace-pod-selector\", }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": podServerLabelSelector, }, }, // Allow traffic only from client-a in namespace-b Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": nsBName, }, }, PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, }}, }, } policy, err = f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).Create(context.TODO(), policy, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Error occurred while creating policy: policy.\") defer cleanupNetworkPolicy(f, policy) ginkgo.By(\"Creating client-a, in server's namespace, which should not be able to contact the server.\", func() { testCannotConnectProtocol(f, nsA, \"client-a\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-b, in server's namespace, which should not be able to contact the server.\", func() { testCannotConnectProtocol(f, nsA, \"client-b\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-a, not in server's namespace, which should be able to contact the server.\", func() { testCanConnectProtocol(f, nsB, \"client-a\", service, 80, v1.ProtocolSCTP) }) ginkgo.By(\"Creating client-b, not in server's namespace, which should not be able to contact the server.\", func() { testCannotConnectProtocol(f, nsB, \"client-b\", service, 80, v1.ProtocolSCTP) }) }) }) }) func testCanConnect(f *framework.Framework, ns *v1.Namespace, podName string, service *v1.Service, targetPort int) { testCanConnectProtocol(f, ns, podName, service, targetPort, v1.ProtocolTCP) } func testCannotConnect(f *framework.Framework, ns *v1.Namespace, podName string, service *v1.Service, targetPort int) { testCannotConnectProtocol(f, ns, podName, service, targetPort, v1.ProtocolTCP) } func testCanConnectProtocol(f *framework.Framework, ns *v1.Namespace, podName string, service *v1.Service, targetPort int, protocol v1.Protocol) { ginkgo.By(fmt.Sprintf(\"Creating client pod %s that should successfully connect to %s.\", podName, service.Name)) podClient := createNetworkClientPod(f, ns, podName, service, targetPort, protocol) defer func() { ginkgo.By(fmt.Sprintf(\"Cleaning up the pod %s\", podClient.Name)) if err := f.ClientSet.CoreV1().Pods(ns.Name).Delete(context.TODO(), podClient.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup pod %v: %v\", podClient.Name, err) } }() checkConnectivity(f, ns, podClient, service) } func testCannotConnectProtocol(f *framework.Framework, ns *v1.Namespace, podName string, service *v1.Service, targetPort int, protocol v1.Protocol) { ginkgo.By(fmt.Sprintf(\"Creating client pod %s that should not be able to connect to %s.\", podName, service.Name)) podClient := createNetworkClientPod(f, ns, podName, service, targetPort, protocol) defer func() { ginkgo.By(fmt.Sprintf(\"Cleaning up the pod %s\", podClient.Name)) if err := f.ClientSet.CoreV1().Pods(ns.Name).Delete(context.TODO(), podClient.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup pod %v: %v\", podClient.Name, err) } }() checkNoConnectivity(f, ns, podClient, service) } func checkConnectivity(f *framework.Framework, ns *v1.Namespace, podClient *v1.Pod, service *v1.Service) { framework.Logf(\"Waiting for %s to complete.\", podClient.Name) err := e2epod.WaitForPodNoLongerRunningInNamespace(f.ClientSet, podClient.Name, ns.Name) framework.ExpectNoError(err, \"Pod did not finish as expected.\") framework.Logf(\"Waiting for %s to complete.\", podClient.Name) err = e2epod.WaitForPodSuccessInNamespace(f.ClientSet, podClient.Name, ns.Name) if err != nil { // Dump debug information for the test namespace. framework.DumpDebugInfo(f.ClientSet, f.Namespace.Name) pods, policies, logs := collectPodsAndNetworkPolicies(f, podClient) framework.Failf(\"Pod %s should be able to connect to service %s, but was not able to connect.nPod logs:n%snn Current NetworkPolicies:nt%vnn Pods:nt%vnn\", podClient.Name, service.Name, logs, policies.Items, pods) } } func checkNoConnectivity(f *framework.Framework, ns *v1.Namespace, podClient *v1.Pod, service *v1.Service) { framework.Logf(\"Waiting for %s to complete.\", podClient.Name) err := e2epod.WaitForPodSuccessInNamespace(f.ClientSet, podClient.Name, ns.Name) // We expect an error here since it's a cannot connect test. // Dump debug information if the error was nil. if err == nil { // Dump debug information for the test namespace. framework.DumpDebugInfo(f.ClientSet, f.Namespace.Name) pods, policies, logs := collectPodsAndNetworkPolicies(f, podClient) framework.Failf(\"Pod %s should not be able to connect to service %s, but was able to connect.nPod logs:n%snn Current NetworkPolicies:nt%vnn Pods:nt %vnn\", podClient.Name, service.Name, logs, policies.Items, pods) } } func checkNoConnectivityByExitCode(f *framework.Framework, ns *v1.Namespace, podClient *v1.Pod, service *v1.Service) { err := e2epod.WaitForPodCondition(f.ClientSet, ns.Name, podClient.Name, \"terminated\", framework.PodStartTimeout, func(pod *v1.Pod) (bool, error) { statuses := pod.Status.ContainerStatuses if len(statuses) == 0 || statuses[0].State.Terminated == nil { return false, nil } if statuses[0].State.Terminated.ExitCode != 0 { return true, fmt.Errorf(\"pod %q container exited with code: %d\", podClient.Name, statuses[0].State.Terminated.ExitCode) } return true, nil }) // We expect an error here since it's a cannot connect test. // Dump debug information if the error was nil. if err == nil { pods, policies, logs := collectPodsAndNetworkPolicies(f, podClient) framework.Failf(\"Pod %s should not be able to connect to service %s, but was able to connect.nPod logs:n%snn Current NetworkPolicies:nt%vnn Pods:nt%vnn\", podClient.Name, service.Name, logs, policies.Items, pods) // Dump debug information for the test namespace. framework.DumpDebugInfo(f.ClientSet, f.Namespace.Name) } } func collectPodsAndNetworkPolicies(f *framework.Framework, podClient *v1.Pod) ([]string, *networkingv1.NetworkPolicyList, string) { // Collect pod logs when we see a failure. logs, logErr := e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, podClient.Name, \"client\") if logErr != nil && apierrors.IsNotFound(logErr) { // Pod may have already been removed; try to get previous pod logs logs, logErr = e2epod.GetPreviousPodLogs(f.ClientSet, f.Namespace.Name, podClient.Name, fmt.Sprintf(\"%s-container\", podClient.Name)) } if logErr != nil { framework.Logf(\"Error getting container logs: %s\", logErr) } // Collect current NetworkPolicies applied in the test namespace. policies, err := f.ClientSet.NetworkingV1().NetworkPolicies(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{}) if err != nil { framework.Logf(\"error getting current NetworkPolicies for %s namespace: %s\", f.Namespace.Name, err) } // Collect the list of pods running in the test namespace. podsInNS, err := e2epod.GetPodsInNamespace(f.ClientSet, f.Namespace.Name, map[string]string{}) if err != nil { framework.Logf(\"error getting pods for %s namespace: %s\", f.Namespace.Name, err) } pods := []string{} for _, p := range podsInNS { pods = append(pods, fmt.Sprintf(\"Pod: %s, Status: %sn\", p.Name, p.Status.String())) } return pods, policies, logs } // Create a server pod with a listening container for each port in ports[]. // Will also assign a pod label with key: \"pod-name\" and label set to the given podName for later use by the network // policy. func createServerPodAndService(f *framework.Framework, namespace *v1.Namespace, podName string, ports []protocolPort) (*v1.Pod, *v1.Service) { // Because we have a variable amount of ports, we'll first loop through and generate our Containers for our pod, // and ServicePorts.for our Service. containers := []v1.Container{} servicePorts := []v1.ServicePort{} for _, portProtocol := range ports { var porterPort string var connectProtocol string switch portProtocol.protocol { case v1.ProtocolTCP: porterPort = fmt.Sprintf(\"SERVE_PORT_%d\", portProtocol.port) connectProtocol = \"tcp\" case v1.ProtocolSCTP: porterPort = fmt.Sprintf(\"SERVE_SCTP_PORT_%d\", portProtocol.port) connectProtocol = \"sctp\" default: framework.Failf(\"createServerPodAndService, unexpected protocol %v\", portProtocol.protocol) } containers = append(containers, v1.Container{ Name: fmt.Sprintf(\"%s-container-%d\", podName, portProtocol.port), Image: imageutils.GetE2EImage(imageutils.Agnhost), Args: []string{\"porter\"}, Env: []v1.EnvVar{ { Name: porterPort, Value: \"foo\", }, }, Ports: []v1.ContainerPort{ { ContainerPort: int32(portProtocol.port), Name: fmt.Sprintf(\"serve-%d\", portProtocol.port), Protocol: portProtocol.protocol, }, }, ReadinessProbe: &v1.Probe{ Handler: v1.Handler{ Exec: &v1.ExecAction{ Command: []string{\"/agnhost\", \"connect\", fmt.Sprintf(\"--protocol=%s\", connectProtocol), \"--timeout=1s\", fmt.Sprintf(\"127.0.0.1:%d\", portProtocol.port)}, }, }, }, }) // Build the Service Ports for the service. servicePorts = append(servicePorts, v1.ServicePort{ Name: fmt.Sprintf(\"%s-%d\", podName, portProtocol.port), Port: int32(portProtocol.port), TargetPort: intstr.FromInt(portProtocol.port), Protocol: portProtocol.protocol, }) } ginkgo.By(fmt.Sprintf(\"Creating a server pod %s in namespace %s\", podName, namespace.Name)) pod, err := f.ClientSet.CoreV1().Pods(namespace.Name).Create(context.TODO(), &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: podName + \"-\", Labels: map[string]string{ \"pod-name\": podName, }, }, Spec: v1.PodSpec{ Containers: containers, RestartPolicy: v1.RestartPolicyNever, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err) framework.Logf(\"Created pod %v\", pod.ObjectMeta.Name) svcName := fmt.Sprintf(\"svc-%s\", podName) ginkgo.By(fmt.Sprintf(\"Creating a service %s for pod %s in namespace %s\", svcName, podName, namespace.Name)) svc, err := f.ClientSet.CoreV1().Services(namespace.Name).Create(context.TODO(), &v1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: svcName, }, Spec: v1.ServiceSpec{ Ports: servicePorts, Selector: map[string]string{ \"pod-name\": podName, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err) framework.Logf(\"Created service %s\", svc.Name) return pod, svc } func cleanupServerPodAndService(f *framework.Framework, pod *v1.Pod, service *v1.Service) { ginkgo.By(\"Cleaning up the server.\") if err := f.ClientSet.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup pod %v: %v\", pod.Name, err) } ginkgo.By(\"Cleaning up the server's service.\") if err := f.ClientSet.CoreV1().Services(service.Namespace).Delete(context.TODO(), service.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup svc %v: %v\", service.Name, err) } } // Create a client pod which will attempt a netcat to the provided service, on the specified port. // This client will attempt a one-shot connection, then die, without restarting the pod. // Test can then be asserted based on whether the pod quit with an error or not. func createNetworkClientPod(f *framework.Framework, namespace *v1.Namespace, podName string, targetService *v1.Service, targetPort int, protocol v1.Protocol) *v1.Pod { return createNetworkClientPodWithRestartPolicy(f, namespace, podName, targetService, targetPort, protocol, v1.RestartPolicyNever) } // Create a client pod which will attempt a netcat to the provided service, on the specified port. // It is similar to createNetworkClientPod but supports specifying RestartPolicy. func createNetworkClientPodWithRestartPolicy(f *framework.Framework, namespace *v1.Namespace, podName string, targetService *v1.Service, targetPort int, protocol v1.Protocol, restartPolicy v1.RestartPolicy) *v1.Pod { var connectProtocol string switch protocol { case v1.ProtocolTCP: connectProtocol = \"tcp\" case v1.ProtocolSCTP: connectProtocol = \"sctp\" default: framework.Failf(\"createNetworkClientPodWithRestartPolicy, unexpected protocol %v\", protocol) } pod, err := f.ClientSet.CoreV1().Pods(namespace.Name).Create(context.TODO(), &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: podName + \"-\", Labels: map[string]string{ \"pod-name\": podName, }, }, Spec: v1.PodSpec{ RestartPolicy: restartPolicy, Containers: []v1.Container{ { Name: \"client\", Image: imageutils.GetE2EImage(imageutils.Agnhost), Command: []string{\"/bin/sh\"}, Args: []string{ \"-c\", fmt.Sprintf(\"for i in $(seq 1 5); do /agnhost connect %s --protocol %s --timeout 8s && exit 0 || sleep 1; done; exit 1\", net.JoinHostPort(targetService.Spec.ClusterIP, strconv.Itoa(targetPort)), connectProtocol), }, }, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err) return pod } // Patch pod with a map value func updatePodLabel(f *framework.Framework, namespace *v1.Namespace, podName string, patchOperation string, patchPath string, patchValue map[string]string) *v1.Pod { type patchMapValue struct { Op string `json:\"op\"` Path string `json:\"path\"` Value map[string]string `json:\"value,omitempty\"` } payload := []patchMapValue{{ Op: patchOperation, Path: patchPath, Value: patchValue, }} payloadBytes, err := json.Marshal(payload) framework.ExpectNoError(err) pod, err := f.ClientSet.CoreV1().Pods(namespace.Name).Patch(context.TODO(), podName, types.JSONPatchType, payloadBytes, metav1.PatchOptions{}) framework.ExpectNoError(err) return pod } func cleanupNetworkPolicy(f *framework.Framework, policy *networkingv1.NetworkPolicy) { ginkgo.By(\"Cleaning up the policy.\") if err := f.ClientSet.NetworkingV1().NetworkPolicies(policy.Namespace).Delete(context.TODO(), policy.Name, metav1.DeleteOptions{}); err != nil { framework.Failf(\"unable to cleanup policy %v: %v\", policy.Name, err) } } var _ = SIGDescribe(\"NetworkPolicy API\", func() { f := framework.NewDefaultFramework(\"networkpolicies\") /* Release: v1.20 Testname: NetworkPolicies API Description: - The networking.k8s.io API group MUST exist in the /apis discovery document. - The networking.k8s.io/v1 API group/version MUST exist in the /apis/networking.k8s.io discovery document. - The NetworkPolicies resources MUST exist in the /apis/networking.k8s.io/v1 discovery document. - The NetworkPolicies resource must support create, get, list, watch, update, patch, delete, and deletecollection. */ ginkgo.It(\"should support creating NetworkPolicy API operations\", func() { // Setup ns := f.Namespace.Name npVersion := \"v1\" npClient := f.ClientSet.NetworkingV1().NetworkPolicies(ns) npTemplate := &networkingv1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{ GenerateName: \"e2e-example-netpol\", Labels: map[string]string{ \"special-label\": f.UniqueName, }, }, Spec: networkingv1.NetworkPolicySpec{ // Apply this policy to the Server PodSelector: metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"test-pod\", }, }, // Allow traffic only from client-a in namespace-b Ingress: []networkingv1.NetworkPolicyIngressRule{{ From: []networkingv1.NetworkPolicyPeer{{ NamespaceSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"ns-name\": \"pod-b\", }, }, PodSelector: &metav1.LabelSelector{ MatchLabels: map[string]string{ \"pod-name\": \"client-a\", }, }, }}, }}, }, } // Discovery ginkgo.By(\"getting /apis\") { discoveryGroups, err := f.ClientSet.Discovery().ServerGroups() framework.ExpectNoError(err) found := false for _, group := range discoveryGroups.Groups { if group.Name == networkingv1.GroupName { for _, version := range group.Versions { if version.Version == npVersion { found = true break } } } } framework.ExpectEqual(found, true, fmt.Sprintf(\"expected networking API group/version, got %#v\", discoveryGroups.Groups)) } ginkgo.By(\"getting /apis/networking.k8s.io\") { group := &metav1.APIGroup{} err := f.ClientSet.Discovery().RESTClient().Get().AbsPath(\"/apis/networking.k8s.io\").Do(context.TODO()).Into(group) framework.ExpectNoError(err) found := false for _, version := range group.Versions { if version.Version == npVersion { found = true break } } framework.ExpectEqual(found, true, fmt.Sprintf(\"expected networking API version, got %#v\", group.Versions)) } ginkgo.By(\"getting /apis/networking.k8s.io\" + npVersion) { resources, err := f.ClientSet.Discovery().ServerResourcesForGroupVersion(networkingv1.SchemeGroupVersion.String()) framework.ExpectNoError(err) foundNetPol := false for _, resource := range resources.APIResources { switch resource.Name { case \"networkpolicies\": foundNetPol = true } } framework.ExpectEqual(foundNetPol, true, fmt.Sprintf(\"expected networkpolicies, got %#v\", resources.APIResources)) } // NetPol resource create/read/update/watch verbs ginkgo.By(\"creating\") _, err := npClient.Create(context.TODO(), npTemplate, metav1.CreateOptions{}) framework.ExpectNoError(err) _, err = npClient.Create(context.TODO(), npTemplate, metav1.CreateOptions{}) framework.ExpectNoError(err) createdNetPol, err := npClient.Create(context.TODO(), npTemplate, metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By(\"getting\") gottenNetPol, err := npClient.Get(context.TODO(), createdNetPol.Name, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(gottenNetPol.UID, createdNetPol.UID) ginkgo.By(\"listing\") nps, err := npClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) framework.ExpectEqual(len(nps.Items), 3, \"filtered list should have 3 items\") ginkgo.By(\"watching\") framework.Logf(\"starting watch\") npWatch, err := npClient.Watch(context.TODO(), metav1.ListOptions{ResourceVersion: nps.ResourceVersion, LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) // Test cluster-wide list and watch clusterNPClient := f.ClientSet.NetworkingV1().NetworkPolicies(\"\") ginkgo.By(\"cluster-wide listing\") clusterNPs, err := clusterNPClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) framework.ExpectEqual(len(clusterNPs.Items), 3, \"filtered list should have 3 items\") ginkgo.By(\"cluster-wide watching\") framework.Logf(\"starting watch\") _, err = clusterNPClient.Watch(context.TODO(), metav1.ListOptions{ResourceVersion: nps.ResourceVersion, LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) ginkgo.By(\"patching\") patchedNetPols, err := npClient.Patch(context.TODO(), createdNetPol.Name, types.MergePatchType, []byte(`{\"metadata\":{\"annotations\":{\"patched\":\"true\"}}}`), metav1.PatchOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(patchedNetPols.Annotations[\"patched\"], \"true\", \"patched object should have the applied annotation\") ginkgo.By(\"updating\") npToUpdate := patchedNetPols.DeepCopy() npToUpdate.Annotations[\"updated\"] = \"true\" updatedNetPols, err := npClient.Update(context.TODO(), npToUpdate, metav1.UpdateOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(updatedNetPols.Annotations[\"updated\"], \"true\", \"updated object should have the applied annotation\") framework.Logf(\"waiting for watch events with expected annotations\") for sawAnnotations := false; !sawAnnotations; { select { case evt, ok := <-npWatch.ResultChan(): framework.ExpectEqual(ok, true, \"watch channel should not close\") framework.ExpectEqual(evt.Type, watch.Modified) watchedNetPol, isNetPol := evt.Object.(*networkingv1.NetworkPolicy) framework.ExpectEqual(isNetPol, true, fmt.Sprintf(\"expected NetworkPolicy, got %T\", evt.Object)) if watchedNetPol.Annotations[\"patched\"] == \"true\" && watchedNetPol.Annotations[\"updated\"] == \"true\" { framework.Logf(\"saw patched and updated annotations\") sawAnnotations = true npWatch.Stop() } else { framework.Logf(\"missing expected annotations, waiting: %#v\", watchedNetPol.Annotations) } case <-time.After(wait.ForeverTestTimeout): framework.Fail(\"timed out waiting for watch event\") } } // NetPol resource delete operations ginkgo.By(\"deleting\") err = npClient.Delete(context.TODO(), createdNetPol.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) _, err = npClient.Get(context.TODO(), createdNetPol.Name, metav1.GetOptions{}) framework.ExpectEqual(apierrors.IsNotFound(err), true, fmt.Sprintf(\"expected 404, got %#v\", err)) nps, err = npClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) framework.ExpectEqual(len(nps.Items), 2, \"filtered list should have 2 items\") ginkgo.By(\"deleting a collection\") err = npClient.DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) nps, err = npClient.List(context.TODO(), metav1.ListOptions{LabelSelector: \"special-label=\" + f.UniqueName}) framework.ExpectNoError(err) framework.ExpectEqual(len(nps.Items), 0, \"filtered list should have 0 items\") }) }) "} {"_id":"doc-en-kubernetes-639a95538548e3e65a7669949cfe4ff20567a54449dd94e6f12259ce0f4a9385","title":"","text":" #!/usr/bin/env bash # Copyright 2014 The Kubernetes Authors. # # 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. # This script verifies the following e2e test ownership policies # - tests MUST start with [sig-foo] # - tests MUST use top-level SIGDescribe # - tests SHOULD NOT have multiple [sig-foo] tags # - tests MUST NOT use nested SIGDescribe # TODO: these two can be dropped if KubeDescribe is gone from codebase # - tests MUST NOT have [k8s.io] in test names # - tests MUST NOT use KubeDescribe set -o errexit set -o nounset set -o pipefail # This will canonicalize the path KUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. && pwd -P) source \"${KUBE_ROOT}/hack/lib/init.sh\" # Set REUSE_BUILD_OUTPUT=y to skip rebuilding dependencies if present REUSE_BUILD_OUTPUT=${REUSE_BUILD_OUTPUT:-n} # set VERBOSE_OUTPUT=y to output .jq files and shell commands VERBOSE_OUTPUT=${VERBOSE_OUTPUT:-n} if [[ ${VERBOSE_OUTPUT} =~ ^[yY]$ ]]; then set -x fi pushd \"${KUBE_ROOT}\" > /dev/null # Setup a tmpdir to hold generated scripts and results readonly tmpdir=$(mktemp -d -t verify-e2e-test-ownership.XXXX) trap 'rm -rf ${tmpdir}' EXIT # input spec_summaries=\"${KUBE_ROOT}/_output/specsummaries.json\" # output results_json=\"${tmpdir}/results.json\" summary_json=\"${tmpdir}/summary.json\" failures_json=\"${tmpdir}/failures.json\" # rebuild dependencies if necessary function ensure_dependencies() { local -r ginkgo=\"${KUBE_ROOT}/_output/bin/ginkgo\" local -r e2e_test=\"${KUBE_ROOT}/_output/bin/e2e.test\" if ! { [ -f \"${ginkgo}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then make ginkgo fi if ! { [ -f \"${e2e_test}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then hack/make-rules/build.sh test/e2e/e2e.test fi if ! { [ -f \"${spec_summaries}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then \"${ginkgo}\" --dryRun=true \"${e2e_test}\" -- --spec-dump \"${spec_summaries}\" > /dev/null fi } # evaluate ginkgo spec summaries against e2e test ownership polices # output to ${results_json} function generate_results_json() { readonly results_jq=${tmpdir}/results.jq cat >\"${results_jq}\" < \"${results_json}\" } # summarize e2e test policy results # output to ${summary_json} function generate_summary_json() { summary_jq=${tmpdir}/summary.jq cat >\"${summary_jq}\" < \"${summary_json}\" } # filter e2e policy tests results to tests that failed, with the policies they failed # output to ${failures_json} function generate_failures_json() { local -r failures_jq=\"${tmpdir}/failures.jq\" cat >\"${failures_jq}\" < \"${failures_json}\" } function output_results_and_exit_if_failed() { local -r total_tests=$(<\"${spec_summaries}\" wc -l | awk '{print $1}') # output results to console ( echo \"run at datetime: $(date -u +%Y-%m-%dT%H:%M:%SZ)\" echo \"based on commit: $(git log -n1 --date=iso-strict --pretty='%h - %cd - %s')\" echo <\"${failures_json}\" cat printf \"%4s: e2e tests %-40s: %-4dn\" \"INFO\" \"in total\" \"${total_tests}\" <\"${summary_json}\" jq -r 'to_entries[].value | \"printf \"%4s: ..failing %-40s: %-4dn\" \"(.log)\" \"(.reason)\" \"(.failing)\"\"' | sh ) | tee \"${tmpdir}/output.txt\" # if we said \"FAIL\" in that output, we should fail if <\"${tmpdir}/output.txt\" grep -q \"^FAIL\"; then echo \"FAIL\" exit 1 fi } ensure_dependencies generate_results_json generate_failures_json generate_summary_json output_results_and_exit_if_failed echo \"PASS\" "} {"_id":"doc-en-kubernetes-8c422f0d0072c7705a400c82460b621e009c3325abcd788ef1d95265e3cab088","title":"","text":" See [e2e-tests](https://git.k8s.io/community/contributors/devel/sig-testing/e2e-tests.md) # test/e2e This is home to e2e tests used for presubmit, periodic, and postsubmit jobs. Some of these jobs are merge-blocking, some are release-blocking. ## e2e test ownership All e2e tests must adhere to the following policies: - the test must be owned by one and only one SIG - the test must live in/underneath a sig-owned package matching pattern: `test/e2e/[{subpath}/]{sig}/...`, e.g. - `test/e2e/auth` - all tests owned by sig-`auth` - `test/e2e/common/storage` - all tests `common` to cluster-level and node-level e2e tests, owned by sig-`node` - `test/e2e/upgrade/apps` - all tests used in `upgrade` testing, owned by sig-`apps` - each sig-owned package should have an OWNERS file defining relevant approvers and labels for the owning sig, e.g. ```yaml # test/e2e/node/OWNERS # See the OWNERS docs at https://go.k8s.io/owners approvers: - alice - bob - cynthia emeritus_approvers: - dave reviewers: - sig-node-reviewers labels: - sig/node ``` - packages that use `{subpath}` should have an `imports.go` file importing sig-owned packages (for ginkgo's benefit), e.g. ```golang // test/e2e/common/imports.go package common import ( // ensure these packages are scanned by ginkgo for e2e tests _ \"k8s.io/kubernetes/test/e2e/common/network\" _ \"k8s.io/kubernetes/test/e2e/common/node\" _ \"k8s.io/kubernetes/test/e2e/common/storage\" ) ``` - test ownership must be declared via a top-level SIGDescribe call defined in the sig-owned package, e.g. ```golang // test/e2e/lifecycle/framework.go package lifecycle import \"github.com/onsi/ginkgo\" // SIGDescribe annotates the test with the SIG label. func SIGDescribe(text string, body func()) bool { return ginkgo.Describe(\"[sig-cluster-lifecycle] \"+text, body) } ``` ```golang // test/e2e/lifecycle/bootstrap/bootstrap_signer.go package bootstrap import ( \"github.com/onsi/ginkgo\" \"k8s.io/kubernetes/test/e2e/lifecycle\" ) var _ = lifecycle.SIGDescribe(\"[Feature:BootstrapTokens]\", func() { /* ... */ ginkgo.It(\"should sign the new added bootstrap tokens\", func() { /* ... */ }) /* etc */ }) ``` These polices are enforced: - via the merge-blocking presubmit job `pull-kubernetes-verify` - which ends up running `hack/verify-e2e-test-ownership.sh` - which can also be run via `make verify WHAT=e2e-test-ownership` ## more info See [kubernetes/community/.../e2e-tests.md](https://git.k8s.io/community/contributors/devel/sig-testing/e2e-tests.md) "} {"_id":"doc-en-kubernetes-05a2b7a20f822376a43078fec4c2468d44cc392615d8001bae060b7ee9b89369","title":"","text":"// barrierOp defines an op that can be used to wait until all scheduled pods of // one or many namespaces have been bound to nodes. This is useful when pods // were scheduled with SkipWaitToCompletion set to true. A barrierOp is added // at the end of each each workload automatically. // were scheduled with SkipWaitToCompletion set to true. type barrierOp struct { // Must be \"barrier\". Opcode string"} {"_id":"doc-en-kubernetes-545d73124c7352f17c95197af04ca2b83793020fad9d36b2211575d76059660b","title":"","text":"b.Fatalf(\"op %d: invalid op %v\", opIndex, concreteOp) } } if err := waitUntilPodsScheduled(ctx, podInformer, b.Name(), nil, numPodsScheduledPerNamespace); err != nil { // Any pending pods must be scheduled before this test can be considered to // be complete. b.Fatal(err) } // Some tests have unschedulable pods. Do not add an implicit barrier at the // end as we do not want to wait for them. return dataItems }"} {"_id":"doc-en-kubernetes-76bcd096da015206c4577368fbe728f91e3e2c15e1a79e751169322546f5170e","title":"","text":"apps/v1/Deployment apps/v1/ReplicaSet apps/v1/StatefulSet extensions/v1beta1/Ingress networking.k8s.io/v1/Ingress ) else read -ra KUBECTL_PRUNE_WHITELIST <<< \"${KUBECTL_PRUNE_WHITELIST_OVERRIDE}\""} {"_id":"doc-en-kubernetes-db6ae1d0936ca6f844678e5248fef9eb2ede4478cec081c99e4be8d3cc607fef","title":"","text":"func getRESTMappings(mapper meta.RESTMapper, pruneResources *[]pruneResource) (namespaced, nonNamespaced []*meta.RESTMapping, err error) { if len(*pruneResources) == 0 { // default whitelist // TODO: need to handle the older api versions - e.g. v1beta1 jobs. Github issue: #35991 // default allowlist *pruneResources = []pruneResource{ {\"\", \"v1\", \"ConfigMap\", true}, {\"\", \"v1\", \"Endpoints\", true},"} {"_id":"doc-en-kubernetes-ac727fac7e108b3438185fed0f5112cebc76c2250db1ac7b59dba3bc1197c774","title":"","text":"{\"\", \"v1\", \"Service\", true}, {\"batch\", \"v1\", \"Job\", true}, {\"batch\", \"v1beta1\", \"CronJob\", true}, {\"extensions\", \"v1beta1\", \"Ingress\", true}, {\"networking.k8s.io\", \"v1\", \"Ingress\", true}, {\"apps\", \"v1\", \"DaemonSet\", true}, {\"apps\", \"v1\", \"Deployment\", true}, {\"apps\", \"v1\", \"ReplicaSet\", true},"} {"_id":"doc-en-kubernetes-21e43db0f187f6733f9b7606cfa3c7b9a7f5fd8e1b29d9ab631b22b952b664e4","title":"","text":"observations, _ := makeSignalObservations(summary) debugLogObservations(\"observations after resource reclaim\", observations) // determine the set of thresholds met independent of grace period thresholds := thresholdsMet(m.config.Thresholds, observations, false) // evaluate all thresholds independently of their grace period to see if with // the new observations, we think we have met min reclaim goals thresholds := thresholdsMet(m.config.Thresholds, observations, true) debugLogThresholdsWithObservation(\"thresholds after resource reclaim - ignoring grace period\", thresholds, observations) if len(thresholds) == 0 {"} {"_id":"doc-en-kubernetes-9510fa1f77170ef19cdac46e6e5022588168bdc16e92e5eb44550763b54bb137","title":"","text":"t.Errorf(\"Manager should not report disk pressure\") } // synchronize manager.synchronize(diskInfoProvider, activePodsFunc) // we should not have disk pressure if manager.IsUnderDiskPressure() { t.Errorf(\"Manager should not report disk pressure\") } // induce hard threshold fakeClock.Step(1 * time.Minute) summaryProvider.result = summaryStatsMaker(\".9Gi\", \"200Gi\", podStats) // make GC return disk usage bellow the threshold, but not satisfying minReclaim diskGC.summaryAfterGC = summaryStatsMaker(\"1.1Gi\", \"200Gi\", podStats) manager.synchronize(diskInfoProvider, activePodsFunc) // we should have disk pressure if !manager.IsUnderDiskPressure() { t.Errorf(\"Manager should report disk pressure since soft threshold was met\") } // verify image gc was invoked if !diskGC.imageGCInvoked || !diskGC.containerGCInvoked { t.Errorf(\"Manager should have invoked image gc\") } // verify a pod was killed because image gc was not enough to satisfy minReclaim if podKiller.pod == nil { t.Errorf(\"Manager should have killed a pod, but didn't\") } // reset state diskGC.imageGCInvoked = false diskGC.containerGCInvoked = false podKiller.pod = nil // remove disk pressure fakeClock.Step(20 * time.Minute) summaryProvider.result = summaryStatsMaker(\"16Gi\", \"200Gi\", podStats) manager.synchronize(diskInfoProvider, activePodsFunc) // we should not have disk pressure if manager.IsUnderDiskPressure() { t.Errorf(\"Manager should not report disk pressure\") } // induce disk pressure! fakeClock.Step(1 * time.Minute) summaryProvider.result = summaryStatsMaker(\"400Mi\", \"200Gi\", podStats)"} {"_id":"doc-en-kubernetes-375dce87c4ce5fa71d124113687d3debf767251e27a1182e12c33ce1993f4a21","title":"","text":"PromoterE2eRegistry string `yaml:\"promoterE2eRegistry\"` BuildImageRegistry string `yaml:\"buildImageRegistry\"` InvalidRegistry string `yaml:\"invalidRegistry\"` GcHttpdRegistry string `yaml:\"gcHttpdRegistry\"` GcEtcdRegistry string `yaml:\"gcEtcdRegistry\"` GcRegistry string `yaml:\"gcRegistry\"` SigStorageRegistry string `yaml:\"sigStorageRegistry\"`"} {"_id":"doc-en-kubernetes-6ab01ee11bc794020b072780c834d2cf8cd850a1c86f034cab7bd8762d4f7598","title":"","text":"BuildImageRegistry: \"k8s.gcr.io/build-image\", InvalidRegistry: \"invalid.com/invalid\", GcEtcdRegistry: \"k8s.gcr.io\", GcHttpdRegistry: \"k8s.gcr.io/e2e-test-images\", GcRegistry: \"k8s.gcr.io\", SigStorageRegistry: \"k8s.gcr.io/sig-storage\", GcrReleaseRegistry: \"gcr.io/gke-release\","} {"_id":"doc-en-kubernetes-569a1a50c0216e1cea480eb282a889b1961603596cc905bb4358c54a7b841dbe","title":"","text":"buildImageRegistry = registry.BuildImageRegistry gcAuthenticatedRegistry = registry.GcAuthenticatedRegistry gcEtcdRegistry = registry.GcEtcdRegistry gcHttpdRegistry = registry.GcHttpdRegistry gcRegistry = registry.GcRegistry sigStorageRegistry = registry.SigStorageRegistry gcrReleaseRegistry = registry.GcrReleaseRegistry"} {"_id":"doc-en-kubernetes-f1cc29d49d55be9475750aa201d7e8e5f1fe5fce8a62ebc6799d02aaffdf170b","title":"","text":"configs[EchoServer] = Config{promoterE2eRegistry, \"echoserver\", \"2.3\"} configs[Etcd] = Config{gcEtcdRegistry, \"etcd\", \"3.4.13-0\"} configs[GlusterDynamicProvisioner] = Config{promoterE2eRegistry, \"glusterdynamic-provisioner\", \"v1.0\"} configs[Httpd] = Config{gcHttpdRegistry, \"httpd\", \"2.4.38-alpine\"} configs[HttpdNew] = Config{gcHttpdRegistry, \"httpd\", \"2.4.39-alpine\"} configs[Httpd] = Config{promoterE2eRegistry, \"httpd\", \"2.4.38-1\"} configs[HttpdNew] = Config{promoterE2eRegistry, \"httpd\", \"2.4.39-1\"} configs[InvalidRegistryImage] = Config{invalidRegistry, \"alpine\", \"3.1\"} configs[IpcUtils] = Config{promoterE2eRegistry, \"ipc-utils\", \"1.2\"} configs[JessieDnsutils] = Config{promoterE2eRegistry, \"jessie-dnsutils\", \"1.4\"} configs[Kitten] = Config{promoterE2eRegistry, \"kitten\", \"1.4\"} configs[Nautilus] = Config{promoterE2eRegistry, \"nautilus\", \"1.4\"} configs[NFSProvisioner] = Config{sigStorageRegistry, \"nfs-provisioner\", \"v2.2.2\"} configs[Nginx] = Config{promoterE2eRegistry, \"nginx\", \"1.14-alpine\"} configs[NginxNew] = Config{promoterE2eRegistry, \"nginx\", \"1.15-alpine\"} configs[Nginx] = Config{promoterE2eRegistry, \"nginx\", \"1.14-1\"} configs[NginxNew] = Config{promoterE2eRegistry, \"nginx\", \"1.15-1\"} configs[NodePerfNpbEp] = Config{promoterE2eRegistry, \"node-perf/npb-ep\", \"1.1\"} configs[NodePerfNpbIs] = Config{promoterE2eRegistry, \"node-perf/npb-is\", \"1.1\"} configs[NodePerfTfWideDeep] = Config{promoterE2eRegistry, \"node-perf/tf-wide-deep\", \"1.1\"}"} {"_id":"doc-en-kubernetes-541331541cc1395804b28ff0ffdf413be825390e9c5aac1c9d174671af4215c0","title":"","text":"return defaultPlugins } type pluginIndex struct { index int plugin v1beta2.Plugin } func mergePluginSet(defaultPluginSet, customPluginSet v1beta2.PluginSet) v1beta2.PluginSet { disabledPlugins := sets.NewString() enabledCustomPlugins := make(map[string]pluginIndex) for _, disabledPlugin := range customPluginSet.Disabled { disabledPlugins.Insert(disabledPlugin.Name) } for index, enabledPlugin := range customPluginSet.Enabled { enabledCustomPlugins[enabledPlugin.Name] = pluginIndex{index, enabledPlugin} } var enabledPlugins []v1beta2.Plugin if !disabledPlugins.Has(\"*\") { for _, defaultEnabledPlugin := range defaultPluginSet.Enabled { if disabledPlugins.Has(defaultEnabledPlugin.Name) { continue } // The default plugin is explicitly re-configured, update the default plugin accordingly. if customPlugin, ok := enabledCustomPlugins[defaultEnabledPlugin.Name]; ok { klog.InfoS(\"Defaut plugin is explicitly re-configured and is overriding.\", \"plugin\", defaultEnabledPlugin.Name) // update the default plugin in place to preserve order defaultEnabledPlugin = customPlugin.plugin // kick the plugin from the enabled list of custom plugins customPluginSet.Enabled = append(customPluginSet.Enabled[:customPlugin.index], customPluginSet.Enabled[customPlugin.index+1:]...) } enabledPlugins = append(enabledPlugins, defaultEnabledPlugin) } }"} {"_id":"doc-en-kubernetes-c0c9b00ce7841b7c9e04cf4329354cdede310ef88a79381acc15549fe79693e0","title":"","text":"}, }, }, { name: \"CustomPluginOverrideDefaultPlugin\", customPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin1\", Weight: pointer.Int32Ptr(2)}, }, }, }, defaultPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin1\"}, }, }, }, expectedPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin1\", Weight: pointer.Int32Ptr(2)}, }, }, }, }, { name: \"OrderPreserveAfterOverride\", customPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin2\", Weight: pointer.Int32Ptr(2)}, }, }, }, defaultPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin1\"}, {Name: \"Plugin2\"}, {Name: \"Plugin3\"}, }, }, }, expectedPlugins: &v1beta2.Plugins{ Filter: v1beta2.PluginSet{ Enabled: []v1beta2.Plugin{ {Name: \"Plugin1\"}, {Name: \"Plugin2\", Weight: pointer.Int32Ptr(2)}, {Name: \"Plugin3\"}, }, }, }, }, } for _, test := range tests {"} {"_id":"doc-en-kubernetes-b668a9d3ee76c9b51f84432aa2e53208468ac927d1937a3a6c8328f8370a9894","title":"","text":"// If an array is empty, missing, or nil, default plugins at that extension point will be used. type PluginSet struct { // Enabled specifies plugins that should be enabled in addition to default plugins. // If the default plugin is also configured in the scheduler config file, the weight of plugin will // be overridden accordingly. // These are called after default plugins and in the same order specified here. // +listType=atomic Enabled []Plugin `json:\"enabled,omitempty\"`"} {"_id":"doc-en-kubernetes-4e89057427add5d89ea34e7d0d4e3be73b2b9967cfa2cd627966eeaa6a216e7b","title":"","text":"get-kubeconfig-basicauth if [[ ${GCE_UPLOAD_KUBCONFIG_TO_MASTER_METADATA:-} == \"true\" ]]; then gcloud compute instances add-metadata \"${MASTER_NAME}\" --zone=\"${ZONE}\" --metadata-from-file=\"kubeconfig=${KUBECONFIG}\" || true gcloud compute instances add-metadata \"${MASTER_NAME}\" --project=\"${PROJECT}\" --zone=\"${ZONE}\" --metadata-from-file=\"kubeconfig=${KUBECONFIG}\" || true fi echo"} {"_id":"doc-en-kubernetes-2c486f7e048f9ef2fb214fc46208e15ec418bdb47e1c7740a61ec01f49576479","title":"","text":" /* Copyright 2014 Google Inc. 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. */ package cloudcfg import ( \"bytes\" \"encoding/json\" \"reflect\" \"testing\" \"gopkg.in/v1/yaml\" ) func TestYAMLPrinterPrint(t *testing.T) { type testStruct struct { Key string `yaml:\"Key\" json:\"Key\"` Map map[string]int `yaml:\"Map\" json:\"Map\"` StringList []string `yaml:\"StringList\" json:\"StringList\"` IntList []int `yaml:\"IntList\" json:\"IntList\"` } testData := testStruct{ \"testValue\", map[string]int{\"TestSubkey\": 1}, []string{\"a\", \"b\", \"c\"}, []int{1, 2, 3}, } printer := &YAMLPrinter{} buf := bytes.NewBuffer([]byte{}) err := printer.Print([]byte(\"invalidJSON\"), buf) if err == nil { t.Error(\"Error: didn't fail on invalid JSON data\") } jTestData, err := json.Marshal(&testData) if err != nil { t.Fatal(\"Unexpected error: couldn't marshal test data\") } err = printer.Print(jTestData, buf) if err != nil { t.Fatal(err) } var poutput testStruct err = yaml.Unmarshal(buf.Bytes(), &poutput) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(testData, poutput) { t.Error(\"Test data and unmarshaled data are not equal\") } } "} {"_id":"doc-en-kubernetes-2ecedb8b91c3a70135c866d6a8045670959a16458ee08b9a327170d0fb5aa656","title":"","text":"\"runtime\" v1 \"k8s.io/api/core/v1\" \"k8s.io/component-helpers/scheduling/corev1\" \"k8s.io/klog/v2\" v1helper \"k8s.io/kubernetes/pkg/apis/core/v1/helper\" \"k8s.io/kubernetes/pkg/kubelet/types\" \"k8s.io/kubernetes/pkg/scheduler\" schedulerframework \"k8s.io/kubernetes/pkg/scheduler/framework\" \"k8s.io/kubernetes/pkg/scheduler/framework/plugins/tainttoleration\" ) type getNodeAnyWayFuncType func() (*v1.Node, error)"} {"_id":"doc-en-kubernetes-1edae5d84c04990bfde8259899302b259f5327a9d6aa8ed3dcc1bf515bf34fa0","title":"","text":"reasons = append(reasons, &PredicateFailureError{r.Name, r.Reason}) } } // Check taint/toleration except for static pods if !types.IsStaticPod(pod) { _, isUntolerated := corev1.FindMatchingUntoleratedTaint(nodeInfo.Node().Spec.Taints, pod.Spec.Tolerations, func(t *v1.Taint) bool { // Kubelet is only interested in the NoExecute taint. return t.Effect == v1.TaintEffectNoExecute }) if isUntolerated { reasons = append(reasons, &PredicateFailureError{tainttoleration.Name, tainttoleration.ErrReasonNotMatch}) } } return reasons }"} {"_id":"doc-en-kubernetes-490e507eee5f304ab7e550f917dc995f5046cbdcadec37f8a9ff186191104401","title":"","text":"\"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" v1helper \"k8s.io/kubernetes/pkg/apis/core/v1/helper\" \"k8s.io/kubernetes/pkg/kubelet/types\" schedulerframework \"k8s.io/kubernetes/pkg/scheduler/framework\" \"k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodename\" \"k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodeports\" \"k8s.io/kubernetes/pkg/scheduler/framework/plugins/tainttoleration\" ) var ("} {"_id":"doc-en-kubernetes-dcc7eb5e3f9a2d0acc07966f04433b2ca6957fc108c11a5d45aa973c72a7b72b","title":"","text":"reasons: []PredicateFailureReason{&PredicateFailureError{nodeports.Name, nodeports.ErrReason}}, name: \"hostport conflict\", }, { pod: &v1.Pod{ Spec: v1.PodSpec{ Tolerations: []v1.Toleration{ {Key: \"foo\"}, {Key: \"bar\"}, }, }, }, nodeInfo: schedulerframework.NewNodeInfo(), node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: \"machine1\"}, Spec: v1.NodeSpec{ Taints: []v1.Taint{ {Key: \"foo\", Effect: v1.TaintEffectNoSchedule}, {Key: \"bar\", Effect: v1.TaintEffectNoExecute}, }, }, Status: v1.NodeStatus{Capacity: makeResources(10, 20, 32, 0, 0, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 32, 0, 0, 0)}, }, name: \"taint/toleration match\", }, { pod: &v1.Pod{}, nodeInfo: schedulerframework.NewNodeInfo(), node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: \"machine1\"}, Spec: v1.NodeSpec{ Taints: []v1.Taint{ {Key: \"foo\", Effect: v1.TaintEffectNoSchedule}, }, }, Status: v1.NodeStatus{Capacity: makeResources(10, 20, 32, 0, 0, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 32, 0, 0, 0)}, }, name: \"NoSchedule taint/toleration not match\", }, { pod: &v1.Pod{}, nodeInfo: schedulerframework.NewNodeInfo(), node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: \"machine1\"}, Spec: v1.NodeSpec{ Taints: []v1.Taint{ {Key: \"bar\", Effect: v1.TaintEffectNoExecute}, }, }, Status: v1.NodeStatus{Capacity: makeResources(10, 20, 32, 0, 0, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 32, 0, 0, 0)}, }, reasons: []PredicateFailureReason{&PredicateFailureError{tainttoleration.Name, tainttoleration.ErrReasonNotMatch}}, name: \"NoExecute taint/toleration not match\", }, { pod: &v1.Pod{}, nodeInfo: schedulerframework.NewNodeInfo(), node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: \"machine1\"}, Spec: v1.NodeSpec{ Taints: []v1.Taint{ {Key: \"baz\", Effect: v1.TaintEffectPreferNoSchedule}, }, }, Status: v1.NodeStatus{Capacity: makeResources(10, 20, 32, 0, 0, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 32, 0, 0, 0)}, }, name: \"PreferNoSchedule taint/toleration not match\", }, { pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ types.ConfigSourceAnnotationKey: types.FileSource, }, }, }, nodeInfo: schedulerframework.NewNodeInfo(), node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: \"machine1\"}, Spec: v1.NodeSpec{ Taints: []v1.Taint{ {Key: \"foo\", Effect: v1.TaintEffectNoSchedule}, {Key: \"bar\", Effect: v1.TaintEffectNoExecute}, }, }, Status: v1.NodeStatus{Capacity: makeResources(10, 20, 32, 0, 0, 0).Capacity, Allocatable: makeAllocatableResources(10, 20, 32, 0, 0, 0)}, }, name: \"static pods ignore taints\", }, } for _, test := range resourceTests { t.Run(test.name, func(t *testing.T) {"} {"_id":"doc-en-kubernetes-8a81883507a9f566bec79d546c2f7a552ba7f8449f38fc576aa8966631ffcaef","title":"","text":"\"text/tabwriter\" \"time\" \"k8s.io/client-go/tools/cache\" \"github.com/onsi/ginkgo\" \"github.com/onsi/gomega\" appsv1 \"k8s.io/api/apps/v1\""} {"_id":"doc-en-kubernetes-95fd7eaa938f97d850bf43a91cce8182dd82272a955e56de8e1205bb9bed9a6a","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/wait\" watch \"k8s.io/apimachinery/pkg/watch\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/client-go/kubernetes/scheme\" watchtools \"k8s.io/client-go/tools/watch\" \"k8s.io/client-go/util/retry\" podutil \"k8s.io/kubernetes/pkg/api/v1/pod\" extensionsinternal \"k8s.io/kubernetes/pkg/apis/extensions\" \"k8s.io/kubernetes/pkg/controller/daemon\""} {"_id":"doc-en-kubernetes-dab94e9300bd165267386541b3e3ca0ec3f0606208a7d33482fe129773575803","title":"","text":"framework.ExpectNoError(err, \"failed to list DaemonSets\") framework.ExpectEqual(len(dsList.Items), 0, \"filtered list should have no daemonset\") }) ginkgo.It(\"should verify changes to a daemon set status\", func() { label := map[string]string{daemonsetNameLabel: dsName} labelSelector := labels.SelectorFromSet(label).String() dsClient := f.ClientSet.AppsV1().DaemonSets(ns) cs := f.ClientSet w := &cache.ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.LabelSelector = labelSelector return dsClient.Watch(context.TODO(), options) }, } dsList, err := cs.AppsV1().DaemonSets(\"\").List(context.TODO(), metav1.ListOptions{LabelSelector: labelSelector}) framework.ExpectNoError(err, \"failed to list Daemon Sets\") ginkgo.By(fmt.Sprintf(\"Creating simple DaemonSet %q\", dsName)) testDaemonset, err := c.AppsV1().DaemonSets(ns).Create(context.TODO(), newDaemonSetWithLabel(dsName, image, label), metav1.CreateOptions{}) framework.ExpectNoError(err) ginkgo.By(\"Check that daemon pods launch on every node of the cluster.\") err = wait.PollImmediate(dsRetryPeriod, dsRetryTimeout, checkRunningOnAllNodes(f, testDaemonset)) framework.ExpectNoError(err, \"error waiting for daemon pod to start\") err = checkDaemonStatus(f, dsName) framework.ExpectNoError(err) ginkgo.By(\"Getting /status\") dsResource := schema.GroupVersionResource{Group: \"apps\", Version: \"v1\", Resource: \"daemonsets\"} dsStatusUnstructured, err := f.DynamicClient.Resource(dsResource).Namespace(ns).Get(context.TODO(), dsName, metav1.GetOptions{}, \"status\") framework.ExpectNoError(err, \"Failed to fetch the status of daemon set %s in namespace %s\", dsName, ns) dsStatusBytes, err := json.Marshal(dsStatusUnstructured) framework.ExpectNoError(err, \"Failed to marshal unstructured response. %v\", err) var dsStatus appsv1.DaemonSet err = json.Unmarshal(dsStatusBytes, &dsStatus) framework.ExpectNoError(err, \"Failed to unmarshal JSON bytes to a daemon set object type\") framework.Logf(\"Daemon Set %s has Conditions: %v\", dsName, dsStatus.Status.Conditions) ginkgo.By(\"updating the DaemonSet Status\") var statusToUpdate, updatedStatus *appsv1.DaemonSet err = retry.RetryOnConflict(retry.DefaultRetry, func() error { statusToUpdate, err = dsClient.Get(context.TODO(), dsName, metav1.GetOptions{}) framework.ExpectNoError(err, \"Unable to retrieve daemon set %s\", dsName) statusToUpdate.Status.Conditions = append(statusToUpdate.Status.Conditions, appsv1.DaemonSetCondition{ Type: \"StatusUpdate\", Status: \"True\", Reason: \"E2E\", Message: \"Set from e2e test\", }) updatedStatus, err = dsClient.UpdateStatus(context.TODO(), statusToUpdate, metav1.UpdateOptions{}) return err }) framework.ExpectNoError(err, \"Failed to update status. %v\", err) framework.Logf(\"updatedStatus.Conditions: %#v\", updatedStatus.Status.Conditions) ginkgo.By(\"watching for the daemon set status to be updated\") ctx, cancel := context.WithTimeout(context.Background(), dsRetryTimeout) defer cancel() _, err = watchtools.Until(ctx, dsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if ds, ok := event.Object.(*appsv1.DaemonSet); ok { found := ds.ObjectMeta.Name == testDaemonset.ObjectMeta.Name && ds.ObjectMeta.Namespace == testDaemonset.ObjectMeta.Namespace && ds.Labels[daemonsetNameLabel] == dsName if !found { framework.Logf(\"Observed daemon set %v in namespace %v with annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.Annotations, ds.Status.Conditions) return false, nil } for _, cond := range ds.Status.Conditions { if cond.Type == \"StatusUpdate\" && cond.Reason == \"E2E\" && cond.Message == \"Set from e2e test\" { framework.Logf(\"Found daemon set %v in namespace %v with labels: %v annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.ObjectMeta.Labels, ds.Annotations, ds.Status.Conditions) return found, nil } framework.Logf(\"Observed daemon set %v in namespace %v with annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.Annotations, ds.Status.Conditions) } } object := strings.Split(fmt.Sprintf(\"%v\", event.Object), \"{\")[0] framework.Logf(\"Observed %v event: %+v\", object, event.Type) return false, nil }) framework.ExpectNoError(err, \"failed to locate daemon set %v in namespace %v\", testDaemonset.ObjectMeta.Name, ns) framework.Logf(\"Daemon set %s has an updated status\", dsName) ginkgo.By(\"patching the DaemonSet Status\") daemonSetStatusPatch := appsv1.DaemonSet{ Status: appsv1.DaemonSetStatus{ Conditions: []appsv1.DaemonSetCondition{ { Type: \"StatusPatched\", Status: \"True\", }, }, }, } payload, err := json.Marshal(daemonSetStatusPatch) framework.ExpectNoError(err, \"Failed to marshal JSON. %v\", err) _, err = dsClient.Patch(context.TODO(), dsName, types.MergePatchType, payload, metav1.PatchOptions{}, \"status\") framework.ExpectNoError(err, \"Failed to patch daemon set status\", err) ginkgo.By(\"watching for the daemon set status to be patched\") ctx, cancel = context.WithTimeout(context.Background(), dsRetryTimeout) defer cancel() _, err = watchtools.Until(ctx, dsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if ds, ok := event.Object.(*appsv1.DaemonSet); ok { found := ds.ObjectMeta.Name == testDaemonset.ObjectMeta.Name && ds.ObjectMeta.Namespace == testDaemonset.ObjectMeta.Namespace && ds.Labels[daemonsetNameLabel] == dsName if !found { framework.Logf(\"Observed daemon set %v in namespace %v with annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.Annotations, ds.Status.Conditions) return false, nil } for _, cond := range ds.Status.Conditions { if cond.Type == \"StatusPatched\" { framework.Logf(\"Found daemon set %v in namespace %v with labels: %v annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.ObjectMeta.Labels, ds.Annotations, ds.Status.Conditions) return found, nil } framework.Logf(\"Observed daemon set %v in namespace %v with annotations: %v & Conditions: %v\", ds.ObjectMeta.Name, ds.ObjectMeta.Namespace, ds.Annotations, ds.Status.Conditions) } } object := strings.Split(fmt.Sprintf(\"%v\", event.Object), \"{\")[0] framework.Logf(\"Observed %v event: %v\", object, event.Type) return false, nil }) framework.ExpectNoError(err, \"failed to locate daemon set %v in namespace %v\", testDaemonset.ObjectMeta.Name, ns) framework.Logf(\"Daemon set %s has a patched status\", dsName) }) }) // randomPod selects a random pod within pods that causes fn to return true, or nil"} {"_id":"doc-en-kubernetes-d926a6076da3150cd3d93907d6103eabf533e7073118e58b8c8ca9e102aeb966","title":"","text":"description: A conformant Kubernetes distribution MUST support DaemonSet RollingUpdates. release: v1.10 file: test/e2e/apps/daemon_set.go - testname: DaemonSet, status sub-resource codename: '[sig-apps] Daemon set [Serial] should verify changes to a daemon set status [Conformance]' description: When a DaemonSet is created it MUST succeed. Attempt to read, update and patch its status sub-resource; all mutating sub-resource operations MUST be visible to subsequent reads. release: v1.22 file: test/e2e/apps/daemon_set.go - testname: Deployment, completes the scaling of a Deployment subresource codename: '[sig-apps] Deployment Deployment should have a working scale subresource [Conformance]'"} {"_id":"doc-en-kubernetes-bb5b6f6bb11d1bb0e37a23a44401e89768c7aba303e84cb5f2504133ba621778","title":"","text":"framework.ExpectEqual(len(dsList.Items), 0, \"filtered list should have no daemonset\") }) ginkgo.It(\"should verify changes to a daemon set status\", func() { /*\tRelease: v1.22 Testname: DaemonSet, status sub-resource Description: When a DaemonSet is created it MUST succeed. Attempt to read, update and patch its status sub-resource; all mutating sub-resource operations MUST be visible to subsequent reads. */ framework.ConformanceIt(\"should verify changes to a daemon set status\", func() { label := map[string]string{daemonsetNameLabel: dsName} labelSelector := labels.SelectorFromSet(label).String()"} {"_id":"doc-en-kubernetes-0b56a93fdff453c012fe0d54981bdcf7835417c51df20f96811b5b8fe1166542","title":"","text":"rules: # Discourage import of k8s.io/kubernetes/test/e2e - selectorRegexp: k8s[.]io/kubernetes/test/e2e # TODO: import-boss --include-test-files is catching these; drive to zero allowedPrefixes: # test/integration/auth/bootstraptoken_test.go is using this - k8s.io/kubernetes/test/e2e/lifecycle/bootstrap forbiddenPrefixes: - \"\" "} {"_id":"doc-en-kubernetes-96442a29a9209b36a57f18ffba8f4e7c52a1628e2f084e5a0c54874459b95b3f","title":"","text":"\"k8s.io/apiserver/pkg/authentication/request/bearertoken\" bootstrapapi \"k8s.io/cluster-bootstrap/token/api\" \"k8s.io/kubernetes/plugin/pkg/auth/authenticator/token/bootstrap\" bootstraputil \"k8s.io/kubernetes/test/e2e/lifecycle/bootstrap\" \"k8s.io/kubernetes/test/integration\" \"k8s.io/kubernetes/test/integration/framework\" )"} {"_id":"doc-en-kubernetes-9899f3cfef31b7d55b77dfe86ae87258a8ac5f5cea75016074057d1cc5eb0c66","title":"","text":"// TestBootstrapTokenAuth tests the bootstrap token auth provider func TestBootstrapTokenAuth(t *testing.T) { tokenID, err := bootstraputil.GenerateTokenID() if err != nil { t.Fatalf(\"unexpected error: %v\", err) } secret, err := bootstraputil.GenerateTokenSecret() if err != nil { t.Fatalf(\"unexpected error: %v\", err) } validTokenID := \"token1\" validSecret := \"validtokensecret\" var bootstrapSecretValid = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceSystem,"} {"_id":"doc-en-kubernetes-5b972b418857f0893c0e93b7a093b17d4d9c155fe44da693e2f063275c2f28be","title":"","text":"}, Type: corev1.SecretTypeBootstrapToken, Data: map[string][]byte{ bootstrapapi.BootstrapTokenIDKey: []byte(tokenID), bootstrapapi.BootstrapTokenSecretKey: []byte(secret), bootstrapapi.BootstrapTokenIDKey: []byte(validTokenID), bootstrapapi.BootstrapTokenSecretKey: []byte(validSecret), bootstrapapi.BootstrapTokenUsageAuthentication: []byte(\"true\"), }, }"} {"_id":"doc-en-kubernetes-3409d76a20d8c9a628e6c8c79d8afbe3b022cf78e5ffaf00461662d11861e63a","title":"","text":"}, Type: corev1.SecretTypeBootstrapToken, Data: map[string][]byte{ bootstrapapi.BootstrapTokenIDKey: []byte(tokenID), bootstrapapi.BootstrapTokenIDKey: []byte(validTokenID), bootstrapapi.BootstrapTokenSecretKey: []byte(\"invalid\"), bootstrapapi.BootstrapTokenUsageAuthentication: []byte(\"true\"), }, } tokenExpiredTime := time.Now().Add(-time.Hour).Format(time.RFC3339) var expiredBootstrapToken = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceSystem,"} {"_id":"doc-en-kubernetes-6a95f9acd35ff5eeb6ff523fc740f0ded01f67a30ef9ef6a61db491ec630e7f8","title":"","text":"}, Type: corev1.SecretTypeBootstrapToken, Data: map[string][]byte{ bootstrapapi.BootstrapTokenIDKey: []byte(tokenID), bootstrapapi.BootstrapTokenIDKey: []byte(validTokenID), bootstrapapi.BootstrapTokenSecretKey: []byte(\"invalid\"), bootstrapapi.BootstrapTokenUsageAuthentication: []byte(\"true\"), bootstrapapi.BootstrapTokenExpirationKey: []byte(bootstraputil.TimeStringFromNow(-time.Hour)), bootstrapapi.BootstrapTokenExpirationKey: []byte(tokenExpiredTime), }, } type request struct {"} {"_id":"doc-en-kubernetes-5b124041f62330486de31359b02a052616298a2af0482196d530d05a43ba36f4","title":"","text":"previousResourceVersion := make(map[string]float64) transport := http.DefaultTransport token := tokenID + \".\" + secret token := validTokenID + \".\" + validSecret var bodyStr string if test.request.body != \"\" { sub := \"\""} {"_id":"doc-en-kubernetes-e553bbf147f15f3d32367fbbd8510c1c1a29107453880334160372a8d98f4062","title":"","text":"# agnhost: bump this one first - name: \"agnhost\" version: \"2.30\" version: \"2.31\" refPaths: - path: test/images/agnhost/VERSION match: d.d"} {"_id":"doc-en-kubernetes-828745884d87ba7c0281e64e96de48d46bd86f891c8ce96faa179fa2a55eecde","title":"","text":" 2.30 2.31 "} {"_id":"doc-en-kubernetes-5607f1fc4293c74880123a9895456d20535e62ed1bfeb55af79be8e19cfe1da0","title":"","text":"func main() { rootCmd := &cobra.Command{ Use: \"app\", Version: \"2.30\", Version: \"2.31\", } rootCmd.AddCommand(auditproxy.CmdAuditProxy)"} {"_id":"doc-en-kubernetes-1ae328463e5509eed2af093199f720a9e6ed0dd8711bc27c51bee3ae1cf0dbf3","title":"","text":"} log.Printf(\"OK: Constructed OIDC provider for issuer %v\", unsafeClaims.Issuer) validTok, err := iss.Verifier(&oidc.Config{ClientID: audience}).Verify(ctx, raw) validTok, err := iss.Verifier(&oidc.Config{ ClientID: audience, SupportedSigningAlgs: []string{oidc.RS256, oidc.ES256}, }).Verify(ctx, raw) if err != nil { log.Fatal(err) }"} {"_id":"doc-en-kubernetes-d7a2ee865fa6f7319cad03246fe880592911b110f4260090346995bf155223cf","title":"","text":"} if shareName == \"\" { // File share name has a length limit of 63, and it cannot contain two consecutive '-'s. // File share name has a length limit of 63, it cannot contain two consecutive '-'s, and all letters must be lower case. name := util.GenerateVolumeName(a.options.ClusterName, a.options.PVName, 63) shareName = strings.Replace(name, \"--\", \"-\", -1) shareName = strings.ToLower(shareName) } if resourceGroup == \"\" {"} {"_id":"doc-en-kubernetes-22540672de86a5007fb6b7bf97f774baaa3475eba602834e13721f76b9a70a7c","title":"","text":"export PROJECT=\"k8s-jkns-e2e-gke-prod\" export CLOUDSDK_BUCKET=\"gs://cloud-sdk-testing/rc\" export JENKINS_USE_SERVER_VERSION=\"y\" export CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER=\"https://container.googleapis.com/\" export ZONE=\"asia-east1-b\" - 'gke-prod-parallel': description: 'Run E2E tests on GKE prod endpoint in parallel.'"} {"_id":"doc-en-kubernetes-4047f9061e73eb748c448e78261f1278ed7b2fea8fb58b04721403fba5df27dd","title":"","text":"export PROJECT=\"k8s-e2e-gke-prod-parallel\" export CLOUDSDK_BUCKET=\"gs://cloud-sdk-testing/rc\" export JENKINS_USE_SERVER_VERSION=\"y\" export CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER=\"https://container.googleapis.com/\" export GINKGO_TEST_ARGS=\"--ginkgo.skip=[Slow]|[Serial]|[Disruptive]|[Flaky]|[Feature:.+]\" export GINKGO_PARALLEL=\"y\" export ZONE=\"asia-east1-b\""} {"_id":"doc-en-kubernetes-12ef90ec8fcf6aae14ab5ba4ed0940f2fdfcb9d80d484b438b036051f6c7dc94","title":"","text":"// newDefaultFieldManager is a helper function which wraps a Manager with certain default logic. func newDefaultFieldManager(f Manager, typeConverter TypeConverter, objectConverter runtime.ObjectConvertor, objectCreater runtime.ObjectCreater, kind schema.GroupVersionKind, ignoreManagedFieldsFromRequestObject bool) *FieldManager { f = NewManagedFieldsUpdater(f) f = NewStripMetaManager(f) f = NewBuildManagerInfoManager(f, kind.GroupVersion()) f = NewCapManagersManager(f, DefaultMaxUpdateManagers) f = NewProbabilisticSkipNonAppliedManager(f, objectCreater, kind, DefaultTrackOnCreateProbability) f = NewLastAppliedManager(f, typeConverter, objectConverter, kind.GroupVersion()) f = NewLastAppliedUpdater(f) return NewFieldManager(f, ignoreManagedFieldsFromRequestObject) return NewFieldManager( NewLastAppliedUpdater( NewLastAppliedManager( NewProbabilisticSkipNonAppliedManager( NewCapManagersManager( NewBuildManagerInfoManager( NewManagedFieldsUpdater( NewStripMetaManager(f), ), kind.GroupVersion(), ), DefaultMaxUpdateManagers, ), objectCreater, kind, DefaultTrackOnCreateProbability, ), typeConverter, objectConverter, kind.GroupVersion()), ), ignoreManagedFieldsFromRequestObject, ) } // DecodeManagedFields converts ManagedFields from the wire format (api format)"} {"_id":"doc-en-kubernetes-aefab3d14d88f0537b5e5f45e41dc6d559a5f11f27c09d0e4ea97b812c9e3962","title":"","text":"live := &unstructured.Unstructured{} live.SetKind(gvk.Kind) live.SetAPIVersion(gvk.GroupVersion().String()) f = NewStripMetaManager(f) f = NewManagedFieldsUpdater(f) f = NewBuildManagerInfoManager(f, gvk.GroupVersion()) f = NewProbabilisticSkipNonAppliedManager(f, &fakeObjectCreater{gvk: gvk}, gvk, DefaultTrackOnCreateProbability) f = NewLastAppliedManager(f, typeConverter, objectConverter, gvk.GroupVersion()) f = NewLastAppliedUpdater(f) f = NewLastAppliedUpdater( NewLastAppliedManager( NewProbabilisticSkipNonAppliedManager( NewBuildManagerInfoManager( NewManagedFieldsUpdater( NewStripMetaManager(f), ), gvk.GroupVersion(), ), &fakeObjectCreater{gvk: gvk}, gvk, DefaultTrackOnCreateProbability, ), typeConverter, objectConverter, gvk.GroupVersion(), ), ) if chainFieldManager != nil { f = chainFieldManager(f) }"} {"_id":"doc-en-kubernetes-29a9bdeea52a83c231f1e2490cfb7e295fa1a229a72ce1adba1f87c86d70f82f","title":"","text":"hook should execute poststart http hook properly [NodeConformance] [Conformance]' description: When a post start handler is specified in the container lifecycle using a HttpGet action, then the handler MUST be invoked after the start of the container. A server pod is created that will serve http requests, create a second pod with a container lifecycle specifying a post start that invokes the server pod to validate that the post start is executed. A server pod is created that will serve http requests, create a second pod on the same node with a container lifecycle specifying a post start that invokes the server pod to validate that the post start is executed. release: v1.9 file: test/e2e/common/node/lifecycle_hook.go - testname: Pod Lifecycle, prestop exec hook"} {"_id":"doc-en-kubernetes-7ff8ab98830508aef283b269a53f0af3058e4b31b2fc18e2d5596db660ed4a2a","title":"","text":"hook should execute prestop http hook properly [NodeConformance] [Conformance]' description: When a pre-stop handler is specified in the container lifecycle using a 'HttpGet' action, then the handler MUST be invoked before the container is terminated. A server pod is created that will serve http requests, create a second pod with a container lifecycle specifying a pre-stop that invokes the server pod to validate that the pre-stop is executed. A server pod is created that will serve http requests, create a second pod on the same node with a container lifecycle specifying a pre-stop that invokes the server pod to validate that the pre-stop is executed. release: v1.9 file: test/e2e/common/node/lifecycle_hook.go - testname: Container Runtime, TerminationMessage, from log output of succeeding container"} {"_id":"doc-en-kubernetes-39c8e361e88c67b337d4e15296ea996c0704166d9ff29c3bea16e93f9e82c0f2","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/kubernetes/test/e2e/framework\" e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" imageutils \"k8s.io/kubernetes/test/utils/image\""} {"_id":"doc-en-kubernetes-bed9d2a214c10d4bcab44d2888e97e848e2e2c4399867392327acb966304bc34","title":"","text":"preStopWaitTimeout = 30 * time.Second ) ginkgo.Context(\"when create a pod with lifecycle hook\", func() { var targetIP, targetURL string var targetIP, targetURL, targetNode string ports := []v1.ContainerPort{ { ContainerPort: 8080,"} {"_id":"doc-en-kubernetes-91d18aa583eb8d5bc971f4921337c655640887e8b9a1fa992984ec13fd26e2c2","title":"","text":"} podHandleHookRequest := e2epod.NewAgnhostPod(\"\", \"pod-handle-http-request\", nil, nil, ports, \"netexec\") ginkgo.BeforeEach(func() { node, err := e2enode.GetRandomReadySchedulableNode(f.ClientSet) framework.ExpectNoError(err) targetNode = node.Name nodeSelection := e2epod.NodeSelection{} e2epod.SetAffinity(&nodeSelection, targetNode) e2epod.SetNodeSelection(&podHandleHookRequest.Spec, nodeSelection) podClient = f.PodClient() ginkgo.By(\"create the container to handle the HTTPGet hook request.\") newPod := podClient.CreateSync(podHandleHookRequest)"} {"_id":"doc-en-kubernetes-56b1451ad21b8798fc347e963ec57cbc3561473ec8c7762d192a5795fb8b1102","title":"","text":"}, } podWithHook := getPodWithHook(\"pod-with-poststart-exec-hook\", imageutils.GetE2EImage(imageutils.Agnhost), lifecycle) testPodWithHook(podWithHook) }) /*"} {"_id":"doc-en-kubernetes-a22b1214db7c96399efb0b2afbece98f525a8d303a9f4d23f49015ed5f8019ac","title":"","text":"/* Release: v1.9 Testname: Pod Lifecycle, post start http hook Description: When a post start handler is specified in the container lifecycle using a HttpGet action, then the handler MUST be invoked after the start of the container. A server pod is created that will serve http requests, create a second pod with a container lifecycle specifying a post start that invokes the server pod to validate that the post start is executed. Description: When a post start handler is specified in the container lifecycle using a HttpGet action, then the handler MUST be invoked after the start of the container. A server pod is created that will serve http requests, create a second pod on the same node with a container lifecycle specifying a post start that invokes the server pod to validate that the post start is executed. */ framework.ConformanceIt(\"should execute poststart http hook properly [NodeConformance]\", func() { lifecycle := &v1.Lifecycle{"} {"_id":"doc-en-kubernetes-7d450b51fca7bcff40b0e1bcab78780bb0d526612cd302580d4036b7bdabb94a","title":"","text":"}, } podWithHook := getPodWithHook(\"pod-with-poststart-http-hook\", imageutils.GetPauseImageName(), lifecycle) // make sure we spawn the test pod on the same node as the webserver. nodeSelection := e2epod.NodeSelection{} e2epod.SetAffinity(&nodeSelection, targetNode) e2epod.SetNodeSelection(&podWithHook.Spec, nodeSelection) testPodWithHook(podWithHook) }) /* Release: v1.9 Testname: Pod Lifecycle, prestop http hook Description: When a pre-stop handler is specified in the container lifecycle using a 'HttpGet' action, then the handler MUST be invoked before the container is terminated. A server pod is created that will serve http requests, create a second pod with a container lifecycle specifying a pre-stop that invokes the server pod to validate that the pre-stop is executed. Description: When a pre-stop handler is specified in the container lifecycle using a 'HttpGet' action, then the handler MUST be invoked before the container is terminated. A server pod is created that will serve http requests, create a second pod on the same node with a container lifecycle specifying a pre-stop that invokes the server pod to validate that the pre-stop is executed. */ framework.ConformanceIt(\"should execute prestop http hook properly [NodeConformance]\", func() { lifecycle := &v1.Lifecycle{"} {"_id":"doc-en-kubernetes-22eb608cf2a4435cb411880ecbbdc0ca38d598552ddc361822ee9303159fa78a","title":"","text":"}, } podWithHook := getPodWithHook(\"pod-with-prestop-http-hook\", imageutils.GetPauseImageName(), lifecycle) // make sure we spawn the test pod on the same node as the webserver. nodeSelection := e2epod.NodeSelection{} e2epod.SetAffinity(&nodeSelection, targetNode) e2epod.SetNodeSelection(&podWithHook.Spec, nodeSelection) testPodWithHook(podWithHook) }) })"} {"_id":"doc-en-kubernetes-a4bbb15f13148c84241cce35013e1ea96bb8fddedd9dd7ff3f5fe386570e579c","title":"","text":"for _, volumePlugin := range pluginWithLimits { attachLimits, err := volumePlugin.GetVolumeLimits() if err != nil { klog.V(4).InfoS(\"Error getting volume limit for plugin\", \"plugin\", volumePlugin.GetPluginName()) klog.V(4).InfoS(\"Skipping volume limits for volume plugin\", \"plugin\", volumePlugin.GetPluginName()) continue } for limitKey, value := range attachLimits {"} {"_id":"doc-en-kubernetes-ebcbadbbab9b16cf52d68ab135481b7cd40224670aa0db20377260aebd44dfe0","title":"","text":"err := cs.CoreV1().Services(ns).Delete(context.TODO(), serviceName, metav1.DeleteOptions{}) framework.ExpectNoError(err, \"failed to delete service: %s in namespace: %s\", serviceName, ns) }() _, err := jig.CreateTCPServiceWithPort(nil, 80) svc, err := jig.CreateTCPServiceWithPort(nil, 80) framework.ExpectNoError(err) validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{})"} {"_id":"doc-en-kubernetes-f6be8c7365a8cfa5ea976f218d2247770c7e2c51067afdde206ab5bba12135fc","title":"","text":"name1 := \"pod1\" name2 := \"pod2\" createPodOrFail(f, ns, name1, jig.Labels, []v1.ContainerPort{{ContainerPort: 80}}) createPodOrFail(f, ns, name1, jig.Labels, []v1.ContainerPort{{ContainerPort: 80}}, \"netexec\", \"--http-port\", \"80\") names[name1] = true validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{name1: {80}}) createPodOrFail(f, ns, name2, jig.Labels, []v1.ContainerPort{{ContainerPort: 80}}) ginkgo.By(\"Checking if the Service forwards traffic to pod1\") execPod := e2epod.CreateExecPodOrFail(cs, ns, \"execpod\", nil) err = jig.CheckServiceReachability(svc, execPod) framework.ExpectNoError(err) createPodOrFail(f, ns, name2, jig.Labels, []v1.ContainerPort{{ContainerPort: 80}}, \"netexec\", \"--http-port\", \"80\") names[name2] = true validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{name1: {80}, name2: {80}}) ginkgo.By(\"Checking if the Service forwards traffic to pod1 and pod2\") err = jig.CheckServiceReachability(svc, execPod) framework.ExpectNoError(err) e2epod.DeletePodOrFail(cs, ns, name1) delete(names, name1) validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{name2: {80}}) ginkgo.By(\"Checking if the Service forwards traffic to pod2\") err = jig.CheckServiceReachability(svc, execPod) framework.ExpectNoError(err) e2epod.DeletePodOrFail(cs, ns, name2) delete(names, name2) validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{})"} {"_id":"doc-en-kubernetes-74822d5afe9f2aa6c636392b95809c3c8962052877c02ba3f808323889d8f67c","title":"","text":"svc2port := \"svc2\" ginkgo.By(\"creating service \" + serviceName + \" in namespace \" + ns) _, err := jig.CreateTCPService(func(service *v1.Service) { svc, err := jig.CreateTCPService(func(service *v1.Service) { service.Spec.Ports = []v1.ServicePort{ { Name: \"portname1\","} {"_id":"doc-en-kubernetes-7efa6feb5fa8e361b3aad92ee8c0a8703a3bb0ee0f87c024fa2d00d1483433b8","title":"","text":"podname1 := \"pod1\" podname2 := \"pod2\" createPodOrFail(f, ns, podname1, jig.Labels, containerPorts1) createPodOrFail(f, ns, podname1, jig.Labels, containerPorts1, \"netexec\", \"--http-port\", strconv.Itoa(port1)) names[podname1] = true validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{podname1: {port1}}) createPodOrFail(f, ns, podname2, jig.Labels, containerPorts2) createPodOrFail(f, ns, podname2, jig.Labels, containerPorts2, \"netexec\", \"--http-port\", strconv.Itoa(port2)) names[podname2] = true validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{podname1: {port1}, podname2: {port2}}) ginkgo.By(\"Checking if the Service forwards traffic to pods\") execPod := e2epod.CreateExecPodOrFail(cs, ns, \"execpod\", nil) err = jig.CheckServiceReachability(svc, execPod) framework.ExpectNoError(err) e2epod.DeletePodOrFail(cs, ns, podname1) delete(names, podname1) validateEndpointsPortsOrFail(cs, ns, serviceName, portsByPodName{podname2: {port2}})"} {"_id":"doc-en-kubernetes-dff70d546cbdda7520be3c795a0b65aff068475c27cced38c6a3af6d23635cd4","title":"","text":"} // createPodOrFail creates a pod with the specified containerPorts. func createPodOrFail(f *framework.Framework, ns, name string, labels map[string]string, containerPorts []v1.ContainerPort) { func createPodOrFail(f *framework.Framework, ns, name string, labels map[string]string, containerPorts []v1.ContainerPort, args ...string) { ginkgo.By(fmt.Sprintf(\"Creating pod %s in namespace %s\", name, ns)) pod := e2epod.NewAgnhostPod(ns, name, nil, nil, containerPorts) pod := e2epod.NewAgnhostPod(ns, name, nil, nil, containerPorts, args...) pod.ObjectMeta.Labels = labels // Add a dummy environment variable to work around a docker issue. // https://github.com/docker/docker/issues/14203"} {"_id":"doc-en-kubernetes-0c67424f1f61adc0e24517aea1577752a391bf57e4769cd153eb0456ffc872e4","title":"","text":"# - iproute2: includes ss used in NodePort tests # from iperf image # install necessary packages: iperf, bash RUN apk --update add bind-tools curl netcat-openbsd iproute2 iperf bash && rm -rf /var/cache/apk/* RUN retry () { i=0; while [ $i -lt 9 ]; do \"$@\" && return || sleep 30; i=\"${i+1}\"; done; \"$@\"; } && retry apk --update add bind-tools curl netcat-openbsd iproute2 iperf bash && rm -rf /var/cache/apk/* && ln -s /usr/bin/iperf /usr/local/bin/iperf && ls -altrh /usr/local/bin/iperf"} {"_id":"doc-en-kubernetes-6fa05285d70f646c31e3a98ad98fa009d0a018ec10e5e7a389e582969767467f","title":"","text":"} if err = watcher.AddWatch(path, inotify.InOpen|inotify.InDeleteSelf); err != nil { klog.ErrorS(err, \"Unable to watch lockfile\") watcher.Close() return err } go func() {"} {"_id":"doc-en-kubernetes-65c09fb577f0877a3bd586e3712c67bba3632fd4db76005373f37db1fb056671","title":"","text":"klog.ErrorS(err, \"inotify watcher error\") } close(done) watcher.Close() }() return nil }"} {"_id":"doc-en-kubernetes-c648b23903ce707995ea3d5ea4a4a3fc5bce4d4224d02cb8723c6d3fc9cee7cb","title":"","text":"v1 \"k8s.io/api/core/v1\" rbacv1 \"k8s.io/api/rbac/v1\" storagev1 \"k8s.io/api/storage/v1\" storagev1beta1 \"k8s.io/api/storage/v1beta1\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime/schema\""} {"_id":"doc-en-kubernetes-98bc6556d7f3a8f24abd0676961aa299639e10ed8dcea635ab43d4b08033862f","title":"","text":"}, } var betaTest *testsuites.StorageClassTest for i, t := range tests { // Beware of closure, use local variables instead of those from // outer scope"} {"_id":"doc-en-kubernetes-6c890f494514786854fa51e2bbf4bca08b9b1682b1a7c462f3b6274629330ce6","title":"","text":"continue } // Remember the last supported test for subsequent test of beta API betaTest = &test ginkgo.By(\"Testing \" + test.Name) suffix := fmt.Sprintf(\"%d\", i) test.Client = c"} {"_id":"doc-en-kubernetes-35016b66d26f4ef184857bc4bd1bd7df6d843312248a0d521a249e285ec92d9b","title":"","text":"test.TestDynamicProvisioning() } // Run the last test with storage.k8s.io/v1beta1 on pvc if betaTest != nil { ginkgo.By(\"Testing \" + betaTest.Name + \" with beta volume provisioning\") betaClass := newBetaStorageClass(*betaTest, \"beta\") // create beta class manually betaClass, err := c.StorageV1beta1().StorageClasses().Create(context.TODO(), betaClass, metav1.CreateOptions{}) framework.ExpectNoError(err) defer deleteStorageClass(c, betaClass.Name) // fetch V1beta1 StorageClass as V1 object for the test class, err := c.StorageV1().StorageClasses().Get(context.TODO(), betaClass.Name, metav1.GetOptions{}) framework.ExpectNoError(err) betaTest.Client = c betaTest.Class = class betaTest.Claim = e2epv.MakePersistentVolumeClaim(e2epv.PersistentVolumeClaimConfig{ ClaimSize: betaTest.ClaimSize, StorageClassName: &class.Name, VolumeMode: &betaTest.VolumeMode, }, ns) betaTest.Claim.Spec.StorageClassName = &(class.Name) (*betaTest).TestDynamicProvisioning() } }) ginkgo.It(\"should provision storage with non-default reclaim policy Retain\", func() {"} {"_id":"doc-en-kubernetes-20755b820b118943e8b6c0684954dd80a58967530b05fce7fe84efc68f2288dc","title":"","text":"} } // TODO: remove when storage.k8s.io/v1beta1 is removed. func newBetaStorageClass(t testsuites.StorageClassTest, suffix string) *storagev1beta1.StorageClass { pluginName := t.Provisioner if pluginName == \"\" { pluginName = getDefaultPluginName() } if suffix == \"\" { suffix = \"default\" } return &storagev1beta1.StorageClass{ TypeMeta: metav1.TypeMeta{ Kind: \"StorageClass\", }, ObjectMeta: metav1.ObjectMeta{ GenerateName: suffix + \"-\", }, Provisioner: pluginName, Parameters: t.Parameters, } } func startGlusterDpServerPod(c clientset.Interface, ns string) *v1.Pod { podClient := c.CoreV1().Pods(ns)"} {"_id":"doc-en-kubernetes-41b75032137a3330799d4ec7caae1b9a3009f602dfbf0668abc81e17abd90283","title":"","text":"# etcd - name: \"etcd\" version: 3.5.0-rc.0 version: 3.5.0 refPaths: - path: cluster/gce/manifests/etcd.manifest match: etcd_docker_tag|etcd_version"} {"_id":"doc-en-kubernetes-ce736f925a7708d42de0f972e7d458342208ebb1c1503051ac71eb90d8bd1825","title":"","text":"NUM_ADDITIONAL_NODES=${NUM_ADDITIONAL_NODES:-} ADDITIONAL_MACHINE_TYPE=${ADDITIONAL_MACHINE_TYPE:-} # Set etcd image (e.g. k8s.gcr.io/etcd) and version (e.g. v3.5.0-rc.0-0) if you need # Set etcd image (e.g. k8s.gcr.io/etcd) and version (e.g. v3.5.0-0) if you need # non-default version. export ETCD_IMAGE=${TEST_ETCD_IMAGE:-} export ETCD_DOCKER_REPOSITORY=${TEST_ETCD_DOCKER_REPOSITORY:-}"} {"_id":"doc-en-kubernetes-8a28d79b55df0540f7f5c09d50c8fdccca1f029b17b2d8d4d77c8fffcc7dc569","title":"","text":"export SECONDARY_RANGE_NAME=\"pods-default\" export STORAGE_BACKEND=\"etcd3\" export STORAGE_MEDIA_TYPE=\"application/vnd.kubernetes.protobuf\" export ETCD_IMAGE=3.5.0-rc.0-0 export ETCD_VERSION=3.5.0-rc.0 export ETCD_IMAGE=3.5.0-0 export ETCD_VERSION=3.5.0 # Upgrade master with updated kube envs \"${KUBE_ROOT}/cluster/gce/upgrade.sh\" -M -l"} {"_id":"doc-en-kubernetes-4ddc0436f3ff9c527712f7af3702527055cb9eb35927397a2a5a55462bd15169","title":"","text":"MinExternalEtcdVersion = \"3.2.18\" // DefaultEtcdVersion indicates the default etcd version that kubeadm uses DefaultEtcdVersion = \"3.5.0-rc.0-0\" DefaultEtcdVersion = \"3.5.0-0\" // Etcd defines variable used internally when referring to etcd component Etcd = \"etcd\""} {"_id":"doc-en-kubernetes-d945458f78cb038c86f32fcb151cc82b4502d64390f7b223458d58a40f4a78fe","title":"","text":"19: \"3.4.13-0\", 20: \"3.4.13-0\", 21: \"3.4.13-0\", 22: \"3.5.0-rc.0-0\", 23: \"3.5.0-rc.0-0\", 22: \"3.5.0-0\", 23: \"3.5.0-0\", } // KubeadmCertsClusterRoleName sets the name for the ClusterRole that allows"} {"_id":"doc-en-kubernetes-0dc41a872d496535d8e5fb7e0cb0a1c177daff47725eb1be6ee89c7c11c57875","title":"","text":"# A set of helpers for starting/running etcd for tests ETCD_VERSION=${ETCD_VERSION:-3.5.0-rc.0} ETCD_VERSION=${ETCD_VERSION:-3.5.0} ETCD_HOST=${ETCD_HOST:-127.0.0.1} ETCD_PORT=${ETCD_PORT:-2379} export KUBE_INTEGRATION_ETCD_URL=\"http://${ETCD_HOST}:${ETCD_PORT}\""} {"_id":"doc-en-kubernetes-8b755e8e0198df04f76d5305093cd1b6edc7a6140ddddd2fe480c6f4bbf5ff09","title":"","text":"imagePullPolicy: Never args: [ \"--etcd-servers=http://localhost:2379\" ] - name: etcd image: quay.io/coreos/etcd:v3.5.0-rc.0 image: quay.io/coreos/etcd:v3.5.0 "} {"_id":"doc-en-kubernetes-238d5c4ad4c0569e02b642572d6a1b60962d6b871eb38f8a9b3f9a8763a0ba14","title":"","text":"e2essh \"k8s.io/kubernetes/test/e2e/framework/ssh\" ) const etcdImage = \"3.5.0-rc.0-0\" const etcdImage = \"3.5.0-0\" // EtcdUpgrade upgrades etcd on GCE. func EtcdUpgrade(targetStorage, targetVersion string) error {"} {"_id":"doc-en-kubernetes-d5ae229e05824dc780843c9778016b2e1f0d429c868dbbe7502aad52dd342ae5","title":"","text":"# See the License for the specific language governing permissions and # limitations under the License. # Set provider independent environment variables # Set the default provider of Kubernetes cluster to know where to load provider-specific scripts # You can override the default provider by exporting the KUBERNETES_PROVIDER # variable in your bashrc # # The valid values: 'gce', 'azure' and 'vagrant' # Set provider of Kubernetes cluster to know where to load provider-specific scripts, values: gce, vagrant, etc. KUBERNETES_PROVIDER=\"gce\" #KUBERNETES_PROVIDER=\"vagrant\" KUBERNETES_PROVIDER=${KUBERNETES_PROVIDER:-gce} "} {"_id":"doc-en-kubernetes-053239adece44904bd9c078bfd7464df888984132c34ea9d80a791ca1907d5bd","title":"","text":"return \"\", err } // try and get canonical path for disk and if we can't throw error vmDiskPath, err = getcanonicalVolumePath(ctx, vm.Datacenter, vmDiskPath) if err != nil { klog.Errorf(\"failed to get canonical path for %s on node %s: %v\", vmDiskPath, convertToString(nodeName), err) return \"\", err // try and get canonical path for disk and if we can't use provided vmDiskPath canonicalPath, pathFetchErr := getcanonicalVolumePath(ctx, vm.Datacenter, vmDiskPath) if canonicalPath != \"\" && pathFetchErr == nil { vmDiskPath = canonicalPath } diskUUID, err = vm.AttachDisk(ctx, vmDiskPath, &vclib.VolumeOptions{SCSIControllerType: vclib.PVSCSIControllerType, StoragePolicyName: storagePolicyName})"} {"_id":"doc-en-kubernetes-f7a05edc0350a98f69e9e1b8713399eaab561c39a1d728a29dc54f0040230efe","title":"","text":"} ) func TestGetServicePrincipalTokenFromMSIWithUserAssignedID(t *testing.T) { configs := []*AzureAuthConfig{ { UseManagedIdentityExtension: true, UserAssignedIdentityID: \"UserAssignedIdentityID\", }, // The Azure service principal is ignored when // UseManagedIdentityExtension is set to true { UseManagedIdentityExtension: true, UserAssignedIdentityID: \"UserAssignedIdentityID\", TenantID: \"TenantID\", AADClientID: \"AADClientID\", AADClientSecret: \"AADClientSecret\", }, } env := &azure.PublicCloud for _, config := range configs { token, err := GetServicePrincipalToken(config, env) assert.NoError(t, err) msiEndpoint, err := adal.GetMSIVMEndpoint() assert.NoError(t, err) spt, err := adal.NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, env.ServiceManagementEndpoint, config.UserAssignedIdentityID) assert.NoError(t, err) assert.Equal(t, token, spt) } } func TestGetServicePrincipalTokenFromMSI(t *testing.T) { configs := []*AzureAuthConfig{ { UseManagedIdentityExtension: true, }, // The Azure service principal is ignored when // UseManagedIdentityExtension is set to true { UseManagedIdentityExtension: true, TenantID: \"TenantID\", AADClientID: \"AADClientID\", AADClientSecret: \"AADClientSecret\", }, } env := &azure.PublicCloud for _, config := range configs { token, err := GetServicePrincipalToken(config, env) assert.NoError(t, err) msiEndpoint, err := adal.GetMSIVMEndpoint() assert.NoError(t, err) spt, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, env.ServiceManagementEndpoint) assert.NoError(t, err) assert.Equal(t, token, spt) } } func TestGetServicePrincipalToken(t *testing.T) { config := &AzureAuthConfig{ TenantID: \"TenantID\","} {"_id":"doc-en-kubernetes-d2800cb5de65a2b3366a0bd686a0a378e09ec039a760e332267ed762d31b6b73","title":"","text":"} func (q *graceTerminateRSList) flushList(handler func(rsToDelete *listItem) (bool, error)) bool { q.lock.Lock() defer q.lock.Unlock() success := true for name, rs := range q.list { deleted, err := handler(rs)"} {"_id":"doc-en-kubernetes-4ce72da2d1a969c5d76986c501370b7ed788b47906afc7eef000a5fd25021147","title":"","text":"} if deleted { klog.InfoS(\"Removed real server from graceful delete real server list\", \"realServer\", name) q.remove(rs) delete(q.list, rs.String()) } } return success"} {"_id":"doc-en-kubernetes-531b8e0767122ab231e801f8e4fdb4cc31bcffac66c6ef2d656f7e3c36c2f13a","title":"","text":"package ipvs import ( \"fmt\" netutils \"k8s.io/utils/net\" \"reflect\" \"testing\" utilipvs \"k8s.io/kubernetes/pkg/util/ipvs\" utilipvstest \"k8s.io/kubernetes/pkg/util/ipvs/testing\" netutils \"k8s.io/utils/net\" ) func Test_GracefulDeleteRS(t *testing.T) {"} {"_id":"doc-en-kubernetes-65673d7303f94f384eec7fd9a625c1ead038c4e9747bc3ef6a9aa9ab8065b3df","title":"","text":"}) } } func Test_RaceTerminateRSList(t *testing.T) { ipvs := &utilipvstest.FakeIPVS{} gracefulTerminationManager := NewGracefulTerminationManager(ipvs) go func() { for i := 1; i <= 10; i++ { for j := 1; i <= 100; j++ { gracefulTerminationManager.rsList.add(makeListItem(i, j)) } } }() if !gracefulTerminationManager.rsList.flushList(gracefulTerminationManager.deleteRsFunc) { t.Error(\"failed to flush entries\") } } func makeListItem(i, j int) *listItem { vs := fmt.Sprintf(\"%d.%d.%d.%d\", 1, 1, i, i) rs := fmt.Sprintf(\"%d.%d.%d.%d\", 1, 1, i, j) return &listItem{ VirtualServer: &utilipvs.VirtualServer{ Address: netutils.ParseIPSloppy(vs), Protocol: \"tcp\", Port: uint16(80), }, RealServer: &utilipvs.RealServer{ Address: netutils.ParseIPSloppy(rs), Port: uint16(80), }, } } "} {"_id":"doc-en-kubernetes-b7131ae47ea1b346d2e5ca358a1f4aef4bef8daf473f2acbb894c33dbba07b8b","title":"","text":"case *corev1.Pod: // if allContainers is true, then we're going to locate all containers and then iterate through them. At that point, \"allContainers\" is false if !allContainers { currOpts := new(corev1.PodLogOptions) if opts != nil { opts.DeepCopyInto(currOpts) } // in case the \"kubectl.kubernetes.io/default-container\" annotation is present, we preset the opts.Containers to default to selected // container. This gives users ability to preselect the most interesting container in pod. if annotations := t.GetAnnotations(); annotations != nil && len(opts.Container) == 0 { var containerName string if annotations := t.GetAnnotations(); annotations != nil && currOpts.Container == \"\" { var defaultContainer string if len(annotations[podcmd.DefaultContainerAnnotationName]) > 0 { containerName = annotations[podcmd.DefaultContainerAnnotationName] defaultContainer = annotations[podcmd.DefaultContainerAnnotationName] } else if len(annotations[defaultLogsContainerAnnotationName]) > 0 { // Only log deprecation if we have only the old annotation. This allows users to // set both to support multiple versions of kubectl; if they are setting both // they must already know it is deprecated, so we don't need to add noisy // warnings. containerName = annotations[defaultLogsContainerAnnotationName] defaultContainer = annotations[defaultLogsContainerAnnotationName] fmt.Fprintf(os.Stderr, \"Using deprecated annotation `kubectl.kubernetes.io/default-logs-container` in pod/%v. Please use `kubectl.kubernetes.io/default-container` insteadn\", t.Name) } if len(containerName) > 0 { if exists, _ := podcmd.FindContainerByName(t, containerName); exists != nil { opts.Container = containerName if len(defaultContainer) > 0 { if exists, _ := podcmd.FindContainerByName(t, defaultContainer); exists == nil { fmt.Fprintf(os.Stderr, \"Default container name %q not found in pod %sn\", defaultContainer, t.Name) } else { fmt.Fprintf(os.Stderr, \"Default container name %q not found in a podn\", containerName) currOpts.Container = defaultContainer } } } var containerName string if opts == nil || len(opts.Container) == 0 { if currOpts.Container == \"\" { // We don't know container name. In this case we expect only one container to be present in the pod (ignoring InitContainers). // If there is more than one container, we should return an error showing all container names. if len(t.Spec.Containers) != 1 {"} {"_id":"doc-en-kubernetes-6091320b708964603d1223948fa8365c7e7ec587c9f0a86f31239c74625785fc","title":"","text":"return nil, errors.New(err) } containerName = t.Spec.Containers[0].Name } else { containerName = opts.Container currOpts.Container = t.Spec.Containers[0].Name } container, fieldPath := podcmd.FindContainerByName(t, containerName) container, fieldPath := podcmd.FindContainerByName(t, currOpts.Container) if container == nil { return nil, fmt.Errorf(\"container %s is not valid for pod %s\", opts.Container, t.Name) return nil, fmt.Errorf(\"container %s is not valid for pod %s\", currOpts.Container, t.Name) } ref, err := reference.GetPartialReference(scheme.Scheme, t, fieldPath) if err != nil {"} {"_id":"doc-en-kubernetes-4814d1f6397c476ddb18c04826a53ed373d795f16b2b4b58d6d5bbe729b4a844","title":"","text":"} ret := make(map[corev1.ObjectReference]rest.ResponseWrapper, 1) ret[*ref] = clientset.Pods(t.Namespace).GetLogs(t.Name, opts) ret[*ref] = clientset.Pods(t.Namespace).GetLogs(t.Name, currOpts) return ret, nil }"} {"_id":"doc-en-kubernetes-c74a1e3e4c3204ad5c5e0c56c573c830533c1fd2ca818f0176432fe469b48388","title":"","text":"name: \"pod logs\", obj: testPodWithOneContainers(), actions: []testclient.Action{ getLogsAction(\"test\", nil), getLogsAction(\"test\", &corev1.PodLogOptions{Container: \"c1\"}), }, expectedSources: []corev1.ObjectReference{ {"} {"_id":"doc-en-kubernetes-ef2066a303ba8005b1fc17acdacb26792113e7b1beb8a7f93949ba7472ae45f1","title":"","text":"Items: []corev1.Pod{*testPodWithOneContainers()}, }, actions: []testclient.Action{ getLogsAction(\"test\", nil), getLogsAction(\"test\", &corev1.PodLogOptions{Container: \"c1\"}), }, expectedSources: []corev1.ObjectReference{{ Kind: testPodWithOneContainers().Kind,"} {"_id":"doc-en-kubernetes-ca9e400951aee499bf3b0bd12b45d24da395fc68657c4426bfc324a5b31665eb","title":"","text":"}}, }, { name: \"pods list logs: default container should not leak across pods\", obj: &corev1.PodList{ Items: []corev1.Pod{ { TypeMeta: metav1.TypeMeta{ Kind: \"pod\", APIVersion: \"v1\", }, ObjectMeta: metav1.ObjectMeta{ Name: \"foo\", Namespace: \"test\", Labels: map[string]string{\"test\": \"logs\"}, Annotations: map[string]string{ \"kubectl.kubernetes.io/default-container\": \"c1\", }, }, Spec: corev1.PodSpec{ RestartPolicy: corev1.RestartPolicyAlways, DNSPolicy: corev1.DNSClusterFirst, Containers: []corev1.Container{ {Name: \"c1\"}, {Name: \"c2\"}, }, }, }, { TypeMeta: metav1.TypeMeta{ Kind: \"pod\", APIVersion: \"v1\", }, ObjectMeta: metav1.ObjectMeta{ Name: \"bar\", Namespace: \"test\", Labels: map[string]string{\"test\": \"logs\"}, }, Spec: corev1.PodSpec{ RestartPolicy: corev1.RestartPolicyAlways, DNSPolicy: corev1.DNSClusterFirst, Containers: []corev1.Container{ {Name: \"c2\"}, }, }, }, }, }, actions: []testclient.Action{ getLogsAction(\"test\", &corev1.PodLogOptions{Container: \"c1\"}), getLogsAction(\"test\", &corev1.PodLogOptions{Container: \"c2\"}), }, expectedSources: []corev1.ObjectReference{{ Kind: \"pod\", APIVersion: \"v1\", Name: \"foo\", Namespace: \"test\", FieldPath: fmt.Sprintf(\"spec.containers{%s}\", \"c1\"), }, { Kind: \"pod\", APIVersion: \"v1\", Name: \"bar\", Namespace: \"test\", FieldPath: fmt.Sprintf(\"spec.containers{%s}\", \"c2\"), }}, }, { name: \"pods list logs: all containers\", obj: &corev1.PodList{ Items: []corev1.Pod{*testPodWithTwoContainersAndTwoInitContainers()},"} {"_id":"doc-en-kubernetes-6dd2a8140ba551a195dec46d1cdea2ba6cf57cdde960253a2132e5470fc00a8e","title":"","text":"clientsetPods: []runtime.Object{testPodWithOneContainers()}, actions: []testclient.Action{ testclient.NewListAction(podsResource, podsKind, \"test\", metav1.ListOptions{LabelSelector: \"foo=bar\"}), getLogsAction(\"test\", nil), getLogsAction(\"test\", &corev1.PodLogOptions{Container: \"c1\"}), }, expectedSources: []corev1.ObjectReference{{ Kind: testPodWithOneContainers().Kind,"} {"_id":"doc-en-kubernetes-dd687e307d6f1110720224f7e2a18e875ae5993b489e3c8df1c4dbc1a7fa511b","title":"","text":" Copyright ©2013 The gonum Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the gonum project nor the names of its authors and contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. No newline at end of file"} {"_id":"doc-en-kubernetes-35e1b66c895b4bbb1fb65467a4b62e3e5d93d2290906168f7c01b496a966132d","title":"","text":" Shell2Junit License Information Feb, 2010 shell2junit library and sample code is licensed under Apache License, v.2.0. (c) 2009 Manolo Carrasco (Manuel Carrasco Moñino) ===== Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 1. Definitions. \"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. \"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. \"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. \"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License. \"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. \"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. \"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). \"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. \"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\" \"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: a. You must give any other recipients of the Work or Derivative Works a copy of this License; and b. You must cause any modified files to carry prominent notices stating that You changed the files; and c. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and d. If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. "} {"_id":"doc-en-kubernetes-9e52ad14c08261b8a1507da351014f79b8f0fb6df0fcb48bf18875623a2cc2a7","title":"","text":" The MIT License (MIT) Copyright (c) 2015-2016 Manfred Touron Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "} {"_id":"doc-en-kubernetes-b3999b9a3818bee85e787e6cc6f886f5a388e8b9efcc9f8c1883b7ec9c5acf27","title":"","text":" Copyright (c) 2013 Joshua Tacoma. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. "} {"_id":"doc-en-kubernetes-5fec012ce19904b795ceea1384a9e62d64a1809b9d266f4e31591da903d84d4b","title":"","text":" Copyright (c) 2012 The Go Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. "} {"_id":"doc-en-kubernetes-899f1b4f03063d6a330977038add69150502b48b7b69a3e621d0933cc4dc1d64","title":"","text":" This project is covered by two different licenses: MIT and Apache. #### MIT License #### The following files were ported to Go from C files of libyaml, and thus are still covered by their original MIT license, with the additional copyright staring in 2011 when the project was ported over: apic.go emitterc.go parserc.go readerc.go scannerc.go writerc.go yamlh.go yamlprivateh.go Copyright (c) 2006-2010 Kirill Simonov Copyright (c) 2006-2011 Kirill Simonov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Apache License ### All the remaining project files are covered by the Apache license: Copyright (c) 2011-2019 Canonical Ltd 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. "} {"_id":"doc-en-kubernetes-ebf88334815fb629da7752db308b514917afb825f785cac336c0b8240edab902","title":"","text":" Copyright 2011-2016 Canonical Ltd. 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. "} {"_id":"doc-en-kubernetes-11fe8732e5cc64a0e44f16b937032297179b363424e82a14fb3e7dc21ecd2ca8","title":"","text":" The MIT License (MIT) Copyright (c) 2018 QRI, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "} {"_id":"doc-en-kubernetes-2b55a93943fdb5a1502e95fe1b1e53f9591e75588931faeb75ae119d261067bb","title":"","text":"mv \"${TMP_LICENSE_FILE}\" \"${dest_dir}/LICENSE\" done # copy licenses for forked code from vendor and third_party directories (cd \"${KUBE_ROOT}\" && find vendor third_party -iname 'licen[sc]e*' -o -iname 'notice*' -o -iname 'copying*' | grep -E 'third_party|forked' | xargs tar -czf - | tar -C \"${TMP_LICENSES_DIR}\" -xzf -) # Leave things like OWNERS alone. rm -f \"${LICENSES_DIR}/LICENSE\" rm -rf \"${LICENSES_DIR}/vendor\" rm -rf \"${LICENSES_DIR}/third_party\" mv \"${TMP_LICENSES_DIR}\"/* \"${LICENSES_DIR}\""} {"_id":"doc-en-kubernetes-9c660ac43c21504af18b02d4838f09e4ddae5f582c9b192ecf4265bc6eea6d72","title":"","text":"}}, metav1.CreateOptions{}) framework.ExpectNoError(err, \"failed to create pod\") framework.Logf(\"created %v\", podTestName) framework.ExpectNoError(e2epod.WaitForPodNameRunningInNamespace(f.ClientSet, podTestName, f.Namespace.Name)) framework.Logf(\"running and ready %v\", podTestName) } // wait as required for all 3 pods to be found"} {"_id":"doc-en-kubernetes-21f57c6d5efd3962c994d6f100479c3031270b7b63e02cc49cb28d71de1ce7a2","title":"","text":"\"errors\" \"fmt\" \"sync\" \"time\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/klog/v2\" utiltrace \"k8s.io/utils/trace\" ) // DeltaFIFOOptions is the configuration parameters for DeltaFIFO. All are"} {"_id":"doc-en-kubernetes-b8be05a78a729ced26306d75d966d75aabb26a0d84ce66487136364485cec882","title":"","text":"} id := f.queue[0] f.queue = f.queue[1:] depth := len(f.queue) if f.initialPopulationCount > 0 { f.initialPopulationCount-- }"} {"_id":"doc-en-kubernetes-3613807937dd569b4381f86d1f2ff32e634dbf7b942c43cb7c9700e05f8282cf","title":"","text":"continue } delete(f.items, id) // Only log traces if the queue depth is greater than 10 and it takes more than // 100 milliseconds to process one item from the queue. // Queue depth never goes high because processing an item is locking the queue, // and new items can't be added until processing finish. // https://github.com/kubernetes/kubernetes/issues/103789 if depth > 10 { trace := utiltrace.New(\"DeltaFIFO Pop Process\", utiltrace.Field{Key: \"ID\", Value: id}, utiltrace.Field{Key: \"Depth\", Value: depth}, utiltrace.Field{Key: \"Reason\", Value: \"slow event handlers blocking the queue\"}) defer trace.LogIfLong(100 * time.Millisecond) } err := process(item) if e, ok := err.(ErrRequeue); ok { f.addIfNotPresent(id, item)"} {"_id":"doc-en-kubernetes-f0ef69efce97bf8b8a2d2636caafc516cf215dc34badb5019496440bc1a2d3e0","title":"","text":"runcmd: - modprobe configs # Setup the installation target at make it executable - mkdir -p /home/kubernetes/bin/nvidia - mount --bind /home/kubernetes/bin/nvidia /home/kubernetes/bin/nvidia - mount -o remount,exec /home/kubernetes/bin/nvidia # Compile and install the nvidia driver (precompiled driver installation currently fails) - docker run --net=host --pid=host -v /dev:/dev -v /:/root -v /home/kubernetes/bin/nvidia:/usr/local/nvidia -e NVIDIA_INSTALL_DIR_HOST=/home/kubernetes/bin/nvidia -e NVIDIA_INSTALL_DIR_CONTAINER=/usr/local/nvidia -e NVIDIA_DRIVER_VERSION=460.91.03 --privileged gcr.io/cos-cloud/cos-gpu-installer:latest # Run the installer again, as on the first try it doesn't detect the libnvidia-ml.so # on the second attempt we detect it and update the ld cache. - docker run --net=host --pid=host -v /dev:/dev -v /:/root -v /home/kubernetes/bin/nvidia:/usr/local/nvidia -e NVIDIA_INSTALL_DIR_HOST=/home/kubernetes/bin/nvidia -e NVIDIA_INSTALL_DIR_CONTAINER=/usr/local/nvidia -e NVIDIA_DRIVER_VERSION=460.91.03 --privileged gcr.io/cos-cloud/cos-gpu-installer:latest # Install GPU drivers - https://cloud.google.com/container-optimized-os/docs/how-to/run-gpus - cos-extensions install gpu - mount --bind /var/lib/nvidia /var/lib/nvidia - mount -o remount,exec /var/lib/nvidia /var/lib/nvidia # Run nvidia-smi to verify installation - /var/lib/nvidia/bin/nvidia-smi # Remove build containers. They're very large. - docker rm -f $(docker ps -aq) # Standard installation proceeds"} {"_id":"doc-en-kubernetes-0f4494616db589ba1015077c91d305e49c01681137a2537abdb9b70ee48c33d6","title":"","text":"err := kl.syncPod(pod, dockerContainers) if err != nil { glog.Errorf(\"Error syncing pod, skipping: %v\", err) record.Eventf(pod, \"\", \"failedSync\", \"Error syncing pod, skipping: %v\", err) } }) }"} {"_id":"doc-en-kubernetes-4ca648c403d87033340c1397e16ae97551cbc4fc1f7103a424fdf2228b47d66e","title":"","text":"jig := e2eservice.NewTestJig(cs, ns, serviceName) ginkgo.By(\"getting the state of the sctp module on nodes\") nodes, err := e2enode.GetReadySchedulableNodes(cs) nodes, err := e2enode.GetBoundedReadySchedulableNodes(cs, 2) framework.ExpectNoError(err) sctpLoadedAtStart := CheckSCTPModuleLoadedOnNodes(f, nodes)"} {"_id":"doc-en-kubernetes-c6b0920a564a4a05131b00f79553c0ae8fdcd8644d60c6015cc1b014b84d14aa","title":"","text":"framework.ExpectNoError(err, fmt.Sprintf(\"error while waiting for service:%s err: %v\", serviceName, err)) hostExec := utils.NewHostExec(f) defer hostExec.Cleanup() node, err := e2enode.GetRandomReadySchedulableNode(cs) framework.ExpectNoError(err) node := &nodes.Items[0] cmd := \"iptables-save\" if framework.TestContext.ClusterIsIPv6() { cmd = \"ip6tables-save\""} {"_id":"doc-en-kubernetes-7a4bc052901e82c4306d3f664dc859710543265a61e7b2f68a33be1d90a96448","title":"","text":"description: The discovery.k8s.io API group MUST exist in the /apis discovery document. The discovery.k8s.io/v1 API group/version MUST exist in the /apis/discovery.k8s.io discovery document. The endpointslices resource MUST exist in the /apis/discovery.k8s.io/v1 discovery document. API Server should create self referential Endpoints and EndpointSlices named \"kubernetes\" in the default namespace. discovery document. The cluster MUST have a service named \"kubernetes\" on the default namespace referencing the API servers. The \"kubernetes.default\" service MUST have Endpoints and EndpointSlices pointing to each API server instance. release: v1.21 file: test/e2e/network/endpointslice.go - testname: EndpointSlice API"} {"_id":"doc-en-kubernetes-c9dd7224c4794a6ffa480be98594fc8517bb6706ce23796fdcd343e92c883581","title":"","text":"Description: The discovery.k8s.io API group MUST exist in the /apis discovery document. The discovery.k8s.io/v1 API group/version MUST exist in the /apis/discovery.k8s.io discovery document. The endpointslices resource MUST exist in the /apis/discovery.k8s.io/v1 discovery document. API Server should create self referential Endpoints and EndpointSlices named \"kubernetes\" in the default namespace. The cluster MUST have a service named \"kubernetes\" on the default namespace referencing the API servers. The \"kubernetes.default\" service MUST have Endpoints and EndpointSlices pointing to each API server instance. */ framework.ConformanceIt(\"should have Endpoints and EndpointSlices pointing to API Server\", func() { namespace := \"default\" name := \"kubernetes\" // verify \"kubernetes.default\" service exist _, err := cs.CoreV1().Services(namespace).Get(context.TODO(), name, metav1.GetOptions{}) framework.ExpectNoError(err, \"error obtaining API server \"kubernetes\" Service resource on \"default\" namespace\") // verify Endpoints for the API servers exist endpoints, err := cs.CoreV1().Endpoints(namespace).Get(context.TODO(), name, metav1.GetOptions{}) framework.ExpectNoError(err, \"error creating Endpoints resource\") if len(endpoints.Subsets) != 1 { framework.Failf(\"Expected 1 subset in endpoints, got %d: %#v\", len(endpoints.Subsets), endpoints.Subsets) framework.ExpectNoError(err, \"error obtaining API server \"kubernetes\" Endpoint resource on \"default\" namespace\") if len(endpoints.Subsets) == 0 { framework.Failf(\"Expected at least 1 subset in endpoints, got %d: %#v\", len(endpoints.Subsets), endpoints.Subsets) } endpointSubset := endpoints.Subsets[0] endpointSlice, err := cs.DiscoveryV1().EndpointSlices(namespace).Get(context.TODO(), name, metav1.GetOptions{}) framework.ExpectNoError(err, \"error creating EndpointSlice resource\") if len(endpointSlice.Ports) != len(endpointSubset.Ports) { framework.Failf(\"Expected EndpointSlice to have %d ports, got %d: %#v\", len(endpointSubset.Ports), len(endpointSlice.Ports), endpointSlice.Ports) // verify EndpointSlices for the API servers exist endpointSliceList, err := cs.DiscoveryV1().EndpointSlices(namespace).List(context.TODO(), metav1.ListOptions{ LabelSelector: \"kubernetes.io/service-name=\" + name, }) framework.ExpectNoError(err, \"error obtaining API server \"kubernetes\" EndpointSlice resource on \"default\" namespace\") if len(endpointSliceList.Items) == 0 { framework.Failf(\"Expected at least 1 EndpointSlice, got %d: %#v\", len(endpoints.Subsets), endpoints.Subsets) } numExpectedEndpoints := len(endpointSubset.Addresses) + len(endpointSubset.NotReadyAddresses) if len(endpointSlice.Endpoints) != numExpectedEndpoints { framework.Failf(\"Expected EndpointSlice to have %d endpoints, got %d: %#v\", numExpectedEndpoints, len(endpointSlice.Endpoints), endpointSlice.Endpoints) if !endpointSlicesEqual(endpoints, endpointSliceList) { framework.Failf(\"Expected EndpointSlice to have same addresses and port as Endpoints, got %#v: %#v\", endpoints, endpointSliceList) } })"} {"_id":"doc-en-kubernetes-99d35e6ff66d8241fd163312bb7fd9e796f74f675c8c79d853ce85310e38c881","title":"","text":"framework.ExpectNoError(err, \"error deleting Service\") return svc } // endpointSlicesEqual compare if the Endpoint and the EndpointSliceList contains the same endpoints values // as in addresses and ports, considering Ready and Unready addresses func endpointSlicesEqual(endpoints *v1.Endpoints, endpointSliceList *discoveryv1.EndpointSliceList) bool { // get the apiserver endpoint addresses epAddresses := sets.NewString() epPorts := sets.NewInt32() for _, subset := range endpoints.Subsets { for _, addr := range subset.Addresses { epAddresses.Insert(addr.IP) } for _, addr := range subset.NotReadyAddresses { epAddresses.Insert(addr.IP) } for _, port := range subset.Ports { epPorts.Insert(port.Port) } } framework.Logf(\"Endpoints addresses: %v , ports: %v\", epAddresses.List(), epPorts.List()) // Endpoints are single stack, and must match the primary IP family of the Service kubernetes.default // However, EndpointSlices can be IPv4 or IPv6, we can only compare the Slices that match the same IP family // framework.TestContext.ClusterIsIPv6() reports the IP family of the kubernetes.default service var addrType discoveryv1.AddressType if framework.TestContext.ClusterIsIPv6() { addrType = discoveryv1.AddressTypeIPv6 } else { addrType = discoveryv1.AddressTypeIPv4 } // get the apiserver addresses from the endpoint slice list sliceAddresses := sets.NewString() slicePorts := sets.NewInt32() for _, slice := range endpointSliceList.Items { if slice.AddressType != addrType { framework.Logf(\"Skipping slice %s: wanted %s family, got %s\", slice.Name, addrType, slice.AddressType) continue } for _, s := range slice.Endpoints { sliceAddresses.Insert(s.Addresses...) } for _, ports := range slice.Ports { if ports.Port != nil { slicePorts.Insert(*ports.Port) } } } framework.Logf(\"EndpointSlices addresses: %v , ports: %v\", sliceAddresses.List(), slicePorts.List()) if sliceAddresses.Equal(epAddresses) && slicePorts.Equal(epPorts) { return true } return false } "} {"_id":"doc-en-kubernetes-24e9f1bae608c0aa33fb93c5fa9803e92c2730561d5872bd423713ea236c7d71","title":"","text":"\"github.com/stretchr/testify/assert\" \"k8s.io/component-base/metrics/legacyregistry\" compbasemetrics \"k8s.io/component-base/metrics\" runtimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1alpha2\" \"k8s.io/kubernetes/pkg/kubelet/metrics\" ) func TestRecordOperation(t *testing.T) { legacyregistry.MustRegister(metrics.RuntimeOperations) legacyregistry.MustRegister(metrics.RuntimeOperationsDuration) legacyregistry.MustRegister(metrics.RuntimeOperationsErrors) // Use local registry var registry = compbasemetrics.NewKubeRegistry() var gather compbasemetrics.Gatherer = registry registry.MustRegister(metrics.RuntimeOperations) registry.MustRegister(metrics.RuntimeOperationsDuration) registry.MustRegister(metrics.RuntimeOperationsErrors) registry.Reset() l, err := net.Listen(\"tcp\", \"127.0.0.1:0\") assert.NoError(t, err)"} {"_id":"doc-en-kubernetes-27a939625c5424b81e7035c014b8a33d12d9794ae5f35b9467dc320d61867373","title":"","text":"prometheusURL := \"http://\" + l.Addr().String() + \"/metrics\" mux := http.NewServeMux() //lint:ignore SA1019 ignore deprecated warning until we move off of global registries mux.Handle(\"/metrics\", legacyregistry.Handler()) handler := compbasemetrics.HandlerFor(gather, compbasemetrics.HandlerOpts{}) mux.Handle(\"/metrics\", handler) server := &http.Server{ Addr: l.Addr().String(), Handler: mux,"} {"_id":"doc-en-kubernetes-2ce6813586d4399e504262df7d07f3aacc880c185c754c1f9d187db84394145f","title":"","text":"\"fmt\" \"math\" \"reflect\" \"sync\" \"testing\" \"github.com/google/go-cmp/cmp\" dto \"github.com/prometheus/client_model/go\" \"k8s.io/component-base/metrics\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/utils/pointer\" )"} {"_id":"doc-en-kubernetes-04c233dffbac3551e47068a9167a47569638744da75a4e5035988503d8f992a3","title":"","text":"} func TestGetHistogramVecFromGatherer(t *testing.T) { var registerMetrics sync.Once tests := []struct { name string lvMap map[string]string"} {"_id":"doc-en-kubernetes-aab97cc88fd29ba559bcbdfe153a8698cdf2bc990a303e5ddd30d5aa69d1e62f","title":"","text":"Buckets: buckets, } vec := metrics.NewHistogramVec(HistogramOpts, labels) registerMetrics.Do(func() { legacyregistry.MustRegister(vec) }) // Use local registry var registry = metrics.NewKubeRegistry() var gather metrics.Gatherer = registry registry.MustRegister(vec) // Observe two metrics with same value for label1 but different value of label2. vec.WithLabelValues(\"value1-0\", \"value2-0\").Observe(1.5) vec.WithLabelValues(\"value1-0\", \"value2-1\").Observe(2.5) vec.WithLabelValues(\"value1-1\", \"value2-0\").Observe(3.5) vec.WithLabelValues(\"value1-1\", \"value2-1\").Observe(4.5) metricName := fmt.Sprintf(\"%s_%s_%s\", HistogramOpts.Namespace, HistogramOpts.Subsystem, HistogramOpts.Name) histogramVec, _ := GetHistogramVecFromGatherer(legacyregistry.DefaultGatherer, metricName, tt.lvMap) histogramVec, _ := GetHistogramVecFromGatherer(gather, metricName, tt.lvMap) if diff := cmp.Diff(tt.wantVec, histogramVec); diff != \"\" { t.Errorf(\"Got unexpected HistogramVec (-want +got):n%s\", diff) }"} {"_id":"doc-en-kubernetes-517399a7a6b02440bc370daee45159225f1e5e0b1c9b83599318fcbf422435b8","title":"","text":"# REVISION provides a version number for this image and all it's bundled # artifacts. It should start at zero for each LATEST_ETCD_VERSION and increment # for each revision of this image at that etcd version. REVISION?=3 REVISION?=4 # IMAGE_TAG Uniquely identifies k8s.gcr.io/etcd docker image with a tag of the form \"-\". IMAGE_TAG=$(LATEST_ETCD_VERSION)-$(REVISION)"} {"_id":"doc-en-kubernetes-faa63f835ea997ce97c2fc4fb62200805f6e37a917db14ec5b9cf8f7bb7415cc","title":"","text":"RUNNERIMAGE?=gcr.io/distroless/static:latest QEMUVERSION?=5.2.0-2 build: # Explicitly copy files to the temp directory $(BIN_INSTALL) migrate-if-needed.sh $(TEMP_DIR)"} {"_id":"doc-en-kubernetes-f7e8a22430fbd3994f287c159de8158b3b38631527385d3fbcf1c1717f06425b","title":"","text":"cd $(TEMP_DIR) && echo \"ENV ETCD_UNSUPPORTED_ARCH=$(ARCH)\" >> Dockerfile endif docker run --rm --privileged multiarch/qemu-user-static:$(QEMUVERSION) --reset -p yes docker buildx version BUILDER=$(shell docker buildx create --use) # And build the image docker build docker buildx build --pull --load --platform linux/$(ARCH) -t $(REGISTRY)/etcd-$(ARCH):$(IMAGE_TAG) --build-arg BASEIMAGE=$(BASEIMAGE) --build-arg RUNNERIMAGE=$(RUNNERIMAGE) $(TEMP_DIR) docker buildx rm $$BUILDER push: build docker tag $(REGISTRY)/etcd-$(ARCH):$(IMAGE_TAG) $(MANIFEST_IMAGE)-$(ARCH):$(IMAGE_TAG)"} {"_id":"doc-en-kubernetes-ee0dda422d7a44f70c3a6e20bea97ab25d9b68c0d9c77a427b70c9b8dee8c226","title":"","text":"- IMAGE=gcr.io/$PROJECT_ID/etcd - BUILD_IMAGE=debian-build - TMPDIR=/workspace - HOME=/root # for docker buildx args: - '-c' - |"} {"_id":"doc-en-kubernetes-7d1f33dc55721a39ded654e255a23c2047bc9bc7bdd791568202d11946747e68","title":"","text":"return nil } numaNodeReservation := strings.Split(s, \":\") if len(numaNodeReservation) != 2 { return fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", s) } memoryTypeReservations := strings.Split(numaNodeReservation[1], \",\") if len(memoryTypeReservations) < 1 { return fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", s) } numaNodeID, err := strconv.Atoi(numaNodeReservation[0]) if err != nil { return fmt.Errorf(\"failed to convert the NUMA node ID, exptected integer, got %s\", numaNodeReservation[0]) } memoryReservation := kubeletconfig.MemoryReservation{ NumaNode: int32(numaNodeID), Limits: map[v1.ResourceName]resource.Quantity{}, } for _, reservation := range memoryTypeReservations { limit := strings.Split(reservation, \"=\") if len(limit) != 2 { return fmt.Errorf(\"the reserved limit has incorrect value, expected type=quantatity, got %s\", reservation) numaNodeReservations := strings.Split(s, \";\") for _, reservation := range numaNodeReservations { numaNodeReservation := strings.Split(reservation, \":\") if len(numaNodeReservation) != 2 { return fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", reservation) } resourceName := v1.ResourceName(limit[0]) if resourceName != v1.ResourceMemory && !corev1helper.IsHugePageResourceName(resourceName) { return fmt.Errorf(\"memory type conversion error, unknown type: %q\", resourceName) memoryTypeReservations := strings.Split(numaNodeReservation[1], \",\") if len(memoryTypeReservations) < 1 { return fmt.Errorf(\"the reserved memory has incorrect format, expected numaNodeID:type=quantity[,type=quantity...], got %s\", reservation) } q, err := resource.ParseQuantity(limit[1]) numaNodeID, err := strconv.Atoi(numaNodeReservation[0]) if err != nil { return fmt.Errorf(\"failed to parse the quantatity, expected quantatity, got %s\", limit[1]) return fmt.Errorf(\"failed to convert the NUMA node ID, exptected integer, got %s\", numaNodeReservation[0]) } memoryReservation.Limits[v1.ResourceName(limit[0])] = q } memoryReservation := kubeletconfig.MemoryReservation{ NumaNode: int32(numaNodeID), Limits: map[v1.ResourceName]resource.Quantity{}, } *v.Value = append(*v.Value, memoryReservation) for _, memoryTypeReservation := range memoryTypeReservations { limit := strings.Split(memoryTypeReservation, \"=\") if len(limit) != 2 { return fmt.Errorf(\"the reserved limit has incorrect value, expected type=quantatity, got %s\", memoryTypeReservation) } resourceName := v1.ResourceName(limit[0]) if resourceName != v1.ResourceMemory && !corev1helper.IsHugePageResourceName(resourceName) { return fmt.Errorf(\"memory type conversion error, unknown type: %q\", resourceName) } q, err := resource.ParseQuantity(limit[1]) if err != nil { return fmt.Errorf(\"failed to parse the quantatity, expected quantatity, got %s\", limit[1]) } memoryReservation.Limits[v1.ResourceName(limit[0])] = q } *v.Value = append(*v.Value, memoryReservation) } return nil }"} {"_id":"doc-en-kubernetes-264c4952578c53d0bdcaf4c120615e67d509c3b836d8da362d532c5c17a50537","title":"","text":"}, }, { desc: \"valid input with ';' as separator for multiple reserved-memory arguments\", argc: \"blah --reserved-memory=0:memory=1Gi,hugepages-1Gi=1Gi;1:memory=1Gi\", expectVal: []kubeletconfig.MemoryReservation{ { NumaNode: 0, Limits: v1.ResourceList{ v1.ResourceMemory: memory1Gi, resourceNameHugepages1Gi: memory1Gi, }, }, { NumaNode: 1, Limits: v1.ResourceList{ v1.ResourceMemory: memory1Gi, }, }, }, }, { desc: \"invalid input\", argc: \"blah --reserved-memory=bad-input\", expectVal: nil,"} {"_id":"doc-en-kubernetes-a3563b3f5411f0f0aa8b22f20737031693249031732547f8a707f1be69b94dfb","title":"","text":"stripped := []byte{} lines := bytes.Split(file, []byte(\"n\")) for i, line := range lines { if bytes.HasPrefix(bytes.TrimSpace(line), []byte(\"#\")) { trimline := bytes.TrimSpace(line) if bytes.HasPrefix(trimline, []byte(\"#\")) && !bytes.HasPrefix(trimline, []byte(\"#!\")) { continue } stripped = append(stripped, line...)"} {"_id":"doc-en-kubernetes-129edd5f9f7694ff6c6f312b574ff1df735dd73c64de37605b08cd9c02ce084a","title":"","text":"\"sigs.k8s.io/structured-merge-diff/v4/fieldpath\" \"k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel\" structurallisttype \"k8s.io/apiextensions-apiserver/pkg/apiserver/schema/listtype\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/util/validation/field\""} {"_id":"doc-en-kubernetes-baafe10563bfd8c87fdaef2153e655c1fc0d0c052e443901d54e565ad2a2b652","title":"","text":"return errs } uOld, ok := old.(*unstructured.Unstructured) var oldObject map[string]interface{} if !ok { uOld = nil // as a safety precaution, continue with validation if uOld self cannot be cast oldObject = nil } else { oldObject = uOld.Object } v := obj.GetObjectKind().GroupVersionKind().Version // ratcheting validation of x-kubernetes-list-type value map and set if newErrs := structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], uNew.Object); len(newErrs) > 0 { if oldErrs := structurallisttype.ValidateListSetsAndMaps(nil, a.structuralSchemas[v], oldObject); len(oldErrs) == 0 { errs = append(errs, newErrs...) } } // validate x-kubernetes-validations rules if celValidator, ok := a.customResourceStrategy.celValidators[v]; ok { if has, err := hasBlockingErr(errs); has { errs = append(errs, err) } else { err, _ := celValidator.Validate(ctx, nil, a.customResourceStrategy.structuralSchemas[v], uNew.Object, uOld.Object, cel.RuntimeCELCostBudget) err, _ := celValidator.Validate(ctx, nil, a.customResourceStrategy.structuralSchemas[v], uNew.Object, oldObject, cel.RuntimeCELCostBudget) errs = append(errs, err...) } }"} {"_id":"doc-en-kubernetes-e4ed146f1e489e13674ed985eb1e72767f49b476abbc18df2be7e9ab7d561a12","title":"","text":"\"reflect\" \"testing\" \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\" apiextensionsv1 \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1\" structuralschema \"k8s.io/apiextensions-apiserver/pkg/apiserver/schema\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"sigs.k8s.io/yaml\" ) func TestPrepareForUpdate(t *testing.T) {"} {"_id":"doc-en-kubernetes-deacd5349dc1e36081e0938fee4ef7f80a9ed8983910048218db93e757f2baa4","title":"","text":"} } } const listTypeResourceSchema = ` apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: foos.test spec: group: test names: kind: Foo listKind: FooList plural: foos singular: foo scope: Cluster versions: - name: v1 schema: openAPIV3Schema: type: object properties: numArray: type: array x-kubernetes-list-type: set items: type: object served: true storage: true - name: v2 schema: openAPIV3Schema: type: object properties: numArray2: type: array ` func TestStatusStrategyValidateUpdate(t *testing.T) { crdV1 := &apiextensionsv1.CustomResourceDefinition{} err := yaml.Unmarshal([]byte(listTypeResourceSchema), &crdV1) if err != nil { t.Fatalf(\"unexpected decoding error: %v\", err) } t.Logf(\"crd v1 details: %v\", crdV1) crd := &apiextensions.CustomResourceDefinition{} if err = apiextensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(crdV1, crd, nil); err != nil { t.Fatalf(\"unexpected convert error: %v\", err) } t.Logf(\"crd details: %v\", crd) strategy := statusStrategy{} kind := schema.GroupVersionKind{ Version: crd.Spec.Versions[0].Name, Kind: crd.Spec.Names.Kind, Group: crd.Spec.Group, } strategy.customResourceStrategy.validator.kind = kind ss, _ := structuralschema.NewStructural(crd.Spec.Versions[0].Schema.OpenAPIV3Schema) strategy.structuralSchemas = map[string]*structuralschema.Structural{ crd.Spec.Versions[0].Name: ss, } ctx := context.TODO() tcs := []struct { name string old *unstructured.Unstructured obj *unstructured.Unstructured isValid bool }{ { name: \"bothValid\", old: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"numArray\": []interface{}{1, 2}}}, obj: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"numArray\": []interface{}{1, 3}, \"metadata\": map[string]interface{}{\"resourceVersion\": \"1\"}}}, isValid: true, }, { name: \"change to invalid\", old: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"old\", \"numArray\": []interface{}{1, 2}}}, obj: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"new\", \"numArray\": []interface{}{1, 1}, \"metadata\": map[string]interface{}{\"resourceVersion\": \"1\"}}}, isValid: false, }, { name: \"change to valid\", old: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"new\", \"numArray\": []interface{}{1, 1}}}, obj: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"old\", \"numArray\": []interface{}{1, 2}, \"metadata\": map[string]interface{}{\"resourceVersion\": \"1\"}}}, isValid: true, }, { name: \"keeps invalid\", old: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"new\", \"numArray\": []interface{}{1, 1}}}, obj: &unstructured.Unstructured{Object: map[string]interface{}{\"apiVersion\": \"test/v1\", \"kind\": \"Foo\", \"spec\": \"old\", \"numArray\": []interface{}{1, 1}, \"metadata\": map[string]interface{}{\"resourceVersion\": \"1\"}}}, isValid: true, }, } for _, tc := range tcs { errs := strategy.ValidateUpdate(ctx, tc.obj, tc.old) if tc.isValid && len(errs) > 0 { t.Errorf(\"%v: unexpected error: %v\", tc.name, errs) } if !tc.isValid && len(errs) == 0 { t.Errorf(\"%v: unexpected non-error\", tc.name) } } } "} {"_id":"doc-en-kubernetes-4ac4e34c87528e1ca8b8b357633248223dfb4817110ad07d736f87c33a24b028","title":"","text":"concurrencyLimit: 6, evalDuration: time.Second * 20, expectedFair: []bool{true}, expectedFairnessMargin: []float64{0.15}, expectedFairnessMargin: []float64{0.155}, expectAllRequests: true, evalInqueueMetrics: true, evalExecutingMetrics: true,"} {"_id":"doc-en-kubernetes-c3d53f240279811bc8764b2593923c9acc49b9b7e3f4357bcaa6560530be9b84","title":"","text":"\"k8s.io/kubernetes/pkg/features\" kevents \"k8s.io/kubernetes/pkg/kubelet/events\" \"k8s.io/kubernetes/pkg/util/goroutinemap/exponentialbackoff\" nodeutil \"k8s.io/kubernetes/pkg/util/node\" \"k8s.io/kubernetes/pkg/util/taints\" \"k8s.io/kubernetes/pkg/volume/util\" \"k8s.io/kubernetes/pkg/volume/util/operationexecutor\""} {"_id":"doc-en-kubernetes-ac342d41855637fd0202498ddb6377382f594e60b06330639e0d576f680f0e62","title":"","text":"return false, nil } // nodeIsHealthy returns true if the node looks healthy. func (rc *reconciler) nodeIsHealthy(nodeName types.NodeName) (bool, error) { node, err := rc.nodeLister.Get(string(nodeName)) if err != nil { return false, err } return nodeutil.IsNodeReady(node), nil } func (rc *reconciler) reconcile() { // Detaches are triggered before attaches so that volumes referenced by // pods that are rescheduled to a different node are detached first."} {"_id":"doc-en-kubernetes-9d2e0e920a45a0e4a0f11e9337d373ee5472c803dfb4af0f1ae30f1cc4015d11","title":"","text":"// Check whether timeout has reached the maximum waiting time timeout := elapsedTime > rc.maxWaitForUnmountDuration isHealthy, err := rc.nodeIsHealthy(attachedVolume.NodeName) if err != nil { klog.Errorf(\"failed to get health of node %s: %s\", attachedVolume.NodeName, err.Error()) } // Force detach volumes from unhealthy nodes after maxWaitForUnmountDuration. forceDetach := !isHealthy && timeout hasOutOfServiceTaint, err := rc.hasOutOfServiceTaint(attachedVolume.NodeName) if err != nil { klog.Errorf(\"failed to get taint specs for node %s: %s\", attachedVolume.NodeName, err.Error()) } // Check whether volume is still mounted. Skip detach if it is still mounted unless timeout // Check whether volume is still mounted. Skip detach if it is still mounted unless force detach timeout // or the node has `node.kubernetes.io/out-of-service` taint. if attachedVolume.MountedByNode && !timeout && !hasOutOfServiceTaint { if attachedVolume.MountedByNode && !forceDetach && !hasOutOfServiceTaint { klog.V(5).InfoS(\"Cannot detach volume because it is still mounted\", \"volume\", attachedVolume) continue }"} {"_id":"doc-en-kubernetes-5c556e11c07548a2a407ee728c9a2814397b971e99f130d0a036dcf69bb0978d","title":"","text":"volumeSpec := controllervolumetesting.GetTestVolumeSpec(string(volumeName), volumeName) nodeName := k8stypes.NodeName(\"node-name\") dsw.AddNode(nodeName, false /*keepTerminatedPodVolumes*/) volumeExists := dsw.VolumeExists(volumeName, nodeName) if volumeExists { t.Fatalf("} {"_id":"doc-en-kubernetes-f291ad5aa5ecaf4e699c7fad6591eccd4ab3b422bb693883326ac18b8b1e1f2b","title":"","text":"waitForDetachCallCount(t, 0 /* expectedDetachCallCount */, fakePlugin) } // Populates desiredStateOfWorld cache with one node/volume/pod tuple. // The node starts as healthy. // // Calls Run() // Verifies there is one attach call and no detach calls. // Deletes the pod from desiredStateOfWorld cache without first marking the node/volume as unmounted. // Verifies that the volume is NOT detached after maxWaitForUnmountDuration. // Marks the node as unhealthy. // Verifies that the volume is detached after maxWaitForUnmountDuration. func Test_Run_OneVolumeDetachOnUnhealthyNode(t *testing.T) { // Arrange volumePluginMgr, fakePlugin := volumetesting.GetTestVolumePluginMgr(t) dsw := cache.NewDesiredStateOfWorld(volumePluginMgr) asw := cache.NewActualStateOfWorld(volumePluginMgr) fakeKubeClient := controllervolumetesting.CreateTestClient() fakeRecorder := &record.FakeRecorder{} fakeHandler := volumetesting.NewBlockVolumePathHandler() ad := operationexecutor.NewOperationExecutor(operationexecutor.NewOperationGenerator( fakeKubeClient, volumePluginMgr, fakeRecorder, fakeHandler)) informerFactory := informers.NewSharedInformerFactory(fakeKubeClient, controller.NoResyncPeriodFunc()) nsu := statusupdater.NewFakeNodeStatusUpdater(false /* returnError */) nodeLister := informerFactory.Core().V1().Nodes().Lister() reconciler := NewReconciler( reconcilerLoopPeriod, maxWaitForUnmountDuration, syncLoopPeriod, false, dsw, asw, ad, nsu, nodeLister, fakeRecorder) podName1 := \"pod-uid1\" volumeName1 := v1.UniqueVolumeName(\"volume-name1\") volumeSpec1 := controllervolumetesting.GetTestVolumeSpec(string(volumeName1), volumeName1) nodeName1 := k8stypes.NodeName(\"worker-0\") node1 := &v1.Node{ ObjectMeta: metav1.ObjectMeta{Name: string(nodeName1)}, Status: v1.NodeStatus{ Conditions: []v1.NodeCondition{ { Type: v1.NodeReady, Status: v1.ConditionTrue, }, }, }, } informerFactory.Core().V1().Nodes().Informer().GetStore().Add(node1) dsw.AddNode(nodeName1, false /*keepTerminatedPodVolumes*/) volumeExists := dsw.VolumeExists(volumeName1, nodeName1) if volumeExists { t.Fatalf( \"Volume %q/node %q should not exist, but it does.\", volumeName1, nodeName1) } generatedVolumeName, podErr := dsw.AddPod(types.UniquePodName(podName1), controllervolumetesting.NewPod(podName1, podName1), volumeSpec1, nodeName1) if podErr != nil { t.Fatalf(\"AddPod failed. Expected: Actual: <%v>\", podErr) } // Act ch := make(chan struct{}) go reconciler.Run(ch) defer close(ch) // Assert waitForNewAttacherCallCount(t, 1 /* expectedCallCount */, fakePlugin) verifyNewAttacherCallCount(t, false /* expectZeroNewAttacherCallCount */, fakePlugin) waitForAttachCallCount(t, 1 /* expectedAttachCallCount */, fakePlugin) verifyNewDetacherCallCount(t, true /* expectZeroNewDetacherCallCount */, fakePlugin) waitForDetachCallCount(t, 0 /* expectedDetachCallCount */, fakePlugin) // Act // Delete the pod and the volume will be detached even after the maxWaitForUnmountDuration expires as volume is // not unmounted and the node is healthy. dsw.DeletePod(types.UniquePodName(podName1), generatedVolumeName, nodeName1) time.Sleep(maxWaitForUnmountDuration * 5) // Assert waitForNewDetacherCallCount(t, 0 /* expectedCallCount */, fakePlugin) verifyNewAttacherCallCount(t, false /* expectZeroNewAttacherCallCount */, fakePlugin) waitForAttachCallCount(t, 1 /* expectedAttachCallCount */, fakePlugin) verifyNewDetacherCallCount(t, true /* expectZeroNewDetacherCallCount */, fakePlugin) waitForDetachCallCount(t, 0 /* expectedDetachCallCount */, fakePlugin) // Act // Mark the node unhealthy node2 := node1.DeepCopy() node2.Status.Conditions[0].Status = v1.ConditionFalse informerFactory.Core().V1().Nodes().Informer().GetStore().Update(node2) // Assert -- Detach was triggered after maxWaitForUnmountDuration waitForNewDetacherCallCount(t, 1 /* expectedCallCount */, fakePlugin) verifyNewAttacherCallCount(t, false /* expectZeroNewAttacherCallCount */, fakePlugin) waitForAttachCallCount(t, 1 /* expectedAttachCallCount */, fakePlugin) verifyNewDetacherCallCount(t, false /* expectZeroNewDetacherCallCount */, fakePlugin) waitForDetachCallCount(t, 1 /* expectedDetachCallCount */, fakePlugin) } func Test_ReportMultiAttachError(t *testing.T) { type nodeWithPods struct { name k8stypes.NodeName"} {"_id":"doc-en-kubernetes-ee37164ed2880418aca4a0c0026f52cbdc1b656b1eadaa59227e5b102a8b7800","title":"","text":"\"k8s.io/kubernetes/pkg/apis/scheduling\" kubelettypes \"k8s.io/kubernetes/pkg/kubelet/types\" \"k8s.io/kubernetes/test/e2e/framework\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"github.com/onsi/ginkgo\""} {"_id":"doc-en-kubernetes-a412860ff84c740aacd8f2d471705a13fd09907783b21eccae1db23067deeb93","title":"","text":"f := framework.NewDefaultFramework(\"critical-pod-test\") ginkgo.Context(\"when we need to admit a critical pod\", func() { ginkgo.It(\"[Flaky] should be able to create and delete a critical pod\", func() { configEnabled, err := isKubeletConfigEnabled(f) framework.ExpectNoError(err) if !configEnabled { e2eskipper.Skipf(\"unable to run test without dynamic kubelet config enabled.\") } // because adminssion Priority enable, If the priority class is not found, the Pod is rejected. node := getNodeName(f) // Define test pods"} {"_id":"doc-en-kubernetes-fc21b5a42aac7107aeb24ba71200e9e441f1071510fc1808ae395fa5e841becf","title":"","text":"// Add each PodStats to the result. result := make([]statsapi.PodStats, 0, len(podToStats)) for _, podStats := range podToStats { // Lookup the volume stats for each pod. podUID := types.UID(podStats.PodRef.UID) var ephemeralStats []statsapi.VolumeStats if vstats, found := p.resourceAnalyzer.GetPodVolumeStats(podUID); found { ephemeralStats = make([]statsapi.VolumeStats, len(vstats.EphemeralVolumes)) copy(ephemeralStats, vstats.EphemeralVolumes) podStats.VolumeStats = append(append([]statsapi.VolumeStats{}, vstats.EphemeralVolumes...), vstats.PersistentVolumes...) } logStats, err := p.hostStatsProvider.getPodLogStats(podStats.PodRef.Namespace, podStats.PodRef.Name, podUID, &rootFsInfo) if err != nil { klog.ErrorS(err, \"Unable to fetch pod log stats\", \"pod\", klog.KRef(podStats.PodRef.Namespace, podStats.PodRef.Name)) } etcHostsStats, err := p.hostStatsProvider.getPodEtcHostsStats(podUID, &rootFsInfo) if err != nil { klog.ErrorS(err, \"Unable to fetch pod etc hosts stats\", \"pod\", klog.KRef(podStats.PodRef.Namespace, podStats.PodRef.Name)) } makePodStorageStats(podStats, &rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, false) podStats.EphemeralStorage = calcEphemeralStorage(podStats.Containers, ephemeralStats, &rootFsInfo, logStats, etcHostsStats, false) podUID := types.UID(podStats.PodRef.UID) // Lookup the pod-level cgroup's CPU and memory stats podInfo := getCadvisorPodInfoFromPodUID(podUID, allInfos) if podInfo != nil {"} {"_id":"doc-en-kubernetes-25dcaad0fcf3254a3703c2c41a9cadd05d849154190b29d56f64cf8eec77849e","title":"","text":"result := make([]statsapi.PodStats, 0, len(sandboxIDToPodStats)) for _, s := range sandboxIDToPodStats { p.makePodStorageStats(s, rootFsInfo) makePodStorageStats(s, rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, true) result = append(result, *s) } return result, nil"} {"_id":"doc-en-kubernetes-b0c5b59020fa7c62105f68c641ad2fe20f3d8f95319b09140e565322ddcbf9a6","title":"","text":"addCRIPodCPUStats(ps, criSandboxStat) addCRIPodMemoryStats(ps, criSandboxStat) addCRIPodProcessStats(ps, criSandboxStat) p.makePodStorageStats(ps, rootFsInfo) makePodStorageStats(ps, rootFsInfo, p.resourceAnalyzer, p.hostStatsProvider, true) summarySandboxStats = append(summarySandboxStats, *ps) } return summarySandboxStats, nil"} {"_id":"doc-en-kubernetes-07a0ec24495b41d71731376d09788cb02ed8d358547ba6f6c365cfe6e9009ec9","title":"","text":"} } func (p *criStatsProvider) makePodStorageStats(s *statsapi.PodStats, rootFsInfo *cadvisorapiv2.FsInfo) { podNs := s.PodRef.Namespace podName := s.PodRef.Name podUID := types.UID(s.PodRef.UID) vstats, found := p.resourceAnalyzer.GetPodVolumeStats(podUID) if !found { return } logStats, err := p.hostStatsProvider.getPodLogStats(podNs, podName, podUID, rootFsInfo) if err != nil { klog.ErrorS(err, \"Unable to fetch pod log stats\", \"pod\", klog.KRef(podNs, podName)) // If people do in-place upgrade, there might be pods still using // the old log path. For those pods, no pod log stats is returned. // We should continue generating other stats in that case. // calcEphemeralStorage tolerants logStats == nil. } etcHostsStats, err := p.hostStatsProvider.getPodEtcHostsStats(podUID, rootFsInfo) if err != nil { klog.ErrorS(err, \"Unable to fetch pod etc hosts stats\", \"pod\", klog.KRef(podNs, podName)) } ephemeralStats := make([]statsapi.VolumeStats, len(vstats.EphemeralVolumes)) copy(ephemeralStats, vstats.EphemeralVolumes) s.VolumeStats = append(append([]statsapi.VolumeStats{}, vstats.EphemeralVolumes...), vstats.PersistentVolumes...) s.EphemeralStorage = calcEphemeralStorage(s.Containers, ephemeralStats, rootFsInfo, logStats, etcHostsStats, true) } func (p *criStatsProvider) addPodNetworkStats( ps *statsapi.PodStats, podSandboxID string,"} {"_id":"doc-en-kubernetes-ca41943a6f861f8bfd5a59bb55f1224cdd190dbec59bde80bbdc9f084643ee55","title":"","text":"cadvisorapiv1 \"github.com/google/cadvisor/info/v1\" cadvisorapiv2 \"github.com/google/cadvisor/info/v2\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/klog/v2\" statsapi \"k8s.io/kubelet/pkg/apis/stats/v1alpha1\" \"k8s.io/kubernetes/pkg/kubelet/cadvisor\" \"k8s.io/kubernetes/pkg/kubelet/server/stats\" ) // defaultNetworkInterfaceName is used for collectng network stats."} {"_id":"doc-en-kubernetes-632b54ab2a91c26757a14df1e9b3c07344e49329f1045ff9490a88c08b532442","title":"","text":"total := *first + *second return &total } func makePodStorageStats(s *statsapi.PodStats, rootFsInfo *cadvisorapiv2.FsInfo, resourceAnalyzer stats.ResourceAnalyzer, hostStatsProvider HostStatsProvider, isCRIStatsProvider bool) { podNs := s.PodRef.Namespace podName := s.PodRef.Name podUID := types.UID(s.PodRef.UID) var ephemeralStats []statsapi.VolumeStats if vstats, found := resourceAnalyzer.GetPodVolumeStats(podUID); found { ephemeralStats = make([]statsapi.VolumeStats, len(vstats.EphemeralVolumes)) copy(ephemeralStats, vstats.EphemeralVolumes) s.VolumeStats = append(append([]statsapi.VolumeStats{}, vstats.EphemeralVolumes...), vstats.PersistentVolumes...) } logStats, err := hostStatsProvider.getPodLogStats(podNs, podName, podUID, rootFsInfo) if err != nil { klog.V(6).ErrorS(err, \"Unable to fetch pod log stats\", \"pod\", klog.KRef(podNs, podName)) // If people do in-place upgrade, there might be pods still using // the old log path. For those pods, no pod log stats is returned. // We should continue generating other stats in that case. // calcEphemeralStorage tolerants logStats == nil. } etcHostsStats, err := hostStatsProvider.getPodEtcHostsStats(podUID, rootFsInfo) if err != nil { klog.V(6).ErrorS(err, \"Unable to fetch pod etc hosts stats\", \"pod\", klog.KRef(podNs, podName)) } s.EphemeralStorage = calcEphemeralStorage(s.Containers, ephemeralStats, rootFsInfo, logStats, etcHostsStats, isCRIStatsProvider) } "} {"_id":"doc-en-kubernetes-76ca7bda64f0c1ad6b3557281665be0eec60ff2541fe7ca00e6267e7873fe8c4","title":"","text":"\"syscall\" \"time\" \"k8s.io/apimachinery/pkg/apis/meta/v1\" v1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" statsapi \"k8s.io/kubelet/pkg/apis/stats/v1alpha1\" )"} {"_id":"doc-en-kubernetes-1fdbd9194199b1d60fdee7bb87aa842fac6c4c8dd6a6c4d4c107882243731e19","title":"","text":"func Stats() (*statsapi.RlimitStats, error) { rlimit := &statsapi.RlimitStats{} if content, err := ioutil.ReadFile(\"/proc/sys/kernel/pid_max\"); err == nil { if maxPid, err := strconv.ParseInt(string(content[:len(content)-1]), 10, 64); err == nil { rlimit.MaxPID = &maxPid taskMax := int64(-1) // Calculate the mininum of kernel.pid_max and kernel.threads-max as they both specify the // system-wide limit on the number of tasks. for _, file := range []string{\"/proc/sys/kernel/pid_max\", \"/proc/sys/kernel/threads-max\"} { if content, err := ioutil.ReadFile(file); err == nil { if limit, err := strconv.ParseInt(string(content[:len(content)-1]), 10, 64); err == nil { if taskMax == -1 || taskMax > limit { taskMax = limit } } } } // Both reads did not fail. if taskMax >= 0 { rlimit.MaxPID = &taskMax } var info syscall.Sysinfo_t syscall.Sysinfo(&info)"} {"_id":"doc-en-kubernetes-ac70fd81c0346c2cfbf9d1699a9295b7d7bb24e2a72d20dfa9b8a4fca1366092","title":"","text":"type RlimitStats struct { Time metav1.Time `json:\"time\"` // The max PID of OS. // The max number of extant process (threads, precisely on Linux) of OS. See RLIMIT_NPROC in getrlimit(2). // The operating system ceiling on the number of process IDs that can be assigned. // On Linux, tasks (either processes or threads) consume 1 PID each. MaxPID *int64 `json:\"maxpid,omitempty\"` // The number of running process in the OS. // The number of running process (threads, precisely on Linux) in the OS. NumOfRunningProcesses *int64 `json:\"curproc,omitempty\"` }"} {"_id":"doc-en-kubernetes-2ed3dadad15b1a28e1f3859f0e1c67e5e33549c19171191a11efae596192bf65","title":"","text":"containerList, _ := runtimeService.ListContainers(nil) for _, c := range containerList { if _, exists := podSandboxMap[c.PodSandboxId]; !exists { return nil, fmt.Errorf(\"no PodsandBox found with Id '%s'\", c.PodSandboxId) return nil, fmt.Errorf(\"no PodsandBox found with Id '%s' for container with ID '%s' and Name '%s'\", c.PodSandboxId, c.Id, c.Metadata.Name) } containerMap.Add(podSandboxMap[c.PodSandboxId], c.Metadata.Name, c.Id) }"} {"_id":"doc-en-kubernetes-195a3fdc70136eb16a7efda5a5f90d04d7ce9888dee7e97cef6922394590a3bb","title":"","text":"if err != nil { klog.ErrorS(err, \"Failed to get node ip address matching nodeport cidrs, services with nodeport may not work as intended\", \"CIDRs\", proxier.nodePortAddresses) } // nodeAddresses may contain dual-stack zero-CIDRs if proxier.nodePortAddresses is empty. // Ensure nodeAddresses only contains the addresses for this proxier's IP family. isIPv6 := proxier.iptables.IsIPv6() for addr := range nodeAddresses { if utilproxy.IsZeroCIDR(addr) && isIPv6 == netutils.IsIPv6CIDRString(addr) { // if any of the addresses is zero cidr of this IP family, non-zero IPs can be excluded. nodeAddresses = sets.NewString(addr) break } } // Build rules for each service. for svcName, svc := range proxier.serviceMap {"} {"_id":"doc-en-kubernetes-019a21ff015d5fb58feb06b12207c9dce00bd0c516e5893f36c8a226bd64ab70","title":"","text":"// Finally, tail-call to the nodeports chain. This needs to be after all // other service portal rules. isIPv6 := proxier.iptables.IsIPv6() for address := range nodeAddresses { // TODO(thockin, m1093782566): If/when we have dual-stack support we will want to distinguish v4 from v6 zero-CIDRs. if utilproxy.IsZeroCIDR(address) {"} {"_id":"doc-en-kubernetes-53541bd74b2d5dd9021a7099518b09c7455033d5e552d3871cdb5a741f437292","title":"","text":"-A KUBE-SERVICES -m comment --comment \"kubernetes service nodeports; NOTE: this must be the last rule in this chain\" -m addrtype --dst-type LOCAL -j KUBE-NODEPORTS COMMIT ` assert.Equal(t, []*netutils.LocalPort{ { Description: \"nodePort for ns1/svc1:p80\", IP: \"\", IPFamily: netutils.IPv4, Port: svcNodePort, Protocol: netutils.TCP, }, }, fp.portMapper.(*fakePortOpener).openPorts) assertIPTablesRulesEqual(t, expected, fp.iptablesData.String()) }"} {"_id":"doc-en-kubernetes-b4488b64b38c9dc2ca225fd9c70c7125dcfcd7588fcae1c5dde0d86f6160a782","title":"","text":"run(ctx, startSATokenController, initializersFunc) }, OnStoppedLeading: func() { klog.Fatalf(\"leaderelection lost\") klog.ErrorS(nil, \"leaderelection lost\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) }, })"} {"_id":"doc-en-kubernetes-94dc06fb5d1a4bba16b9790ff3d312e24fce3482a3d1402de2b452d48c9bb263","title":"","text":"run(ctx, nil, createInitializersFunc(leaderMigrator.FilterFunc, leadermigration.ControllerMigrated)) }, OnStoppedLeading: func() { klog.Fatalf(\"migration leaderelection lost\") klog.ErrorS(nil, \"migration leaderelection lost\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) }, }) }"} {"_id":"doc-en-kubernetes-881f03860eca3c8d4ac21ecd34dcfea220fb3fcb3fafb013dcfbe321fa63e176","title":"","text":"default: // We lost the lock. klog.ErrorS(nil, \"Leaderelection lost\") os.Exit(1) klog.FlushAndExit(klog.ExitFlushTimeout, 1) } }, }"} {"_id":"doc-en-kubernetes-c57d6340e877cd8cef2e18a75bb26ab792ca80b6495b213f605353b6f4a4fd38","title":"","text":"run(ctx, initializers) }, OnStoppedLeading: func() { klog.Fatalf(\"leaderelection lost\") klog.ErrorS(nil, \"leaderelection lost\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) }, })"} {"_id":"doc-en-kubernetes-904d0cc71f7d2f44864bcc57eaca64535f665dcf856b3720337ba8497b385690","title":"","text":"run(ctx, filterInitializers(controllerInitializers, leaderMigrator.FilterFunc, leadermigration.ControllerMigrated)) }, OnStoppedLeading: func() { klog.Fatalf(\"migration leaderelection lost\") klog.ErrorS(nil, \"migration leaderelection lost\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) }, }) }"} {"_id":"doc-en-kubernetes-ce78f8bb4c6730d920b1d77b6645a835ed282d1247d06d6678185f7ca49f66e3","title":"","text":"\"crypto/x509\" \"encoding/json\" \"fmt\" \"io\" \"io/ioutil\" \"net\" \"net/http\" \"net/http/httptest\" \"net/http/httptrace\" \"os\" \"reflect\" \"strings\" \"sync\""} {"_id":"doc-en-kubernetes-ac75622cb7170cc4f1b2ee4a23b24a550175a0bb2b4c9aa12331b14e1abf360f","title":"","text":"res.Body.Close() } func captureStdErr() (func() string, func(), error) { func TestErrConnKilled(t *testing.T) { var buf bytes.Buffer reader, writer, err := os.Pipe() if err != nil { return nil, nil, err } stderr := os.Stderr readerClosedCh := make(chan struct{}) stopReadingStdErr := func() string { writer.Close() <-readerClosedCh return buf.String() } klog.LogToStderr(true) cleanUp := func() { os.Stderr = stderr klog.LogToStderr(false) stopReadingStdErr() } os.Stderr = writer go func() { io.Copy(&buf, reader) readerClosedCh <- struct{}{} close(readerClosedCh) }() klog.LogToStderr(true) klog.SetOutput(&buf) klog.LogToStderr(false) defer klog.LogToStderr(true) return stopReadingStdErr, cleanUp, nil } func TestErrConnKilled(t *testing.T) { readStdErr, cleanUp, err := captureStdErr() if err != nil { t.Fatalf(\"unable to setup the test, err %v\", err) } defer cleanUp() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // this error must be ignored by the WithPanicRecovery handler // it is thrown by WithTimeoutForNonLongRunningRequests handler when a response has been already sent to the client and the handler timed out"} {"_id":"doc-en-kubernetes-9797bbfebf7316c0977ec43b13deff662edbc3ed1478d869070bcda0fb0387d0","title":"","text":"ts := httptest.NewServer(WithPanicRecovery(handler, resolver)) defer ts.Close() _, err = http.Get(ts.URL) _, err := http.Get(ts.URL) if err == nil { t.Fatal(\"expected to receive an error\") } capturedOutput := readStdErr() klog.Flush() klog.SetOutput(&bytes.Buffer{}) // prevent further writes into buf capturedOutput := buf.String() // We don't expect stack trace from the panic to be included in the log. if isStackTraceLoggedByRuntime(capturedOutput) {"} {"_id":"doc-en-kubernetes-037d35641f47731195b81439e93754ffd84ae535daa4c3652ae6b4b527344d9f","title":"","text":"// TestErrConnKilledHTTP2 check if HTTP/2 connection is not closed when an HTTP handler panics // The net/http library recovers the panic and sends an HTTP/2 RST_STREAM. func TestErrConnKilledHTTP2(t *testing.T) { readStdErr, cleanUp, err := captureStdErr() if err != nil { t.Fatalf(\"unable to setup the test, err %v\", err) } defer cleanUp() var buf bytes.Buffer klog.SetOutput(&buf) klog.LogToStderr(false) defer klog.LogToStderr(true) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // this error must be ignored by the WithPanicRecovery handler // it is thrown by WithTimeoutForNonLongRunningRequests handler when a response has been already sent to the client and the handler timed out"} {"_id":"doc-en-kubernetes-541bda49f6db0b5069932e076aa8afd2c05458d240791031deb647478e6b2a6c","title":"","text":"t.Fatal(\"expected to receive an error\") } capturedOutput := readStdErr() klog.Flush() klog.SetOutput(&bytes.Buffer{}) // prevent further writes into buf capturedOutput := buf.String() // We don't expect stack trace from the panic to be included in the log. if isStackTraceLoggedByRuntime(capturedOutput) {"} {"_id":"doc-en-kubernetes-b5a87dad459bdbd575f616f23aed135952ea741c8938fcf2040a5264e88f8095","title":"","text":"ttlSeconds = int(v1.DefaultClientIPServiceAffinitySeconds) //default to 3 hours if not specified. Should 0 be unlimited instead???? } if _, exists := lb.services[svcPort]; !exists { if state, exists := lb.services[svcPort]; !exists || state == nil { lb.services[svcPort] = &balancerState{affinity: *newAffinityPolicy(affinityType, ttlSeconds)} klog.V(4).InfoS(\"LoadBalancerRR service does not exist, created\", \"servicePortName\", svcPort) } else if affinityType != \"\" {"} {"_id":"doc-en-kubernetes-400c3467b76a9dc543ea1ee163dae56eca9c8e7733dc289307355620928f61d3","title":"","text":"lb.lock.RLock() defer lb.lock.RUnlock() state, exists := lb.services[svcPort] // TODO: while nothing ever assigns nil to the map, *some* of the code using the map // checks for it. The code should all follow the same convention. return exists && state != nil && len(state.endpoints) > 0 if !exists || state == nil { return false } return len(state.endpoints) > 0 } // NextEndpoint returns a service endpoint."} {"_id":"doc-en-kubernetes-ed42756396eb6e7d3924bd23f767ad54b24f3cd1b904f3e0455709a345092664","title":"","text":"} state, exists := lb.services[svcPort] if !exists { if !exists || state == nil { return } for _, existingEndpoint := range state.endpoints {"} {"_id":"doc-en-kubernetes-35d105f7a41df961c3bee78d10804ecb8eb045088995a703ee0a2972dde8e97e","title":"","text":"func (lb *LoadBalancerRR) resetService(svcPort proxy.ServicePortName) { // If the service is still around, reset but don't delete. if state, ok := lb.services[svcPort]; ok { if state, ok := lb.services[svcPort]; ok && state != nil { if len(state.endpoints) > 0 { klog.V(2).InfoS(\"LoadBalancerRR: Removing endpoints service\", \"servicePortName\", svcPort) state.endpoints = []string{}"} {"_id":"doc-en-kubernetes-d3d54ff30dc38073aedb7d176c74d0f9df1f1c35e84a228dd1a2ff5b99bbb8fb","title":"","text":"defer lb.lock.Unlock() state, exists := lb.services[svcPort] if !exists { if !exists || state == nil { return } for ip, affinity := range state.affinity.affinityMap {"} {"_id":"doc-en-kubernetes-8110055fb886fbdb797fae30ca46e414d3f72412ab8ea9c69ccff7cd450e0a6e","title":"","text":"return err } // Drop EndpointSlices that have been marked for deletion to prevent the controller from getting stuck. endpointSlices = dropEndpointSlicesPendingDeletion(endpointSlices) if c.endpointSliceTracker.StaleSlices(service, endpointSlices) { return endpointsliceutil.NewStaleInformerCache(\"EndpointSlice informer cache is out of date\") }"} {"_id":"doc-en-kubernetes-acf9e510a6d01f25fa51b4d59156f82ddbb12950c11f6bdfde22bab2942c755c","title":"","text":"} endpointslicemetrics.EndpointSliceSyncs.WithLabelValues(metricLabel).Inc() } func dropEndpointSlicesPendingDeletion(endpointSlices []*discovery.EndpointSlice) []*discovery.EndpointSlice { n := 0 for _, endpointSlice := range endpointSlices { if endpointSlice.DeletionTimestamp == nil { endpointSlices[n] = endpointSlice n++ } } return endpointSlices[:n] } "} {"_id":"doc-en-kubernetes-89401aa01f4dca0602c7a109050330e08e51de27dbc253b45b1b63440a489455","title":"","text":"assert.EqualValues(t, endpoint.TargetRef, &v1.ObjectReference{Kind: \"Pod\", Namespace: ns, Name: pod1.Name}) } func TestSyncServiceEndpointSlicePendingDeletion(t *testing.T) { client, esController := newController([]string{\"node-1\"}, time.Duration(0)) ns := metav1.NamespaceDefault serviceName := \"testing-1\" service := createService(t, esController, ns, serviceName) err := esController.syncService(fmt.Sprintf(\"%s/%s\", ns, serviceName)) assert.Nil(t, err, \"Expected no error syncing service\") gvk := schema.GroupVersionKind{Version: \"v1\", Kind: \"Service\"} ownerRef := metav1.NewControllerRef(service, gvk) deletedTs := metav1.Now() endpointSlice := &discovery.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ Name: \"epSlice-1\", Namespace: ns, OwnerReferences: []metav1.OwnerReference{*ownerRef}, Labels: map[string]string{ discovery.LabelServiceName: serviceName, discovery.LabelManagedBy: controllerName, }, DeletionTimestamp: &deletedTs, }, AddressType: discovery.AddressTypeIPv4, } err = esController.endpointSliceStore.Add(endpointSlice) if err != nil { t.Fatalf(\"Expected no error adding EndpointSlice: %v\", err) } _, err = client.DiscoveryV1().EndpointSlices(ns).Create(context.TODO(), endpointSlice, metav1.CreateOptions{}) if err != nil { t.Fatalf(\"Expected no error creating EndpointSlice: %v\", err) } numActionsBefore := len(client.Actions()) err = esController.syncService(fmt.Sprintf(\"%s/%s\", ns, serviceName)) assert.Nil(t, err, \"Expected no error syncing service\") // The EndpointSlice marked for deletion should be ignored by the controller, and thus // should not result in more than one action from the client (an update to the non-terminating // EndpointSlice removing the trigger time annotation.) if len(client.Actions()) != numActionsBefore+1 { t.Errorf(\"Expected 1 more action, got %d\", len(client.Actions())-numActionsBefore) } } // Ensure SyncService correctly selects and labels EndpointSlices. func TestSyncServiceEndpointSliceLabelSelection(t *testing.T) { client, esController := newController([]string{\"node-1\"}, time.Duration(0))"} {"_id":"doc-en-kubernetes-63becf94690f4990bc4788161cf1d1f910f05699608f0f160610d0d0599997a0","title":"","text":"} } } func Test_dropEndpointSlicesPendingDeletion(t *testing.T) { now := metav1.Now() endpointSlices := []*discovery.EndpointSlice{ { ObjectMeta: metav1.ObjectMeta{ Name: \"epSlice1\", DeletionTimestamp: &now, }, }, { ObjectMeta: metav1.ObjectMeta{ Name: \"epSlice2\", }, AddressType: discovery.AddressTypeIPv4, Endpoints: []discovery.Endpoint{ { Addresses: []string{\"172.18.0.2\"}, }, }, }, { ObjectMeta: metav1.ObjectMeta{ Name: \"epSlice3\", }, AddressType: discovery.AddressTypeIPv6, Endpoints: []discovery.Endpoint{ { Addresses: []string{\"3001:0da8:75a3:0000:0000:8a2e:0370:7334\"}, }, }, }, } epSlice2 := endpointSlices[1] epSlice3 := endpointSlices[2] result := dropEndpointSlicesPendingDeletion(endpointSlices) assert.Len(t, result, 2) for _, epSlice := range result { if epSlice.Name == \"epSlice1\" { t.Errorf(\"Expected EndpointSlice marked for deletion to be dropped.\") } } // We don't use endpointSlices and instead check manually for equality, because // `dropEndpointSlicesPendingDeletion` mutates the slice it receives, so it's easy // to break this test later. This way, we can be absolutely sure that the result // has exactly what we expect it to. if !reflect.DeepEqual(epSlice2, result[0]) { t.Errorf(\"EndpointSlice was unexpectedly mutated. Expected: %+v, Mutated: %+v\", epSlice2, result[0]) } if !reflect.DeepEqual(epSlice3, result[1]) { t.Errorf(\"EndpointSlice was unexpectedly mutated. Expected: %+v, Mutated: %+v\", epSlice3, result[1]) } } "} {"_id":"doc-en-kubernetes-a19d63ef8b58db5658cbb15195685efd574c214663c32d62ea7bce7673165145","title":"","text":"// 1. One or more of the provided EndpointSlices have older generations than the // corresponding tracked ones. // 2. The tracker is expecting one or more of the provided EndpointSlices to be // deleted. // deleted. (EndpointSlices that have already been marked for deletion are ignored here.) // 3. The tracker is tracking EndpointSlices that have not been provided. func (est *EndpointSliceTracker) StaleSlices(service *v1.Service, endpointSlices []*discovery.EndpointSlice) bool { est.lock.Lock()"} {"_id":"doc-en-kubernetes-57f6b300d974d0e1aafe3248562e34a997f3aab86979b58a01ca6b13a07c06c3","title":"","text":"epSlice1NewerGen := epSlice1.DeepCopy() epSlice1NewerGen.Generation = 2 epTerminatingSlice := epSlice1.DeepCopy() now := metav1.Now() epTerminatingSlice.DeletionTimestamp = &now testCases := []struct { name string tracker *EndpointSliceTracker"} {"_id":"doc-en-kubernetes-c3681733dc7a114c5777b3e00657d92c78f6f78d76449e6b625c0e10af0a4d40","title":"","text":"\"context\" \"fmt\" \"os\" \"os/exec\" \"path\" \"regexp\" \"strings\" \"time\" \"github.com/onsi/ginkgo\" \"github.com/onsi/gomega\" appsv1 \"k8s.io/api/apps/v1\" v1 \"k8s.io/api/core/v1\" rbacv1 \"k8s.io/api/rbac/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/uuid\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/kubernetes/test/e2e/framework\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" imageutils \"k8s.io/kubernetes/test/utils/image\" \"github.com/onsi/ginkgo\" \"github.com/onsi/gomega\" ) const ("} {"_id":"doc-en-kubernetes-f40f50b219b13fa0e7a2da1a18c9711744c7a5309c59432d99a07eac87089a1a","title":"","text":"gmsaCustomResourceName = \"gmsa-e2e\" // gmsaWebhookDeployScriptURL is the URL of the deploy script for the GMSA webook // TODO(wk8): we should pin versions. gmsaWebhookDeployScriptURL = \"https://raw.githubusercontent.com/kubernetes-sigs/windows-gmsa/master/admission-webhook/deploy/deploy-gmsa-webhook.sh\" // output from the nltest /query command should have this in it"} {"_id":"doc-en-kubernetes-9fb5f579fc302114d131db9065b9f210372c12732ddc267bbb0045113b5c3f07","title":"","text":"ginkgo.By(\"retrieving the contents of the GMSACredentialSpec custom resource manifest from the node\") crdManifestContents := retrieveCRDManifestFileContents(f, node) ginkgo.By(\"downloading the GMSA webhook deploy script\") deployScriptPath, err := downloadFile(gmsaWebhookDeployScriptURL) defer func() { os.Remove(deployScriptPath) }() if err != nil { framework.Failf(err.Error()) } ginkgo.By(\"deploying the GMSA webhook\") webhookCleanUp, err := deployGmsaWebhook(f, deployScriptPath) webhookCleanUp, err := deployGmsaWebhook(f) defer webhookCleanUp() if err != nil { framework.Failf(err.Error())"} {"_id":"doc-en-kubernetes-e052a7ee49d69ad25697734ef7c69b73e20eb67ae05a2c2452e5f4c84be21a42","title":"","text":"} return strings.Contains(output, \"This is a test file.\") }, 1*time.Minute, 1*time.Second).Should(gomega.BeTrue()) }) }) })"} {"_id":"doc-en-kubernetes-705b46002fd44f4ebaa04a9efa1f6a6f91ef6fcb640872706d72d3e290aabbf5","title":"","text":"// deployGmsaWebhook deploys the GMSA webhook, and returns a cleanup function // to be called when done with testing, that removes the temp files it's created // on disks as well as the API resources it's created. func deployGmsaWebhook(f *framework.Framework, deployScriptPath string) (func(), error) { cleanUpFunc := func() {} func deployGmsaWebhook(f *framework.Framework) (func(), error) { deployerName := \"webhook-deployer\" deployerNamespace := f.Namespace.Name webHookName := \"gmsa-webhook\" webHookNamespace := deployerNamespace + \"-webhook\" tempDir, err := os.MkdirTemp(\"\", \"\") if err != nil { return cleanUpFunc, fmt.Errorf(\"unable to create temp dir: %w\", err) } // regardless of whether the deployment succeeded, let's do a best effort at cleanup cleanUpFunc := func() { framework.Logf(\"Best effort clean up of the webhook:n\") stdout, err := framework.RunKubectl(\"\", \"delete\", \"CustomResourceDefinition\", \"gmsacredentialspecs.windows.k8s.io\") framework.Logf(\"stdout:%snerror:%s\", stdout, err) manifestsFile := path.Join(tempDir, \"manifests.yml\") name := \"gmsa-webhook\" namespace := f.Namespace.Name + \"-webhook\" certsDir := path.Join(tempDir, \"certs\") stdout, err = framework.RunKubectl(\"\", \"delete\", \"CertificateSigningRequest\", fmt.Sprintf(\"%s.%s\", webHookName, webHookNamespace)) framework.Logf(\"stdout:%snerror:%s\", stdout, err) // regardless of whether the deployment succeeded, let's do a best effort at cleanup cleanUpFunc = func() { framework.RunKubectl(f.Namespace.Name, \"delete\", \"--filename\", manifestsFile) framework.RunKubectl(f.Namespace.Name, \"delete\", \"CustomResourceDefinition\", \"gmsacredentialspecs.windows.k8s.io\") framework.RunKubectl(f.Namespace.Name, \"delete\", \"CertificateSigningRequest\", fmt.Sprintf(\"%s.%s\", name, namespace)) os.RemoveAll(tempDir) stdout, err = runKubectlExecInNamespace(deployerNamespace, deployerName, \"--\", \"kubectl\", \"delete\", \"-f\", \"/manifests.yml\") framework.Logf(\"stdout:%snerror:%s\", stdout, err) } // ensure the deployer has ability to approve certificatesigningrequests to install the webhook s := createServiceAccount(f) bindClusterRBACRoleToServiceAccount(f, s, \"cluster-admin\") installSteps := []string{ \"echo \"@testing http://dl-cdn.alpinelinux.org/alpine/edge/testing/\" >> /etc/apk/repositories\", \"&& apk add kubectl@testing gettext openssl\", \"&& apk add --update coreutils\", fmt.Sprintf(\"&& curl %s > gmsa.sh\", gmsaWebhookDeployScriptURL), \"&& chmod +x gmsa.sh\", fmt.Sprintf(\"&& ./gmsa.sh --file %s --name %s --namespace %s --certs-dir %s --tolerate-master\", \"/manifests.yml\", webHookName, webHookNamespace, \"certs\"), \"&& /agnhost pause\", } installCommand := strings.Join(installSteps, \" \") cmd := exec.Command(\"bash\", deployScriptPath, \"--file\", manifestsFile, \"--name\", name, \"--namespace\", namespace, \"--certs-dir\", certsDir, \"--tolerate-master\") pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: deployerName, Namespace: deployerNamespace, }, Spec: v1.PodSpec{ ServiceAccountName: s, NodeSelector: map[string]string{ \"kubernetes.io/os\": \"linux\", }, Containers: []v1.Container{ { Name: deployerName, Image: imageutils.GetE2EImage(imageutils.Agnhost), Command: []string{\"bash\", \"-c\"}, Args: []string{installCommand}, }, }, Tolerations: []v1.Toleration{ { Operator: v1.TolerationOpExists, Effect: v1.TaintEffectNoSchedule, }, }, }, } f.PodClient().CreateSync(pod) output, err := cmd.CombinedOutput() // Wait for the Webhook deployment to become ready. The deployer pod takes a few seconds to initialize and create resources err := waitForDeployment(func() (*appsv1.Deployment, error) { return f.ClientSet.AppsV1().Deployments(webHookNamespace).Get(context.TODO(), webHookName, metav1.GetOptions{}) }, 10*time.Second, f.Timeouts.PodStart) if err == nil { framework.Logf(\"GMSA webhook successfully deployed, output:n%s\", string(output)) framework.Logf(\"GMSA webhook successfully deployed\") } else { err = fmt.Errorf(\"unable to deploy GMSA webhook, output:n%s: %w\", string(output), err) err = fmt.Errorf(\"GMSA webhook did not become ready: %w\", err) } // Dump deployer logs logs, _ := e2epod.GetPodLogs(f.ClientSet, deployerNamespace, deployerName, deployerName) framework.Logf(\"GMSA deployment logs:n%s\", logs) return cleanUpFunc, err }"} {"_id":"doc-en-kubernetes-15409ab2b17d5010b95cec333a4e350ae0747c49aa51c1fde6107fed8f936bcb","title":"","text":"// createServiceAccount creates a service account, and returns its name. func createServiceAccount(f *framework.Framework) string { accountName := f.Namespace.Name + \"-sa\" accountName := f.Namespace.Name + \"-sa-\" + string(uuid.NewUUID()) account := &v1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: accountName,"} {"_id":"doc-en-kubernetes-762fe8f176ef54f9e927fe55343a4ea65ad2e022bb445b31bce28c3de89606c8","title":"","text":"f.ClientSet.RbacV1().RoleBindings(f.Namespace.Name).Create(context.TODO(), binding, metav1.CreateOptions{}) } func bindClusterRBACRoleToServiceAccount(f *framework.Framework, serviceAccountName, rbacRoleName string) { binding := &rbacv1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: f.Namespace.Name + \"-rbac-binding\", Namespace: f.Namespace.Name, }, Subjects: []rbacv1.Subject{ { Kind: \"ServiceAccount\", Name: serviceAccountName, Namespace: f.Namespace.Name, }, }, RoleRef: rbacv1.RoleRef{ APIGroup: \"rbac.authorization.k8s.io\", Kind: \"ClusterRole\", Name: rbacRoleName, }, } f.ClientSet.RbacV1().ClusterRoleBindings().Create(context.TODO(), binding, metav1.CreateOptions{}) } // createPodWithGmsa creates a pod using the test GMSA cred spec, and returns its name. func createPodWithGmsa(f *framework.Framework, serviceAccountName string) string { podName := \"pod-with-gmsa\""} {"_id":"doc-en-kubernetes-655691874f02405019456c286b6cc81b9e8d9a343602238174d6d0861ca9e3ba","title":"","text":"package windows import ( \"fmt\" \"io\" \"net/http\" \"os\" \"time\" appsv1 \"k8s.io/api/apps/v1\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/kubernetes/pkg/controller/deployment/util\" \"k8s.io/kubernetes/test/e2e/framework\" ) // downloadFile saves a remote URL to a local temp file, and returns its path. // It's the caller's responsibility to clean up the temp file when done. func downloadFile(url string) (string, error) { response, err := http.Get(url) if err != nil { return \"\", fmt.Errorf(\"unable to download from %q: %w\", url, err) } defer response.Body.Close() tempFile, err := os.CreateTemp(\"\", \"\") if err != nil { return \"\", fmt.Errorf(\"unable to create temp file: %w\", err) } defer tempFile.Close() _, err = io.Copy(tempFile, response.Body) return tempFile.Name(), err // waits for a deployment to be created and the desired replicas // are updated and available, and no old pods are running. func waitForDeployment(getDeploymentFunc func() (*appsv1.Deployment, error), interval, timeout time.Duration) error { return wait.PollImmediate(interval, timeout, func() (bool, error) { deployment, err := getDeploymentFunc() if err != nil { if apierrors.IsNotFound(err) { framework.Logf(\"deployment not found, continue waiting: %s\", err) return false, nil } framework.Logf(\"error while deploying, error %s\", err) return false, err } framework.Logf(\"deployment status %s\", &deployment.Status) return util.DeploymentComplete(deployment, &deployment.Status), nil }) }"} {"_id":"doc-en-kubernetes-226506a7022711190ffa06504cb00559dfb4084519de3cb199d650fa0df3af56","title":"","text":"if err != nil { return currentRevision, updateRevision, currentStatus, err } // update the set's status err = ssc.updateStatefulSetStatus(ctx, set, currentStatus) if err != nil { return currentRevision, updateRevision, currentStatus, err } klog.V(4).InfoS(\"StatefulSet pod status\", \"statefulSet\", klog.KObj(set), \"replicas\", currentStatus.Replicas, \"readyReplicas\", currentStatus.ReadyReplicas, \"currentReplicas\", currentStatus.CurrentReplicas, \"updatedReplicas\", currentStatus.UpdatedReplicas) klog.V(4).InfoS(\"StatefulSet revisions\", \"statefulSet\", klog.KObj(set), \"currentRevision\", currentStatus.CurrentRevision,"} {"_id":"doc-en-kubernetes-77cfdc29a9a2fac9190c95e6468b990f68f0ecc85879ca28cb82b188f0af1077","title":"","text":"currentRevision *apps.ControllerRevision, updateRevision *apps.ControllerRevision, collisionCount int32, pods []*v1.Pod) (*apps.StatefulSetStatus, error) { pods []*v1.Pod) (statefulSetStatus *apps.StatefulSetStatus, updateErr error) { // get the current and update revisions of the set. currentSet, err := ApplyRevision(set, currentRevision) if err != nil {"} {"_id":"doc-en-kubernetes-a62793a3b95d6154d92dbb5c2a9dce87a97b4035747cff8d90565e03c4cdd943","title":"","text":"// If the ordinal could not be parsed (ord < 0), ignore the Pod. } // make sure to update the latest status even if there is an error later defer func() { // update the set's status statusErr := ssc.updateStatefulSetStatus(ctx, set, &status) if statusErr == nil { klog.V(4).InfoS(\"Updated status\", \"statefulSet\", klog.KObj(set), \"replicas\", status.Replicas, \"readyReplicas\", status.ReadyReplicas, \"currentReplicas\", status.CurrentReplicas, \"updatedReplicas\", status.UpdatedReplicas) } else if updateErr == nil { updateErr = statusErr } else { klog.V(4).InfoS(\"Could not update status\", \"statefulSet\", klog.KObj(set), \"err\", statusErr) } }() // for any empty indices in the sequence [0,set.Spec.Replicas) create a new Pod at the correct revision for ord := 0; ord < replicaCount; ord++ { if replicas[ord] == nil {"} {"_id":"doc-en-kubernetes-02369f5455d315618e0fe3a5d64d150795609f5590ddf5c6cca8520c03a0b991","title":"","text":"\"k8s.io/apimachinery/pkg/util/wait\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/dynamic\" \"k8s.io/client-go/informers\" clientset \"k8s.io/client-go/kubernetes\" restclient \"k8s.io/client-go/rest\" featuregatetesting \"k8s.io/component-base/featuregate/testing\" apiservertesting \"k8s.io/kubernetes/cmd/kube-apiserver/app/testing\" podutil \"k8s.io/kubernetes/pkg/api/v1/pod\" \"k8s.io/kubernetes/pkg/controller/statefulset\" \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/test/integration/framework\" )"} {"_id":"doc-en-kubernetes-e84c0e32bfe65505956074e2f3aaca99604674973b4c388043a60a6186bc3923","title":"","text":"t.Fatalf(\"failed to mark all StatefulSet pods to ready: %v\", err) } } // add for issue: https://github.com/kubernetes/kubernetes/issues/108837 func TestStatefulSetStatusWithPodFail(t *testing.T) { limitedPodNumber := 2 controlPlaneConfig := framework.NewIntegrationTestControlPlaneConfig() controlPlaneConfig.GenericConfig.AdmissionControl = &fakePodFailAdmission{ limitedPodNumber: limitedPodNumber, } _, s, closeFn := framework.RunAnAPIServer(controlPlaneConfig) defer closeFn() config := restclient.Config{Host: s.URL} c, err := clientset.NewForConfig(&config) if err != nil { t.Fatalf(\"Could not create clientset: %v\", err) } resyncPeriod := 12 * time.Hour informers := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, \"statefulset-informers\")), resyncPeriod) ssc := statefulset.NewStatefulSetController( informers.Core().V1().Pods(), informers.Apps().V1().StatefulSets(), informers.Core().V1().PersistentVolumeClaims(), informers.Apps().V1().ControllerRevisions(), clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, \"statefulset-controller\")), ) ns := framework.CreateTestingNamespace(\"test-pod-fail\", s, t) defer framework.DeleteTestingNamespace(ns, s, t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() informers.Start(ctx.Done()) go ssc.Run(ctx, 5) sts := newSTS(\"sts\", ns.Name, 4) _, err = c.AppsV1().StatefulSets(sts.Namespace).Create(context.TODO(), sts, metav1.CreateOptions{}) if err != nil { t.Fatalf(\"Could not create statefuleSet %s: %v\", sts.Name, err) } wantReplicas := limitedPodNumber var gotReplicas int32 if err := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) { newSTS, err := c.AppsV1().StatefulSets(sts.Namespace).Get(context.TODO(), sts.Name, metav1.GetOptions{}) if err != nil { return false, err } gotReplicas = newSTS.Status.Replicas return gotReplicas == int32(wantReplicas), nil }); err != nil { t.Fatalf(\"StatefulSet %s status has %d replicas, want replicas %d: %v\", sts.Name, gotReplicas, wantReplicas, err) } } "} {"_id":"doc-en-kubernetes-f31a66de7a792b9ed2eeed3febd01148ea3ffc1f214396ca2acb4d14d508758f","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/apiserver/pkg/admission\" \"k8s.io/client-go/informers\" clientset \"k8s.io/client-go/kubernetes\" typedappsv1 \"k8s.io/client-go/kubernetes/typed/apps/v1\" typedv1 \"k8s.io/client-go/kubernetes/typed/core/v1\" restclient \"k8s.io/client-go/rest\" \"k8s.io/client-go/util/retry\" api \"k8s.io/kubernetes/pkg/apis/core\" //svc \"k8s.io/kubernetes/pkg/api/v1/service\" \"k8s.io/kubernetes/pkg/controller/statefulset\""} {"_id":"doc-en-kubernetes-0f3dc5e6f38ff6334211019f6e75716bab58a113bc4f2fa35c566ea0c270297f","title":"","text":"} waitSTSStable(t, c, sts) } var _ admission.ValidationInterface = &fakePodFailAdmission{} type fakePodFailAdmission struct { limitedPodNumber int succeedPodsCount int } func (f *fakePodFailAdmission) Handles(operation admission.Operation) bool { return operation == admission.Create } func (f *fakePodFailAdmission) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) { if attr.GetKind().GroupKind() != api.Kind(\"Pod\") { return nil } if f.succeedPodsCount >= f.limitedPodNumber { return fmt.Errorf(\"fakePodFailAdmission error\") } f.succeedPodsCount++ return nil } "} {"_id":"doc-en-kubernetes-d12b67112640c77ebb59b7a3b9430401678232d296e1770731ce43450d62cd48","title":"","text":"\"context\" \"crypto/sha256\" \"encoding/binary\" \"encoding/json\" \"errors\" \"fmt\" \"math\""} {"_id":"doc-en-kubernetes-0f95c287d93357d1e884c26f2f7483051fdd8094d53d308effec3342829bef79","title":"","text":"apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" apitypes \"k8s.io/apimachinery/pkg/types\" utilerrors \"k8s.io/apimachinery/pkg/util/errors\" utilruntime \"k8s.io/apimachinery/pkg/util/runtime\" \"k8s.io/apimachinery/pkg/util/sets\""} {"_id":"doc-en-kubernetes-0ebaad127f0e14eb22d5992a0f6b2a49c2716aa2788a119b281a86a1d055ac21","title":"","text":"\"k8s.io/utils/clock\" flowcontrol \"k8s.io/api/flowcontrol/v1beta2\" flowcontrolapplyconfiguration \"k8s.io/client-go/applyconfigurations/flowcontrol/v1beta2\" flowcontrolclient \"k8s.io/client-go/kubernetes/typed/flowcontrol/v1beta2\" flowcontrollister \"k8s.io/client-go/listers/flowcontrol/v1beta2\" )"} {"_id":"doc-en-kubernetes-f3e9bc44b7bb73e77e8141a0387be43fe47a09cd5251ef5e8359f5a771661bff","title":"","text":"// if we are going to issue an update, be sure we track every name we update so we know if we update it too often. currResult.updatedItems.Insert(fsu.flowSchema.Name) patchBytes, err := makeFlowSchemaConditionPatch(fsu.condition) if err != nil { // should never happen because these conditions are created here and well formed panic(fmt.Sprintf(\"Failed to json.Marshall(%#+v): %s\", fsu.condition, err.Error())) } if klogV := klog.V(4); klogV.Enabled() { klogV.Infof(\"%s writing Condition %s to FlowSchema %s, which had ResourceVersion=%s, because its previous value was %s, diff: %s\", cfgCtlr.name, fsu.condition, fsu.flowSchema.Name, fsu.flowSchema.ResourceVersion, fcfmt.Fmt(fsu.oldValue), cmp.Diff(fsu.oldValue, fsu.condition)) } fsIfc := cfgCtlr.flowcontrolClient.FlowSchemas() applyOptions := metav1.ApplyOptions{FieldManager: cfgCtlr.asFieldManager, Force: true} // the condition field in fsStatusUpdate holds the new condition we want to update. // TODO: this will break when we have multiple conditions for a flowschema _, err := fsIfc.ApplyStatus(context.TODO(), toFlowSchemaApplyConfiguration(fsu), applyOptions) patchOptions := metav1.PatchOptions{FieldManager: cfgCtlr.asFieldManager} _, err = fsIfc.Patch(context.TODO(), fsu.flowSchema.Name, apitypes.StrategicMergePatchType, patchBytes, patchOptions, \"status\") if err != nil { if apierrors.IsNotFound(err) { // This object has been deleted. A notification is coming"} {"_id":"doc-en-kubernetes-43bf4f69ce6d650a59e97eea1cf73c80fafd8031a8242048fcc686b03b1568a1","title":"","text":"return suggestedDelay, utilerrors.NewAggregate(errs) } func toFlowSchemaApplyConfiguration(fsUpdate fsStatusUpdate) *flowcontrolapplyconfiguration.FlowSchemaApplyConfiguration { condition := flowcontrolapplyconfiguration.FlowSchemaCondition(). WithType(fsUpdate.condition.Type). WithStatus(fsUpdate.condition.Status). WithReason(fsUpdate.condition.Reason). WithLastTransitionTime(fsUpdate.condition.LastTransitionTime). WithMessage(fsUpdate.condition.Message) return flowcontrolapplyconfiguration.FlowSchema(fsUpdate.flowSchema.Name). WithStatus(flowcontrolapplyconfiguration.FlowSchemaStatus(). WithConditions(condition), ) // makeFlowSchemaConditionPatch takes in a condition and returns the patch status as a json. func makeFlowSchemaConditionPatch(condition flowcontrol.FlowSchemaCondition) ([]byte, error) { o := struct { Status flowcontrol.FlowSchemaStatus `json:\"status\"` }{ Status: flowcontrol.FlowSchemaStatus{ Conditions: []flowcontrol.FlowSchemaCondition{ condition, }, }, } return json.Marshal(o) } // shouldDelayUpdate checks to see if a flowschema has been updated too often and returns true if a delay is needed."} {"_id":"doc-en-kubernetes-a070881c3f97cd29c42199e1bf52ecbec9ec149a4bbfcfa4252faf31aeafd2c8","title":"","text":" /* Copyright 2021 The Kubernetes Authors. 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. */ package flowcontrol import ( \"fmt\" \"reflect\" \"testing\" \"time\" \"github.com/google/go-cmp/cmp\" flowcontrol \"k8s.io/api/flowcontrol/v1beta2\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" ) func Test_configController_generatePatchBytes(t *testing.T) { now := time.Now().UTC() tests := []struct { name string condition flowcontrol.FlowSchemaCondition want []byte }{ { name: \"check if only condition is parsed\", condition: flowcontrol.FlowSchemaCondition{ Type: flowcontrol.FlowSchemaConditionDangling, Status: flowcontrol.ConditionTrue, Reason: \"test reason\", Message: \"test none\", LastTransitionTime: metav1.NewTime(now), }, want: []byte(fmt.Sprintf(`{\"status\":{\"conditions\":[{\"type\":\"Dangling\",\"status\":\"True\",\"lastTransitionTime\":\"%s\",\"reason\":\"test reason\",\"message\":\"test none\"}]}}`, now.Format(time.RFC3339))), }, { name: \"check when message has double quotes\", condition: flowcontrol.FlowSchemaCondition{ Type: flowcontrol.FlowSchemaConditionDangling, Status: flowcontrol.ConditionTrue, Reason: \"test reason\", Message: `test \"\"none`, LastTransitionTime: metav1.NewTime(now), }, want: []byte(fmt.Sprintf(`{\"status\":{\"conditions\":[{\"type\":\"Dangling\",\"status\":\"True\",\"lastTransitionTime\":\"%s\",\"reason\":\"test reason\",\"message\":\"test \"\"none\"}]}}`, now.Format(time.RFC3339))), }, { name: \"check when message has a whitespace character that can be escaped\", condition: flowcontrol.FlowSchemaCondition{ Type: flowcontrol.FlowSchemaConditionDangling, Status: flowcontrol.ConditionTrue, Reason: \"test reason\", Message: `test \t\tnone`, LastTransitionTime: metav1.NewTime(now), }, want: []byte(fmt.Sprintf(`{\"status\":{\"conditions\":[{\"type\":\"Dangling\",\"status\":\"True\",\"lastTransitionTime\":\"%s\",\"reason\":\"test reason\",\"message\":\"test ttnone\"}]}}`, now.Format(time.RFC3339))), }, { name: \"check when a few fields (message & lastTransitionTime) are missing\", condition: flowcontrol.FlowSchemaCondition{ Type: flowcontrol.FlowSchemaConditionDangling, Status: flowcontrol.ConditionTrue, Reason: \"test reason\", }, want: []byte(`{\"status\":{\"conditions\":[{\"type\":\"Dangling\",\"status\":\"True\",\"lastTransitionTime\":null,\"reason\":\"test reason\"}]}}`), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, _ := makeFlowSchemaConditionPatch(tt.condition) if !reflect.DeepEqual(got, tt.want) { t.Errorf(\"makeFlowSchemaConditionPatch() got = %s, want %s; diff is %s\", got, tt.want, cmp.Diff(tt.want, got)) } }) } } "} {"_id":"doc-en-kubernetes-91e7217604dce837a03f15b2bcb30d3e09052d8ef6c6921a2905e6d97a218e90","title":"","text":"// resetFieldsStatusDefault conflicts with statusDefault const resetFieldsStatusDefault = `{\"status\": {\"conditions\": [{\"type\": \"MyStatus\", \"status\":\"False\"}]}}` var resetFieldsSkippedResources = map[string]struct{}{} var resetFieldsSkippedResources = map[string]struct{}{ // TODO: flowschemas is flaking, // possible bug in the flowschemas controller. \"flowschemas\": {}, } // noConflicts is the set of reources for which // a conflict cannot occur."} {"_id":"doc-en-kubernetes-5a384f75fb6688acf5da84b8e468cb007c3dd6978785eaa6e6f11852a64ef5d2","title":"","text":"} // Return the first match. backingFilePath := strings.TrimSpace(string(data)) backingFilePath := cleanBackingFilePath(string(data)) if backingFilePath == path || backingFilePath == realPath { return fmt.Sprintf(\"/dev/%s\", filepath.Base(device)), nil }"} {"_id":"doc-en-kubernetes-a2d3e44aaf10413e98038c48740da8d83a74bf78cfbd3bd6157c7262a5c5f4b1","title":"","text":"return \"\", errors.New(ErrDeviceNotFound) } // cleanPath remove any trailing substrings that are not part of the backing file path. func cleanBackingFilePath(path string) string { // If the block device was deleted, the path will contain a \"(deleted)\" suffix path = strings.TrimSpace(path) path = strings.TrimSuffix(path, \"(deleted)\") return strings.TrimSpace(path) } // FindGlobalMapPathUUIDFromPod finds {pod uuid} bind mount under globalMapPath // corresponding to map path symlink, and then return global map path with pod uuid. // (See pkg/volume/volume.go for details on a global map path and a pod device map path.)"} {"_id":"doc-en-kubernetes-aca08ed9bea023a2c91af6cf590db6380c1f2c419977c3d2cbce28029068ff54","title":"","text":" /* Copyright 2023 The Kubernetes Authors. 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. */ package volumepathhandler import ( \"fmt\" \"testing\" ) func pathWithSuffix(suffix string) string { return fmt.Sprintf(\"%s%s\", \"/var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/pvc-1d205234-06cd-4fe4-a7ea-0e8f3e2faf5f/dev/e196ebd3-2ab1-4185-bed4-b997ba38d1dc\", suffix) } func TestCleanBackingFilePath(t *testing.T) { const defaultPath = \"/var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/pvc-1d205234-06cd-4fe4-a7ea-0e8f3e2faf5f/dev/e196ebd3-2ab1-4185-bed4-b997ba38d1dc\" testCases := []struct { name string input string expectedOuput string }{ { name: \"regular path\", input: defaultPath, expectedOuput: defaultPath, }, { name: \"path is suffixed with whitespaces\", input: fmt.Sprintf(\"%srtn \", defaultPath), expectedOuput: defaultPath, }, { name: \"path is suffixed with \"(deleted)\"\", input: pathWithSuffix(\"(deleted)\"), expectedOuput: defaultPath, }, { name: \"path is suffixed with \"(deleted)\" and whitespaces\", input: pathWithSuffix(\" (deleted)t\"), expectedOuput: defaultPath, }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { output := cleanBackingFilePath(tc.input) if output != tc.expectedOuput { t.Fatalf(\"expected %q, got %q\", tc.expectedOuput, output) } }) } } "} {"_id":"doc-en-kubernetes-0a57c606ae41374bcd6b84f6e7251c970da3071c69edf77c8b9fd2547cb3024d","title":"","text":"var r result client := newClient(true) for i := 0; i < 5; i++ { r = doer.Do(client, func(httptrace.GotConnInfo) {}, fmt.Sprintf(\"/echo?message=attempt-%d\", i), 100*time.Millisecond) r = doer.Do(client, func(httptrace.GotConnInfo) {}, fmt.Sprintf(\"/echo?message=attempt-%d\", i), 1*time.Second) if r.err != nil { break }"} {"_id":"doc-en-kubernetes-a4b80a32faa18675391d61342fdf9d1922a61deec60b36411a8f5d2883ee7717","title":"","text":"} if err := vec.Validate(); err != nil { klog.Error(err) klog.ErrorS(err, \"the validation for HistogramVec is failed. The data for this metric won't be stored in a benchmark result file\", \"metric\", metric, \"labels\", labels) return nil } if vec.GetAggregatedSampleCount() == 0 { klog.InfoS(\"It is expected that this metric wasn't recorded. The data for this metric won't be stored in a benchmark result file\", \"metric\", metric, \"labels\", labels) return nil }"} {"_id":"doc-en-kubernetes-f7496202b32572aa3c8730825e294ae399b6c7ab22831426947c1b0ff7e31229","title":"","text":"} func (rc *resourceMetricsCollector) collectContainerStartTime(ch chan<- metrics.Metric, pod summary.PodStats, s summary.ContainerStats) { if s.StartTime.Unix() == 0 { if s.StartTime.Unix() <= 0 { return }"} {"_id":"doc-en-kubernetes-28f88a8d95ec9ab210cffb6511b240cde2cbe669b317ffd384f18aea933cd70c","title":"","text":"`, }, { name: \"arbitrary container metrics for negative StartTime\", summary: &statsapi.Summary{ Pods: []statsapi.PodStats{ { PodRef: statsapi.PodReference{ Name: \"pod_a\", Namespace: \"namespace_a\", }, Containers: []statsapi.ContainerStats{ { Name: \"container_a\", StartTime: metav1.NewTime(time.Unix(0, -1624396278302091597)), CPU: &statsapi.CPUStats{ Time: testTime, UsageCoreNanoSeconds: uint64Ptr(10000000000), }, Memory: &statsapi.MemoryStats{ Time: testTime, WorkingSetBytes: uint64Ptr(1000), }, }, }, }, }, }, summaryErr: nil, expectedMetrics: ` # HELP scrape_error [ALPHA] 1 if there was an error while getting container metrics, 0 otherwise # TYPE scrape_error gauge scrape_error 0 # HELP container_cpu_usage_seconds_total [ALPHA] Cumulative cpu time consumed by the container in core-seconds # TYPE container_cpu_usage_seconds_total counter container_cpu_usage_seconds_total{container=\"container_a\",namespace=\"namespace_a\",pod=\"pod_a\"} 10 1624396278302 # HELP container_memory_working_set_bytes [ALPHA] Current working set of the container in bytes # TYPE container_memory_working_set_bytes gauge container_memory_working_set_bytes{container=\"container_a\",namespace=\"namespace_a\",pod=\"pod_a\"} 1000 1624396278302 `, }, { name: \"nil container metrics\", summary: &statsapi.Summary{ Pods: []statsapi.PodStats{"} {"_id":"doc-en-kubernetes-19ed289b6e120634ff9fc0b9338b4fa5fcbf2af3d8db30cd270388697ee4057f","title":"","text":"} func NewResourceExpirationEvaluator(currentVersion apimachineryversion.Info) (ResourceExpirationEvaluator, error) { ret := &resourceExpirationEvaluator{ // TODO https://github.com/kubernetes/kubernetes/issues/109799 set this back to false after beta is tagged. strictRemovedHandlingInAlpha: true, } ret := &resourceExpirationEvaluator{} if len(currentVersion.Major) > 0 { currentMajor64, err := strconv.ParseInt(currentVersion.Major, 10, 32) if err != nil {"} {"_id":"doc-en-kubernetes-fde0b292044f25544d383f8a78ef481be9df6474a0b1d088fb5d9d239e6677df","title":"","text":"go k.ListenAndServe(kubeCfg, kubeDeps.TLSOptions, kubeDeps.Auth, kubeDeps.TracerProvider) } if kubeCfg.ReadOnlyPort > 0 { go k.ListenAndServeReadOnly(netutils.ParseIPSloppy(kubeCfg.Address), uint(kubeCfg.ReadOnlyPort)) go k.ListenAndServeReadOnly(netutils.ParseIPSloppy(kubeCfg.Address), uint(kubeCfg.ReadOnlyPort), kubeDeps.TracerProvider) } go k.ListenAndServePodResources() }"} {"_id":"doc-en-kubernetes-9097d13a29b17ce9129d49a16ef1eb133bc7ab86e3c293c76a1af5153e7f5c16","title":"","text":"BirthCry() StartGarbageCollection() ListenAndServe(kubeCfg *kubeletconfiginternal.KubeletConfiguration, tlsOptions *server.TLSOptions, auth server.AuthInterface, tp trace.TracerProvider) ListenAndServeReadOnly(address net.IP, port uint) ListenAndServeReadOnly(address net.IP, port uint, tp trace.TracerProvider) ListenAndServePodResources() Run(<-chan kubetypes.PodUpdate) RunOnce(<-chan kubetypes.PodUpdate) ([]RunPodResult, error)"} {"_id":"doc-en-kubernetes-8e7cfe67d592705e337a935a5036a26ba8587f27e0240c620f5c222808d54301","title":"","text":"} // ListenAndServeReadOnly runs the kubelet HTTP server in read-only mode. func (kl *Kubelet) ListenAndServeReadOnly(address net.IP, port uint) { server.ListenAndServeKubeletReadOnlyServer(kl, kl.resourceAnalyzer, address, port) func (kl *Kubelet) ListenAndServeReadOnly(address net.IP, port uint, tp trace.TracerProvider) { server.ListenAndServeKubeletReadOnlyServer(kl, kl.resourceAnalyzer, address, port, tp) } // ListenAndServePodResources runs the kubelet podresources grpc service"} {"_id":"doc-en-kubernetes-fc585f0d94ccd5b314f423cde8a32b9b697d145eecf216470760a54a4a48d3ee","title":"","text":"address := netutils.ParseIPSloppy(kubeCfg.Address) port := uint(kubeCfg.Port) klog.InfoS(\"Starting to listen\", \"address\", address, \"port\", port) handler := NewServer(host, resourceAnalyzer, auth, tp, kubeCfg) handler := NewServer(host, resourceAnalyzer, auth, kubeCfg) if utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) { handler.InstallTracingFilter(tp) } s := &http.Server{ Addr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)), Handler: &handler,"} {"_id":"doc-en-kubernetes-7668623fe8dc53686f244a7df3790ee6f1f0f0a1bb01a271656f9d4436e517e8","title":"","text":"host HostInterface, resourceAnalyzer stats.ResourceAnalyzer, address net.IP, port uint) { port uint, tp oteltrace.TracerProvider) { klog.InfoS(\"Starting to listen read-only\", \"address\", address, \"port\", port) // TODO: https://github.com/kubernetes/kubernetes/issues/109829 tracer should use WithPublicEndpoint s := NewServer(host, resourceAnalyzer, nil, oteltrace.NewNoopTracerProvider(), nil) s := NewServer(host, resourceAnalyzer, nil, nil) if utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) { s.InstallTracingFilter(tp, otelrestful.WithPublicEndpoint()) } server := &http.Server{ Addr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),"} {"_id":"doc-en-kubernetes-76131511a1d25d0fb57611360db2bd186f10c608eadb8dd6f337b2b9d8901202","title":"","text":"host HostInterface, resourceAnalyzer stats.ResourceAnalyzer, auth AuthInterface, tp oteltrace.TracerProvider, kubeCfg *kubeletconfiginternal.KubeletConfiguration) Server { server := Server{"} {"_id":"doc-en-kubernetes-2aa9de9c1cbcbca0ab89f8a14c2fdf91e04ca9f31de0d2e3eeb03737708d64fe","title":"","text":"if auth != nil { server.InstallAuthFilter() } if utilfeature.DefaultFeatureGate.Enabled(features.KubeletTracing) { server.InstallTracingFilter(tp) } server.InstallDefaultHandlers() if kubeCfg != nil && kubeCfg.EnableDebuggingHandlers { server.InstallDebuggingHandlers()"} {"_id":"doc-en-kubernetes-a415337524d606230393c53118ddfa25eb3a4a523ad3e51b493342dd0ee74f13","title":"","text":"} // InstallTracingFilter installs OpenTelemetry tracing filter with the restful Container. func (s *Server) InstallTracingFilter(tp oteltrace.TracerProvider) { s.restfulCont.Filter(otelrestful.OTelFilter(\"kubelet\", otelrestful.WithTracerProvider(tp))) func (s *Server) InstallTracingFilter(tp oteltrace.TracerProvider, opts ...otelrestful.Option) { s.restfulCont.Filter(otelrestful.OTelFilter(\"kubelet\", append(opts, otelrestful.WithTracerProvider(tp))...)) } // addMetricsBucketMatcher adds a regexp matcher and the relevant bucket to use when"} {"_id":"doc-en-kubernetes-de85329fcb42a675b536a49f578ae599281fc7c4861c52c3c499c150ffae2f2c","title":"","text":"cadvisorapiv2 \"github.com/google/cadvisor/info/v2\" \"github.com/stretchr/testify/assert\" \"github.com/stretchr/testify/require\" oteltrace \"go.opentelemetry.io/otel/trace\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\""} {"_id":"doc-en-kubernetes-b330c1d75a4f4d5a75decdf75cd8c106b86868f4b8212d81b489cf8fb956baa7","title":"","text":"fw.fakeKubelet, stats.NewResourceAnalyzer(fw.fakeKubelet, time.Minute, &record.FakeRecorder{}), fw.fakeAuth, oteltrace.NewNoopTracerProvider(), kubeCfg, ) fw.serverUnderTest = &server"} {"_id":"doc-en-kubernetes-bb82edda22877729cd4e138cc428a8713af38248262d1121f278e87c7941e10d","title":"","text":"\"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/uuid\" kubefeatures \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/test/e2e/framework\" e2enetwork \"k8s.io/kubernetes/test/e2e/framework/network\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" imageutils \"k8s.io/kubernetes/test/utils/image\" admissionapi \"k8s.io/pod-security-admission/api\""} {"_id":"doc-en-kubernetes-b860557d79921cd9518e3bf196daf2a6e3acc90b56694b730db1566a1095fcf8","title":"","text":"f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged ginkgo.Context(\"Downward API tests for hugepages\", func() { ginkgo.BeforeEach(func() { e2eskipper.SkipUnlessFeatureGateEnabled(kubefeatures.DownwardAPIHugePages) }) ginkgo.It(\"should provide container's limits.hugepages- and requests.hugepages- as env vars\", func() { podName := \"downward-api-\" + string(uuid.NewUUID()) env := []v1.EnvVar{"} {"_id":"doc-en-kubernetes-a91b086132829351055a4cd79fa2f1b2b14a942a2a85aa8fba5000fff7dbd7b0","title":"","text":"Done(types.UID) Update(logger klog.Logger, oldPod, newPod *v1.Pod) Delete(pod *v1.Pod) // TODO(sanposhiho): move all PreEnqueueCheck to Requeue and delete it from this parameter eventually. // Some PreEnqueueCheck include event filtering logic based on some in-tree plugins // and it affect badly to other plugins. // See https://github.com/kubernetes/kubernetes/issues/110175 // Important Note: preCheck shouldn't include anything that depends on the in-tree plugins' logic. // (e.g., filter Pods based on added/updated Node's capacity, etc.) // We know currently some do, but we'll eventually remove them in favor of the scheduling queue hint. MoveAllToActiveOrBackoffQueue(logger klog.Logger, event framework.ClusterEvent, oldObj, newObj interface{}, preCheck PreEnqueueCheck) AssignedPodAdded(logger klog.Logger, pod *v1.Pod) AssignedPodUpdated(logger klog.Logger, oldPod, newPod *v1.Pod, event framework.ClusterEvent)"} {"_id":"doc-en-kubernetes-b23e4f63b460f75730d9a0bb08d81f5911effae912bbf19754e8cf35deae6017","title":"","text":"} func preCheckForNode(nodeInfo *framework.NodeInfo) queue.PreEnqueueCheck { if utilfeature.DefaultFeatureGate.Enabled(features.SchedulerQueueingHints) { // QHint is initially created from the motivation of replacing this preCheck. // It assumes that the scheduler only has in-tree plugins, which is problematic for our extensibility. // Here, we skip preCheck if QHint is enabled, and we eventually remove it after QHint is graduated. return nil } // Note: the following checks doesn't take preemption into considerations, in very rare // cases (e.g., node resizing), \"pod\" may still fail a check but preemption helps. We deliberately // chose to ignore those cases as unschedulable pods will be re-queued eventually."} {"_id":"doc-en-kubernetes-ac18e852a80142a04019f9dd4c618f0a435be4f7302554390b1f84ada294af3c","title":"","text":"nodeFn func() *v1.Node existingPods, pods []*v1.Pod want []bool qHintEnabled bool }{ { name: \"regular node, pods with a single constraint\","} {"_id":"doc-en-kubernetes-97d1c77abdec17a13ce3a3960ae508e46f750dac730ae44bc10a710d26c7b904","title":"","text":"want: []bool{true, false, false, true, false, true, false, true, false}, }, { name: \"no filtering when QHint is enabled\", nodeFn: func() *v1.Node { return st.MakeNode().Name(\"fake-node\").Label(\"hostname\", \"fake-node\").Capacity(cpu8).Obj() }, existingPods: []*v1.Pod{ st.MakePod().Name(\"p\").HostPort(80).Obj(), }, pods: []*v1.Pod{ st.MakePod().Name(\"p1\").Req(cpu4).Obj(), st.MakePod().Name(\"p2\").Req(cpu16).Obj(), st.MakePod().Name(\"p3\").Req(cpu4).Req(cpu8).Obj(), st.MakePod().Name(\"p4\").NodeAffinityIn(\"hostname\", []string{\"fake-node\"}).Obj(), st.MakePod().Name(\"p5\").NodeAffinityNotIn(\"hostname\", []string{\"fake-node\"}).Obj(), st.MakePod().Name(\"p6\").Obj(), st.MakePod().Name(\"p7\").Node(\"invalid-node\").Obj(), st.MakePod().Name(\"p8\").HostPort(8080).Obj(), st.MakePod().Name(\"p9\").HostPort(80).Obj(), }, qHintEnabled: true, want: []bool{true, true, true, true, true, true, true, true, true}, }, { name: \"tainted node, pods with a single constraint\", nodeFn: func() *v1.Node { node := st.MakeNode().Name(\"fake-node\").Obj()"} {"_id":"doc-en-kubernetes-6e4166e531d9acf8b3dbeba61e4a8336326b0b3697ae614a9a5dc91a14b7c739","title":"","text":"for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.SchedulerQueueingHints, tt.qHintEnabled) nodeInfo := framework.NewNodeInfo(tt.existingPods...) nodeInfo.SetNode(tt.nodeFn()) preCheckFn := preCheckForNode(nodeInfo) var got []bool got := make([]bool, 0, len(tt.pods)) for _, pod := range tt.pods { got = append(got, preCheckFn(pod)) got = append(got, preCheckFn == nil || preCheckFn(pod)) } if diff := cmp.Diff(tt.want, got); diff != \"\" {"} {"_id":"doc-en-kubernetes-9fc8c94d523fa0f2df2500e89858fabf1cda227455e6658972894bde9f054f1a","title":"","text":"} // newPodInformer creates a shared index informer that returns only non-terminal pods. // The PodInformer allows indexers to be added, but note that only non-conflict indexers are allowed. func newPodInformer(cs clientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { selector := fmt.Sprintf(\"status.phase!=%v,status.phase!=%v\", v1.PodSucceeded, v1.PodFailed) tweakListOptions := func(options *metav1.ListOptions) { options.FieldSelector = selector } return coreinformers.NewFilteredPodInformer(cs, metav1.NamespaceAll, resyncPeriod, nil, tweakListOptions) return coreinformers.NewFilteredPodInformer(cs, metav1.NamespaceAll, resyncPeriod, cache.Indexers{}, tweakListOptions) }"} {"_id":"doc-en-kubernetes-bdbbdd10e97e87b20dcfe1ddd237b08ddd25d1ee1f3698dd1fd6e0bdb449907b","title":"","text":"v1 \"k8s.io/api/core/v1\" apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/client-go/informers\" \"k8s.io/client-go/kubernetes\""} {"_id":"doc-en-kubernetes-4463e9ea899e4f4e2005a32d2a4fb44e6972c886bc6596817c46e0d0300412b1","title":"","text":"return s, fwk, nil } func TestInitPluginsWithIndexers(t *testing.T) { tests := []struct { name string // the plugin registration ordering must not matter, being map traversal random entrypoints map[string]frameworkruntime.PluginFactory wantErr string }{ { name: \"register indexer, no conflicts\", entrypoints: map[string]frameworkruntime.PluginFactory{ \"AddIndexer\": func(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { podInformer := handle.SharedInformerFactory().Core().V1().Pods() err := podInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{ \"nodeName\": indexByPodSpecNodeName, }) return &TestPlugin{name: \"AddIndexer\"}, err }, }, }, { name: \"register the same indexer name multiple times, conflict\", // order of registration doesn't matter entrypoints: map[string]frameworkruntime.PluginFactory{ \"AddIndexer1\": func(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { podInformer := handle.SharedInformerFactory().Core().V1().Pods() err := podInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{ \"nodeName\": indexByPodSpecNodeName, }) return &TestPlugin{name: \"AddIndexer1\"}, err }, \"AddIndexer2\": func(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { podInformer := handle.SharedInformerFactory().Core().V1().Pods() err := podInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{ \"nodeName\": indexByPodAnnotationNodeName, }) return &TestPlugin{name: \"AddIndexer1\"}, err }, }, wantErr: \"indexer conflict\", }, { name: \"register the same indexer body with different names, no conflicts\", // order of registration doesn't matter entrypoints: map[string]frameworkruntime.PluginFactory{ \"AddIndexer1\": func(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { podInformer := handle.SharedInformerFactory().Core().V1().Pods() err := podInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{ \"nodeName1\": indexByPodSpecNodeName, }) return &TestPlugin{name: \"AddIndexer1\"}, err }, \"AddIndexer2\": func(obj runtime.Object, handle framework.Handle) (framework.Plugin, error) { podInformer := handle.SharedInformerFactory().Core().V1().Pods() err := podInformer.Informer().GetIndexer().AddIndexers(cache.Indexers{ \"nodeName2\": indexByPodAnnotationNodeName, }) return &TestPlugin{name: \"AddIndexer2\"}, err }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { fakeInformerFactory := NewInformerFactory(&fake.Clientset{}, 0*time.Second) var registerPluginFuncs []st.RegisterPluginFunc for name, entrypoint := range tt.entrypoints { registerPluginFuncs = append(registerPluginFuncs, // anything supported by TestPlugin is fine st.RegisterFilterPlugin(name, entrypoint), ) } // we always need this registerPluginFuncs = append(registerPluginFuncs, st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New), st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New), ) _, err := st.NewFramework(registerPluginFuncs, \"test\", frameworkruntime.WithInformerFactory(fakeInformerFactory)) if len(tt.wantErr) > 0 { if err == nil || !strings.Contains(err.Error(), tt.wantErr) { t.Errorf(\"got error %q, want %q\", err, tt.wantErr) } return } if err != nil { t.Fatalf(\"Failed to create scheduler: %v\", err) } }) } } func indexByPodSpecNodeName(obj interface{}) ([]string, error) { pod, ok := obj.(*v1.Pod) if !ok { return []string{}, nil } if len(pod.Spec.NodeName) == 0 { return []string{}, nil } return []string{pod.Spec.NodeName}, nil } func indexByPodAnnotationNodeName(obj interface{}) ([]string, error) { pod, ok := obj.(*v1.Pod) if !ok { return []string{}, nil } if len(pod.Annotations) == 0 { return []string{}, nil } nodeName, ok := pod.Annotations[\"node-name\"] if !ok { return []string{}, nil } return []string{nodeName}, nil } "} {"_id":"doc-en-kubernetes-458bdafef1e799654ae79e55da583424af1013a631605333fa234de9857f650e","title":"","text":"visible at runtime in the container. release: v1.9 file: test/e2e/common/node/downwardapi.go - testname: Ephemeral Container Creation codename: '[sig-node] Ephemeral Containers [NodeConformance] will start an ephemeral container in an existing pod [Conformance]' description: Adding an ephemeral container to pod.spec MUST result in the container running. release: \"1.25\" file: test/e2e/common/node/ephemeral_containers.go - testname: init-container-starts-app-restartalways-pod codename: '[sig-node] InitContainer [NodeConformance] should invoke init containers on a RestartAlways pod [Conformance]'"} {"_id":"doc-en-kubernetes-562c6a94d7977f71b946337fa610aef1e6105a9e7b798a01f72200a793c15af9","title":"","text":"podClient = f.PodClient() }) ginkgo.It(\"will start an ephemeral container in an existing pod\", func() { // Release: 1.25 // Testname: Ephemeral Container Creation // Description: Adding an ephemeral container to pod.spec MUST result in the container running. framework.ConformanceIt(\"will start an ephemeral container in an existing pod\", func() { ginkgo.By(\"creating a target pod\") pod := podClient.CreateSync(&v1.Pod{ ObjectMeta: metav1.ObjectMeta{Name: \"ephemeral-containers-target-pod\"},"} {"_id":"doc-en-kubernetes-e997c374c131282d54fb40d4bbddebe12ac987a55a471eeef97040498c0c956a","title":"","text":"\"k8s.io/client-go/openapi\" cachedopenapi \"k8s.io/client-go/openapi/cached\" restclient \"k8s.io/client-go/rest\" \"k8s.io/klog/v2\" ) type cacheEntry struct {"} {"_id":"doc-en-kubernetes-a477b233f23ec9ea00ede72c3e90733905dbae90342f1abead4d541c3228c710","title":"","text":"ErrCacheNotFound = errors.New(\"not found\") ) // Server returning empty ResourceList for Group/Version. type emptyResponseError struct { gv string } func (e *emptyResponseError) Error() string { return fmt.Sprintf(\"received empty response for: %s\", e.gv) } var _ discovery.CachedDiscoveryInterface = &memCacheClient{} // isTransientConnectionError checks whether given error is \"Connection refused\" or"} {"_id":"doc-en-kubernetes-f6d23ead00fe7bca8d31f0bf0f233c08a10fe722e067054a44751db7ead28d80","title":"","text":"if cachedVal.err != nil && isTransientError(cachedVal.err) { r, err := d.serverResourcesForGroupVersion(groupVersion) if err != nil { utilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", groupVersion, err)) // Don't log \"empty response\" as an error; it is a common response for metrics. if _, emptyErr := err.(*emptyResponseError); emptyErr { // Log at same verbosity as disk cache. klog.V(3).Infof(\"%v\", err) } else { utilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", groupVersion, err)) } } cachedVal = &cacheEntry{r, err} d.groupToServerResources[groupVersion] = cachedVal"} {"_id":"doc-en-kubernetes-b1efd33e903142dadbd1e3d06f05720fce300edfb748675ecb31464e56d162d9","title":"","text":"r, err := d.serverResourcesForGroupVersion(gv) if err != nil { utilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", gv, err)) // Don't log \"empty response\" as an error; it is a common response for metrics. if _, emptyErr := err.(*emptyResponseError); emptyErr { // Log at same verbosity as disk cache. klog.V(3).Infof(\"%v\", err) } else { utilruntime.HandleError(fmt.Errorf(\"couldn't get resource list for %v: %v\", gv, err)) } } resultLock.Lock()"} {"_id":"doc-en-kubernetes-3ea2a80d5b22480f69c26bf4386dceadb9e61073f73c1984db23d69b005e7002","title":"","text":"return r, err } if len(r.APIResources) == 0 { return r, fmt.Errorf(\"Got empty response for: %v\", groupVersion) return r, &emptyResponseError{gv: groupVersion} } return r, nil }"} {"_id":"doc-en-kubernetes-1213c0510029a82a931f29e7f413d4fffd7918a900dbc6b3dd18a793d42b6bbb","title":"","text":"return finalURL } // finalURLTemplate is similar to URL(), but will make all specific parameter values equal // - instead of name or namespace, \"{name}\" and \"{namespace}\" will be used, and all query // parameters will be reset. This creates a copy of the url so as not to change the // underlying object. func (r Request) finalURLTemplate() url.URL { newParams := url.Values{} v := []string{\"{value}\"} for k := range r.params { newParams[k] = v } r.params = newParams u := r.URL() if u == nil { return url.URL{} } segments := strings.Split(u.Path, \"/\") groupIndex := 0 index := 0 trimmedBasePath := \"\" if r.c.base != nil && strings.Contains(u.Path, r.c.base.Path) { p := strings.TrimPrefix(u.Path, r.c.base.Path) if !strings.HasPrefix(p, \"/\") { p = \"/\" + p } // store the base path that we have trimmed so we can append it // before returning the URL trimmedBasePath = r.c.base.Path segments = strings.Split(p, \"/\") groupIndex = 1 } if len(segments) <= 2 { return *u } const CoreGroupPrefix = \"api\" const NamedGroupPrefix = \"apis\" isCoreGroup := segments[groupIndex] == CoreGroupPrefix isNamedGroup := segments[groupIndex] == NamedGroupPrefix if isCoreGroup { // checking the case of core group with /api/v1/... format index = groupIndex + 2 } else if isNamedGroup { // checking the case of named group with /apis/apps/v1/... format index = groupIndex + 3 } else { // this should not happen that the only two possibilities are /api... and /apis..., just want to put an // outlet here in case more API groups are added in future if ever possible: // https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups // if a wrong API groups name is encountered, return the {prefix} for url.Path u.Path = \"/{prefix}\" u.RawQuery = \"\" return *u } // switch segLength := len(segments) - index; segLength { switch { // case len(segments) - index == 1: // resource (with no name) do nothing case len(segments)-index == 2: // /$RESOURCE/$NAME: replace $NAME with {name} segments[index+1] = \"{name}\" case len(segments)-index == 3: if segments[index+2] == \"finalize\" || segments[index+2] == \"status\" { // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name} segments[index+1] = \"{name}\" } else { // /namespace/$NAMESPACE/$RESOURCE: replace $NAMESPACE with {namespace} segments[index+1] = \"{namespace}\" } case len(segments)-index >= 4: segments[index+1] = \"{namespace}\" // /namespace/$NAMESPACE/$RESOURCE/$NAME: replace $NAMESPACE with {namespace}, $NAME with {name} if segments[index+3] != \"finalize\" && segments[index+3] != \"status\" { // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name} segments[index+3] = \"{name}\" } } u.Path = path.Join(trimmedBasePath, path.Join(segments...)) return *u } func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) error { if r.rateLimiter == nil { return nil"} {"_id":"doc-en-kubernetes-c3b8a5e10f3c5d11da03b09da55f4691de1beab3266226636784cdcab9428c4a","title":"","text":"// but we use a throttled logger to prevent spamming. globalThrottledLogger.Infof(\"%s\", message) } metrics.RateLimiterLatency.Observe(ctx, r.verb, *r.URL(), latency) metrics.RateLimiterLatency.Observe(ctx, r.verb, r.finalURLTemplate(), latency) return err }"} {"_id":"doc-en-kubernetes-91fddabd675811e95ce1fb6e9c3e6d9c0b5683638cd15a79d0231fe6e41e5226","title":"","text":"// Metrics for total request latency start := time.Now() defer func() { metrics.RequestLatency.Observe(ctx, r.verb, *r.URL(), time.Since(start)) metrics.RequestLatency.Observe(ctx, r.verb, r.finalURLTemplate(), time.Since(start)) }() if r.err != nil {"} {"_id":"doc-en-kubernetes-e3694f28351eb5ebaf8d48209d0cbb80241c7844343a198fb59ca1c91496db84","title":"","text":"} } func TestURLTemplate(t *testing.T) { uri, _ := url.Parse(\"http://localhost/some/base/url/path\") uriSingleSlash, _ := url.Parse(\"http://localhost/\") testCases := []struct { Request *Request ExpectedFullURL string ExpectedFinalURL string }{ { // non dynamic client Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"POST\"). Prefix(\"api\", \"v1\").Resource(\"r1\").Namespace(\"ns\").Name(\"nm\").Param(\"p0\", \"v0\"), ExpectedFullURL: \"http://localhost/some/base/url/path/api/v1/namespaces/ns/r1/nm?p0=v0\", ExpectedFinalURL: \"http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D?p0=%7Bvalue%7D\", }, { // non dynamic client with wrong api group Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"POST\"). Prefix(\"pre1\", \"v1\").Resource(\"r1\").Namespace(\"ns\").Name(\"nm\").Param(\"p0\", \"v0\"), ExpectedFullURL: \"http://localhost/some/base/url/path/pre1/v1/namespaces/ns/r1/nm?p0=v0\", ExpectedFinalURL: \"http://localhost/%7Bprefix%7D\", }, { // dynamic client with core group + namespace + resourceResource (with name) // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/api/v1/namespaces/ns/r1/name1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/api/v1/namespaces/ns/r1/name1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D\", }, { // dynamic client with named group + namespace + resourceResource (with name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/g1/v1/namespaces/ns/r1/name1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/g1/v1/namespaces/ns/r1/name1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/g1/v1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D\", }, { // dynamic client with core group + namespace + resourceResource (with NO name) // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/api/v1/namespaces/ns/r1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/api/v1/namespaces/ns/r1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r1\", }, { // dynamic client with named group + namespace + resourceResource (with NO name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/g1/v1/namespaces/ns/r1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/g1/v1/namespaces/ns/r1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/g1/v1/namespaces/%7Bnamespace%7D/r1\", }, { // dynamic client with core group + resourceResource (with name) // /api/$RESOURCEVERSION/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/api/v1/r1/name1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/api/v1/r1/name1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/api/v1/r1/%7Bname%7D\", }, { // dynamic client with named group + resourceResource (with name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/g1/v1/r1/name1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/g1/v1/r1/name1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/g1/v1/r1/%7Bname%7D\", }, { // dynamic client with named group + namespace + resourceResource (with name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME/$SUBRESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/%7Bname%7D/finalize\", }, { // dynamic client with named group + namespace + resourceResource (with name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/%7Bname%7D\", }, { // dynamic client with named group + namespace + resourceResource (with NO name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%SUBRESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/finalize\", }, { // dynamic client with named group + namespace + resourceResource (with NO name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%SUBRESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/namespaces/status\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces/status\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces/status\", }, { // dynamic client with named group + namespace + resourceResource (with no name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/namespaces\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/namespaces\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bnamespace%7D/namespaces\", }, { // dynamic client with named group + resourceResource (with name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/finalize\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/finalize\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D/finalize\", }, { // dynamic client with named group + resourceResource (with name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces/status\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces/status\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D/status\", }, { // dynamic client with named group + resourceResource (with name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces/namespaces\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/namespaces\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces/%7Bname%7D\", }, { // dynamic client with named group + resourceResource (with no name) // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/apis/namespaces/namespaces/namespaces\"), ExpectedFullURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces\", ExpectedFinalURL: \"http://localhost/some/base/url/path/apis/namespaces/namespaces/namespaces\", }, { // dynamic client with wrong api group + namespace + resourceResource (with name) + subresource // /apis/$NAMEDGROUPNAME/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME/$SUBRESOURCE Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/pre1/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\"), ExpectedFullURL: \"http://localhost/some/base/url/path/pre1/namespaces/namespaces/namespaces/namespaces/namespaces/namespaces/finalize\", ExpectedFinalURL: \"http://localhost/%7Bprefix%7D\", }, { // dynamic client with core group + namespace + resourceResource (with name) where baseURL is a single / // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uriSingleSlash, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/api/v1/namespaces/ns/r2/name1\"), ExpectedFullURL: \"http://localhost/api/v1/namespaces/ns/r2/name1\", ExpectedFinalURL: \"http://localhost/api/v1/namespaces/%7Bnamespace%7D/r2/%7Bname%7D\", }, { // dynamic client with core group + namespace + resourceResource (with name) where baseURL is 'some/base/url/path' // /api/$RESOURCEVERSION/namespaces/$NAMESPACE/$RESOURCE/%NAME Request: NewRequestWithClient(uri, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/api/v1/namespaces/ns/r3/name1\"), ExpectedFullURL: \"http://localhost/some/base/url/path/api/v1/namespaces/ns/r3/name1\", ExpectedFinalURL: \"http://localhost/some/base/url/path/api/v1/namespaces/%7Bnamespace%7D/r3/%7Bname%7D\", }, { // dynamic client where baseURL is a single / // / Request: NewRequestWithClient(uriSingleSlash, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/\"), ExpectedFullURL: \"http://localhost/\", ExpectedFinalURL: \"http://localhost/\", }, { // dynamic client where baseURL is a single / // /version Request: NewRequestWithClient(uriSingleSlash, \"\", ClientContentConfig{GroupVersion: schema.GroupVersion{Group: \"test\"}}, nil).Verb(\"DELETE\"). Prefix(\"/version\"), ExpectedFullURL: \"http://localhost/version\", ExpectedFinalURL: \"http://localhost/version\", }, } for i, testCase := range testCases { r := testCase.Request full := r.URL() if full.String() != testCase.ExpectedFullURL { t.Errorf(\"%d: unexpected initial URL: %s %s\", i, full, testCase.ExpectedFullURL) } actualURL := r.finalURLTemplate() actual := actualURL.String() if actual != testCase.ExpectedFinalURL { t.Errorf(\"%d: unexpected URL template: %s %s\", i, actual, testCase.ExpectedFinalURL) } if r.URL().String() != full.String() { t.Errorf(\"%d, creating URL template changed request: %s -> %s\", i, full.String(), r.URL().String()) } } } func TestTransformResponse(t *testing.T) { invalid := []byte(\"aaaaa\") uri, _ := url.Parse(\"http://localhost\")"} {"_id":"doc-en-kubernetes-8dc90655f13da676740b15d73678de96de70d03fd04665dce2cfc103adca03c2","title":"","text":"\"k8s.io/apiserver/pkg/storage/value\" kmstypes \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/v2alpha1\" \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics\" \"k8s.io/klog/v2\" \"k8s.io/utils/lru\" )"} {"_id":"doc-en-kubernetes-c8575a0e2b7a9cd04492909f47452a90be4c02553886a873972a5fdb6973858c","title":"","text":"value.RecordCacheMiss() } uid := string(uuid.NewUUID()) klog.V(6).InfoS(\"Decrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData())) key, err := t.envelopeService.Decrypt(ctx, uid, &DecryptRequest{ Ciphertext: encryptedObject.EncryptedDEK, KeyID: encryptedObject.KeyID,"} {"_id":"doc-en-kubernetes-57029b3658101c63dea4174a15acbe67b928c77cc0519db7ea2273e334ad3340","title":"","text":"} uid := string(uuid.NewUUID()) klog.V(6).InfoS(\"Encrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData())) resp, err := t.envelopeService.Encrypt(ctx, uid, newKey) if err != nil { return nil, fmt.Errorf(\"failed to encrypt DEK, error: %w\", err)"} {"_id":"doc-en-kubernetes-677b3228219f4cb8bd179e0dbe7c6749963e73f22502c1ec1840ae5900983fdf","title":"","text":"\"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/validation\" \"k8s.io/apimachinery/pkg/util/validation/field\" genericapirequest \"k8s.io/apiserver/pkg/endpoints/request\" \"k8s.io/apiserver/pkg/storage/value\" kmstypes \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/v2alpha1\" \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics\""} {"_id":"doc-en-kubernetes-e82b081b5500c00743625c21720766b53c0d1773a698103ecafab9c40d73f9c0","title":"","text":"if transformer == nil { value.RecordCacheMiss() requestInfo := getRequestInfoFromContext(ctx) uid := string(uuid.NewUUID()) klog.V(6).InfoS(\"Decrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData())) klog.V(6).InfoS(\"decrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData()), \"group\", requestInfo.APIGroup, \"version\", requestInfo.APIVersion, \"resource\", requestInfo.Resource, \"subresource\", requestInfo.Subresource, \"verb\", requestInfo.Verb, \"namespace\", requestInfo.Namespace, \"name\", requestInfo.Name) key, err := t.envelopeService.Decrypt(ctx, uid, &kmsservice.DecryptRequest{ Ciphertext: encryptedObject.EncryptedDEK, KeyID: encryptedObject.KeyID,"} {"_id":"doc-en-kubernetes-07fafa69a165b05849bb3b0212cbb934b5244d0b305be93eddeccc87c59f6e8f","title":"","text":"return nil, err } requestInfo := getRequestInfoFromContext(ctx) uid := string(uuid.NewUUID()) klog.V(6).InfoS(\"encrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData())) klog.V(6).InfoS(\"encrypting content using envelope service\", \"uid\", uid, \"key\", string(dataCtx.AuthenticatedData()), \"group\", requestInfo.APIGroup, \"version\", requestInfo.APIVersion, \"resource\", requestInfo.Resource, \"subresource\", requestInfo.Subresource, \"verb\", requestInfo.Verb, \"namespace\", requestInfo.Namespace, \"name\", requestInfo.Name) resp, err := t.envelopeService.Encrypt(ctx, uid, newKey) if err != nil { return nil, fmt.Errorf(\"failed to encrypt DEK, error: %w\", err)"} {"_id":"doc-en-kubernetes-13c66730f389ea0ff4b350226d93c6e729309da2993ac2dea3ed6869f46b7c6d","title":"","text":"} return errKeyIDOKCode, nil } func getRequestInfoFromContext(ctx context.Context) *genericapirequest.RequestInfo { if reqInfo, found := genericapirequest.RequestInfoFrom(ctx); found { return reqInfo } return &genericapirequest.RequestInfo{} } "} {"_id":"doc-en-kubernetes-f846a076c0c33f512c48c1a1a806ebada2a7444cc7d461c1d32819b363c0b6ad","title":"","text":"\"bytes\" \"context\" \"encoding/base64\" \"flag\" \"fmt\" \"reflect\" \"regexp\" \"strconv\" \"strings\" \"testing\" \"time\" genericapirequest \"k8s.io/apiserver/pkg/endpoints/request\" \"k8s.io/apiserver/pkg/storage/value\" aestransformer \"k8s.io/apiserver/pkg/storage/value/encrypt/aes\" kmstypes \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/v2alpha1\" \"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/component-base/metrics/testutil\" \"k8s.io/klog/v2\" kmsservice \"k8s.io/kms/pkg/service\" testingclock \"k8s.io/utils/clock/testing\" )"} {"_id":"doc-en-kubernetes-0dac91fd18c728f8367e81b16a9662854f7c5080cf4f6b4e0b6a8099a238a507","title":"","text":"}) } } func TestEnvelopeLogging(t *testing.T) { klog.InitFlags(nil) flag.Set(\"v\", \"6\") flag.Parse() testCases := []struct { desc string ctx context.Context wantLogs []string }{ { desc: \"no request info in context\", ctx: testContext(t), wantLogs: []string{ `\"encrypting content using envelope service\" uid=\"UID\" key=\"0123456789\" group=\"\" version=\"\" resource=\"\" subresource=\"\" verb=\"\" namespace=\"\" name=\"\"`, `\"decrypting content using envelope service\" uid=\"UID\" key=\"0123456789\" group=\"\" version=\"\" resource=\"\" subresource=\"\" verb=\"\" namespace=\"\" name=\"\"`, }, }, { desc: \"request info in context\", ctx: genericapirequest.WithRequestInfo(testContext(t), &genericapirequest.RequestInfo{ APIGroup: \"awesome.bears.com\", APIVersion: \"v1\", Resource: \"pandas\", Subresource: \"status\", Namespace: \"kube-system\", Name: \"panda\", Verb: \"update\", }), wantLogs: []string{ `\"encrypting content using envelope service\" uid=\"UID\" key=\"0123456789\" group=\"awesome.bears.com\" version=\"v1\" resource=\"pandas\" subresource=\"status\" verb=\"update\" namespace=\"kube-system\" name=\"panda\"`, `\"decrypting content using envelope service\" uid=\"UID\" key=\"0123456789\" group=\"awesome.bears.com\" version=\"v1\" resource=\"pandas\" subresource=\"status\" verb=\"update\" namespace=\"kube-system\" name=\"panda\"`, }, }, } for _, tc := range testCases { tc := tc t.Run(tc.desc, func(t *testing.T) { var buf bytes.Buffer klog.SetOutput(&buf) klog.LogToStderr(false) defer klog.LogToStderr(true) envelopeService := newTestEnvelopeService() fakeClock := testingclock.NewFakeClock(time.Now()) envelopeTransformer := newEnvelopeTransformerWithClock(envelopeService, testProviderName, func(ctx context.Context) (string, error) { return \"1\", nil }, func(ctx context.Context) error { return nil }, aestransformer.NewGCMTransformer, 1*time.Second, fakeClock) dataCtx := value.DefaultContext([]byte(testContextText)) originalText := []byte(testText) transformedData, err := envelopeTransformer.TransformToStorage(tc.ctx, originalText, dataCtx) if err != nil { t.Fatalf(\"envelopeTransformer: error while transforming data to storage: %v\", err) } // advance the clock to trigger cache to expire, so we make a decrypt call that will log fakeClock.Step(2 * time.Second) _, _, err = envelopeTransformer.TransformFromStorage(tc.ctx, transformedData, dataCtx) if err != nil { t.Fatalf(\"could not decrypt Envelope transformer's encrypted data even once: %v\", err) } klog.Flush() klog.SetOutput(&bytes.Buffer{}) // prevent further writes into buf capturedOutput := buf.String() // replace the uid with a constant to make the test output stable and assertable capturedOutput = regexp.MustCompile(`uid=\"[^\"]+\"`).ReplaceAllString(capturedOutput, `uid=\"UID\"`) for _, wantLog := range tc.wantLogs { if !strings.Contains(capturedOutput, wantLog) { t.Errorf(\"expected log %q, got %q\", wantLog, capturedOutput) } } }) } } "} {"_id":"doc-en-kubernetes-bcddab6f3d40826d34c09b3d195b5f4132894e4ba6b55d86347ebfb4656823e2","title":"","text":"import ( \"context\" \"encoding/json\" \"fmt\" \"reflect\" \"strconv\" \"time\" v1 \"k8s.io/api/core/v1\" apiequality \"k8s.io/apimachinery/pkg/api/equality\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/types\" utilrand \"k8s.io/apimachinery/pkg/util/rand\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/apimachinery/pkg/watch\""} {"_id":"doc-en-kubernetes-11aedc2c7bda63dcb4ded66311ce19574fa50714af9066ec2abf46e72011c46d","title":"","text":"framework.ExpectNoError(err) }) ginkgo.It(\"should list, patch and delete a LimitRange by collection\", func() { ns := f.Namespace.Name lrClient := f.ClientSet.CoreV1().LimitRanges(ns) lrName := \"e2e-limitrange-\" + utilrand.String(5) e2eLabelSelector := \"e2e-test=\" + lrName patchedLabelSelector := lrName + \"=patched\" min := getResourceList(\"50m\", \"100Mi\", \"100Gi\") max := getResourceList(\"500m\", \"500Mi\", \"500Gi\") defaultLimit := getResourceList(\"500m\", \"500Mi\", \"500Gi\") defaultRequest := getResourceList(\"100m\", \"200Mi\", \"200Gi\") maxLimitRequestRatio := v1.ResourceList{} limitRange := &v1.LimitRange{ ObjectMeta: metav1.ObjectMeta{ Name: lrName, Labels: map[string]string{ \"e2e-test\": lrName, lrName: \"created\", }, }, Spec: v1.LimitRangeSpec{ Limits: []v1.LimitRangeItem{ { Type: v1.LimitTypeContainer, Min: min, Max: max, Default: defaultLimit, DefaultRequest: defaultRequest, MaxLimitRequestRatio: maxLimitRequestRatio, }, }, }, } // Create a copy to be used in a second namespace limitRange2 := &v1.LimitRange{} *limitRange2 = *limitRange ctx, cancelCtx := context.WithTimeout(context.Background(), wait.ForeverTestTimeout) defer cancelCtx() ginkgo.By(fmt.Sprintf(\"Creating LimitRange %q in namespace %q\", lrName, f.Namespace.Name)) limitRange, err := lrClient.Create(ctx, limitRange, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Failed to create limitRange %q\", lrName) ginkgo.By(\"Creating another limitRange in another namespace\") lrNamespace, err := f.CreateNamespace(lrName, nil) framework.ExpectNoError(err, \"failed creating Namespace\") framework.Logf(\"Namespace %q created\", lrNamespace.ObjectMeta.Name) framework.Logf(fmt.Sprintf(\"Creating LimitRange %q in namespace %q\", lrName, lrNamespace.Name)) _, err = f.ClientSet.CoreV1().LimitRanges(lrNamespace.ObjectMeta.Name).Create(ctx, limitRange2, metav1.CreateOptions{}) framework.ExpectNoError(err, \"Failed to create limitRange %q in %q namespace\", lrName, lrNamespace.ObjectMeta.Name) // Listing across all namespaces to verify api endpoint: listCoreV1LimitRangeForAllNamespaces ginkgo.By(fmt.Sprintf(\"Listing all LimitRanges with label %q\", e2eLabelSelector)) limitRangeList, err := f.ClientSet.CoreV1().LimitRanges(\"\").List(ctx, metav1.ListOptions{LabelSelector: e2eLabelSelector}) framework.ExpectNoError(err, \"Failed to list any limitRanges: %v\", err) framework.ExpectEqual(len(limitRangeList.Items), 2, \"Failed to find the correct limitRange count\") framework.Logf(\"Found %d limitRanges\", len(limitRangeList.Items)) ginkgo.By(fmt.Sprintf(\"Patching LimitRange %q in %q namespace\", lrName, ns)) newMin := getResourceList(\"9m\", \"49Mi\", \"49Gi\") limitRange.Spec.Limits[0].Min = newMin limitRangePayload, err := json.Marshal(v1.LimitRange{ ObjectMeta: metav1.ObjectMeta{ CreationTimestamp: limitRange.CreationTimestamp, Labels: map[string]string{ lrName: \"patched\", }, }, Spec: v1.LimitRangeSpec{ Limits: limitRange.Spec.Limits, }, }) framework.ExpectNoError(err, \"Failed to marshal limitRange JSON\") patchedLimitRange, err := lrClient.Patch(ctx, lrName, types.StrategicMergePatchType, []byte(limitRangePayload), metav1.PatchOptions{}) framework.ExpectNoError(err, \"Failed to patch limitRange %q\", lrName) framework.ExpectEqual(patchedLimitRange.Labels[lrName], \"patched\", \"%q label didn't have value 'patched' for this limitRange. Current labels: %v\", lrName, patchedLimitRange.Labels) checkMinLimitRange := apiequality.Semantic.DeepEqual(patchedLimitRange.Spec.Limits[0].Min, newMin) framework.ExpectEqual(checkMinLimitRange, true, \"LimitRange does not have the correct min limitRange. Currently is %#v \", patchedLimitRange.Spec.Limits[0].Min) framework.Logf(\"LimitRange %q has been patched\", lrName) ginkgo.By(fmt.Sprintf(\"Delete LimitRange %q by Collection with labelSelector: %q\", lrName, patchedLabelSelector)) err = lrClient.DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: patchedLabelSelector}) framework.ExpectNoError(err, \"failed to delete the LimitRange by Collection\") ginkgo.By(fmt.Sprintf(\"Confirm that the limitRange %q has been deleted\", lrName)) err = wait.PollImmediate(1*time.Second, 10*time.Second, checkLimitRangeListQuantity(f, patchedLabelSelector, 0)) framework.ExpectNoError(err, \"failed to count the required limitRanges\") framework.Logf(\"LimitRange %q has been deleted.\", lrName) ginkgo.By(fmt.Sprintf(\"Confirm that a single LimitRange still exists with label %q\", e2eLabelSelector)) limitRangeList, err = f.ClientSet.CoreV1().LimitRanges(\"\").List(ctx, metav1.ListOptions{LabelSelector: e2eLabelSelector}) framework.ExpectNoError(err, \"Failed to list any limitRanges: %v\", err) framework.ExpectEqual(len(limitRangeList.Items), 1, \"Failed to find the correct limitRange count\") framework.Logf(\"Found %d limitRange\", len(limitRangeList.Items)) }) }) func equalResourceRequirement(expected v1.ResourceRequirements, actual v1.ResourceRequirements) error {"} {"_id":"doc-en-kubernetes-4815dc450f34db07dda96460f182f07755fa48efcdff116245a5b0c44bf8f7e0","title":"","text":"}, } } func checkLimitRangeListQuantity(f *framework.Framework, label string, quantity int) func() (bool, error) { return func() (bool, error) { framework.Logf(\"Requesting list of LimitRange to confirm quantity\") list, err := f.ClientSet.CoreV1().LimitRanges(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{LabelSelector: label}) if err != nil { return false, err } if len(list.Items) != quantity { return false, nil } framework.Logf(\"Found %d LimitRange with label %q\", quantity, label) return true, nil } } "} {"_id":"doc-en-kubernetes-e117de801d37811f5803feb0ae5d3fa917ba89ed0a84e4697298d5826f46c568","title":"","text":"validate the pod resources are applied to the Limitrange release: v1.18 file: test/e2e/scheduling/limit_range.go - testname: LimitRange, list, patch and delete a LimitRange by collection codename: '[sig-scheduling] LimitRange should list, patch and delete a LimitRange by collection [Conformance]' description: When two limitRanges are created in different namespaces, both MUST succeed. Listing limitRanges across all namespaces with a labelSelector MUST find both limitRanges. When patching the first limitRange it MUST succeed and the fields MUST equal the new values. When deleting the limitRange by collection with a labelSelector it MUST delete only one limitRange. release: v1.26 file: test/e2e/scheduling/limit_range.go - testname: Scheduler, resource limits codename: '[sig-scheduling] SchedulerPredicates [Serial] validates resource limits of pods that are allowed to run [Conformance]'"} {"_id":"doc-en-kubernetes-b62da7a828b5668cba64ce6304b0e7a921f296bb180ef805f2d4008f8da9a366","title":"","text":"framework.ExpectNoError(err) }) ginkgo.It(\"should list, patch and delete a LimitRange by collection\", func() { /* Release: v1.26 Testname: LimitRange, list, patch and delete a LimitRange by collection Description: When two limitRanges are created in different namespaces, both MUST succeed. Listing limitRanges across all namespaces with a labelSelector MUST find both limitRanges. When patching the first limitRange it MUST succeed and the fields MUST equal the new values. When deleting the limitRange by collection with a labelSelector it MUST delete only one limitRange. */ framework.ConformanceIt(\"should list, patch and delete a LimitRange by collection\", func() { ns := f.Namespace.Name lrClient := f.ClientSet.CoreV1().LimitRanges(ns)"} {"_id":"doc-en-kubernetes-8f11fbe91fcc9e6c9655ad66308de8ae050820f484175e463906dfc40ef087ab","title":"","text":"if _, err := dc.coreClient.CoreV1().Pods(tc.pod.Namespace).Create(ctx, tc.pod, metav1.CreateOptions{}); err != nil { t.Fatalf(\"Failed to create pod: %v\", err) } dc.clock.Sleep(tc.timePassed) if err := dc.informerFactory.Core().V1().Pods().Informer().GetIndexer().Add(tc.pod); err != nil { t.Fatalf(\"Failed adding pod to indexer: %v\", err) } dc.clock.Sleep(tc.timePassed) diff := \"\" if err := wait.Poll(100*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) { return dc.stalePodDisruptionQueue.Len() == 0, nil pod, err := dc.kubeClient.CoreV1().Pods(tc.pod.Namespace).Get(ctx, tc.pod.Name, metav1.GetOptions{}) if err != nil { t.Fatalf(\"Failed getting updated pod: %v\", err) } diff = cmp.Diff(tc.wantConditions, pod.Status.Conditions, cmpopts.IgnoreFields(v1.PodCondition{}, \"LastTransitionTime\")) return diff == \"\", nil }); err != nil { t.Fatalf(\"Failed waiting for worker to sync: %v\", err) } pod, err := dc.kubeClient.CoreV1().Pods(tc.pod.Namespace).Get(ctx, tc.pod.Name, metav1.GetOptions{}) if err != nil { t.Fatalf(\"Failed getting updated pod: %v\", err) } diff := cmp.Diff(tc.wantConditions, pod.Status.Conditions, cmpopts.IgnoreFields(v1.PodCondition{}, \"LastTransitionTime\")) if diff != \"\" { t.Errorf(\"Obtained pod conditions (-want,+got):n%s\", diff) t.Fatalf(\"Failed waiting for worker to sync: %v, (-want,+got):n%s\", err, diff) } }) }"} {"_id":"doc-en-kubernetes-f40d15098ee96a5085d648785a6f0b11cbaa05092863f200b382301473fc76c6","title":"","text":"} else { klog.V(3).InfoS(\"Skipped creating Hns LoadBalancer for loadBalancer Ingress resources\", \"lbIngressIP\", lbIngressIP) } lbIngressIP.hnsID = hnsLoadBalancer.hnsID klog.V(3).InfoS(\"Hns LoadBalancer resource created for loadBalancer Ingress resources\", \"lbIngressIP\", lbIngressIP) if proxier.forwardHealthCheckVip && gatewayHnsendpoint != nil { nodeport := proxier.healthzPort"} {"_id":"doc-en-kubernetes-ead3094b0f2945db82b8d59f348ceb45895a7fe27eed108bb3e77714aecead08","title":"","text":"return false, nil } completionMode := string(batch.NonIndexedCompletion) if isIndexedJob(&job) { completionMode = string(batch.IndexedCompletion) } completionMode := getCompletionMode(&job) action := metrics.JobSyncActionReconciling defer func() {"} {"_id":"doc-en-kubernetes-76c9ec417d59ca043654bdc3262b73cb6212e660be1afcfc85dc19034f8a3372","title":"","text":"job.Status.CompletedIndexes = succeededIndexes.String() } job.Status.UncountedTerminatedPods = nil jm.enactJobFinished(&job, finishedCondition) jobFinished := jm.enactJobFinished(&job, finishedCondition) if _, err := jm.updateStatusHandler(ctx, &job); err != nil { return forget, err } if jobFinished { jm.recordJobFinished(&job, finishedCondition) } if jobHasNewFailure && !IsJobFinished(&job) { // returning an error will re-enqueue Job after the backoff period"} {"_id":"doc-en-kubernetes-680b32bd39c47b8f45163ae54e4b8111dbdf6ec82dc7b47f37100fb8727822a4","title":"","text":"if job, needsFlush, err = jm.flushUncountedAndRemoveFinalizers(ctx, job, podsToRemoveFinalizer, uidsWithFinalizer, &oldCounters, needsFlush); err != nil { return err } if jm.enactJobFinished(job, finishedCond) { jobFinished := jm.enactJobFinished(job, finishedCond) if jobFinished { needsFlush = true } if needsFlush { if _, err := jm.updateStatusHandler(ctx, job); err != nil { return fmt.Errorf(\"removing uncounted pods from status: %w\", err) } if jobFinished { jm.recordJobFinished(job, finishedCond) } recordJobPodFinished(job, oldCounters) } return nil"} {"_id":"doc-en-kubernetes-ddc6faa52b900fb51e957eb323a7aca78e0380d6c569aa119a09e479aea55958","title":"","text":"return false } } completionMode := string(batch.NonIndexedCompletion) if isIndexedJob(job) { completionMode = string(*job.Spec.CompletionMode) } job.Status.Conditions, _ = ensureJobConditionStatus(job.Status.Conditions, finishedCond.Type, finishedCond.Status, finishedCond.Reason, finishedCond.Message) if finishedCond.Type == batch.JobComplete { job.Status.CompletionTime = &finishedCond.LastTransitionTime } return true } // recordJobFinished records events and the job_finished_total metric for a finished job. func (jm *Controller) recordJobFinished(job *batch.Job, finishedCond *batch.JobCondition) bool { completionMode := getCompletionMode(job) if finishedCond.Type == batch.JobComplete { if job.Spec.Completions != nil && job.Status.Succeeded > *job.Spec.Completions { jm.recorder.Event(job, v1.EventTypeWarning, \"TooManySucceededPods\", \"Too many succeeded pods running after completion count reached\") } job.Status.CompletionTime = &finishedCond.LastTransitionTime jm.recorder.Event(job, v1.EventTypeNormal, \"Completed\", \"Job completed\") metrics.JobFinishedNum.WithLabelValues(completionMode, \"succeeded\").Inc() } else {"} {"_id":"doc-en-kubernetes-28dda6809d0ebd43ca79a9ceb9122e94d5b1ba6c22398a4a456010f40ee24629","title":"","text":"return result } // getCompletionMode returns string representation of the completion mode. Used as a label value for metrics. func getCompletionMode(job *batch.Job) string { if isIndexedJob(job) { return string(batch.IndexedCompletion) } return string(batch.NonIndexedCompletion) } func trackingUncountedPods(job *batch.Job) bool { return feature.DefaultFeatureGate.Enabled(features.JobTrackingWithFinalizers) && hasJobTrackingAnnotation(job) }"} {"_id":"doc-en-kubernetes-9e24138f31a5f4deb1dae7623971b5f538243ad9d7b724dfa475274423d9e5a3","title":"","text":"\"k8s.io/client-go/restmapper\" \"k8s.io/client-go/util/retry\" featuregatetesting \"k8s.io/component-base/featuregate/testing\" basemetrics \"k8s.io/component-base/metrics\" \"k8s.io/component-base/metrics/testutil\" \"k8s.io/controller-manager/pkg/informerfactory\" \"k8s.io/klog/v2\" kubeapiservertesting \"k8s.io/kubernetes/cmd/kube-apiserver/app/testing\" podutil \"k8s.io/kubernetes/pkg/api/v1/pod\" \"k8s.io/kubernetes/pkg/controller/garbagecollector\" jobcontroller \"k8s.io/kubernetes/pkg/controller/job\" \"k8s.io/kubernetes/pkg/controller/job/metrics\" \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/test/integration/framework\" \"k8s.io/utils/pointer\""} {"_id":"doc-en-kubernetes-236ed06a42d0508894e04775cba17f7052a641fad23f8c7240a8a4c0d154e89b","title":"","text":"const waitInterval = time.Second type metricLabelsWithValue struct { Labels []string Value int } func TestMetrics(t *testing.T) { nonIndexedCompletion := batchv1.NonIndexedCompletion indexedCompletion := batchv1.IndexedCompletion wFinalizers := true defer featuregatetesting.SetFeatureGateDuringTest(t, feature.DefaultFeatureGate, features.JobTrackingWithFinalizers, wFinalizers)() // setup the job controller closeFn, restConfig, clientSet, ns := setup(t, \"simple\") defer closeFn() ctx, cancel := startJobControllerAndWaitForCaches(restConfig) defer func() { cancel() }() testCases := map[string]struct { job *batchv1.Job wantJobFinishedNumMetricDelta metricLabelsWithValue wantJobPodsFinishedMetricDelta metricLabelsWithValue }{ \"non-indexed job\": { job: &batchv1.Job{ Spec: batchv1.JobSpec{ Completions: pointer.Int32(2), Parallelism: pointer.Int32(2), CompletionMode: &nonIndexedCompletion, }, }, wantJobFinishedNumMetricDelta: metricLabelsWithValue{ Labels: []string{\"NonIndexed\", \"succeeded\"}, Value: 1, }, wantJobPodsFinishedMetricDelta: metricLabelsWithValue{ Labels: []string{\"NonIndexed\", \"succeeded\"}, Value: 2, }, }, \"indexed job\": { job: &batchv1.Job{ Spec: batchv1.JobSpec{ Completions: pointer.Int32(2), Parallelism: pointer.Int32(2), CompletionMode: &indexedCompletion, }, }, wantJobFinishedNumMetricDelta: metricLabelsWithValue{ Labels: []string{\"Indexed\", \"succeeded\"}, Value: 1, }, wantJobPodsFinishedMetricDelta: metricLabelsWithValue{ Labels: []string{\"Indexed\", \"succeeded\"}, Value: 2, }, }, } job_index := 0 // job index to avoid collisions between job names created by different test cases for name, tc := range testCases { t.Run(name, func(t *testing.T) { // record the metrics after the job is created jobFinishedNumBefore, err := getCounterMetricValueForLabels(metrics.JobFinishedNum, tc.wantJobFinishedNumMetricDelta.Labels) if err != nil { t.Fatalf(\"Failed to collect the JobFinishedNum metric before creating the job: %q\", err) } jobPodsFinishedBefore, err := getCounterMetricValueForLabels(metrics.JobPodsFinished, tc.wantJobPodsFinishedMetricDelta.Labels) if err != nil { t.Fatalf(\"Failed to collect the JobPodsFinished metric before creating the job: %q\", err) } // create a single job and wait for its completion job := tc.job.DeepCopy() job.Name = fmt.Sprintf(\"job-%v\", job_index) job_index++ jobObj, err := createJobWithDefaults(ctx, clientSet, ns.Name, job) if err != nil { t.Fatalf(\"Failed to create Job: %v\", err) } validateJobPodsStatus(ctx, t, clientSet, jobObj, podsByStatus{ Active: int(*jobObj.Spec.Parallelism), Ready: pointer.Int32(0), }, wFinalizers) if err, _ := setJobPodsPhase(ctx, clientSet, jobObj, v1.PodSucceeded, int(*jobObj.Spec.Parallelism)); err != nil { t.Fatalf(\"Failed setting phase %s on Job Pod: %v\", v1.PodSucceeded, err) } validateJobSucceeded(ctx, t, clientSet, jobObj) // verify metric values after the job is finished validateMetricValueDeltas(t, metrics.JobFinishedNum, tc.wantJobFinishedNumMetricDelta, jobFinishedNumBefore) validateMetricValueDeltas(t, metrics.JobPodsFinished, tc.wantJobPodsFinishedMetricDelta, jobPodsFinishedBefore) }) } } func validateMetricValueDeltas(t *testing.T, counterVer *basemetrics.CounterVec, wantMetricDelta metricLabelsWithValue, metricValuesBefore metricLabelsWithValue) { t.Helper() var cmpErr error err := wait.PollImmediate(10*time.Millisecond, 10*time.Second, func() (bool, error) { cmpErr = nil metricValuesAfter, err := getCounterMetricValueForLabels(counterVer, wantMetricDelta.Labels) if err != nil { return true, fmt.Errorf(\"Failed to collect the %q metric after the job is finished: %q\", counterVer.Name, err) } wantDelta := wantMetricDelta.Value gotDelta := metricValuesAfter.Value - metricValuesBefore.Value if wantDelta != gotDelta { cmpErr = fmt.Errorf(\"Unexepected metric delta for %q metric with labels %q. want: %v, got: %v\", counterVer.Name, wantMetricDelta.Labels, wantDelta, gotDelta) return false, nil } return true, nil }) if err != nil { t.Errorf(\"Failed waiting for expected metric delta: %q\", err) } if cmpErr != nil { t.Error(cmpErr) } } func getCounterMetricValueForLabels(counterVec *basemetrics.CounterVec, labels []string) (metricLabelsWithValue, error) { var result metricLabelsWithValue = metricLabelsWithValue{Labels: labels} value, err := testutil.GetCounterMetricValue(counterVec.WithLabelValues(labels...)) if err != nil { return result, err } result.Value = int(value) return result, nil } // TestJobPodFailurePolicyWithFailedPodDeletedDuringControllerRestart verifies that the job is properly marked as Failed // in a scenario when the job controller crashes between removing pod finalizers and marking the job as Failed (based on // the pod failure policy). After the finalizer for the failed pod is removed we remove the failed pod. This step is"} {"_id":"doc-en-kubernetes-c372401c5ca24ad3e2f0b57693e641a99c4a793660b8e2268cfe91e410093e95","title":"","text":"componentbaseconfig \"k8s.io/component-base/config\" \"k8s.io/component-base/configz\" \"k8s.io/component-base/logs\" metricsfeatures \"k8s.io/component-base/metrics/features\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/component-base/metrics/prometheus/slis\" \"k8s.io/component-base/version\" \"k8s.io/component-base/version/verflag\" \"k8s.io/klog/v2\""} {"_id":"doc-en-kubernetes-22fc827228c2e7e0cb689900403cd1adb93023f07b1ddff9eb23c4e674b88493","title":"","text":"\"k8s.io/utils/pointer\" ) func init() { utilruntime.Must(metricsfeatures.AddFeatureGates(utilfeature.DefaultMutableFeatureGate)) } // proxyRun defines the interface to run a specified ProxyServer type proxyRun interface { Run() error"} {"_id":"doc-en-kubernetes-3abe1a5cf7252a4d84848932d5106f25d52ad3d78bf67033dc33dbe2368bd976","title":"","text":"proxyMux := mux.NewPathRecorderMux(\"kube-proxy\") healthz.InstallHandler(proxyMux) if utilfeature.DefaultFeatureGate.Enabled(metricsfeatures.ComponentSLIs) { slis.SLIMetricsWithReset{}.Install(proxyMux) } proxyMux.HandleFunc(\"/proxyMode\", func(w http.ResponseWriter, r *http.Request) { w.Header().Set(\"Content-Type\", \"text/plain; charset=utf-8\") w.Header().Set(\"X-Content-Type-Options\", \"nosniff\")"} {"_id":"doc-en-kubernetes-4d62c9faa32b5c61cd8d27ceb21726318bbde62d2e69d182cf99d60660d14c84","title":"","text":"\"k8s.io/component-base/configz\" \"k8s.io/component-base/logs\" compbasemetrics \"k8s.io/component-base/metrics\" metricsfeatures \"k8s.io/component-base/metrics/features\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/component-base/metrics/prometheus/slis\" runtimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1\" podresourcesapi \"k8s.io/kubelet/pkg/apis/podresources/v1\" podresourcesapiv1alpha1 \"k8s.io/kubelet/pkg/apis/podresources/v1alpha1\""} {"_id":"doc-en-kubernetes-e91973b14d3bffd8c9008c91cbe07429f6e2323084ed676716efe889be41aa71","title":"","text":"\"k8s.io/kubernetes/pkg/kubelet/util\" ) func init() { utilruntime.Must(metricsfeatures.AddFeatureGates(utilfeature.DefaultMutableFeatureGate)) } const ( metricsPath = \"/metrics\" cadvisorMetricsPath = \"/metrics/cadvisor\""} {"_id":"doc-en-kubernetes-89ae37d733cefeea60dd2e7e5e83cabd4712996ebd1c9f4080684873ccc4a236","title":"","text":"healthz.NamedCheck(\"syncloop\", s.syncLoopHealthCheck), ) if utilfeature.DefaultFeatureGate.Enabled(metricsfeatures.ComponentSLIs) { slis.SLIMetricsWithReset{}.Install(s.restfulCont) } s.addMetricsBucketMatcher(\"pods\") ws := new(restful.WebService) ws."} {"_id":"doc-en-kubernetes-28d86e177d87068375b4738f649e83fdda2201a0c8e3a3d658e1c5e6b9dda4af","title":"","text":"func (t *prefixTransformers) TransformToStorage(ctx context.Context, data []byte, dataCtx Context) ([]byte, error) { start := time.Now() transformer := t.transformers[0] prefixedData := make([]byte, len(transformer.Prefix), len(data)+len(transformer.Prefix)) copy(prefixedData, transformer.Prefix) result, err := transformer.Transformer.TransformToStorage(ctx, data, dataCtx) RecordTransformation(\"to_storage\", string(transformer.Prefix), start, err) if err != nil { return nil, err } prefixedData := make([]byte, len(transformer.Prefix), len(result)+len(transformer.Prefix)) copy(prefixedData, transformer.Prefix) prefixedData = append(prefixedData, result...) return prefixedData, nil }"} {"_id":"doc-en-kubernetes-caaa88fd39dda0fcb40915898578def7369e056d1a9b1ae03534b114a928821b","title":"","text":"testDeploymentDefaultReplicas := int32(2) testDeploymentMinimumReplicas := int32(1) testDeploymentNoReplicas := int32(0) testDeploymentAvailableReplicas := int32(0) testDeploymentLabels := map[string]string{\"test-deployment-static\": \"true\"} testDeploymentLabelsFlat := \"test-deployment-static=true\" w := &cache.ListWatch{"} {"_id":"doc-en-kubernetes-4bcb85f16d30637b0f34694e090c9d9e0f74f1d85b523c94fb4f8d8e8360565d","title":"","text":"\"labels\": map[string]string{\"test-deployment\": \"patched-status\"}, }, \"status\": map[string]interface{}{ \"readyReplicas\": testDeploymentNoReplicas, \"readyReplicas\": testDeploymentNoReplicas, \"availableReplicas\": testDeploymentAvailableReplicas, }, }) framework.ExpectNoError(err, \"failed to Marshal Deployment JSON patch\") // This test is broken, patching fails with: // Deployment.apps \"test-deployment\" is invalid: status.availableReplicas: Invalid value: 2: cannot be greater than readyReplicas // https://github.com/kubernetes/kubernetes/issues/113259 _, _ = dc.Resource(deploymentResource).Namespace(testNamespaceName).Patch(ctx, testDeploymentName, types.StrategicMergePatchType, []byte(deploymentStatusPatch), metav1.PatchOptions{}, \"status\") _, err = dc.Resource(deploymentResource).Namespace(testNamespaceName).Patch(ctx, testDeploymentName, types.StrategicMergePatchType, []byte(deploymentStatusPatch), metav1.PatchOptions{}, \"status\") framework.ExpectNoError(err) ctxUntil, cancel = context.WithTimeout(ctx, 30*time.Second) defer cancel()"} {"_id":"doc-en-kubernetes-2e7a6df77b22949d5a170ef946fd543dfc0c08b46184091de061b36ca7eb5050","title":"","text":"limitRange := validLimitRangeNoDefaults() limitRanges := []corev1.LimitRange{limitRange} var count int64 mockClient := &fake.Clientset{} unhold := make(chan struct{}) var ( testCount int64 test1Count int64 ) mockClient.AddReactor(\"list\", \"limitranges\", func(action core.Action) (bool, runtime.Object, error) { atomic.AddInt64(&count, 1) switch action.GetNamespace() { case \"test\": atomic.AddInt64(&testCount, 1) case \"test1\": atomic.AddInt64(&test1Count, 1) default: t.Error(\"unexpected namespace\") } limitRangeList := &corev1.LimitRangeList{ ListMeta: metav1.ListMeta{"} {"_id":"doc-en-kubernetes-94f639e7ee76cfec34e2d23451c361ef2576b5c7f2251b715754e1831503428e","title":"","text":"value.Namespace = action.GetNamespace() limitRangeList.Items = append(limitRangeList.Items, value) } // he always blocking before sending the signal <-unhold // make the handler slow so concurrent calls exercise the singleflight time.Sleep(time.Second) return true, limitRangeList, nil })"} {"_id":"doc-en-kubernetes-52dc6561ecfd67a35750c7a5cbb9812c02030cf03bdfc6600f08307648daecf6","title":"","text":"} }() } // unhold all the calls with the same namespace handler.GetLimitRanges(attributes) calls, that have to be aggregated unhold <- struct{}{} go func() { unhold <- struct{}{} }() // and here we wait for all the goroutines wg.Wait() // since all the calls with the same namespace will be holded, they must be catched on the singleflight group, // There are two different sets of namespace calls // hence only 2 if count != 2 { t.Errorf(\"Expected 1 limit range, got %d\", count) if testCount != 1 { t.Errorf(\"Expected 1 limit range call, got %d\", testCount) } if test1Count != 1 { t.Errorf(\"Expected 1 limit range call, got %d\", test1Count) } // invalidate the cache handler.liveLookupCache.Remove(attributes.GetNamespace()) go func() { // unhold it is blocking until GetLimitRanges is executed unhold <- struct{}{} }() _, err = handler.GetLimitRanges(attributes) if err != nil { t.Errorf(\"unexpected error: %v\", err) } close(unhold) if count != 3 { t.Errorf(\"Expected 2 limit range, got %d\", count) if testCount != 2 { t.Errorf(\"Expected 2 limit range call, got %d\", testCount) } if test1Count != 1 { t.Errorf(\"Expected 1 limit range call, got %d\", test1Count) } }"} {"_id":"doc-en-kubernetes-b8e6a9996ddcd3f2fbdd4d60bff2a8049a87df09ba377a55e4f0ffe3ab4f1a96","title":"","text":"eventsRule(), }, }) addControllerRole(&controllerRoles, &controllerRoleBindings, rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"disruption-controller\"}, Rules: []rbacv1.PolicyRule{ rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(extensionsGroup, appsGroup).Resources(\"deployments\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"replicationcontrollers\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(policyGroup).Resources(\"poddisruptionbudgets\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup).Resources(\"statefulsets\").RuleOrDie(), rbacv1helpers.NewRule(\"update\").Groups(policyGroup).Resources(\"poddisruptionbudgets/status\").RuleOrDie(), rbacv1helpers.NewRule(\"get\").Groups(\"*\").Resources(\"*/scale\").RuleOrDie(), eventsRule(), }, }) addControllerRole(&controllerRoles, &controllerRoleBindings, func() rbacv1.ClusterRole { role := rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"disruption-controller\"}, Rules: []rbacv1.PolicyRule{ rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(extensionsGroup, appsGroup).Resources(\"deployments\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup, extensionsGroup).Resources(\"replicasets\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(legacyGroup).Resources(\"replicationcontrollers\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(policyGroup).Resources(\"poddisruptionbudgets\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(appsGroup).Resources(\"statefulsets\").RuleOrDie(), rbacv1helpers.NewRule(\"update\").Groups(policyGroup).Resources(\"poddisruptionbudgets/status\").RuleOrDie(), rbacv1helpers.NewRule(\"get\").Groups(\"*\").Resources(\"*/scale\").RuleOrDie(), eventsRule(), }, } if utilfeature.DefaultFeatureGate.Enabled(features.PodDisruptionConditions) { role.Rules = append(role.Rules, rbacv1helpers.NewRule(\"patch\").Groups(legacyGroup).Resources(\"pods/status\").RuleOrDie()) } return role }()) addControllerRole(&controllerRoles, &controllerRoleBindings, rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{Name: saRolePrefix + \"endpoint-controller\"}, Rules: []rbacv1.PolicyRule{"} {"_id":"doc-en-kubernetes-09f5619ef0bae1d9ca0340d3021d076d65cb5eb40f9b0813ababf1e866bd6780","title":"","text":"\"description\": \"CustomResourceConversion describes how to convert different versions of a CR.\", \"properties\": { \"strategy\": { \"description\": \"strategy specifies how custom resources are converted between versions. Allowed values are: - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `Webhook`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", \"description\": \"strategy specifies how custom resources are converted between versions. Allowed values are: - `\"None\"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `\"Webhook\"`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", \"type\": \"string\" }, \"webhook\": { \"$ref\": \"#/definitions/io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion\", \"description\": \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `Webhook`.\" \"description\": \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `\"Webhook\"`.\" } }, \"required\": ["} {"_id":"doc-en-kubernetes-eb1f850fc3177fab6b7d825d554ea3522f7efe16857c07888b4bbe685e1a3026","title":"","text":"\"properties\": { \"strategy\": { \"default\": \"\", \"description\": \"strategy specifies how custom resources are converted between versions. Allowed values are: - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `Webhook`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", \"description\": \"strategy specifies how custom resources are converted between versions. Allowed values are: - `\"None\"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `\"Webhook\"`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", \"type\": \"string\" }, \"webhook\": {"} {"_id":"doc-en-kubernetes-cd8ff2eeacfe86356feb32aa58109571a630cf2a8eb4b7ecf68c6916a3b9fc9a","title":"","text":"\"$ref\": \"#/components/schemas/io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1.WebhookConversion\" } ], \"description\": \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `Webhook`.\" \"description\": \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `\"Webhook\"`.\" } }, \"required\": ["} {"_id":"doc-en-kubernetes-b79b11c4cd11f62507452a408fdf51ae279049e715d48ff6c693062c1c74391d","title":"","text":" /* Copyright 2023 The Kubernetes Authors. 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. */ package main import ( \"fmt\" \"os\" \"regexp\" \"strings\" flag \"github.com/spf13/pflag\" kruntime \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/klog/v2\" ) var ( typeSrc = flag.StringP(\"type-src\", \"s\", \"\", \"From where we are going to read the types\") re = regexp.MustCompile(\"`(bw+b)`\") ) // kubeTypesMap is a map from field name to its tag name and doc. type kubeTypesMap map[string]kruntime.Pair func main() { flag.Parse() if *typeSrc == \"\" { klog.Fatalf(\"Please define -s flag as it is the api type file\") } docsForTypes := kruntime.ParseDocumentationFrom(*typeSrc) rc := false for _, ks := range docsForTypes { typesMap := make(kubeTypesMap) for _, p := range ks[1:] { // skip the field with no tag name if p.Name != \"\" { typesMap[strings.ToLower(p.Name)] = p } } structName := ks[0].Name rc = checkFieldNameAndDoc(structName, \"\", ks[0].Doc, typesMap) for _, p := range ks[1:] { rc = checkFieldNameAndDoc(structName, p.Name, p.Doc, typesMap) } } if rc { os.Exit(1) } } func checkFieldNameAndDoc(structName, fieldName, doc string, typesMap kubeTypesMap) bool { rc := false visited := sets.Set[string]{} // The rule is: // 1. Get all back-tick quoted names in the doc // 2. Skip the name which is already found mismatched. // 3. Skip the name whose lowercase is different from the lowercase of tag names, // because some docs use back-tick to quote field value or nil // 4. Check if the name is different from its tag name // TODO: a manual pass adding back-ticks to the doc strings, then update the linter to // check the existence of back-ticks nameGroups := re.FindAllStringSubmatch(doc, -1) for _, nameGroup := range nameGroups { name := nameGroup[1] if visited.Has(name) { continue } if p, ok := typesMap[strings.ToLower(name)]; ok && p.Name != name { rc = true visited.Insert(name) fmt.Fprintf(os.Stderr, \"Error: doc for %s\", structName) if fieldName != \"\" { fmt.Fprintf(os.Stderr, \".%s\", fieldName) } fmt.Fprintf(os.Stderr, \" contains: %s, which should be: %sn\", name, p.Name) } } return rc } "} {"_id":"doc-en-kubernetes-08bb38368d31a5c234d5a76d28b19fdbca0d9ee3d4382f6cbf2a95d28e890822","title":"","text":" #!/usr/bin/env bash # Copyright 2023 The Kubernetes Authors. # # 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. # This script checks API-related files for mismatch in docs and field names, # and outputs a list of fields that their docs and field names are mismatched. # Usage: `hack/verify-fieldname-docs.sh`. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/.. source \"${KUBE_ROOT}/hack/lib/init.sh\" source \"${KUBE_ROOT}/hack/lib/util.sh\" kube::golang::setup_env make -C \"${KUBE_ROOT}\" WHAT=cmd/fieldnamedocscheck # Find binary fieldnamedocscheck=$(kube::util::find-binary \"fieldnamedocscheck\") result=0 find_files() { find . -not ( ( -wholename './output' -o -wholename './_output' -o -wholename './_gopath' -o -wholename './release' -o -wholename './target' -o -wholename '*/third_party/*' -o -wholename '*/vendor/*' -o -wholename './pkg/*' ) -prune ) ( -wholename './staging/src/k8s.io/api/*/v*/types.go' -o -wholename './staging/src/k8s.io/kube-aggregator/pkg/apis/*/v*/types.go' -o -wholename './staging/src/k8s.io/apiextensions-apiserver/pkg/apis/*/v*/types.go' ) } versioned_api_files=$(find_files) || true for file in ${versioned_api_files}; do package=\"${file%\"/types.go\"}\" echo \"Checking ${package}\" ${fieldnamedocscheck} -s \"${file}\" || result=$? done exit ${result} "} {"_id":"doc-en-kubernetes-d8b2f8ed83208b09a563d3d5f60a1454dd38451cabbe16329105a880709b968e","title":"","text":"Properties: map[string]spec.Schema{ \"strategy\": { SchemaProps: spec.SchemaProps{ Description: \"strategy specifies how custom resources are converted between versions. Allowed values are: - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `Webhook`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", Description: \"strategy specifies how custom resources are converted between versions. Allowed values are: - `\"None\"`: The converter only change the apiVersion and would not touch any other field in the custom resource. - `\"Webhook\"`: API Server will call to an external webhook to do the conversion. Additional informationn is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set.\", Default: \"\", Type: []string{\"string\"}, Format: \"\","} {"_id":"doc-en-kubernetes-5cc112ec294c65e6709a6fb35161cc04934e9e0a26b84676504a0b91759d35e9","title":"","text":"}, \"webhook\": { SchemaProps: spec.SchemaProps{ Description: \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `Webhook`.\", Description: \"webhook describes how to call the conversion webhook. Required when `strategy` is set to `\"Webhook\"`.\", Ref: ref(\"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1.WebhookConversion\"), }, },"} {"_id":"doc-en-kubernetes-bc835d95804f0d34ca8d719bf195eab423128cd98c279a9d4cf1c2b86acce2b5","title":"","text":"// CustomResourceConversion describes how to convert different versions of a CR. message CustomResourceConversion { // strategy specifies how custom resources are converted between versions. Allowed values are: // - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. // - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information // - `\"None\"`: The converter only change the apiVersion and would not touch any other field in the custom resource. // - `\"Webhook\"`: API Server will call to an external webhook to do the conversion. Additional information // is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. optional string strategy = 1; // webhook describes how to call the conversion webhook. Required when `strategy` is set to `Webhook`. // webhook describes how to call the conversion webhook. Required when `strategy` is set to `\"Webhook\"`. // +optional optional WebhookConversion webhook = 2; }"} {"_id":"doc-en-kubernetes-772fe1bc256cc16c219de007e8767e7ce4f97ca657bd9d9211215a15333d0bb5","title":"","text":"// CustomResourceConversion describes how to convert different versions of a CR. type CustomResourceConversion struct { // strategy specifies how custom resources are converted between versions. Allowed values are: // - `None`: The converter only change the apiVersion and would not touch any other field in the custom resource. // - `Webhook`: API Server will call to an external webhook to do the conversion. Additional information // - `\"None\"`: The converter only change the apiVersion and would not touch any other field in the custom resource. // - `\"Webhook\"`: API Server will call to an external webhook to do the conversion. Additional information // is needed for this option. This requires spec.preserveUnknownFields to be false, and spec.conversion.webhook to be set. Strategy ConversionStrategyType `json:\"strategy\" protobuf:\"bytes,1,name=strategy\"` // webhook describes how to call the conversion webhook. Required when `strategy` is set to `Webhook`. // webhook describes how to call the conversion webhook. Required when `strategy` is set to `\"Webhook\"`. // +optional Webhook *WebhookConversion `json:\"webhook,omitempty\" protobuf:\"bytes,2,opt,name=webhook\"` }"} {"_id":"doc-en-kubernetes-914d9aac9302cc1336bce235213c3e141843260c7c4ff83157d6fff59c53e97a","title":"","text":"\"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/client-go/kubernetes\" resourcev1alpha2listers \"k8s.io/client-go/listers/resource/v1alpha2\" corev1helpers \"k8s.io/component-helpers/scheduling/corev1\" \"k8s.io/component-helpers/scheduling/corev1/nodeaffinity\" \"k8s.io/dynamic-resource-allocation/resourceclaim\" \"k8s.io/klog/v2\""} {"_id":"doc-en-kubernetes-91b4b9547790b2ef186cae4b0e1ae52aed3776eeb3b2cbddde02542e29e8bbdf","title":"","text":"// Empty if the Pod has no claims. claims []*resourcev1alpha2.ResourceClaim // The AvailableOnNodes node filters of the claims converted from the // v1 API to nodeaffinity.NodeSelector by PreFilter for repeated // evaluation in Filter. Nil for claims which don't have it. availableOnNodes []*nodeaffinity.NodeSelector // The indices of all claims that: // - are allocated // - use delayed allocation"} {"_id":"doc-en-kubernetes-db9897dc06baee665972a9ac8c9dd855ca0dd0e5e3836c079765a2b7368789e9","title":"","text":"podSchedulingDirty bool mutex sync.Mutex informationsForClaim []informationForClaim } type informationForClaim struct { // The availableOnNode node filter of the claim converted from the // v1 API to nodeaffinity.NodeSelector by PreFilter for repeated // evaluation in Filter. Nil for claim which don't have it. availableOnNode *nodeaffinity.NodeSelector // The status of the claim got from the // schedulingCtx by PreFilter for repeated // evaluation in Filter. Nil for claim which don't have it. status *resourcev1alpha2.ResourceClaimSchedulingStatus } func (d *stateData) Clone() framework.StateData {"} {"_id":"doc-en-kubernetes-893771f7884f2b5549f027f3fc18b1dcc2308a25f1d0dc3609a0ae9eb1a0cd25","title":"","text":"return nil, framework.NewStatus(framework.Skip) } s.availableOnNodes = make([]*nodeaffinity.NodeSelector, len(claims)) s.informationsForClaim = make([]informationForClaim, len(claims)) for index, claim := range claims { if claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeImmediate && claim.Status.Allocation == nil {"} {"_id":"doc-en-kubernetes-109e7c2a275a57e795f59e916295c2d2afba6262472485b22cbabba637a2417d","title":"","text":"if err != nil { return nil, statusError(logger, err) } s.availableOnNodes[index] = nodeSelector s.informationsForClaim[index].availableOnNode = nodeSelector } if claim.Status.Allocation == nil && claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeWaitForFirstConsumer { // The ResourceClass might have a node filter. This is // useful for trimming the initial set of potential // nodes before we ask the driver(s) for information // about the specific pod. class, err := pl.classLister.Get(claim.Spec.ResourceClassName) if err != nil { // If the class does not exist, then allocation cannot proceed. return nil, statusError(logger, fmt.Errorf(\"look up resource class: %v\", err)) } if class.SuitableNodes != nil { selector, err := nodeaffinity.NewNodeSelector(class.SuitableNodes) if err != nil { return nil, statusError(logger, err) } s.informationsForClaim[index].availableOnNode = selector } // Now we need information from drivers. schedulingCtx, err := s.initializePodSchedulingContexts(ctx, pod, pl.podSchedulingContextLister) if err != nil { return nil, statusError(logger, err) } s.informationsForClaim[index].status = statusForClaim(schedulingCtx, pod.Spec.ResourceClaims[index].Name) } }"} {"_id":"doc-en-kubernetes-cef74b7b1dbb9686df4cfed0475861abd3380248dced0f9fef1f1e6985994f57","title":"","text":"logger.V(10).Info(\"filtering based on resource claims of the pod\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim)) switch { case claim.Status.Allocation != nil: if nodeSelector := state.availableOnNodes[index]; nodeSelector != nil { if nodeSelector := state.informationsForClaim[index].availableOnNode; nodeSelector != nil { if !nodeSelector.Match(node) { logger.V(5).Info(\"AvailableOnNodes does not match\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim)) unavailableClaims = append(unavailableClaims, index)"} {"_id":"doc-en-kubernetes-845a9e89e4a301de8fb06ae77eadec1fcefbe7bb65692f382f7f867dd74420da","title":"","text":"// We shouldn't get here. PreFilter already checked this. return statusUnschedulable(logger, \"resourceclaim must be reallocated\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim)) case claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeWaitForFirstConsumer: // The ResourceClass might have a node filter. This is // useful for trimming the initial set of potential // nodes before we ask the driver(s) for information // about the specific pod. class, err := pl.classLister.Get(claim.Spec.ResourceClassName) if err != nil { // If the class does not exist, then allocation cannot proceed. return statusError(logger, fmt.Errorf(\"look up resource class: %v\", err)) } if class.SuitableNodes != nil { // TODO (#113700): parse class.SuitableNodes once in PreFilter, reuse result. matches, err := corev1helpers.MatchNodeSelectorTerms(node, class.SuitableNodes) if err != nil { return statusError(logger, fmt.Errorf(\"potential node filter: %v\", err)) if selector := state.informationsForClaim[index].availableOnNode; selector != nil { if matches := selector.Match(node); !matches { return statusUnschedulable(logger, \"excluded by resource class node filter\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclassName\", claim.Spec.ResourceClassName) } if !matches { return statusUnschedulable(logger, \"excluded by resource class node filter\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclass\", klog.KObj(class)) } } // Now we need information from drivers. schedulingCtx, err := state.initializePodSchedulingContexts(ctx, pod, pl.podSchedulingContextLister) if err != nil { return statusError(logger, err) } status := statusForClaim(schedulingCtx, pod.Spec.ResourceClaims[index].Name) if status != nil { if status := state.informationsForClaim[index].status; status != nil { for _, unsuitableNode := range status.UnsuitableNodes { if node.Name == unsuitableNode { return statusUnschedulable(logger, \"resourceclaim cannot be allocated for the node (unsuitable)\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"resourceclaim\", klog.KObj(claim), \"unsuitablenodes\", status.UnsuitableNodes)"} {"_id":"doc-en-kubernetes-69f1dbca59ab06d4a70cc0d92bba737e4bdb2540a3b2687d6b5d1a156ba14bdf","title":"","text":"pod: podWithClaimName, claims: []*resourcev1alpha2.ResourceClaim{pendingDelayedClaim}, want: want{ filter: perNodeResult{ workerNode.Name: { status: framework.AsStatus(fmt.Errorf(`look up resource class: resourceclass.resource.k8s.io \"%s\" not found`, className)), }, prefilter: result{ status: framework.AsStatus(fmt.Errorf(`look up resource class: resourceclass.resource.k8s.io \"%s\" not found`, className)), }, postfilter: result{ status: framework.NewStatus(framework.Unschedulable, `still not schedulable`), status: framework.NewStatus(framework.Unschedulable, `no new claims to deallocate`), }, }, },"} {"_id":"doc-en-kubernetes-d7d2aafed79f78cc79c5c21e132e443ec786a065db418ec01cd950bfa6b4bada","title":"","text":"kubeReserved, err := parseResourceList(s.KubeReserved) if err != nil { return err return fmt.Errorf(\"--kube-reserved value failed to parse: %w\", err) } systemReserved, err := parseResourceList(s.SystemReserved) if err != nil { return err return fmt.Errorf(\"--system-reserved value failed to parse: %w\", err) } var hardEvictionThresholds []evictionapi.Threshold // If the user requested to ignore eviction thresholds, then do not set valid values for hardEvictionThresholds here."} {"_id":"doc-en-kubernetes-d430f5fad2ea674f842a77b239affa611e292bb55ea30616a16467e1b4c4e419","title":"","text":"} experimentalQOSReserved, err := cm.ParseQOSReserved(s.QOSReserved) if err != nil { return err return fmt.Errorf(\"--qos-reserved value failed to parse: %w\", err) } var cpuManagerPolicyOptions map[string]string"} {"_id":"doc-en-kubernetes-002778e7eafc67eda38ab480f37369e7995579f9382ce2f6f10e996a99f2a8d7","title":"","text":"case v1.ResourceCPU, v1.ResourceMemory, v1.ResourceEphemeralStorage, pidlimit.PIDs: q, err := resource.ParseQuantity(v) if err != nil { return nil, err return nil, fmt.Errorf(\"failed to parse quantity %q for %q resource: %w\", v, k, err) } if q.Sign() == -1 { return nil, fmt.Errorf(\"resource quantity for %q cannot be negative: %v\", k, v)"} {"_id":"doc-en-kubernetes-a9df4ec77cc05b4e98bb794071393c6aeefcda5b0160098fa9d767944af0b3e6","title":"","text":"case v1.ResourceMemory: q, err := parsePercentage(v) if err != nil { return nil, err return nil, fmt.Errorf(\"failed to parse percentage %q for %q resource: %w\", v, k, err) } reservations[v1.ResourceName(k)] = q default:"} {"_id":"doc-en-kubernetes-1d01473cc54fee5db828d5236207ab3a91be494c5cfa8192421ae1f962474913","title":"","text":"package kuberuntime import ( \"runtime\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/resource\" runtimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1\" \"k8s.io/klog/v2\" kubecontainer \"k8s.io/kubernetes/pkg/kubelet/container\" \"k8s.io/kubernetes/pkg/kubelet/winstats\" \"k8s.io/kubernetes/pkg/securitycontext\" )"} {"_id":"doc-en-kubernetes-9d1808bbd393dcb7d0528ccb82d92d452099615453b4550340843bc610da093f","title":"","text":"cpuLimit := container.Resources.Limits.Cpu() if !cpuLimit.IsZero() { // Note that sysinfo.NumCPU() is limited to 64 CPUs on Windows due to Processor Groups, // as only 64 processors are available for execution by a given process. This causes // some oddities on systems with more than 64 processors. // Refer https://msdn.microsoft.com/en-us/library/windows/desktop/dd405503(v=vs.85).aspx. // Since Kubernetes doesn't have any notion of weight in the Pod/Container API, only limits/reserves, then applying CpuMaximum only // will better follow the intent of the user. At one point CpuWeights were set, but this prevented limits from having any effect."} {"_id":"doc-en-kubernetes-110c641939170ce6f1d387cf53543405cd127b27e87056298a74c8dead782d3e","title":"","text":"// https://github.com/kubernetes/kubernetes/blob/56d1c3b96d0a544130a82caad33dd57629b8a7f8/staging/src/k8s.io/cri-api/pkg/apis/runtime/v1/api.proto#L681-L682 // https://github.com/opencontainers/runtime-spec/blob/ad53dcdc39f1f7f7472b10aa0a45648fe4865496/config-windows.md#cpu // If both CpuWeight and CpuMaximum are set - ContainerD catches this invalid case and returns an error instead. cpuMaximum := 10000 * cpuLimit.MilliValue() / int64(runtime.NumCPU()) / 1000 // ensure cpuMaximum is in range [1, 10000]. if cpuMaximum < 1 { cpuMaximum = 1 } else if cpuMaximum > 10000 { cpuMaximum = 10000 } wc.Resources.CpuMaximum = cpuMaximum wc.Resources.CpuMaximum = calculateCPUMaximum(cpuLimit, int64(winstats.ProcessorCount())) } // The processor resource controls are mutually exclusive on"} {"_id":"doc-en-kubernetes-5efcc9aa575cceef8c301f642243dded92940aad7534b8a4c6064233fdc025e6","title":"","text":"return wc, nil } // calculateCPUMaximum calculates the maximum CPU given a limit and a number of cpus while ensuring it's in range [1,10000]. func calculateCPUMaximum(cpuLimit *resource.Quantity, cpuCount int64) int64 { cpuMaximum := 10 * cpuLimit.MilliValue() / cpuCount // ensure cpuMaximum is in range [1, 10000]. if cpuMaximum < 1 { cpuMaximum = 1 } else if cpuMaximum > 10000 { cpuMaximum = 10000 } return cpuMaximum } "} {"_id":"doc-en-kubernetes-609980bbb12e54b4e048d0f87988347a0554e227167682d6487bd0ef95e641f4","title":"","text":"package kuberuntime import ( \"runtime\" \"testing\" \"github.com/stretchr/testify/assert\""} {"_id":"doc-en-kubernetes-fcea764f51360b6f236804addb6f56e0754dc747330f7e280120c88c6a2d199c","title":"","text":"v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" featuregatetesting \"k8s.io/component-base/featuregate/testing\" runtimeapi \"k8s.io/cri-api/pkg/apis/runtime/v1\" \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/pkg/kubelet/winstats\" ) func TestApplyPlatformSpecificContainerConfig(t *testing.T) {"} {"_id":"doc-en-kubernetes-57b5709cc737dd1da855e8da16b0e72986bf3bc806ba8b450b43a236d26b3739","title":"","text":"err = fakeRuntimeSvc.applyPlatformSpecificContainerConfig(containerConfig, &pod.Spec.Containers[0], pod, new(int64), \"foo\", nil) require.NoError(t, err) expectedCpuMax := ((10000 * 3000) / int64(runtime.NumCPU()) / 1000) limit := int64(3000) expectedCpuMax := 10 * limit / int64(winstats.ProcessorCount()) expectedWindowsConfig := &runtimeapi.WindowsContainerConfig{ Resources: &runtimeapi.WindowsContainerResources{ CpuMaximum: expectedCpuMax,"} {"_id":"doc-en-kubernetes-64196f0c5ff80524ea759ff869c9671c3fb56cad19c388b75296835eefbe227b","title":"","text":"} assert.Equal(t, expectedWindowsConfig, containerConfig.Windows) } func TestCalculateCPUMaximum(t *testing.T) { tests := []struct { name string cpuLimit resource.Quantity cpuCount int64 want int64 }{ { name: \"max range when same amount\", cpuLimit: resource.MustParse(\"1\"), cpuCount: 1, want: 10000, }, { name: \"percentage calculation is working as intended\", cpuLimit: resource.MustParse(\"94\"), cpuCount: 96, want: 9791, }, { name: \"half range when half amount\", cpuLimit: resource.MustParse(\"1\"), cpuCount: 2, want: 5000, }, { name: \"max range when more requested than available\", cpuLimit: resource.MustParse(\"2\"), cpuCount: 1, want: 10000, }, { name: \"min range when less than minimum\", cpuLimit: resource.MustParse(\"1m\"), cpuCount: 100, want: 1, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.want, calculateCPUMaximum(&tt.cpuLimit, tt.cpuCount)) }) } } "} {"_id":"doc-en-kubernetes-231196180f23e76c0db108b49ccde575dd175d1659cfc8f5f29688046794e8de","title":"","text":"} return &cadvisorapi.MachineInfo{ NumCores: processorCount(), NumCores: ProcessorCount(), MemoryCapacity: p.nodeInfo.memoryPhysicalCapacityBytes, MachineID: hostname, SystemUUID: systemUUID,"} {"_id":"doc-en-kubernetes-e92ebb9ccacf96096778873ba9ba0d300b85355923729146104900efb9640d2f","title":"","text":"// more notes for this issue: // same issue in moby: https://github.com/moby/moby/issues/38935#issuecomment-744638345 // solution in hcsshim: https://github.com/microsoft/hcsshim/blob/master/internal/processorinfo/processor_count.go func processorCount() int { func ProcessorCount() int { if amount := getActiveProcessorCount(allProcessorGroups); amount != 0 { return int(amount) }"} {"_id":"doc-en-kubernetes-aa59c396bfb15b50b6a2473d46b2cff811c22be75d884efb51db0d7dfe08256e","title":"","text":"}) ginkgo.It(\"should work with the pod containing more than 6 DNS search paths and longer than 256 search list characters\", func(ctx context.Context) { ginkgo.By(\"Getting the kube-dns IP\") svc, err := f.ClientSet.CoreV1().Services(\"kube-system\").Get(ctx, \"kube-dns\", metav1.GetOptions{}) framework.ExpectNoError(err, \"Failed to get kube-dns service\") kubednsIP := svc.Spec.ClusterIP // All the names we need to be able to resolve. namesToResolve := []string{ \"kubernetes.default\","} {"_id":"doc-en-kubernetes-9d98d365a349054943ab5a2631292aca6b8e4ff2ef4ef7d89661b09c6781d621","title":"","text":"pod := createDNSPod(f.Namespace.Name, wheezyProbeCmd, jessieProbeCmd, dnsTestPodHostName, dnsTestServiceName) pod.Spec.DNSPolicy = v1.DNSClusterFirst pod.Spec.DNSConfig = &v1.PodDNSConfig{ Nameservers: []string{kubednsIP}, Searches: testSearchPaths, Searches: testSearchPaths, Options: []v1.PodDNSConfigOption{ { Name: \"ndots\","} {"_id":"doc-en-kubernetes-9f59fa4dd1b16a5ae38208defe6362c8e96b62dfc888326c9e66b7b1a3137219","title":"","text":"v1.LabelTopologyRegion, } func translateToGALabel(label string) string { if label == v1.LabelFailureDomainBetaRegion { return v1.LabelTopologyRegion } if label == v1.LabelFailureDomainBetaZone { return v1.LabelTopologyZone } return label } // Name returns name of the plugin. It is used in logs, etc. func (pl *VolumeZone) Name() string { return Name"} {"_id":"doc-en-kubernetes-435ebca1e5327f524a24a0ad2a8bf58feff57417d91e5f9444b7c8e82ddd0000","title":"","text":"for _, pvTopology := range podPVTopologies { v, ok := node.Labels[pvTopology.key] if !ok { // if we can't match the beta label, try to match pv's beta label with node's ga label v, ok = node.Labels[translateToGALabel(pvTopology.key)] } if !ok || !pvTopology.values.Has(v) { logger.V(10).Info(\"Won't schedule pod onto node due to volume (mismatch on label key)\", \"pod\", klog.KObj(pod), \"node\", klog.KObj(node), \"PV\", klog.KRef(\"\", pvTopology.pvName), \"PVLabelKey\", pvTopology.key) return framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonConflict)"} {"_id":"doc-en-kubernetes-5559440b17164285c81092a898435cca496fae09528cabdddab23e8da37ee36e","title":"","text":"}, wantFilterStatus: framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonConflict), }, { name: \"pv with beta label,node with ga label, matched\", Pod: createPodWithVolume(\"pod_1\", \"Vol_1\", \"PVC_1\"), Node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: \"host1\", Labels: map[string]string{ v1.LabelTopologyZone: \"us-west1-a\", }, }, }, }, { name: \"pv with beta label,node with ga label, don't match\", Pod: createPodWithVolume(\"pod_1\", \"vol_1\", \"PVC_1\"), Node: &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: \"host1\", Labels: map[string]string{ v1.LabelTopologyZone: \"us-west1-b\", }, }, }, wantFilterStatus: framework.NewStatus(framework.UnschedulableAndUnresolvable, ErrReasonConflict), }, } for _, test := range tests {"} {"_id":"doc-en-kubernetes-2b4aa248712f480c0dab5669f7674be6e9d00336759320f01a4885d559c87b48","title":"","text":"return } // enforce a timeout of at most requestTimeoutUpperBound (34s) or less if the user-provided // timeout inside the parent context is lower than requestTimeoutUpperBound. ctx, cancel := context.WithTimeout(ctx, requestTimeoutUpperBound) defer cancel() // DELETECOLLECTION can be a lengthy operation, // we should not impose any 34s timeout here. // NOTE: This is similar to LIST which does not enforce a 34s timeout. ctx = request.WithNamespace(ctx, namespace) outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)"} {"_id":"doc-en-kubernetes-ea3f93c22e85eb100686945bd49623075a014cb26c95e178cae061c7d7046841","title":"","text":"\"context\" \"io\" \"net/http\" \"net/http/httptest\" \"strings\" \"sync/atomic\" \"testing\" metainternalversion \"k8s.io/apimachinery/pkg/apis/meta/internalversion\" metainternalversionscheme \"k8s.io/apimachinery/pkg/apis/meta/internalversion/scheme\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\""} {"_id":"doc-en-kubernetes-bf5382cc07ed99f34657e2ec4348bc32d7da90db9d2f144ebeefe5c990c7c308","title":"","text":"auditapis \"k8s.io/apiserver/pkg/apis/audit\" \"k8s.io/apiserver/pkg/audit\" \"k8s.io/apiserver/pkg/endpoints/handlers/negotiation\" \"k8s.io/apiserver/pkg/registry/rest\" \"k8s.io/utils/pointer\" )"} {"_id":"doc-en-kubernetes-b50de18301928dbe26671b7b40ec6a015fd27cf92df4af3789d1a9c7af844aa6","title":"","text":"}) } } func TestDeleteCollectionWithNoContextDeadlineEnforced(t *testing.T) { var invokedGot, hasDeadlineGot int32 fakeDeleterFn := func(ctx context.Context, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions, _ *metainternalversion.ListOptions) (runtime.Object, error) { // we expect CollectionDeleter to be executed once atomic.AddInt32(&invokedGot, 1) // we don't expect any context deadline to be set if _, hasDeadline := ctx.Deadline(); hasDeadline { atomic.AddInt32(&hasDeadlineGot, 1) } return nil, nil } // do the minimum setup to ensure that it gets as far as CollectionDeleter scope := &RequestScope{ Namer: &mockNamer{}, Serializer: &fakeSerializer{ serializer: runtime.NewCodec(runtime.NoopEncoder{}, runtime.NoopDecoder{}), }, } handler := DeleteCollection(fakeCollectionDeleterFunc(fakeDeleterFn), false, scope, nil) request, err := http.NewRequest(\"GET\", \"/test\", nil) if err != nil { t.Fatalf(\"unexpected error: %v\", err) } // the request context should not have any deadline by default if _, hasDeadline := request.Context().Deadline(); hasDeadline { t.Fatalf(\"expected request context to not have any deadline\") } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) if atomic.LoadInt32(&invokedGot) != 1 { t.Errorf(\"expected collection deleter to be invoked\") } if atomic.LoadInt32(&hasDeadlineGot) > 0 { t.Errorf(\"expected context to not have any deadline\") } } type fakeCollectionDeleterFunc func(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) func (f fakeCollectionDeleterFunc) DeleteCollection(ctx context.Context, deleteValidation rest.ValidateObjectFunc, options *metav1.DeleteOptions, listOptions *metainternalversion.ListOptions) (runtime.Object, error) { return f(ctx, deleteValidation, options, listOptions) } type fakeSerializer struct { serializer runtime.Serializer } func (n *fakeSerializer) SupportedMediaTypes() []runtime.SerializerInfo { return []runtime.SerializerInfo{ { MediaType: \"application/json\", MediaTypeType: \"application\", MediaTypeSubType: \"json\", }, } } func (n *fakeSerializer) EncoderForVersion(serializer runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder { return n.serializer } func (n *fakeSerializer) DecoderToVersion(serializer runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder { return n.serializer } "} {"_id":"doc-en-kubernetes-cebafc7d6862e9a6f340045407e21140af838e9fad923c40a3af2265dc3ae54b","title":"","text":"var _ storagelisters.CSINodeLister = CSINodeLister{} // CSINodeLister declares a storagev1.CSINode type for testing. type CSINodeLister storagev1.CSINode type CSINodeLister []storagev1.CSINode // Get returns a fake CSINode object. func (n CSINodeLister) Get(name string) (*storagev1.CSINode, error) { csiNode := storagev1.CSINode(n) return &csiNode, nil for _, cn := range n { if cn.Name == name { return &cn, nil } } return nil, fmt.Errorf(\"csiNode %q not found\", name) } // List lists all CSINodes in the indexer."} {"_id":"doc-en-kubernetes-8c5b87a6ba662e105708ed623270495140e2607923785ba9360e3dd20c782d4e","title":"","text":"return fmt.Errorf(\"looking up provisioner name for volume %v: %w\", vol, err) } if !isCSIMigrationOn(csiNode, inTreeProvisionerName) { csiNodeName := \"\" if csiNode != nil { csiNodeName = csiNode.Name } klog.V(5).InfoS(\"CSI Migration is not enabled for provisioner\", \"provisioner\", inTreeProvisionerName, \"pod\", klog.KObj(pod), \"csiNode\", csiNode.Name) \"pod\", klog.KObj(pod), \"csiNode\", csiNodeName) return nil } // Do translation for the in-tree volume."} {"_id":"doc-en-kubernetes-5e997b92b86fbe522a89327b7fd9a167373fa85d3b79ddfa05e6b976394415e5","title":"","text":"wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded), }, { newPod: inTreeInlineVolPod, existingPods: []*v1.Pod{inTreeTwoVolPod}, filterName: \"csi\", maxVols: 2, driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName}, migrationEnabled: true, limitSource: \"node\", test: \"nil csi node\", }, { newPod: pendingVolumePod, existingPods: []*v1.Pod{inTreeTwoVolPod}, filterName: \"csi\","} {"_id":"doc-en-kubernetes-769c7e2b94d3640ba05b827e98397c0ebcacb35c61460ed24c9a40e8aa47f42b","title":"","text":"} pvLister = append(pvLister, pv) } } return pvLister }"} {"_id":"doc-en-kubernetes-790c4dcc6aa026cafe061542a58e915e450d34419646f2b24066329ff16c4d33","title":"","text":"} func getFakeCSINodeLister(csiNode *storagev1.CSINode) fakeframework.CSINodeLister { csiNodeLister := fakeframework.CSINodeLister{} if csiNode != nil { return fakeframework.CSINodeLister(*csiNode) csiNodeLister = append(csiNodeLister, *csiNode.DeepCopy()) } return fakeframework.CSINodeLister{} return csiNodeLister } func getNodeWithPodAndVolumeLimits(limitSource string, pods []*v1.Pod, limit int64, driverNames ...string) (*framework.NodeInfo, *storagev1.CSINode) {"} {"_id":"doc-en-kubernetes-39daf1c7347d2179e50fa471e2a17b4203996c735ea3dfa0e1a7389d2af78460","title":"","text":"initCSINode := func() { csiNode = &storagev1.CSINode{ ObjectMeta: metav1.ObjectMeta{Name: \"csi-node-for-max-pd-test-1\"}, ObjectMeta: metav1.ObjectMeta{Name: \"node-for-max-pd-test-1\"}, Spec: storagev1.CSINodeSpec{ Drivers: []storagev1.CSINodeDriver{}, },"} {"_id":"doc-en-kubernetes-fe23ca6e9b76b71b1b04d456fb2a96098a537b6f213ac77da6e1d942cefe1031","title":"","text":"API Server using the current Aggregator [Conformance]' description: Ensure that the sample-apiserver code from 1.17 and compiled against 1.17 will work on the current Aggregator/API-Server. release: v1.17, v1.21 release: v1.17, v1.21, v1.27 file: test/e2e/apimachinery/aggregator.go - testname: Custom Resource Definition Conversion Webhook, convert mixed version list codename: '[sig-api-machinery] CustomResourceConversionWebhook [Privileged:ClusterAdmin]"} {"_id":"doc-en-kubernetes-6a0b2b86c775f0e10ad95799d399f748c6ac18a0c376a39d2be48fcf1feb758c","title":"","text":"apierrors \"k8s.io/apimachinery/pkg/api/errors\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/intstr\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/discovery\" clientset \"k8s.io/client-go/kubernetes\" \"k8s.io/client-go/util/retry\" apiregistrationv1 \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1\" aggregatorclient \"k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset\" rbacv1helpers \"k8s.io/kubernetes/pkg/apis/rbac/v1\" \"k8s.io/kubernetes/test/e2e/framework\" e2eauth \"k8s.io/kubernetes/test/e2e/framework/auth\" e2edeployment \"k8s.io/kubernetes/test/e2e/framework/deployment\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" imageutils \"k8s.io/kubernetes/test/utils/image\""} {"_id":"doc-en-kubernetes-5ffe127a13f91aaca8925cf7ae76920f4f8e68f9598f97c1eb965098beb772fe","title":"","text":"const ( aggregatorServicePort = 7443 apiServiceRetryPeriod = 1 * time.Second apiServiceRetryTimeout = 2 * time.Minute ) var _ = SIGDescribe(\"Aggregator\", func() {"} {"_id":"doc-en-kubernetes-18a4e5fdff2645fe6d6a2932d6e3108dfcd90be510fc395e7c0572ee32049a7a","title":"","text":"}) /* Release: v1.17, v1.21 Release: v1.17, v1.21, v1.27 Testname: aggregator-supports-the-sample-apiserver Description: Ensure that the sample-apiserver code from 1.17 and compiled against 1.17 will work on the current Aggregator/API-Server."} {"_id":"doc-en-kubernetes-d1dc933f628c472e25be81a4d632439cddf828f88bb68acaa42197cc84d74563","title":"","text":"_, err := client.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating secret %s in namespace %s\", secretName, namespace) // kubectl create -f clusterrole.yaml _, err = client.RbacV1().ClusterRoles().Create(ctx, &rbacv1.ClusterRole{ if e2eauth.IsRBACEnabled(ctx, client.RbacV1()) { // kubectl create -f clusterrole.yaml _, err = client.RbacV1().ClusterRoles().Create(ctx, &rbacv1.ClusterRole{ ObjectMeta: metav1.ObjectMeta{Name: \"sample-apiserver-reader\"}, Rules: []rbacv1.PolicyRule{ rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(\"\").Resources(\"namespaces\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(\"admissionregistration.k8s.io\").Resources(\"*\").RuleOrDie(), }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role %s\", \"sample-apiserver-reader\") ObjectMeta: metav1.ObjectMeta{Name: \"sample-apiserver-reader\"}, Rules: []rbacv1.PolicyRule{ rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(\"\").Resources(\"namespaces\").RuleOrDie(), rbacv1helpers.NewRule(\"get\", \"list\", \"watch\").Groups(\"admissionregistration.k8s.io\").Resources(\"*\").RuleOrDie(), }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role %s\", \"sample-apiserver-reader\") _, err = client.RbacV1().ClusterRoleBindings().Create(ctx, &rbacv1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler:\" + namespace + \":sample-apiserver-reader\", }, RoleRef: rbacv1.RoleRef{ APIGroup: \"rbac.authorization.k8s.io\", Kind: \"ClusterRole\", Name: \"sample-apiserver-reader\", }, Subjects: []rbacv1.Subject{ { APIGroup: \"\", Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, _, err = client.RbacV1().ClusterRoleBindings().Create(ctx, &rbacv1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler:\" + namespace + \":sample-apiserver-reader\", }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role binding %s\", \"wardler:\"+namespace+\":sample-apiserver-reader\") RoleRef: rbacv1.RoleRef{ APIGroup: \"rbac.authorization.k8s.io\", Kind: \"ClusterRole\", Name: \"sample-apiserver-reader\", }, Subjects: []rbacv1.Subject{ { APIGroup: \"\", Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role binding %s\", \"wardler:\"+namespace+\":sample-apiserver-reader\") // kubectl create -f authDelegator.yaml _, err = client.RbacV1().ClusterRoleBindings().Create(ctx, &rbacv1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler:\" + namespace + \":auth-delegator\", }, RoleRef: rbacv1.RoleRef{ APIGroup: \"rbac.authorization.k8s.io\", Kind: \"ClusterRole\", Name: \"system:auth-delegator\", }, Subjects: []rbacv1.Subject{ { APIGroup: \"\", Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, // kubectl create -f authDelegator.yaml _, err = client.RbacV1().ClusterRoleBindings().Create(ctx, &rbacv1.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler:\" + namespace + \":auth-delegator\", }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role binding %s\", \"wardler:\"+namespace+\":auth-delegator\") RoleRef: rbacv1.RoleRef{ APIGroup: \"rbac.authorization.k8s.io\", Kind: \"ClusterRole\", Name: \"system:auth-delegator\", }, Subjects: []rbacv1.Subject{ { APIGroup: \"\", Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating cluster role binding %s\", \"wardler:\"+namespace+\":auth-delegator\") } // kubectl create -f deploy.yaml deploymentName := \"sample-apiserver-deployment\""} {"_id":"doc-en-kubernetes-a5c9ba16ec9c375f795c3875dc5ce6700e621dd0fcc96fadbf1b1c608f11a09b","title":"","text":"_, err = client.CoreV1().ServiceAccounts(namespace).Create(ctx, sa, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating service account %s in namespace %s\", \"sample-apiserver\", namespace) // kubectl create -f auth-reader.yaml _, err = client.RbacV1().RoleBindings(\"kube-system\").Create(ctx, &rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler-auth-reader\", Annotations: map[string]string{ rbacv1.AutoUpdateAnnotationKey: \"true\", if e2eauth.IsRBACEnabled(ctx, client.RbacV1()) { // kubectl create -f auth-reader.yaml _, err = client.RbacV1().RoleBindings(\"kube-system\").Create(ctx, &rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: \"wardler-auth-reader\", Annotations: map[string]string{ rbacv1.AutoUpdateAnnotationKey: \"true\", }, }, }, RoleRef: rbacv1.RoleRef{ APIGroup: \"\", Kind: \"Role\", Name: \"extension-apiserver-authentication-reader\", }, Subjects: []rbacv1.Subject{ { Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, RoleRef: rbacv1.RoleRef{ APIGroup: \"\", Kind: \"Role\", Name: \"extension-apiserver-authentication-reader\", }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating role binding %s in namespace %s\", \"wardler-auth-reader\", \"kube-system\") Subjects: []rbacv1.Subject{ { Kind: \"ServiceAccount\", Name: \"default\", Namespace: namespace, }, }, }, metav1.CreateOptions{}) framework.ExpectNoError(err, \"creating role binding %s in namespace %s\", \"wardler-auth-reader\", \"kube-system\") } // Wait for the extension apiserver to be up and healthy // kubectl get deployments -n && status == Running"} {"_id":"doc-en-kubernetes-960bb1fa776e1f8069524ddf61021142a7ef50b43f1f2c358995103b6a7f971c","title":"","text":"Service: &apiregistrationv1.ServiceReference{ Namespace: namespace, Name: \"sample-api\", Port: pointer.Int32Ptr(aggregatorServicePort), Port: pointer.Int32(aggregatorServicePort), }, Group: \"wardle.example.com\", Version: \"v1alpha1\","} {"_id":"doc-en-kubernetes-e003263995fd799f3eaddd35909cb5f10993a3ef18e1047a801fb825b214e4ae","title":"","text":"framework.Failf(\"Unable to find v1alpha1.wardle.example.com in APIServiceList\") } // As the APIService doesn't have any labels currently set we need to // set one so that we can select it later when we call deleteCollection ginkgo.By(\"Adding a label to the APIService\") apiServiceName := \"v1alpha1.wardle.example.com\" apiServiceClient := aggrclient.ApiregistrationV1().APIServices() apiServiceLabel := map[string]string{\"e2e-apiservice\": \"patched\"} apiServiceLabelSelector := labels.SelectorFromSet(apiServiceLabel).String() apiServicePatch, err := json.Marshal(map[string]interface{}{ \"metadata\": map[string]interface{}{ \"labels\": apiServiceLabel, }, }) framework.ExpectNoError(err, \"failed to Marshal APIService JSON patch\") _, err = apiServiceClient.Patch(ctx, apiServiceName, types.StrategicMergePatchType, []byte(apiServicePatch), metav1.PatchOptions{}) framework.ExpectNoError(err, \"failed to patch APIService\") patchedApiService, err := apiServiceClient.Get(ctx, apiServiceName, metav1.GetOptions{}) framework.ExpectNoError(err, \"Unable to retrieve api service %s\", apiServiceName) framework.Logf(\"APIService labels: %v\", patchedApiService.Labels) ginkgo.By(\"Updating APIService Status\") var updatedStatus, wardle *apiregistrationv1.APIService err = retry.RetryOnConflict(retry.DefaultRetry, func() error { var statusToUpdate *apiregistrationv1.APIService statusContent, err = restClient.Get(). AbsPath(\"/apis/apiregistration.k8s.io/v1/apiservices/v1alpha1.wardle.example.com/status\"). SetHeader(\"Accept\", \"application/json\").DoRaw(ctx) framework.ExpectNoError(err, \"No response for .../apiservices/v1alpha1.wardle.example.com/status. Error: %v\", err) err = json.Unmarshal([]byte(statusContent), &statusToUpdate) framework.ExpectNoError(err, \"Failed to process statusContent: %v | err: %v \", string(statusContent), err) statusToUpdate.Status.Conditions = append(statusToUpdate.Status.Conditions, apiregistrationv1.APIServiceCondition{ Type: \"StatusUpdated\", Status: \"True\", Reason: \"E2E\", Message: \"Set from e2e test\", }) updatedStatus, err = apiServiceClient.UpdateStatus(ctx, statusToUpdate, metav1.UpdateOptions{}) return err }) framework.ExpectNoError(err, \"Failed to update status. %v\", err) framework.Logf(\"updatedStatus.Conditions: %#v\", updatedStatus.Status.Conditions) ginkgo.By(\"Confirm that v1alpha1.wardle.example.com /status was updated\") statusContent, err = restClient.Get(). AbsPath(\"/apis/apiregistration.k8s.io/v1/apiservices/v1alpha1.wardle.example.com/status\"). SetHeader(\"Accept\", \"application/json\").DoRaw(ctx) framework.ExpectNoError(err, \"No response for .../apiservices/v1alpha1.wardle.example.com/status. Error: %v\", err) err = json.Unmarshal([]byte(statusContent), &wardle) framework.ExpectNoError(err, \"Failed to process statusContent: %v | err: %v \", string(statusContent), err) foundUpdatedStatusCondition := false for _, cond := range wardle.Status.Conditions { if cond.Type == \"StatusUpdated\" && cond.Reason == \"E2E\" && cond.Message == \"Set from e2e test\" { framework.Logf(\"Found APIService %v with Labels: %v & Condition: %v\", wardle.ObjectMeta.Name, wardle.Labels, cond) foundUpdatedStatusCondition = true break } else { framework.Logf(\"Observed APIService %v with Labels: %v & Condition: %v\", wardle.ObjectMeta.Name, wardle.Labels, cond) } } framework.ExpectEqual(foundUpdatedStatusCondition, true, \"The updated status condition was not found. %#v\", wardle.Status.Conditions) framework.Logf(\"Found updated status condition for %s\", wardle.ObjectMeta.Name) ginkgo.By(fmt.Sprintf(\"Replace APIService %s\", apiServiceName)) var updatedApiService *apiregistrationv1.APIService err = retry.RetryOnConflict(retry.DefaultRetry, func() error { currentApiService, err := apiServiceClient.Get(ctx, apiServiceName, metav1.GetOptions{}) framework.ExpectNoError(err, \"Unable to get APIService %s\", apiServiceName) currentApiService.Labels = map[string]string{ apiServiceName: \"updated\", } updatedApiService, err = apiServiceClient.Update(ctx, currentApiService, metav1.UpdateOptions{}) return err }) framework.ExpectNoError(err) framework.ExpectEqual(updatedApiService.Labels[apiServiceName], \"updated\", \"should have the updated label but have %q\", updatedApiService.Labels[apiServiceName]) framework.Logf(\"Found updated apiService label for %q\", apiServiceName) // kubectl delete flunder test-flunder ginkgo.By(fmt.Sprintf(\"Delete APIService %q\", flunderName)) err = dynamicClient.Delete(ctx, flunderName, metav1.DeleteOptions{}) validateErrorWithDebugInfo(ctx, f, err, pods, \"deleting flunders(%v) using dynamic client\", unstructuredList.Items)"} {"_id":"doc-en-kubernetes-57f2bb84f9dc82a8e86c4e48548cba0b0964410b02a0f3e9faba319a7b1d9210","title":"","text":"framework.Failf(\"failed to get back the correct deleted flunders list %v from the dynamic client\", unstructuredList) } ginkgo.By(\"Recreating test-flunder before removing endpoint via deleteCollection\") jsonFlunder, err = json.Marshal(testFlunder) framework.ExpectNoError(err, \"marshalling test-flunder for create using dynamic client\") unstruct = &unstructured.Unstructured{} err = unstruct.UnmarshalJSON(jsonFlunder) framework.ExpectNoError(err, \"unmarshalling test-flunder as unstructured for create using dynamic client\") _, err = dynamicClient.Create(ctx, unstruct, metav1.CreateOptions{}) framework.ExpectNoError(err, \"listing flunders using dynamic client\") // kubectl get flunders unstructuredList, err = dynamicClient.List(ctx, metav1.ListOptions{}) framework.ExpectNoError(err, \"listing flunders using dynamic client\") if len(unstructuredList.Items) != 1 { framework.Failf(\"failed to get back the correct flunders list %v from the dynamic client\", unstructuredList) } ginkgo.By(\"Read v1alpha1.wardle.example.com /status before patching it\") statusContent, err = restClient.Get(). AbsPath(\"/apis/apiregistration.k8s.io/v1/apiservices/v1alpha1.wardle.example.com/status\"). SetHeader(\"Accept\", \"application/json\").DoRaw(ctx) framework.ExpectNoError(err, \"No response for .../apiservices/v1alpha1.wardle.example.com/status. Error: %v\", err) wardle.Reset() err = json.Unmarshal([]byte(statusContent), &wardle) framework.ExpectNoError(err, \"Failed to process statusContent: %v | err: %v \", string(statusContent), err) ginkgo.By(\"Patch APIService Status\") patch := map[string]interface{}{ \"status\": map[string]interface{}{ \"conditions\": append(wardle.Status.Conditions, apiregistrationv1.APIServiceCondition{ Type: \"StatusPatched\", Status: \"True\", Reason: \"E2E\", Message: \"Set by e2e test\", }), }, } payload, err := json.Marshal(patch) framework.ExpectNoError(err, \"Failed to marshal JSON. %v\", err) _, err = restClient.Patch(types.MergePatchType). AbsPath(\"/apis/apiregistration.k8s.io/v1/apiservices/v1alpha1.wardle.example.com/status\"). SetHeader(\"Accept\", \"application/json\"). Body([]byte(payload)). DoRaw(ctx) framework.ExpectNoError(err, \"Patch failed for .../apiservices/v1alpha1.wardle.example.com/status. Error: %v\", err) ginkgo.By(\"Confirm that v1alpha1.wardle.example.com /status was patched\") statusContent, err = restClient.Get(). AbsPath(\"/apis/apiregistration.k8s.io/v1/apiservices/v1alpha1.wardle.example.com/status\"). SetHeader(\"Accept\", \"application/json\").DoRaw(ctx) framework.ExpectNoError(err, \"No response for .../apiservices/v1alpha1.wardle.example.com/status. Error: %v\", err) wardle.Reset() err = json.Unmarshal([]byte(statusContent), &wardle) framework.ExpectNoError(err, \"Failed to process statusContent: %v | err: %v \", string(statusContent), err) foundPatchedStatusCondition := false for _, cond := range wardle.Status.Conditions { if cond.Type == \"StatusPatched\" && cond.Reason == \"E2E\" && cond.Message == \"Set by e2e test\" { framework.Logf(\"Found APIService %v with Labels: %v & Conditions: %v\", wardle.ObjectMeta.Name, wardle.Labels, cond) foundPatchedStatusCondition = true break } else { framework.Logf(\"Observed APIService %v with Labels: %v & Conditions: %v\", wardle.ObjectMeta.Name, wardle.Labels, cond) } } framework.ExpectEqual(foundPatchedStatusCondition, true, \"The patched status condition was not found. %#v\", wardle.Status.Conditions) framework.Logf(\"Found patched status condition for %s\", wardle.ObjectMeta.Name) ginkgo.By(fmt.Sprintf(\"APIService deleteCollection with labelSelector: %q\", apiServiceLabelSelector)) err = aggrclient.ApiregistrationV1().APIServices().DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: apiServiceLabelSelector}) framework.ExpectNoError(err, \"Unable to delete apiservice %s\", apiServiceName) ginkgo.By(\"Confirm that the generated APIService has been deleted\") err = wait.PollImmediate(apiServiceRetryPeriod, apiServiceRetryTimeout, checkApiServiceListQuantity(ctx, aggrclient, apiServiceLabelSelector, 0)) framework.ExpectNoError(err, \"failed to count the required APIServices\") framework.Logf(\"APIService %s has been deleted.\", apiServiceName) cleanTest(ctx, client, aggrclient, namespace) }"} {"_id":"doc-en-kubernetes-2f1a3a28906780f771bdd8fb6f7aca0f061903df34715a93d6379c1bfc1b2615","title":"","text":"} return fmt.Sprintf(\"%s-%d\", base, id) } func checkApiServiceListQuantity(ctx context.Context, aggrclient *aggregatorclient.Clientset, label string, quantity int) func() (bool, error) { return func() (bool, error) { var err error framework.Logf(\"Requesting list of APIServices to confirm quantity\") list, err := aggrclient.ApiregistrationV1().APIServices().List(ctx, metav1.ListOptions{LabelSelector: label}) if err != nil { return false, err } if len(list.Items) != quantity { return false, err } framework.Logf(\"Found %d APIService with label %q\", quantity, label) return true, nil } } "} {"_id":"doc-en-kubernetes-8ca30b6fe0a058f21d123edb518016758be1d4b1ae4725a6ffaac453bbd91ddd","title":"","text":"isMigratedOnNode := mpaSet.Has(pluginName) if isMigratedOnNode { installed := false driverName, err := csiMigratedPluginManager.GetCSINameFromInTreeName(pluginName) if err != nil { return isMigratedOnNode, err } for _, driver := range csiNode.Spec.Drivers { if driver.Name == driverName { installed = true break } } if !installed { return true, fmt.Errorf(\"in-tree plugin %s is migrated on node %s but driver %s is not installed\", pluginName, string(nodeName), driverName) } } return isMigratedOnNode, nil }"} {"_id":"doc-en-kubernetes-6112970c4a8d2d7086c631f704cab8c762d14fe080d9b66b81123df8de744fd8","title":"","text":" /* Copyright 2017 The Kubernetes Authors. 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. */ package util import ( \"os\" \"reflect\" \"strings\" \"testing\" \"time\" \"github.com/google/go-cmp/cmp\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" kubetypes \"k8s.io/apimachinery/pkg/types\" \"k8s.io/client-go/informers\" csitrans \"k8s.io/csi-translation-lib\" fakeframework \"k8s.io/kubernetes/pkg/scheduler/framework/fake\" \"k8s.io/kubernetes/pkg/volume/csimigration\" \"k8s.io/kubernetes/pkg/volume/fc\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/kubernetes/fake\" utiltesting \"k8s.io/client-go/util/testing\" \"k8s.io/kubernetes/pkg/volume\" volumetest \"k8s.io/kubernetes/pkg/volume/testing\" ) const ( testHostName = \"test-hostname\" socketPath = \"/var/run/kmsplugin\" migratedVolume = \"migrated-volume-name\" nonMigratedVolume = \"non-migrated-volume-name\" testNodeName = \"test-node-name\" ) var ( dirOrCreate = v1.HostPathType(v1.HostPathDirectoryOrCreate) nodeName = kubetypes.NodeName(testNodeName) hostPath = &v1.HostPathVolumeSource{ Path: socketPath, Type: &dirOrCreate, } migratedObjectReference = v1.ObjectReference{Namespace: \"default\", Name: \"migrated-pvc\"} nonMigratedObjectReference = v1.ObjectReference{Namespace: \"default\", Name: \"non-migrated-pvc\"} fsVolumeMode = new(v1.PersistentVolumeMode) ) type vaTest struct { desc string createNodeName kubetypes.NodeName pod *v1.Pod wantVolume *v1.Volume wantPersistentVolume *v1.PersistentVolume wantErrorMessage string } func Test_CreateVolumeSpec(t *testing.T) { for _, test := range []vaTest{ { desc: \"inline volume type that does not support csi migration\", createNodeName: nodeName, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"kube-apiserver\", Namespace: \"default\", }, Spec: v1.PodSpec{ Volumes: []v1.Volume{ { Name: migratedVolume, VolumeSource: v1.VolumeSource{ HostPath: hostPath, }, }, }, }, }, wantVolume: &v1.Volume{ Name: migratedVolume, VolumeSource: v1.VolumeSource{ HostPath: hostPath, }, }, }, { desc: \"inline volume type that supports csi migration\", createNodeName: nodeName, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"kube-apiserver\", Namespace: \"default\", }, Spec: v1.PodSpec{ Volumes: []v1.Volume{ { Name: migratedVolume, VolumeSource: v1.VolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: \"test-disk\", FSType: \"ext4\", Partition: 0, ReadOnly: false, }, }, }, }, }, }, wantPersistentVolume: &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: \"pd.csi.storage.gke.io-test-disk\", }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ CSI: &v1.CSIPersistentVolumeSource{ Driver: \"pd.csi.storage.gke.io\", VolumeHandle: \"projects/UNSPECIFIED/zones/UNSPECIFIED/disks/test-disk\", FSType: \"ext4\", ReadOnly: false, VolumeAttributes: map[string]string{\"partition\": \"\"}, }, }, AccessModes: []v1.PersistentVolumeAccessMode{\"ReadWriteOnce\"}, VolumeMode: fsVolumeMode, }, }, }, { desc: \"pv type that does not support csi migration\", createNodeName: nodeName, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"kube-apiserver\", Namespace: \"default\", }, Spec: v1.PodSpec{ Volumes: []v1.Volume{ { Name: nonMigratedVolume, VolumeSource: v1.VolumeSource{ PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: \"non-migrated-pvc\", ReadOnly: false, }, }, }, }, }, }, wantPersistentVolume: &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: nonMigratedVolume, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ ScaleIO: &v1.ScaleIOPersistentVolumeSource{}, }, ClaimRef: &nonMigratedObjectReference, }, }, }, { desc: \"pv type that supports csi migration\", createNodeName: nodeName, pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"kube-apiserver\", Namespace: \"default\", }, Spec: v1.PodSpec{ Volumes: []v1.Volume{ { Name: migratedVolume, VolumeSource: v1.VolumeSource{ PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: \"migrated-pvc\", ReadOnly: false, }, }, }, }, }, }, wantPersistentVolume: &v1.PersistentVolume{ ObjectMeta: metav1.ObjectMeta{ Name: migratedVolume, }, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ CSI: &v1.CSIPersistentVolumeSource{ Driver: \"pd.csi.storage.gke.io\", VolumeHandle: \"projects/UNSPECIFIED/zones/UNSPECIFIED/disks/test-disk\", FSType: \"ext4\", ReadOnly: false, VolumeAttributes: map[string]string{\"partition\": \"\"}, }, }, ClaimRef: &migratedObjectReference, }, }, }, { desc: \"CSINode not found for a volume type that supports csi migration\", createNodeName: kubetypes.NodeName(\"another-node\"), pod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: \"kube-apiserver\", Namespace: \"default\", }, Spec: v1.PodSpec{ Volumes: []v1.Volume{ { Name: migratedVolume, VolumeSource: v1.VolumeSource{ PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{ ClaimName: \"migrated-pvc\", ReadOnly: false, }, }, }, }, }, }, wantErrorMessage: \"csiNode \"another-node\" not found\", }, } { t.Run(test.desc, func(t *testing.T) { plugMgr, intreeToCSITranslator, csiTranslator, pvLister, pvcLister := setup(testNodeName, t) actualSpec, err := CreateVolumeSpec(test.pod.Spec.Volumes[0], test.pod, test.createNodeName, plugMgr, pvcLister, pvLister, intreeToCSITranslator, csiTranslator) if actualSpec == nil && (test.wantPersistentVolume != nil || test.wantVolume != nil) { t.Errorf(\"got volume spec is nil\") } if (len(test.wantErrorMessage) > 0 && err == nil) || (err != nil && !strings.Contains(err.Error(), test.wantErrorMessage)) { t.Errorf(\"got err %v, want err with message %v\", err, test.wantErrorMessage) } if test.wantPersistentVolume != nil { if actualSpec.PersistentVolume == nil { t.Errorf(\"gotVolumeWithCSIMigration is nil\") } gotVolumeWithCSIMigration := *actualSpec.PersistentVolume if gotVolumeWithCSIMigration.Name != test.wantPersistentVolume.Name { t.Errorf(\"got volume name is %v, want volume name is %v\", gotVolumeWithCSIMigration.Name, test.wantPersistentVolume.Name) } if !reflect.DeepEqual(gotVolumeWithCSIMigration.Spec, test.wantPersistentVolume.Spec) { t.Errorf(\"got volume.Spec and want.Spec diff is %s\", cmp.Diff(gotVolumeWithCSIMigration.Spec, test.wantPersistentVolume.Spec)) } } if test.wantVolume != nil { if actualSpec.Volume == nil { t.Errorf(\"gotVolume is nil\") } gotVolume := *actualSpec.Volume if !reflect.DeepEqual(gotVolume, *test.wantVolume) { t.Errorf(\"got volume and want diff is %s\", cmp.Diff(gotVolume, test.wantVolume)) } } }) } } func setup(nodeName string, t *testing.T) (*volume.VolumePluginMgr, csimigration.PluginManager, csitrans.CSITranslator, fakeframework.PersistentVolumeLister, fakeframework.PersistentVolumeClaimLister) { tmpDir, err := utiltesting.MkTmpdir(\"csi-test\") if err != nil { t.Fatalf(\"can't make a temp dir: %v\", err) } defer os.RemoveAll(tmpDir) *fsVolumeMode = v1.PersistentVolumeFilesystem csiTranslator := csitrans.New() intreeToCSITranslator := csimigration.NewPluginManager(csiTranslator, utilfeature.DefaultFeatureGate) kubeClient := fake.NewSimpleClientset() factory := informers.NewSharedInformerFactory(kubeClient, time.Minute) csiDriverInformer := factory.Storage().V1().CSIDrivers() csiDriverLister := csiDriverInformer.Lister() volumeAttachmentInformer := factory.Storage().V1().VolumeAttachments() volumeAttachmentLister := volumeAttachmentInformer.Lister() plugMgr := &volume.VolumePluginMgr{} fakeAttachDetachVolumeHost := volumetest.NewFakeAttachDetachVolumeHostWithCSINodeName(t, tmpDir, kubeClient, fc.ProbeVolumePlugins(), nodeName, csiDriverLister, volumeAttachmentLister, ) plugMgr.Host = fakeAttachDetachVolumeHost pvLister := fakeframework.PersistentVolumeLister{ { ObjectMeta: metav1.ObjectMeta{Name: migratedVolume}, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ PDName: \"test-disk\", FSType: \"ext4\", Partition: 0, ReadOnly: false, }, }, ClaimRef: &migratedObjectReference, }, }, { ObjectMeta: metav1.ObjectMeta{Name: nonMigratedVolume}, Spec: v1.PersistentVolumeSpec{ PersistentVolumeSource: v1.PersistentVolumeSource{ ScaleIO: &v1.ScaleIOPersistentVolumeSource{}, }, ClaimRef: &nonMigratedObjectReference, }, }, } pvcLister := fakeframework.PersistentVolumeClaimLister{ { ObjectMeta: metav1.ObjectMeta{Name: \"migrated-pvc\", Namespace: \"default\"}, Spec: v1.PersistentVolumeClaimSpec{VolumeName: migratedVolume}, Status: v1.PersistentVolumeClaimStatus{ Phase: v1.ClaimBound, }, }, { ObjectMeta: metav1.ObjectMeta{Name: \"non-migrated-pvc\", Namespace: \"default\"}, Spec: v1.PersistentVolumeClaimSpec{VolumeName: nonMigratedVolume}, Status: v1.PersistentVolumeClaimStatus{ Phase: v1.ClaimBound, }, }, } return plugMgr, intreeToCSITranslator, csiTranslator, pvLister, pvcLister } "} {"_id":"doc-en-kubernetes-c344af00490ae519ccd492bdb21d93599190b242dd0cff0c34c4819eb2153983","title":"","text":"\"fmt\" \"net\" \"path/filepath\" \"strings\" \"sync\" \"testing\" \"time\" authenticationv1 \"k8s.io/api/authentication/v1\" v1 \"k8s.io/api/core/v1\" storagev1 \"k8s.io/api/storage/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/wait\" \"k8s.io/client-go/informers\" clientset \"k8s.io/client-go/kubernetes\""} {"_id":"doc-en-kubernetes-92107579e54d96400b617b596f54e43e809d8c4aca2e3eed9f48d3018b8306a8","title":"","text":"\"k8s.io/client-go/tools/cache\" \"k8s.io/client-go/tools/record\" cloudprovider \"k8s.io/cloud-provider\" csilibplugins \"k8s.io/csi-translation-lib/plugins\" proxyutil \"k8s.io/kubernetes/pkg/proxy/util\" . \"k8s.io/kubernetes/pkg/volume\" \"k8s.io/kubernetes/pkg/volume/util/hostutil\""} {"_id":"doc-en-kubernetes-a16f4d0361d9022bd49314597410d9af998f54441a6dadaf8476561b0709e74f","title":"","text":"} func (f *fakeAttachDetachVolumeHost) CSINodeLister() storagelistersv1.CSINodeLister { // not needed for testing return nil csiNode := &storagev1.CSINode{ ObjectMeta: metav1.ObjectMeta{Name: f.nodeName}, Spec: storagev1.CSINodeSpec{ Drivers: []storagev1.CSINodeDriver{}, }, } enableMigrationOnNode(csiNode, csilibplugins.GCEPDInTreePluginName) return getFakeCSINodeLister(csiNode) } func enableMigrationOnNode(csiNode *storagev1.CSINode, pluginName string) { nodeInfoAnnotations := csiNode.GetAnnotations() if nodeInfoAnnotations == nil { nodeInfoAnnotations = map[string]string{} } newAnnotationSet := sets.NewString() newAnnotationSet.Insert(pluginName) nas := strings.Join(newAnnotationSet.List(), \",\") nodeInfoAnnotations[v1.MigratedPluginsAnnotationKey] = nas csiNode.Annotations = nodeInfoAnnotations } func (f *fakeAttachDetachVolumeHost) CSIDriverLister() storagelistersv1.CSIDriverLister {"} {"_id":"doc-en-kubernetes-69bd6ef272b0795b7dac35934225cd5d3cc3c94ce8906b72ef93dfa483be2c3b","title":"","text":"return f } type CSINodeLister []storagev1.CSINode // Get returns a fake CSINode object. func (n CSINodeLister) Get(name string) (*storagev1.CSINode, error) { for _, cn := range n { if cn.Name == name { return &cn, nil } } return nil, fmt.Errorf(\"csiNode %q not found\", name) } // List lists all CSINodes in the indexer. func (n CSINodeLister) List(selector labels.Selector) (ret []*storagev1.CSINode, err error) { return nil, fmt.Errorf(\"not implemented\") } func getFakeCSINodeLister(csiNode *storagev1.CSINode) CSINodeLister { csiNodeLister := CSINodeLister{} if csiNode != nil { csiNodeLister = append(csiNodeLister, *csiNode.DeepCopy()) } return csiNodeLister } func (f *fakeKubeletVolumeHost) SetKubeletError(err error) { f.mux.Lock() defer f.mux.Unlock()"} {"_id":"doc-en-kubernetes-2099499e2eeca2a944dcdaa7e99d09933ae061c8b46e2cdbe8cf911809dad3a4","title":"","text":"utilnet \"k8s.io/apimachinery/pkg/util/net\" \"k8s.io/apiserver/pkg/apis/apiserver\" egressmetrics \"k8s.io/apiserver/pkg/server/egressselector/metrics\" compbasemetrics \"k8s.io/component-base/metrics\" \"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/component-base/tracing\" \"k8s.io/klog/v2\" client \"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client\""} {"_id":"doc-en-kubernetes-1b35ae76c573aac492a08b8ae3c6dde33e87b0f197303e5e7ed08a327ba04170","title":"","text":"var directDialer utilnet.DialFunc = http.DefaultTransport.(*http.Transport).DialContext func init() { client.Metrics.RegisterMetrics(compbasemetrics.NewKubeRegistry().Registerer()) client.Metrics.RegisterMetrics(legacyregistry.Registerer()) } // EgressSelector is the map of network context type to context dialer, for network egress."} {"_id":"doc-en-kubernetes-2a1d7e8a48e3559a1d8f0969615e4f6b8a396623ff3c3c44c4bfc35fa933422d","title":"","text":"import ( \"context\" \"errors\" \"fmt\" \"net\" \"strings\""} {"_id":"doc-en-kubernetes-2b8e00eef2568c05064f873ec882fff964b71faa36d7b473684281829ce03187","title":"","text":"\"k8s.io/component-base/metrics/legacyregistry\" \"k8s.io/component-base/metrics/testutil\" testingclock \"k8s.io/utils/clock/testing\" clientmetrics \"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client/metrics\" ccmetrics \"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/common/metrics\" \"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client\" ) type fakeEgressSelection struct {"} {"_id":"doc-en-kubernetes-ca536117af8623d94b15e4e60509369d0e89bd36c6d35b1363f6a640a8ee82aa","title":"","text":"} }) } } func TestKonnectivityClientMetrics(t *testing.T) { testcases := []struct { name string metrics []string trigger func() want string }{ { name: \"stream packets\", metrics: []string{\"konnectivity_network_proxy_client_stream_packets_total\"}, trigger: func() { clientmetrics.Metrics.ObservePacket(ccmetrics.SegmentFromClient, client.PacketType_DIAL_REQ) }, want: ` # HELP konnectivity_network_proxy_client_stream_packets_total Count of packets processed, by segment and packet type (example: from_client, DIAL_REQ) # TYPE konnectivity_network_proxy_client_stream_packets_total counter konnectivity_network_proxy_client_stream_packets_total{packet_type=\"DIAL_REQ\",segment=\"from_client\"} 1 `, }, { name: \"stream errors\", metrics: []string{\"konnectivity_network_proxy_client_stream_errors_total\"}, trigger: func() { clientmetrics.Metrics.ObserveStreamError(ccmetrics.SegmentToClient, errors.New(\"example\"), client.PacketType_DIAL_RSP) }, want: ` # HELP konnectivity_network_proxy_client_stream_errors_total Count of gRPC stream errors, by segment, grpc Code, packet type. (example: from_agent, Code.Unavailable, DIAL_RSP) # TYPE konnectivity_network_proxy_client_stream_errors_total counter konnectivity_network_proxy_client_stream_errors_total{code=\"Unknown\",packet_type=\"DIAL_RSP\",segment=\"to_client\"} 1 `, }, { name: \"dial failure\", metrics: []string{\"konnectivity_network_proxy_client_dial_failure_total\"}, trigger: func() { clientmetrics.Metrics.ObserveDialFailure(clientmetrics.DialFailureTimeout) }, want: ` # HELP konnectivity_network_proxy_client_dial_failure_total Number of dial failures observed, by reason (example: remote endpoint error) # TYPE konnectivity_network_proxy_client_dial_failure_total counter konnectivity_network_proxy_client_dial_failure_total{reason=\"timeout\"} 1 `, }, { name: \"client connections\", metrics: []string{\"konnectivity_network_proxy_client_client_connections\"}, trigger: func() { clientmetrics.Metrics.GetClientConnectionsMetric().WithLabelValues(\"dialing\").Inc() }, want: ` # HELP konnectivity_network_proxy_client_client_connections Number of open client connections, by status (Example: dialing) # TYPE konnectivity_network_proxy_client_client_connections gauge konnectivity_network_proxy_client_client_connections{status=\"dialing\"} 1 `, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { tc.trigger() if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(tc.want), tc.metrics...); err != nil { t.Errorf(\"GatherAndCompare error: %v\", err) } }) } }"} {"_id":"doc-en-kubernetes-c65a8d049bc82f63c90f4e735135c4cfee747917ea6c1c0ab0f2f4ebcb8b10a8","title":"","text":"// Register registers a collectable metric but uses the global registry Register = defaultRegistry.Register // Registerer exposes the global registerer Registerer = defaultRegistry.Registerer ) func init() {"} {"_id":"doc-en-kubernetes-835e2b4a89ac5297285607e50095bf8deb56f4565253c51d2d63e2208b59a864","title":"","text":"endpointsAvailableForLB := !allEndpointsTerminating && !allEndpointsNonServing proxier.deleteExistingLoadBalancer(hns, svcInfo.winProxyOptimization, &svcInfo.hnsID, sourceVip, Enum(svcInfo.Protocol()), uint16(svcInfo.targetPort), uint16(svcInfo.Port()), hnsEndpoints, queriedLoadBalancers) if endpointsAvailableForLB { // clusterIPEndpoints is the endpoint list used for creating ClusterIP loadbalancer. clusterIPEndpoints := hnsEndpoints if svcInfo.internalTrafficLocal { // Take local endpoints for clusterip loadbalancer when internal traffic policy is local. clusterIPEndpoints = hnsLocalEndpoints } // clusterIPEndpoints is the endpoint list used for creating ClusterIP loadbalancer. clusterIPEndpoints := hnsEndpoints if svcInfo.internalTrafficLocal { // Take local endpoints for clusterip loadbalancer when internal traffic policy is local. clusterIPEndpoints = hnsLocalEndpoints } if len(clusterIPEndpoints) > 0 { // If all endpoints are terminating, then no need to create Cluster IP LoadBalancer // Cluster IP LoadBalancer creation"} {"_id":"doc-en-kubernetes-5db7293da306e9e4c4a94428efa87290f10fc99dbd33049f5413c7d387bed691","title":"","text":"} } // TestClusterIPLBInCreateDsrLoadBalancer tests, if the available endpoints are remote, // syncproxyrules only creates ClusterIP Loadbalancer and no NodePort, External IP or IngressIP // loadbalancers will be created. func TestClusterIPLBInCreateDsrLoadBalancer(t *testing.T) { syncPeriod := 30 * time.Second proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, \"testhost\", netutils.ParseIPSloppy(\"10.0.0.1\"), NETWORK_TYPE_OVERLAY) if proxier == nil { t.Error() } svcIP := \"10.20.30.41\" svcPort := 80 svcNodePort := 3001 svcPortName := proxy.ServicePortName{ NamespacedName: makeNSN(\"ns1\", \"svc1\"), Port: \"p80\", Protocol: v1.ProtocolTCP, } lbIP := \"11.21.31.41\" makeServiceMap(proxier, makeTestService(svcPortName.Namespace, svcPortName.Name, func(svc *v1.Service) { svc.Spec.Type = \"NodePort\" svc.Spec.ClusterIP = svcIP svc.Spec.ExternalTrafficPolicy = v1.ServiceExternalTrafficPolicyLocal svc.Spec.Ports = []v1.ServicePort{{ Name: svcPortName.Port, Port: int32(svcPort), Protocol: v1.ProtocolTCP, NodePort: int32(svcNodePort), }} svc.Status.LoadBalancer.Ingress = []v1.LoadBalancerIngress{{ IP: lbIP, }} }), ) tcpProtocol := v1.ProtocolTCP populateEndpointSlices(proxier, makeTestEndpointSlice(svcPortName.Namespace, svcPortName.Name, 1, func(eps *discovery.EndpointSlice) { eps.AddressType = discovery.AddressTypeIPv4 eps.Endpoints = []discovery.Endpoint{{ Addresses: []string{epIpAddressRemote}, NodeName: pointer.StringPtr(\"testhost2\"), // This will make this endpoint as a remote endpoint }} eps.Ports = []discovery.EndpointPort{{ Name: pointer.StringPtr(svcPortName.Port), Port: pointer.Int32(int32(svcPort)), Protocol: &tcpProtocol, }} }), ) proxier.setInitialized(true) proxier.syncProxyRules() svc := proxier.svcPortMap[svcPortName] svcInfo, ok := svc.(*serviceInfo) if !ok { t.Errorf(\"Failed to cast serviceInfo %q\", svcPortName.String()) } else { // Checking ClusterIP Loadbalancer is created if svcInfo.hnsID != guid { t.Errorf(\"%v does not match %v\", svcInfo.hnsID, guid) } // Verifying NodePort Loadbalancer is not created if svcInfo.nodePorthnsID != \"\" { t.Errorf(\"NodePortHnsID %v is not empty.\", svcInfo.nodePorthnsID) } // Verifying ExternalIP Loadbalancer is not created for _, externalIP := range svcInfo.externalIPs { if externalIP.hnsID != \"\" { t.Errorf(\"ExternalLBID %v is not empty.\", externalIP.hnsID) } } // Verifying IngressIP Loadbalancer is not created for _, ingressIP := range svcInfo.loadBalancerIngressIPs { if ingressIP.hnsID != \"\" { t.Errorf(\"IngressLBID %v is not empty.\", ingressIP.hnsID) } } } } func TestEndpointSlice(t *testing.T) { syncPeriod := 30 * time.Second proxier := NewFakeProxier(syncPeriod, syncPeriod, clusterCIDR, \"testhost\", netutils.ParseIPSloppy(\"10.0.0.1\"), NETWORK_TYPE_OVERLAY)"} {"_id":"doc-en-kubernetes-fe6b293da1f4a5a5dab1ac14f9924e5bf0eb7efacc1af238f85d72760d44eab5","title":"","text":"register(\"storage-version-gc\", startStorageVersionGCController) } if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.DynamicResourceAllocation) { controllers[\"resource-claim-controller\"] = startResourceClaimController register(\"resource-claim-controller\", startResourceClaimController) } return controllers"} {"_id":"doc-en-kubernetes-ef618d5b92f5620e6b3ba223d6e129217a4b77a9725aa224694a250b07710556","title":"","text":"const ( // SampleDevicePluginDSYAML is the path of the daemonset template of the sample device plugin. // TODO: Parametrize it by making it a feature in TestFramework. SampleDevicePluginDSYAML = \"test/e2e/testing-manifests/sample-device-plugin.yaml\" SampleDevicePluginDSYAML = \"test/e2e/testing-manifests/sample-device-plugin/sample-device-plugin.yaml\" SampleDevicePluginControlRegistrationDSYAML = \"test/e2e/testing-manifests/sample-device-plugin/sample-device-plugin-control-registration.yaml\" // SampleDevicePluginName is the name of the device plugin pod"} {"_id":"doc-en-kubernetes-dd696876cfb12f5ca62ef73e3e76204b111d7286e3956037c85ac96cfb701be5","title":"","text":"\"k8s.io/apimachinery/pkg/watch\" \"k8s.io/apiserver/pkg/apis/example\" examplev1 \"k8s.io/apiserver/pkg/apis/example/v1\" example2v1 \"k8s.io/apiserver/pkg/apis/example2/v1\" \"k8s.io/apiserver/pkg/features\" \"k8s.io/apiserver/pkg/storage\" \"k8s.io/apiserver/pkg/storage/etcd3\""} {"_id":"doc-en-kubernetes-b0713de582f031a4ff47cfc84b6ebe874458d87c1f533f75ab3eb2ed0899a298","title":"","text":"metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion) utilruntime.Must(example.AddToScheme(scheme)) utilruntime.Must(examplev1.AddToScheme(scheme)) utilruntime.Must(example2v1.AddToScheme(scheme)) } func newTestCacher(s storage.Interface) (*Cacher, storage.Versioner, error) {"} {"_id":"doc-en-kubernetes-301369fe3554828290d1197caa7aa079130e0e62ee542e986bcd19d83a692790","title":"","text":"// test data newEtcdTestStorage := func(t *testing.T, prefix string) (*etcd3testing.EtcdTestServer, storage.Interface) { server, _ := etcd3testing.NewUnsecuredEtcd3TestClientServer(t) storage := etcd3.New(server.V3Client, apitesting.TestCodec(codecs, example.SchemeGroupVersion), func() runtime.Object { return &example.Pod{} }, prefix, schema.GroupResource{Resource: \"pods\"}, identity.NewEncryptCheckTransformer(), true, etcd3.NewDefaultLeaseManagerConfig()) storage := etcd3.New(server.V3Client, apitesting.TestCodec(codecs, examplev1.SchemeGroupVersion, example2v1.SchemeGroupVersion), func() runtime.Object { return &example.Pod{} }, prefix, schema.GroupResource{Resource: \"pods\"}, identity.NewEncryptCheckTransformer(), true, etcd3.NewDefaultLeaseManagerConfig()) return server, storage } server, etcdStorage := newEtcdTestStorage(t, \"\")"} {"_id":"doc-en-kubernetes-a48b521f9c60271386d5913c9332fcfa460b1006e7a9266e22a7134d306e7046","title":"","text":"require.NoError(t, err) return out } makeReplicaSet := func(name string) *example.ReplicaSet { return &example.ReplicaSet{ makeReplicaSet := func(name string) *example2v1.ReplicaSet { return &example2v1.ReplicaSet{ ObjectMeta: metav1.ObjectMeta{Namespace: \"ns\", Name: name}, } } createReplicaSet := func(obj *example.ReplicaSet) *example.ReplicaSet { createReplicaSet := func(obj *example2v1.ReplicaSet) *example2v1.ReplicaSet { key := \"replicasets/\" + obj.Namespace + \"/\" + obj.Name out := &example.ReplicaSet{} out := &example2v1.ReplicaSet{} err := etcdStorage.Create(context.TODO(), key, obj, out, 0) require.NoError(t, err) return out"} {"_id":"doc-en-kubernetes-7b9f304dc3ce92447646beaaddac687823a796430ef24a41f0d464d894e0e811","title":"","text":"framework.ExpectNoError(waitErr, \"some pods failed to complete within %v\", completeTimeout) }) }) ginkgo.Context(\"Pods sharing a single local PV [Serial]\", func() { var ( pv *v1.PersistentVolume ) ginkgo.BeforeEach(func(ctx context.Context) { localVolume := &localTestVolume{ ltr: &utils.LocalTestResource{ Node: config.randomNode, Path: \"/tmp\", }, localVolumeType: DirectoryLocalVolumeType, } pvConfig := makeLocalPVConfig(config, localVolume) var err error pv, err = e2epv.CreatePV(ctx, config.client, f.Timeouts, e2epv.MakePersistentVolume(pvConfig)) framework.ExpectNoError(err) }) ginkgo.AfterEach(func(ctx context.Context) { if pv == nil { return } ginkgo.By(fmt.Sprintf(\"Clean PV %s\", pv.Name)) err := config.client.CoreV1().PersistentVolumes().Delete(ctx, pv.Name, metav1.DeleteOptions{}) framework.ExpectNoError(err) }) ginkgo.It(\"all pods should be running\", func(ctx context.Context) { var ( pvc *v1.PersistentVolumeClaim pods = map[string]*v1.Pod{} count = 2 err error ) pvc = e2epv.MakePersistentVolumeClaim(makeLocalPVCConfig(config, DirectoryLocalVolumeType), config.ns) ginkgo.By(fmt.Sprintf(\"Create a PVC %s\", pvc.Name)) pvc, err = e2epv.CreatePVC(ctx, config.client, config.ns, pvc) framework.ExpectNoError(err) ginkgo.By(fmt.Sprintf(\"Create %d pods to use this PVC\", count)) podConfig := e2epod.Config{ NS: config.ns, PVCs: []*v1.PersistentVolumeClaim{pvc}, SeLinuxLabel: selinuxLabel, } for i := 0; i < count; i++ { pod, err := e2epod.MakeSecPod(&podConfig) framework.ExpectNoError(err) pod, err = config.client.CoreV1().Pods(config.ns).Create(ctx, pod, metav1.CreateOptions{}) framework.ExpectNoError(err) pods[pod.Name] = pod } ginkgo.By(\"Wait for all pods are running\") const runningTimeout = 5 * time.Minute waitErr := wait.PollImmediate(time.Second, runningTimeout, func() (done bool, err error) { podsList, err := config.client.CoreV1().Pods(config.ns).List(ctx, metav1.ListOptions{}) if err != nil { return false, err } runningPods := 0 for _, pod := range podsList.Items { switch pod.Status.Phase { case v1.PodRunning: runningPods++ } } return runningPods == count, nil }) framework.ExpectNoError(waitErr, \"Some pods are not running within %v\", runningTimeout) }) }) }) func deletePodAndPVCs(ctx context.Context, config *localTestConfig, pod *v1.Pod) error {"} {"_id":"doc-en-kubernetes-d436d8e721335d66f986e9b43010679bd7b4b93efa0ae7bb2ccaad9c1f634e1e","title":"","text":"See our documentation on [kubernetes.io]. Try our [interactive tutorial]. Take a free course on [Scalable Microservices with Kubernetes]. To use Kubernetes code as a library in other applications, see the [list of published components](https://git.k8s.io/kubernetes/staging/README.md)."} {"_id":"doc-en-kubernetes-715f49eb7c0b288e67d6689f80e0154faa746d7ea1bb611999eecf6cb9cf2730","title":"","text":"[developer's documentation]: https://git.k8s.io/community/contributors/devel#readme [Docker environment]: https://docs.docker.com/engine [Go environment]: https://go.dev/doc/install [interactive tutorial]: https://kubernetes.io/docs/tutorials/kubernetes-basics [kubernetes.io]: https://kubernetes.io [Scalable Microservices with Kubernetes]: https://www.udacity.com/course/scalable-microservices-with-kubernetes--ud615 [troubleshooting guide]: https://kubernetes.io/docs/tasks/debug/"} {"_id":"doc-en-kubernetes-df84e3a937f3c4cdf0bf5841d1a631f8a8de0b6c4ab7f9e59c1bd205daef9a91","title":"","text":"return retval, nil }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { w := watch.NewFake() w := watch.NewRaceFreeFake() if options.ResourceVersion == \"1\" { go func() { // Close with a \"Gone\" error when trying to start a watch from the first list"} {"_id":"doc-en-kubernetes-57894d1c754d3280dac6898156ede8134f9cf3358b7468e5742658e8cfe64a46","title":"","text":"}, } _, _, w, done := NewIndexerInformerWatcher(lw, &corev1.Secret{}) defer w.Stop() // Expect secret add select {"} {"_id":"doc-en-kubernetes-cbd9cd4002bea1f529bec39538e66a5294b25daa492a4f60458a9699e6ec6674","title":"","text":"} } // This is the spec for the volume that this plugin wraps. var wrappedVolumeSpec = volume.Spec{ // This should be on a tmpfs instead of the local disk; the problem is // charging the memory for the tmpfs to the right cgroup. We should make // this a tmpfs when we can do the accounting correctly. Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, func wrappedVolumeSpec() volume.Spec { // This is the spec for the volume that this plugin wraps. return volume.Spec{ // This should be on a tmpfs instead of the local disk; the problem is // charging the memory for the tmpfs to the right cgroup. We should make // this a tmpfs when we can do the accounting correctly. Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, } } func (b *configMapVolumeMounter) SetUp(fsGroup *int64) error {"} {"_id":"doc-en-kubernetes-db0177d1581641bfddd32d8b483a981a60a9a4b62cd4ec484ef542cb86b22e40","title":"","text":"var _ volume.VolumePlugin = &downwardAPIPlugin{} var wrappedVolumeSpec = volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, func wrappedVolumeSpec() volume.Spec { return volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, } } func (plugin *downwardAPIPlugin) Init(host volume.VolumeHost) error {"} {"_id":"doc-en-kubernetes-b7f997339f33739176a3fbab5c8ec86c020b1f8fad3e9af171f387461f216718","title":"","text":"func (b *downwardAPIVolumeMounter) SetUpAt(dir string, fsGroup *int64) error { glog.V(3).Infof(\"Setting up a downwardAPI volume %v for pod %v/%v at %v\", b.volName, b.pod.Namespace, b.pod.Name, dir) // Wrap EmptyDir. Here we rely on the idempotency of the wrapped plugin to avoid repeatedly mounting wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec, b.pod, *b.opts) wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), b.pod, *b.opts) if err != nil { glog.Errorf(\"Couldn't setup downwardAPI volume %v for pod %v/%v: %s\", b.volName, b.pod.Namespace, b.pod.Name, err.Error()) return err"} {"_id":"doc-en-kubernetes-409bdfc7f3bcdf5a6c25c1050a940642d4cf672324fa9d682af3c3b695cad765","title":"","text":"var _ volume.VolumePlugin = &gitRepoPlugin{} var wrappedVolumeSpec = volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, func wrappedVolumeSpec() volume.Spec { return volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}, } } const ("} {"_id":"doc-en-kubernetes-9e9f70dabc1cc5462660d87119838c47aebe4a2a5eb3c2718e695cb41b1ea472","title":"","text":"} // Wrap EmptyDir, let it do the setup. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec, &b.pod, b.opts) wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), &b.pod, b.opts) if err != nil { return err }"} {"_id":"doc-en-kubernetes-3cca84f08522d5fd517e773b0a03826d3be1a6a76c91c37a6e8bcb2eabee8d36","title":"","text":"func (c *gitRepoVolumeUnmounter) TearDownAt(dir string) error { // Wrap EmptyDir, let it do the teardown. wrapped, err := c.plugin.host.NewWrapperUnmounter(c.volName, wrappedVolumeSpec, c.podUID) wrapped, err := c.plugin.host.NewWrapperUnmounter(c.volName, wrappedVolumeSpec(), c.podUID) if err != nil { return err }"} {"_id":"doc-en-kubernetes-199017eb3cb767bb18c1fdda158ec00278b782821955276c94eb76d9e1ead0fe","title":"","text":"var _ volume.VolumePlugin = &secretPlugin{} var wrappedVolumeSpec = volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, func wrappedVolumeSpec() volume.Spec { return volume.Spec{ Volume: &api.Volume{VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{Medium: api.StorageMediumMemory}}}, } } func getPath(uid types.UID, volName string, host volume.VolumeHost) string {"} {"_id":"doc-en-kubernetes-f2e1fd39c4c29ca16badf8db2c872424b41c14af0204ffc81f631d4cf5266a73","title":"","text":"glog.V(3).Infof(\"Setting up volume %v for pod %v at %v\", b.volName, b.pod.UID, dir) // Wrap EmptyDir, let it do the setup. wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec, &b.pod, *b.opts) wrapped, err := b.plugin.host.NewWrapperMounter(b.volName, wrappedVolumeSpec(), &b.pod, *b.opts) if err != nil { return err }"} {"_id":"doc-en-kubernetes-10404edca84bf27841dba7cebe4d3ac3d547a4edf381119f88d7c5f7814be3cb","title":"","text":"glog.V(3).Infof(\"Tearing down volume %v for pod %v at %v\", c.volName, c.podUID, dir) // Wrap EmptyDir, let it do the teardown. wrapped, err := c.plugin.host.NewWrapperUnmounter(c.volName, wrappedVolumeSpec, c.podUID) wrapped, err := c.plugin.host.NewWrapperUnmounter(c.volName, wrappedVolumeSpec(), c.podUID) if err != nil { return err }"} {"_id":"doc-en-kubernetes-3105c280d5a9658dbaf924b1e959eff706d7c135226c6d3183e815df88024b0d","title":"","text":"- [Debugging clusters](#debugging-clusters) - [Local clusters](#local-clusters) - [Testing against local clusters](#testing-against-local-clusters) - [Version-skewed and upgrade testing](#version-skewed-and-upgrade-testing) - [Kinds of tests](#kinds-of-tests) - [Conformance tests](#conformance-tests) - [Defining Conformance Subset](#defining-conformance-subset)"} {"_id":"doc-en-kubernetes-870cc31e341f2b1838b5bd69a3de92a5659d7326a141bcb472be534347807689","title":"","text":"go run hack/e2e.go -v --test --check_node_count=false --test_args=\"--host=http://127.0.0.1:8080\" --ginkgo.focus=\"Secrets\" ``` ### Version-skewed and upgrade testing We run version-skewed tests to check that newer versions of Kubernetes work similarly enough to older versions. The general strategy is to cover the following cases: 1. One version of `kubectl` with another version of the cluster and tests (e.g. that v1.2 and v1.4 `kubectl` doesn't break v1.3 tests running against a v1.3 cluster). 1. A newer version of the Kubernetes master with older nodes and tests (e.g. that upgrading a master to v1.3 with nodes at v1.2 still passes v1.2 tests). 1. A newer version of the whole cluster with older tests (e.g. that a cluster upgraded---master and nodes---to v1.3 still passes v1.2 tests). 1. That an upgraded cluster functions the same as a brand-new cluster of the same version (e.g. a cluster upgraded to v1.3 passes the same v1.3 tests as a newly-created v1.3 cluster). [hack/e2e-runner.sh](http://releases.k8s.io/HEAD/hack/jenkins/e2e-runner.sh) is the authoritative source on how to run version-skewed tests, but below is a quick-and-dirty tutorial. ```sh # Assume you have two copies of the Kubernetes repository checked out, at # ./kubernetes and ./kubernetes_old # If using GKE: export KUBERNETES_PROVIDER=gke export CLUSTER_API_VERSION=${OLD_VERSION} # Deploy a cluster at the old version; see above for more details cd ./kubernetes_old go run ./hack/e2e.go -v --up # Upgrade the cluster to the new version # # If using GKE, add --upgrade-target=${NEW_VERSION} # # You can target Feature:MasterUpgrade or Feature:ClusterUpgrade cd ../kubernetes go run ./hack/e2e.go -v --test --check_version_skew=false --test_args=\"--ginkgo.focus=[Feature:MasterUpgrade]\" # Run old tests with new kubectl cd ../kubernetes_old go run ./hack/e2e.go -v --test --test_args=\"--kubectl-path=$(pwd)/../kubernetes/cluster/kubectl.sh\" ``` If you are just testing version-skew, you may want to just deploy at one version and then test at another version, instead of going through the whole upgrade process: ```sh # With the same setup as above # Deploy a cluster at the new version cd ./kubernetes go run ./hack/e2e.go -v --up # Run new tests with old kubectl go run ./hack/e2e.go -v --test --test_args=\"--kubectl-path=$(pwd)/../kubernetes_old/cluster/kubectl.sh\" # Run old tests with new kubectl cd ../kubernetes_old go run ./hack/e2e.go -v --test --test_args=\"--kubectl-path=$(pwd)/../kubernetes/cluster/kubectl.sh\" ``` ## Kinds of tests We are working on implementing clearer partitioning of our e2e tests to make"} {"_id":"doc-en-kubernetes-c098c81571bb12eeff63c6557f7e1d176bddfae294ad78afda24b6400d8f1096","title":"","text":"configs[ResourceConsumer] = Config{list.PromoterE2eRegistry, \"resource-consumer\", \"1.13\"} configs[SdDummyExporter] = Config{list.GcRegistry, \"sd-dummy-exporter\", \"v0.2.0\"} configs[VolumeNFSServer] = Config{list.PromoterE2eRegistry, \"volume/nfs\", \"1.3\"} configs[VolumeISCSIServer] = Config{list.PromoterE2eRegistry, \"volume/iscsi\", \"2.5\"} configs[VolumeISCSIServer] = Config{list.PromoterE2eRegistry, \"volume/iscsi\", \"2.6\"} configs[VolumeRBDServer] = Config{list.PromoterE2eRegistry, \"volume/rbd\", \"1.0.6\"} configs[WindowsServer] = Config{list.MicrosoftRegistry, \"windows\", \"1809\"}"} {"_id":"doc-en-kubernetes-5b7b4710d409330e493ef49e519dfdc199f0822992147041eea133e9c7769a2c","title":"","text":"// TODO (#113700): patch claim := claim.DeepCopy() claim.Status.ReservedFor = valid // When a ResourceClaim uses delayed allocation, then it makes sense to // deallocate the claim as soon as the last consumer stops using // it. This ensures that the claim can be allocated again as needed by // some future consumer instead of trying to schedule that consumer // onto the node that was chosen for the previous consumer. It also // releases the underlying resources for use by other claims. // // This has to be triggered by the transition from \"was being used\" to // \"is not used anymore\" because a DRA driver is not required to set // `status.reservedFor` together with `status.allocation`, i.e. a claim // that is \"currently unused\" should not get deallocated. // // This does not matter for claims that were created for a pod. For // those, the resource claim controller will trigger deletion when the // pod is done. However, it doesn't hurt to also trigger deallocation // for such claims and not checking for them keeps this code simpler. if len(valid) == 0 && claim.Spec.AllocationMode == resourcev1alpha2.AllocationModeWaitForFirstConsumer { claim.Status.DeallocationRequested = true } _, err := ec.kubeClient.ResourceV1alpha2().ResourceClaims(claim.Namespace).UpdateStatus(ctx, claim, metav1.UpdateOptions{}) if err != nil { return err"} {"_id":"doc-en-kubernetes-c4be106cbbe99c4dd9173f257c2843fea72962423c019645962cfab802a76206","title":"","text":"plugin, err := app.StartPlugin(logger, \"/cdi\", d.Name, nodename, app.FileOperations{ Create: func(name string, content []byte) error { ginkgo.By(fmt.Sprintf(\"creating CDI file %s on node %s:n%s\", name, nodename, string(content))) klog.Background().Info(\"creating CDI file\", \"node\", nodename, \"filename\", name, \"content\", string(content)) return d.createFile(&pod, name, content) }, Remove: func(name string) error { ginkgo.By(fmt.Sprintf(\"deleting CDI file %s on node %s\", name, nodename)) klog.Background().Info(\"deleting CDI file\", \"node\", nodename, \"filename\", name) return d.removeFile(&pod, name) }, },"} {"_id":"doc-en-kubernetes-4271ccbdec2ac3118faae750348e798ae0820615aceaed835567597c88577a34","title":"","text":"ginkgo.Context(\"with immediate allocation\", func() { claimTests(resourcev1alpha2.AllocationModeImmediate) }) ginkgo.It(\"must deallocate after use when using delayed allocation\", func(ctx context.Context) { parameters := b.parameters() pod := b.podExternal() claim := b.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) b.create(ctx, parameters, claim, pod) gomega.Eventually(ctx, func(ctx context.Context) (*resourcev1alpha2.ResourceClaim, error) { return b.f.ClientSet.ResourceV1alpha2().ResourceClaims(b.f.Namespace.Name).Get(ctx, claim.Name, metav1.GetOptions{}) }).WithTimeout(f.Timeouts.PodDelete).ShouldNot(gomega.HaveField(\"Status.Allocation\", (*resourcev1alpha2.AllocationResult)(nil))) b.testPod(ctx, f.ClientSet, pod) ginkgo.By(fmt.Sprintf(\"deleting pod %s\", klog.KObj(pod))) framework.ExpectNoError(b.f.ClientSet.CoreV1().Pods(b.f.Namespace.Name).Delete(ctx, pod.Name, metav1.DeleteOptions{})) ginkgo.By(\"waiting for claim to get deallocated\") gomega.Eventually(ctx, func(ctx context.Context) (*resourcev1alpha2.ResourceClaim, error) { return b.f.ClientSet.ResourceV1alpha2().ResourceClaims(b.f.Namespace.Name).Get(ctx, claim.Name, metav1.GetOptions{}) }).WithTimeout(f.Timeouts.PodDelete).Should(gomega.HaveField(\"Status.Allocation\", (*resourcev1alpha2.AllocationResult)(nil))) }) }) ginkgo.Context(\"multiple nodes\", func() {"} {"_id":"doc-en-kubernetes-6a0f3091028d3a264c0e8152e95b69fa4e6dd92ade6b06a7957fbe42aeeed4b4","title":"","text":"// TODO: move it to k8s.io/utils/net, this is the same as current AddIPOffset() // but using netip.Addr instead of net.IP func addOffsetAddress(address netip.Addr, offset uint64) (netip.Addr, error) { addressBig := big.NewInt(0).SetBytes(address.AsSlice()) r := big.NewInt(0).Add(addressBig, big.NewInt(int64(offset))) addr, ok := netip.AddrFromSlice(r.Bytes()) addressBytes := address.AsSlice() addressBig := big.NewInt(0).SetBytes(addressBytes) r := big.NewInt(0).Add(addressBig, big.NewInt(int64(offset))).Bytes() // r must be 4 or 16 bytes depending of the ip family // bigInt conversion to bytes will not take this into consideration // and drop the leading zeros, so we have to take this into account. lenDiff := len(addressBytes) - len(r) if lenDiff > 0 { r = append(make([]byte, lenDiff), r...) } else if lenDiff < 0 { return netip.Addr{}, fmt.Errorf(\"invalid address %v\", r) } addr, ok := netip.AddrFromSlice(r) if !ok { return netip.Addr{}, fmt.Errorf(\"invalid address %v\", r.Bytes()) return netip.Addr{}, fmt.Errorf(\"invalid address %v\", r) } return addr, nil }"} {"_id":"doc-en-kubernetes-d2867cd09c59f20dcdf53caeebfe2c08db0c21c9bf10177a1b7d9e65f41ad88e","title":"","text":"want: netip.MustParseAddr(\"192.168.0.128\"), }, { name: \"IPv4 with leading zeros\", address: netip.MustParseAddr(\"0.0.1.8\"), offset: 138, want: netip.MustParseAddr(\"0.0.1.146\"), }, { name: \"IPv6 with leading zeros\", address: netip.MustParseAddr(\"00fc::1\"), offset: 255, want: netip.MustParseAddr(\"fc::100\"), }, { name: \"IPv6 offset 255\", address: netip.MustParseAddr(\"2001:db8:1::101\"), offset: 255,"} {"_id":"doc-en-kubernetes-b43b55db3e7ceec89f9278b09869f59b1903aec2f474744dfa5687c3ec70a6b7","title":"","text":"subnet: netip.MustParsePrefix(\"fd00:1:2:3::/64\"), want: netip.MustParseAddr(\"fd00:1:2:3:FFFF:FFFF:FFFF:FFFF\"), }, { name: \"ipv6 00fc::/112\", subnet: netip.MustParsePrefix(\"00fc::/112\"), want: netip.MustParseAddr(\"fc::ffff\"), }, { name: \"ipv6 fc00::/112\", subnet: netip.MustParsePrefix(\"fc00::/112\"), want: netip.MustParseAddr(\"fc00::ffff\"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {"} {"_id":"doc-en-kubernetes-a1a68096d1553649d5495b5174687520b346f86b6662bf1167e5f8eb9a15a113","title":"","text":"} } func TestAllocateNextFC(t *testing.T) { _, cidr, err := netutils.ParseCIDRSloppy(\"fc::/112\") if err != nil { t.Fatal(err) } t.Logf(\"CIDR %s\", cidr) r, err := newTestAllocator(cidr) if err != nil { t.Fatal(err) } defer r.Destroy() ip, err := r.AllocateNext() if err != nil { t.Fatalf(\"wrong ip %s : %v\", ip, err) } t.Log(ip.String()) } func BenchmarkIPAllocatorAllocateNextIPv4Size1048574(b *testing.B) { _, cidr, err := netutils.ParseCIDRSloppy(\"10.0.0.0/12\") if err != nil {"} {"_id":"doc-en-kubernetes-d86a21f9bca0a491385ae616d59370d25543e5dd756c2c43c410ecfcf0a5f51b","title":"","text":"testingclock \"k8s.io/utils/clock/testing\" \"k8s.io/utils/pointer\" \"github.com/google/go-cmp/cmp\" \"github.com/stretchr/testify/assert\" )"} {"_id":"doc-en-kubernetes-ed5e0050240851ce334606dd762c3e53f7a5e9df8072072c21fa266763e5d20e","title":"","text":"gotNames.Insert(pod.Name) } assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(), \"expected %v, got %v\", expectedNames.List(), gotNames.List()) assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(), \"expected %v, got %v\", expectedNames.List(), gotNames.List()) if diff := cmp.Diff(expectedNames.List(), gotNames.List()); diff != \"\" { t.Errorf(\"Active pod names (-want,+got):n%s\", diff) } } func TestSortingActivePods(t *testing.T) {"} {"_id":"doc-en-kubernetes-52dcc80f6725e757a9009260dc8e2b4f12753a522c60c8819cf2a3f02be8bcd7","title":"","text":"gotNames.Insert(rs.Name) } assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(), \"expected %v, got %v\", expectedNames.List(), gotNames.List()) assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(), \"expected %v, got %v\", expectedNames.List(), gotNames.List()) if diff := cmp.Diff(expectedNames.List(), gotNames.List()); diff != \"\" { t.Errorf(\"Active replica set names (-want,+got):n%s\", diff) } } func TestComputeHash(t *testing.T) {"} {"_id":"doc-en-kubernetes-7b8973831f6cd08c60d20a19a4c0702947ad019dd35899fa5ff0a4e41f52fc2c","title":"","text":"metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/types\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/uuid\" utilfeature \"k8s.io/apiserver/pkg/util/feature\""} {"_id":"doc-en-kubernetes-b4b035f76018f84f7303d154213d7d99072dc6e719f10dcd640a4320992db013","title":"","text":"} } func newReplicaSet(name string, replicas int) *apps.ReplicaSet { func newReplicaSet(name string, replicas int, rsUuid types.UID) *apps.ReplicaSet { return &apps.ReplicaSet{ TypeMeta: metav1.TypeMeta{APIVersion: \"v1\"}, ObjectMeta: metav1.ObjectMeta{ UID: uuid.NewUUID(), UID: rsUuid, Name: name, Namespace: metav1.NamespaceDefault, ResourceVersion: \"18\","} {"_id":"doc-en-kubernetes-db8fc0de680422deb2aa058c0b978d0181bec6af1054a0323ce827cd731ebd12","title":"","text":"} wg.Wait() // Expectations have been surpassed podExp, exists, err := e.GetExpectations(rcKey) assert.NoError(t, err, \"Could not get expectations for rc, exists %v and err %v\", exists, err) assert.True(t, exists, \"Could not get expectations for rc, exists %v and err %v\", exists, err) add, del := podExp.GetExpectations() assert.Equal(t, int64(-1), add, \"Unexpected pod expectations %#v\", podExp) assert.Equal(t, int64(-1), del, \"Unexpected pod expectations %#v\", podExp) assert.True(t, e.SatisfiedExpectations(logger, rcKey), \"Expectations are met but the rc will not sync\") // Next round of rc sync, old expectations are cleared e.SetExpectations(logger, rcKey, 1, 2) podExp, exists, err = e.GetExpectations(rcKey) assert.NoError(t, err, \"Could not get expectations for rc, exists %v and err %v\", exists, err) assert.True(t, exists, \"Could not get expectations for rc, exists %v and err %v\", exists, err) add, del = podExp.GetExpectations() assert.Equal(t, int64(1), add, \"Unexpected pod expectations %#v\", podExp) assert.Equal(t, int64(2), del, \"Unexpected pod expectations %#v\", podExp) // Expectations have expired because of ttl fakeClock.Step(ttl + 1) assert.True(t, e.SatisfiedExpectations(logger, rcKey), \"Expectations should have expired but didn't\") tests := []struct { name string expectationsToSet []int expireExpectations bool wantPodExpectations []int64 wantExpectationsSatisfied bool }{ { name: \"Expectations have been surpassed\", expireExpectations: false, wantPodExpectations: []int64{int64(-1), int64(-1)}, wantExpectationsSatisfied: true, }, { name: \"Old expectations are cleared because of ttl\", expectationsToSet: []int{1, 2}, expireExpectations: true, wantPodExpectations: []int64{int64(1), int64(2)}, wantExpectationsSatisfied: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { if len(test.expectationsToSet) > 0 { e.SetExpectations(logger, rcKey, test.expectationsToSet[0], test.expectationsToSet[1]) } podExp, exists, err := e.GetExpectations(rcKey) assert.NoError(t, err, \"Could not get expectations for rc, exists %v and err %v\", exists, err) assert.True(t, exists, \"Could not get expectations for rc, exists %v and err %v\", exists, err) add, del := podExp.GetExpectations() assert.Equal(t, test.wantPodExpectations[0], add, \"Unexpected pod expectations %#v\", podExp) assert.Equal(t, test.wantPodExpectations[1], del, \"Unexpected pod expectations %#v\", podExp) assert.Equal(t, test.wantExpectationsSatisfied, e.SatisfiedExpectations(logger, rcKey), \"Expectations are met but the rc will not sync\") if test.expireExpectations { fakeClock.Step(ttl + 1) assert.True(t, e.SatisfiedExpectations(logger, rcKey), \"Expectations should have expired but didn't\") } }) } } func TestUIDExpectations(t *testing.T) { logger, _ := ktesting.NewTestContext(t) uidExp := NewUIDTrackingControllerExpectations(NewControllerExpectations()) rcList := []*v1.ReplicationController{ newReplicationController(2), newReplicationController(1), newReplicationController(0), newReplicationController(5), type test struct { name string numReplicas int } shuffleTests := func(tests []test) { for i := range tests { j := rand.Intn(i + 1) tests[i], tests[j] = tests[j], tests[i] } } rcToPods := map[string][]string{} rcKeys := []string{} for i := range rcList { rc := rcList[i] rcName := fmt.Sprintf(\"rc-%v\", i) getRcDataFrom := func(test test) (string, []string) { rc := newReplicationController(test.numReplicas) rcName := fmt.Sprintf(\"rc-%v\", test.numReplicas) rc.Name = rcName rc.Spec.Selector[rcName] = rcName podList := newPodList(nil, 5, v1.PodRunning, rc) rcKey, err := KeyFunc(rc) if err != nil { t.Fatalf(\"Couldn't get key for object %#v: %v\", rc, err) } rcKeys = append(rcKeys, rcKey) rcPodNames := []string{} for i := range podList.Items { p := &podList.Items[i] p.Name = fmt.Sprintf(\"%v-%v\", p.Name, rc.Name) rcPodNames = append(rcPodNames, PodKey(p)) } rcToPods[rcKey] = rcPodNames uidExp.ExpectDeletions(logger, rcKey, rcPodNames) return rcKey, rcPodNames } for i := range rcKeys { j := rand.Intn(i + 1) rcKeys[i], rcKeys[j] = rcKeys[j], rcKeys[i] tests := []test{ {name: \"Replication controller with 2 replicas\", numReplicas: 2}, {name: \"Replication controller with 1 replica\", numReplicas: 1}, {name: \"Replication controller with no replicas\", numReplicas: 0}, {name: \"Replication controller with 5 replicas\", numReplicas: 5}, } for _, rcKey := range rcKeys { assert.False(t, uidExp.SatisfiedExpectations(logger, rcKey), \"Controller %v satisfied expectations before deletion\", rcKey) for _, p := range rcToPods[rcKey] { uidExp.DeletionObserved(logger, rcKey, p) } shuffleTests(tests) for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert.True(t, uidExp.SatisfiedExpectations(logger, rcKey), \"Controller %v didn't satisfy expectations after deletion\", rcKey) rcKey, rcPodNames := getRcDataFrom(test) assert.False(t, uidExp.SatisfiedExpectations(logger, rcKey), \"Controller %v satisfied expectations before deletion\", rcKey) uidExp.DeleteExpectations(logger, rcKey) for _, p := range rcPodNames { uidExp.DeletionObserved(logger, rcKey, p) } assert.Nil(t, uidExp.GetUIDs(rcKey), \"Failed to delete uid expectations for %v\", rcKey) } } assert.True(t, uidExp.SatisfiedExpectations(logger, rcKey), \"Controller %v didn't satisfy expectations after deletion\", rcKey) func TestCreatePods(t *testing.T) { ns := metav1.NamespaceDefault body := runtime.EncodeOrDie(clientscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"empty_pod\"}}) fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: string(body), } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: \"\", Version: \"v1\"}}}) uidExp.DeleteExpectations(logger, rcKey) podControl := RealPodControl{ KubeClient: clientset, Recorder: &record.FakeRecorder{}, assert.Nil(t, uidExp.GetUIDs(rcKey), \"Failed to delete uid expectations for %v\", rcKey) }) } } func TestCreatePodsWithGenerateName(t *testing.T) { ns := metav1.NamespaceDefault generateName := \"hello-\" controllerSpec := newReplicationController(1) controllerRef := metav1.NewControllerRef(controllerSpec, v1.SchemeGroupVersion.WithKind(\"ReplicationController\")) // Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template err := podControl.CreatePods(context.TODO(), ns, controllerSpec.Spec.Template, controllerSpec, controllerRef) assert.NoError(t, err, \"unexpected error: %v\", err) expectedPod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Labels: controllerSpec.Spec.Template.Labels, GenerateName: fmt.Sprintf(\"%s-\", controllerSpec.Name), }, Spec: controllerSpec.Spec.Template.Spec, type test struct { name string podCreationFunc func(podControl RealPodControl) error wantPod *v1.Pod } fakeHandler.ValidateRequest(t, \"/api/v1/namespaces/default/pods\", \"POST\", nil) var actualPod = &v1.Pod{} err = json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) assert.NoError(t, err, \"unexpected error: %v\", err) assert.True(t, apiequality.Semantic.DeepDerivative(&expectedPod, actualPod), \"Body: %s\", fakeHandler.RequestBody) } func TestCreatePodsWithGenerateName(t *testing.T) { ns := metav1.NamespaceDefault body := runtime.EncodeOrDie(clientscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"empty_pod\"}}) fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: string(body), var tests = []test{ { name: \"Create pod\", podCreationFunc: func(podControl RealPodControl) error { return podControl.CreatePods(context.TODO(), ns, controllerSpec.Spec.Template, controllerSpec, controllerRef) }, wantPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Labels: controllerSpec.Spec.Template.Labels, GenerateName: fmt.Sprintf(\"%s-\", controllerSpec.Name), }, Spec: controllerSpec.Spec.Template.Spec, }, }, { name: \"Create pod with generate name\", podCreationFunc: func(podControl RealPodControl) error { // Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template return podControl.CreatePodsWithGenerateName(context.TODO(), ns, controllerSpec.Spec.Template, controllerSpec, controllerRef, generateName) }, wantPod: &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Labels: controllerSpec.Spec.Template.Labels, GenerateName: generateName, OwnerReferences: []metav1.OwnerReference{*controllerRef}, }, Spec: controllerSpec.Spec.Template.Spec, }, }, } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: \"\", Version: \"v1\"}}}) podControl := RealPodControl{ KubeClient: clientset, Recorder: &record.FakeRecorder{}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { body := runtime.EncodeOrDie(clientscheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"empty_pod\"}}) fakeHandler := utiltesting.FakeHandler{ StatusCode: 200, ResponseBody: string(body), } testServer := httptest.NewServer(&fakeHandler) defer testServer.Close() clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: \"\", Version: \"v1\"}}}) controllerSpec := newReplicationController(1) controllerRef := metav1.NewControllerRef(controllerSpec, v1.SchemeGroupVersion.WithKind(\"ReplicationController\")) podControl := RealPodControl{ KubeClient: clientset, Recorder: &record.FakeRecorder{}, } // Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template generateName := \"hello-\" err := podControl.CreatePodsWithGenerateName(context.TODO(), ns, controllerSpec.Spec.Template, controllerSpec, controllerRef, generateName) assert.NoError(t, err, \"unexpected error: %v\", err) err := test.podCreationFunc(podControl) assert.NoError(t, err, \"unexpected error: %v\", err) expectedPod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Labels: controllerSpec.Spec.Template.Labels, GenerateName: generateName, OwnerReferences: []metav1.OwnerReference{*controllerRef}, }, Spec: controllerSpec.Spec.Template.Spec, fakeHandler.ValidateRequest(t, \"/api/v1/namespaces/default/pods\", \"POST\", nil) var actualPod = &v1.Pod{} err = json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) assert.NoError(t, err, \"unexpected error: %v\", err) assert.True(t, apiequality.Semantic.DeepDerivative(test.wantPod, actualPod), \"Body: %s\", fakeHandler.RequestBody) }) } fakeHandler.ValidateRequest(t, \"/api/v1/namespaces/default/pods\", \"POST\", nil) var actualPod = &v1.Pod{} err = json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) assert.NoError(t, err, \"unexpected error: %v\", err) assert.True(t, apiequality.Semantic.DeepDerivative(&expectedPod, actualPod), \"Body: %s\", fakeHandler.RequestBody) } func TestDeletePodsAllowsMissing(t *testing.T) {"} {"_id":"doc-en-kubernetes-57ec8590113aafcd68a99159399518fe7de131198c63f0e27f65d14525046d45","title":"","text":"func TestActivePodFiltering(t *testing.T) { logger, _ := ktesting.NewTestContext(t) // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. rc := newReplicationController(0) podList := newPodList(nil, 5, v1.PodRunning, rc) podList.Items[0].Status.Phase = v1.PodSucceeded podList.Items[1].Status.Phase = v1.PodFailed expectedNames := sets.NewString() for _, pod := range podList.Items[2:] { expectedNames.Insert(pod.Name) type podData struct { podName string podPhase v1.PodPhase } var podPointers []*v1.Pod for i := range podList.Items { podPointers = append(podPointers, &podList.Items[i]) type test struct { name string pods []podData wantPodNames []string } got := FilterActivePods(logger, podPointers) gotNames := sets.NewString() for _, pod := range got { gotNames.Insert(pod.Name) tests := []test{ { name: \"Filters active pods\", pods: []podData{ {podName: \"pod-1\", podPhase: v1.PodSucceeded}, {podName: \"pod-2\", podPhase: v1.PodFailed}, {podName: \"pod-3\"}, {podName: \"pod-4\"}, {podName: \"pod-5\"}, }, wantPodNames: []string{\"pod-3\", \"pod-4\", \"pod-5\"}, }, } if diff := cmp.Diff(expectedNames.List(), gotNames.List()); diff != \"\" { t.Errorf(\"Active pod names (-want,+got):n%s\", diff) for _, test := range tests { t.Run(test.name, func(t *testing.T) { // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. rc := newReplicationController(0) podList := newPodList(nil, 5, v1.PodRunning, rc) for idx, testPod := range test.pods { podList.Items[idx].Name = testPod.podName podList.Items[idx].Status.Phase = testPod.podPhase } var podPointers []*v1.Pod for i := range podList.Items { podPointers = append(podPointers, &podList.Items[i]) } got := FilterActivePods(logger, podPointers) gotNames := sets.NewString() for _, pod := range got { gotNames.Insert(pod.Name) } if diff := cmp.Diff(test.wantPodNames, gotNames.List()); diff != \"\" { t.Errorf(\"Active pod names (-want,+got):n%s\", diff) } }) } } func TestSortingActivePods(t *testing.T) { numPods := 9 // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. rc := newReplicationController(0) podList := newPodList(nil, numPods, v1.PodRunning, rc) pods := make([]*v1.Pod, len(podList.Items)) for i := range podList.Items { pods[i] = &podList.Items[i] } // pods[0] is not scheduled yet. pods[0].Spec.NodeName = \"\" pods[0].Status.Phase = v1.PodPending // pods[1] is scheduled but pending. pods[1].Spec.NodeName = \"bar\" pods[1].Status.Phase = v1.PodPending // pods[2] is unknown. pods[2].Spec.NodeName = \"foo\" pods[2].Status.Phase = v1.PodUnknown // pods[3] is running but not ready. pods[3].Spec.NodeName = \"foo\" pods[3].Status.Phase = v1.PodRunning // pods[4] is running and ready but without LastTransitionTime. now := metav1.Now() pods[4].Spec.NodeName = \"foo\" pods[4].Status.Phase = v1.PodRunning pods[4].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}} pods[4].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[5] is running and ready and with LastTransitionTime. pods[5].Spec.NodeName = \"foo\" pods[5].Status.Phase = v1.PodRunning pods[5].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: now}} pods[5].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[6] is running ready for a longer time than pods[5]. then := metav1.Time{Time: now.AddDate(0, -1, 0)} pods[6].Spec.NodeName = \"foo\" pods[6].Status.Phase = v1.PodRunning pods[6].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} pods[6].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} // pods[7] has lower container restart count than pods[6]. pods[7].Spec.NodeName = \"foo\" pods[7].Status.Phase = v1.PodRunning pods[7].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} pods[7].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} pods[7].CreationTimestamp = now // pods[8] is older than pods[7]. pods[8].Spec.NodeName = \"foo\" pods[8].Status.Phase = v1.PodRunning pods[8].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} pods[8].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} pods[8].CreationTimestamp = then getOrder := func(pods []*v1.Pod) []string { names := make([]string, len(pods)) for i := range pods { names[i] = pods[i].Name } return names tests := []struct { name string pods []v1.Pod wantOrder []string }{ { name: \"Sorts by active pod\", pods: []v1.Pod{ { ObjectMeta: metav1.ObjectMeta{Name: \"unscheduled\"}, Spec: v1.PodSpec{NodeName: \"\"}, Status: v1.PodStatus{Phase: v1.PodPending}, }, { ObjectMeta: metav1.ObjectMeta{Name: \"scheduledButPending\"}, Spec: v1.PodSpec{NodeName: \"bar\"}, Status: v1.PodStatus{Phase: v1.PodPending}, }, { ObjectMeta: metav1.ObjectMeta{Name: \"unknownPhase\"}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{Phase: v1.PodUnknown}, }, { ObjectMeta: metav1.ObjectMeta{Name: \"runningButNotReady\"}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{Phase: v1.PodRunning}, }, { ObjectMeta: metav1.ObjectMeta{Name: \"runningNoLastTransitionTime\"}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}}, ContainerStatuses: []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}}, }, }, { ObjectMeta: metav1.ObjectMeta{Name: \"runningWithLastTransitionTime\"}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: now}}, ContainerStatuses: []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}}, }, }, { ObjectMeta: metav1.ObjectMeta{Name: \"runningLongerTime\"}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}}, ContainerStatuses: []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}}, }, }, { ObjectMeta: metav1.ObjectMeta{Name: \"lowerContainerRestartCount\", CreationTimestamp: now}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}}, ContainerStatuses: []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}}, }, }, { ObjectMeta: metav1.ObjectMeta{Name: \"oldest\", CreationTimestamp: then}, Spec: v1.PodSpec{NodeName: \"foo\"}, Status: v1.PodStatus{ Phase: v1.PodRunning, Conditions: []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}}, ContainerStatuses: []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}}, }, }, }, wantOrder: []string{ \"unscheduled\", \"scheduledButPending\", \"unknownPhase\", \"runningButNotReady\", \"runningNoLastTransitionTime\", \"runningWithLastTransitionTime\", \"runningLongerTime\", \"lowerContainerRestartCount\", \"oldest\", }, }, } expected := getOrder(pods) for _, test := range tests { t.Run(test.name, func(t *testing.T) { numPods := len(test.pods) for i := 0; i < 20; i++ { idx := rand.Perm(numPods) randomizedPods := make([]*v1.Pod, numPods) for j := 0; j < numPods; j++ { randomizedPods[j] = pods[idx[j]] } sort.Sort(ActivePods(randomizedPods)) actual := getOrder(randomizedPods) for i := 0; i < 20; i++ { idx := rand.Perm(numPods) randomizedPods := make([]*v1.Pod, numPods) for j := 0; j < numPods; j++ { randomizedPods[j] = &test.pods[idx[j]] } assert.EqualValues(t, expected, actual, \"expected %v, got %v\", expected, actual) sort.Sort(ActivePods(randomizedPods)) gotOrder := make([]string, len(randomizedPods)) for i := range randomizedPods { gotOrder[i] = randomizedPods[i].Name } if diff := cmp.Diff(test.wantOrder, gotOrder); diff != \"\" { t.Errorf(\"Sorted active pod names (-want,+got):n%s\", diff) } } }) } }"} {"_id":"doc-en-kubernetes-9844b7aa479297cf0a4bd31dda8a3c4dc8abe0c27753cbd442224befe5b3e71a","title":"","text":"{p1: unscheduled5Hours, p2: unscheduled8Hours}, {p1: ready5Hours, p2: ready10Hours}, } for _, tc := range equalityTests { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.LogarithmicScaleDown, !tc.disableLogarithmicScaleDown)() if tc.p2 == nil { tc.p2 = tc.p1 } podsWithRanks := ActivePodsWithRanks{ Pods: []*v1.Pod{tc.p1, tc.p2}, Rank: []int{1, 1}, Now: now, } if podsWithRanks.Less(0, 1) || podsWithRanks.Less(1, 0) { t.Errorf(\"expected pod %q to be equivalent to %q\", tc.p1.Name, tc.p2.Name) } for i, test := range equalityTests { t.Run(fmt.Sprintf(\"Equality tests %d\", i), func(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.LogarithmicScaleDown, !test.disableLogarithmicScaleDown)() if test.p2 == nil { test.p2 = test.p1 } podsWithRanks := ActivePodsWithRanks{ Pods: []*v1.Pod{test.p1, test.p2}, Rank: []int{1, 1}, Now: now, } if podsWithRanks.Less(0, 1) || podsWithRanks.Less(1, 0) { t.Errorf(\"expected pod %q to be equivalent to %q\", test.p1.Name, test.p2.Name) } }) } type podWithRank struct { pod *v1.Pod rank int"} {"_id":"doc-en-kubernetes-8a5e0797658f9a414bca245a0abdd30b445553923d6943a7a60bff2d7905b808","title":"","text":"{lesser: podWithRank{highPodDeletionCost, 2}, greater: podWithRank{lowPodDeletionCost, 1}, disablePodDeletioncost: true}, {lesser: podWithRank{ready2Hours, 1}, greater: podWithRank{ready5Hours, 1}}, } for i, test := range inequalityTests { t.Run(fmt.Sprintf(\"test%d\", i), func(t *testing.T) { t.Run(fmt.Sprintf(\"Inequality tests %d\", i), func(t *testing.T) { defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PodDeletionCost, !test.disablePodDeletioncost)() defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.LogarithmicScaleDown, !test.disableLogarithmicScaleDown)()"} {"_id":"doc-en-kubernetes-0be199efe99d9e612769dcba4cef9eca41b004e91b7c5132724131046913a7ae","title":"","text":"} func TestActiveReplicaSetsFiltering(t *testing.T) { var replicaSets []*apps.ReplicaSet replicaSets = append(replicaSets, newReplicaSet(\"zero\", 0)) replicaSets = append(replicaSets, nil) replicaSets = append(replicaSets, newReplicaSet(\"foo\", 1)) replicaSets = append(replicaSets, newReplicaSet(\"bar\", 2)) expectedNames := sets.NewString() for _, rs := range replicaSets[2:] { expectedNames.Insert(rs.Name) } got := FilterActiveReplicaSets(replicaSets) gotNames := sets.NewString() for _, rs := range got { gotNames.Insert(rs.Name) rsUuid := uuid.NewUUID() tests := []struct { name string replicaSets []*apps.ReplicaSet wantReplicaSets []*apps.ReplicaSet }{ { name: \"Filters active replica sets\", replicaSets: []*apps.ReplicaSet{ newReplicaSet(\"zero\", 0, rsUuid), nil, newReplicaSet(\"foo\", 1, rsUuid), newReplicaSet(\"bar\", 2, rsUuid), }, wantReplicaSets: []*apps.ReplicaSet{ newReplicaSet(\"foo\", 1, rsUuid), newReplicaSet(\"bar\", 2, rsUuid), }, }, } if diff := cmp.Diff(expectedNames.List(), gotNames.List()); diff != \"\" { t.Errorf(\"Active replica set names (-want,+got):n%s\", diff) for _, test := range tests { t.Run(test.name, func(t *testing.T) { gotReplicaSets := FilterActiveReplicaSets(test.replicaSets) if diff := cmp.Diff(test.wantReplicaSets, gotReplicaSets); diff != \"\" { t.Errorf(\"Active replica set names (-want,+got):n%s\", diff) } }) } }"} {"_id":"doc-en-kubernetes-1f68b41cd5282f66f55aa0da497ef8f8c68faa4c28f7bb72795910bbead745da","title":"","text":"return false, pod, fmt.Errorf(\"invalid pod: %#v\", obj) } if newPod.Name == \"\" { return true, pod, fmt.Errorf(\"invalid pod: name is needed for the pod\") } // Apply default values and validate the pod. if err = defaultFn(newPod); err != nil { return true, pod, err"} {"_id":"doc-en-kubernetes-1156607eb627874616a0cf3dffa0a49ad645a50b98fdb4e46092b4ea78327a88","title":"","text":"// Apply default values and validate pods. for i := range newPods.Items { newPod := &newPods.Items[i] if newPod.Name == \"\" { return true, pods, fmt.Errorf(\"invalid pod: name is needed for the pod\") } if err = defaultFn(newPod); err != nil { return true, pods, err }"} {"_id":"doc-en-kubernetes-e1b039d72ee0447b989c5ebe01871bc68e477d9c74e0385ac9b83c1c380ca5f2","title":"","text":"driver := NewDriver(f, nodes, func() app.Resources { return app.Resources{ NodeLocal: true, MaxAllocations: 2, MaxAllocations: 1, Nodes: nodes.NodeNames, } }) driver2 := NewDriver(f, nodes, func() app.Resources { return app.Resources{ NodeLocal: true, MaxAllocations: 2, MaxAllocations: 1, Nodes: nodes.NodeNames, AllocateWrapper: func("} {"_id":"doc-en-kubernetes-71824e4b5be8aae0d98209ffba125a2dcb314b498867d5f53c6510840be44736","title":"","text":"parameters1 := b.parameters() parameters2 := b2.parameters() pod1 := b.podExternal() pod2 := b2.podExternal() // Order is relevant here: each pod must be matched with its own claim. pod1claim1 := b.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) pod1 := b.podExternal() pod2claim1 := b2.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) pod1claim2 := b2.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) pod1claim3 := b2.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) pod2 := b2.podExternal() // Add another claim to pod1. pod1claim2 := b2.externalClaim(resourcev1alpha2.AllocationModeWaitForFirstConsumer) pod1.Spec.ResourceClaims = append(pod1.Spec.ResourceClaims, v1.PodResourceClaim{ Name: \"claim-other1\", Name: \"claim-other\", Source: v1.ClaimSource{ ResourceClaimName: &pod1claim2.Name, }, }, v1.PodResourceClaim{ Name: \"claim-other2\", Source: v1.ClaimSource{ ResourceClaimName: &pod1claim3.Name, }, }, ) // Block on the second, third external claim from driver2 that is to be allocated. // Allocating the second claim in pod1 has to wait until pod2 has // consumed the available resources on the node. blockClaim, cancelBlockClaim := context.WithCancel(ctx) defer cancelBlockClaim() b2.create(ctx, parameters2, pod1claim2, pod1claim3) b.create(ctx, parameters1, pod1claim1, pod1) allocateWrapper2 = func(ctx context.Context, claimAllocations []*controller.ClaimAllocation, selectedNode string,"} {"_id":"doc-en-kubernetes-7abf70bfdccbb1283eac3cab01128cb639db11c29d3c00f83b7eac443a9c7d83","title":"","text":"claimAllocations []*controller.ClaimAllocation, selectedNode string), ) { // pod1 will have only external-claim[2-3], it has to wait // for pod2 to consume resources from driver2 if claimAllocations[0].Claim.Name != \"external-claim-other\" { if claimAllocations[0].Claim.Name == pod1claim2.Name { <-blockClaim.Done() } handler(ctx, claimAllocations, selectedNode) return } b.create(ctx, parameters1, parameters2, pod1claim1, pod1claim2, pod1) ginkgo.By(\"waiting for one claim from driver1 to be allocated\") var nodeSelector *v1.NodeSelector gomega.Eventually(ctx, func(ctx context.Context) (int, error) {"} {"_id":"doc-en-kubernetes-792f6cdf81b6a139cea37b8dae1f9cd5a22883a93104e5807974a1cb0d4c9805","title":"","text":"b2.create(ctx, pod2claim1, pod2) framework.ExpectNoError(e2epod.WaitForPodRunningInNamespace(ctx, f.ClientSet, pod2), \"start pod 2\") // Allow allocation of pod1 claim2, claim3 to proceed. It should fail now // Allow allocation of second claim in pod1 to proceed. It should fail now // and the other node must be used instead, after deallocating // the first claim. ginkgo.By(\"move first pod to other node\")"} {"_id":"doc-en-kubernetes-f233a458831cf6cf2a3173d7f25548181314c969ca600adbc74a5466b8d17c88","title":"","text":"} } if !probeGracePeriodInUse(oldPodSpec) { // Set pod-level terminationGracePeriodSeconds to nil if the feature is disabled and it is not used VisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool { if c.LivenessProbe != nil { c.LivenessProbe.TerminationGracePeriodSeconds = nil } if c.StartupProbe != nil { c.StartupProbe.TerminationGracePeriodSeconds = nil } // cannot be set for readiness probes return true }) } // If the feature is disabled and not in use, drop the hostUsers field. if !utilfeature.DefaultFeatureGate.Enabled(features.UserNamespacesSupport) && !hostUsersInUse(oldPodSpec) { // Drop the field in podSpec only if SecurityContext is not nil."} {"_id":"doc-en-kubernetes-8a0bd2821522448b3da9a1643b65040b25597b47e3d88e8605e11fef31ff66cf","title":"","text":"return false } // probeGracePeriodInUse returns true if the pod spec is non-nil and has a probe that makes use // of the probe-level terminationGracePeriodSeconds feature func probeGracePeriodInUse(podSpec *api.PodSpec) bool { if podSpec == nil { return false } var inUse bool VisitContainers(podSpec, AllContainers, func(c *api.Container, containerType ContainerType) bool { // cannot be set for readiness probes if (c.LivenessProbe != nil && c.LivenessProbe.TerminationGracePeriodSeconds != nil) || (c.StartupProbe != nil && c.StartupProbe.TerminationGracePeriodSeconds != nil) { inUse = true return false } return true }) return inUse } // schedulingGatesInUse returns true if the pod spec is non-nil and it has SchedulingGates field set. func schedulingGatesInUse(podSpec *api.PodSpec) bool { if podSpec == nil {"} {"_id":"doc-en-kubernetes-e05d2146761432580c39b2c741a72f8342e3f9e56971d3e3d5a9e22b482fac52","title":"","text":"\"k8s.io/apimachinery/pkg/labels\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apimachinery/pkg/util/validation/field\" celconfig \"k8s.io/apiserver/pkg/apis/cel\" \"k8s.io/apiserver/pkg/features\""} {"_id":"doc-en-kubernetes-c87afd42aff4c365863e1843bfddf521e39263af800b8d827e9c602795144eb2","title":"","text":"} // WarningsOnCreate returns warnings for the creation of the given object. func (customResourceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return nil func (a customResourceStrategy) WarningsOnCreate(ctx context.Context, obj runtime.Object) []string { return generateWarningsFromObj(obj, nil) } func generateWarningsFromObj(obj, old runtime.Object) []string { var allWarnings []string fldPath := field.NewPath(\"metadata\", \"finalizers\") newObjAccessor, err := meta.Accessor(obj) if err != nil { return allWarnings } newAdded := sets.NewString(newObjAccessor.GetFinalizers()...) if old != nil { oldObjAccessor, err := meta.Accessor(old) if err != nil { return allWarnings } newAdded = newAdded.Difference(sets.NewString(oldObjAccessor.GetFinalizers()...)) } for _, finalizer := range newAdded.List() { allWarnings = append(allWarnings, validateKubeFinalizerName(finalizer, fldPath)...) } return allWarnings } // Canonicalize normalizes the object after validation."} {"_id":"doc-en-kubernetes-0200fd883335fba82b92053d7cbfec46fc9b43c1631c56cf108efbfa15bbc491","title":"","text":"} // WarningsOnUpdate returns warnings for the given update. func (customResourceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil func (a customResourceStrategy) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return generateWarningsFromObj(obj, old) } // GetAttrs returns labels and fields of a given object for filtering purposes."} {"_id":"doc-en-kubernetes-4903462c57c22c3ed4277d1f8d463f8648013128123d30f9a13cbddbc5e56714","title":"","text":"\"math\" \"strings\" corev1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/meta\" \"k8s.io/apimachinery/pkg/api/validation\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured\" \"k8s.io/apimachinery/pkg/runtime\" \"k8s.io/apimachinery/pkg/runtime/schema\" \"k8s.io/apimachinery/pkg/util/sets\" apimachineryvalidation \"k8s.io/apimachinery/pkg/util/validation\" \"k8s.io/apimachinery/pkg/util/validation/field\" \"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions\""} {"_id":"doc-en-kubernetes-707ef183d0214754e0257a3b0ed05dda01de1981248feb01d718b650ffc88891","title":"","text":"return allErrs } // WarningsOnUpdate returns warnings for the given update. func (customResourceValidator) WarningsOnUpdate(ctx context.Context, obj, old runtime.Object) []string { return nil var standardFinalizers = sets.NewString( metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents, string(corev1.FinalizerKubernetes), ) func validateKubeFinalizerName(stringValue string, fldPath *field.Path) []string { var allWarnings []string for _, msg := range apimachineryvalidation.IsQualifiedName(stringValue) { allWarnings = append(allWarnings, fmt.Sprintf(\"%s: %q: %s\", fldPath.String(), stringValue, msg)) } if len(strings.Split(stringValue, \"/\")) == 1 { if !standardFinalizers.Has(stringValue) { allWarnings = append(allWarnings, fmt.Sprintf(\"%s: %q: prefer a domain-qualified finalizer name to avoid accidental conflicts with other finalizer writers\", fldPath.String(), stringValue)) } } return allWarnings } func (a customResourceValidator) ValidateStatusUpdate(ctx context.Context, obj, old runtime.Object, scale *apiextensions.CustomResourceSubresourceScale) field.ErrorList {"} {"_id":"doc-en-kubernetes-767e2b6ce43a0969e616ab1b6dc5a7ef16f824a311466cc87d6a8bed93516642","title":"","text":"} }` crdApplyFinalizerBody = ` { \"apiVersion\": \"%s\", \"kind\": \"%s\", \"metadata\": { \"name\": \"%s\", \"finalizers\": %s }, \"spec\": { \"knownField1\": \"val1\", \"ports\": [{ \"name\": \"portName\", \"containerPort\": 8080, \"protocol\": \"TCP\", \"hostPort\": 8082 }], \"embeddedObj\": { \"apiVersion\": \"v1\", \"kind\": \"ConfigMap\", \"metadata\": { \"name\": \"my-cm\", \"namespace\": \"my-ns\" } } } }` patchYAMLBody = ` apiVersion: %s kind: %s metadata: name: %s finalizers: - test-finalizer - test/finalizer spec: cronSpec: \"* * * * */5\" ports:"} {"_id":"doc-en-kubernetes-354f21c6e03be5f13679053c8a69ad761da77ee5768f72bf7298e62bc6467ea3","title":"","text":"t.Run(\"PatchCRDSchemaless\", func(t *testing.T) { testFieldValidationPatchCRDSchemaless(t, rest, schemalessGVK, schemalessGVR) }) t.Run(\"ApplyCreateCRDSchemaless\", func(t *testing.T) { testFieldValidationApplyCreateCRDSchemaless(t, rest, schemalessGVK, schemalessGVR) }) t.Run(\"ApplyUpdateCRDSchemaless\", func(t *testing.T) { testFieldValidationApplyUpdateCRDSchemaless(t, rest, schemalessGVK, schemalessGVR) }) t.Run(\"testFinalizerValidationApplyCreateCRD\", func(t *testing.T) { testFinalizerValidationApplyCreateAndUpdateCRD(t, rest, schemalessGVK, schemalessGVR) }) } // testFieldValidationPost tests POST requests containing unknown fields with"} {"_id":"doc-en-kubernetes-960582acebb5930ccc241b90c98e1d8469a5141817754e70d76e1c2ddff7041d","title":"","text":"} } func testFinalizerValidationApplyCreateAndUpdateCRD(t *testing.T, rest rest.Interface, gvk schema.GroupVersionKind, gvr schema.GroupVersionResource) { var testcases = []struct { name string finalizer []string updatedFinalizer []string opts metav1.PatchOptions expectUpdateWarnings []string expectCreateWarnings []string }{ { name: \"create-crd-with-invalid-finalizer\", finalizer: []string{\"invalid-finalizer\"}, expectCreateWarnings: []string{ `metadata.finalizers: \"invalid-finalizer\": prefer a domain-qualified finalizer name to avoid accidental conflicts with other finalizer writers`, }, }, { name: \"create-crd-with-valid-finalizer\", finalizer: []string{\"kubernetes.io/valid-finalizer\"}, }, { name: \"update-crd-with-invalid-finalizer\", finalizer: []string{\"invalid-finalizer\"}, updatedFinalizer: []string{\"another-invalid-finalizer\"}, expectCreateWarnings: []string{ `metadata.finalizers: \"invalid-finalizer\": prefer a domain-qualified finalizer name to avoid accidental conflicts with other finalizer writers`, }, expectUpdateWarnings: []string{ `metadata.finalizers: \"another-invalid-finalizer\": prefer a domain-qualified finalizer name to avoid accidental conflicts with other finalizer writers`, }, }, { name: \"update-crd-with-valid-finalizer\", finalizer: []string{\"kubernetes.io/valid-finalizer\"}, updatedFinalizer: []string{\"kubernetes.io/another-valid-finalizer\"}, }, { name: \"update-crd-with-valid-finalizer-leaving-an-existing-invalid-finalizer\", finalizer: []string{\"invalid-finalizer\"}, updatedFinalizer: []string{\"kubernetes.io/another-valid-finalizer\"}, expectCreateWarnings: []string{ `metadata.finalizers: \"invalid-finalizer\": prefer a domain-qualified finalizer name to avoid accidental conflicts with other finalizer writers`, }, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { kind := gvk.Kind apiVersion := gvk.Group + \"/\" + gvk.Version // create the CR as specified by the test case name := fmt.Sprintf(\"apply-create-crd-%s\", tc.name) finalizerVal, _ := json.Marshal(tc.finalizer) applyCreateBody := []byte(fmt.Sprintf(crdApplyFinalizerBody, apiVersion, kind, name, finalizerVal)) req := rest.Patch(types.ApplyPatchType). AbsPath(\"/apis\", gvr.Group, gvr.Version, gvr.Resource). Name(name). Param(\"fieldManager\", \"apply_test\"). VersionedParams(&tc.opts, metav1.ParameterCodec) result := req.Body(applyCreateBody).Do(context.TODO()) if result.Error() != nil { t.Fatalf(\"unexpected error: %v\", result.Error()) } if len(result.Warnings()) != len(tc.expectCreateWarnings) { for _, r := range result.Warnings() { t.Logf(\"received warning: %v\", r) } t.Fatalf(\"unexpected number of warnings, expected: %d, got: %d\", len(tc.expectCreateWarnings), len(result.Warnings())) } for i, expectedWarning := range tc.expectCreateWarnings { if expectedWarning != result.Warnings()[i].Text { t.Fatalf(\"expected warning: %s, got warning: %s\", expectedWarning, result.Warnings()[i].Text) } } if len(tc.updatedFinalizer) != 0 { finalizerVal, _ := json.Marshal(tc.updatedFinalizer) applyUpdateBody := []byte(fmt.Sprintf(crdApplyFinalizerBody, apiVersion, kind, name, finalizerVal)) updateReq := rest.Patch(types.ApplyPatchType). AbsPath(\"/apis\", gvr.Group, gvr.Version, gvr.Resource). Name(name). Param(\"fieldManager\", \"apply_test\"). VersionedParams(&tc.opts, metav1.ParameterCodec) result = updateReq.Body(applyUpdateBody).Do(context.TODO()) if result.Error() != nil { t.Fatalf(\"unexpected error: %v\", result.Error()) } if len(result.Warnings()) != len(tc.expectUpdateWarnings) { t.Fatalf(\"unexpected number of warnings, expected: %d, got: %d\", len(tc.expectUpdateWarnings), len(result.Warnings())) } for i, expectedWarning := range tc.expectUpdateWarnings { if expectedWarning != result.Warnings()[i].Text { t.Fatalf(\"expected warning: %s, got warning: %s\", expectedWarning, result.Warnings()[i].Text) } } } }) } } func setupCRD(t testing.TB, config *rest.Config, apiGroup string, schemaless bool) *apiextensionsv1.CustomResourceDefinition { apiExtensionClient, err := apiextensionsclient.NewForConfig(config) if err != nil {"} {"_id":"doc-en-kubernetes-e470faecf924856acb4a948c283fcc6ec6e53f5d0f62d4df10540b282e9c3cad","title":"","text":"metadata: name: %s finalizers: - test-finalizer - test/finalizer spec: cronSpec: \"* * * * */5\" ports:"} {"_id":"doc-en-kubernetes-2d0a09c2096f687a01e2a1964b6709410346ccb3e5f97799251efe188785f70c","title":"","text":"Labels: testSvcLabels, }, Spec: v1.ServiceSpec{ Type: \"ClusterIP\", Type: \"LoadBalancer\", Ports: []v1.ServicePort{{ Name: \"http\", Protocol: v1.ProtocolTCP, Port: int32(80), TargetPort: intstr.FromInt(80), }}, LoadBalancerClass: utilpointer.String(\"example.com/internal-vip\"), }, } _, err = cs.CoreV1().Services(ns).Create(ctx, &testService, metav1.CreateOptions{})"} {"_id":"doc-en-kubernetes-8e82df1fdd745748b05e776339a98276920672979399b7895ffe37702db55d66","title":"","text":"// Error returns detailed information of why the pod failed to fit on each node. // A message format is \"0/X nodes are available: . . .\" func (f *FitError) Error() string { reasons := make(map[string]int) for _, status := range f.Diagnosis.NodeToStatusMap { for _, reason := range status.Reasons() { reasons[reason]++ } } reasonMsg := fmt.Sprintf(NoNodeAvailableMsg+\":\", f.NumAllNodes) // Add the messages from PreFilter plugins to reasonMsg. preFilterMsg := f.Diagnosis.PreFilterMsg if preFilterMsg != \"\" { // PreFilter plugin returns unschedulable. // Add the messages from PreFilter plugins to reasonMsg. reasonMsg += fmt.Sprintf(SeparatorFormat, preFilterMsg) } sortReasonsHistogram := func() []string { var reasonStrings []string for k, v := range reasons { reasonStrings = append(reasonStrings, fmt.Sprintf(\"%v %v\", v, k)) if preFilterMsg == \"\" { // the scheduling cycle went through PreFilter extension point successfully. // // When the prefilter plugin returns unschedulable, // the scheduling framework inserts the same unschedulable status to all nodes in NodeToStatusMap. // So, we shouldn't add the message from NodeToStatusMap when the PreFilter failed. // Otherwise, we will have duplicated reasons in the error message. reasons := make(map[string]int) for _, status := range f.Diagnosis.NodeToStatusMap { for _, reason := range status.Reasons() { reasons[reason]++ } } sortReasonsHistogram := func() []string { var reasonStrings []string for k, v := range reasons { reasonStrings = append(reasonStrings, fmt.Sprintf(\"%v %v\", v, k)) } sort.Strings(reasonStrings) return reasonStrings } sortedFilterMsg := sortReasonsHistogram() if len(sortedFilterMsg) != 0 { reasonMsg += fmt.Sprintf(SeparatorFormat, strings.Join(sortedFilterMsg, \", \")) } sort.Strings(reasonStrings) return reasonStrings } sortedFilterMsg := sortReasonsHistogram() if len(sortedFilterMsg) != 0 { reasonMsg += fmt.Sprintf(SeparatorFormat, strings.Join(sortedFilterMsg, \", \")) } // Add the messages from PostFilter plugins to reasonMsg. // We can add this message regardless of whether the scheduling cycle fails at PreFilter or Filter // since we may run PostFilter (if enabled) in both cases. postFilterMsg := f.Diagnosis.PostFilterMsg if postFilterMsg != \"\" { reasonMsg += fmt.Sprintf(SeparatorFormat, postFilterMsg)"} {"_id":"doc-en-kubernetes-6684d11ce3cbd4e421a97da17435980c6dc2017344503d2edff09c0db49d73b4","title":"","text":"numAllNodes: 3, diagnosis: Diagnosis{ PreFilterMsg: \"Node(s) failed PreFilter plugin FalsePreFilter\", NodeToStatusMap: NodeToStatusMap{ // They're inserted by the framework. // We don't include them in the reason message because they'd be just duplicates. \"node1\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), \"node2\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), \"node3\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), }, }, wantReasonMsg: \"0/3 nodes are available: Node(s) failed PreFilter plugin FalsePreFilter.\", }, { name: \"nodes failed Prefilter plugin and the preemption also failed\", numAllNodes: 3, diagnosis: Diagnosis{ PreFilterMsg: \"Node(s) failed PreFilter plugin FalsePreFilter\", NodeToStatusMap: NodeToStatusMap{ // They're inserted by the framework. // We don't include them in the reason message because they'd be just duplicates. \"node1\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), \"node2\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), \"node3\": NewStatus(Unschedulable, \"Node(s) failed PreFilter plugin FalsePreFilter\"), }, // PostFilterMsg will be included. PostFilterMsg: \"Error running PostFilter plugin FailedPostFilter\", }, wantReasonMsg: \"0/3 nodes are available: Node(s) failed PreFilter plugin FalsePreFilter. Error running PostFilter plugin FailedPostFilter.\", }, { name: \"nodes failed one Filter plugin with an empty PostFilterMsg\", numAllNodes: 3, diagnosis: Diagnosis{"} {"_id":"doc-en-kubernetes-ec79ce7144db2ca9006d403658db2c45b0bff96f34830b5e8d03fb9e85d665a9","title":"","text":"if !s.IsUnschedulable() { return nil, diagnosis, s.AsError() } // All nodes in NodeToStatusMap will have the same status so that they can be handled in the preemption. // Some non trivial refactoring is needed to avoid this copy. for _, n := range allNodes { diagnosis.NodeToStatusMap[n.Node().Name] = s } // Record the messages from PreFilter in Diagnosis.PreFilterMsg. msg := s.Message() diagnosis.PreFilterMsg = msg"} {"_id":"doc-en-kubernetes-634a49721bd9eea169b166214f8d278830239065bc96757197134900b7d1accc","title":"","text":"Pod: st.MakePod().Name(\"ignore\").UID(\"ignore\").PVC(\"unknownPVC\").Obj(), NumAllNodes: 2, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{}, NodeToStatusMap: framework.NodeToStatusMap{ \"node1\": framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"unknownPVC\" not found`).WithFailedPlugin(\"VolumeBinding\"), \"node2\": framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"unknownPVC\" not found`).WithFailedPlugin(\"VolumeBinding\"), }, PreFilterMsg: `persistentvolumeclaim \"unknownPVC\" not found`, UnschedulablePlugins: sets.New(volumebinding.Name), },"} {"_id":"doc-en-kubernetes-9cbff752b2891619d59a477eb7e1ffdb99d699c14f38c960d9adbeb6add08d6f","title":"","text":"Pod: st.MakePod().Name(\"ignore\").UID(\"ignore\").Namespace(v1.NamespaceDefault).PVC(\"existingPVC\").Obj(), NumAllNodes: 2, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{}, NodeToStatusMap: framework.NodeToStatusMap{ \"node1\": framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"existingPVC\" is being deleted`).WithFailedPlugin(\"VolumeBinding\"), \"node2\": framework.NewStatus(framework.UnschedulableAndUnresolvable, `persistentvolumeclaim \"existingPVC\" is being deleted`).WithFailedPlugin(\"VolumeBinding\"), }, PreFilterMsg: `persistentvolumeclaim \"existingPVC\" is being deleted`, UnschedulablePlugins: sets.New(volumebinding.Name), },"} {"_id":"doc-en-kubernetes-32d4f84a6ec033d47e982fcbd48a820bf1aad31bb16327044717c052c9a8e859","title":"","text":"Pod: st.MakePod().Name(\"test-prefilter\").UID(\"test-prefilter\").Obj(), NumAllNodes: 2, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{}, NodeToStatusMap: framework.NodeToStatusMap{ \"1\": framework.NewStatus(framework.UnschedulableAndUnresolvable, \"injected unschedulable status\").WithFailedPlugin(\"FakePreFilter\"), \"2\": framework.NewStatus(framework.UnschedulableAndUnresolvable, \"injected unschedulable status\").WithFailedPlugin(\"FakePreFilter\"), }, PreFilterMsg: \"injected unschedulable status\", UnschedulablePlugins: sets.New(\"FakePreFilter\"), },"} {"_id":"doc-en-kubernetes-1c2efdd6a5017f55dd7744a0707defd26a8f30a4dd99211c6302cfd085992506","title":"","text":"Pod: st.MakePod().Name(\"test-prefilter\").UID(\"test-prefilter\").Obj(), NumAllNodes: 3, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{}, NodeToStatusMap: framework.NodeToStatusMap{ \"node1\": framework.NewStatus(framework.Unschedulable, \"node(s) didn't satisfy plugin(s) [FakePreFilter2 FakePreFilter3] simultaneously\"), \"node2\": framework.NewStatus(framework.Unschedulable, \"node(s) didn't satisfy plugin(s) [FakePreFilter2 FakePreFilter3] simultaneously\"), \"node3\": framework.NewStatus(framework.Unschedulable, \"node(s) didn't satisfy plugin(s) [FakePreFilter2 FakePreFilter3] simultaneously\"), }, UnschedulablePlugins: sets.Set[string]{}, PreFilterMsg: \"node(s) didn't satisfy plugin(s) [FakePreFilter2 FakePreFilter3] simultaneously\", },"} {"_id":"doc-en-kubernetes-1af62f6f00e1c18b27b5c5254c89eea05916cd0a0f9e8a15e6c70e5b804d1bcb","title":"","text":"Pod: st.MakePod().Name(\"test-prefilter\").UID(\"test-prefilter\").Obj(), NumAllNodes: 1, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{}, NodeToStatusMap: framework.NodeToStatusMap{ \"node1\": framework.NewStatus(framework.Unschedulable, \"node(s) didn't satisfy plugin FakePreFilter2\"), }, UnschedulablePlugins: sets.Set[string]{}, PreFilterMsg: \"node(s) didn't satisfy plugin FakePreFilter2\", },"} {"_id":"doc-en-kubernetes-97a05e4e0c74e92db401c475667c4939af032e1d3a019ae0a2ab408edbf3c2cd","title":"","text":"} // Complete completes all the required options. func (o *Options) Complete() error { func (o *Options) Complete(fs *pflag.FlagSet) error { if len(o.ConfigFile) == 0 && len(o.WriteConfigTo) == 0 { o.config.HealthzBindAddress = addressFromDeprecatedFlags(o.config.HealthzBindAddress, o.healthzPort) o.config.MetricsBindAddress = addressFromDeprecatedFlags(o.config.MetricsBindAddress, o.metricsPort)"} {"_id":"doc-en-kubernetes-cc88e3488bf1b0a8d7c11698be1c57a0d168d320f73ec98dd7b7af39fec67a55","title":"","text":"if err != nil { return err } // Before we overwrite the config which holds the parsed // command line parameters, we need to copy all modified // logging settings over to the loaded config (i.e. logging // command line flags have priority). Otherwise `--config // ... -v=5` doesn't work (config resets verbosity even // when it contains no logging settings). copyLogsFromFlags(fs, &c.Logging) o.config = c if err := o.initWatcher(); err != nil {"} {"_id":"doc-en-kubernetes-448fe9202c75734089d184de32cf879e535a08513d729b80b8db5366024ef5c5","title":"","text":"return utilfeature.DefaultMutableFeatureGate.SetFromMap(o.config.FeatureGates) } // copyLogsFromFlags applies the logging flags from the given flag set to the given // configuration. Fields for which the corresponding flag was not used are left // unmodified. For fields that have multiple values (like vmodule), the values from // the flags get joined so that the command line flags have priority. // // TODO (pohly): move this to logsapi func copyLogsFromFlags(from *pflag.FlagSet, to *logsapi.LoggingConfiguration) error { var cloneFS pflag.FlagSet logsapi.AddFlags(to, &cloneFS) vmodule := to.VModule to.VModule = nil var err error cloneFS.VisitAll(func(f *pflag.Flag) { if err != nil { return } fsFlag := from.Lookup(f.Name) if fsFlag == nil { err = fmt.Errorf(\"logging flag %s not found in flag set\", f.Name) return } if !fsFlag.Changed { return } if setErr := f.Value.Set(fsFlag.Value.String()); setErr != nil { err = fmt.Errorf(\"copying flag %s value: %v\", f.Name, setErr) return } }) to.VModule = append(to.VModule, vmodule...) return err } // Creates a new filesystem watcher and adds watches for the config file. func (o *Options) initWatcher() error { fswatcher := filesystem.NewFsnotifyWatcher()"} {"_id":"doc-en-kubernetes-473d116b14f59977dac9248de0c3f7cbbd1fbe942852893fc23c7c80b46906b1","title":"","text":"return fmt.Errorf(\"failed os init: %w\", err) } if err := opts.Complete(); err != nil { if err := opts.Complete(cmd.Flags()); err != nil { return fmt.Errorf(\"failed complete: %w\", err) }"} {"_id":"doc-en-kubernetes-bf03ac6f3c5e2e29c7b7167248d5301fef1684104afc69ed2f94f68dac0592d2","title":"","text":"\"testing\" \"time\" \"github.com/spf13/pflag\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/runtime\""} {"_id":"doc-en-kubernetes-51b2b40a7953d8cb897750bab3ed7a637ebbfd9c5caab2a8603008a2348a0512","title":"","text":"opt := NewOptions() opt.ConfigFile = file.Name() err = opt.Complete() err = opt.Complete(new(pflag.FlagSet)) if err != nil { t.Fatal(err) }"} {"_id":"doc-en-kubernetes-2ea25b496dbded0a98a014511b12a69c47119772e008ed3b77d2071cc4cac28b","title":"","text":"import ( \"errors\" \"fmt\" \"io/ioutil\" \"path\" \"testing\" \"time\" \"github.com/google/go-cmp/cmp\" \"github.com/spf13/pflag\" \"github.com/stretchr/testify/assert\" \"github.com/stretchr/testify/require\" v1 \"k8s.io/api/core/v1\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" clientsetfake \"k8s.io/client-go/kubernetes/fake\" componentbaseconfig \"k8s.io/component-base/config\""} {"_id":"doc-en-kubernetes-0e91228d9b8bcd856813819117d9b5a80207db12a8343cdd5a775e4bd7abae1d","title":"","text":"} } // TestOptionsComplete checks that command line flags are combined with a // config properly. func TestOptionsComplete(t *testing.T) { header := `apiVersion: kubeproxy.config.k8s.io/v1alpha1 kind: KubeProxyConfiguration ` // Determine default config (depends on platform defaults). o := NewOptions() require.NoError(t, o.Complete(new(pflag.FlagSet))) expected := o.config config := header + `logging: format: json flushFrequency: 1s verbosity: 10 vmodule: - filePattern: foo.go verbosity: 6 - filePattern: bar.go verbosity: 8 ` expectedLoggingConfig := logsapi.LoggingConfiguration{ Format: \"json\", FlushFrequency: logsapi.TimeOrMetaDuration{Duration: metav1.Duration{Duration: time.Second}, SerializeAsString: true}, Verbosity: 10, VModule: []logsapi.VModuleItem{ { FilePattern: \"foo.go\", Verbosity: 6, }, { FilePattern: \"bar.go\", Verbosity: 8, }, }, Options: logsapi.FormatOptions{ JSON: logsapi.JSONOptions{ InfoBufferSize: resource.QuantityValue{Quantity: resource.MustParse(\"0\")}, }, }, } for name, tc := range map[string]struct { config string flags []string expected *kubeproxyconfig.KubeProxyConfiguration }{ \"empty\": { expected: expected, }, \"empty-config\": { config: header, expected: expected, }, \"logging-config\": { config: config, expected: func() *kubeproxyconfig.KubeProxyConfiguration { c := expected.DeepCopy() c.Logging = *expectedLoggingConfig.DeepCopy() return c }(), }, \"flags\": { flags: []string{ \"-v=7\", \"--vmodule\", \"goo.go=8\", }, expected: func() *kubeproxyconfig.KubeProxyConfiguration { c := expected.DeepCopy() c.Logging.Verbosity = 7 c.Logging.VModule = append(c.Logging.VModule, logsapi.VModuleItem{ FilePattern: \"goo.go\", Verbosity: 8, }) return c }(), }, \"both\": { config: config, flags: []string{ \"-v=7\", \"--vmodule\", \"goo.go=8\", \"--ipvs-scheduler\", \"some-scheduler\", // Overwritten by config. }, expected: func() *kubeproxyconfig.KubeProxyConfiguration { c := expected.DeepCopy() c.Logging = *expectedLoggingConfig.DeepCopy() // Flag wins. c.Logging.Verbosity = 7 // Flag and config get merged with command line flags first. c.Logging.VModule = append([]logsapi.VModuleItem{ { FilePattern: \"goo.go\", Verbosity: 8, }, }, c.Logging.VModule...) return c }(), }, } { t.Run(name, func(t *testing.T) { options := NewOptions() fs := new(pflag.FlagSet) options.AddFlags(fs) flags := tc.flags if len(tc.config) > 0 { tmp := t.TempDir() configFile := path.Join(tmp, \"kube-proxy.conf\") require.NoError(t, ioutil.WriteFile(configFile, []byte(tc.config), 0666)) flags = append(flags, \"--config\", configFile) } require.NoError(t, fs.Parse(flags)) require.NoError(t, options.Complete(fs)) assert.Equal(t, tc.expected, options.config) }) } } type fakeProxyServerLongRun struct{} // Run runs the specified ProxyServer."} {"_id":"doc-en-kubernetes-4a1013b6802732c111d54b1fc7935f375839d041198db2b896a4aa5255a04b80","title":"","text":"- baseImportPath: \"./vendor/k8s.io/kms/\" allowedImports: - k8s.io/apimachinery - k8s.io/klog - k8s.io/kms - baseImportPath: \"./vendor/k8s.io/endpointslice/\""} {"_id":"doc-en-kubernetes-8aaa1c1d3615d2089ed2e2f411c97b5f20e78c62d5042bcf0a651954c6c192a0","title":"","text":"require ( github.com/gogo/protobuf v1.3.2 google.golang.org/grpc v1.56.3 k8s.io/apimachinery v0.0.0 ) require ( github.com/go-logr/logr v1.2.4 // indirect github.com/golang/protobuf v1.5.3 // indirect golang.org/x/net v0.17.0 // indirect golang.org/x/sys v0.13.0 // indirect golang.org/x/text v0.13.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 // indirect google.golang.org/protobuf v1.31.0 // indirect k8s.io/klog/v2 v2.100.1 // indirect k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect ) replace ( k8s.io/apimachinery => ../apimachinery k8s.io/kms => ../kms ) replace k8s.io/kms => ../kms "} {"_id":"doc-en-kubernetes-8b23cb76ebd917e9e1d171b5ee02e635e0ff2674c1910d75761e48b123a1e89d","title":"","text":"cloud.google.com/go/compute v1.19.1/go.mod h1:6ylj3a05WF8leseCdIf77NK0g1ey+nj5IKd5/kvShxE= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cncf/udpa/go v0.0.0-20220112060539-c52dc94e7fbe/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= github.com/cncf/xds/go v0.0.0-20230607035331-e9ce68804cb4/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.11.1-0.20230524094728-9239064ad72f/go.mod h1:sfYdkwUW4BA3PbKjySwjJy+O4Pu0h62rlqCMHNk+K+Q= github.com/envoyproxy/protoc-gen-validate v0.10.1/go.mod h1:DRjgyB0I43LtJapqN6NiRwroiAU2PaFuvk/vjgh61ss= github.com/evanphx/json-patch v4.12.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= github.com/onsi/gomega v1.28.0/go.mod h1:A1H2JE76sI14WIP57LMKj7FVfCHx3g3BcZVjJG8bjX8= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w="} {"_id":"doc-en-kubernetes-a8f6f5d02893f7d8cb2ea51da016730b507e44e02a67250d71ed88ad4e8024f9","title":"","text":"golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.12.0/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0="} {"_id":"doc-en-kubernetes-f34197a400046a870d681b363be6c17c8fdeab3f4c3d538274bcd79d8cbaeb74","title":"","text":"google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA= k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/structured-merge-diff/v4 v4.3.0/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08= sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= "} {"_id":"doc-en-kubernetes-a219282e4b86dfe2f2daafed7857de0e958a5860c63f6131a99cea49194a3b44","title":"","text":"github.com/ThalesIgnite/crypto11 v1.2.5/go.mod h1:ILDKtnCKiQ7zRoNxcp36Y1ZR8LBPmR2E23+wTQe/MlE= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk="} {"_id":"doc-en-kubernetes-3d1248f3b62df08f6c7c1a1c3e11384a31b606df22411c7114248e4a68caf604","title":"","text":"google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI= "} {"_id":"doc-en-kubernetes-8ec92acc2938eb433f1c8104a6d40f58368a5a1c7c8f44f8623d47cdf318c8ae","title":"","text":"\"google.golang.org/grpc\" \"google.golang.org/grpc/credentials/insecure\" \"k8s.io/apimachinery/pkg/util/wait\" kmsapi \"k8s.io/kms/apis/v2\" )"} {"_id":"doc-en-kubernetes-87eaf28570120f8c42aaf63956c9da4cae3aceee46f4893e1b9c44b9643aeafb","title":"","text":"client := newClient(t, address) // make sure the gRPC server is up before running tests if err := wait.PollImmediateUntilWithContext(ctx, time.Second, func(ctx context.Context) (bool, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() _, err := client.Status(ctx, &kmsapi.StatusRequest{}) if err != nil { t.Logf(\"failed to get kms status: %v\", err) ready: for { select { case <-ctx.Done(): t.Fatalf(\"server failed to start in time: %v\", ctx.Err()) default: if done := func() bool { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() _, err := client.Status(ctx, &kmsapi.StatusRequest{}) if err != nil { t.Logf(\"failed to get kms status: %v\", err) } return err == nil }(); done { break ready } time.Sleep(time.Second) } return err == nil, nil }); err != nil { t.Fatal(err) } t.Run(\"should be able to encrypt and decrypt through unix domain sockets\", func(t *testing.T) {"} {"_id":"doc-en-kubernetes-d577c29ec57ad41323e2f7f92777ff902dd73bc827f54402c73d35dd3e104b3a","title":"","text":"if !reflect.DeepEqual(n.podCIDRs, podCIDRs) { klog.ErrorS(nil, \"Using NodeCIDR LocalDetector mode, current PodCIDRs are different than previous PodCIDRs, restarting\", \"node\", klog.KObj(node), \"newPodCIDRs\", podCIDRs, \"oldPodCIDRs\", n.podCIDRs) panic(\"Current Node PodCIDRs are different than previous PodCIDRs, restarting\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) } }"} {"_id":"doc-en-kubernetes-dcb6a96113ce958a4995c52166025e96588e84a763040a398851937ebb083bc1","title":"","text":"if !reflect.DeepEqual(n.podCIDRs, podCIDRs) { klog.ErrorS(nil, \"Using NodeCIDR LocalDetector mode, current PodCIDRs are different than previous PodCIDRs, restarting\", \"node\", klog.KObj(node), \"newPodCIDRs\", podCIDRs, \"oldPODCIDRs\", n.podCIDRs) panic(\"Current Node PodCIDRs are different than previous PodCIDRs, restarting\") klog.FlushAndExit(klog.ExitFlushTimeout, 1) } }"} {"_id":"doc-en-kubernetes-4a7f1726c10a5fc79019828265140a521fc0c64017978f8c03fc17b3afa4c46c","title":"","text":"package proxy import ( \"strconv\" \"testing\" v1 \"k8s.io/api/core/v1\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/klog/v2\" ) func TestNodePodCIDRHandlerAdd(t *testing.T) { oldKlogOsExit := klog.OsExit defer func() { klog.OsExit = oldKlogOsExit }() klog.OsExit = customExit tests := []struct { name string oldNodePodCIDRs []string"} {"_id":"doc-en-kubernetes-2d4238c0ab7f596c825ee23ce3f5a80bbf9501eb4871ae058f8e78c0e8d0a3a2","title":"","text":"t.Errorf(\"The code did panic\") } }() n.OnNodeAdd(node) }) } } func TestNodePodCIDRHandlerUpdate(t *testing.T) { oldKlogOsExit := klog.OsExit defer func() { klog.OsExit = oldKlogOsExit }() klog.OsExit = customExit tests := []struct { name string oldNodePodCIDRs []string"} {"_id":"doc-en-kubernetes-a9fa375fa59d6841a05ca562d8368e83aeed4663be7984665c5dfbd158b01aee","title":"","text":"t.Errorf(\"The code did panic\") } }() n.OnNodeUpdate(oldNode, node) }) } } func customExit(exitCode int) { panic(strconv.Itoa(exitCode)) } "} {"_id":"doc-en-kubernetes-d6949c12717d29c1be74528f84defadb7329fde72205e6c2386edef32be5f6ca","title":"","text":" rules: - selectorRegexp: k8s[.]io/kubernetes allowedPrefixes: - k8s.io/kubernetes/cmd/kube-apiserver - k8s.io/kubernetes/pkg - k8s.io/kubernetes/plugin - k8s.io/kubernetes/test/utils - k8s.io/kubernetes/third_party "} {"_id":"doc-en-kubernetes-34397c4e1a6cafb89857b9e024ef4005efd0d5fd84f3e34e52812ed5f92add67","title":"","text":"import ( \"context\" \"crypto/ecdsa\" \"crypto/elliptic\" \"crypto/rand\" \"crypto/rsa\" \"crypto/x509\" \"crypto/x509/pkix\" \"encoding/pem\" \"fmt\" \"math\" \"math/big\" \"net\" \"os\" \"path/filepath\""} {"_id":"doc-en-kubernetes-29ea50ac44b82b087bea53cd79dfafa48cbeacaee83ec47c52103e0e5e6843ef","title":"","text":"restclient \"k8s.io/client-go/rest\" clientgotransport \"k8s.io/client-go/transport\" \"k8s.io/client-go/util/cert\" \"k8s.io/client-go/util/keyutil\" logsapi \"k8s.io/component-base/logs/api/v1\" \"k8s.io/klog/v2\" \"k8s.io/kube-aggregator/pkg/apiserver\""} {"_id":"doc-en-kubernetes-b83d0fe38e252159961dfb7436a6afb0dda234ead72156fef0d2761a56751f6d","title":"","text":"\"k8s.io/kubernetes/cmd/kube-apiserver/app\" \"k8s.io/kubernetes/cmd/kube-apiserver/app/options\" \"k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil\" testutil \"k8s.io/kubernetes/test/utils\" )"} {"_id":"doc-en-kubernetes-20bf9a68b671962f26e4c9b7058633f30c611cb5174368b2ad102192582bd8d5","title":"","text":"// give the kube api server an \"identity\" it can use to for request header auth // so that aggregated api servers can understand who the calling user is s.Authentication.RequestHeader.AllowedNames = []string{\"ash\", \"misty\", \"brock\"} // create private key signer, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return result, err } // make a client certificate for the api server - common name has to match one of our defined names above serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64-1)) if err != nil { return result, err } serial = new(big.Int).Add(serial, big.NewInt(1)) tenThousandHoursLater := time.Now().Add(10_000 * time.Hour) clientCrtOfAPIServer, signer, err := pkiutil.NewCertAndKey(proxySigningCert, proxySigningKey, &pkiutil.CertConfig{ Config: cert.Config{ certTmpl := x509.Certificate{ Subject: pkix.Name{ CommonName: \"misty\", Usages: []x509.ExtKeyUsage{ x509.ExtKeyUsageClientAuth, }, }, NotAfter: &tenThousandHoursLater, PublicKeyAlgorithm: x509.ECDSA, }) SerialNumber: serial, NotBefore: proxySigningCert.NotBefore, NotAfter: tenThousandHoursLater, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageClientAuth, }, BasicConstraintsValid: true, } certDERBytes, err := x509.CreateCertificate(rand.Reader, &certTmpl, proxySigningCert, signer.Public(), proxySigningKey) if err != nil { return result, err } if err := pkiutil.WriteCertAndKey(s.SecureServing.ServerCert.CertDirectory, \"misty-crt\", clientCrtOfAPIServer, signer); err != nil { clientCrtOfAPIServer, err := x509.ParseCertificate(certDERBytes) if err != nil { return result, err } // write the cert to disk certificatePath := filepath.Join(s.SecureServing.ServerCert.CertDirectory, \"misty-crt.crt\") certBlock := pem.Block{ Type: \"CERTIFICATE\", Bytes: clientCrtOfAPIServer.Raw, } certBytes := pem.EncodeToMemory(&certBlock) if err := cert.WriteCert(certificatePath, certBytes); err != nil { return result, err } // write the key to disk privateKeyPath := filepath.Join(s.SecureServing.ServerCert.CertDirectory, \"misty-crt.key\") encodedPrivateKey, err := keyutil.MarshalPrivateKeyToPEM(signer) if err != nil { return result, err } if err := keyutil.WriteKey(privateKeyPath, encodedPrivateKey); err != nil { return result, err } s.ProxyClientKeyFile = filepath.Join(s.SecureServing.ServerCert.CertDirectory, \"misty-crt.key\") s.ProxyClientCertFile = filepath.Join(s.SecureServing.ServerCert.CertDirectory, \"misty-crt.crt\")"} {"_id":"doc-en-kubernetes-a8b4ef7b989797b1205082ff1570076c5a5cf8b43ba2fb767e82a35fa8a0ea42","title":"","text":"\"k8s.io/kubernetes/test/e2e/framework\" e2edaemonset \"k8s.io/kubernetes/test/e2e/framework/daemonset\" e2edeployment \"k8s.io/kubernetes/test/e2e/framework/deployment\" e2ekubesystem \"k8s.io/kubernetes/test/e2e/framework/kubesystem\" e2enetwork \"k8s.io/kubernetes/test/e2e/framework/network\" e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\""} {"_id":"doc-en-kubernetes-b0a6d70d4872db6a8892452f31e3f83157643636c7c9fd609a256bc6e4b9e575","title":"","text":"e2eservice \"k8s.io/kubernetes/test/e2e/framework/service\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" \"k8s.io/kubernetes/test/e2e/network/common\" gcecloud \"k8s.io/legacy-cloud-providers/gce\" admissionapi \"k8s.io/pod-security-admission/api\" netutils \"k8s.io/utils/net\" utilpointer \"k8s.io/utils/pointer\""} {"_id":"doc-en-kubernetes-eb314eebbc91a610f4c05b64c8c07d87473175e2896867fb9ac357206edbfba0","title":"","text":"} }) // This test creates a load balancer, make sure its health check interval // equals to gceHcCheckIntervalSeconds. Then the interval is manipulated // to be something else, see if the interval will be reconciled. ginkgo.It(\"should reconcile LB health check interval [Slow][Serial][Disruptive]\", func(ctx context.Context) { const gceHcCheckIntervalSeconds = int64(8) // This test is for clusters on GCE. // (It restarts kube-controller-manager, which we don't support on GKE) e2eskipper.SkipUnlessProviderIs(\"gce\") e2eskipper.SkipUnlessSSHKeyPresent() clusterID, err := gce.GetClusterID(ctx, cs) if err != nil { framework.Failf(\"framework.GetClusterID(cs) = _, %v; want nil\", err) } gceCloud, err := gce.GetGCECloud() if err != nil { framework.Failf(\"framework.GetGCECloud() = _, %v; want nil\", err) } namespace := f.Namespace.Name serviceName := \"lb-hc-int\" jig := e2eservice.NewTestJig(cs, namespace, serviceName) ginkgo.By(\"create load balancer service\") // Create loadbalancer service with source range from node[0] and podAccept svc, err := jig.CreateTCPService(ctx, func(svc *v1.Service) { svc.Spec.Type = v1.ServiceTypeLoadBalancer }) framework.ExpectNoError(err) ginkgo.DeferCleanup(func(ctx context.Context) { ginkgo.By(\"Clean up loadbalancer service\") e2eservice.WaitForServiceDeletedWithFinalizer(ctx, cs, svc.Namespace, svc.Name) }) svc, err = jig.WaitForLoadBalancer(ctx, e2eservice.GetServiceLoadBalancerCreationTimeout(ctx, cs)) framework.ExpectNoError(err) hcName := gcecloud.MakeNodesHealthCheckName(clusterID) hc, err := gceCloud.GetHTTPHealthCheck(hcName) if err != nil { framework.Failf(\"gceCloud.GetHttpHealthCheck(%q) = _, %v; want nil\", hcName, err) } gomega.Expect(hc.CheckIntervalSec).To(gomega.Equal(gceHcCheckIntervalSeconds)) ginkgo.By(\"modify the health check interval\") hc.CheckIntervalSec = gceHcCheckIntervalSeconds - 1 if err = gceCloud.UpdateHTTPHealthCheck(hc); err != nil { framework.Failf(\"gcecloud.UpdateHttpHealthCheck(%#v) = %v; want nil\", hc, err) } ginkgo.By(\"restart kube-controller-manager\") if err := e2ekubesystem.RestartControllerManager(ctx); err != nil { framework.Failf(\"e2ekubesystem.RestartControllerManager() = %v; want nil\", err) } if err := e2ekubesystem.WaitForControllerManagerUp(ctx); err != nil { framework.Failf(\"e2ekubesystem.WaitForControllerManagerUp() = %v; want nil\", err) } ginkgo.By(\"health check should be reconciled\") pollInterval := framework.Poll * 10 loadBalancerPropagationTimeout := e2eservice.GetServiceLoadBalancerPropagationTimeout(ctx, cs) if pollErr := wait.PollImmediate(pollInterval, loadBalancerPropagationTimeout, func() (bool, error) { hc, err := gceCloud.GetHTTPHealthCheck(hcName) if err != nil { framework.Logf(\"ginkgo.Failed to get HttpHealthCheck(%q): %v\", hcName, err) return false, err } framework.Logf(\"hc.CheckIntervalSec = %v\", hc.CheckIntervalSec) return hc.CheckIntervalSec == gceHcCheckIntervalSeconds, nil }); pollErr != nil { framework.Failf(\"Health check %q does not reconcile its check interval to %d.\", hcName, gceHcCheckIntervalSeconds) } }) // [LinuxOnly]: Windows does not support session affinity. ginkgo.It(\"should have session affinity work for LoadBalancer service with ESIPP on [Slow] [LinuxOnly]\", func(ctx context.Context) { // L4 load balancer affinity `ClientIP` is not supported on AWS ELB."} {"_id":"doc-en-kubernetes-5414aff216a41ff14583f3dc370a24cb556385334824ec066d8a405151bbdd2e","title":"","text":"indexer.Add(resourceQuota) // old service was a load balancer, but updated version is a node port. oldService := &api.Service{ ObjectMeta: api.ObjectMeta{Name: \"service\", Namespace: \"test\"}, existingService := &api.Service{ ObjectMeta: api.ObjectMeta{Name: \"service\", Namespace: \"test\", ResourceVersion: \"1\"}, Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}, } newService := &api.Service{"} {"_id":"doc-en-kubernetes-80ff490c68a379b29761d2b042be8f31ea2774d73c42e585a3631b378dbf92f7","title":"","text":"Ports: []api.ServicePort{{Port: 1234}}, }, } err := handler.Admit(admission.NewAttributesRecord(newService, oldService, api.Kind(\"Service\").WithVersion(\"version\"), newService.Namespace, newService.Name, api.Resource(\"services\").WithVersion(\"version\"), \"\", admission.Update, nil)) err := handler.Admit(admission.NewAttributesRecord(newService, existingService, api.Kind(\"Service\").WithVersion(\"version\"), newService.Namespace, newService.Name, api.Resource(\"services\").WithVersion(\"version\"), \"\", admission.Update, nil)) if err != nil { t.Errorf(\"Unexpected error: %v\", err) }"} {"_id":"doc-en-kubernetes-93ac7a07b867ac57ce95d31eb6d64e65cc688a1cf9833f16433d8bd1d91d6086","title":"","text":"if prevItem == nil { return nil, admission.NewForbidden(a, fmt.Errorf(\"unable to get previous usage since prior version of object was not found\")) } prevUsage := evaluator.Usage(prevItem) deltaUsage = quota.Subtract(deltaUsage, prevUsage) // if we can definitively determine that this is not a case of \"create on update\", // then charge based on the delta. Otherwise, bill the maximum metadata, err := meta.Accessor(prevItem) if err == nil && len(metadata.GetResourceVersion()) > 0 { prevUsage := evaluator.Usage(prevItem) deltaUsage = quota.Subtract(deltaUsage, prevUsage) } } if quota.IsZero(deltaUsage) { return quotas, nil"} {"_id":"doc-en-kubernetes-87faed89a11c3b4a283bc3a6840617b80b14456a6b055f4cb45fae1cb863fa0a","title":"","text":"// Verify PodReady is not set (since sandboxcreation is blocked) _, err = getTransitionTimeForPodConditionWithStatus(p, v1.PodReady, false) framework.ExpectNoError(err) // this testcase is creating the missing volume that unblock the pod above, // and check PodReadyToStartContainer is setting correctly. ginkgo.By(\"checking pod condition for a pod when volumes source is created\") configmap := v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: \"cm-that-unblock-pod-condition\", }, Data: map[string]string{ \"key\": \"value\", }, BinaryData: map[string][]byte{ \"binaryKey\": []byte(\"value\"), }, } _, err = f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).Create(ctx, &configmap, metav1.CreateOptions{}) framework.ExpectNoError(err) defer func() { err = f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).Delete(ctx, \"cm-that-unblock-pod-condition\", metav1.DeleteOptions{}) framework.ExpectNoError(err, \"unable to delete configmap\") }() p2 := webserverPodSpec(\"pod2-\"+string(uuid.NewUUID()), \"web2\", \"init2\", hasInitContainers) p2.Spec.Volumes = []v1.Volume{ { Name: \"cm-2\", VolumeSource: v1.VolumeSource{ ConfigMap: &v1.ConfigMapVolumeSource{ LocalObjectReference: v1.LocalObjectReference{Name: \"cm-that-unblock-pod-condition\"}, }, }, }, } p2.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{ { Name: \"cm-2\", MountPath: \"/config\", }, } p2 = e2epod.NewPodClient(f).Create(ctx, p2) framework.ExpectNoError(e2epod.WaitTimeoutForPodReadyInNamespace(ctx, f.ClientSet, p2.Name, p2.Namespace, framework.PodStartTimeout)) p2, err = e2epod.NewPodClient(f).Get(ctx, p2.Name, metav1.GetOptions{}) framework.ExpectNoError(err) _, err = getTransitionTimeForPodConditionWithStatus(p2, v1.PodScheduled, true) framework.ExpectNoError(err) _, err = getTransitionTimeForPodConditionWithStatus(p2, v1.PodInitialized, true) framework.ExpectNoError(err) // Verify PodReadyToStartContainers is set (since sandboxcreation is unblocked) if checkPodReadyToStart { _, err = getTransitionTimeForPodConditionWithStatus(p2, v1.PodReadyToStartContainers, true) framework.ExpectNoError(err) } } }"} {"_id":"doc-en-kubernetes-bd3e930b6fb932a8e1df87ff62c47e39dbcbdbca520765b4c99fcb8557b4a9e3","title":"","text":"// Verify PodReady is not set (since sandboxcreation is blocked) _, err = getTransitionTimeForPodConditionWithStatus(p, v1.PodReady, false) framework.ExpectNoError(err) ginkgo.By(\"update pod related volume resource to unblock sandbox creation\") e2epod.NewPodClient(f).Update(ctx, p.Name, func(pod *v1.Pod) { pod.Spec.Volumes = []v1.Volume{ { Name: \"secret\", VolumeSource: v1.VolumeSource{ Secret: &v1.SecretVolumeSource{ SecretName: \"secret\", }, }, }, } pod.Spec.Containers[0].VolumeMounts = []v1.VolumeMount{ { Name: \"secret\", MountPath: \"/config\", }, } }) // Verify PodReadyToStartContainers is set (since sandboxcreation is unblocked) if checkPodReadyToStart { _, err = getTransitionTimeForPodConditionWithStatus(p, v1.PodReadyToStartContainers, true) framework.ExpectNoError(err) } } }"} {"_id":"doc-en-kubernetes-ad4294f0da3434dd67a2ffdd06c43e92f958654fb0f10140f63eb6a300bc88ae","title":"","text":"} func (f *fakeService) WaitForReady(ctx context.Context) error { err := wait.PollWithContext(ctx, 1*time.Second, 200*time.Millisecond, func(ctx context.Context) (done bool, err error) { err := wait.PollUntilContextTimeout(ctx, 200*time.Millisecond, time.Second, false, func(ctx context.Context) (done bool, err error) { return f.Port() != nil, nil })"} {"_id":"doc-en-kubernetes-019ba0c70fc64dd8786b25b8efb50558427cccbd38ecc087d389cf052666f90e","title":"","text":"fs.DurationVar(&o.NodeMonitorGracePeriod.Duration, \"node-monitor-grace-period\", o.NodeMonitorGracePeriod.Duration, \"Amount of time which we allow running Node to be unresponsive before marking it unhealthy. \"+ \"Must be N times more than kubelet's nodeStatusUpdateFrequency, \"+ \"where N means number of retries allowed for kubelet to post node status.\") \"where N means number of retries allowed for kubelet to post node status. \"+ \"This value should also be greater than the sum of HTTP2_PING_TIMEOUT_SECONDS and HTTP2_READ_IDLE_TIMEOUT_SECONDS\") fs.Float32Var(&o.NodeEvictionRate, \"node-eviction-rate\", 0.1, \"Number of nodes per second on which pods are deleted in case of node failure when a zone is healthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters.\") fs.Float32Var(&o.SecondaryNodeEvictionRate, \"secondary-node-eviction-rate\", 0.01, \"Number of nodes per second on which pods are deleted in case of node failure when a zone is unhealthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters. This value is implicitly overridden to 0 if the cluster size is smaller than --large-cluster-size-threshold.\") fs.Int32Var(&o.LargeClusterSizeThreshold, \"large-cluster-size-threshold\", 50, fmt.Sprintf(\"Number of nodes from which %s treats the cluster as large for the eviction logic purposes. --secondary-node-eviction-rate is implicitly overridden to 0 for clusters this size or smaller. Notice: If nodes reside in multiple zones, this threshold will be considered as zone node size threshold for each zone to determine node eviction rate independently.\", names.NodeLifecycleController))"} {"_id":"doc-en-kubernetes-e5ddfca4d29e5cbac97e77e15a9f1c44ba9e4a79751f6c8346eacc3408cee7a7","title":"","text":"// NodeMonitorGracePeriod is the amount of time which we allow a running node to be // unresponsive before marking it unhealthy. Must be N times more than kubelet's // nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet // to post node status. // to post node status. This value should also be greater than the sum of // HTTP2_PING_TIMEOUT_SECONDS and HTTP2_READ_IDLE_TIMEOUT_SECONDS. NodeMonitorGracePeriod metav1.Duration // secondaryNodeEvictionRate is implicitly overridden to 0 for clusters smaller than or equal to largeClusterSizeThreshold LargeClusterSizeThreshold int32"} {"_id":"doc-en-kubernetes-b298aa533e01a8861ea89770d61f59a2bd6e41742c729fa66c0a7d319fa3df52","title":"","text":"if obj.PodEvictionTimeout == zero { obj.PodEvictionTimeout = metav1.Duration{Duration: 5 * time.Minute} } // NodeMonitorGracePeriod is set to a default value of 50 seconds. // This value should be greater than the sum of HTTP2_PING_TIMEOUT_SECONDS (30s) // and HTTP2_READ_IDLE_TIMEOUT_SECONDS (15s) from the http2 health check // to ensure that the server has adequate time to handle slow or idle connections // properly before marking a node as unhealthy. if obj.NodeMonitorGracePeriod == zero { obj.NodeMonitorGracePeriod = metav1.Duration{Duration: 40 * time.Second} obj.NodeMonitorGracePeriod = metav1.Duration{Duration: 50 * time.Second} } if obj.NodeStartupGracePeriod == zero { obj.NodeStartupGracePeriod = metav1.Duration{Duration: 60 * time.Second}"} {"_id":"doc-en-kubernetes-10415c8e6b63a1a7864b05acd3128e8235676cbe7993af36aaf402f09aff765b","title":"","text":"// be less than the node health signal update frequency, since there will // only be fresh values from Kubelet at an interval of node health signal // update frequency. // 2. nodeMonitorGracePeriod can't be too large for user experience - larger // 2. nodeMonitorGracePeriod should be greater than the sum of HTTP2_PING_TIMEOUT_SECONDS (30s) // \t and HTTP2_READ_IDLE_TIMEOUT_SECONDS (15s) from the http2 health check // \t to ensure that the server has adequate time to handle slow or idle connections // properly before marking a node as unhealthy. // 3. nodeMonitorGracePeriod can't be too large for user experience - larger // value takes longer for user to see up-to-date node health. nodeMonitorGracePeriod time.Duration"} {"_id":"doc-en-kubernetes-067690a2376ed4e75d2c496110fc628323bc3c6ee42b5f13f20f3889e2f2d0a5","title":"","text":") const ( testNodeMonitorGracePeriod = 40 * time.Second testNodeMonitorGracePeriod = 50 * time.Second testNodeStartupGracePeriod = 60 * time.Second testNodeMonitorPeriod = 5 * time.Second testRateLimiterQPS = float32(100000)"} {"_id":"doc-en-kubernetes-a883055a5cbab7183d5d74a1c90d5afc9e5e3f0c48031aefab3ee091c7a89632","title":"","text":"}, \"NodeMonitorGracePeriod\": { SchemaProps: spec.SchemaProps{ Description: \"nodeMontiorGracePeriod is the amount of time which we allow a running node to be unresponsive before marking it unhealthy. Must be N times more than kubelet's nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet to post node status.\", Description: \"nodeMontiorGracePeriod is the amount of time which we allow a running node to be unresponsive before marking it unhealthy. Must be N times more than kubelet's nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet to post node status. This value should also be greater than the sum of HTTP2_PING_TIMEOUT_SECONDS and HTTP2_READ_IDLE_TIMEOUT_SECONDS.\", Ref: ref(\"k8s.io/apimachinery/pkg/apis/meta/v1.Duration\"), }, },"} {"_id":"doc-en-kubernetes-9f75c9e143630cfef071efbfe99003d6890f82e8aa4350ab67c4acefdc85a48b","title":"","text":"// nodeMontiorGracePeriod is the amount of time which we allow a running node to be // unresponsive before marking it unhealthy. Must be N times more than kubelet's // nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet // to post node status. // to post node status. This value should also be greater than the sum of // HTTP2_PING_TIMEOUT_SECONDS and HTTP2_READ_IDLE_TIMEOUT_SECONDS. NodeMonitorGracePeriod metav1.Duration // podEvictionTimeout is the grace period for deleting pods on failed nodes. PodEvictionTimeout metav1.Duration"} {"_id":"doc-en-kubernetes-032a2ae98e5a53ac8b654ba2f8c7c303d677389cf3b16a2020921ee5b31f0fcd","title":"","text":"\"fmt\" \"math\" \"strconv\" \"sync\" \"time\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/api\""} {"_id":"doc-en-kubernetes-2fcf60467a31c9c88d74923fd9a1bd537d43cb6e9c975fa87363d22478db46f7","title":"","text":"Expect(badEvents).NotTo(BeNumerically(\">\", int(math.Floor(0.01*float64(totalPods))))) }) } type Scalability struct { skip bool totalPods int podsPerMinion int rcsPerThread int } scalabilityTests := []Scalability{ {totalPods: 500, podsPerMinion: 10, rcsPerThread: 5, skip: true}, {totalPods: 500, podsPerMinion: 10, rcsPerThread: 25, skip: true}, } for _, testArg := range scalabilityTests { // # of threads calibrate to totalPods threads := (testArg.totalPods / (testArg.podsPerMinion * testArg.rcsPerThread)) name := fmt.Sprintf( \"should be able to launch %v pods, %v per minion, in %v rcs/thread.\", testArg.totalPods, testArg.podsPerMinion, testArg.rcsPerThread) if testArg.skip { name = \"[Skipped] \" + name } itArg := testArg It(name, func() { podsLaunched := 0 var wg sync.WaitGroup wg.Add(threads) // Create queue of pending requests on the api server. for i := 0; i < threads; i++ { go func() { defer wg.Done() for i := 0; i < itArg.rcsPerThread; i++ { name := \"my-short-lived-pod\" + string(util.NewUUID()) n := itArg.podsPerMinion * minionCount expectNoError(RunRC(c, name, ns, \"gcr.io/google_containers/pause:go\", n)) podsLaunched += n Logf(\"Launched %v pods so far...\", podsLaunched) err := DeleteRC(c, ns, name) expectNoError(err) } }() } // Wait for all the pods from all the RC's to return. wg.Wait() Logf(\"%v pods out of %v launched\", podsLaunched, itArg.totalPods) }) } })"} {"_id":"doc-en-kubernetes-ab21726b2e4ac1c257da810d937f5e0e70c0239368a1a2bec76afe6dd631f1ef","title":"","text":" /* Copyright 2015 Google Inc. 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. */ package e2e import ( \"fmt\" \"sync\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/client\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/fields\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/labels\" \"github.com/GoogleCloudPlatform/kubernetes/pkg/util\" . \"github.com/onsi/ginkgo\" . \"github.com/onsi/gomega\" ) // This test suite can take a long time to run, so by default it is added to // the ginkgo.skip list (see driver.go). // To run this suite you must explicitly ask for it by setting the // -t/--test flag or ginkgo.focus flag. var _ = Describe(\"Scale\", func() { var c *client.Client var minionCount int var RCName string var ns string BeforeEach(func() { var err error c, err = loadClient() expectNoError(err) minions, err := c.Nodes().List(labels.Everything(), fields.Everything()) expectNoError(err) minionCount = len(minions.Items) Expect(minionCount).NotTo(BeZero()) nsForTesting, err := createTestingNS(\"scale\", c) ns = nsForTesting.Name expectNoError(err) }) AfterEach(func() { // Remove any remaining pods from this test if the // replication controller still exists and the replica count // isn't 0. This means the controller wasn't cleaned up // during the test so clean it up here rc, err := c.ReplicationControllers(ns).Get(RCName) if err == nil && rc.Spec.Replicas != 0 { By(\"Cleaning up the replication controller\") err := DeleteRC(c, ns, RCName) expectNoError(err) } By(fmt.Sprintf(\"Destroying namespace for this suite %v\", ns)) if err := c.Namespaces().Delete(ns); err != nil { Failf(\"Couldn't delete ns %s\", err) } }) type Scalability struct { skip bool totalPods int podsPerMinion int rcsPerThread int } scalabilityTests := []Scalability{ {totalPods: 500, podsPerMinion: 10, rcsPerThread: 5, skip: true}, {totalPods: 500, podsPerMinion: 10, rcsPerThread: 25, skip: true}, } for _, testArg := range scalabilityTests { // # of threads calibrate to totalPods threads := (testArg.totalPods / (testArg.podsPerMinion * testArg.rcsPerThread)) name := fmt.Sprintf( \"should be able to launch %v pods, %v per minion, in %v rcs/thread.\", testArg.totalPods, testArg.podsPerMinion, testArg.rcsPerThread) if testArg.skip { name = \"[Skipped] \" + name } itArg := testArg It(name, func() { podsLaunched := 0 var wg sync.WaitGroup wg.Add(threads) // Create queue of pending requests on the api server. for i := 0; i < threads; i++ { go func() { defer GinkgoRecover() defer wg.Done() for i := 0; i < itArg.rcsPerThread; i++ { name := \"my-short-lived-pod\" + string(util.NewUUID()) n := itArg.podsPerMinion * minionCount expectNoError(RunRC(c, name, ns, \"gcr.io/google_containers/pause:go\", n)) podsLaunched += n Logf(\"Launched %v pods so far...\", podsLaunched) err := DeleteRC(c, ns, name) expectNoError(err) } }() } // Wait for all the pods from all the RC's to return. wg.Wait() Logf(\"%v pods out of %v launched\", podsLaunched, itArg.totalPods) }) } }) "} {"_id":"doc-en-kubernetes-dcf417cf877d9705e72073c1cc95b20cac779f6fcc5bc73723a54c03b06c9241","title":"","text":"if err != nil { return nil, \"\", err } return aggregator.FilterSpecByPathsWithoutSideEffects(result, []string{\"/apis/\"}), etag, nil group := specInfo.apiService.Spec.Group version := specInfo.apiService.Spec.Version return aggregator.FilterSpecByPathsWithoutSideEffects(result, []string{\"/apis/\" + group + \"/\" + version}), etag, nil }, cached.Result[*spec.Swagger]{Value: result, Etag: etag, Err: err}) specInfo.spec.Store(filteredResult) return err"} {"_id":"doc-en-kubernetes-04c293f10c664d0bf8f455188a69cb5a00abc51145012d786405b4d4924cd7c9","title":"","text":"SwaggerProps: spec.SwaggerProps{ Paths: &spec.Paths{ Paths: map[string]spec.PathItem{ \"/apis/apiservicegroup/v1\": {}, \"/apis/apiservicegroup/v1/path1\": {}, }, }, },"} {"_id":"doc-en-kubernetes-349f82ced31ca497bcc011205c962bb46588d3ba780adddb5a9d7d231d10372d","title":"","text":"t.Error(err) } expectPath(t, swagger, \"/apis/apiservicegroup/v1\") expectPath(t, swagger, \"/apis/apiservicegroup/v1/path1\") expectPath(t, swagger, \"/apis/apiregistration.k8s.io/v1\") t.Log(\"Update APIService OpenAPI\")"} {"_id":"doc-en-kubernetes-63e1336b438fed98eb174974df6f860f30660cbab7d53a33031fafe90526cdd3","title":"","text":"SwaggerProps: spec.SwaggerProps{ Paths: &spec.Paths{ Paths: map[string]spec.PathItem{ \"/apis/apiservicegroup/v2\": {}, \"/apis/apiservicegroup/v1/path2\": {}, }, }, },"} {"_id":"doc-en-kubernetes-f3d7ef8c3f5c7d0dff1aae449bc18616f3fd6c10a1f5ea9cdeda19d6cbe3c736","title":"","text":"} // Ensure that the if the APIService OpenAPI is updated, the // aggregated OpenAPI is also updated. expectPath(t, swagger, \"/apis/apiservicegroup/v1/path2\") expectNoPath(t, swagger, \"/apis/apiservicegroup/v1/path1\") expectPath(t, swagger, \"/apis/apiregistration.k8s.io/v1\") } // Tests that an APIService that registers OpenAPI will only have the OpenAPI // for its specific group version served registered. // See https://github.com/kubernetes/kubernetes/pull/123570 for full context. func TestAPIServiceOpenAPIServiceMismatch(t *testing.T) { mux := http.NewServeMux() var delegationHandlers []http.Handler delegate1 := &openAPIHandler{openapi: &spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Paths: &spec.Paths{ Paths: map[string]spec.PathItem{ \"/apis/foo/v1\": {}, }, }, }, }} delegationHandlers = append(delegationHandlers, delegate1) s := buildAndRegisterSpecAggregator(delegationHandlers, mux) apiService := &v1.APIService{ Spec: v1.APIServiceSpec{ Group: \"apiservicegroup\", Version: \"v1\", Service: &v1.ServiceReference{Name: \"dummy\"}, }, } apiService.Name = \"apiservice\" apiService2 := &v1.APIService{ Spec: v1.APIServiceSpec{ Group: \"apiservicegroup\", Version: \"v2\", Service: &v1.ServiceReference{Name: \"dummy2\"}, }, } apiService2.Name = \"apiservice2\" handler := &openAPIHandler{openapi: &spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Paths: &spec.Paths{ Paths: map[string]spec.PathItem{ \"/apis/apiservicegroup/v1\": {}, }, }, }, }} handler2 := &openAPIHandler{openapi: &spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Paths: &spec.Paths{ Paths: map[string]spec.PathItem{ \"/apis/a\": {}, \"/apis/apiservicegroup/v1\": {}, \"/apis/apiservicegroup/v2\": {}, }, }, }, }} if err := s.AddUpdateAPIService(apiService, handler); err != nil { t.Error(err) } if err := s.UpdateAPIServiceSpec(apiService.Name); err != nil { t.Error(err) } if err := s.AddUpdateAPIService(apiService2, handler2); err != nil { t.Error(err) } if err := s.UpdateAPIServiceSpec(apiService2.Name); err != nil { t.Error(err) } swagger, err := fetchOpenAPI(mux) if err != nil { t.Error(err) } expectPath(t, swagger, \"/apis/apiservicegroup/v1\") expectPath(t, swagger, \"/apis/apiservicegroup/v2\") expectPath(t, swagger, \"/apis/apiregistration.k8s.io/v1\") t.Logf(\"Remove APIService %s\", apiService.Name) s.RemoveAPIService(apiService.Name) swagger, err = fetchOpenAPI(mux) if err != nil { t.Error(err) } // Ensure that the if the APIService is added then removed, the OpenAPI disappears from the aggregated OpenAPI as well. expectNoPath(t, swagger, \"/apis/apiservicegroup/v1\") expectPath(t, swagger, \"/apis/apiregistration.k8s.io/v1\") }"} {"_id":"doc-en-kubernetes-92fed4d3acf8bb9676e53f898a9042eae7660a4f048ccf65b0e9fc2605388bcc","title":"","text":"apiServiceSuccess := &v1.APIService{ Spec: v1.APIServiceSpec{ Group: \"success\", Version: \"v1\", Service: &v1.ServiceReference{Name: \"dummy2\"}, }, }"} {"_id":"doc-en-kubernetes-ea61a38753dbff6b4639d682388111b30288895d878e2ba922246628d05673ef","title":"","text":"apiService := &v1.APIService{ Spec: v1.APIServiceSpec{ Group: \"apiservicegroup\", Version: \"v1\", Service: &v1.ServiceReference{Name: \"dummy\"}, }, }"} {"_id":"doc-en-kubernetes-1f596b1d7bbddfecb7a8bf9bc9210a9ca9d6dea36a0defe1d62562a8ff1a39ee","title":"","text":"apiServiceFailed := &v1.APIService{ Spec: v1.APIServiceSpec{ Group: \"failed\", Version: \"v1\", Service: &v1.ServiceReference{Name: \"dummy\"}, }, }"} {"_id":"doc-en-kubernetes-466e83113315ebab1014c4b6a40f5cefc9e6bcd928d43d01d22fc164098d4072","title":"","text":" #!/usr/bin/env bash # Copyright 2024 The Kubernetes Authors. # # 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. set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/.. cd \"${KUBE_ROOT}\" source hack/lib/init.sh # NOTE: Please do NOT add any to this list!! # # We are aiming to consolidate on: registry.k8s.io/e2e-test-images/agnhost # The sources for which are in test/images/agnhost. # If agnhost is missing functionality for your tests, please reach out to SIG Testing. kube::util::read-array PERMITTED_IMAGES < <(sed '/^#/d' ./test/images/.permitted-images) # get current list of images, ignoring tags echo \"Getting e2e image list ...\" make WHAT=test/e2e/e2e.test e2e_test=\"$(kube::util::find-binary e2e.test)\" kube::util::read-array IMAGES < <(\"${e2e_test}\" --list-images | sed -E 's/^(.+):[^:]+$/1/' | LC_ALL=C sort -u) # diff versus known permitted images ret=0 >&2 echo \"Diffing e2e image list ...\" diff -Naupr <(printf '%sn' \"${IMAGES[@]}\") <(printf '%sn' \"${PERMITTED_IMAGES[@]}\") || ret=$? if [[ $ret -eq 0 ]]; then >&2 echo \"PASS: e2e images used are OK.\" else >&2 echo \"FAIL: e2e images do not match the approved list!\" >&2 echo \"\" >&2 echo \"Please use registry.k8s.io/e2e-test-images/agnhost wherever possible, we are consolidating test images.\" >&2 echo \"See: test/images/agnhost/README.md\" >&2 echo \"\" >&2 echo \"You can reach out to https://git.k8s.io/community/sig-testing for help.\" exit 1 fi "} {"_id":"doc-en-kubernetes-30f2d4728716bc36892e11c7384f528d558fd5ef7d4c90e39e63fab79eac554b","title":"","text":" # NOTE: Please do NOT add any to this list!! # # We are aiming to consolidate on: registry.k8s.io/e2e-test-images/agnhost # The sources for which are in test/images/agnhost. # If agnhost is missing functionality for your tests, please reach out to SIG Testing. gcr.io/authenticated-image-pulling/alpine gcr.io/authenticated-image-pulling/windows-nanoserver gcr.io/k8s-authenticated-test/agnhost invalid.registry.k8s.io/invalid/alpine registry.k8s.io/build-image/distroless-iptables registry.k8s.io/cloud-provider-gcp/gcp-compute-persistent-disk-csi-driver registry.k8s.io/e2e-test-images/agnhost registry.k8s.io/e2e-test-images/apparmor-loader registry.k8s.io/e2e-test-images/busybox registry.k8s.io/e2e-test-images/cuda-vector-add registry.k8s.io/e2e-test-images/httpd registry.k8s.io/e2e-test-images/ipc-utils registry.k8s.io/e2e-test-images/jessie-dnsutils registry.k8s.io/e2e-test-images/kitten registry.k8s.io/e2e-test-images/nautilus registry.k8s.io/e2e-test-images/nginx registry.k8s.io/e2e-test-images/node-perf/npb-ep registry.k8s.io/e2e-test-images/node-perf/npb-is registry.k8s.io/e2e-test-images/node-perf/tf-wide-deep registry.k8s.io/e2e-test-images/nonewprivs registry.k8s.io/e2e-test-images/nonroot registry.k8s.io/e2e-test-images/perl registry.k8s.io/e2e-test-images/redis registry.k8s.io/e2e-test-images/regression-issue-74839 registry.k8s.io/e2e-test-images/resource-consumer registry.k8s.io/e2e-test-images/sample-apiserver registry.k8s.io/e2e-test-images/volume/iscsi registry.k8s.io/e2e-test-images/volume/nfs registry.k8s.io/etcd registry.k8s.io/pause registry.k8s.io/prometheus-dummy-exporter registry.k8s.io/prometheus-to-sd registry.k8s.io/sd-dummy-exporter registry.k8s.io/sig-storage/csi-attacher registry.k8s.io/sig-storage/csi-external-health-monitor-controller registry.k8s.io/sig-storage/csi-node-driver-registrar registry.k8s.io/sig-storage/csi-provisioner registry.k8s.io/sig-storage/csi-resizer registry.k8s.io/sig-storage/csi-snapshotter registry.k8s.io/sig-storage/hello-populator registry.k8s.io/sig-storage/hostpathplugin registry.k8s.io/sig-storage/livenessprobe registry.k8s.io/sig-storage/nfs-provisioner registry.k8s.io/sig-storage/volume-data-source-validator "} {"_id":"doc-en-kubernetes-32dfc2efb9044ba9771900b1cfbd393af20ef23e3781260ed57757ec81bf45c2","title":"","text":"}, []string{\"resource\"}, ) WatchCacheReadWait = compbasemetrics.NewHistogramVec( &compbasemetrics.HistogramOpts{ Namespace: namespace, Subsystem: subsystem, Name: \"read_wait_seconds\", Help: \"Histogram of time spent waiting for a watch cache to become fresh.\", StabilityLevel: compbasemetrics.ALPHA, Buckets: []float64{0.005, 0.025, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.25, 1.5, 2, 3}, }, []string{\"resource\"}) ) var registerMetrics sync.Once"} {"_id":"doc-en-kubernetes-4ccfa5242482bb183632b62a8ea72d76b8bffea61b74d840471c6926e72dc01e","title":"","text":"legacyregistry.MustRegister(watchCacheCapacityDecreaseTotal) legacyregistry.MustRegister(WatchCacheCapacity) legacyregistry.MustRegister(WatchCacheInitializations) legacyregistry.MustRegister(WatchCacheReadWait) }) }"} {"_id":"doc-en-kubernetes-27ccb88b1ae8ddaf70323b16d0ea92e2d659bea263267da2d7b23c512bea881c","title":"","text":"// You HAVE TO explicitly call w.RUnlock() after this function. func (w *watchCache) waitUntilFreshAndBlock(ctx context.Context, resourceVersion uint64) error { startTime := w.clock.Now() defer func() { if resourceVersion > 0 { metrics.WatchCacheReadWait.WithContext(ctx).WithLabelValues(w.groupResource.String()).Observe(w.clock.Since(startTime).Seconds()) } }() // In case resourceVersion is 0, we accept arbitrarily stale result. // As a result, the condition in the below for loop will never be"} {"_id":"doc-en-kubernetes-bff951a9cc2c30ec982dd5f3685f2709148f2461052c750a693a86fd0faa9d27","title":"","text":"\"k8s.io/apimachinery/pkg/watch\" \"k8s.io/apiserver/pkg/features\" \"k8s.io/apiserver/pkg/storage\" \"k8s.io/apiserver/pkg/storage/cacher/metrics\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/tools/cache\" featuregatetesting \"k8s.io/component-base/featuregate/testing\" k8smetrics \"k8s.io/component-base/metrics\" \"k8s.io/component-base/metrics/testutil\" \"k8s.io/utils/clock\" testingclock \"k8s.io/utils/clock/testing\" )"} {"_id":"doc-en-kubernetes-c5dc8d13b13dbbceaf670ef377770b72a86ea973783d996789610c4049505844","title":"","text":"store.updateCache(add) } } func TestHistogramCacheReadWait(t *testing.T) { registry := k8smetrics.NewKubeRegistry() if err := registry.Register(metrics.WatchCacheReadWait); err != nil { t.Errorf(\"unexpected error: %v\", err) } ctx := context.Background() testedMetrics := \"apiserver_watch_cache_read_wait_seconds\" store := newTestWatchCache(2, &cache.Indexers{}) defer store.Stop() // In background, update the store. go func() { if err := store.Add(makeTestPod(\"foo\", 2)); err != nil { t.Errorf(\"unexpected error: %v\", err) } if err := store.Add(makeTestPod(\"bar\", 5)); err != nil { t.Errorf(\"unexpected error: %v\", err) } }() testCases := []struct { desc string resourceVersion uint64 want string }{ { desc: \"resourceVersion is non-zero\", resourceVersion: 5, want: ` # HELP apiserver_watch_cache_read_wait_seconds [ALPHA] Histogram of time spent waiting for a watch cache to become fresh. # TYPE apiserver_watch_cache_read_wait_seconds histogram apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.005\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.025\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.05\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.1\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.2\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.4\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.6\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"0.8\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"1\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"1.25\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"1.5\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"2\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"3\"} 1 apiserver_watch_cache_read_wait_seconds_bucket{resource=\"pods\",le=\"+Inf\"} 1 apiserver_watch_cache_read_wait_seconds_sum{resource=\"pods\"} 0 apiserver_watch_cache_read_wait_seconds_count{resource=\"pods\"} 1 `, }, { desc: \"resourceVersion is 0\", resourceVersion: 0, want: ``, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { defer registry.Reset() if _, _, _, err := store.WaitUntilFreshAndGet(ctx, test.resourceVersion, \"prefix/ns/bar\"); err != nil { t.Errorf(\"unexpected error: %v\", err) } if err := testutil.GatherAndCompare(registry, strings.NewReader(test.want), testedMetrics); err != nil { t.Errorf(\"unexpected error: %v\", err) } }) } } "} {"_id":"doc-en-kubernetes-41f46c93bd5771a09726e91664b0b0107924f25fe92702b072d1ad00f7cc8857","title":"","text":"MINION_TAG=\"${INSTANCE_PREFIX}-minion\" MINION_NAMES=($(eval echo ${INSTANCE_PREFIX}-minion-{1..${NUM_MINIONS}})) MINION_IP_RANGES=($(eval echo \"10.245.{1..${NUM_MINIONS}}.0/24\")) MINION_SCOPES=\"\" MINION_SCOPES=\"storage-ro,compute-rw\" # Increase the sleep interval value if concerned about API rate limits. 3, in seconds, is the default. POLL_SLEEP_INTERVAL=3 PORTAL_NET=\"10.0.0.0/16\""} {"_id":"doc-en-kubernetes-9a3911e23d79b609d32b7100c79844384085a6ac9c5f38eacdce2c1e3dfecd4f","title":"","text":" apiVersion: v1beta1 desiredState: manifest: containers: - image: kubernetes/pause name: testpd volumeMounts: - mountPath: \"/testpd\" name: \"testpd\" id: testpd version: v1beta1 volumes: - name: testpd source: persistentDisk: # This GCE PD must already exist and be formatted ext4 pdName: \"%insert_pd_name_here%\" fsType: ext4 id: testpd kind: Pod labels: test: testpd "} {"_id":"doc-en-kubernetes-a5fd77247d73ccb39ef29b9b2173fb7359d3bc2a3821f09118697f9dd145a1e3","title":"","text":" #!/bin/bash # Copyright 2014 Google Inc. 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. # Launches a container and verifies it can be reached. Assumes that # we're being called by hack/e2e-test.sh (we use some env vars it sets up). # TODO: Convert uses of gcutil to gcloud set -o errexit set -o nounset set -o pipefail KUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/../.. source \"${KUBE_ROOT}/cluster/kube-env.sh\" source \"${KUBE_ROOT}/cluster/$KUBERNETES_PROVIDER/util.sh\" if [[ \"$KUBERNETES_PROVIDER\" != \"gce\" ]]; then echo \"PD test is only run for GCE\" return 0 fi disk_name=\"e2e-$(date +%H-%M-%s)\" config=\"/tmp/${disk_name}.yaml\" function teardown() { echo \"Cleaning up test artifacts\" ${KUBECFG} delete pods/testpd rm -rf ${config} echo \"Waiting for disk to become unmounted\" sleep 20 gcutil deletedisk -f --zone=${ZONE} ${disk_name} } trap \"teardown\" EXIT perl -p -e \"s/%.*%/${disk_name}/g\" ${KUBE_ROOT}/examples/gce-pd/testpd.yaml > ${config} # Create and mount the disk. gcutil adddisk --size_gb=10 --zone=${ZONE} ${disk_name} gcutil attachdisk --disk ${disk_name} ${MASTER_NAME} gcutil ssh ${MASTER_NAME} sudo rm -rf /mnt/tmp gcutil ssh ${MASTER_NAME} sudo mkdir /mnt/tmp gcutil ssh ${MASTER_NAME} sudo /usr/share/google/safe_format_and_mount /dev/disk/by-id/google-${disk_name} /mnt/tmp gcutil ssh ${MASTER_NAME} sudo umount /mnt/tmp gcloud compute instances detach-disk --disk ${disk_name} --zone ${ZONE} ${MASTER_NAME} ${KUBECFG} -c ${config} create pods pod_id_list=$($KUBECFG '-template={{range.items}}{{.id}} {{end}}' -l test=testpd list pods) # Pod turn up on a clean cluster can take a while for the docker image pull. all_running=0 for i in $(seq 1 24); do echo \"Waiting for pods to come up.\" sleep 5 all_running=1 for id in $pod_id_list; do current_status=$($KUBECFG -template '{{.currentState.status}}' get pods/$id) || true if [[ \"$current_status\" != \"Running\" ]]; then all_running=0 break fi done if [[ \"${all_running}\" == 1 ]]; then break fi done if [[ \"${all_running}\" == 0 ]]; then echo \"Pods did not come up in time\" exit 1 fi "} {"_id":"doc-en-kubernetes-40aa644f9e896a85fdb78ad4e9907f0b8165c7b56194cc1b7e48fcb49831bd10","title":"","text":"\"regexp\" \"strings\" \"syscall\" \"github.com/golang/glog\" ) const MOUNT_MS_BIND = syscall.MS_BIND"} {"_id":"doc-en-kubernetes-d2f8dd8ba4d882d7774c610701aac28e324f9d0e781561c2bc7ae6641b496548","title":"","text":"// Wraps syscall.Mount() func (mounter *DiskMounter) Mount(source string, target string, fstype string, flags uintptr, data string) error { glog.V(5).Infof(\"Mounting %s %s %s %d %s\", source, target, fstype, flags, data) return syscall.Mount(source, target, fstype, flags, data) }"} {"_id":"doc-en-kubernetes-7d41a112f31af69fae8bc67d83e740799d130892a1a22b341ce7f6b423a52170","title":"","text":"// Update uncertain volumes - the new markVolumeOpts may have updated information. // Especially reconstructed volumes (marked as uncertain during reconstruction) need // an update. updateUncertainVolume = utilfeature.DefaultFeatureGate.Enabled(features.SELinuxMountReadWriteOncePod) && podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain updateUncertainVolume = utilfeature.DefaultFeatureGate.Enabled(features.NewVolumeManagerReconstruction) && podObj.volumeMountStateForPod == operationexecutor.VolumeMountUncertain } if !podExists || updateUncertainVolume { // Add new mountedPod or update existing one."} {"_id":"doc-en-kubernetes-779b313b80b03b65e53d2a753b0f8f895dec03a57b7ee5428a5df9c7eb9b9c9b","title":"","text":"utilfeature \"k8s.io/apiserver/pkg/util/feature\" \"k8s.io/client-go/kubernetes\" \"k8s.io/client-go/transport\" \"k8s.io/component-base/tracing\" \"k8s.io/component-base/version\" v1 \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1\" v1helper \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper\""} {"_id":"doc-en-kubernetes-94b9c094a581c21eae052b07b13c5343954f2b7db56190a6a1465d5b1eee2a58","title":"","text":"// rejectForwardingRedirects is whether to allow to forward redirect response rejectForwardingRedirects bool // tracerProvider is used to wrap the proxy transport and handler with tracing tracerProvider tracing.TracerProvider } // Complete fills in any fields not set that are required to have valid data. It's mutating the receiver."} {"_id":"doc-en-kubernetes-89d2ed2010ef7649a86ef85026045e2e915144c217092ff1a50704be3178bc26","title":"","text":"openAPIV3Config: c.GenericConfig.OpenAPIV3Config, proxyCurrentCertKeyContent: func() (bytes []byte, bytes2 []byte) { return nil, nil }, rejectForwardingRedirects: c.ExtraConfig.RejectForwardingRedirects, tracerProvider: c.GenericConfig.TracerProvider, } // used later to filter the served resource by those that have expired."} {"_id":"doc-en-kubernetes-bb85ad15b8e889033ce1636ff0196c460fa8df3a2398e2d78c3d97fb8fa0f889","title":"","text":"proxyTransportDial: s.proxyTransportDial, serviceResolver: s.serviceResolver, rejectForwardingRedirects: s.rejectForwardingRedirects, tracerProvider: s.tracerProvider, } proxyHandler.updateAPIService(apiService) if s.openAPIAggregationController != nil {"} {"_id":"doc-en-kubernetes-0c1a8ac1c162de05a3e631f724995a54e942c32db196a1335a31b22321f96c5d","title":"","text":"\"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters\" endpointmetrics \"k8s.io/apiserver/pkg/endpoints/metrics\" genericapirequest \"k8s.io/apiserver/pkg/endpoints/request\" genericfeatures \"k8s.io/apiserver/pkg/features\" utilfeature \"k8s.io/apiserver/pkg/util/feature\" utilflowcontrol \"k8s.io/apiserver/pkg/util/flowcontrol\" apiserverproxyutil \"k8s.io/apiserver/pkg/util/proxy\" \"k8s.io/apiserver/pkg/util/x509metrics\" \"k8s.io/client-go/transport\" \"k8s.io/component-base/tracing\" \"k8s.io/klog/v2\" apiregistrationv1api \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1\" apiregistrationv1apihelper \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper\""} {"_id":"doc-en-kubernetes-4ac99539ffaea21bdd126c9a3c602ce92ddf94412e9d31b19c70dfc4a2f23e7d","title":"","text":"// reject to forward redirect response rejectForwardingRedirects bool // tracerProvider is used to wrap the proxy transport and handler with tracing tracerProvider tracing.TracerProvider } type proxyHandlingInfo struct {"} {"_id":"doc-en-kubernetes-5c9e27634230d699bff54544db3428d2fb3c4c92cc6a57da9028469058cdafb1","title":"","text":"proxyRoundTripper = transport.NewAuthProxyRoundTripper(user.GetName(), user.GetGroups(), user.GetExtra(), proxyRoundTripper) if utilfeature.DefaultFeatureGate.Enabled(genericfeatures.APIServerTracing) && !upgrade { tracingWrapper := tracing.WrapperFor(r.tracerProvider) proxyRoundTripper = tracingWrapper(proxyRoundTripper) } // If we are upgrading, then the upgrade path tries to use this request with the TLS config we provide, but it does // NOT use the proxyRoundTripper. It's a direct dial that bypasses the proxyRoundTripper. This means that we have to // attach the \"correct\" user headers to the request ahead of time."} {"_id":"doc-en-kubernetes-3c0d58d2ef7a97a49c97ed2124bd216eeaefd235b012076306f6f02fa5478669","title":"","text":"\"golang.org/x/net/websocket\" \"go.opentelemetry.io/otel/propagation\" sdktrace \"go.opentelemetry.io/otel/sdk/trace\" \"go.opentelemetry.io/otel/sdk/trace/tracetest\" \"go.opentelemetry.io/otel/trace\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/types\" utilnet \"k8s.io/apimachinery/pkg/util/net\" \"k8s.io/apimachinery/pkg/util/proxy\" \"k8s.io/apimachinery/pkg/util/sets\" \"k8s.io/apiserver/pkg/authentication/user\" \"k8s.io/apiserver/pkg/endpoints/filters\" genericapirequest \"k8s.io/apiserver/pkg/endpoints/request\" \"k8s.io/apiserver/pkg/server/egressselector\" utilflowcontrol \"k8s.io/apiserver/pkg/util/flowcontrol\""} {"_id":"doc-en-kubernetes-82eef4161a915122c45613d3a6754af3beacfa9da1da552551008248d2148408","title":"","text":"\"k8s.io/component-base/metrics/legacyregistry\" apiregistration \"k8s.io/kube-aggregator/pkg/apis/apiregistration/v1\" \"k8s.io/utils/pointer\" \"k8s.io/utils/ptr\" ) type targetHTTPHandler struct {"} {"_id":"doc-en-kubernetes-c73d053dfefb73690996dc4fddbf0687c124a48642350725d480c21564fdcf43","title":"","text":"} func TestTracerProvider(t *testing.T) { fakeRecorder := tracetest.NewSpanRecorder() otelTracer := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(fakeRecorder)) target := &targetHTTPHandler{} user := &user.DefaultInfo{ Name: \"username\", Groups: []string{\"one\", \"two\"}, } path := \"/request/path\" apiService := &apiregistration.APIService{ ObjectMeta: metav1.ObjectMeta{Name: \"v1.foo\"}, Spec: apiregistration.APIServiceSpec{ Service: &apiregistration.ServiceReference{Name: \"test-service\", Namespace: \"test-ns\", Port: ptr.To(int32(443))}, Group: \"foo\", Version: \"v1\", CABundle: testCACrt, }, Status: apiregistration.APIServiceStatus{ Conditions: []apiregistration.APIServiceCondition{ {Type: apiregistration.Available, Status: apiregistration.ConditionTrue}, }, }, } targetServer := httptest.NewUnstartedServer(target) serviceCert := svcCrt if cert, err := tls.X509KeyPair(serviceCert, svcKey); err != nil { t.Fatalf(\"TestTracerProvider: failed to parse key pair: %v\", err) } else { targetServer.TLS = &tls.Config{Certificates: []tls.Certificate{cert}} } targetServer.StartTLS() defer targetServer.Close() serviceResolver := &mockedRouter{destinationHost: targetServer.Listener.Addr().String()} handler := &proxyHandler{ localDelegate: http.NewServeMux(), serviceResolver: serviceResolver, proxyCurrentCertKeyContent: func() ([]byte, []byte) { return emptyCert(), emptyCert() }, tracerProvider: otelTracer, } server := httptest.NewServer(contextHandler(filters.WithTracing(handler, otelTracer), user)) defer server.Close() handler.updateAPIService(apiService) curr := handler.handlingInfo.Load().(proxyHandlingInfo) handler.handlingInfo.Store(curr) var propagator propagation.TraceContext req, err := http.NewRequest(http.MethodGet, server.URL+path, nil) if err != nil { t.Errorf(\"expected new request: %v\", err) return } t.Logf(\"Sending request: %v\", req) _, err = http.DefaultClient.Do(req) if err != nil { t.Errorf(\"http request failed: %v\", err) return } t.Log(\"Ensure the target server received the traceparent header\") id, ok := target.headers[\"Traceparent\"] if !ok { t.Error(\"expected traceparent header\") return } t.Log(\"Get the span context from the traceparent header\") h := http.Header{ \"Traceparent\": id, } ctx := propagator.Extract(context.Background(), propagation.HeaderCarrier(h)) span := trace.SpanFromContext(ctx) t.Log(\"Ensure that the span context is valid and remote\") if !span.SpanContext().IsValid() { t.Error(\"expected valid span context\") return } if !span.SpanContext().IsRemote() { t.Error(\"expected remote span context\") return } t.Log(\"Ensure that the span ID and trace ID match the expected values\") expectedSpanCtx := fakeRecorder.Ended()[0].SpanContext() if expectedSpanCtx.TraceID() != span.SpanContext().TraceID() { t.Errorf(\"expected trace id to match. expected: %v, but got %v\", expectedSpanCtx.TraceID(), span.SpanContext().TraceID()) return } if expectedSpanCtx.SpanID() != span.SpanContext().SpanID() { t.Errorf(\"expected span id to match. expected: %v, but got: %v\", expectedSpanCtx.SpanID(), span.SpanContext().SpanID()) return } t.Log(\"Ensure that the expected spans were recorded when sending a request through the proxy\") expectedSpanNames := []string{\"HTTP GET\", \"GET\"} spanNames := []string{} for _, span := range fakeRecorder.Ended() { spanNames = append(spanNames, span.Name()) } if e, a := expectedSpanNames, spanNames; !reflect.DeepEqual(e, a) { t.Errorf(\"expected span names %v, got %v\", e, a) return } } func TestNewRequestForProxyWithAuditID(t *testing.T) { tests := []struct { name string"} {"_id":"doc-en-kubernetes-294248eeca0ff972f25cfb9713997e12881638673e8106c449b4c26ef5795588","title":"","text":"\"fmt\" \"math/rand\" \"sync\" \"sync/atomic\" \"testing\" \"time\""} {"_id":"doc-en-kubernetes-47e3067e807d1b9d00deb0ab9a0b25afa6240eb0dd89254638acdff8af7e0767","title":"","text":"close(stopCh) } func TestTransformingInformerRace(t *testing.T) { // source simulates an apiserver object endpoint. source := fcache.NewFakeControllerSource() label := \"to-be-transformed\" makePod := func(name string) *v1.Pod { return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: \"namespace\", Labels: map[string]string{label: \"true\"}, }, Spec: v1.PodSpec{ Hostname: \"hostname\", }, } } badTransform := atomic.Bool{} podTransformer := func(obj interface{}) (interface{}, error) { pod, ok := obj.(*v1.Pod) if !ok { return nil, fmt.Errorf(\"unexpected object type: %T\", obj) } if pod.ObjectMeta.Labels[label] != \"true\" { badTransform.Store(true) return nil, fmt.Errorf(\"object already transformed: %#v\", obj) } pod.ObjectMeta.Labels[label] = \"false\" return pod, nil } numObjs := 5 for i := 0; i < numObjs; i++ { source.Add(makePod(fmt.Sprintf(\"pod-%d\", i))) } type event struct{} events := make(chan event, numObjs) recordEvent := func(eventType watch.EventType, previous, current interface{}) { events <- event{} } checkEvents := func(count int) { for i := 0; i < count; i++ { <-events } } store, controller := NewTransformingInformer( source, &v1.Pod{}, 5*time.Millisecond, ResourceEventHandlerDetailedFuncs{ AddFunc: func(obj interface{}, isInInitialList bool) { recordEvent(watch.Added, nil, obj) }, UpdateFunc: func(oldObj, newObj interface{}) { recordEvent(watch.Modified, oldObj, newObj) }, DeleteFunc: func(obj interface{}) { recordEvent(watch.Deleted, obj, nil) }, }, podTransformer, ) stopCh := make(chan struct{}) go controller.Run(stopCh) checkEvents(numObjs) // Periodically fetch objects to ensure no access races. wg := sync.WaitGroup{} errors := make(chan error, numObjs) for i := 0; i < numObjs; i++ { wg.Add(1) go func(index int) { defer wg.Done() key := fmt.Sprintf(\"namespace/pod-%d\", index) for { select { case <-stopCh: return default: } obj, ok, err := store.GetByKey(key) if !ok || err != nil { errors <- fmt.Errorf(\"couldn't get the object for %v\", key) return } pod := obj.(*v1.Pod) if pod.ObjectMeta.Labels[label] != \"false\" { errors <- fmt.Errorf(\"unexpected object: %#v\", pod) return } } }(i) } // Let resyncs to happen for some time. time.Sleep(time.Second) close(stopCh) wg.Wait() close(errors) for err := range errors { t.Error(err) } if badTransform.Load() { t.Errorf(\"unexpected transformation happened\") } } func TestDeletionHandlingObjectToName(t *testing.T) { cm := &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{"} {"_id":"doc-en-kubernetes-2b8ef14843d02718b88c41d828af657cb7881cc201ddf6d81e81b026b904205a","title":"","text":"} // TransformFunc allows for transforming an object before it will be processed. // TransformFunc (similarly to ResourceEventHandler functions) should be able // to correctly handle the tombstone of type cache.DeletedFinalStateUnknown. // // New in v1.27: In such cases, the contained object will already have gone // through the transform object separately (when it was added / updated prior // to the delete), so the TransformFunc can likely safely ignore such objects // (i.e., just return the input object). // // The most common usage pattern is to clean-up some parts of the object to // reduce component memory usage if a given component doesn't care about them. // // New in v1.27: unless the object is a DeletedFinalStateUnknown, TransformFunc // sees the object before any other actor, and it is now safe to mutate the // object in place instead of making a copy. // New in v1.27: TransformFunc sees the object before any other actor, and it // is now safe to mutate the object in place instead of making a copy. // // It's recommended for the TransformFunc to be idempotent. // It MUST be idempotent if objects already present in the cache are passed to // the Replace() to avoid re-mutating them. Default informers do not pass // existing objects to Replace though. // // Note that TransformFunc is called while inserting objects into the // notification queue and is therefore extremely performance sensitive; please"} {"_id":"doc-en-kubernetes-2b3ad40d8d67599afb445a83bebc81d35da54cd55248a21fca7d7da3a5ba4c9a","title":"","text":"// queueActionLocked appends to the delta list for the object. // Caller must lock first. func (f *DeltaFIFO) queueActionLocked(actionType DeltaType, obj interface{}) error { return f.queueActionInternalLocked(actionType, actionType, obj) } // queueActionInternalLocked appends to the delta list for the object. // The actionType is emitted and must honor emitDeltaTypeReplaced. // The internalActionType is only used within this function and must // ignore emitDeltaTypeReplaced. // Caller must lock first. func (f *DeltaFIFO) queueActionInternalLocked(actionType, internalActionType DeltaType, obj interface{}) error { id, err := f.KeyOf(obj) if err != nil { return KeyError{obj, err} } // Every object comes through this code path once, so this is a good // place to call the transform func. If obj is a // DeletedFinalStateUnknown tombstone, then the containted inner object // will already have gone through the transformer, but we document that // this can happen. In cases involving Replace(), such an object can // come through multiple times. // place to call the transform func. // // If obj is a DeletedFinalStateUnknown tombstone or the action is a Sync, // then the object have already gone through the transformer. // // If the objects already present in the cache are passed to Replace(), // the transformer must be idempotent to avoid re-mutating them, // or coordinate with all readers from the cache to avoid data races. // Default informers do not pass existing objects to Replace. if f.transformer != nil { var err error obj, err = f.transformer(obj) if err != nil { return err _, isTombstone := obj.(DeletedFinalStateUnknown) if !isTombstone && internalActionType != Sync { var err error obj, err = f.transformer(obj) if err != nil { return err } } }"} {"_id":"doc-en-kubernetes-e6bcdc3c732b3e6b62421a45bac8acdb5bcea08e90ce6696bbfa56a368c9fcd2","title":"","text":"return KeyError{item, err} } keys.Insert(key) if err := f.queueActionLocked(action, item); err != nil { if err := f.queueActionInternalLocked(action, Replaced, item); err != nil { return fmt.Errorf(\"couldn't enqueue object: %v\", err) } }"} {"_id":"doc-en-kubernetes-ca90c16a7bcf35fe50ec05a925a95e1370ec5f871dc0384d5201df2665a93798","title":"","text":"return fmt.Errorf(\"failed to try resolving symlinks in path %q: %v\", path, err) } path = evaluated f, err := os.Open(path) f, err := openFileShareDelete(path) if err != nil { return fmt.Errorf(\"failed to open log file %q: %v\", path, err) }"} {"_id":"doc-en-kubernetes-189830cd8dbc188d15542d3382d864c2efbbe5ec850cdcd793a3d0c42100db25","title":"","text":"return err } if recreated { newF, err := os.Open(path) newF, err := openFileShareDelete(path) if err != nil { if os.IsNotExist(err) { continue"} {"_id":"doc-en-kubernetes-b12e3e2ada8cf619cf732e03f20820bdb5a116624e94b6e0b439a5a855464578","title":"","text":" //go:build !windows // +build !windows /* Copyright 2024 The Kubernetes Authors. 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. */ package logs import ( \"os\" ) func openFileShareDelete(path string) (*os.File, error) { // Noop. Only relevant for Windows. return os.Open(path) } "} {"_id":"doc-en-kubernetes-2f72ba65ba7079ec6cd9bf3cdb76ae17905af025cd1eb0162d48ecec4e33609f","title":"","text":"\"io\" \"os\" \"path/filepath\" goruntime \"runtime\" \"testing\" \"time\""} {"_id":"doc-en-kubernetes-84b4a3ac47689d62f37c39273d79236de22457b89319af6ae626bf0537393099","title":"","text":"} func TestReadRotatedLog(t *testing.T) { if goruntime.GOOS == \"windows\" { // TODO: remove skip once the failing test has been fixed. t.Skip(\"Skip failing test on Windows.\") } tmpDir := t.TempDir() file, err := os.CreateTemp(tmpDir, \"logfile\") if err != nil {"} {"_id":"doc-en-kubernetes-64ab86bef72196a12f0e864f76f401aa68b5fd4e556f5a723657399f69fe9c6e","title":"","text":"} } // Finished writing into the file, close it, so we can delete it later. err = file.Close() assert.NoErrorf(t, err, \"could not close file.\") time.Sleep(20 * time.Millisecond) // Make the function ReadLogs end. fakeRuntimeService.Lock()"} {"_id":"doc-en-kubernetes-fecda3a5e3c600f007d0ee99828912194b5365f07a343cbc836d1ba231a5c239","title":"","text":" //go:build windows // +build windows /* Copyright 2024 The Kubernetes Authors. 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. */ package logs import ( \"os\" \"syscall\" ) // Based on Windows implementation of Windows' syscall.Open // https://cs.opensource.google/go/go/+/refs/tags/go1.22.2:src/syscall/syscall_windows.go;l=342 // In addition to syscall.Open, this function also adds the syscall.FILE_SHARE_DELETE flag to sharemode, // which will allow us to read from the file without blocking the file from being deleted or renamed. // This is essential for Log Rotation which is done by renaming the open file. Without this, the file rename would fail. func openFileShareDelete(path string) (*os.File, error) { pathp, err := syscall.UTF16PtrFromString(path) if err != nil { return nil, err } var access uint32 = syscall.GENERIC_READ var sharemode uint32 = syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE var createmode uint32 = syscall.OPEN_EXISTING var attrs uint32 = syscall.FILE_ATTRIBUTE_NORMAL handle, err := syscall.CreateFile(pathp, access, sharemode, nil, createmode, attrs, 0) if err != nil { return nil, err } return os.NewFile(uintptr(handle), path), nil } "} {"_id":"doc-en-kubernetes-3f518396f065d4732362c41548440f936ff293d7df087836e4555c677522e0bb","title":"","text":"o.Prefix = true return o }, expectedOutSubstrings: []string{\"[pod/test-sts-0/test-container] test log content for pod test-sts-0n[pod/test-sts-1/test-container] test log content for pod test-sts-1n\"}, expectedOutSubstrings: []string{ \"[pod/test-sts-0/test-container] test log content for pod test-sts-0n\", \"[pod/test-sts-1/test-container] test log content for pod test-sts-1n\", }, }, { name: \"pod logs with prefix: init container\","} {"_id":"doc-en-kubernetes-114ccddf3f4ce4f84cfcd741cb4bab397bfa35a1df9a5cfc30a246af7e16c845","title":"","text":"// latency for a pod. InitialAttemptTimestamp *time.Time // UnschedulablePlugins records the plugin names that the Pod failed with Unschedulable or UnschedulableAndUnresolvable status. // It's registered only when the Pod is rejected in PreFilter, Filter, Reserve, or Permit (WaitOnPermit). // It's registered only when the Pod is rejected in PreFilter, Filter, Reserve, PreBind or Permit (WaitOnPermit). UnschedulablePlugins sets.Set[string] // PendingPlugins records the plugin names that the Pod failed with Pending status. PendingPlugins sets.Set[string]"} {"_id":"doc-en-kubernetes-0dff1702fdabbce7cd58b038f670fe8ec01ccfcf5fca3bf42aa4913e4977735d","title":"","text":"// Run \"prebind\" plugins. if status := fwk.RunPreBindPlugins(ctx, state, assumedPod, scheduleResult.SuggestedHost); !status.IsSuccess() { if status.IsRejected() { fitErr := &framework.FitError{ NumAllNodes: 1, Pod: assumedPodInfo.Pod, Diagnosis: framework.Diagnosis{ NodeToStatusMap: framework.NodeToStatusMap{scheduleResult.SuggestedHost: status}, UnschedulablePlugins: sets.New(status.Plugin()), }, } return framework.NewStatus(status.Code()).WithError(fitErr) } return status }"} {"_id":"doc-en-kubernetes-01d62bbbec6127ff46d1ac19c932cb10ae794e05bde57dd22a7b804a95b9e592","title":"","text":"ginkgo.It(\"should reject a pod with an AppArmor profile\", func(ctx context.Context) { status := runAppArmorTest(ctx, f, false, v1.DeprecatedAppArmorBetaProfileRuntimeDefault) expectSoftRejection(status) expectRejection(status) }) }) }"} {"_id":"doc-en-kubernetes-40178464ac61f7cf2f70f8ea8732bd2896c688e46c27ae9361e6779234fcf36e","title":"","text":"return e2epod.NewPodClient(f).Create(ctx, pod) } func expectSoftRejection(status v1.PodStatus) { func expectRejection(status v1.PodStatus) { args := []interface{}{\"PodStatus: %+v\", status} gomega.Expect(status.Phase).To(gomega.Equal(v1.PodPending), args...) gomega.Expect(status.Phase).To(gomega.Equal(v1.PodFailed), args...) gomega.Expect(status.Reason).To(gomega.Equal(\"AppArmor\"), args...) gomega.Expect(status.Message).To(gomega.ContainSubstring(\"AppArmor\"), args...) gomega.Expect(status.ContainerStatuses[0].State.Waiting.Reason).To(gomega.Equal(\"Blocked\"), args...) } func isAppArmorEnabled() bool {"} {"_id":"doc-en-kubernetes-3d695f1d2efc90a7c2026f46d6f53493e20f2196e8244c9a0359cecda44d10b0","title":"","text":"// When specified, it should match one the container or initContainer // names in the pod template. // +optional ContainerName *string `json:\"containerName\" protobuf:\"bytes,1,opt,name=containerName\"` ContainerName *string `json:\"containerName,omitempty\" protobuf:\"bytes,1,opt,name=containerName\"` // Represents the relationship between the container exit code(s) and the // specified values. Containers completed with success (exit code 0) are"} {"_id":"doc-en-kubernetes-e51279fb7b326d790b1115e55a1cb5a30b042a1e5da2f13b45c14bed83c742aa","title":"","text":"// Represents the requirement on the container exit codes. // +optional OnExitCodes *PodFailurePolicyOnExitCodesRequirement `json:\"onExitCodes\" protobuf:\"bytes,2,opt,name=onExitCodes\"` OnExitCodes *PodFailurePolicyOnExitCodesRequirement `json:\"onExitCodes,omitempty\" protobuf:\"bytes,2,opt,name=onExitCodes\"` // Represents the requirement on the pod conditions. The requirement is represented // as a list of pod condition patterns. The requirement is satisfied if at // least one pattern matches an actual pod condition. At most 20 elements are allowed. // +listType=atomic // +optional OnPodConditions []PodFailurePolicyOnPodConditionsPattern `json:\"onPodConditions\" protobuf:\"bytes,3,opt,name=onPodConditions\"` OnPodConditions []PodFailurePolicyOnPodConditionsPattern `json:\"onPodConditions,omitempty\" protobuf:\"bytes,3,opt,name=onPodConditions\"` } // PodFailurePolicy describes how failed pods influence the backoffLimit."} {"_id":"doc-en-kubernetes-f9904e9d4c041ec27a063fb6e209047e768b4c1a27f83bbd29ae12d27c6ab487","title":"","text":"e2eoutput.TestContainerOutput(ctx, f, \"check pod SecurityContext username\", pod, 1, []string{\"ContainerAdministrator\"}) }) ginkgo.It(\"should ignore SELinux Specific SecurityContext if set\", func(ctx context.Context) { ginkgo.It(\"should ignore Linux Specific SecurityContext if set\", func(ctx context.Context) { ginkgo.By(\"Creating a pod with SELinux options\") // It is sufficient to show that the pod comes up here. Since we're stripping the SELinux and other linux // security contexts in apiserver and not updating the pod object in the apiserver, we cannot validate the"} {"_id":"doc-en-kubernetes-77bc79f7e1216df6b00989ca0231d6913efc001984a3253bf8ed835e61cfe3a6","title":"","text":"f.Namespace.Name), \"failed to wait for pod %s to be running\", windowsPodWithSELinux.Name) }) ginkgo.It(\"should ignore ProcMount Specific SecurityContext if set\", func(ctx context.Context) { ginkgo.By(\"Creating a pod with ProcMount options\") // It is sufficient to show that the pod comes up here. Since we're stripping the SELinux and other linux // security contexts in apiserver and not updating the pod object in the apiserver, we cannot validate the // pod object to not have those security contexts. However the pod coming to running state is a sufficient // enough condition for us to validate since prior to https://github.com/kubernetes/kubernetes/pull/93475 // the pod would have failed to come up. windowsPodWithSELinux := createTestPod(f, imageutils.GetE2EImage(imageutils.Agnhost), windowsOS) windowsPodWithSELinux.Spec.Containers[0].Args = []string{\"test-webserver-with-selinux\"} windowsPodWithSELinux.Spec.SecurityContext = &v1.PodSecurityContext{} pmt := v1.UnmaskedProcMount containerUserName := \"ContainerAdministrator\" windowsPodWithSELinux.Spec.Containers[0].SecurityContext = &v1.SecurityContext{ ProcMount: &pmt, WindowsOptions: &v1.WindowsSecurityContextOptions{RunAsUserName: &containerUserName}} windowsPodWithSELinux.Spec.Tolerations = []v1.Toleration{{Key: \"os\", Value: \"Windows\"}} windowsPodWithSELinux, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(ctx, windowsPodWithSELinux, metav1.CreateOptions{}) framework.ExpectNoError(err) framework.Logf(\"Created pod %v\", windowsPodWithSELinux) framework.ExpectNoError(e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, windowsPodWithSELinux.Name, f.Namespace.Name), \"failed to wait for pod %s to be running\", windowsPodWithSELinux.Name) }) ginkgo.It(\"should not be able to create pods with containers running as ContainerAdministrator when runAsNonRoot is true\", func(ctx context.Context) { ginkgo.By(\"Creating a pod\")"} {"_id":"doc-en-kubernetes-2ff06fb1bd30f159ca8d78839a2f41b11f56253892ef31177049f66d4837706d","title":"","text":"// TODO: document the feature (owning SIG, when to use this feature for a test) PodResources = framework.WithNodeFeature(framework.ValidNodeFeatures.Add(\"PodResources\")) // ResourceHealthStatus (SIG-node, resource health Status for device plugins and DRA ) ResourceHealthStatus = framework.WithNodeFeature(framework.ValidNodeFeatures.Add(\"ResourceHealthStatus\")) // TODO: document the feature (owning SIG, when to use this feature for a test) ProcMountType = framework.WithNodeFeature(framework.ValidNodeFeatures.Add(\"ProcMountType\"))"} {"_id":"doc-en-kubernetes-2c0740963eaa056043f5d37008467025ae2b27da7ffa2e19b2132dc630cbf5ba","title":"","text":"v1 \"k8s.io/api/core/v1\" kubeletdevicepluginv1beta1 \"k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" \"k8s.io/kubernetes/test/e2e/nodefeature\" imageutils \"k8s.io/kubernetes/test/utils/image\" admissionapi \"k8s.io/pod-security-admission/api\" \"k8s.io/apimachinery/pkg/api/resource\" metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\" \"k8s.io/apimachinery/pkg/util/uuid\" \"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/test/e2e/framework\" \"k8s.io/kubernetes/test/e2e_node/testdeviceplugin\" ) var _ = SIGDescribe(\"Device Plugin Failures Pod Status:\", framework.WithFeatureGate(features.ResourceHealthStatus), func() { var _ = SIGDescribe(\"Device Plugin Failures Pod Status\", nodefeature.ResourceHealthStatus, func() { f := framework.NewDefaultFramework(\"device-plugin-failures\") f.NamespacePodSecurityLevel = admissionapi.LevelPrivileged"} {"_id":"doc-en-kubernetes-7ab716f43f388e7dbcd440f6954a86361deeda7183bbc9cedf228168ab0099c4","title":"","text":"\"k8s.io/kubernetes/pkg/features\" \"k8s.io/kubernetes/pkg/kubelet/images\" \"k8s.io/kubernetes/test/e2e/framework\" e2enode \"k8s.io/kubernetes/test/e2e/framework/node\" e2epod \"k8s.io/kubernetes/test/e2e/framework/pod\" e2eskipper \"k8s.io/kubernetes/test/e2e/framework/skipper\" \"k8s.io/kubernetes/test/e2e/nodefeature\""} {"_id":"doc-en-kubernetes-349ba4f2272a05f3a1a360a2049a1e5cac1ca04c4b3d633d748bde9c961d7228","title":"","text":"e2eskipper.SkipUnlessFeatureGateEnabled(features.ImageVolume) }) createPod := func(ctx context.Context, volumes []v1.Volume, volumeMounts []v1.VolumeMount) { var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod: %v\", selinuxOptions)) } createPod := func(ctx context.Context, podName, nodeName string, volumes []v1.Volume, volumeMounts []v1.VolumeMount, selinuxOptions *v1.SELinuxOptions) { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: podName, Namespace: f.Namespace.Name, }, Spec: v1.PodSpec{ NodeName: nodeName, RestartPolicy: v1.RestartPolicyAlways, SecurityContext: &v1.PodSecurityContext{ SELinuxOptions: selinuxOptions,"} {"_id":"doc-en-kubernetes-22f40f5d401cbf71d602fe82fb4923145a0bf5e8aff38cebfd168301c681e5c7","title":"","text":"}, } ginkgo.By(fmt.Sprintf(\"Creating a pod (%v/%v)\", f.Namespace.Name, podName)) ginkgo.By(fmt.Sprintf(\"Creating a pod (%s/%s)\", f.Namespace.Name, podName)) e2epod.NewPodClient(f).Create(ctx, pod) } f.It(\"should succeed with pod and pull policy of Always\", func(ctx context.Context) { var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod: %v\", selinuxOptions)) } createPod(ctx, podName, \"\", []v1.Volume{{Name: volumeName, VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: validImageRef, PullPolicy: v1.PullAlways}}}}, []v1.VolumeMount{{Name: volumeName, MountPath: volumePathPrefix}}, selinuxOptions, ) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%v/%v) to be running\", f.Namespace.Name, podName)) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%s/%s) to be running\", f.Namespace.Name, podName)) err := e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, podName, f.Namespace.Name) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%v/%v)\", f.Namespace.Name, podName) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) ginkgo.By(fmt.Sprintf(\"Verifying the volume mount contents for path: %s\", volumePathPrefix))"} {"_id":"doc-en-kubernetes-032a72fb3ee8b1057c3858e11d48d732bd5cb5db956c43d77cae6ee06db90c08","title":"","text":"}) f.It(\"should succeed with pod and multiple volumes\", func(ctx context.Context) { var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod: %v\", selinuxOptions)) } createPod(ctx, podName, \"\", []v1.Volume{ {Name: volumeName + \"-0\", VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: validImageRef}}}, {Name: volumeName + \"-1\", VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: validImageRef}}},"} {"_id":"doc-en-kubernetes-7eb864b087ff7a30392d7d7afac3ebc6c5aeae0d50a8c238fb2be38e47d79002","title":"","text":"{Name: volumeName + \"-0\", MountPath: volumePathPrefix + \"-0\"}, {Name: volumeName + \"-1\", MountPath: volumePathPrefix + \"-1\"}, }, selinuxOptions, ) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%v/%v) to be running\", f.Namespace.Name, podName)) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%s/%s) to be running\", f.Namespace.Name, podName)) err := e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, podName, f.Namespace.Name) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%v/%v)\", f.Namespace.Name, podName) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) for i := range 2 { volumePath := fmt.Sprintf(\"%s-%d\", volumePathPrefix, i)"} {"_id":"doc-en-kubernetes-e79ca52db4902f603f7ce18658fcc11ff5d228c4f6b73e3e5644653eafce2938","title":"","text":"}) f.It(\"should fail if image volume is not existing\", func(ctx context.Context) { var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod: %v\", selinuxOptions)) } createPod(ctx, podName, \"\", []v1.Volume{{Name: volumeName, VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: invalidImageRef}}}}, []v1.VolumeMount{{Name: volumeName, MountPath: volumePathPrefix}}, selinuxOptions, ) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%v/%v) to fail\", f.Namespace.Name, podName)) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%s/%s) to fail\", f.Namespace.Name, podName)) err := e2epod.WaitForPodContainerToFail(ctx, f.ClientSet, f.Namespace.Name, podName, 0, images.ErrImagePullBackOff.Error(), time.Minute) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%v/%v)\", f.Namespace.Name, podName) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) }) f.It(\"should succeed if image volume is not existing but unused\", func(ctx context.Context) { var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod: %v\", selinuxOptions)) } createPod(ctx, podName, \"\", []v1.Volume{{Name: volumeName, VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: invalidImageRef}}}}, nil, selinuxOptions, ) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%v/%v) to be running\", f.Namespace.Name, podName)) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%s/%s) to be running\", f.Namespace.Name, podName)) err := e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, podName, f.Namespace.Name) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%v/%v)\", f.Namespace.Name, podName) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) ginkgo.By(fmt.Sprintf(\"Verifying the volume mount is not used for path: %s\", volumePathPrefix)) output := e2epod.ExecCommandInContainer(f, podName, containerName, \"/bin/ls\", filepath.Dir(volumePathPrefix)) gomega.Expect(output).NotTo(gomega.ContainSubstring(strings.TrimPrefix(volumePathPrefix, \"/\"))) }) f.It(\"should succeed with multiple pods and same image on the same node\", func(ctx context.Context) { node, err := e2enode.GetRandomReadySchedulableNode(ctx, f.ClientSet) framework.ExpectNoError(err, \"Failed to get a ready schedulable node\") baseName := \"test-pod\" anotherSELinuxLevel := \"s0:c100,c200\" for i := range 2 { podName := fmt.Sprintf(\"%s-%d\", baseName, i) var selinuxOptions *v1.SELinuxOptions if selinux.GetEnabled() { if i == 0 { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: defaultSELinuxLevel, } } else { selinuxOptions = &v1.SELinuxOptions{ User: defaultSELinuxUser, Role: defaultSELinuxRole, Type: defaultSELinuxType, Level: anotherSELinuxLevel, } } ginkgo.By(fmt.Sprintf(\"Using SELinux on pod %q: %v\", podName, selinuxOptions)) } createPod(ctx, podName, node.Name, []v1.Volume{{Name: volumeName, VolumeSource: v1.VolumeSource{Image: &v1.ImageVolumeSource{Reference: validImageRef}}}}, []v1.VolumeMount{{Name: volumeName, MountPath: volumePathPrefix}}, selinuxOptions, ) ginkgo.By(fmt.Sprintf(\"Waiting for the pod (%s/%s) to be running\", f.Namespace.Name, podName)) err := e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, podName, f.Namespace.Name) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) ginkgo.By(fmt.Sprintf(\"Verifying the volume mount contents for path: %s\", volumePathPrefix)) firstFileContents := e2epod.ExecCommandInContainer(f, podName, containerName, \"/bin/cat\", filepath.Join(volumePathPrefix, \"dir\", \"file\")) gomega.Expect(firstFileContents).To(gomega.Equal(\"1\")) secondFileContents := e2epod.ExecCommandInContainer(f, podName, containerName, \"/bin/cat\", filepath.Join(volumePathPrefix, \"file\")) gomega.Expect(secondFileContents).To(gomega.Equal(\"2\")) } podName := baseName + \"-0\" ginkgo.By(fmt.Sprintf(\"Rechecking the pod (%s/%s) after another pod is running as expected\", f.Namespace.Name, podName)) err = e2epod.WaitForPodNameRunningInNamespace(ctx, f.ClientSet, podName, f.Namespace.Name) framework.ExpectNoError(err, \"Failed to await for the pod to be running: (%s/%s)\", f.Namespace.Name, podName) ginkgo.By(fmt.Sprintf(\"Verifying the volume mount contents for path: %s\", volumePathPrefix)) firstFileContents := e2epod.ExecCommandInContainer(f, podName, containerName, \"/bin/cat\", filepath.Join(volumePathPrefix, \"dir\", \"file\")) gomega.Expect(firstFileContents).To(gomega.Equal(\"1\")) secondFileContents := e2epod.ExecCommandInContainer(f, podName, containerName, \"/bin/cat\", filepath.Join(volumePathPrefix, \"file\")) gomega.Expect(secondFileContents).To(gomega.Equal(\"2\")) }) })"}