From baa66debd8216e1bf39911fb1e6df44c36e2e726 Mon Sep 17 00:00:00 2001 From: "Krishnakumar R(KK)" <29471693+kkmsft@users.noreply.github.com> Date: Tue, 11 Feb 2020 13:46:56 -0800 Subject: [PATCH 1/4] Fix registration socket removal on windows. - Until the bug - golang/go#33357 is fixed, os.stat wouldn't return the right mode(socket) on windows. Hence deleting the file, without checking whether its a socket, on windows. - Place os specific logic into util_{linux, windows} files and move util under pkg. --- .../node_register.go | 17 ++----- cmd/csi-node-driver-registrar/util_windows.go | 27 ----------- .../util}/util_linux.go | 21 ++++++++- pkg/util/util_windows.go | 47 +++++++++++++++++++ 4 files changed, 71 insertions(+), 41 deletions(-) delete mode 100644 cmd/csi-node-driver-registrar/util_windows.go rename {cmd/csi-node-driver-registrar => pkg/util}/util_linux.go (54%) create mode 100644 pkg/util/util_windows.go diff --git a/cmd/csi-node-driver-registrar/node_register.go b/cmd/csi-node-driver-registrar/node_register.go index 47efd349a..3fe2a395a 100644 --- a/cmd/csi-node-driver-registrar/node_register.go +++ b/cmd/csi-node-driver-registrar/node_register.go @@ -24,6 +24,7 @@ import ( "google.golang.org/grpc" + "github.com/kubernetes-csi/node-driver-registrar/pkg/util" "k8s.io/klog" registerapi "k8s.io/kubernetes/pkg/kubelet/apis/pluginregistration/v1alpha1" ) @@ -36,23 +37,15 @@ func nodeRegister( // pluginswatcher infrastructure. Node labeling is done by kubelet's csi code. registrar := newRegistrationServer(csiDriverName, *kubeletRegistrationPath, supportedVersions) socketPath := fmt.Sprintf("/registration/%s-reg.sock", csiDriverName) - fi, err := os.Stat(socketPath) - if err == nil && (fi.Mode()&os.ModeSocket) != 0 { - // Remove any socket, stale or not, but fall through for other files - if err := os.Remove(socketPath); err != nil { - klog.Errorf("failed to remove stale socket %s with error: %+v", socketPath, err) - os.Exit(1) - } - } - if err != nil && !os.IsNotExist(err) { - klog.Errorf("failed to stat the socket %s with error: %+v", socketPath, err) + if err := util.CleanupSocketFile(socketPath); err != nil { + klog.Errorf("%+v", err) os.Exit(1) } var oldmask int if runtime.GOOS == "linux" { // Default to only user accessible socket, caller can open up later if desired - oldmask, _ = umask(0077) + oldmask, _ = util.Umask(0077) } klog.Infof("Starting Registration Server at: %s\n", socketPath) @@ -62,7 +55,7 @@ func nodeRegister( os.Exit(1) } if runtime.GOOS == "linux" { - umask(oldmask) + util.Umask(oldmask) } klog.Infof("Registration Server started at: %s\n", socketPath) grpcServer := grpc.NewServer() diff --git a/cmd/csi-node-driver-registrar/util_windows.go b/cmd/csi-node-driver-registrar/util_windows.go deleted file mode 100644 index 7a65a9382..000000000 --- a/cmd/csi-node-driver-registrar/util_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build windows - -/* -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 main - -import ( - "errors" -) - -func umask(mask int) (int, error) { - return -1, errors.New("umask not supported in Windows") -} diff --git a/cmd/csi-node-driver-registrar/util_linux.go b/pkg/util/util_linux.go similarity index 54% rename from cmd/csi-node-driver-registrar/util_linux.go rename to pkg/util/util_linux.go index bab7d62f6..317955245 100644 --- a/cmd/csi-node-driver-registrar/util_linux.go +++ b/pkg/util/util_linux.go @@ -16,12 +16,29 @@ See the License for the specific language governing permissions and limitations under the License. */ -package main +package util import ( + "fmt" + "os" + "golang.org/x/sys/unix" ) -func umask(mask int) (int, error) { +func Umask(mask int) (int, error) { return unix.Umask(mask), nil } + +func CleanupSocketFile(socketPath string) error { + fi, err := os.Stat(socketPath) + if err == nil && (fi.Mode()&os.ModeSocket) != 0 { + // Remove any socket, stale or not, but fall through for other files + if err := os.Remove(socketPath); err != nil { + return fmt.Errorf("failed to remove stale socket %s with error: %+v", socketPath, err) + } + } + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("failed to stat the socket %s with error: %+v", socketPath, err) + } + return nil +} diff --git a/pkg/util/util_windows.go b/pkg/util/util_windows.go new file mode 100644 index 000000000..faa1e0004 --- /dev/null +++ b/pkg/util/util_windows.go @@ -0,0 +1,47 @@ +// +build windows + +/* +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 util + +import ( + "errors" + "fmt" + "os" +) + +func Umask(mask int) (int, error) { + return -1, errors.New("umask not supported in Windows") +} + +func CleanupSocketFile(socketPath string) error { + if _, err := os.Lstat(socketPath); err != nil { + // If the file does not exist, then the cleanup can be considered successful. + if os.IsNotExist(err) { + return nil + } + return fmt.Errorf("failed to lstat the socket %s with error: %+v", socketPath, err) + } + + // TODO: Until the bug - https://github.com/golang/go/issues/33357 is fixed, os.stat wouldn't return the + // right mode(socket) on windows. Hence deleting the file, without checking whether + // its a socket, on windows. + if err := os.Remove(socketPath); err != nil { + return fmt.Errorf("failed to remove stale socket %s with error: %+v", socketPath, err) + } + return nil +} From 1ee4d80d69da5d1d91391067eae3f8dbd98b5bb4 Mon Sep 17 00:00:00 2001 From: "Krishnakumar R(KK)" <29471693+kkmsft@users.noreply.github.com> Date: Tue, 11 Feb 2020 20:32:08 -0800 Subject: [PATCH 2/4] Utils UT --- pkg/util/util_test.go | 139 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 pkg/util/util_test.go diff --git a/pkg/util/util_test.go b/pkg/util/util_test.go new file mode 100644 index 000000000..4b18f2fe2 --- /dev/null +++ b/pkg/util/util_test.go @@ -0,0 +1,139 @@ +/* +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 util + +import ( + "net" + "os" + "path/filepath" + "runtime" + "testing" + + utiltesting "k8s.io/client-go/util/testing" + "k8s.io/klog" +) + +var socketFileName = "reg.sock" + +// TestSocketFileDoesNotExist - Test1: file does not exist. So clean up should be successful. +func TestSocketFileDoesNotExist(t *testing.T) { + // Create a temp directory + testDir, err := utiltesting.MkTmpdir("csi-test") + if err != nil { + t.Fatalf("could not create temp dir: %v", err) + } + defer os.RemoveAll(testDir) + socketPath := filepath.Join(testDir, socketFileName) + // Negative test, file is not created. So file name in current path used. + err = CleanupSocketFile(socketPath) + if err != nil { + t.Fatalf("cleanup returned error: %+v", err) + } +} + +// TestSocketPathDoesNotExist - Test2: directory does not exist. So clean up should be successful. +func TestSocketPathDoesNotExist(t *testing.T) { + // Create a temp directory and delete it. This way we know the directory + // does not exist. + testDir, err := utiltesting.MkTmpdir("csi-test") + if err != nil { + t.Fatalf("could not create temp dir: %v", err) + } + os.RemoveAll(testDir) + + socketPath := filepath.Join(testDir, socketFileName) + err = CleanupSocketFile(socketPath) + if err != nil { + t.Fatalf("cleanup returned error: %+v", err) + } +} + +// TestSocketPathSimple - Test3: +ve test create socket and call delete. Regular happy path scenario. +func TestSocketPathSimple(t *testing.T) { + // Create a temp directory + testDir, err := utiltesting.MkTmpdir("csi-test") + if err != nil { + t.Fatalf("could not create temp dir: %v", err) + } + defer os.RemoveAll(testDir) + + socketPath := filepath.Join(testDir, socketFileName) + + _, err = net.Listen("unix", socketPath) + if err != nil { + klog.Errorf("failed to listen on socket: %s with error: %+v", socketPath, err) + os.Exit(1) + } + + err = CleanupSocketFile(socketPath) + if err != nil { + t.Fatalf("cleanup returned error: %+v", err) + } + + _, err = os.Lstat(socketPath) + if err != nil { + if !os.IsNotExist(err) { + t.Fatalf("lstat error on file %s ", socketPath) + } + } else { + t.Fatalf("socket file %s exists", socketPath) + } +} + +// TestSocketRegularFile - Test 4: Create a regular file and check the deletion logic +func TestSocketRegularFile(t *testing.T) { + // Create a temp directory + testDir, err := utiltesting.MkTmpdir("csi-test") + if err != nil { + t.Fatalf("could not create temp dir: %v", err) + } + defer os.RemoveAll(testDir) + + socketPath := filepath.Join(testDir, socketFileName) + f, err := os.Create(socketPath) + if err != nil { + t.Fatalf("create file failed: %s", socketPath) + } + f.Close() + + err = CleanupSocketFile(socketPath) + if err != nil { + t.Fatalf("cleanup returned error: %+v", err) + } + + if runtime.GOOS == "windows" { + // In windows a regular file will be deleted without checking whether + // its a socket. + _, err = os.Lstat(socketPath) + if err != nil { + if !os.IsNotExist(err) { + t.Fatalf("lstat error on file %s ", socketPath) + } + } else { + t.Fatalf("regular file %s exists", socketPath) + } + } else { + _, err = os.Lstat(socketPath) + if err != nil { + if os.IsNotExist(err) { + t.Fatalf("regular file %s got deleted", socketPath) + } else { + t.Fatalf("lstat error on file %s ", socketPath) + } + } + } +} From 82423aa74ede97ec335fdbb46ce407f1a8f64686 Mon Sep 17 00:00:00 2001 From: "Krishnakumar R(KK)" <29471693+kkmsft@users.noreply.github.com> Date: Tue, 11 Feb 2020 20:36:24 -0800 Subject: [PATCH 3/4] Add go.mod & go.sum - for using tmp test dir create util --- go.mod | 1 + go.sum | 2 ++ 2 files changed, 3 insertions(+) diff --git a/go.mod b/go.mod index 2f49bf96e..8d5486870 100644 --- a/go.mod +++ b/go.mod @@ -15,6 +15,7 @@ require ( golang.org/x/text v0.3.0 // indirect google.golang.org/genproto v0.0.0-20180301225018-2c5e7ac708aa // indirect google.golang.org/grpc v1.10.0 + k8s.io/client-go v11.0.0+incompatible k8s.io/klog v0.1.0 k8s.io/kubernetes v1.11.0-beta.2 ) diff --git a/go.sum b/go.sum index c07313e22..e6a235137 100644 --- a/go.sum +++ b/go.sum @@ -31,6 +31,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +k8s.io/client-go v11.0.0+incompatible h1:LBbX2+lOwY9flffWlJM7f1Ct8V2SRNiMRDFeiwnJo9o= +k8s.io/client-go v11.0.0+incompatible/go.mod h1:7vJpHMYJwNQCWgzmNV+VYUl1zCObLyodBc8nIyt8L5s= k8s.io/klog v0.1.0 h1:I5HMfc/DtuVaGR1KPwUrTc476K8NCqNBldC7H4dYEzk= k8s.io/klog v0.1.0/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= k8s.io/kubernetes v1.11.0-beta.2 h1:j+a7AoIPChQQHzsISzw49r6OfnUvYLwyE0E8sRXfSns= From 49f5e4eea8f2b07df2b80d106eaa1831cf397fe1 Mon Sep 17 00:00:00 2001 From: "Krishnakumar R(KK)" <29471693+kkmsft@users.noreply.github.com> Date: Tue, 11 Feb 2020 20:41:23 -0800 Subject: [PATCH 4/4] Update from go mod vendor --- vendor/k8s.io/client-go/LICENSE | 202 ++++++++++++++++++ .../client-go/util/testing/fake_handler.go | 139 ++++++++++++ .../k8s.io/client-go/util/testing/tmpdir.go | 44 ++++ vendor/modules.txt | 2 + 4 files changed, 387 insertions(+) create mode 100644 vendor/k8s.io/client-go/LICENSE create mode 100644 vendor/k8s.io/client-go/util/testing/fake_handler.go create mode 100644 vendor/k8s.io/client-go/util/testing/tmpdir.go diff --git a/vendor/k8s.io/client-go/LICENSE b/vendor/k8s.io/client-go/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/k8s.io/client-go/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/vendor/k8s.io/client-go/util/testing/fake_handler.go b/vendor/k8s.io/client-go/util/testing/fake_handler.go new file mode 100644 index 000000000..6790cfd8c --- /dev/null +++ b/vendor/k8s.io/client-go/util/testing/fake_handler.go @@ -0,0 +1,139 @@ +/* +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. +*/ + +package testing + +import ( + "io/ioutil" + "net/http" + "net/url" + "reflect" + "sync" +) + +// TestInterface is a simple interface providing Errorf, to make injection for +// testing easier (insert 'yo dawg' meme here). +type TestInterface interface { + Errorf(format string, args ...interface{}) + Logf(format string, args ...interface{}) +} + +// LogInterface is a simple interface to allow injection of Logf to report serving errors. +type LogInterface interface { + Logf(format string, args ...interface{}) +} + +// FakeHandler is to assist in testing HTTP requests. Notice that FakeHandler is +// not thread safe and you must not direct traffic to except for the request +// you want to test. You can do this by hiding it in an http.ServeMux. +type FakeHandler struct { + RequestReceived *http.Request + RequestBody string + StatusCode int + ResponseBody string + // For logging - you can use a *testing.T + // This will keep log messages associated with the test. + T LogInterface + + // Enforce "only one use" constraint. + lock sync.Mutex + requestCount int + hasBeenChecked bool + + SkipRequestFn func(verb string, url url.URL) bool +} + +func (f *FakeHandler) SetResponseBody(responseBody string) { + f.lock.Lock() + defer f.lock.Unlock() + f.ResponseBody = responseBody +} + +func (f *FakeHandler) ServeHTTP(response http.ResponseWriter, request *http.Request) { + f.lock.Lock() + defer f.lock.Unlock() + + if f.SkipRequestFn != nil && f.SkipRequestFn(request.Method, *request.URL) { + response.Header().Set("Content-Type", "application/json") + response.WriteHeader(f.StatusCode) + response.Write([]byte(f.ResponseBody)) + return + } + + f.requestCount++ + if f.hasBeenChecked { + panic("got request after having been validated") + } + + f.RequestReceived = request + response.Header().Set("Content-Type", "application/json") + response.WriteHeader(f.StatusCode) + response.Write([]byte(f.ResponseBody)) + + bodyReceived, err := ioutil.ReadAll(request.Body) + if err != nil && f.T != nil { + f.T.Logf("Received read error: %v", err) + } + f.RequestBody = string(bodyReceived) + if f.T != nil { + f.T.Logf("request body: %s", f.RequestBody) + } +} + +func (f *FakeHandler) ValidateRequestCount(t TestInterface, count int) bool { + ok := true + f.lock.Lock() + defer f.lock.Unlock() + if f.requestCount != count { + ok = false + t.Errorf("Expected %d call, but got %d. Only the last call is recorded and checked.", count, f.requestCount) + } + f.hasBeenChecked = true + return ok +} + +// ValidateRequest verifies that FakeHandler received a request with expected path, method, and body. +func (f *FakeHandler) ValidateRequest(t TestInterface, expectedPath, expectedMethod string, body *string) { + f.lock.Lock() + defer f.lock.Unlock() + if f.requestCount != 1 { + t.Logf("Expected 1 call, but got %v. Only the last call is recorded and checked.", f.requestCount) + } + f.hasBeenChecked = true + + expectURL, err := url.Parse(expectedPath) + if err != nil { + t.Errorf("Couldn't parse %v as a URL.", expectedPath) + } + if f.RequestReceived == nil { + t.Errorf("Unexpected nil request received for %s", expectedPath) + return + } + if f.RequestReceived.URL.Path != expectURL.Path { + t.Errorf("Unexpected request path for request %#v, received: %q, expected: %q", f.RequestReceived, f.RequestReceived.URL.Path, expectURL.Path) + } + if e, a := expectURL.Query(), f.RequestReceived.URL.Query(); !reflect.DeepEqual(e, a) { + t.Errorf("Unexpected query for request %#v, received: %q, expected: %q", f.RequestReceived, a, e) + } + if f.RequestReceived.Method != expectedMethod { + t.Errorf("Unexpected method: %q, expected: %q", f.RequestReceived.Method, expectedMethod) + } + if body != nil { + if *body != f.RequestBody { + t.Errorf("Received body:\n%s\n Doesn't match expected body:\n%s", f.RequestBody, *body) + } + } +} diff --git a/vendor/k8s.io/client-go/util/testing/tmpdir.go b/vendor/k8s.io/client-go/util/testing/tmpdir.go new file mode 100644 index 000000000..3b2d885fc --- /dev/null +++ b/vendor/k8s.io/client-go/util/testing/tmpdir.go @@ -0,0 +1,44 @@ +/* +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 testing + +import ( + "io/ioutil" + "os" +) + +// MkTmpdir creates a temporary directory based upon the prefix passed in. +// If successful, it returns the temporary directory path. The directory can be +// deleted with a call to "os.RemoveAll(...)". +// In case of error, it'll return an empty string and the error. +func MkTmpdir(prefix string) (string, error) { + tmpDir, err := ioutil.TempDir(os.TempDir(), prefix) + if err != nil { + return "", err + } + return tmpDir, nil +} + +// MkTmpdir does the same work as "MkTmpdir", except in case of +// errors, it'll trigger a panic. +func MkTmpdirOrDie(prefix string) string { + tmpDir, err := MkTmpdir(prefix) + if err != nil { + panic(err) + } + return tmpDir +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 2ab8b524d..f60017f5f 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -58,6 +58,8 @@ google.golang.org/grpc/stats google.golang.org/grpc/status google.golang.org/grpc/tap google.golang.org/grpc/transport +# k8s.io/client-go v11.0.0+incompatible +k8s.io/client-go/util/testing # k8s.io/klog v0.1.0 k8s.io/klog # k8s.io/kubernetes v1.11.0-beta.2