From 9332283a3a3217bdc7bb807e40ea1d0cf43c7802 Mon Sep 17 00:00:00 2001 From: Alvaro Aleman Date: Sun, 3 Mar 2019 12:28:37 +0100 Subject: [PATCH] Kubeivirt provider: Use dynamic client from controller-runtime The main purpose of this change is to get rid of another transient dependency on a specific client-go version. --- Gopkg.lock | 31 +- .../provider/kubevirt/provider.go | 46 +- vendor/github.com/golang/mock/AUTHORS | 12 - vendor/github.com/golang/mock/CONTRIBUTORS | 37 - vendor/github.com/golang/mock/LICENSE | 202 --- vendor/github.com/golang/mock/gomock/call.go | 428 ------ .../github.com/golang/mock/gomock/callset.go | 108 -- .../golang/mock/gomock/controller.go | 217 --- .../github.com/golang/mock/gomock/matchers.go | 99 -- vendor/github.com/gorilla/websocket/AUTHORS | 9 - vendor/github.com/gorilla/websocket/LICENSE | 22 - vendor/github.com/gorilla/websocket/client.go | 395 ------ .../gorilla/websocket/client_clone.go | 16 - .../gorilla/websocket/client_clone_legacy.go | 38 - .../gorilla/websocket/compression.go | 148 --- vendor/github.com/gorilla/websocket/conn.go | 1165 ----------------- .../gorilla/websocket/conn_write.go | 15 - .../gorilla/websocket/conn_write_legacy.go | 18 - vendor/github.com/gorilla/websocket/doc.go | 180 --- vendor/github.com/gorilla/websocket/json.go | 60 - vendor/github.com/gorilla/websocket/mask.go | 54 - .../github.com/gorilla/websocket/mask_safe.go | 15 - .../github.com/gorilla/websocket/prepared.go | 102 -- vendor/github.com/gorilla/websocket/proxy.go | 77 -- vendor/github.com/gorilla/websocket/server.go | 363 ----- vendor/github.com/gorilla/websocket/trace.go | 19 - .../github.com/gorilla/websocket/trace_17.go | 12 - vendor/github.com/gorilla/websocket/util.go | 237 ---- .../gorilla/websocket/x_net_proxy.go | 473 ------- .../pkg/apis/uploadcontroller/register.go | 6 - .../pkg/apis/uploadcontroller/v1alpha1/doc.go | 5 - .../uploadcontroller/v1alpha1/register.go | 39 - .../apis/uploadcontroller/v1alpha1/types.go | 54 - .../v1alpha1/zz_generated.deepcopy.go | 118 -- .../client/clientset/versioned/clientset.go | 122 -- .../pkg/client/clientset/versioned/doc.go | 20 - .../client/clientset/versioned/scheme/doc.go | 20 - .../clientset/versioned/scheme/register.go | 56 - .../v1alpha1/datavolume.go | 174 --- .../v1alpha1/datavolumecontroller_client.go | 90 -- .../datavolumecontroller/v1alpha1/doc.go | 20 - .../v1alpha1/generated_expansion.go | 21 - .../typed/uploadcontroller/v1alpha1/doc.go | 20 - .../v1alpha1/generated_expansion.go | 21 - .../v1alpha1/uploadcontroller_client.go | 90 -- .../v1alpha1/uploadtokenrequest.go | 174 --- .../pkg/kubecli/generated_mock_kubevirt.go | 1089 --------------- .../kubevirt/pkg/kubecli/handler.go | 107 -- .../kubevirt/pkg/kubecli/kubecli.go | 216 --- .../kubevirt/pkg/kubecli/kubevirt.go | 124 -- .../pkg/kubecli/kubevirt_test_utils.go | 57 - .../kubevirt/pkg/kubecli/migration.go | 133 -- .../kubevirt/pkg/kubecli/replicaset.go | 101 -- .../kubevirt/pkg/kubecli/version.go | 85 -- vendor/kubevirt.io/kubevirt/pkg/kubecli/vm.go | 133 -- .../kubevirt.io/kubevirt/pkg/kubecli/vmi.go | 440 ------- .../kubevirt/pkg/kubecli/vmpreset.go | 115 -- .../pkg/util/subresources/constants.go | 25 - .../kubevirt.io/kubevirt/pkg/version/base.go | 28 - .../kubevirt.io/kubevirt/pkg/version/types.go | 34 - .../kubevirt/pkg/version/version.go | 37 - 61 files changed, 27 insertions(+), 8345 deletions(-) delete mode 100644 vendor/github.com/golang/mock/AUTHORS delete mode 100644 vendor/github.com/golang/mock/CONTRIBUTORS delete mode 100644 vendor/github.com/golang/mock/LICENSE delete mode 100644 vendor/github.com/golang/mock/gomock/call.go delete mode 100644 vendor/github.com/golang/mock/gomock/callset.go delete mode 100644 vendor/github.com/golang/mock/gomock/controller.go delete mode 100644 vendor/github.com/golang/mock/gomock/matchers.go delete mode 100644 vendor/github.com/gorilla/websocket/AUTHORS delete mode 100644 vendor/github.com/gorilla/websocket/LICENSE delete mode 100644 vendor/github.com/gorilla/websocket/client.go delete mode 100644 vendor/github.com/gorilla/websocket/client_clone.go delete mode 100644 vendor/github.com/gorilla/websocket/client_clone_legacy.go delete mode 100644 vendor/github.com/gorilla/websocket/compression.go delete mode 100644 vendor/github.com/gorilla/websocket/conn.go delete mode 100644 vendor/github.com/gorilla/websocket/conn_write.go delete mode 100644 vendor/github.com/gorilla/websocket/conn_write_legacy.go delete mode 100644 vendor/github.com/gorilla/websocket/doc.go delete mode 100644 vendor/github.com/gorilla/websocket/json.go delete mode 100644 vendor/github.com/gorilla/websocket/mask.go delete mode 100644 vendor/github.com/gorilla/websocket/mask_safe.go delete mode 100644 vendor/github.com/gorilla/websocket/prepared.go delete mode 100644 vendor/github.com/gorilla/websocket/proxy.go delete mode 100644 vendor/github.com/gorilla/websocket/server.go delete mode 100644 vendor/github.com/gorilla/websocket/trace.go delete mode 100644 vendor/github.com/gorilla/websocket/trace_17.go delete mode 100644 vendor/github.com/gorilla/websocket/util.go delete mode 100644 vendor/github.com/gorilla/websocket/x_net_proxy.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/register.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/doc.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/register.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/types.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/zz_generated.deepcopy.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/clientset.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/doc.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/doc.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/register.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolume.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolumecontroller_client.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/doc.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/generated_expansion.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/doc.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/generated_expansion.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadcontroller_client.go delete mode 100644 vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadtokenrequest.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/generated_mock_kubevirt.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/handler.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/kubecli.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt_test_utils.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/migration.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/replicaset.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/version.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/vm.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/vmi.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/kubecli/vmpreset.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/util/subresources/constants.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/version/base.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/version/types.go delete mode 100644 vendor/kubevirt.io/kubevirt/pkg/version/version.go diff --git a/Gopkg.lock b/Gopkg.lock index f297ccb98..81c59a6d4 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -330,14 +330,6 @@ pruneopts = "NUT" revision = "66deaeb636dff1ac7d938ce666d090556056a4b0" -[[projects]] - digest = "1:bc38c7c481812e178d85160472e231c5e1c9a7f5845d67e23ee4e706933c10d8" - name = "github.com/golang/mock" - packages = ["gomock"] - pruneopts = "NUT" - revision = "c34cdb4725f4c3844d095133c6e40e448b86589b" - version = "v1.1.1" - [[projects]] digest = "1:63ccdfbd20f7ccd2399d0647a7d100b122f79c13bb83da9660b1598396fd9f62" name = "github.com/golang/protobuf" @@ -426,14 +418,6 @@ pruneopts = "NUT" revision = "c38d3807cb5863eb95a857d694f6a4d6b31cde32" -[[projects]] - digest = "1:4a0c072e44da763409da72d41492373a034baf2e6d849c76d239b4abdfbb6c49" - name = "github.com/gorilla/websocket" - packages = ["."] - pruneopts = "NUT" - revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d" - version = "v1.4.0" - [[projects]] branch = "master" digest = "1:7fdf3223c7372d1ced0b98bf53457c5e89d89aecbad9a77ba9fcc6e01f9e5621" @@ -1243,17 +1227,11 @@ revision = "0f2f0396e266ad24afbd02375ba74c0dda1e3611" [[projects]] - digest = "1:a8e45142412cc3a18fb238c1ddd40de356eb6d3073b8d8cdbf2435ae42752e1d" + digest = "1:b08090946952cd290d95494732c1a588ca1796e52c3d5382ffd0f67cb9754f4b" name = "kubevirt.io/containerized-data-importer" packages = [ "pkg/apis/datavolumecontroller", "pkg/apis/datavolumecontroller/v1alpha1", - "pkg/apis/uploadcontroller", - "pkg/apis/uploadcontroller/v1alpha1", - "pkg/client/clientset/versioned", - "pkg/client/clientset/versioned/scheme", - "pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1", - "pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1", ] pruneopts = "NUT" revision = "8d7a20b86c9a2ed8ac31e26aab50e362f0c84475" @@ -1262,14 +1240,11 @@ [[projects]] branch = "release-0.10" - digest = "1:e8b22ee4b1bdfcbf397a91a98a901707298ccfc9eeeb2858eb4ffb143b80bd46" + digest = "1:452617fbc46d453dc35684a1e2dd70a09b64e77ee29ba647458adb4e53d8acf0" name = "kubevirt.io/kubevirt" packages = [ "pkg/api/v1", - "pkg/kubecli", "pkg/precond", - "pkg/util/subresources", - "pkg/version", ] pruneopts = "NUT" revision = "6ddf4f4e2db4924ac0725676db72bb78acc6cca2" @@ -1452,7 +1427,6 @@ "k8s.io/code-generator/cmd/deepcopy-gen", "k8s.io/gengo/examples/defaulter-gen/generators", "kubevirt.io/kubevirt/pkg/api/v1", - "kubevirt.io/kubevirt/pkg/kubecli", "sigs.k8s.io/cluster-api/pkg/apis", "sigs.k8s.io/cluster-api/pkg/apis/cluster/common", "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1", @@ -1463,6 +1437,7 @@ "sigs.k8s.io/cluster-api/pkg/client/listers_generated/cluster/v1alpha1", "sigs.k8s.io/cluster-api/pkg/controller/machinedeployment", "sigs.k8s.io/cluster-api/pkg/controller/machineset", + "sigs.k8s.io/controller-runtime/pkg/client", "sigs.k8s.io/controller-runtime/pkg/manager", ] solver-name = "gps-cdcl" diff --git a/pkg/cloudprovider/provider/kubevirt/provider.go b/pkg/cloudprovider/provider/kubevirt/provider.go index ba4d30b88..cc1012e78 100644 --- a/pkg/cloudprovider/provider/kubevirt/provider.go +++ b/pkg/cloudprovider/provider/kubevirt/provider.go @@ -1,6 +1,7 @@ package kubevirt import ( + "context" "encoding/json" "fmt" "strconv" @@ -18,9 +19,9 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" kubevirtv1 "kubevirt.io/kubevirt/pkg/api/v1" - "kubevirt.io/kubevirt/pkg/kubecli" "sigs.k8s.io/cluster-api/pkg/apis/cluster/common" "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" @@ -133,19 +134,20 @@ func (p *provider) Get(machine *v1alpha1.Machine) (instance.Instance, error) { Message: fmt.Sprintf("Failed to parse MachineSpec, due to %v", err), } } - client, err := kubecli.GetKubevirtClientFromRESTConfig(&c.Config) + client, err := client.New(&c.Config, client.Options{}) if err != nil { return nil, fmt.Errorf("failed to get kubevirt client: %v", err) } + ctx := context.Background() - virtualMachineInstance, err := client.VirtualMachineInstance(c.Namespace).Get(machine.Name, &metav1.GetOptions{}) - if err != nil { + virtualMachineInstance := &kubevirtv1.VirtualMachineInstance{} + if err := client.Get(ctx, types.NamespacedName{Namespace: c.Namespace, Name: machine.Name}, virtualMachineInstance); err != nil { if !kerrors.IsNotFound(err) { return nil, fmt.Errorf("failed to get VirtualMachineInstance %s: %v", machine.Name, err) } return nil, cloudprovidererrors.ErrInstanceNotFound - } + // Deletion takes some time, so consider the VMI as deleted as soon as it has a DeletionTimestamp // because once the node got into status not ready its informers wont fire again // With the current approach we may run into a conflict when creating the VMI again, however this @@ -160,7 +162,7 @@ func (p *provider) Get(machine *v1alpha1.Machine) (instance.Instance, error) { virtualMachineInstance.Status.Phase == kubevirtv1.Succeeded { // The pod got deleted, delete the VMI and return ErrNotFound so the VMI // will get recreated - if err := client.VirtualMachine(c.Namespace).Delete(machine.Name, &metav1.DeleteOptions{}); err != nil { + if err := client.Delete(ctx, virtualMachineInstance); err != nil { return nil, fmt.Errorf("failed to delete failed VMI %s: %v", machine.Name, err) } return nil, cloudprovidererrors.ErrInstanceNotFound @@ -187,13 +189,13 @@ func (p *provider) Validate(spec v1alpha1.MachineSpec) error { if pc.OperatingSystem == providerconfig.OperatingSystemCoreos { return fmt.Errorf("CoreOS is not supported") } - client, err := kubecli.GetKubevirtClientFromRESTConfig(&c.Config) + client, err := client.New(&c.Config, client.Options{}) if err != nil { return fmt.Errorf("failed to get kubevirt client: %v", err) } // Check if we can reach the API of the target cluster - _, err = client.VirtualMachineInstance(c.Namespace).Get("not-expected-to-exist", &metav1.GetOptions{}) - if err != nil && !kerrors.IsNotFound(err) { + vmi := &kubevirtv1.VirtualMachineInstance{} + if err := client.Get(context.Background(), types.NamespacedName{Namespace: c.Namespace, Name: "not-expected-to-exist"}, vmi); err != nil && !kerrors.IsNotFound(err) { return fmt.Errorf("failed to request VirtualMachineInstances: %v", err) } @@ -288,30 +290,28 @@ func (p *provider) Create(machine *v1alpha1.Machine, _ *cloud.MachineCreateDelet }, } - client, err := kubecli.GetKubevirtClientFromRESTConfig(&c.Config) + client, err := client.New(&c.Config, client.Options{}) if err != nil { return nil, fmt.Errorf("failed to get kubevirt client: %v", err) } + ctx := context.Background() - createdVMI, err := client.VirtualMachineInstance(virtualMachineInstance.Namespace). - Create(virtualMachineInstance) - if err != nil { + if err := client.Create(ctx, virtualMachineInstance); err != nil { return nil, fmt.Errorf("failed to create vmi: %v", err) } secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: userdataSecretName, - Namespace: createdVMI.Namespace, - OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(createdVMI, kubevirtv1.VirtualMachineInstanceGroupVersionKind)}, + Namespace: virtualMachineInstance.Namespace, + OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(virtualMachineInstance, kubevirtv1.VirtualMachineInstanceGroupVersionKind)}, }, Data: map[string][]byte{"userdata": []byte(userdata)}, } - _, err = client.CoreV1().Secrets(secret.Namespace).Create(secret) - if err != nil { + if err := client.Create(ctx, secret); err != nil { return nil, fmt.Errorf("failed to create secret for userdata: %v", err) } - return &kubeVirtServer{vmi: *createdVMI}, nil + return &kubeVirtServer{vmi: *virtualMachineInstance}, nil } @@ -323,12 +323,14 @@ func (p *provider) Cleanup(machine *v1alpha1.Machine, _ *cloud.MachineCreateDele Message: fmt.Sprintf("Failed to parse MachineSpec, due to %v", err), } } - client, err := kubecli.GetKubevirtClientFromRESTConfig(&c.Config) + client, err := client.New(&c.Config, client.Options{}) if err != nil { return false, fmt.Errorf("failed to get kubevirt client: %v", err) } - _, err = client.VirtualMachineInstance(c.Namespace).Get(machine.Name, &metav1.GetOptions{}) - if err != nil { + ctx := context.Background() + + vmi := &kubevirtv1.VirtualMachineInstance{} + if err := client.Get(ctx, types.NamespacedName{Namespace: c.Namespace, Name: machine.Name}, vmi); err != nil { if !kerrors.IsNotFound(err) { return false, fmt.Errorf("failed to get VirtualMachineInstance %s: %v", machine.Name, err) } @@ -336,7 +338,7 @@ func (p *provider) Cleanup(machine *v1alpha1.Machine, _ *cloud.MachineCreateDele return true, nil } - return false, client.VirtualMachineInstance(c.Namespace).Delete(machine.Name, &metav1.DeleteOptions{}) + return false, client.Delete(ctx, vmi) } func parseResources(cpus, memory string) (*corev1.ResourceList, error) { diff --git a/vendor/github.com/golang/mock/AUTHORS b/vendor/github.com/golang/mock/AUTHORS deleted file mode 100644 index 660b8ccc8..000000000 --- a/vendor/github.com/golang/mock/AUTHORS +++ /dev/null @@ -1,12 +0,0 @@ -# This is the official list of GoMock authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Alex Reece -Google Inc. diff --git a/vendor/github.com/golang/mock/CONTRIBUTORS b/vendor/github.com/golang/mock/CONTRIBUTORS deleted file mode 100644 index def849cab..000000000 --- a/vendor/github.com/golang/mock/CONTRIBUTORS +++ /dev/null @@ -1,37 +0,0 @@ -# This is the official list of people who can contribute (and typically -# have contributed) code to the gomock repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name -# -# An entry with two email addresses specifies that the -# first address should be used in the submit logs and -# that the second address should be recognized as the -# same person when interacting with Rietveld. - -# Please keep the list sorted. - -Aaron Jacobs -Alex Reece -David Symonds -Ryan Barrett diff --git a/vendor/github.com/golang/mock/LICENSE b/vendor/github.com/golang/mock/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/golang/mock/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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/github.com/golang/mock/gomock/call.go b/vendor/github.com/golang/mock/gomock/call.go deleted file mode 100644 index a3fa1ae41..000000000 --- a/vendor/github.com/golang/mock/gomock/call.go +++ /dev/null @@ -1,428 +0,0 @@ -// Copyright 2010 Google Inc. -// -// 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 gomock - -import ( - "fmt" - "reflect" - "strconv" - "strings" -) - -// Call represents an expected call to a mock. -type Call struct { - t TestReporter // for triggering test failures on invalid call setup - - receiver interface{} // the receiver of the method call - method string // the name of the method - methodType reflect.Type // the type of the method - args []Matcher // the args - origin string // file and line number of call setup - - preReqs []*Call // prerequisite calls - - // Expectations - minCalls, maxCalls int - - numCalls int // actual number made - - // actions are called when this Call is called. Each action gets the args and - // can set the return values by returning a non-nil slice. Actions run in the - // order they are created. - actions []func([]interface{}) []interface{} -} - -// newCall creates a *Call. It requires the method type in order to support -// unexported methods. -func newCall(t TestReporter, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := t.(testHelper); ok { - h.Helper() - } - - // TODO: check arity, types. - margs := make([]Matcher, len(args)) - for i, arg := range args { - if m, ok := arg.(Matcher); ok { - margs[i] = m - } else if arg == nil { - // Handle nil specially so that passing a nil interface value - // will match the typed nils of concrete args. - margs[i] = Nil() - } else { - margs[i] = Eq(arg) - } - } - - origin := callerInfo(3) - actions := []func([]interface{}) []interface{}{func([]interface{}) []interface{} { - // Synthesize the zero value for each of the return args' types. - rets := make([]interface{}, methodType.NumOut()) - for i := 0; i < methodType.NumOut(); i++ { - rets[i] = reflect.Zero(methodType.Out(i)).Interface() - } - return rets - }} - return &Call{t: t, receiver: receiver, method: method, methodType: methodType, - args: margs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions} -} - -// AnyTimes allows the expectation to be called 0 or more times -func (c *Call) AnyTimes() *Call { - c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity - return c -} - -// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also -// sets the maximum number of calls to infinity. -func (c *Call) MinTimes(n int) *Call { - c.minCalls = n - if c.maxCalls == 1 { - c.maxCalls = 1e8 - } - return c -} - -// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also -// sets the minimum number of calls to 0. -func (c *Call) MaxTimes(n int) *Call { - c.maxCalls = n - if c.minCalls == 1 { - c.minCalls = 0 - } - return c -} - -// DoAndReturn declares the action to run when the call is matched. -// The return values from this function are returned by the mocked function. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) DoAndReturn(f interface{}) *Call { - // TODO: Check arity and types here, rather than dying badly elsewhere. - v := reflect.ValueOf(f) - - c.addAction(func(args []interface{}) []interface{} { - vargs := make([]reflect.Value, len(args)) - ft := v.Type() - for i := 0; i < len(args); i++ { - if args[i] != nil { - vargs[i] = reflect.ValueOf(args[i]) - } else { - // Use the zero value for the arg. - vargs[i] = reflect.Zero(ft.In(i)) - } - } - vrets := v.Call(vargs) - rets := make([]interface{}, len(vrets)) - for i, ret := range vrets { - rets[i] = ret.Interface() - } - return rets - }) - return c -} - -// Do declares the action to run when the call is matched. The function's -// return values are ignored to retain backward compatibility. To use the -// return values call DoAndReturn. -// It takes an interface{} argument to support n-arity functions. -func (c *Call) Do(f interface{}) *Call { - // TODO: Check arity and types here, rather than dying badly elsewhere. - v := reflect.ValueOf(f) - - c.addAction(func(args []interface{}) []interface{} { - vargs := make([]reflect.Value, len(args)) - ft := v.Type() - for i := 0; i < len(args); i++ { - if args[i] != nil { - vargs[i] = reflect.ValueOf(args[i]) - } else { - // Use the zero value for the arg. - vargs[i] = reflect.Zero(ft.In(i)) - } - } - v.Call(vargs) - return nil - }) - return c -} - -// Return declares the values to be returned by the mocked function call. -func (c *Call) Return(rets ...interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - mt := c.methodType - if len(rets) != mt.NumOut() { - c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]", - c.receiver, c.method, len(rets), mt.NumOut(), c.origin) - } - for i, ret := range rets { - if got, want := reflect.TypeOf(ret), mt.Out(i); got == want { - // Identical types; nothing to do. - } else if got == nil { - // Nil needs special handling. - switch want.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - // ok - default: - c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]", - i, c.receiver, c.method, want, c.origin) - } - } else if got.AssignableTo(want) { - // Assignable type relation. Make the assignment now so that the generated code - // can return the values with a type assertion. - v := reflect.New(want).Elem() - v.Set(reflect.ValueOf(ret)) - rets[i] = v.Interface() - } else { - c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]", - i, c.receiver, c.method, got, want, c.origin) - } - } - - c.addAction(func([]interface{}) []interface{} { - return rets - }) - - return c -} - -// Times declares the exact number of times a function call is expected to be executed. -func (c *Call) Times(n int) *Call { - c.minCalls, c.maxCalls = n, n - return c -} - -// SetArg declares an action that will set the nth argument's value, -// indirected through a pointer. Or, in the case of a slice, SetArg -// will copy value's elements into the nth argument. -func (c *Call) SetArg(n int, value interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - mt := c.methodType - // TODO: This will break on variadic methods. - // We will need to check those at invocation time. - if n < 0 || n >= mt.NumIn() { - c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]", - n, mt.NumIn(), c.origin) - } - // Permit setting argument through an interface. - // In the interface case, we don't (nay, can't) check the type here. - at := mt.In(n) - switch at.Kind() { - case reflect.Ptr: - dt := at.Elem() - if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) { - c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]", - n, vt, dt, c.origin) - } - case reflect.Interface: - // nothing to do - case reflect.Slice: - // nothing to do - default: - c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice type %v [%s]", - n, at, c.origin) - } - - c.addAction(func(args []interface{}) []interface{} { - v := reflect.ValueOf(value) - switch reflect.TypeOf(args[n]).Kind() { - case reflect.Slice: - setSlice(args[n], v) - default: - reflect.ValueOf(args[n]).Elem().Set(v) - } - return nil - }) - return c -} - -// isPreReq returns true if other is a direct or indirect prerequisite to c. -func (c *Call) isPreReq(other *Call) bool { - for _, preReq := range c.preReqs { - if other == preReq || preReq.isPreReq(other) { - return true - } - } - return false -} - -// After declares that the call may only match after preReq has been exhausted. -func (c *Call) After(preReq *Call) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } - - if c == preReq { - c.t.Fatalf("A call isn't allowed to be its own prerequisite") - } - if preReq.isPreReq(c) { - c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq) - } - - c.preReqs = append(c.preReqs, preReq) - return c -} - -// Returns true if the minimum number of calls have been made. -func (c *Call) satisfied() bool { - return c.numCalls >= c.minCalls -} - -// Returns true iff the maximum number of calls have been made. -func (c *Call) exhausted() bool { - return c.numCalls >= c.maxCalls -} - -func (c *Call) String() string { - args := make([]string, len(c.args)) - for i, arg := range c.args { - args[i] = arg.String() - } - arguments := strings.Join(args, ", ") - return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin) -} - -// Tests if the given call matches the expected call. -// If yes, returns nil. If no, returns error with message explaining why it does not match. -func (c *Call) matches(args []interface{}) error { - if !c.methodType.IsVariadic() { - if len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", - c.origin, len(args), len(c.args)) - } - - for i, m := range c.args { - if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i], m) - } - } - } else { - if len(c.args) < c.methodType.NumIn()-1 { - return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d", - c.origin, len(c.args), c.methodType.NumIn()-1) - } - if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", - c.origin, len(args), len(c.args)) - } - if len(args) < len(c.args)-1 { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", - c.origin, len(args), len(c.args)-1) - } - - for i, m := range c.args { - if i < c.methodType.NumIn()-1 { - // Non-variadic args - if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i], m) - } - continue - } - // The last arg has a possibility of a variadic argument, so let it branch - - // sample: Foo(a int, b int, c ...int) - if i < len(c.args) && i < len(args) { - if m.Matches(args[i]) { - // Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC) - // Got Foo(a, b) want Foo(matcherA, matcherB) - // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD) - continue - } - } - - // The number of actual args don't match the number of matchers, - // or the last matcher is a slice and the last arg is not. - // If this function still matches it is because the last matcher - // matches all the remaining arguments or the lack of any. - // Convert the remaining arguments, if any, into a slice of the - // expected type. - vargsType := c.methodType.In(c.methodType.NumIn() - 1) - vargs := reflect.MakeSlice(vargsType, 0, len(args)-i) - for _, arg := range args[i:] { - vargs = reflect.Append(vargs, reflect.ValueOf(arg)) - } - if m.Matches(vargs.Interface()) { - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher) - // Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any()) - // Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher) - break - } - // Wrong number of matchers or not match. Fail. - // Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE) - // Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD) - // Got Foo(a, b, c) want Foo(matcherA, matcherB) - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i:], c.args[i]) - - } - } - - // Check that all prerequisite calls have been satisfied. - for _, preReqCall := range c.preReqs { - if !preReqCall.satisfied() { - return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v", - c.origin, preReqCall, c) - } - } - - // Check that the call is not exhausted. - if c.exhausted() { - return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin) - } - - return nil -} - -// dropPrereqs tells the expected Call to not re-check prerequisite calls any -// longer, and to return its current set. -func (c *Call) dropPrereqs() (preReqs []*Call) { - preReqs = c.preReqs - c.preReqs = nil - return -} - -func (c *Call) call(args []interface{}) []func([]interface{}) []interface{} { - c.numCalls++ - return c.actions -} - -// InOrder declares that the given calls should occur in order. -func InOrder(calls ...*Call) { - for i := 1; i < len(calls); i++ { - calls[i].After(calls[i-1]) - } -} - -func setSlice(arg interface{}, v reflect.Value) { - va := reflect.ValueOf(arg) - for i := 0; i < v.Len(); i++ { - va.Index(i).Set(v.Index(i)) - } -} - -func (c *Call) addAction(action func([]interface{}) []interface{}) { - c.actions = append(c.actions, action) -} diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/github.com/golang/mock/gomock/callset.go deleted file mode 100644 index c44a8a585..000000000 --- a/vendor/github.com/golang/mock/gomock/callset.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2011 Google Inc. -// -// 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 gomock - -import ( - "bytes" - "fmt" -) - -// callSet represents a set of expected calls, indexed by receiver and method -// name. -type callSet struct { - // Calls that are still expected. - expected map[callSetKey][]*Call - // Calls that have been exhausted. - exhausted map[callSetKey][]*Call -} - -// callSetKey is the key in the maps in callSet -type callSetKey struct { - receiver interface{} - fname string -} - -func newCallSet() *callSet { - return &callSet{make(map[callSetKey][]*Call), make(map[callSetKey][]*Call)} -} - -// Add adds a new expected call. -func (cs callSet) Add(call *Call) { - key := callSetKey{call.receiver, call.method} - m := cs.expected - if call.exhausted() { - m = cs.exhausted - } - m[key] = append(m[key], call) -} - -// Remove removes an expected call. -func (cs callSet) Remove(call *Call) { - key := callSetKey{call.receiver, call.method} - calls := cs.expected[key] - for i, c := range calls { - if c == call { - // maintain order for remaining calls - cs.expected[key] = append(calls[:i], calls[i+1:]...) - cs.exhausted[key] = append(cs.exhausted[key], call) - break - } - } -} - -// FindMatch searches for a matching call. Returns error with explanation message if no call matched. -func (cs callSet) FindMatch(receiver interface{}, method string, args []interface{}) (*Call, error) { - key := callSetKey{receiver, method} - - // Search through the expected calls. - expected := cs.expected[key] - var callsErrors bytes.Buffer - for _, call := range expected { - err := call.matches(args) - if err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) - } else { - return call, nil - } - } - - // If we haven't found a match then search through the exhausted calls so we - // get useful error messages. - exhausted := cs.exhausted[key] - for _, call := range exhausted { - if err := call.matches(args); err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) - } - } - - if len(expected)+len(exhausted) == 0 { - fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) - } - - return nil, fmt.Errorf(callsErrors.String()) -} - -// Failures returns the calls that are not satisfied. -func (cs callSet) Failures() []*Call { - failures := make([]*Call, 0, len(cs.expected)) - for _, calls := range cs.expected { - for _, call := range calls { - if !call.satisfied() { - failures = append(failures, call) - } - } - } - return failures -} diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/github.com/golang/mock/gomock/controller.go deleted file mode 100644 index a7b79188b..000000000 --- a/vendor/github.com/golang/mock/gomock/controller.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2010 Google Inc. -// -// 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. - -// GoMock - a mock framework for Go. -// -// Standard usage: -// (1) Define an interface that you wish to mock. -// type MyInterface interface { -// SomeMethod(x int64, y string) -// } -// (2) Use mockgen to generate a mock from the interface. -// (3) Use the mock in a test: -// func TestMyThing(t *testing.T) { -// mockCtrl := gomock.NewController(t) -// defer mockCtrl.Finish() -// -// mockObj := something.NewMockMyInterface(mockCtrl) -// mockObj.EXPECT().SomeMethod(4, "blah") -// // pass mockObj to a real object and play with it. -// } -// -// By default, expected calls are not enforced to run in any particular order. -// Call order dependency can be enforced by use of InOrder and/or Call.After. -// Call.After can create more varied call order dependencies, but InOrder is -// often more convenient. -// -// The following examples create equivalent call order dependencies. -// -// Example of using Call.After to chain expected call order: -// -// firstCall := mockObj.EXPECT().SomeMethod(1, "first") -// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall) -// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall) -// -// Example of using InOrder to declare expected call order: -// -// gomock.InOrder( -// mockObj.EXPECT().SomeMethod(1, "first"), -// mockObj.EXPECT().SomeMethod(2, "second"), -// mockObj.EXPECT().SomeMethod(3, "third"), -// ) -// -// TODO: -// - Handle different argument/return types (e.g. ..., chan, map, interface). -package gomock - -import ( - "fmt" - "golang.org/x/net/context" - "reflect" - "runtime" - "sync" -) - -// A TestReporter is something that can be used to report test failures. -// It is satisfied by the standard library's *testing.T. -type TestReporter interface { - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) -} - -// A Controller represents the top-level control of a mock ecosystem. -// It defines the scope and lifetime of mock objects, as well as their expectations. -// It is safe to call Controller's methods from multiple goroutines. -type Controller struct { - mu sync.Mutex - t TestReporter - expectedCalls *callSet - finished bool -} - -func NewController(t TestReporter) *Controller { - return &Controller{ - t: t, - expectedCalls: newCallSet(), - } -} - -type cancelReporter struct { - t TestReporter - cancel func() -} - -func (r *cancelReporter) Errorf(format string, args ...interface{}) { r.t.Errorf(format, args...) } -func (r *cancelReporter) Fatalf(format string, args ...interface{}) { - defer r.cancel() - r.t.Fatalf(format, args...) -} - -// WithContext returns a new Controller and a Context, which is cancelled on any -// fatal failure. -func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { - ctx, cancel := context.WithCancel(ctx) - return NewController(&cancelReporter{t, cancel}), ctx -} - -func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - recv := reflect.ValueOf(receiver) - for i := 0; i < recv.Type().NumMethod(); i++ { - if recv.Type().Method(i).Name == method { - return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) - } - } - ctrl.t.Fatalf("gomock: failed finding method %s on %T", method, receiver) - panic("unreachable") -} - -func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - call := newCall(ctrl.t, receiver, method, methodType, args...) - - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - ctrl.expectedCalls.Add(call) - - return call -} - -func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - // Nest this code so we can use defer to make sure the lock is released. - actions := func() []func([]interface{}) []interface{} { - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - - expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) - if err != nil { - origin := callerInfo(2) - ctrl.t.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) - } - - // Two things happen here: - // * the matching call no longer needs to check prerequite calls, - // * and the prerequite calls are no longer expected, so remove them. - preReqCalls := expected.dropPrereqs() - for _, preReqCall := range preReqCalls { - ctrl.expectedCalls.Remove(preReqCall) - } - - actions := expected.call(args) - if expected.exhausted() { - ctrl.expectedCalls.Remove(expected) - } - return actions - }() - - var rets []interface{} - for _, action := range actions { - if r := action(args); r != nil { - rets = r - } - } - - return rets -} - -func (ctrl *Controller) Finish() { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } - - ctrl.mu.Lock() - defer ctrl.mu.Unlock() - - if ctrl.finished { - ctrl.t.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") - } - ctrl.finished = true - - // If we're currently panicking, probably because this is a deferred call, - // pass through the panic. - if err := recover(); err != nil { - panic(err) - } - - // Check that all remaining expected calls are satisfied. - failures := ctrl.expectedCalls.Failures() - for _, call := range failures { - ctrl.t.Errorf("missing call(s) to %v", call) - } - if len(failures) != 0 { - ctrl.t.Fatalf("aborting test due to missing call(s)") - } -} - -func callerInfo(skip int) string { - if _, file, line, ok := runtime.Caller(skip + 1); ok { - return fmt.Sprintf("%s:%d", file, line) - } - return "unknown file" -} - -type testHelper interface { - TestReporter - Helper() -} diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/github.com/golang/mock/gomock/matchers.go deleted file mode 100644 index e8b1ddccf..000000000 --- a/vendor/github.com/golang/mock/gomock/matchers.go +++ /dev/null @@ -1,99 +0,0 @@ -//go:generate mockgen -destination mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher - -// Copyright 2010 Google Inc. -// -// 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 gomock - -import ( - "fmt" - "reflect" -) - -// A Matcher is a representation of a class of values. -// It is used to represent the valid or expected arguments to a mocked method. -type Matcher interface { - // Matches returns whether x is a match. - Matches(x interface{}) bool - - // String describes what the matcher matches. - String() string -} - -type anyMatcher struct{} - -func (anyMatcher) Matches(x interface{}) bool { - return true -} - -func (anyMatcher) String() string { - return "is anything" -} - -type eqMatcher struct { - x interface{} -} - -func (e eqMatcher) Matches(x interface{}) bool { - return reflect.DeepEqual(e.x, x) -} - -func (e eqMatcher) String() string { - return fmt.Sprintf("is equal to %v", e.x) -} - -type nilMatcher struct{} - -func (nilMatcher) Matches(x interface{}) bool { - if x == nil { - return true - } - - v := reflect.ValueOf(x) - switch v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice: - return v.IsNil() - } - - return false -} - -func (nilMatcher) String() string { - return "is nil" -} - -type notMatcher struct { - m Matcher -} - -func (n notMatcher) Matches(x interface{}) bool { - return !n.m.Matches(x) -} - -func (n notMatcher) String() string { - // TODO: Improve this if we add a NotString method to the Matcher interface. - return "not(" + n.m.String() + ")" -} - -// Constructors -func Any() Matcher { return anyMatcher{} } -func Eq(x interface{}) Matcher { return eqMatcher{x} } -func Nil() Matcher { return nilMatcher{} } -func Not(x interface{}) Matcher { - if m, ok := x.(Matcher); ok { - return notMatcher{m} - } - return notMatcher{Eq(x)} -} diff --git a/vendor/github.com/gorilla/websocket/AUTHORS b/vendor/github.com/gorilla/websocket/AUTHORS deleted file mode 100644 index 1931f4006..000000000 --- a/vendor/github.com/gorilla/websocket/AUTHORS +++ /dev/null @@ -1,9 +0,0 @@ -# This is the official list of Gorilla WebSocket authors for copyright -# purposes. -# -# Please keep the list sorted. - -Gary Burd -Google LLC (https://opensource.google.com/) -Joachim Bauch - diff --git a/vendor/github.com/gorilla/websocket/LICENSE b/vendor/github.com/gorilla/websocket/LICENSE deleted file mode 100644 index 9171c9722..000000000 --- a/vendor/github.com/gorilla/websocket/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 The Gorilla WebSocket 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. - -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. diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go deleted file mode 100644 index 2e32fd506..000000000 --- a/vendor/github.com/gorilla/websocket/client.go +++ /dev/null @@ -1,395 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bytes" - "context" - "crypto/tls" - "errors" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptrace" - "net/url" - "strings" - "time" -) - -// ErrBadHandshake is returned when the server response to opening handshake is -// invalid. -var ErrBadHandshake = errors.New("websocket: bad handshake") - -var errInvalidCompression = errors.New("websocket: invalid compression negotiation") - -// NewClient creates a new client connection using the given net connection. -// The URL u specifies the host and request URI. Use requestHeader to specify -// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies -// (Cookie). Use the response.Header to get the selected subprotocol -// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). -// -// If the WebSocket handshake fails, ErrBadHandshake is returned along with a -// non-nil *http.Response so that callers can handle redirects, authentication, -// etc. -// -// Deprecated: Use Dialer instead. -func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) { - d := Dialer{ - ReadBufferSize: readBufSize, - WriteBufferSize: writeBufSize, - NetDial: func(net, addr string) (net.Conn, error) { - return netConn, nil - }, - } - return d.Dial(u.String(), requestHeader) -} - -// A Dialer contains options for connecting to WebSocket server. -type Dialer struct { - // NetDial specifies the dial function for creating TCP connections. If - // NetDial is nil, net.Dial is used. - NetDial func(network, addr string) (net.Conn, error) - - // NetDialContext specifies the dial function for creating TCP connections. If - // NetDialContext is nil, net.DialContext is used. - NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error) - - // Proxy specifies a function to return a proxy for a given - // Request. If the function returns a non-nil error, the - // request is aborted with the provided error. - // If Proxy is nil or returns a nil *URL, no proxy is used. - Proxy func(*http.Request) (*url.URL, error) - - // TLSClientConfig specifies the TLS configuration to use with tls.Client. - // If nil, the default configuration is used. - TLSClientConfig *tls.Config - - // HandshakeTimeout specifies the duration for the handshake to complete. - HandshakeTimeout time.Duration - - // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer - // size is zero, then a useful default size is used. The I/O buffer sizes - // do not limit the size of the messages that can be sent or received. - ReadBufferSize, WriteBufferSize int - - // WriteBufferPool is a pool of buffers for write operations. If the value - // is not set, then write buffers are allocated to the connection for the - // lifetime of the connection. - // - // A pool is most useful when the application has a modest volume of writes - // across a large number of connections. - // - // Applications should use a single pool for each unique value of - // WriteBufferSize. - WriteBufferPool BufferPool - - // Subprotocols specifies the client's requested subprotocols. - Subprotocols []string - - // EnableCompression specifies if the client should attempt to negotiate - // per message compression (RFC 7692). Setting this value to true does not - // guarantee that compression will be supported. Currently only "no context - // takeover" modes are supported. - EnableCompression bool - - // Jar specifies the cookie jar. - // If Jar is nil, cookies are not sent in requests and ignored - // in responses. - Jar http.CookieJar -} - -// Dial creates a new client connection by calling DialContext with a background context. -func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { - return d.DialContext(context.Background(), urlStr, requestHeader) -} - -var errMalformedURL = errors.New("malformed ws or wss URL") - -func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) { - hostPort = u.Host - hostNoPort = u.Host - if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") { - hostNoPort = hostNoPort[:i] - } else { - switch u.Scheme { - case "wss": - hostPort += ":443" - case "https": - hostPort += ":443" - default: - hostPort += ":80" - } - } - return hostPort, hostNoPort -} - -// DefaultDialer is a dialer with all fields set to the default values. -var DefaultDialer = &Dialer{ - Proxy: http.ProxyFromEnvironment, - HandshakeTimeout: 45 * time.Second, -} - -// nilDialer is dialer to use when receiver is nil. -var nilDialer = *DefaultDialer - -// DialContext creates a new client connection. Use requestHeader to specify the -// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). -// Use the response.Header to get the selected subprotocol -// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). -// -// The context will be used in the request and in the Dialer -// -// If the WebSocket handshake fails, ErrBadHandshake is returned along with a -// non-nil *http.Response so that callers can handle redirects, authentication, -// etcetera. The response body may not contain the entire response and does not -// need to be closed by the application. -func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { - if d == nil { - d = &nilDialer - } - - challengeKey, err := generateChallengeKey() - if err != nil { - return nil, nil, err - } - - u, err := url.Parse(urlStr) - if err != nil { - return nil, nil, err - } - - switch u.Scheme { - case "ws": - u.Scheme = "http" - case "wss": - u.Scheme = "https" - default: - return nil, nil, errMalformedURL - } - - if u.User != nil { - // User name and password are not allowed in websocket URIs. - return nil, nil, errMalformedURL - } - - req := &http.Request{ - Method: "GET", - URL: u, - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - Header: make(http.Header), - Host: u.Host, - } - req = req.WithContext(ctx) - - // Set the cookies present in the cookie jar of the dialer - if d.Jar != nil { - for _, cookie := range d.Jar.Cookies(u) { - req.AddCookie(cookie) - } - } - - // Set the request headers using the capitalization for names and values in - // RFC examples. Although the capitalization shouldn't matter, there are - // servers that depend on it. The Header.Set method is not used because the - // method canonicalizes the header names. - req.Header["Upgrade"] = []string{"websocket"} - req.Header["Connection"] = []string{"Upgrade"} - req.Header["Sec-WebSocket-Key"] = []string{challengeKey} - req.Header["Sec-WebSocket-Version"] = []string{"13"} - if len(d.Subprotocols) > 0 { - req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")} - } - for k, vs := range requestHeader { - switch { - case k == "Host": - if len(vs) > 0 { - req.Host = vs[0] - } - case k == "Upgrade" || - k == "Connection" || - k == "Sec-Websocket-Key" || - k == "Sec-Websocket-Version" || - k == "Sec-Websocket-Extensions" || - (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): - return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) - case k == "Sec-Websocket-Protocol": - req.Header["Sec-WebSocket-Protocol"] = vs - default: - req.Header[k] = vs - } - } - - if d.EnableCompression { - req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"} - } - - if d.HandshakeTimeout != 0 { - var cancel func() - ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout) - defer cancel() - } - - // Get network dial function. - var netDial func(network, add string) (net.Conn, error) - - if d.NetDialContext != nil { - netDial = func(network, addr string) (net.Conn, error) { - return d.NetDialContext(ctx, network, addr) - } - } else if d.NetDial != nil { - netDial = d.NetDial - } else { - netDialer := &net.Dialer{} - netDial = func(network, addr string) (net.Conn, error) { - return netDialer.DialContext(ctx, network, addr) - } - } - - // If needed, wrap the dial function to set the connection deadline. - if deadline, ok := ctx.Deadline(); ok { - forwardDial := netDial - netDial = func(network, addr string) (net.Conn, error) { - c, err := forwardDial(network, addr) - if err != nil { - return nil, err - } - err = c.SetDeadline(deadline) - if err != nil { - c.Close() - return nil, err - } - return c, nil - } - } - - // If needed, wrap the dial function to connect through a proxy. - if d.Proxy != nil { - proxyURL, err := d.Proxy(req) - if err != nil { - return nil, nil, err - } - if proxyURL != nil { - dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial)) - if err != nil { - return nil, nil, err - } - netDial = dialer.Dial - } - } - - hostPort, hostNoPort := hostPortNoPort(u) - trace := httptrace.ContextClientTrace(ctx) - if trace != nil && trace.GetConn != nil { - trace.GetConn(hostPort) - } - - netConn, err := netDial("tcp", hostPort) - if trace != nil && trace.GotConn != nil { - trace.GotConn(httptrace.GotConnInfo{ - Conn: netConn, - }) - } - if err != nil { - return nil, nil, err - } - - defer func() { - if netConn != nil { - netConn.Close() - } - }() - - if u.Scheme == "https" { - cfg := cloneTLSConfig(d.TLSClientConfig) - if cfg.ServerName == "" { - cfg.ServerName = hostNoPort - } - tlsConn := tls.Client(netConn, cfg) - netConn = tlsConn - - var err error - if trace != nil { - err = doHandshakeWithTrace(trace, tlsConn, cfg) - } else { - err = doHandshake(tlsConn, cfg) - } - - if err != nil { - return nil, nil, err - } - } - - conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil) - - if err := req.Write(netConn); err != nil { - return nil, nil, err - } - - if trace != nil && trace.GotFirstResponseByte != nil { - if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 { - trace.GotFirstResponseByte() - } - } - - resp, err := http.ReadResponse(conn.br, req) - if err != nil { - return nil, nil, err - } - - if d.Jar != nil { - if rc := resp.Cookies(); len(rc) > 0 { - d.Jar.SetCookies(u, rc) - } - } - - if resp.StatusCode != 101 || - !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || - !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || - resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) { - // Before closing the network connection on return from this - // function, slurp up some of the response to aid application - // debugging. - buf := make([]byte, 1024) - n, _ := io.ReadFull(resp.Body, buf) - resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) - return nil, resp, ErrBadHandshake - } - - for _, ext := range parseExtensions(resp.Header) { - if ext[""] != "permessage-deflate" { - continue - } - _, snct := ext["server_no_context_takeover"] - _, cnct := ext["client_no_context_takeover"] - if !snct || !cnct { - return nil, resp, errInvalidCompression - } - conn.newCompressionWriter = compressNoContextTakeover - conn.newDecompressionReader = decompressNoContextTakeover - break - } - - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") - - netConn.SetDeadline(time.Time{}) - netConn = nil // to avoid close in defer. - return conn, resp, nil -} - -func doHandshake(tlsConn *tls.Conn, cfg *tls.Config) error { - if err := tlsConn.Handshake(); err != nil { - return err - } - if !cfg.InsecureSkipVerify { - if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/gorilla/websocket/client_clone.go b/vendor/github.com/gorilla/websocket/client_clone.go deleted file mode 100644 index 4f0d94372..000000000 --- a/vendor/github.com/gorilla/websocket/client_clone.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package websocket - -import "crypto/tls" - -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return cfg.Clone() -} diff --git a/vendor/github.com/gorilla/websocket/client_clone_legacy.go b/vendor/github.com/gorilla/websocket/client_clone_legacy.go deleted file mode 100644 index babb007fb..000000000 --- a/vendor/github.com/gorilla/websocket/client_clone_legacy.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8 - -package websocket - -import "crypto/tls" - -// cloneTLSConfig clones all public fields except the fields -// SessionTicketsDisabled and SessionTicketKey. This avoids copying the -// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a -// config in active use. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - } -} diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go deleted file mode 100644 index 813ffb1e8..000000000 --- a/vendor/github.com/gorilla/websocket/compression.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "compress/flate" - "errors" - "io" - "strings" - "sync" -) - -const ( - minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 - maxCompressionLevel = flate.BestCompression - defaultCompressionLevel = 1 -) - -var ( - flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool - flateReaderPool = sync.Pool{New: func() interface{} { - return flate.NewReader(nil) - }} -) - -func decompressNoContextTakeover(r io.Reader) io.ReadCloser { - const tail = - // Add four bytes as specified in RFC - "\x00\x00\xff\xff" + - // Add final block to squelch unexpected EOF error from flate reader. - "\x01\x00\x00\xff\xff" - - fr, _ := flateReaderPool.Get().(io.ReadCloser) - fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) - return &flateReadWrapper{fr} -} - -func isValidCompressionLevel(level int) bool { - return minCompressionLevel <= level && level <= maxCompressionLevel -} - -func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { - p := &flateWriterPools[level-minCompressionLevel] - tw := &truncWriter{w: w} - fw, _ := p.Get().(*flate.Writer) - if fw == nil { - fw, _ = flate.NewWriter(tw, level) - } else { - fw.Reset(tw) - } - return &flateWriteWrapper{fw: fw, tw: tw, p: p} -} - -// truncWriter is an io.Writer that writes all but the last four bytes of the -// stream to another io.Writer. -type truncWriter struct { - w io.WriteCloser - n int - p [4]byte -} - -func (w *truncWriter) Write(p []byte) (int, error) { - n := 0 - - // fill buffer first for simplicity. - if w.n < len(w.p) { - n = copy(w.p[w.n:], p) - p = p[n:] - w.n += n - if len(p) == 0 { - return n, nil - } - } - - m := len(p) - if m > len(w.p) { - m = len(w.p) - } - - if nn, err := w.w.Write(w.p[:m]); err != nil { - return n + nn, err - } - - copy(w.p[:], w.p[m:]) - copy(w.p[len(w.p)-m:], p[len(p)-m:]) - nn, err := w.w.Write(p[:len(p)-m]) - return n + nn, err -} - -type flateWriteWrapper struct { - fw *flate.Writer - tw *truncWriter - p *sync.Pool -} - -func (w *flateWriteWrapper) Write(p []byte) (int, error) { - if w.fw == nil { - return 0, errWriteClosed - } - return w.fw.Write(p) -} - -func (w *flateWriteWrapper) Close() error { - if w.fw == nil { - return errWriteClosed - } - err1 := w.fw.Flush() - w.p.Put(w.fw) - w.fw = nil - if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { - return errors.New("websocket: internal error, unexpected bytes at end of flate stream") - } - err2 := w.tw.w.Close() - if err1 != nil { - return err1 - } - return err2 -} - -type flateReadWrapper struct { - fr io.ReadCloser -} - -func (r *flateReadWrapper) Read(p []byte) (int, error) { - if r.fr == nil { - return 0, io.ErrClosedPipe - } - n, err := r.fr.Read(p) - if err == io.EOF { - // Preemptively place the reader back in the pool. This helps with - // scenarios where the application does not call NextReader() soon after - // this final read. - r.Close() - } - return n, err -} - -func (r *flateReadWrapper) Close() error { - if r.fr == nil { - return io.ErrClosedPipe - } - err := r.fr.Close() - flateReaderPool.Put(r.fr) - r.fr = nil - return err -} diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go deleted file mode 100644 index d2a21c148..000000000 --- a/vendor/github.com/gorilla/websocket/conn.go +++ /dev/null @@ -1,1165 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "encoding/binary" - "errors" - "io" - "io/ioutil" - "math/rand" - "net" - "strconv" - "sync" - "time" - "unicode/utf8" -) - -const ( - // Frame header byte 0 bits from Section 5.2 of RFC 6455 - finalBit = 1 << 7 - rsv1Bit = 1 << 6 - rsv2Bit = 1 << 5 - rsv3Bit = 1 << 4 - - // Frame header byte 1 bits from Section 5.2 of RFC 6455 - maskBit = 1 << 7 - - maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask - maxControlFramePayloadSize = 125 - - writeWait = time.Second - - defaultReadBufferSize = 4096 - defaultWriteBufferSize = 4096 - - continuationFrame = 0 - noFrame = -1 -) - -// Close codes defined in RFC 6455, section 11.7. -const ( - CloseNormalClosure = 1000 - CloseGoingAway = 1001 - CloseProtocolError = 1002 - CloseUnsupportedData = 1003 - CloseNoStatusReceived = 1005 - CloseAbnormalClosure = 1006 - CloseInvalidFramePayloadData = 1007 - ClosePolicyViolation = 1008 - CloseMessageTooBig = 1009 - CloseMandatoryExtension = 1010 - CloseInternalServerErr = 1011 - CloseServiceRestart = 1012 - CloseTryAgainLater = 1013 - CloseTLSHandshake = 1015 -) - -// The message types are defined in RFC 6455, section 11.8. -const ( - // TextMessage denotes a text data message. The text message payload is - // interpreted as UTF-8 encoded text data. - TextMessage = 1 - - // BinaryMessage denotes a binary data message. - BinaryMessage = 2 - - // CloseMessage denotes a close control message. The optional message - // payload contains a numeric code and text. Use the FormatCloseMessage - // function to format a close message payload. - CloseMessage = 8 - - // PingMessage denotes a ping control message. The optional message payload - // is UTF-8 encoded text. - PingMessage = 9 - - // PongMessage denotes a pong control message. The optional message payload - // is UTF-8 encoded text. - PongMessage = 10 -) - -// ErrCloseSent is returned when the application writes a message to the -// connection after sending a close message. -var ErrCloseSent = errors.New("websocket: close sent") - -// ErrReadLimit is returned when reading a message that is larger than the -// read limit set for the connection. -var ErrReadLimit = errors.New("websocket: read limit exceeded") - -// netError satisfies the net Error interface. -type netError struct { - msg string - temporary bool - timeout bool -} - -func (e *netError) Error() string { return e.msg } -func (e *netError) Temporary() bool { return e.temporary } -func (e *netError) Timeout() bool { return e.timeout } - -// CloseError represents a close message. -type CloseError struct { - // Code is defined in RFC 6455, section 11.7. - Code int - - // Text is the optional text payload. - Text string -} - -func (e *CloseError) Error() string { - s := []byte("websocket: close ") - s = strconv.AppendInt(s, int64(e.Code), 10) - switch e.Code { - case CloseNormalClosure: - s = append(s, " (normal)"...) - case CloseGoingAway: - s = append(s, " (going away)"...) - case CloseProtocolError: - s = append(s, " (protocol error)"...) - case CloseUnsupportedData: - s = append(s, " (unsupported data)"...) - case CloseNoStatusReceived: - s = append(s, " (no status)"...) - case CloseAbnormalClosure: - s = append(s, " (abnormal closure)"...) - case CloseInvalidFramePayloadData: - s = append(s, " (invalid payload data)"...) - case ClosePolicyViolation: - s = append(s, " (policy violation)"...) - case CloseMessageTooBig: - s = append(s, " (message too big)"...) - case CloseMandatoryExtension: - s = append(s, " (mandatory extension missing)"...) - case CloseInternalServerErr: - s = append(s, " (internal server error)"...) - case CloseTLSHandshake: - s = append(s, " (TLS handshake error)"...) - } - if e.Text != "" { - s = append(s, ": "...) - s = append(s, e.Text...) - } - return string(s) -} - -// IsCloseError returns boolean indicating whether the error is a *CloseError -// with one of the specified codes. -func IsCloseError(err error, codes ...int) bool { - if e, ok := err.(*CloseError); ok { - for _, code := range codes { - if e.Code == code { - return true - } - } - } - return false -} - -// IsUnexpectedCloseError returns boolean indicating whether the error is a -// *CloseError with a code not in the list of expected codes. -func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { - if e, ok := err.(*CloseError); ok { - for _, code := range expectedCodes { - if e.Code == code { - return false - } - } - return true - } - return false -} - -var ( - errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} - errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} - errBadWriteOpCode = errors.New("websocket: bad write message type") - errWriteClosed = errors.New("websocket: write closed") - errInvalidControlFrame = errors.New("websocket: invalid control frame") -) - -func newMaskKey() [4]byte { - n := rand.Uint32() - return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} -} - -func hideTempErr(err error) error { - if e, ok := err.(net.Error); ok && e.Temporary() { - err = &netError{msg: e.Error(), timeout: e.Timeout()} - } - return err -} - -func isControl(frameType int) bool { - return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage -} - -func isData(frameType int) bool { - return frameType == TextMessage || frameType == BinaryMessage -} - -var validReceivedCloseCodes = map[int]bool{ - // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number - - CloseNormalClosure: true, - CloseGoingAway: true, - CloseProtocolError: true, - CloseUnsupportedData: true, - CloseNoStatusReceived: false, - CloseAbnormalClosure: false, - CloseInvalidFramePayloadData: true, - ClosePolicyViolation: true, - CloseMessageTooBig: true, - CloseMandatoryExtension: true, - CloseInternalServerErr: true, - CloseServiceRestart: true, - CloseTryAgainLater: true, - CloseTLSHandshake: false, -} - -func isValidReceivedCloseCode(code int) bool { - return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) -} - -// BufferPool represents a pool of buffers. The *sync.Pool type satisfies this -// interface. The type of the value stored in a pool is not specified. -type BufferPool interface { - // Get gets a value from the pool or returns nil if the pool is empty. - Get() interface{} - // Put adds a value to the pool. - Put(interface{}) -} - -// writePoolData is the type added to the write buffer pool. This wrapper is -// used to prevent applications from peeking at and depending on the values -// added to the pool. -type writePoolData struct{ buf []byte } - -// The Conn type represents a WebSocket connection. -type Conn struct { - conn net.Conn - isServer bool - subprotocol string - - // Write fields - mu chan bool // used as mutex to protect write to conn - writeBuf []byte // frame is constructed in this buffer. - writePool BufferPool - writeBufSize int - writeDeadline time.Time - writer io.WriteCloser // the current writer returned to the application - isWriting bool // for best-effort concurrent write detection - - writeErrMu sync.Mutex - writeErr error - - enableWriteCompression bool - compressionLevel int - newCompressionWriter func(io.WriteCloser, int) io.WriteCloser - - // Read fields - reader io.ReadCloser // the current reader returned to the application - readErr error - br *bufio.Reader - readRemaining int64 // bytes remaining in current frame. - readFinal bool // true the current message has more frames. - readLength int64 // Message size. - readLimit int64 // Maximum message size. - readMaskPos int - readMaskKey [4]byte - handlePong func(string) error - handlePing func(string) error - handleClose func(int, string) error - readErrCount int - messageReader *messageReader // the current low-level reader - - readDecompress bool // whether last read frame had RSV1 set - newDecompressionReader func(io.Reader) io.ReadCloser -} - -func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn { - - if br == nil { - if readBufferSize == 0 { - readBufferSize = defaultReadBufferSize - } else if readBufferSize < maxControlFramePayloadSize { - // must be large enough for control frame - readBufferSize = maxControlFramePayloadSize - } - br = bufio.NewReaderSize(conn, readBufferSize) - } - - if writeBufferSize <= 0 { - writeBufferSize = defaultWriteBufferSize - } - writeBufferSize += maxFrameHeaderSize - - if writeBuf == nil && writeBufferPool == nil { - writeBuf = make([]byte, writeBufferSize) - } - - mu := make(chan bool, 1) - mu <- true - c := &Conn{ - isServer: isServer, - br: br, - conn: conn, - mu: mu, - readFinal: true, - writeBuf: writeBuf, - writePool: writeBufferPool, - writeBufSize: writeBufferSize, - enableWriteCompression: true, - compressionLevel: defaultCompressionLevel, - } - c.SetCloseHandler(nil) - c.SetPingHandler(nil) - c.SetPongHandler(nil) - return c -} - -// Subprotocol returns the negotiated protocol for the connection. -func (c *Conn) Subprotocol() string { - return c.subprotocol -} - -// Close closes the underlying network connection without sending or waiting -// for a close message. -func (c *Conn) Close() error { - return c.conn.Close() -} - -// LocalAddr returns the local network address. -func (c *Conn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -// RemoteAddr returns the remote network address. -func (c *Conn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -// Write methods - -func (c *Conn) writeFatal(err error) error { - err = hideTempErr(err) - c.writeErrMu.Lock() - if c.writeErr == nil { - c.writeErr = err - } - c.writeErrMu.Unlock() - return err -} - -func (c *Conn) read(n int) ([]byte, error) { - p, err := c.br.Peek(n) - if err == io.EOF { - err = errUnexpectedEOF - } - c.br.Discard(len(p)) - return p, err -} - -func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error { - <-c.mu - defer func() { c.mu <- true }() - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - if err != nil { - return err - } - - c.conn.SetWriteDeadline(deadline) - if len(buf1) == 0 { - _, err = c.conn.Write(buf0) - } else { - err = c.writeBufs(buf0, buf1) - } - if err != nil { - return c.writeFatal(err) - } - if frameType == CloseMessage { - c.writeFatal(ErrCloseSent) - } - return nil -} - -// WriteControl writes a control message with the given deadline. The allowed -// message types are CloseMessage, PingMessage and PongMessage. -func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { - if !isControl(messageType) { - return errBadWriteOpCode - } - if len(data) > maxControlFramePayloadSize { - return errInvalidControlFrame - } - - b0 := byte(messageType) | finalBit - b1 := byte(len(data)) - if !c.isServer { - b1 |= maskBit - } - - buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) - buf = append(buf, b0, b1) - - if c.isServer { - buf = append(buf, data...) - } else { - key := newMaskKey() - buf = append(buf, key[:]...) - buf = append(buf, data...) - maskBytes(key, 0, buf[6:]) - } - - d := time.Hour * 1000 - if !deadline.IsZero() { - d = deadline.Sub(time.Now()) - if d < 0 { - return errWriteTimeout - } - } - - timer := time.NewTimer(d) - select { - case <-c.mu: - timer.Stop() - case <-timer.C: - return errWriteTimeout - } - defer func() { c.mu <- true }() - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - if err != nil { - return err - } - - c.conn.SetWriteDeadline(deadline) - _, err = c.conn.Write(buf) - if err != nil { - return c.writeFatal(err) - } - if messageType == CloseMessage { - c.writeFatal(ErrCloseSent) - } - return err -} - -func (c *Conn) prepWrite(messageType int) error { - // Close previous writer if not already closed by the application. It's - // probably better to return an error in this situation, but we cannot - // change this without breaking existing applications. - if c.writer != nil { - c.writer.Close() - c.writer = nil - } - - if !isControl(messageType) && !isData(messageType) { - return errBadWriteOpCode - } - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - if err != nil { - return err - } - - if c.writeBuf == nil { - wpd, ok := c.writePool.Get().(writePoolData) - if ok { - c.writeBuf = wpd.buf - } else { - c.writeBuf = make([]byte, c.writeBufSize) - } - } - return nil -} - -// NextWriter returns a writer for the next message to send. The writer's Close -// method flushes the complete message to the network. -// -// There can be at most one open writer on a connection. NextWriter closes the -// previous writer if the application has not already done so. -// -// All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and -// PongMessage) are supported. -func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { - if err := c.prepWrite(messageType); err != nil { - return nil, err - } - - mw := &messageWriter{ - c: c, - frameType: messageType, - pos: maxFrameHeaderSize, - } - c.writer = mw - if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { - w := c.newCompressionWriter(c.writer, c.compressionLevel) - mw.compress = true - c.writer = w - } - return c.writer, nil -} - -type messageWriter struct { - c *Conn - compress bool // whether next call to flushFrame should set RSV1 - pos int // end of data in writeBuf. - frameType int // type of the current frame. - err error -} - -func (w *messageWriter) fatal(err error) error { - if w.err != nil { - w.err = err - w.c.writer = nil - } - return err -} - -// flushFrame writes buffered data and extra as a frame to the network. The -// final argument indicates that this is the last frame in the message. -func (w *messageWriter) flushFrame(final bool, extra []byte) error { - c := w.c - length := w.pos - maxFrameHeaderSize + len(extra) - - // Check for invalid control frames. - if isControl(w.frameType) && - (!final || length > maxControlFramePayloadSize) { - return w.fatal(errInvalidControlFrame) - } - - b0 := byte(w.frameType) - if final { - b0 |= finalBit - } - if w.compress { - b0 |= rsv1Bit - } - w.compress = false - - b1 := byte(0) - if !c.isServer { - b1 |= maskBit - } - - // Assume that the frame starts at beginning of c.writeBuf. - framePos := 0 - if c.isServer { - // Adjust up if mask not included in the header. - framePos = 4 - } - - switch { - case length >= 65536: - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | 127 - binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) - case length > 125: - framePos += 6 - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | 126 - binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) - default: - framePos += 8 - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | byte(length) - } - - if !c.isServer { - key := newMaskKey() - copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) - maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) - if len(extra) > 0 { - return c.writeFatal(errors.New("websocket: internal error, extra used in client mode")) - } - } - - // Write the buffers to the connection with best-effort detection of - // concurrent writes. See the concurrency section in the package - // documentation for more info. - - if c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = true - - err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) - - if !c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = false - - if err != nil { - return w.fatal(err) - } - - if final { - c.writer = nil - if c.writePool != nil { - c.writePool.Put(writePoolData{buf: c.writeBuf}) - c.writeBuf = nil - } - return nil - } - - // Setup for next frame. - w.pos = maxFrameHeaderSize - w.frameType = continuationFrame - return nil -} - -func (w *messageWriter) ncopy(max int) (int, error) { - n := len(w.c.writeBuf) - w.pos - if n <= 0 { - if err := w.flushFrame(false, nil); err != nil { - return 0, err - } - n = len(w.c.writeBuf) - w.pos - } - if n > max { - n = max - } - return n, nil -} - -func (w *messageWriter) Write(p []byte) (int, error) { - if w.err != nil { - return 0, w.err - } - - if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { - // Don't buffer large messages. - err := w.flushFrame(false, p) - if err != nil { - return 0, err - } - return len(p), nil - } - - nn := len(p) - for len(p) > 0 { - n, err := w.ncopy(len(p)) - if err != nil { - return 0, err - } - copy(w.c.writeBuf[w.pos:], p[:n]) - w.pos += n - p = p[n:] - } - return nn, nil -} - -func (w *messageWriter) WriteString(p string) (int, error) { - if w.err != nil { - return 0, w.err - } - - nn := len(p) - for len(p) > 0 { - n, err := w.ncopy(len(p)) - if err != nil { - return 0, err - } - copy(w.c.writeBuf[w.pos:], p[:n]) - w.pos += n - p = p[n:] - } - return nn, nil -} - -func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { - if w.err != nil { - return 0, w.err - } - for { - if w.pos == len(w.c.writeBuf) { - err = w.flushFrame(false, nil) - if err != nil { - break - } - } - var n int - n, err = r.Read(w.c.writeBuf[w.pos:]) - w.pos += n - nn += int64(n) - if err != nil { - if err == io.EOF { - err = nil - } - break - } - } - return nn, err -} - -func (w *messageWriter) Close() error { - if w.err != nil { - return w.err - } - if err := w.flushFrame(true, nil); err != nil { - return err - } - w.err = errWriteClosed - return nil -} - -// WritePreparedMessage writes prepared message into connection. -func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { - frameType, frameData, err := pm.frame(prepareKey{ - isServer: c.isServer, - compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), - compressionLevel: c.compressionLevel, - }) - if err != nil { - return err - } - if c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = true - err = c.write(frameType, c.writeDeadline, frameData, nil) - if !c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = false - return err -} - -// WriteMessage is a helper method for getting a writer using NextWriter, -// writing the message and closing the writer. -func (c *Conn) WriteMessage(messageType int, data []byte) error { - - if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { - // Fast path with no allocations and single frame. - - if err := c.prepWrite(messageType); err != nil { - return err - } - mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize} - n := copy(c.writeBuf[mw.pos:], data) - mw.pos += n - data = data[n:] - return mw.flushFrame(true, data) - } - - w, err := c.NextWriter(messageType) - if err != nil { - return err - } - if _, err = w.Write(data); err != nil { - return err - } - return w.Close() -} - -// SetWriteDeadline sets the write deadline on the underlying network -// connection. After a write has timed out, the websocket state is corrupt and -// all future writes will return an error. A zero value for t means writes will -// not time out. -func (c *Conn) SetWriteDeadline(t time.Time) error { - c.writeDeadline = t - return nil -} - -// Read methods - -func (c *Conn) advanceFrame() (int, error) { - // 1. Skip remainder of previous frame. - - if c.readRemaining > 0 { - if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { - return noFrame, err - } - } - - // 2. Read and parse first two bytes of frame header. - - p, err := c.read(2) - if err != nil { - return noFrame, err - } - - final := p[0]&finalBit != 0 - frameType := int(p[0] & 0xf) - mask := p[1]&maskBit != 0 - c.readRemaining = int64(p[1] & 0x7f) - - c.readDecompress = false - if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 { - c.readDecompress = true - p[0] &^= rsv1Bit - } - - if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 { - return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16)) - } - - switch frameType { - case CloseMessage, PingMessage, PongMessage: - if c.readRemaining > maxControlFramePayloadSize { - return noFrame, c.handleProtocolError("control frame length > 125") - } - if !final { - return noFrame, c.handleProtocolError("control frame not final") - } - case TextMessage, BinaryMessage: - if !c.readFinal { - return noFrame, c.handleProtocolError("message start before final message frame") - } - c.readFinal = final - case continuationFrame: - if c.readFinal { - return noFrame, c.handleProtocolError("continuation after final message frame") - } - c.readFinal = final - default: - return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType)) - } - - // 3. Read and parse frame length. - - switch c.readRemaining { - case 126: - p, err := c.read(2) - if err != nil { - return noFrame, err - } - c.readRemaining = int64(binary.BigEndian.Uint16(p)) - case 127: - p, err := c.read(8) - if err != nil { - return noFrame, err - } - c.readRemaining = int64(binary.BigEndian.Uint64(p)) - } - - // 4. Handle frame masking. - - if mask != c.isServer { - return noFrame, c.handleProtocolError("incorrect mask flag") - } - - if mask { - c.readMaskPos = 0 - p, err := c.read(len(c.readMaskKey)) - if err != nil { - return noFrame, err - } - copy(c.readMaskKey[:], p) - } - - // 5. For text and binary messages, enforce read limit and return. - - if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { - - c.readLength += c.readRemaining - if c.readLimit > 0 && c.readLength > c.readLimit { - c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) - return noFrame, ErrReadLimit - } - - return frameType, nil - } - - // 6. Read control frame payload. - - var payload []byte - if c.readRemaining > 0 { - payload, err = c.read(int(c.readRemaining)) - c.readRemaining = 0 - if err != nil { - return noFrame, err - } - if c.isServer { - maskBytes(c.readMaskKey, 0, payload) - } - } - - // 7. Process control frame payload. - - switch frameType { - case PongMessage: - if err := c.handlePong(string(payload)); err != nil { - return noFrame, err - } - case PingMessage: - if err := c.handlePing(string(payload)); err != nil { - return noFrame, err - } - case CloseMessage: - closeCode := CloseNoStatusReceived - closeText := "" - if len(payload) >= 2 { - closeCode = int(binary.BigEndian.Uint16(payload)) - if !isValidReceivedCloseCode(closeCode) { - return noFrame, c.handleProtocolError("invalid close code") - } - closeText = string(payload[2:]) - if !utf8.ValidString(closeText) { - return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") - } - } - if err := c.handleClose(closeCode, closeText); err != nil { - return noFrame, err - } - return noFrame, &CloseError{Code: closeCode, Text: closeText} - } - - return frameType, nil -} - -func (c *Conn) handleProtocolError(message string) error { - c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait)) - return errors.New("websocket: " + message) -} - -// NextReader returns the next data message received from the peer. The -// returned messageType is either TextMessage or BinaryMessage. -// -// There can be at most one open reader on a connection. NextReader discards -// the previous message if the application has not already consumed it. -// -// Applications must break out of the application's read loop when this method -// returns a non-nil error value. Errors returned from this method are -// permanent. Once this method returns a non-nil error, all subsequent calls to -// this method return the same error. -func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { - // Close previous reader, only relevant for decompression. - if c.reader != nil { - c.reader.Close() - c.reader = nil - } - - c.messageReader = nil - c.readLength = 0 - - for c.readErr == nil { - frameType, err := c.advanceFrame() - if err != nil { - c.readErr = hideTempErr(err) - break - } - if frameType == TextMessage || frameType == BinaryMessage { - c.messageReader = &messageReader{c} - c.reader = c.messageReader - if c.readDecompress { - c.reader = c.newDecompressionReader(c.reader) - } - return frameType, c.reader, nil - } - } - - // Applications that do handle the error returned from this method spin in - // tight loop on connection failure. To help application developers detect - // this error, panic on repeated reads to the failed connection. - c.readErrCount++ - if c.readErrCount >= 1000 { - panic("repeated read on failed websocket connection") - } - - return noFrame, nil, c.readErr -} - -type messageReader struct{ c *Conn } - -func (r *messageReader) Read(b []byte) (int, error) { - c := r.c - if c.messageReader != r { - return 0, io.EOF - } - - for c.readErr == nil { - - if c.readRemaining > 0 { - if int64(len(b)) > c.readRemaining { - b = b[:c.readRemaining] - } - n, err := c.br.Read(b) - c.readErr = hideTempErr(err) - if c.isServer { - c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) - } - c.readRemaining -= int64(n) - if c.readRemaining > 0 && c.readErr == io.EOF { - c.readErr = errUnexpectedEOF - } - return n, c.readErr - } - - if c.readFinal { - c.messageReader = nil - return 0, io.EOF - } - - frameType, err := c.advanceFrame() - switch { - case err != nil: - c.readErr = hideTempErr(err) - case frameType == TextMessage || frameType == BinaryMessage: - c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") - } - } - - err := c.readErr - if err == io.EOF && c.messageReader == r { - err = errUnexpectedEOF - } - return 0, err -} - -func (r *messageReader) Close() error { - return nil -} - -// ReadMessage is a helper method for getting a reader using NextReader and -// reading from that reader to a buffer. -func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { - var r io.Reader - messageType, r, err = c.NextReader() - if err != nil { - return messageType, nil, err - } - p, err = ioutil.ReadAll(r) - return messageType, p, err -} - -// SetReadDeadline sets the read deadline on the underlying network connection. -// After a read has timed out, the websocket connection state is corrupt and -// all future reads will return an error. A zero value for t means reads will -// not time out. -func (c *Conn) SetReadDeadline(t time.Time) error { - return c.conn.SetReadDeadline(t) -} - -// SetReadLimit sets the maximum size for a message read from the peer. If a -// message exceeds the limit, the connection sends a close message to the peer -// and returns ErrReadLimit to the application. -func (c *Conn) SetReadLimit(limit int64) { - c.readLimit = limit -} - -// CloseHandler returns the current close handler -func (c *Conn) CloseHandler() func(code int, text string) error { - return c.handleClose -} - -// SetCloseHandler sets the handler for close messages received from the peer. -// The code argument to h is the received close code or CloseNoStatusReceived -// if the close message is empty. The default close handler sends a close -// message back to the peer. -// -// The handler function is called from the NextReader, ReadMessage and message -// reader Read methods. The application must read the connection to process -// close messages as described in the section on Control Messages above. -// -// The connection read methods return a CloseError when a close message is -// received. Most applications should handle close messages as part of their -// normal error handling. Applications should only set a close handler when the -// application must perform some action before sending a close message back to -// the peer. -func (c *Conn) SetCloseHandler(h func(code int, text string) error) { - if h == nil { - h = func(code int, text string) error { - message := FormatCloseMessage(code, "") - c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) - return nil - } - } - c.handleClose = h -} - -// PingHandler returns the current ping handler -func (c *Conn) PingHandler() func(appData string) error { - return c.handlePing -} - -// SetPingHandler sets the handler for ping messages received from the peer. -// The appData argument to h is the PING message application data. The default -// ping handler sends a pong to the peer. -// -// The handler function is called from the NextReader, ReadMessage and message -// reader Read methods. The application must read the connection to process -// ping messages as described in the section on Control Messages above. -func (c *Conn) SetPingHandler(h func(appData string) error) { - if h == nil { - h = func(message string) error { - err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) - if err == ErrCloseSent { - return nil - } else if e, ok := err.(net.Error); ok && e.Temporary() { - return nil - } - return err - } - } - c.handlePing = h -} - -// PongHandler returns the current pong handler -func (c *Conn) PongHandler() func(appData string) error { - return c.handlePong -} - -// SetPongHandler sets the handler for pong messages received from the peer. -// The appData argument to h is the PONG message application data. The default -// pong handler does nothing. -// -// The handler function is called from the NextReader, ReadMessage and message -// reader Read methods. The application must read the connection to process -// pong messages as described in the section on Control Messages above. -func (c *Conn) SetPongHandler(h func(appData string) error) { - if h == nil { - h = func(string) error { return nil } - } - c.handlePong = h -} - -// UnderlyingConn returns the internal net.Conn. This can be used to further -// modifications to connection specific flags. -func (c *Conn) UnderlyingConn() net.Conn { - return c.conn -} - -// EnableWriteCompression enables and disables write compression of -// subsequent text and binary messages. This function is a noop if -// compression was not negotiated with the peer. -func (c *Conn) EnableWriteCompression(enable bool) { - c.enableWriteCompression = enable -} - -// SetCompressionLevel sets the flate compression level for subsequent text and -// binary messages. This function is a noop if compression was not negotiated -// with the peer. See the compress/flate package for a description of -// compression levels. -func (c *Conn) SetCompressionLevel(level int) error { - if !isValidCompressionLevel(level) { - return errors.New("websocket: invalid compression level") - } - c.compressionLevel = level - return nil -} - -// FormatCloseMessage formats closeCode and text as a WebSocket close message. -// An empty message is returned for code CloseNoStatusReceived. -func FormatCloseMessage(closeCode int, text string) []byte { - if closeCode == CloseNoStatusReceived { - // Return empty message because it's illegal to send - // CloseNoStatusReceived. Return non-nil value in case application - // checks for nil. - return []byte{} - } - buf := make([]byte, 2+len(text)) - binary.BigEndian.PutUint16(buf, uint16(closeCode)) - copy(buf[2:], text) - return buf -} diff --git a/vendor/github.com/gorilla/websocket/conn_write.go b/vendor/github.com/gorilla/websocket/conn_write.go deleted file mode 100644 index a509a21f8..000000000 --- a/vendor/github.com/gorilla/websocket/conn_write.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package websocket - -import "net" - -func (c *Conn) writeBufs(bufs ...[]byte) error { - b := net.Buffers(bufs) - _, err := b.WriteTo(c.conn) - return err -} diff --git a/vendor/github.com/gorilla/websocket/conn_write_legacy.go b/vendor/github.com/gorilla/websocket/conn_write_legacy.go deleted file mode 100644 index 37edaff5a..000000000 --- a/vendor/github.com/gorilla/websocket/conn_write_legacy.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8 - -package websocket - -func (c *Conn) writeBufs(bufs ...[]byte) error { - for _, buf := range bufs { - if len(buf) > 0 { - if _, err := c.conn.Write(buf); err != nil { - return err - } - } - } - return nil -} diff --git a/vendor/github.com/gorilla/websocket/doc.go b/vendor/github.com/gorilla/websocket/doc.go deleted file mode 100644 index dcce1a63c..000000000 --- a/vendor/github.com/gorilla/websocket/doc.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package websocket implements the WebSocket protocol defined in RFC 6455. -// -// Overview -// -// The Conn type represents a WebSocket connection. A server application calls -// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn: -// -// var upgrader = websocket.Upgrader{ -// ReadBufferSize: 1024, -// WriteBufferSize: 1024, -// } -// -// func handler(w http.ResponseWriter, r *http.Request) { -// conn, err := upgrader.Upgrade(w, r, nil) -// if err != nil { -// log.Println(err) -// return -// } -// ... Use conn to send and receive messages. -// } -// -// Call the connection's WriteMessage and ReadMessage methods to send and -// receive messages as a slice of bytes. This snippet of code shows how to echo -// messages using these methods: -// -// for { -// messageType, p, err := conn.ReadMessage() -// if err != nil { -// log.Println(err) -// return -// } -// if err := conn.WriteMessage(messageType, p); err != nil { -// log.Println(err) -// return -// } -// } -// -// In above snippet of code, p is a []byte and messageType is an int with value -// websocket.BinaryMessage or websocket.TextMessage. -// -// An application can also send and receive messages using the io.WriteCloser -// and io.Reader interfaces. To send a message, call the connection NextWriter -// method to get an io.WriteCloser, write the message to the writer and close -// the writer when done. To receive a message, call the connection NextReader -// method to get an io.Reader and read until io.EOF is returned. This snippet -// shows how to echo messages using the NextWriter and NextReader methods: -// -// for { -// messageType, r, err := conn.NextReader() -// if err != nil { -// return -// } -// w, err := conn.NextWriter(messageType) -// if err != nil { -// return err -// } -// if _, err := io.Copy(w, r); err != nil { -// return err -// } -// if err := w.Close(); err != nil { -// return err -// } -// } -// -// Data Messages -// -// The WebSocket protocol distinguishes between text and binary data messages. -// Text messages are interpreted as UTF-8 encoded text. The interpretation of -// binary messages is left to the application. -// -// This package uses the TextMessage and BinaryMessage integer constants to -// identify the two data message types. The ReadMessage and NextReader methods -// return the type of the received message. The messageType argument to the -// WriteMessage and NextWriter methods specifies the type of a sent message. -// -// It is the application's responsibility to ensure that text messages are -// valid UTF-8 encoded text. -// -// Control Messages -// -// The WebSocket protocol defines three types of control messages: close, ping -// and pong. Call the connection WriteControl, WriteMessage or NextWriter -// methods to send a control message to the peer. -// -// Connections handle received close messages by calling the handler function -// set with the SetCloseHandler method and by returning a *CloseError from the -// NextReader, ReadMessage or the message Read method. The default close -// handler sends a close message to the peer. -// -// Connections handle received ping messages by calling the handler function -// set with the SetPingHandler method. The default ping handler sends a pong -// message to the peer. -// -// Connections handle received pong messages by calling the handler function -// set with the SetPongHandler method. The default pong handler does nothing. -// If an application sends ping messages, then the application should set a -// pong handler to receive the corresponding pong. -// -// The control message handler functions are called from the NextReader, -// ReadMessage and message reader Read methods. The default close and ping -// handlers can block these methods for a short time when the handler writes to -// the connection. -// -// The application must read the connection to process close, ping and pong -// messages sent from the peer. If the application is not otherwise interested -// in messages from the peer, then the application should start a goroutine to -// read and discard messages from the peer. A simple example is: -// -// func readLoop(c *websocket.Conn) { -// for { -// if _, _, err := c.NextReader(); err != nil { -// c.Close() -// break -// } -// } -// } -// -// Concurrency -// -// Connections support one concurrent reader and one concurrent writer. -// -// Applications are responsible for ensuring that no more than one goroutine -// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, -// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and -// that no more than one goroutine calls the read methods (NextReader, -// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) -// concurrently. -// -// The Close and WriteControl methods can be called concurrently with all other -// methods. -// -// Origin Considerations -// -// Web browsers allow Javascript applications to open a WebSocket connection to -// any host. It's up to the server to enforce an origin policy using the Origin -// request header sent by the browser. -// -// The Upgrader calls the function specified in the CheckOrigin field to check -// the origin. If the CheckOrigin function returns false, then the Upgrade -// method fails the WebSocket handshake with HTTP status 403. -// -// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail -// the handshake if the Origin request header is present and the Origin host is -// not equal to the Host request header. -// -// The deprecated package-level Upgrade function does not perform origin -// checking. The application is responsible for checking the Origin header -// before calling the Upgrade function. -// -// Compression EXPERIMENTAL -// -// Per message compression extensions (RFC 7692) are experimentally supported -// by this package in a limited capacity. Setting the EnableCompression option -// to true in Dialer or Upgrader will attempt to negotiate per message deflate -// support. -// -// var upgrader = websocket.Upgrader{ -// EnableCompression: true, -// } -// -// If compression was successfully negotiated with the connection's peer, any -// message received in compressed form will be automatically decompressed. -// All Read methods will return uncompressed bytes. -// -// Per message compression of messages written to a connection can be enabled -// or disabled by calling the corresponding Conn method: -// -// conn.EnableWriteCompression(false) -// -// Currently this package does not support compression with "context takeover". -// This means that messages must be compressed and decompressed in isolation, -// without retaining sliding window or dictionary state across messages. For -// more details refer to RFC 7692. -// -// Use of compression is experimental and may result in decreased performance. -package websocket diff --git a/vendor/github.com/gorilla/websocket/json.go b/vendor/github.com/gorilla/websocket/json.go deleted file mode 100644 index dc2c1f641..000000000 --- a/vendor/github.com/gorilla/websocket/json.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "encoding/json" - "io" -) - -// WriteJSON writes the JSON encoding of v as a message. -// -// Deprecated: Use c.WriteJSON instead. -func WriteJSON(c *Conn, v interface{}) error { - return c.WriteJSON(v) -} - -// WriteJSON writes the JSON encoding of v as a message. -// -// See the documentation for encoding/json Marshal for details about the -// conversion of Go values to JSON. -func (c *Conn) WriteJSON(v interface{}) error { - w, err := c.NextWriter(TextMessage) - if err != nil { - return err - } - err1 := json.NewEncoder(w).Encode(v) - err2 := w.Close() - if err1 != nil { - return err1 - } - return err2 -} - -// ReadJSON reads the next JSON-encoded message from the connection and stores -// it in the value pointed to by v. -// -// Deprecated: Use c.ReadJSON instead. -func ReadJSON(c *Conn, v interface{}) error { - return c.ReadJSON(v) -} - -// ReadJSON reads the next JSON-encoded message from the connection and stores -// it in the value pointed to by v. -// -// See the documentation for the encoding/json Unmarshal function for details -// about the conversion of JSON to a Go value. -func (c *Conn) ReadJSON(v interface{}) error { - _, r, err := c.NextReader() - if err != nil { - return err - } - err = json.NewDecoder(r).Decode(v) - if err == io.EOF { - // One value is expected in the message. - err = io.ErrUnexpectedEOF - } - return err -} diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go deleted file mode 100644 index 577fce9ef..000000000 --- a/vendor/github.com/gorilla/websocket/mask.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of -// this source code is governed by a BSD-style license that can be found in the -// LICENSE file. - -// +build !appengine - -package websocket - -import "unsafe" - -const wordSize = int(unsafe.Sizeof(uintptr(0))) - -func maskBytes(key [4]byte, pos int, b []byte) int { - // Mask one byte at a time for small buffers. - if len(b) < 2*wordSize { - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - return pos & 3 - } - - // Mask one byte at a time to word boundary. - if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { - n = wordSize - n - for i := range b[:n] { - b[i] ^= key[pos&3] - pos++ - } - b = b[n:] - } - - // Create aligned word size key. - var k [wordSize]byte - for i := range k { - k[i] = key[(pos+i)&3] - } - kw := *(*uintptr)(unsafe.Pointer(&k)) - - // Mask one word at a time. - n := (len(b) / wordSize) * wordSize - for i := 0; i < n; i += wordSize { - *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw - } - - // Mask one byte at a time for remaining bytes. - b = b[n:] - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - - return pos & 3 -} diff --git a/vendor/github.com/gorilla/websocket/mask_safe.go b/vendor/github.com/gorilla/websocket/mask_safe.go deleted file mode 100644 index 2aac060e5..000000000 --- a/vendor/github.com/gorilla/websocket/mask_safe.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of -// this source code is governed by a BSD-style license that can be found in the -// LICENSE file. - -// +build appengine - -package websocket - -func maskBytes(key [4]byte, pos int, b []byte) int { - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - return pos & 3 -} diff --git a/vendor/github.com/gorilla/websocket/prepared.go b/vendor/github.com/gorilla/websocket/prepared.go deleted file mode 100644 index 74ec565d2..000000000 --- a/vendor/github.com/gorilla/websocket/prepared.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bytes" - "net" - "sync" - "time" -) - -// PreparedMessage caches on the wire representations of a message payload. -// Use PreparedMessage to efficiently send a message payload to multiple -// connections. PreparedMessage is especially useful when compression is used -// because the CPU and memory expensive compression operation can be executed -// once for a given set of compression options. -type PreparedMessage struct { - messageType int - data []byte - mu sync.Mutex - frames map[prepareKey]*preparedFrame -} - -// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. -type prepareKey struct { - isServer bool - compress bool - compressionLevel int -} - -// preparedFrame contains data in wire representation. -type preparedFrame struct { - once sync.Once - data []byte -} - -// NewPreparedMessage returns an initialized PreparedMessage. You can then send -// it to connection using WritePreparedMessage method. Valid wire -// representation will be calculated lazily only once for a set of current -// connection options. -func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { - pm := &PreparedMessage{ - messageType: messageType, - frames: make(map[prepareKey]*preparedFrame), - data: data, - } - - // Prepare a plain server frame. - _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) - if err != nil { - return nil, err - } - - // To protect against caller modifying the data argument, remember the data - // copied to the plain server frame. - pm.data = frameData[len(frameData)-len(data):] - return pm, nil -} - -func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { - pm.mu.Lock() - frame, ok := pm.frames[key] - if !ok { - frame = &preparedFrame{} - pm.frames[key] = frame - } - pm.mu.Unlock() - - var err error - frame.once.Do(func() { - // Prepare a frame using a 'fake' connection. - // TODO: Refactor code in conn.go to allow more direct construction of - // the frame. - mu := make(chan bool, 1) - mu <- true - var nc prepareConn - c := &Conn{ - conn: &nc, - mu: mu, - isServer: key.isServer, - compressionLevel: key.compressionLevel, - enableWriteCompression: true, - writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), - } - if key.compress { - c.newCompressionWriter = compressNoContextTakeover - } - err = c.WriteMessage(pm.messageType, pm.data) - frame.data = nc.buf.Bytes() - }) - return pm.messageType, frame.data, err -} - -type prepareConn struct { - buf bytes.Buffer - net.Conn -} - -func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } -func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/vendor/github.com/gorilla/websocket/proxy.go b/vendor/github.com/gorilla/websocket/proxy.go deleted file mode 100644 index bf2478e43..000000000 --- a/vendor/github.com/gorilla/websocket/proxy.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "encoding/base64" - "errors" - "net" - "net/http" - "net/url" - "strings" -) - -type netDialerFunc func(network, addr string) (net.Conn, error) - -func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { - return fn(network, addr) -} - -func init() { - proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { - return &httpProxyDialer{proxyURL: proxyURL, fowardDial: forwardDialer.Dial}, nil - }) -} - -type httpProxyDialer struct { - proxyURL *url.URL - fowardDial func(network, addr string) (net.Conn, error) -} - -func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { - hostPort, _ := hostPortNoPort(hpd.proxyURL) - conn, err := hpd.fowardDial(network, hostPort) - if err != nil { - return nil, err - } - - connectHeader := make(http.Header) - if user := hpd.proxyURL.User; user != nil { - proxyUser := user.Username() - if proxyPassword, passwordSet := user.Password(); passwordSet { - credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) - connectHeader.Set("Proxy-Authorization", "Basic "+credential) - } - } - - connectReq := &http.Request{ - Method: "CONNECT", - URL: &url.URL{Opaque: addr}, - Host: addr, - Header: connectHeader, - } - - if err := connectReq.Write(conn); err != nil { - conn.Close() - return nil, err - } - - // Read response. It's OK to use and discard buffered reader here becaue - // the remote server does not speak until spoken to. - br := bufio.NewReader(conn) - resp, err := http.ReadResponse(br, connectReq) - if err != nil { - conn.Close() - return nil, err - } - - if resp.StatusCode != 200 { - conn.Close() - f := strings.SplitN(resp.Status, " ", 2) - return nil, errors.New(f[1]) - } - return conn, nil -} diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go deleted file mode 100644 index a761824b3..000000000 --- a/vendor/github.com/gorilla/websocket/server.go +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "errors" - "io" - "net/http" - "net/url" - "strings" - "time" -) - -// HandshakeError describes an error with the handshake from the peer. -type HandshakeError struct { - message string -} - -func (e HandshakeError) Error() string { return e.message } - -// Upgrader specifies parameters for upgrading an HTTP connection to a -// WebSocket connection. -type Upgrader struct { - // HandshakeTimeout specifies the duration for the handshake to complete. - HandshakeTimeout time.Duration - - // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer - // size is zero, then buffers allocated by the HTTP server are used. The - // I/O buffer sizes do not limit the size of the messages that can be sent - // or received. - ReadBufferSize, WriteBufferSize int - - // WriteBufferPool is a pool of buffers for write operations. If the value - // is not set, then write buffers are allocated to the connection for the - // lifetime of the connection. - // - // A pool is most useful when the application has a modest volume of writes - // across a large number of connections. - // - // Applications should use a single pool for each unique value of - // WriteBufferSize. - WriteBufferPool BufferPool - - // Subprotocols specifies the server's supported protocols in order of - // preference. If this field is not nil, then the Upgrade method negotiates a - // subprotocol by selecting the first match in this list with a protocol - // requested by the client. If there's no match, then no protocol is - // negotiated (the Sec-Websocket-Protocol header is not included in the - // handshake response). - Subprotocols []string - - // Error specifies the function for generating HTTP error responses. If Error - // is nil, then http.Error is used to generate the HTTP response. - Error func(w http.ResponseWriter, r *http.Request, status int, reason error) - - // CheckOrigin returns true if the request Origin header is acceptable. If - // CheckOrigin is nil, then a safe default is used: return false if the - // Origin request header is present and the origin host is not equal to - // request Host header. - // - // A CheckOrigin function should carefully validate the request origin to - // prevent cross-site request forgery. - CheckOrigin func(r *http.Request) bool - - // EnableCompression specify if the server should attempt to negotiate per - // message compression (RFC 7692). Setting this value to true does not - // guarantee that compression will be supported. Currently only "no context - // takeover" modes are supported. - EnableCompression bool -} - -func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { - err := HandshakeError{reason} - if u.Error != nil { - u.Error(w, r, status, err) - } else { - w.Header().Set("Sec-Websocket-Version", "13") - http.Error(w, http.StatusText(status), status) - } - return nil, err -} - -// checkSameOrigin returns true if the origin is not set or is equal to the request host. -func checkSameOrigin(r *http.Request) bool { - origin := r.Header["Origin"] - if len(origin) == 0 { - return true - } - u, err := url.Parse(origin[0]) - if err != nil { - return false - } - return equalASCIIFold(u.Host, r.Host) -} - -func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { - if u.Subprotocols != nil { - clientProtocols := Subprotocols(r) - for _, serverProtocol := range u.Subprotocols { - for _, clientProtocol := range clientProtocols { - if clientProtocol == serverProtocol { - return clientProtocol - } - } - } - } else if responseHeader != nil { - return responseHeader.Get("Sec-Websocket-Protocol") - } - return "" -} - -// Upgrade upgrades the HTTP server connection to the WebSocket protocol. -// -// The responseHeader is included in the response to the client's upgrade -// request. Use the responseHeader to specify cookies (Set-Cookie) and the -// application negotiated subprotocol (Sec-WebSocket-Protocol). -// -// If the upgrade fails, then Upgrade replies to the client with an HTTP error -// response. -func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { - const badHandshake = "websocket: the client is not using the websocket protocol: " - - if !tokenListContainsValue(r.Header, "Connection", "upgrade") { - return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header") - } - - if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { - return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header") - } - - if r.Method != "GET" { - return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET") - } - - if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { - return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") - } - - if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { - return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported") - } - - checkOrigin := u.CheckOrigin - if checkOrigin == nil { - checkOrigin = checkSameOrigin - } - if !checkOrigin(r) { - return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin") - } - - challengeKey := r.Header.Get("Sec-Websocket-Key") - if challengeKey == "" { - return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-WebSocket-Key' header is missing or blank") - } - - subprotocol := u.selectSubprotocol(r, responseHeader) - - // Negotiate PMCE - var compress bool - if u.EnableCompression { - for _, ext := range parseExtensions(r.Header) { - if ext[""] != "permessage-deflate" { - continue - } - compress = true - break - } - } - - h, ok := w.(http.Hijacker) - if !ok { - return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") - } - var brw *bufio.ReadWriter - netConn, brw, err := h.Hijack() - if err != nil { - return u.returnError(w, r, http.StatusInternalServerError, err.Error()) - } - - if brw.Reader.Buffered() > 0 { - netConn.Close() - return nil, errors.New("websocket: client sent data before handshake is complete") - } - - var br *bufio.Reader - if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 { - // Reuse hijacked buffered reader as connection reader. - br = brw.Reader - } - - buf := bufioWriterBuffer(netConn, brw.Writer) - - var writeBuf []byte - if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 { - // Reuse hijacked write buffer as connection buffer. - writeBuf = buf - } - - c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf) - c.subprotocol = subprotocol - - if compress { - c.newCompressionWriter = compressNoContextTakeover - c.newDecompressionReader = decompressNoContextTakeover - } - - // Use larger of hijacked buffer and connection write buffer for header. - p := buf - if len(c.writeBuf) > len(p) { - p = c.writeBuf - } - p = p[:0] - - p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) - p = append(p, computeAcceptKey(challengeKey)...) - p = append(p, "\r\n"...) - if c.subprotocol != "" { - p = append(p, "Sec-WebSocket-Protocol: "...) - p = append(p, c.subprotocol...) - p = append(p, "\r\n"...) - } - if compress { - p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) - } - for k, vs := range responseHeader { - if k == "Sec-Websocket-Protocol" { - continue - } - for _, v := range vs { - p = append(p, k...) - p = append(p, ": "...) - for i := 0; i < len(v); i++ { - b := v[i] - if b <= 31 { - // prevent response splitting. - b = ' ' - } - p = append(p, b) - } - p = append(p, "\r\n"...) - } - } - p = append(p, "\r\n"...) - - // Clear deadlines set by HTTP server. - netConn.SetDeadline(time.Time{}) - - if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) - } - if _, err = netConn.Write(p); err != nil { - netConn.Close() - return nil, err - } - if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Time{}) - } - - return c, nil -} - -// Upgrade upgrades the HTTP server connection to the WebSocket protocol. -// -// Deprecated: Use websocket.Upgrader instead. -// -// Upgrade does not perform origin checking. The application is responsible for -// checking the Origin header before calling Upgrade. An example implementation -// of the same origin policy check is: -// -// if req.Header.Get("Origin") != "http://"+req.Host { -// http.Error(w, "Origin not allowed", http.StatusForbidden) -// return -// } -// -// If the endpoint supports subprotocols, then the application is responsible -// for negotiating the protocol used on the connection. Use the Subprotocols() -// function to get the subprotocols requested by the client. Use the -// Sec-Websocket-Protocol response header to specify the subprotocol selected -// by the application. -// -// The responseHeader is included in the response to the client's upgrade -// request. Use the responseHeader to specify cookies (Set-Cookie) and the -// negotiated subprotocol (Sec-Websocket-Protocol). -// -// The connection buffers IO to the underlying network connection. The -// readBufSize and writeBufSize parameters specify the size of the buffers to -// use. Messages can be larger than the buffers. -// -// If the request is not a valid WebSocket handshake, then Upgrade returns an -// error of type HandshakeError. Applications should handle this error by -// replying to the client with an HTTP error response. -func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { - u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} - u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { - // don't return errors to maintain backwards compatibility - } - u.CheckOrigin = func(r *http.Request) bool { - // allow all connections by default - return true - } - return u.Upgrade(w, r, responseHeader) -} - -// Subprotocols returns the subprotocols requested by the client in the -// Sec-Websocket-Protocol header. -func Subprotocols(r *http.Request) []string { - h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) - if h == "" { - return nil - } - protocols := strings.Split(h, ",") - for i := range protocols { - protocols[i] = strings.TrimSpace(protocols[i]) - } - return protocols -} - -// IsWebSocketUpgrade returns true if the client requested upgrade to the -// WebSocket protocol. -func IsWebSocketUpgrade(r *http.Request) bool { - return tokenListContainsValue(r.Header, "Connection", "upgrade") && - tokenListContainsValue(r.Header, "Upgrade", "websocket") -} - -// bufioReaderSize size returns the size of a bufio.Reader. -func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int { - // This code assumes that peek on a reset reader returns - // bufio.Reader.buf[:0]. - // TODO: Use bufio.Reader.Size() after Go 1.10 - br.Reset(originalReader) - if p, err := br.Peek(0); err == nil { - return cap(p) - } - return 0 -} - -// writeHook is an io.Writer that records the last slice passed to it vio -// io.Writer.Write. -type writeHook struct { - p []byte -} - -func (wh *writeHook) Write(p []byte) (int, error) { - wh.p = p - return len(p), nil -} - -// bufioWriterBuffer grabs the buffer from a bufio.Writer. -func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte { - // This code assumes that bufio.Writer.buf[:1] is passed to the - // bufio.Writer's underlying writer. - var wh writeHook - bw.Reset(&wh) - bw.WriteByte(0) - bw.Flush() - - bw.Reset(originalWriter) - - return wh.p[:cap(wh.p)] -} diff --git a/vendor/github.com/gorilla/websocket/trace.go b/vendor/github.com/gorilla/websocket/trace.go deleted file mode 100644 index 834f122a0..000000000 --- a/vendor/github.com/gorilla/websocket/trace.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build go1.8 - -package websocket - -import ( - "crypto/tls" - "net/http/httptrace" -) - -func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { - if trace.TLSHandshakeStart != nil { - trace.TLSHandshakeStart() - } - err := doHandshake(tlsConn, cfg) - if trace.TLSHandshakeDone != nil { - trace.TLSHandshakeDone(tlsConn.ConnectionState(), err) - } - return err -} diff --git a/vendor/github.com/gorilla/websocket/trace_17.go b/vendor/github.com/gorilla/websocket/trace_17.go deleted file mode 100644 index 77d05a0b5..000000000 --- a/vendor/github.com/gorilla/websocket/trace_17.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !go1.8 - -package websocket - -import ( - "crypto/tls" - "net/http/httptrace" -) - -func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error { - return doHandshake(tlsConn, cfg) -} diff --git a/vendor/github.com/gorilla/websocket/util.go b/vendor/github.com/gorilla/websocket/util.go deleted file mode 100644 index 354001e1e..000000000 --- a/vendor/github.com/gorilla/websocket/util.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "crypto/rand" - "crypto/sha1" - "encoding/base64" - "io" - "net/http" - "strings" - "unicode/utf8" -) - -var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - -func computeAcceptKey(challengeKey string) string { - h := sha1.New() - h.Write([]byte(challengeKey)) - h.Write(keyGUID) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} - -func generateChallengeKey() (string, error) { - p := make([]byte, 16) - if _, err := io.ReadFull(rand.Reader, p); err != nil { - return "", err - } - return base64.StdEncoding.EncodeToString(p), nil -} - -// Octet types from RFC 2616. -var octetTypes [256]byte - -const ( - isTokenOctet = 1 << iota - isSpaceOctet -) - -func init() { - // From RFC 2616 - // - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t byte - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 - if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { - t |= isSpaceOctet - } - if isChar && !isCtl && !isSeparator { - t |= isTokenOctet - } - octetTypes[c] = t - } -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpaceOctet == 0 { - break - } - } - return s[i:] -} - -func nextToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isTokenOctet == 0 { - break - } - } - return s[:i], s[i:] -} - -func nextTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return nextToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j++ - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j++ - } - } - return "", "" - } - } - return "", "" -} - -// equalASCIIFold returns true if s is equal to t with ASCII case folding. -func equalASCIIFold(s, t string) bool { - for s != "" && t != "" { - sr, size := utf8.DecodeRuneInString(s) - s = s[size:] - tr, size := utf8.DecodeRuneInString(t) - t = t[size:] - if sr == tr { - continue - } - if 'A' <= sr && sr <= 'Z' { - sr = sr + 'a' - 'A' - } - if 'A' <= tr && tr <= 'Z' { - tr = tr + 'a' - 'A' - } - if sr != tr { - return false - } - } - return s == t -} - -// tokenListContainsValue returns true if the 1#token header with the given -// name contains a token equal to value with ASCII case folding. -func tokenListContainsValue(header http.Header, name string, value string) bool { -headers: - for _, s := range header[name] { - for { - var t string - t, s = nextToken(skipSpace(s)) - if t == "" { - continue headers - } - s = skipSpace(s) - if s != "" && s[0] != ',' { - continue headers - } - if equalASCIIFold(t, value) { - return true - } - if s == "" { - continue headers - } - s = s[1:] - } - } - return false -} - -// parseExtensions parses WebSocket extensions from a header. -func parseExtensions(header http.Header) []map[string]string { - // From RFC 6455: - // - // Sec-WebSocket-Extensions = extension-list - // extension-list = 1#extension - // extension = extension-token *( ";" extension-param ) - // extension-token = registered-token - // registered-token = token - // extension-param = token [ "=" (token | quoted-string) ] - // ;When using the quoted-string syntax variant, the value - // ;after quoted-string unescaping MUST conform to the - // ;'token' ABNF. - - var result []map[string]string -headers: - for _, s := range header["Sec-Websocket-Extensions"] { - for { - var t string - t, s = nextToken(skipSpace(s)) - if t == "" { - continue headers - } - ext := map[string]string{"": t} - for { - s = skipSpace(s) - if !strings.HasPrefix(s, ";") { - break - } - var k string - k, s = nextToken(skipSpace(s[1:])) - if k == "" { - continue headers - } - s = skipSpace(s) - var v string - if strings.HasPrefix(s, "=") { - v, s = nextTokenOrQuoted(skipSpace(s[1:])) - s = skipSpace(s) - } - if s != "" && s[0] != ',' && s[0] != ';' { - continue headers - } - ext[k] = v - } - if s != "" && s[0] != ',' { - continue headers - } - result = append(result, ext) - if s == "" { - continue headers - } - s = s[1:] - } - } - return result -} diff --git a/vendor/github.com/gorilla/websocket/x_net_proxy.go b/vendor/github.com/gorilla/websocket/x_net_proxy.go deleted file mode 100644 index 2e668f6b8..000000000 --- a/vendor/github.com/gorilla/websocket/x_net_proxy.go +++ /dev/null @@ -1,473 +0,0 @@ -// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. -//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy - -// Package proxy provides support for a variety of protocols to proxy network -// data. -// - -package websocket - -import ( - "errors" - "io" - "net" - "net/url" - "os" - "strconv" - "strings" - "sync" -) - -type proxy_direct struct{} - -// Direct is a direct proxy: one that makes network connections directly. -var proxy_Direct = proxy_direct{} - -func (proxy_direct) Dial(network, addr string) (net.Conn, error) { - return net.Dial(network, addr) -} - -// A PerHost directs connections to a default Dialer unless the host name -// requested matches one of a number of exceptions. -type proxy_PerHost struct { - def, bypass proxy_Dialer - - bypassNetworks []*net.IPNet - bypassIPs []net.IP - bypassZones []string - bypassHosts []string -} - -// NewPerHost returns a PerHost Dialer that directs connections to either -// defaultDialer or bypass, depending on whether the connection matches one of -// the configured rules. -func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost { - return &proxy_PerHost{ - def: defaultDialer, - bypass: bypass, - } -} - -// Dial connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - - return p.dialerForRequest(host).Dial(network, addr) -} - -func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer { - if ip := net.ParseIP(host); ip != nil { - for _, net := range p.bypassNetworks { - if net.Contains(ip) { - return p.bypass - } - } - for _, bypassIP := range p.bypassIPs { - if bypassIP.Equal(ip) { - return p.bypass - } - } - return p.def - } - - for _, zone := range p.bypassZones { - if strings.HasSuffix(host, zone) { - return p.bypass - } - if host == zone[1:] { - // For a zone ".example.com", we match "example.com" - // too. - return p.bypass - } - } - for _, bypassHost := range p.bypassHosts { - if bypassHost == host { - return p.bypass - } - } - return p.def -} - -// AddFromString parses a string that contains comma-separated values -// specifying hosts that should use the bypass proxy. Each value is either an -// IP address, a CIDR range, a zone (*.example.com) or a host name -// (localhost). A best effort is made to parse the string and errors are -// ignored. -func (p *proxy_PerHost) AddFromString(s string) { - hosts := strings.Split(s, ",") - for _, host := range hosts { - host = strings.TrimSpace(host) - if len(host) == 0 { - continue - } - if strings.Contains(host, "/") { - // We assume that it's a CIDR address like 127.0.0.0/8 - if _, net, err := net.ParseCIDR(host); err == nil { - p.AddNetwork(net) - } - continue - } - if ip := net.ParseIP(host); ip != nil { - p.AddIP(ip) - continue - } - if strings.HasPrefix(host, "*.") { - p.AddZone(host[1:]) - continue - } - p.AddHost(host) - } -} - -// AddIP specifies an IP address that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match an IP. -func (p *proxy_PerHost) AddIP(ip net.IP) { - p.bypassIPs = append(p.bypassIPs, ip) -} - -// AddNetwork specifies an IP range that will use the bypass proxy. Note that -// this will only take effect if a literal IP address is dialed. A connection -// to a named host will never match. -func (p *proxy_PerHost) AddNetwork(net *net.IPNet) { - p.bypassNetworks = append(p.bypassNetworks, net) -} - -// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of -// "example.com" matches "example.com" and all of its subdomains. -func (p *proxy_PerHost) AddZone(zone string) { - if strings.HasSuffix(zone, ".") { - zone = zone[:len(zone)-1] - } - if !strings.HasPrefix(zone, ".") { - zone = "." + zone - } - p.bypassZones = append(p.bypassZones, zone) -} - -// AddHost specifies a host name that will use the bypass proxy. -func (p *proxy_PerHost) AddHost(host string) { - if strings.HasSuffix(host, ".") { - host = host[:len(host)-1] - } - p.bypassHosts = append(p.bypassHosts, host) -} - -// A Dialer is a means to establish a connection. -type proxy_Dialer interface { - // Dial connects to the given address via the proxy. - Dial(network, addr string) (c net.Conn, err error) -} - -// Auth contains authentication parameters that specific Dialers may require. -type proxy_Auth struct { - User, Password string -} - -// FromEnvironment returns the dialer specified by the proxy related variables in -// the environment. -func proxy_FromEnvironment() proxy_Dialer { - allProxy := proxy_allProxyEnv.Get() - if len(allProxy) == 0 { - return proxy_Direct - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return proxy_Direct - } - proxy, err := proxy_FromURL(proxyURL, proxy_Direct) - if err != nil { - return proxy_Direct - } - - noProxy := proxy_noProxyEnv.Get() - if len(noProxy) == 0 { - return proxy - } - - perHost := proxy_NewPerHost(proxy, proxy_Direct) - perHost.AddFromString(noProxy) - return perHost -} - -// proxySchemes is a map from URL schemes to a function that creates a Dialer -// from a URL with such a scheme. -var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error) - -// RegisterDialerType takes a URL scheme and a function to generate Dialers from -// a URL with that scheme and a forwarding Dialer. Registered schemes are used -// by FromURL. -func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) { - if proxy_proxySchemes == nil { - proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) - } - proxy_proxySchemes[scheme] = f -} - -// FromURL returns a Dialer given a URL specification and an underlying -// Dialer for it to make network requests. -func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) { - var auth *proxy_Auth - if u.User != nil { - auth = new(proxy_Auth) - auth.User = u.User.Username() - if p, ok := u.User.Password(); ok { - auth.Password = p - } - } - - switch u.Scheme { - case "socks5": - return proxy_SOCKS5("tcp", u.Host, auth, forward) - } - - // If the scheme doesn't match any of the built-in schemes, see if it - // was registered by another package. - if proxy_proxySchemes != nil { - if f, ok := proxy_proxySchemes[u.Scheme]; ok { - return f(u, forward) - } - } - - return nil, errors.New("proxy: unknown scheme: " + u.Scheme) -} - -var ( - proxy_allProxyEnv = &proxy_envOnce{ - names: []string{"ALL_PROXY", "all_proxy"}, - } - proxy_noProxyEnv = &proxy_envOnce{ - names: []string{"NO_PROXY", "no_proxy"}, - } -) - -// envOnce looks up an environment variable (optionally by multiple -// names) once. It mitigates expensive lookups on some platforms -// (e.g. Windows). -// (Borrowed from net/http/transport.go) -type proxy_envOnce struct { - names []string - once sync.Once - val string -} - -func (e *proxy_envOnce) Get() string { - e.once.Do(e.init) - return e.val -} - -func (e *proxy_envOnce) init() { - for _, n := range e.names { - e.val = os.Getenv(n) - if e.val != "" { - return - } - } -} - -// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address -// with an optional username and password. See RFC 1928 and RFC 1929. -func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) { - s := &proxy_socks5{ - network: network, - addr: addr, - forward: forward, - } - if auth != nil { - s.user = auth.User - s.password = auth.Password - } - - return s, nil -} - -type proxy_socks5 struct { - user, password string - network, addr string - forward proxy_Dialer -} - -const proxy_socks5Version = 5 - -const ( - proxy_socks5AuthNone = 0 - proxy_socks5AuthPassword = 2 -) - -const proxy_socks5Connect = 1 - -const ( - proxy_socks5IP4 = 1 - proxy_socks5Domain = 3 - proxy_socks5IP6 = 4 -) - -var proxy_socks5Errors = []string{ - "", - "general failure", - "connection forbidden", - "network unreachable", - "host unreachable", - "connection refused", - "TTL expired", - "command not supported", - "address type not supported", -} - -// Dial connects to the address addr on the given network via the SOCKS5 proxy. -func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) - } - - conn, err := s.forward.Dial(s.network, s.addr) - if err != nil { - return nil, err - } - if err := s.connect(conn, addr); err != nil { - conn.Close() - return nil, err - } - return conn, nil -} - -// connect takes an existing connection to a socks5 proxy server, -// and commands the server to extend that connection to target, -// which must be a canonical address with a host and port. -func (s *proxy_socks5) connect(conn net.Conn, target string) error { - host, portStr, err := net.SplitHostPort(target) - if err != nil { - return err - } - - port, err := strconv.Atoi(portStr) - if err != nil { - return errors.New("proxy: failed to parse port number: " + portStr) - } - if port < 1 || port > 0xffff { - return errors.New("proxy: port number out of range: " + portStr) - } - - // the size here is just an estimate - buf := make([]byte, 0, 6+len(host)) - - buf = append(buf, proxy_socks5Version) - if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { - buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword) - } else { - buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone) - } - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - if buf[0] != 5 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) - } - if buf[1] == 0xff { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") - } - - // See RFC 1929 - if buf[1] == proxy_socks5AuthPassword { - buf = buf[:0] - buf = append(buf, 1 /* password protocol version */) - buf = append(buf, uint8(len(s.user))) - buf = append(buf, s.user...) - buf = append(buf, uint8(len(s.password))) - buf = append(buf, s.password...) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if buf[1] != 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") - } - } - - buf = buf[:0] - buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */) - - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - buf = append(buf, proxy_socks5IP4) - ip = ip4 - } else { - buf = append(buf, proxy_socks5IP6) - } - buf = append(buf, ip...) - } else { - if len(host) > 255 { - return errors.New("proxy: destination host name too long: " + host) - } - buf = append(buf, proxy_socks5Domain) - buf = append(buf, byte(len(host))) - buf = append(buf, host...) - } - buf = append(buf, byte(port>>8), byte(port)) - - if _, err := conn.Write(buf); err != nil { - return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - if _, err := io.ReadFull(conn, buf[:4]); err != nil { - return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - failure := "unknown error" - if int(buf[1]) < len(proxy_socks5Errors) { - failure = proxy_socks5Errors[buf[1]] - } - - if len(failure) > 0 { - return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) - } - - bytesToDiscard := 0 - switch buf[3] { - case proxy_socks5IP4: - bytesToDiscard = net.IPv4len - case proxy_socks5IP6: - bytesToDiscard = net.IPv6len - case proxy_socks5Domain: - _, err := io.ReadFull(conn, buf[:1]) - if err != nil { - return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - bytesToDiscard = int(buf[0]) - default: - return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) - } - - if cap(buf) < bytesToDiscard { - buf = make([]byte, bytesToDiscard) - } else { - buf = buf[:bytesToDiscard] - } - if _, err := io.ReadFull(conn, buf); err != nil { - return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - // Also need to discard the port number - if _, err := io.ReadFull(conn, buf[:2]); err != nil { - return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) - } - - return nil -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/register.go b/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/register.go deleted file mode 100644 index 74ca0e42c..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/register.go +++ /dev/null @@ -1,6 +0,0 @@ -package uploadcontroller - -const ( - // GroupName to hold the string name for the cdi uploads - GroupName = "upload.cdi.kubevirt.io" -) diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/doc.go b/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/doc.go deleted file mode 100644 index 10779f6b7..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// +k8s:deepcopy-gen=package - -// Package v1alpha1 is the v1alpha1 version of the API. -// +groupName=upload.cdi.kubevirt.io -package v1alpha1 diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/register.go b/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/register.go deleted file mode 100644 index 6ff5c42b8..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/register.go +++ /dev/null @@ -1,39 +0,0 @@ -package v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - - "kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: uploadcontroller.GroupName, Version: "v1alpha1"} - -// Kind takes an unqualified kind and returns back a Group qualified GroupKind -func Kind(kind string) schema.GroupKind { - return SchemeGroupVersion.WithKind(kind).GroupKind() -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - // SchemeBuilder tbd - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - // AddToScheme tbd - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &UploadTokenRequest{}, - &UploadTokenRequestList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/types.go b/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/types.go deleted file mode 100644 index 0e2c16aa8..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/types.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2018 The CDI 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -// UploadTokenRequest is the CR used to initiate a CDI upload -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type UploadTokenRequest struct { - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - // Spec contains the parameters of the request - Spec UploadTokenRequestSpec `json:"spec"` - - // Status contains the status of the request - Status UploadTokenRequestStatus `json:"status"` -} - -// UploadTokenRequestSpec defines the parameters of the token request -type UploadTokenRequestSpec struct { - PvcName string `json:"pvcName"` -} - -// UploadTokenRequestStatus stores the status of a token request -type UploadTokenRequestStatus struct { - Token string `json:"token,omitempty"` -} - -// UploadTokenRequestList contains a list of UploadTokenRequests -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -type UploadTokenRequestList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata"` - - Items []UploadTokenRequest `json:"items"` -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/zz_generated.deepcopy.go b/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 766ed745d..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,118 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UploadTokenRequest) DeepCopyInto(out *UploadTokenRequest) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - out.Spec = in.Spec - out.Status = in.Status - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UploadTokenRequest. -func (in *UploadTokenRequest) DeepCopy() *UploadTokenRequest { - if in == nil { - return nil - } - out := new(UploadTokenRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *UploadTokenRequest) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UploadTokenRequestList) DeepCopyInto(out *UploadTokenRequestList) { - *out = *in - out.TypeMeta = in.TypeMeta - out.ListMeta = in.ListMeta - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]UploadTokenRequest, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UploadTokenRequestList. -func (in *UploadTokenRequestList) DeepCopy() *UploadTokenRequestList { - if in == nil { - return nil - } - out := new(UploadTokenRequestList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *UploadTokenRequestList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UploadTokenRequestSpec) DeepCopyInto(out *UploadTokenRequestSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UploadTokenRequestSpec. -func (in *UploadTokenRequestSpec) DeepCopy() *UploadTokenRequestSpec { - if in == nil { - return nil - } - out := new(UploadTokenRequestSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *UploadTokenRequestStatus) DeepCopyInto(out *UploadTokenRequestStatus) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UploadTokenRequestStatus. -func (in *UploadTokenRequestStatus) DeepCopy() *UploadTokenRequestStatus { - if in == nil { - return nil - } - out := new(UploadTokenRequestStatus) - in.DeepCopyInto(out) - return out -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/clientset.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/clientset.go deleted file mode 100644 index 89fc23187..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/clientset.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package versioned - -import ( - glog "github.com/golang/glog" - discovery "k8s.io/client-go/discovery" - rest "k8s.io/client-go/rest" - flowcontrol "k8s.io/client-go/util/flowcontrol" - cdiv1alpha1 "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1" - uploadv1alpha1 "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1" -) - -type Interface interface { - Discovery() discovery.DiscoveryInterface - CdiV1alpha1() cdiv1alpha1.CdiV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Cdi() cdiv1alpha1.CdiV1alpha1Interface - UploadV1alpha1() uploadv1alpha1.UploadV1alpha1Interface - // Deprecated: please explicitly pick a version if possible. - Upload() uploadv1alpha1.UploadV1alpha1Interface -} - -// Clientset contains the clients for groups. Each group has exactly one -// version included in a Clientset. -type Clientset struct { - *discovery.DiscoveryClient - cdiV1alpha1 *cdiv1alpha1.CdiV1alpha1Client - uploadV1alpha1 *uploadv1alpha1.UploadV1alpha1Client -} - -// CdiV1alpha1 retrieves the CdiV1alpha1Client -func (c *Clientset) CdiV1alpha1() cdiv1alpha1.CdiV1alpha1Interface { - return c.cdiV1alpha1 -} - -// Deprecated: Cdi retrieves the default version of CdiClient. -// Please explicitly pick a version. -func (c *Clientset) Cdi() cdiv1alpha1.CdiV1alpha1Interface { - return c.cdiV1alpha1 -} - -// UploadV1alpha1 retrieves the UploadV1alpha1Client -func (c *Clientset) UploadV1alpha1() uploadv1alpha1.UploadV1alpha1Interface { - return c.uploadV1alpha1 -} - -// Deprecated: Upload retrieves the default version of UploadClient. -// Please explicitly pick a version. -func (c *Clientset) Upload() uploadv1alpha1.UploadV1alpha1Interface { - return c.uploadV1alpha1 -} - -// Discovery retrieves the DiscoveryClient -func (c *Clientset) Discovery() discovery.DiscoveryInterface { - if c == nil { - return nil - } - return c.DiscoveryClient -} - -// NewForConfig creates a new Clientset for the given config. -func NewForConfig(c *rest.Config) (*Clientset, error) { - configShallowCopy := *c - if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 { - configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst) - } - var cs Clientset - var err error - cs.cdiV1alpha1, err = cdiv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - cs.uploadV1alpha1, err = uploadv1alpha1.NewForConfig(&configShallowCopy) - if err != nil { - return nil, err - } - - cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy) - if err != nil { - glog.Errorf("failed to create the DiscoveryClient: %v", err) - return nil, err - } - return &cs, nil -} - -// NewForConfigOrDie creates a new Clientset for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *Clientset { - var cs Clientset - cs.cdiV1alpha1 = cdiv1alpha1.NewForConfigOrDie(c) - cs.uploadV1alpha1 = uploadv1alpha1.NewForConfigOrDie(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c) - return &cs -} - -// New creates a new Clientset for the given RESTClient. -func New(c rest.Interface) *Clientset { - var cs Clientset - cs.cdiV1alpha1 = cdiv1alpha1.New(c) - cs.uploadV1alpha1 = uploadv1alpha1.New(c) - - cs.DiscoveryClient = discovery.NewDiscoveryClient(c) - return &cs -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/doc.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/doc.go deleted file mode 100644 index 53b927fa7..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated clientset. -package versioned diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/doc.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/doc.go deleted file mode 100644 index eec0cb9d2..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package contains the scheme of the automatically generated clientset. -package scheme diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/register.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/register.go deleted file mode 100644 index 2cfe41b1e..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme/register.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package scheme - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - schema "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - cdiv1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/datavolumecontroller/v1alpha1" - uploadv1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1" -) - -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) - -func init() { - v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) - AddToScheme(Scheme) -} - -// AddToScheme adds all types of this clientset into the given scheme. This allows composition -// of clientsets, like in: -// -// import ( -// "k8s.io/client-go/kubernetes" -// clientsetscheme "k8s.io/client-go/kubernetes/scheme" -// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" -// ) -// -// kclientset, _ := kubernetes.NewForConfig(c) -// aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) -// -// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types -// correctly. -func AddToScheme(scheme *runtime.Scheme) { - cdiv1alpha1.AddToScheme(scheme) - uploadv1alpha1.AddToScheme(scheme) -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolume.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolume.go deleted file mode 100644 index 7be7fb840..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolume.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" - v1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/datavolumecontroller/v1alpha1" - scheme "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme" -) - -// DataVolumesGetter has a method to return a DataVolumeInterface. -// A group's client should implement this interface. -type DataVolumesGetter interface { - DataVolumes(namespace string) DataVolumeInterface -} - -// DataVolumeInterface has methods to work with DataVolume resources. -type DataVolumeInterface interface { - Create(*v1alpha1.DataVolume) (*v1alpha1.DataVolume, error) - Update(*v1alpha1.DataVolume) (*v1alpha1.DataVolume, error) - UpdateStatus(*v1alpha1.DataVolume) (*v1alpha1.DataVolume, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.DataVolume, error) - List(opts v1.ListOptions) (*v1alpha1.DataVolumeList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.DataVolume, err error) - DataVolumeExpansion -} - -// dataVolumes implements DataVolumeInterface -type dataVolumes struct { - client rest.Interface - ns string -} - -// newDataVolumes returns a DataVolumes -func newDataVolumes(c *CdiV1alpha1Client, namespace string) *dataVolumes { - return &dataVolumes{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the dataVolume, and returns the corresponding dataVolume object, and an error if there is any. -func (c *dataVolumes) Get(name string, options v1.GetOptions) (result *v1alpha1.DataVolume, err error) { - result = &v1alpha1.DataVolume{} - err = c.client.Get(). - Namespace(c.ns). - Resource("datavolumes"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of DataVolumes that match those selectors. -func (c *dataVolumes) List(opts v1.ListOptions) (result *v1alpha1.DataVolumeList, err error) { - result = &v1alpha1.DataVolumeList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("datavolumes"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested dataVolumes. -func (c *dataVolumes) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("datavolumes"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a dataVolume and creates it. Returns the server's representation of the dataVolume, and an error, if there is any. -func (c *dataVolumes) Create(dataVolume *v1alpha1.DataVolume) (result *v1alpha1.DataVolume, err error) { - result = &v1alpha1.DataVolume{} - err = c.client.Post(). - Namespace(c.ns). - Resource("datavolumes"). - Body(dataVolume). - Do(). - Into(result) - return -} - -// Update takes the representation of a dataVolume and updates it. Returns the server's representation of the dataVolume, and an error, if there is any. -func (c *dataVolumes) Update(dataVolume *v1alpha1.DataVolume) (result *v1alpha1.DataVolume, err error) { - result = &v1alpha1.DataVolume{} - err = c.client.Put(). - Namespace(c.ns). - Resource("datavolumes"). - Name(dataVolume.Name). - Body(dataVolume). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *dataVolumes) UpdateStatus(dataVolume *v1alpha1.DataVolume) (result *v1alpha1.DataVolume, err error) { - result = &v1alpha1.DataVolume{} - err = c.client.Put(). - Namespace(c.ns). - Resource("datavolumes"). - Name(dataVolume.Name). - SubResource("status"). - Body(dataVolume). - Do(). - Into(result) - return -} - -// Delete takes name of the dataVolume and deletes it. Returns an error if one occurs. -func (c *dataVolumes) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("datavolumes"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *dataVolumes) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("datavolumes"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched dataVolume. -func (c *dataVolumes) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.DataVolume, err error) { - result = &v1alpha1.DataVolume{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("datavolumes"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolumecontroller_client.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolumecontroller_client.go deleted file mode 100644 index 9d4f754f3..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/datavolumecontroller_client.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - rest "k8s.io/client-go/rest" - v1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/datavolumecontroller/v1alpha1" - "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme" -) - -type CdiV1alpha1Interface interface { - RESTClient() rest.Interface - DataVolumesGetter -} - -// CdiV1alpha1Client is used to interact with features provided by the cdi.kubevirt.io group. -type CdiV1alpha1Client struct { - restClient rest.Interface -} - -func (c *CdiV1alpha1Client) DataVolumes(namespace string) DataVolumeInterface { - return newDataVolumes(c, namespace) -} - -// NewForConfig creates a new CdiV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*CdiV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &CdiV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new CdiV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *CdiV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new CdiV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *CdiV1alpha1Client { - return &CdiV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *CdiV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/doc.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/doc.go deleted file mode 100644 index e1cc6da82..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/generated_expansion.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/generated_expansion.go deleted file mode 100644 index 02586030d..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/datavolumecontroller/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type DataVolumeExpansion interface{} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/doc.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/doc.go deleted file mode 100644 index e1cc6da82..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -// This package has the automatically generated typed clients. -package v1alpha1 diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/generated_expansion.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/generated_expansion.go deleted file mode 100644 index 09a3ff7b1..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/generated_expansion.go +++ /dev/null @@ -1,21 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -type UploadTokenRequestExpansion interface{} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadcontroller_client.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadcontroller_client.go deleted file mode 100644 index 42f09b543..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadcontroller_client.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - rest "k8s.io/client-go/rest" - v1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1" - "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme" -) - -type UploadV1alpha1Interface interface { - RESTClient() rest.Interface - UploadTokenRequestsGetter -} - -// UploadV1alpha1Client is used to interact with features provided by the upload.cdi.kubevirt.io group. -type UploadV1alpha1Client struct { - restClient rest.Interface -} - -func (c *UploadV1alpha1Client) UploadTokenRequests(namespace string) UploadTokenRequestInterface { - return newUploadTokenRequests(c, namespace) -} - -// NewForConfig creates a new UploadV1alpha1Client for the given config. -func NewForConfig(c *rest.Config) (*UploadV1alpha1Client, error) { - config := *c - if err := setConfigDefaults(&config); err != nil { - return nil, err - } - client, err := rest.RESTClientFor(&config) - if err != nil { - return nil, err - } - return &UploadV1alpha1Client{client}, nil -} - -// NewForConfigOrDie creates a new UploadV1alpha1Client for the given config and -// panics if there is an error in the config. -func NewForConfigOrDie(c *rest.Config) *UploadV1alpha1Client { - client, err := NewForConfig(c) - if err != nil { - panic(err) - } - return client -} - -// New creates a new UploadV1alpha1Client for the given RESTClient. -func New(c rest.Interface) *UploadV1alpha1Client { - return &UploadV1alpha1Client{c} -} - -func setConfigDefaults(config *rest.Config) error { - gv := v1alpha1.SchemeGroupVersion - config.GroupVersion = &gv - config.APIPath = "/apis" - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - - if config.UserAgent == "" { - config.UserAgent = rest.DefaultKubernetesUserAgent() - } - - return nil -} - -// RESTClient returns a RESTClient that is used to communicate -// with API server by this client implementation. -func (c *UploadV1alpha1Client) RESTClient() rest.Interface { - if c == nil { - return nil - } - return c.restClient -} diff --git a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadtokenrequest.go b/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadtokenrequest.go deleted file mode 100644 index 83ab1b696..000000000 --- a/vendor/kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/typed/uploadcontroller/v1alpha1/uploadtokenrequest.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2018 The CDI 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. -*/ - -// Code generated by client-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - watch "k8s.io/apimachinery/pkg/watch" - rest "k8s.io/client-go/rest" - v1alpha1 "kubevirt.io/containerized-data-importer/pkg/apis/uploadcontroller/v1alpha1" - scheme "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned/scheme" -) - -// UploadTokenRequestsGetter has a method to return a UploadTokenRequestInterface. -// A group's client should implement this interface. -type UploadTokenRequestsGetter interface { - UploadTokenRequests(namespace string) UploadTokenRequestInterface -} - -// UploadTokenRequestInterface has methods to work with UploadTokenRequest resources. -type UploadTokenRequestInterface interface { - Create(*v1alpha1.UploadTokenRequest) (*v1alpha1.UploadTokenRequest, error) - Update(*v1alpha1.UploadTokenRequest) (*v1alpha1.UploadTokenRequest, error) - UpdateStatus(*v1alpha1.UploadTokenRequest) (*v1alpha1.UploadTokenRequest, error) - Delete(name string, options *v1.DeleteOptions) error - DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error - Get(name string, options v1.GetOptions) (*v1alpha1.UploadTokenRequest, error) - List(opts v1.ListOptions) (*v1alpha1.UploadTokenRequestList, error) - Watch(opts v1.ListOptions) (watch.Interface, error) - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.UploadTokenRequest, err error) - UploadTokenRequestExpansion -} - -// uploadTokenRequests implements UploadTokenRequestInterface -type uploadTokenRequests struct { - client rest.Interface - ns string -} - -// newUploadTokenRequests returns a UploadTokenRequests -func newUploadTokenRequests(c *UploadV1alpha1Client, namespace string) *uploadTokenRequests { - return &uploadTokenRequests{ - client: c.RESTClient(), - ns: namespace, - } -} - -// Get takes name of the uploadTokenRequest, and returns the corresponding uploadTokenRequest object, and an error if there is any. -func (c *uploadTokenRequests) Get(name string, options v1.GetOptions) (result *v1alpha1.UploadTokenRequest, err error) { - result = &v1alpha1.UploadTokenRequest{} - err = c.client.Get(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// List takes label and field selectors, and returns the list of UploadTokenRequests that match those selectors. -func (c *uploadTokenRequests) List(opts v1.ListOptions) (result *v1alpha1.UploadTokenRequestList, err error) { - result = &v1alpha1.UploadTokenRequestList{} - err = c.client.Get(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - VersionedParams(&opts, scheme.ParameterCodec). - Do(). - Into(result) - return -} - -// Watch returns a watch.Interface that watches the requested uploadTokenRequests. -func (c *uploadTokenRequests) Watch(opts v1.ListOptions) (watch.Interface, error) { - opts.Watch = true - return c.client.Get(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - VersionedParams(&opts, scheme.ParameterCodec). - Watch() -} - -// Create takes the representation of a uploadTokenRequest and creates it. Returns the server's representation of the uploadTokenRequest, and an error, if there is any. -func (c *uploadTokenRequests) Create(uploadTokenRequest *v1alpha1.UploadTokenRequest) (result *v1alpha1.UploadTokenRequest, err error) { - result = &v1alpha1.UploadTokenRequest{} - err = c.client.Post(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - Body(uploadTokenRequest). - Do(). - Into(result) - return -} - -// Update takes the representation of a uploadTokenRequest and updates it. Returns the server's representation of the uploadTokenRequest, and an error, if there is any. -func (c *uploadTokenRequests) Update(uploadTokenRequest *v1alpha1.UploadTokenRequest) (result *v1alpha1.UploadTokenRequest, err error) { - result = &v1alpha1.UploadTokenRequest{} - err = c.client.Put(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - Name(uploadTokenRequest.Name). - Body(uploadTokenRequest). - Do(). - Into(result) - return -} - -// UpdateStatus was generated because the type contains a Status member. -// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). - -func (c *uploadTokenRequests) UpdateStatus(uploadTokenRequest *v1alpha1.UploadTokenRequest) (result *v1alpha1.UploadTokenRequest, err error) { - result = &v1alpha1.UploadTokenRequest{} - err = c.client.Put(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - Name(uploadTokenRequest.Name). - SubResource("status"). - Body(uploadTokenRequest). - Do(). - Into(result) - return -} - -// Delete takes name of the uploadTokenRequest and deletes it. Returns an error if one occurs. -func (c *uploadTokenRequests) Delete(name string, options *v1.DeleteOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - Name(name). - Body(options). - Do(). - Error() -} - -// DeleteCollection deletes a collection of objects. -func (c *uploadTokenRequests) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { - return c.client.Delete(). - Namespace(c.ns). - Resource("uploadtokenrequests"). - VersionedParams(&listOptions, scheme.ParameterCodec). - Body(options). - Do(). - Error() -} - -// Patch applies the patch and returns the patched uploadTokenRequest. -func (c *uploadTokenRequests) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.UploadTokenRequest, err error) { - result = &v1alpha1.UploadTokenRequest{} - err = c.client.Patch(pt). - Namespace(c.ns). - Resource("uploadtokenrequests"). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/generated_mock_kubevirt.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/generated_mock_kubevirt.go deleted file mode 100644 index aead4ed7a..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/generated_mock_kubevirt.go +++ /dev/null @@ -1,1089 +0,0 @@ -// Automatically generated by MockGen. DO NOT EDIT! -// Source: kubevirt.go - -package kubecli - -import ( - time "time" - - gomock "github.com/golang/mock/gomock" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - types "k8s.io/apimachinery/pkg/types" - discovery "k8s.io/client-go/discovery" - v1alpha1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1alpha1" - v1beta1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1" - v10 "k8s.io/client-go/kubernetes/typed/apps/v1" - v1beta10 "k8s.io/client-go/kubernetes/typed/apps/v1beta1" - v1beta2 "k8s.io/client-go/kubernetes/typed/apps/v1beta2" - v11 "k8s.io/client-go/kubernetes/typed/authentication/v1" - v1beta11 "k8s.io/client-go/kubernetes/typed/authentication/v1beta1" - v12 "k8s.io/client-go/kubernetes/typed/authorization/v1" - v1beta12 "k8s.io/client-go/kubernetes/typed/authorization/v1beta1" - v13 "k8s.io/client-go/kubernetes/typed/autoscaling/v1" - v2beta1 "k8s.io/client-go/kubernetes/typed/autoscaling/v2beta1" - v14 "k8s.io/client-go/kubernetes/typed/batch/v1" - v1beta13 "k8s.io/client-go/kubernetes/typed/batch/v1beta1" - v2alpha1 "k8s.io/client-go/kubernetes/typed/batch/v2alpha1" - v1beta14 "k8s.io/client-go/kubernetes/typed/certificates/v1beta1" - v15 "k8s.io/client-go/kubernetes/typed/core/v1" - v1beta15 "k8s.io/client-go/kubernetes/typed/events/v1beta1" - v1beta16 "k8s.io/client-go/kubernetes/typed/extensions/v1beta1" - v16 "k8s.io/client-go/kubernetes/typed/networking/v1" - v1beta17 "k8s.io/client-go/kubernetes/typed/policy/v1beta1" - v17 "k8s.io/client-go/kubernetes/typed/rbac/v1" - v1alpha10 "k8s.io/client-go/kubernetes/typed/rbac/v1alpha1" - v1beta18 "k8s.io/client-go/kubernetes/typed/rbac/v1beta1" - v1alpha11 "k8s.io/client-go/kubernetes/typed/scheduling/v1alpha1" - v1beta19 "k8s.io/client-go/kubernetes/typed/scheduling/v1beta1" - v1alpha12 "k8s.io/client-go/kubernetes/typed/settings/v1alpha1" - v18 "k8s.io/client-go/kubernetes/typed/storage/v1" - v1alpha13 "k8s.io/client-go/kubernetes/typed/storage/v1alpha1" - v1beta110 "k8s.io/client-go/kubernetes/typed/storage/v1beta1" - rest "k8s.io/client-go/rest" - - versioned "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned" - v19 "kubevirt.io/kubevirt/pkg/api/v1" -) - -// Mock of KubevirtClient interface -type MockKubevirtClient struct { - ctrl *gomock.Controller - recorder *_MockKubevirtClientRecorder -} - -// Recorder for MockKubevirtClient (not exported) -type _MockKubevirtClientRecorder struct { - mock *MockKubevirtClient -} - -func NewMockKubevirtClient(ctrl *gomock.Controller) *MockKubevirtClient { - mock := &MockKubevirtClient{ctrl: ctrl} - mock.recorder = &_MockKubevirtClientRecorder{mock} - return mock -} - -func (_m *MockKubevirtClient) EXPECT() *_MockKubevirtClientRecorder { - return _m.recorder -} - -func (_m *MockKubevirtClient) VirtualMachineInstance(namespace string) VirtualMachineInstanceInterface { - ret := _m.ctrl.Call(_m, "VirtualMachineInstance", namespace) - ret0, _ := ret[0].(VirtualMachineInstanceInterface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) VirtualMachineInstance(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "VirtualMachineInstance", arg0) -} - -func (_m *MockKubevirtClient) VirtualMachineInstanceMigration(namespace string) VirtualMachineInstanceMigrationInterface { - ret := _m.ctrl.Call(_m, "VirtualMachineInstanceMigration", namespace) - ret0, _ := ret[0].(VirtualMachineInstanceMigrationInterface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) VirtualMachineInstanceMigration(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "VirtualMachineInstanceMigration", arg0) -} - -func (_m *MockKubevirtClient) ReplicaSet(namespace string) ReplicaSetInterface { - ret := _m.ctrl.Call(_m, "ReplicaSet", namespace) - ret0, _ := ret[0].(ReplicaSetInterface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) ReplicaSet(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "ReplicaSet", arg0) -} - -func (_m *MockKubevirtClient) VirtualMachine(namespace string) VirtualMachineInterface { - ret := _m.ctrl.Call(_m, "VirtualMachine", namespace) - ret0, _ := ret[0].(VirtualMachineInterface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) VirtualMachine(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "VirtualMachine", arg0) -} - -func (_m *MockKubevirtClient) ServerVersion() *ServerVersion { - ret := _m.ctrl.Call(_m, "ServerVersion") - ret0, _ := ret[0].(*ServerVersion) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) ServerVersion() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "ServerVersion") -} - -func (_m *MockKubevirtClient) RestClient() *rest.RESTClient { - ret := _m.ctrl.Call(_m, "RestClient") - ret0, _ := ret[0].(*rest.RESTClient) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) RestClient() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RestClient") -} - -func (_m *MockKubevirtClient) CdiClient() versioned.Interface { - ret := _m.ctrl.Call(_m, "CdiClient") - ret0, _ := ret[0].(versioned.Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) CdiClient() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "CdiClient") -} - -func (_m *MockKubevirtClient) Discovery() discovery.DiscoveryInterface { - ret := _m.ctrl.Call(_m, "Discovery") - ret0, _ := ret[0].(discovery.DiscoveryInterface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Discovery() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Discovery") -} - -func (_m *MockKubevirtClient) AdmissionregistrationV1alpha1() v1alpha1.AdmissionregistrationV1alpha1Interface { - ret := _m.ctrl.Call(_m, "AdmissionregistrationV1alpha1") - ret0, _ := ret[0].(v1alpha1.AdmissionregistrationV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AdmissionregistrationV1alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AdmissionregistrationV1alpha1") -} - -func (_m *MockKubevirtClient) AdmissionregistrationV1beta1() v1beta1.AdmissionregistrationV1beta1Interface { - ret := _m.ctrl.Call(_m, "AdmissionregistrationV1beta1") - ret0, _ := ret[0].(v1beta1.AdmissionregistrationV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AdmissionregistrationV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AdmissionregistrationV1beta1") -} - -func (_m *MockKubevirtClient) Admissionregistration() v1beta1.AdmissionregistrationV1beta1Interface { - ret := _m.ctrl.Call(_m, "Admissionregistration") - ret0, _ := ret[0].(v1beta1.AdmissionregistrationV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Admissionregistration() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Admissionregistration") -} - -func (_m *MockKubevirtClient) AppsV1beta1() v1beta10.AppsV1beta1Interface { - ret := _m.ctrl.Call(_m, "AppsV1beta1") - ret0, _ := ret[0].(v1beta10.AppsV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AppsV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AppsV1beta1") -} - -func (_m *MockKubevirtClient) AppsV1beta2() v1beta2.AppsV1beta2Interface { - ret := _m.ctrl.Call(_m, "AppsV1beta2") - ret0, _ := ret[0].(v1beta2.AppsV1beta2Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AppsV1beta2() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AppsV1beta2") -} - -func (_m *MockKubevirtClient) AppsV1() v10.AppsV1Interface { - ret := _m.ctrl.Call(_m, "AppsV1") - ret0, _ := ret[0].(v10.AppsV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AppsV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AppsV1") -} - -func (_m *MockKubevirtClient) Apps() v10.AppsV1Interface { - ret := _m.ctrl.Call(_m, "Apps") - ret0, _ := ret[0].(v10.AppsV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Apps() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Apps") -} - -func (_m *MockKubevirtClient) AuthenticationV1() v11.AuthenticationV1Interface { - ret := _m.ctrl.Call(_m, "AuthenticationV1") - ret0, _ := ret[0].(v11.AuthenticationV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AuthenticationV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AuthenticationV1") -} - -func (_m *MockKubevirtClient) Authentication() v11.AuthenticationV1Interface { - ret := _m.ctrl.Call(_m, "Authentication") - ret0, _ := ret[0].(v11.AuthenticationV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Authentication() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Authentication") -} - -func (_m *MockKubevirtClient) AuthenticationV1beta1() v1beta11.AuthenticationV1beta1Interface { - ret := _m.ctrl.Call(_m, "AuthenticationV1beta1") - ret0, _ := ret[0].(v1beta11.AuthenticationV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AuthenticationV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AuthenticationV1beta1") -} - -func (_m *MockKubevirtClient) AuthorizationV1() v12.AuthorizationV1Interface { - ret := _m.ctrl.Call(_m, "AuthorizationV1") - ret0, _ := ret[0].(v12.AuthorizationV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AuthorizationV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AuthorizationV1") -} - -func (_m *MockKubevirtClient) Authorization() v12.AuthorizationV1Interface { - ret := _m.ctrl.Call(_m, "Authorization") - ret0, _ := ret[0].(v12.AuthorizationV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Authorization() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Authorization") -} - -func (_m *MockKubevirtClient) AuthorizationV1beta1() v1beta12.AuthorizationV1beta1Interface { - ret := _m.ctrl.Call(_m, "AuthorizationV1beta1") - ret0, _ := ret[0].(v1beta12.AuthorizationV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AuthorizationV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AuthorizationV1beta1") -} - -func (_m *MockKubevirtClient) AutoscalingV1() v13.AutoscalingV1Interface { - ret := _m.ctrl.Call(_m, "AutoscalingV1") - ret0, _ := ret[0].(v13.AutoscalingV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AutoscalingV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AutoscalingV1") -} - -func (_m *MockKubevirtClient) Autoscaling() v13.AutoscalingV1Interface { - ret := _m.ctrl.Call(_m, "Autoscaling") - ret0, _ := ret[0].(v13.AutoscalingV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Autoscaling() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Autoscaling") -} - -func (_m *MockKubevirtClient) AutoscalingV2beta1() v2beta1.AutoscalingV2beta1Interface { - ret := _m.ctrl.Call(_m, "AutoscalingV2beta1") - ret0, _ := ret[0].(v2beta1.AutoscalingV2beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) AutoscalingV2beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "AutoscalingV2beta1") -} - -func (_m *MockKubevirtClient) BatchV1() v14.BatchV1Interface { - ret := _m.ctrl.Call(_m, "BatchV1") - ret0, _ := ret[0].(v14.BatchV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) BatchV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "BatchV1") -} - -func (_m *MockKubevirtClient) Batch() v14.BatchV1Interface { - ret := _m.ctrl.Call(_m, "Batch") - ret0, _ := ret[0].(v14.BatchV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Batch() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Batch") -} - -func (_m *MockKubevirtClient) BatchV1beta1() v1beta13.BatchV1beta1Interface { - ret := _m.ctrl.Call(_m, "BatchV1beta1") - ret0, _ := ret[0].(v1beta13.BatchV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) BatchV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "BatchV1beta1") -} - -func (_m *MockKubevirtClient) BatchV2alpha1() v2alpha1.BatchV2alpha1Interface { - ret := _m.ctrl.Call(_m, "BatchV2alpha1") - ret0, _ := ret[0].(v2alpha1.BatchV2alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) BatchV2alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "BatchV2alpha1") -} - -func (_m *MockKubevirtClient) CertificatesV1beta1() v1beta14.CertificatesV1beta1Interface { - ret := _m.ctrl.Call(_m, "CertificatesV1beta1") - ret0, _ := ret[0].(v1beta14.CertificatesV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) CertificatesV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "CertificatesV1beta1") -} - -func (_m *MockKubevirtClient) Certificates() v1beta14.CertificatesV1beta1Interface { - ret := _m.ctrl.Call(_m, "Certificates") - ret0, _ := ret[0].(v1beta14.CertificatesV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Certificates() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Certificates") -} - -func (_m *MockKubevirtClient) CoreV1() v15.CoreV1Interface { - ret := _m.ctrl.Call(_m, "CoreV1") - ret0, _ := ret[0].(v15.CoreV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) CoreV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "CoreV1") -} - -func (_m *MockKubevirtClient) Core() v15.CoreV1Interface { - ret := _m.ctrl.Call(_m, "Core") - ret0, _ := ret[0].(v15.CoreV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Core() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Core") -} - -func (_m *MockKubevirtClient) EventsV1beta1() v1beta15.EventsV1beta1Interface { - ret := _m.ctrl.Call(_m, "EventsV1beta1") - ret0, _ := ret[0].(v1beta15.EventsV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) EventsV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "EventsV1beta1") -} - -func (_m *MockKubevirtClient) Events() v1beta15.EventsV1beta1Interface { - ret := _m.ctrl.Call(_m, "Events") - ret0, _ := ret[0].(v1beta15.EventsV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Events() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Events") -} - -func (_m *MockKubevirtClient) ExtensionsV1beta1() v1beta16.ExtensionsV1beta1Interface { - ret := _m.ctrl.Call(_m, "ExtensionsV1beta1") - ret0, _ := ret[0].(v1beta16.ExtensionsV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) ExtensionsV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "ExtensionsV1beta1") -} - -func (_m *MockKubevirtClient) Extensions() v1beta16.ExtensionsV1beta1Interface { - ret := _m.ctrl.Call(_m, "Extensions") - ret0, _ := ret[0].(v1beta16.ExtensionsV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Extensions() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Extensions") -} - -func (_m *MockKubevirtClient) NetworkingV1() v16.NetworkingV1Interface { - ret := _m.ctrl.Call(_m, "NetworkingV1") - ret0, _ := ret[0].(v16.NetworkingV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) NetworkingV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "NetworkingV1") -} - -func (_m *MockKubevirtClient) Networking() v16.NetworkingV1Interface { - ret := _m.ctrl.Call(_m, "Networking") - ret0, _ := ret[0].(v16.NetworkingV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Networking() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Networking") -} - -func (_m *MockKubevirtClient) PolicyV1beta1() v1beta17.PolicyV1beta1Interface { - ret := _m.ctrl.Call(_m, "PolicyV1beta1") - ret0, _ := ret[0].(v1beta17.PolicyV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) PolicyV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "PolicyV1beta1") -} - -func (_m *MockKubevirtClient) Policy() v1beta17.PolicyV1beta1Interface { - ret := _m.ctrl.Call(_m, "Policy") - ret0, _ := ret[0].(v1beta17.PolicyV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Policy() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Policy") -} - -func (_m *MockKubevirtClient) RbacV1() v17.RbacV1Interface { - ret := _m.ctrl.Call(_m, "RbacV1") - ret0, _ := ret[0].(v17.RbacV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) RbacV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RbacV1") -} - -func (_m *MockKubevirtClient) Rbac() v17.RbacV1Interface { - ret := _m.ctrl.Call(_m, "Rbac") - ret0, _ := ret[0].(v17.RbacV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Rbac() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Rbac") -} - -func (_m *MockKubevirtClient) RbacV1beta1() v1beta18.RbacV1beta1Interface { - ret := _m.ctrl.Call(_m, "RbacV1beta1") - ret0, _ := ret[0].(v1beta18.RbacV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) RbacV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RbacV1beta1") -} - -func (_m *MockKubevirtClient) RbacV1alpha1() v1alpha10.RbacV1alpha1Interface { - ret := _m.ctrl.Call(_m, "RbacV1alpha1") - ret0, _ := ret[0].(v1alpha10.RbacV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) RbacV1alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "RbacV1alpha1") -} - -func (_m *MockKubevirtClient) SchedulingV1alpha1() v1alpha11.SchedulingV1alpha1Interface { - ret := _m.ctrl.Call(_m, "SchedulingV1alpha1") - ret0, _ := ret[0].(v1alpha11.SchedulingV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) SchedulingV1alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SchedulingV1alpha1") -} - -func (_m *MockKubevirtClient) SchedulingV1beta1() v1beta19.SchedulingV1beta1Interface { - ret := _m.ctrl.Call(_m, "SchedulingV1beta1") - ret0, _ := ret[0].(v1beta19.SchedulingV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) SchedulingV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SchedulingV1beta1") -} - -func (_m *MockKubevirtClient) Scheduling() v1beta19.SchedulingV1beta1Interface { - ret := _m.ctrl.Call(_m, "Scheduling") - ret0, _ := ret[0].(v1beta19.SchedulingV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Scheduling() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Scheduling") -} - -func (_m *MockKubevirtClient) SettingsV1alpha1() v1alpha12.SettingsV1alpha1Interface { - ret := _m.ctrl.Call(_m, "SettingsV1alpha1") - ret0, _ := ret[0].(v1alpha12.SettingsV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) SettingsV1alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SettingsV1alpha1") -} - -func (_m *MockKubevirtClient) Settings() v1alpha12.SettingsV1alpha1Interface { - ret := _m.ctrl.Call(_m, "Settings") - ret0, _ := ret[0].(v1alpha12.SettingsV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Settings() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Settings") -} - -func (_m *MockKubevirtClient) StorageV1beta1() v1beta110.StorageV1beta1Interface { - ret := _m.ctrl.Call(_m, "StorageV1beta1") - ret0, _ := ret[0].(v1beta110.StorageV1beta1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) StorageV1beta1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "StorageV1beta1") -} - -func (_m *MockKubevirtClient) StorageV1() v18.StorageV1Interface { - ret := _m.ctrl.Call(_m, "StorageV1") - ret0, _ := ret[0].(v18.StorageV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) StorageV1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "StorageV1") -} - -func (_m *MockKubevirtClient) Storage() v18.StorageV1Interface { - ret := _m.ctrl.Call(_m, "Storage") - ret0, _ := ret[0].(v18.StorageV1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) Storage() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Storage") -} - -func (_m *MockKubevirtClient) StorageV1alpha1() v1alpha13.StorageV1alpha1Interface { - ret := _m.ctrl.Call(_m, "StorageV1alpha1") - ret0, _ := ret[0].(v1alpha13.StorageV1alpha1Interface) - return ret0 -} - -func (_mr *_MockKubevirtClientRecorder) StorageV1alpha1() *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "StorageV1alpha1") -} - -// Mock of StreamInterface interface -type MockStreamInterface struct { - ctrl *gomock.Controller - recorder *_MockStreamInterfaceRecorder -} - -// Recorder for MockStreamInterface (not exported) -type _MockStreamInterfaceRecorder struct { - mock *MockStreamInterface -} - -func NewMockStreamInterface(ctrl *gomock.Controller) *MockStreamInterface { - mock := &MockStreamInterface{ctrl: ctrl} - mock.recorder = &_MockStreamInterfaceRecorder{mock} - return mock -} - -func (_m *MockStreamInterface) EXPECT() *_MockStreamInterfaceRecorder { - return _m.recorder -} - -func (_m *MockStreamInterface) Stream(options StreamOptions) error { - ret := _m.ctrl.Call(_m, "Stream", options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockStreamInterfaceRecorder) Stream(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Stream", arg0) -} - -// Mock of VirtualMachineInstanceInterface interface -type MockVirtualMachineInstanceInterface struct { - ctrl *gomock.Controller - recorder *_MockVirtualMachineInstanceInterfaceRecorder -} - -// Recorder for MockVirtualMachineInstanceInterface (not exported) -type _MockVirtualMachineInstanceInterfaceRecorder struct { - mock *MockVirtualMachineInstanceInterface -} - -func NewMockVirtualMachineInstanceInterface(ctrl *gomock.Controller) *MockVirtualMachineInstanceInterface { - mock := &MockVirtualMachineInstanceInterface{ctrl: ctrl} - mock.recorder = &_MockVirtualMachineInstanceInterfaceRecorder{mock} - return mock -} - -func (_m *MockVirtualMachineInstanceInterface) EXPECT() *_MockVirtualMachineInstanceInterfaceRecorder { - return _m.recorder -} - -func (_m *MockVirtualMachineInstanceInterface) Get(name string, options *v1.GetOptions) (*v19.VirtualMachineInstance, error) { - ret := _m.ctrl.Call(_m, "Get", name, options) - ret0, _ := ret[0].(*v19.VirtualMachineInstance) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) Get(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Get", arg0, arg1) -} - -func (_m *MockVirtualMachineInstanceInterface) List(opts *v1.ListOptions) (*v19.VirtualMachineInstanceList, error) { - ret := _m.ctrl.Call(_m, "List", opts) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceList) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) List(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "List", arg0) -} - -func (_m *MockVirtualMachineInstanceInterface) Create(instance *v19.VirtualMachineInstance) (*v19.VirtualMachineInstance, error) { - ret := _m.ctrl.Call(_m, "Create", instance) - ret0, _ := ret[0].(*v19.VirtualMachineInstance) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) Create(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0) -} - -func (_m *MockVirtualMachineInstanceInterface) Update(_param0 *v19.VirtualMachineInstance) (*v19.VirtualMachineInstance, error) { - ret := _m.ctrl.Call(_m, "Update", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstance) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) Update(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Update", arg0) -} - -func (_m *MockVirtualMachineInstanceInterface) Delete(name string, options *v1.DeleteOptions) error { - ret := _m.ctrl.Call(_m, "Delete", name, options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) Delete(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Delete", arg0, arg1) -} - -func (_m *MockVirtualMachineInstanceInterface) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v19.VirtualMachineInstance, error) { - _s := []interface{}{name, pt, data} - for _, _x := range subresources { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "Patch", _s...) - ret0, _ := ret[0].(*v19.VirtualMachineInstance) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1, arg2}, arg3...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "Patch", _s...) -} - -func (_m *MockVirtualMachineInstanceInterface) SerialConsole(name string, timeout time.Duration) (StreamInterface, error) { - ret := _m.ctrl.Call(_m, "SerialConsole", name, timeout) - ret0, _ := ret[0].(StreamInterface) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) SerialConsole(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "SerialConsole", arg0, arg1) -} - -func (_m *MockVirtualMachineInstanceInterface) VNC(name string) (StreamInterface, error) { - ret := _m.ctrl.Call(_m, "VNC", name) - ret0, _ := ret[0].(StreamInterface) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceInterfaceRecorder) VNC(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "VNC", arg0) -} - -// Mock of ReplicaSetInterface interface -type MockReplicaSetInterface struct { - ctrl *gomock.Controller - recorder *_MockReplicaSetInterfaceRecorder -} - -// Recorder for MockReplicaSetInterface (not exported) -type _MockReplicaSetInterfaceRecorder struct { - mock *MockReplicaSetInterface -} - -func NewMockReplicaSetInterface(ctrl *gomock.Controller) *MockReplicaSetInterface { - mock := &MockReplicaSetInterface{ctrl: ctrl} - mock.recorder = &_MockReplicaSetInterfaceRecorder{mock} - return mock -} - -func (_m *MockReplicaSetInterface) EXPECT() *_MockReplicaSetInterfaceRecorder { - return _m.recorder -} - -func (_m *MockReplicaSetInterface) Get(name string, options v1.GetOptions) (*v19.VirtualMachineInstanceReplicaSet, error) { - ret := _m.ctrl.Call(_m, "Get", name, options) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceReplicaSet) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockReplicaSetInterfaceRecorder) Get(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Get", arg0, arg1) -} - -func (_m *MockReplicaSetInterface) List(opts v1.ListOptions) (*v19.VirtualMachineInstanceReplicaSetList, error) { - ret := _m.ctrl.Call(_m, "List", opts) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceReplicaSetList) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockReplicaSetInterfaceRecorder) List(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "List", arg0) -} - -func (_m *MockReplicaSetInterface) Create(_param0 *v19.VirtualMachineInstanceReplicaSet) (*v19.VirtualMachineInstanceReplicaSet, error) { - ret := _m.ctrl.Call(_m, "Create", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceReplicaSet) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockReplicaSetInterfaceRecorder) Create(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0) -} - -func (_m *MockReplicaSetInterface) Update(_param0 *v19.VirtualMachineInstanceReplicaSet) (*v19.VirtualMachineInstanceReplicaSet, error) { - ret := _m.ctrl.Call(_m, "Update", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceReplicaSet) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockReplicaSetInterfaceRecorder) Update(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Update", arg0) -} - -func (_m *MockReplicaSetInterface) Delete(name string, options *v1.DeleteOptions) error { - ret := _m.ctrl.Call(_m, "Delete", name, options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockReplicaSetInterfaceRecorder) Delete(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Delete", arg0, arg1) -} - -// Mock of VMIPresetInterface interface -type MockVMIPresetInterface struct { - ctrl *gomock.Controller - recorder *_MockVMIPresetInterfaceRecorder -} - -// Recorder for MockVMIPresetInterface (not exported) -type _MockVMIPresetInterfaceRecorder struct { - mock *MockVMIPresetInterface -} - -func NewMockVMIPresetInterface(ctrl *gomock.Controller) *MockVMIPresetInterface { - mock := &MockVMIPresetInterface{ctrl: ctrl} - mock.recorder = &_MockVMIPresetInterfaceRecorder{mock} - return mock -} - -func (_m *MockVMIPresetInterface) EXPECT() *_MockVMIPresetInterfaceRecorder { - return _m.recorder -} - -func (_m *MockVMIPresetInterface) Get(name string, options v1.GetOptions) (*v19.VirtualMachineInstancePreset, error) { - ret := _m.ctrl.Call(_m, "Get", name, options) - ret0, _ := ret[0].(*v19.VirtualMachineInstancePreset) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) Get(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Get", arg0, arg1) -} - -func (_m *MockVMIPresetInterface) List(opts v1.ListOptions) (*v19.VirtualMachineInstancePresetList, error) { - ret := _m.ctrl.Call(_m, "List", opts) - ret0, _ := ret[0].(*v19.VirtualMachineInstancePresetList) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) List(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "List", arg0) -} - -func (_m *MockVMIPresetInterface) Create(_param0 *v19.VirtualMachineInstancePreset) (*v19.VirtualMachineInstancePreset, error) { - ret := _m.ctrl.Call(_m, "Create", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstancePreset) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) Create(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0) -} - -func (_m *MockVMIPresetInterface) Update(_param0 *v19.VirtualMachineInstancePreset) (*v19.VirtualMachineInstancePreset, error) { - ret := _m.ctrl.Call(_m, "Update", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstancePreset) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) Update(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Update", arg0) -} - -func (_m *MockVMIPresetInterface) Delete(name string, options *v1.DeleteOptions) error { - ret := _m.ctrl.Call(_m, "Delete", name, options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) Delete(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Delete", arg0, arg1) -} - -func (_m *MockVMIPresetInterface) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v19.VirtualMachineInstancePreset, error) { - _s := []interface{}{name, pt, data} - for _, _x := range subresources { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "Patch", _s...) - ret0, _ := ret[0].(*v19.VirtualMachineInstancePreset) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVMIPresetInterfaceRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1, arg2}, arg3...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "Patch", _s...) -} - -// Mock of VirtualMachineInterface interface -type MockVirtualMachineInterface struct { - ctrl *gomock.Controller - recorder *_MockVirtualMachineInterfaceRecorder -} - -// Recorder for MockVirtualMachineInterface (not exported) -type _MockVirtualMachineInterfaceRecorder struct { - mock *MockVirtualMachineInterface -} - -func NewMockVirtualMachineInterface(ctrl *gomock.Controller) *MockVirtualMachineInterface { - mock := &MockVirtualMachineInterface{ctrl: ctrl} - mock.recorder = &_MockVirtualMachineInterfaceRecorder{mock} - return mock -} - -func (_m *MockVirtualMachineInterface) EXPECT() *_MockVirtualMachineInterfaceRecorder { - return _m.recorder -} - -func (_m *MockVirtualMachineInterface) Get(name string, options *v1.GetOptions) (*v19.VirtualMachine, error) { - ret := _m.ctrl.Call(_m, "Get", name, options) - ret0, _ := ret[0].(*v19.VirtualMachine) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) Get(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Get", arg0, arg1) -} - -func (_m *MockVirtualMachineInterface) List(opts *v1.ListOptions) (*v19.VirtualMachineList, error) { - ret := _m.ctrl.Call(_m, "List", opts) - ret0, _ := ret[0].(*v19.VirtualMachineList) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) List(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "List", arg0) -} - -func (_m *MockVirtualMachineInterface) Create(_param0 *v19.VirtualMachine) (*v19.VirtualMachine, error) { - ret := _m.ctrl.Call(_m, "Create", _param0) - ret0, _ := ret[0].(*v19.VirtualMachine) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) Create(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0) -} - -func (_m *MockVirtualMachineInterface) Update(_param0 *v19.VirtualMachine) (*v19.VirtualMachine, error) { - ret := _m.ctrl.Call(_m, "Update", _param0) - ret0, _ := ret[0].(*v19.VirtualMachine) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) Update(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Update", arg0) -} - -func (_m *MockVirtualMachineInterface) Delete(name string, options *v1.DeleteOptions) error { - ret := _m.ctrl.Call(_m, "Delete", name, options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) Delete(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Delete", arg0, arg1) -} - -func (_m *MockVirtualMachineInterface) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v19.VirtualMachine, error) { - _s := []interface{}{name, pt, data} - for _, _x := range subresources { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "Patch", _s...) - ret0, _ := ret[0].(*v19.VirtualMachine) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInterfaceRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1, arg2}, arg3...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "Patch", _s...) -} - -// Mock of VirtualMachineInstanceMigrationInterface interface -type MockVirtualMachineInstanceMigrationInterface struct { - ctrl *gomock.Controller - recorder *_MockVirtualMachineInstanceMigrationInterfaceRecorder -} - -// Recorder for MockVirtualMachineInstanceMigrationInterface (not exported) -type _MockVirtualMachineInstanceMigrationInterfaceRecorder struct { - mock *MockVirtualMachineInstanceMigrationInterface -} - -func NewMockVirtualMachineInstanceMigrationInterface(ctrl *gomock.Controller) *MockVirtualMachineInstanceMigrationInterface { - mock := &MockVirtualMachineInstanceMigrationInterface{ctrl: ctrl} - mock.recorder = &_MockVirtualMachineInstanceMigrationInterfaceRecorder{mock} - return mock -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) EXPECT() *_MockVirtualMachineInstanceMigrationInterfaceRecorder { - return _m.recorder -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) Get(name string, options *v1.GetOptions) (*v19.VirtualMachineInstanceMigration, error) { - ret := _m.ctrl.Call(_m, "Get", name, options) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceMigration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) Get(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Get", arg0, arg1) -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) List(opts *v1.ListOptions) (*v19.VirtualMachineInstanceMigrationList, error) { - ret := _m.ctrl.Call(_m, "List", opts) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceMigrationList) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) List(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "List", arg0) -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) Create(_param0 *v19.VirtualMachineInstanceMigration) (*v19.VirtualMachineInstanceMigration, error) { - ret := _m.ctrl.Call(_m, "Create", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceMigration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) Create(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0) -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) Update(_param0 *v19.VirtualMachineInstanceMigration) (*v19.VirtualMachineInstanceMigration, error) { - ret := _m.ctrl.Call(_m, "Update", _param0) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceMigration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) Update(arg0 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Update", arg0) -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) Delete(name string, options *v1.DeleteOptions) error { - ret := _m.ctrl.Call(_m, "Delete", name, options) - ret0, _ := ret[0].(error) - return ret0 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) Delete(arg0, arg1 interface{}) *gomock.Call { - return _mr.mock.ctrl.RecordCall(_mr.mock, "Delete", arg0, arg1) -} - -func (_m *MockVirtualMachineInstanceMigrationInterface) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v19.VirtualMachineInstanceMigration, error) { - _s := []interface{}{name, pt, data} - for _, _x := range subresources { - _s = append(_s, _x) - } - ret := _m.ctrl.Call(_m, "Patch", _s...) - ret0, _ := ret[0].(*v19.VirtualMachineInstanceMigration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -func (_mr *_MockVirtualMachineInstanceMigrationInterfaceRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { - _s := append([]interface{}{arg0, arg1, arg2}, arg3...) - return _mr.mock.ctrl.RecordCall(_mr.mock, "Patch", _s...) -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/handler.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/handler.go deleted file mode 100644 index 90ff5c92b..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/handler.go +++ /dev/null @@ -1,107 +0,0 @@ -package kubecli - -import ( - "fmt" - "net/url" - - "k8s.io/api/core/v1" - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/fields" - "k8s.io/apimachinery/pkg/labels" - - virtv1 "kubevirt.io/kubevirt/pkg/api/v1" -) - -func NewVirtHandlerClient(client KubevirtClient) VirtHandlerClient { - return &virtHandler{client} -} - -type VirtHandlerClient interface { - ForNode(nodeName string) VirtHandlerConn -} - -type VirtHandlerConn interface { - ConnectionDetails() (ip string, port string, err error) - ConsoleURI(vmi *virtv1.VirtualMachineInstance) (*url.URL, error) - Pod() (pod *v1.Pod, err error) -} - -type virtHandler struct { - client KubevirtClient -} - -type virtHandlerConn struct { - client KubevirtClient - pod *v1.Pod - err error -} - -func (v *virtHandler) ForNode(nodeName string) VirtHandlerConn { - pod, found, err := v.getVirtHandler(nodeName) - conn := &virtHandlerConn{} - if !found { - conn.err = fmt.Errorf("No virt-handler on node %s found", nodeName) - } - if err != nil { - conn.err = err - } - conn.pod = pod - conn.client = v.client - return conn -} - -func (v *virtHandler) getVirtHandler(nodeName string) (*v1.Pod, bool, error) { - - handlerNodeSelector := fields.ParseSelectorOrDie("spec.nodeName=" + nodeName) - labelSelector, err := labels.Parse(virtv1.AppLabel + " in (virt-handler)") - if err != nil { - return nil, false, err - } - pods, err := v.client.CoreV1().Pods(v1.NamespaceAll).List( - k8smetav1.ListOptions{ - FieldSelector: handlerNodeSelector.String(), - LabelSelector: labelSelector.String()}) - if err != nil { - return nil, false, err - } - if len(pods.Items) > 1 { - return nil, false, fmt.Errorf("Expected to find one Pod, found %d Pods", len(pods.Items)) - } - - if len(pods.Items) == 0 { - return nil, false, nil - } - return &pods.Items[0], true, nil -} - -func (v *virtHandlerConn) ConnectionDetails() (ip string, port string, err error) { - if v.err != nil { - err = v.err - return - } - // TODO depending on in which network namespace virt-handler runs, we might have to choose the NodeIPt d - ip = v.pod.Status.PodIP - // TODO get rid of the hardcoded port - port = "8185" - return -} - -//TODO move the actual ws handling in here, and work with channels -func (v *virtHandlerConn) ConsoleURI(vmi *virtv1.VirtualMachineInstance) (*url.URL, error) { - ip, port, err := v.ConnectionDetails() - if err != nil { - return nil, err - } - return &url.URL{ - Path: fmt.Sprintf("/api/v1/namespaces/%s/virtualmachineinstances/%s/console", vmi.ObjectMeta.Namespace, vmi.ObjectMeta.Name), - Host: ip + ":" + port, - }, nil -} - -func (v *virtHandlerConn) Pod() (pod *v1.Pod, err error) { - if v.err != nil { - err = v.err - return - } - return v.pod, err -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubecli.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubecli.go deleted file mode 100644 index 90b999ec0..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubecli.go +++ /dev/null @@ -1,216 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * Copyright 2018 The Kubernetes Authors. - * - */ - -package kubecli - -import ( - "flag" - "os" - - "github.com/spf13/pflag" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - - cdiclient "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned" - "kubevirt.io/kubevirt/pkg/api/v1" -) - -var ( - kubeconfig string - master string -) - -func init() { - flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file") - flag.StringVar(&master, "master", "", "master url") -} - -func GetKubevirtSubresourceClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) { - config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig) - if err != nil { - return nil, err - } - - config.GroupVersion = &v1.SubresourceGroupVersion - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - config.APIPath = "/apis" - config.ContentType = runtime.ContentTypeJSON - - restClient, err := rest.RESTClientFor(config) - if err != nil { - return nil, err - } - - coreClient, err := kubernetes.NewForConfig(config) - if err != nil { - return nil, err - } - - cdiClient, err := cdiclient.NewForConfig(config) - if err != nil { - return nil, err - } - - return &kubevirt{ - master, - kubeconfig, - restClient, - config, - cdiClient, - coreClient, - }, nil -} - -// DefaultClientConfig creates a clientcmd.ClientConfig with the following hierarchy: -// 1. Use the kubeconfig builder. The number of merges and overrides here gets a little crazy. Stay with me. -// 1. Merge the kubeconfig itself. This is done with the following hierarchy rules: -// 1. CommandLineLocation - this parsed from the command line, so it must be late bound. If you specify this, -// then no other kubeconfig files are merged. This file must exist. -// 2. If $KUBECONFIG is set, then it is treated as a list of files that should be merged. -// 3. HomeDirectoryLocation -// 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 -// non-conflicting entries from the second file's "red-user" are discarded. -// 2. Determine the context to use based on the first hit in this chain -// 1. command line argument - again, parsed from the command line, so it must be late bound -// 2. CurrentContext from the merged kubeconfig file -// 3. Empty is allowed at this stage -// 3. Determine the cluster info and auth info to use. At this point, we may or may not have a context. They -// are built based on the first hit in this chain. (run it twice, once for auth, once for cluster) -// 1. command line argument -// 2. If context is present, then use the context value -// 3. Empty is allowed -// 4. Determine the actual cluster info to use. At this point, we may or may not have a cluster info. Build -// each piece of the cluster info based on the chain: -// 1. command line argument -// 2. If cluster info is present and a value for the attribute is present, use it. -// 3. If you don't have a server location, bail. -// 5. Auth info is build using the same rules as cluster info, EXCEPT that you can only have one authentication -// technique per auth info. The following conditions result in an error: -// 1. If there are two conflicting techniques specified from the command line, fail. -// 2. If the command line does not specify one, and the auth info has conflicting techniques, fail. -// 3. If the command line specifies one and the auth info specifies another, honor the command line technique. -// 2. Use default values and potentially prompt for auth information -// -// However, if it appears that we're running in a kubernetes cluster -// container environment, then run with the auth info kubernetes mounted for -// us. Specifically: -// The env vars KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are -// set, and the file /var/run/secrets/kubernetes.io/serviceaccount/token -// exists and is not a directory. -// Initially copied from https://github.com/kubernetes/kubernetes/blob/09f321c80bfc9bca63a5530b56d7a1a3ba80ba9b/pkg/kubectl/cmd/util/factory_client_access.go#L174 -func DefaultClientConfig(flags *pflag.FlagSet) clientcmd.ClientConfig { - loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() - // use the standard defaults for this client command - // DEPRECATED: remove and replace with something more accurate - loadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig - - flags.StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.") - - overrides := &clientcmd.ConfigOverrides{ClusterDefaults: clientcmd.ClusterDefaults} - - flagNames := clientcmd.RecommendedConfigOverrideFlags("") - // short flagnames are disabled by default. These are here for compatibility with existing scripts - flagNames.ClusterOverrideFlags.APIServer.ShortName = "s" - - clientcmd.BindOverrideFlags(overrides, flags, flagNames) - clientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin) - - return clientConfig -} - -// this function is defined as a closure so iut could be overwritten by unit tests -var GetKubevirtClientFromClientConfig = func(cmdConfig clientcmd.ClientConfig) (KubevirtClient, error) { - config, err := cmdConfig.ClientConfig() - if err != nil { - return nil, err - } - return GetKubevirtClientFromRESTConfig(config) - -} - -func GetKubevirtClientFromRESTConfig(config *rest.Config) (KubevirtClient, error) { - config.GroupVersion = &v1.GroupVersion - config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: v1.Codecs} - config.APIPath = "/apis" - config.ContentType = runtime.ContentTypeJSON - if config.UserAgent == "" { - config.UserAgent = restclient.DefaultKubernetesUserAgent() - } - - restClient, err := rest.RESTClientFor(config) - if err != nil { - return nil, err - } - - coreClient, err := kubernetes.NewForConfig(config) - if err != nil { - return nil, err - } - - cdiClient, err := cdiclient.NewForConfig(config) - if err != nil { - return nil, err - } - - return &kubevirt{ - master, - kubeconfig, - restClient, - config, - cdiClient, - coreClient, - }, nil -} - -func GetKubevirtClientFromFlags(master string, kubeconfig string) (KubevirtClient, error) { - config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig) - if err != nil { - return nil, err - } - return GetKubevirtClientFromRESTConfig(config) -} - -func GetKubevirtClient() (KubevirtClient, error) { - return GetKubevirtClientFromFlags(master, kubeconfig) -} - -func GetKubevirtSubresourceClient() (KubevirtClient, error) { - return GetKubevirtSubresourceClientFromFlags(master, kubeconfig) -} - -func GetConfig() (*restclient.Config, error) { - return clientcmd.BuildConfigFromFlags(master, kubeconfig) -} - -func GetKubevirtClientConfig() (*rest.Config, error) { - config, err := clientcmd.BuildConfigFromFlags(master, kubeconfig) - if err != nil { - return nil, err - } - return config, nil -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt.go deleted file mode 100644 index dfbe61796..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt.go +++ /dev/null @@ -1,124 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package kubecli - -//go:generate mockgen -source $GOFILE -package=$GOPACKAGE -destination=generated_mock_$GOFILE - -/* - ATTENTION: Rerun code generators when interface signatures are modified. -*/ - -import ( - "io" - "time" - - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" - - cdiclient "kubevirt.io/containerized-data-importer/pkg/client/clientset/versioned" - "kubevirt.io/kubevirt/pkg/api/v1" -) - -type KubevirtClient interface { - VirtualMachineInstance(namespace string) VirtualMachineInstanceInterface - VirtualMachineInstanceMigration(namespace string) VirtualMachineInstanceMigrationInterface - ReplicaSet(namespace string) ReplicaSetInterface - VirtualMachine(namespace string) VirtualMachineInterface - ServerVersion() *ServerVersion - RestClient() *rest.RESTClient - CdiClient() cdiclient.Interface - kubernetes.Interface -} - -type kubevirt struct { - master string - kubeconfig string - restClient *rest.RESTClient - config *rest.Config - cdiClient *cdiclient.Clientset - *kubernetes.Clientset -} - -func (k kubevirt) CdiClient() cdiclient.Interface { - return k.cdiClient -} - -func (k kubevirt) RestClient() *rest.RESTClient { - return k.restClient -} - -type StreamOptions struct { - In io.Reader - Out io.Writer -} - -type StreamInterface interface { - Stream(options StreamOptions) error -} - -type VirtualMachineInstanceInterface interface { - Get(name string, options *k8smetav1.GetOptions) (*v1.VirtualMachineInstance, error) - List(opts *k8smetav1.ListOptions) (*v1.VirtualMachineInstanceList, error) - Create(instance *v1.VirtualMachineInstance) (*v1.VirtualMachineInstance, error) - Update(*v1.VirtualMachineInstance) (*v1.VirtualMachineInstance, error) - Delete(name string, options *k8smetav1.DeleteOptions) error - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstance, err error) - SerialConsole(name string, timeout time.Duration) (StreamInterface, error) - VNC(name string) (StreamInterface, error) -} - -type ReplicaSetInterface interface { - Get(name string, options k8smetav1.GetOptions) (*v1.VirtualMachineInstanceReplicaSet, error) - List(opts k8smetav1.ListOptions) (*v1.VirtualMachineInstanceReplicaSetList, error) - Create(*v1.VirtualMachineInstanceReplicaSet) (*v1.VirtualMachineInstanceReplicaSet, error) - Update(*v1.VirtualMachineInstanceReplicaSet) (*v1.VirtualMachineInstanceReplicaSet, error) - Delete(name string, options *k8smetav1.DeleteOptions) error -} - -type VMIPresetInterface interface { - Get(name string, options k8smetav1.GetOptions) (*v1.VirtualMachineInstancePreset, error) - List(opts k8smetav1.ListOptions) (*v1.VirtualMachineInstancePresetList, error) - Create(*v1.VirtualMachineInstancePreset) (*v1.VirtualMachineInstancePreset, error) - Update(*v1.VirtualMachineInstancePreset) (*v1.VirtualMachineInstancePreset, error) - Delete(name string, options *k8smetav1.DeleteOptions) error - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstancePreset, err error) -} - -// VirtualMachineInterface provides convenience methods to work with -// virtual machines inside the cluster -type VirtualMachineInterface interface { - Get(name string, options *k8smetav1.GetOptions) (*v1.VirtualMachine, error) - List(opts *k8smetav1.ListOptions) (*v1.VirtualMachineList, error) - Create(*v1.VirtualMachine) (*v1.VirtualMachine, error) - Update(*v1.VirtualMachine) (*v1.VirtualMachine, error) - Delete(name string, options *k8smetav1.DeleteOptions) error - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachine, err error) -} - -type VirtualMachineInstanceMigrationInterface interface { - Get(name string, options *k8smetav1.GetOptions) (*v1.VirtualMachineInstanceMigration, error) - List(opts *k8smetav1.ListOptions) (*v1.VirtualMachineInstanceMigrationList, error) - Create(*v1.VirtualMachineInstanceMigration) (*v1.VirtualMachineInstanceMigration, error) - Update(*v1.VirtualMachineInstanceMigration) (*v1.VirtualMachineInstanceMigration, error) - Delete(name string, options *k8smetav1.DeleteOptions) error - Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstanceMigration, err error) -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt_test_utils.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt_test_utils.go deleted file mode 100644 index 398b0594d..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/kubevirt_test_utils.go +++ /dev/null @@ -1,57 +0,0 @@ -package kubecli - -import ( - "errors" - - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/tools/clientcmd" - - "kubevirt.io/kubevirt/pkg/api/v1" -) - -// GetMockKubevirtClientFromClientConfig, MockKubevirtClientInstance are used to create a mechanism -// for overriding the actual kubevirt client access. This is useful when the unit tested code invokes GetKubevirtClientFromClientConfig() -// and therefore the unit test code cannot generate the mock client directly. In such a case following steps are needed: -// (1) Override the GetKubevirtClientFromClientConfig() closure with GetMockKubevirtClientFromClientConfig() or -// GetInvalidKubevirtClientFromClientConfig() -// (2) Then create the instance of the client, and assign into MockKubevirtClientInstance before the tests start: -// ctrl := gomock.NewController(GinkgoT()) -// kubecli.MockKubevirtClientInstance = kubecli.NewMockKubevirtClient(ctrl) -// (3) Rest of the kubevirt mocking is automatically generated in generated_mock_kubevirt.go - -// MockKubevirtClientInstance is a reference to the kubevirt client that could be manipulated by the test code -var MockKubevirtClientInstance *MockKubevirtClient - -// GetMockKubevirtClientFromClientConfig is an entry point for testing, could be used to override GetKubevirtClientFromClientConfig -func GetMockKubevirtClientFromClientConfig(cmdConfig clientcmd.ClientConfig) (KubevirtClient, error) { - return MockKubevirtClientInstance, nil -} - -// GetInvalidKubevirtClientFromClientConfig is an entry point for testing case where client should be invalid -func GetInvalidKubevirtClientFromClientConfig(cmdConfig clientcmd.ClientConfig) (KubevirtClient, error) { - return nil, errors.New("invalid fake client") -} - -func NewMinimalMigration(name string) *v1.VirtualMachineInstanceMigration { - return &v1.VirtualMachineInstanceMigration{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachineInstanceMigration"}, ObjectMeta: k8smetav1.ObjectMeta{Name: name}} -} - -func NewMinimalVM(name string) *v1.VirtualMachine { - return &v1.VirtualMachine{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachine"}, ObjectMeta: k8smetav1.ObjectMeta{Name: name}} -} - -func NewMigrationList(migrations ...v1.VirtualMachineInstanceMigration) *v1.VirtualMachineInstanceMigrationList { - return &v1.VirtualMachineInstanceMigrationList{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachineInstanceMigrationList"}, Items: migrations} -} - -func NewVMList(vms ...v1.VirtualMachine) *v1.VirtualMachineList { - return &v1.VirtualMachineList{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachineList"}, Items: vms} -} - -func NewVirtualMachineInstanceReplicaSetList(rss ...v1.VirtualMachineInstanceReplicaSet) *v1.VirtualMachineInstanceReplicaSetList { - return &v1.VirtualMachineInstanceReplicaSetList{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachineInstanceReplicaSetList"}, Items: rss} -} - -func NewMinimalVirtualMachineInstanceReplicaSet(name string) *v1.VirtualMachineInstanceReplicaSet { - return &v1.VirtualMachineInstanceReplicaSet{TypeMeta: k8smetav1.TypeMeta{APIVersion: v1.GroupVersion.String(), Kind: "VirtualMachineInstanceReplicaSet"}, ObjectMeta: k8smetav1.ObjectMeta{Name: name}} -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/migration.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/migration.go deleted file mode 100644 index 90483d7b1..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/migration.go +++ /dev/null @@ -1,133 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package kubecli - -import ( - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" -) - -func (k *kubevirt) VirtualMachineInstanceMigration(namespace string) VirtualMachineInstanceMigrationInterface { - return &migration{ - restClient: k.restClient, - namespace: namespace, - resource: "virtualmachineinstancemigrations", - } -} - -type migration struct { - restClient *rest.RESTClient - namespace string - resource string -} - -// Create new VirtualMachineInstanceMigration in the cluster to specified namespace -func (o *migration) Create(newMigration *v1.VirtualMachineInstanceMigration) (*v1.VirtualMachineInstanceMigration, error) { - newMigrationResult := &v1.VirtualMachineInstanceMigration{} - err := o.restClient.Post(). - Resource(o.resource). - Namespace(o.namespace). - Body(newMigration). - Do(). - Into(newMigrationResult) - - newMigrationResult.SetGroupVersionKind(v1.VirtualMachineInstanceMigrationGroupVersionKind) - - return newMigrationResult, err -} - -// Get the VirtualMachineInstanceMigration from the cluster by its name and namespace -func (o *migration) Get(name string, options *k8smetav1.GetOptions) (*v1.VirtualMachineInstanceMigration, error) { - newVm := &v1.VirtualMachineInstanceMigration{} - err := o.restClient.Get(). - Resource(o.resource). - Namespace(o.namespace). - Name(name). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(newVm) - - newVm.SetGroupVersionKind(v1.VirtualMachineInstanceMigrationGroupVersionKind) - - return newVm, err -} - -// Update the VirtualMachineInstanceMigration instance in the cluster in given namespace -func (o *migration) Update(migration *v1.VirtualMachineInstanceMigration) (*v1.VirtualMachineInstanceMigration, error) { - updatedVm := &v1.VirtualMachineInstanceMigration{} - err := o.restClient.Put(). - Resource(o.resource). - Namespace(o.namespace). - Name(migration.Name). - Body(migration). - Do(). - Into(updatedVm) - - updatedVm.SetGroupVersionKind(v1.VirtualMachineInstanceMigrationGroupVersionKind) - - return updatedVm, err -} - -// Delete the defined VirtualMachineInstanceMigration in the cluster in defined namespace -func (o *migration) Delete(name string, options *k8smetav1.DeleteOptions) error { - err := o.restClient.Delete(). - Resource(o.resource). - Namespace(o.namespace). - Name(name). - Body(options). - Do(). - Error() - - return err -} - -// List all VirtualMachineInstanceMigrations in given namespace -func (o *migration) List(options *k8smetav1.ListOptions) (*v1.VirtualMachineInstanceMigrationList, error) { - newVmList := &v1.VirtualMachineInstanceMigrationList{} - err := o.restClient.Get(). - Resource(o.resource). - Namespace(o.namespace). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(newVmList) - - for _, migration := range newVmList.Items { - migration.SetGroupVersionKind(v1.VirtualMachineInstanceMigrationGroupVersionKind) - } - - return newVmList, err -} - -func (v *migration) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstanceMigration, err error) { - result = &v1.VirtualMachineInstanceMigration{} - err = v.restClient.Patch(pt). - Namespace(v.namespace). - Resource(v.resource). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return result, err -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/replicaset.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/replicaset.go deleted file mode 100644 index b2336cbbb..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/replicaset.go +++ /dev/null @@ -1,101 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2017 Red Hat, Inc. - * - */ - -package kubecli - -import ( - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" -) - -func (k *kubevirt) ReplicaSet(namespace string) ReplicaSetInterface { - return &rc{k.restClient, namespace, "virtualmachineinstancereplicasets"} -} - -type rc struct { - restClient *rest.RESTClient - namespace string - resource string -} - -func (v *rc) Get(name string, options k8smetav1.GetOptions) (replicaset *v1.VirtualMachineInstanceReplicaSet, err error) { - replicaset = &v1.VirtualMachineInstanceReplicaSet{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(replicaset) - replicaset.SetGroupVersionKind(v1.VirtualMachineInstanceReplicaSetGroupVersionKind) - return -} - -func (v *rc) List(options k8smetav1.ListOptions) (replicasetList *v1.VirtualMachineInstanceReplicaSetList, err error) { - replicasetList = &v1.VirtualMachineInstanceReplicaSetList{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(replicasetList) - for _, replicaset := range replicasetList.Items { - replicaset.SetGroupVersionKind(v1.VirtualMachineInstanceReplicaSetGroupVersionKind) - } - - return -} - -func (v *rc) Create(replicaset *v1.VirtualMachineInstanceReplicaSet) (result *v1.VirtualMachineInstanceReplicaSet, err error) { - result = &v1.VirtualMachineInstanceReplicaSet{} - err = v.restClient.Post(). - Namespace(v.namespace). - Resource(v.resource). - Body(replicaset). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstanceReplicaSetGroupVersionKind) - return -} - -func (v *rc) Update(replicaset *v1.VirtualMachineInstanceReplicaSet) (result *v1.VirtualMachineInstanceReplicaSet, err error) { - result = &v1.VirtualMachineInstanceReplicaSet{} - err = v.restClient.Put(). - Name(replicaset.ObjectMeta.Name). - Namespace(v.namespace). - Resource(v.resource). - Body(replicaset). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstanceReplicaSetGroupVersionKind) - return -} - -func (v *rc) Delete(name string, options *k8smetav1.DeleteOptions) error { - return v.restClient.Delete(). - Namespace(v.namespace). - Resource(v.resource). - Name(name). - Body(options). - Do(). - Error() -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/version.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/version.go deleted file mode 100644 index 4482b17fd..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/version.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package kubecli - -import ( - "encoding/json" - "fmt" - "net/url" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" - "kubevirt.io/kubevirt/pkg/version" -) - -const ( - ApiGroupName = "/apis/" + v1.SubresourceGroupName -) - -func (k *kubevirt) ServerVersion() *ServerVersion { - return &ServerVersion{ - restClient: k.restClient, - resource: "version", - } -} - -type ServerVersion struct { - restClient *rest.RESTClient - resource string -} - -func (v *ServerVersion) Get() (*version.Info, error) { - - var group metav1.APIGroup - // First, find out which version to query - uri := ApiGroupName - result := v.restClient.Get().RequestURI(uri).Do() - if data, err := result.Raw(); err != nil { - connErr, isConnectionErr := err.(*url.Error) - - if isConnectionErr { - return nil, connErr.Err - } - - return nil, err - } else if err = json.Unmarshal(data, &group); err != nil { - return nil, err - } - - // Now, query the preferred version - uri = fmt.Sprintf("/apis/%s/version", group.PreferredVersion.GroupVersion) - var serverInfo version.Info - - result = v.restClient.Get().RequestURI(uri).Do() - if data, err := result.Raw(); err != nil { - connErr, isConnectionErr := err.(*url.Error) - - if isConnectionErr { - return nil, connErr.Err - } - - return nil, err - } else if err = json.Unmarshal(data, &serverInfo); err != nil { - return nil, err - } - return &serverInfo, nil -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vm.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/vm.go deleted file mode 100644 index c3cbd14f2..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vm.go +++ /dev/null @@ -1,133 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package kubecli - -import ( - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" -) - -func (k *kubevirt) VirtualMachine(namespace string) VirtualMachineInterface { - return &vm{ - restClient: k.restClient, - namespace: namespace, - resource: "virtualmachines", - } -} - -type vm struct { - restClient *rest.RESTClient - namespace string - resource string -} - -// Create new VirtualMachine in the cluster to specified namespace -func (o *vm) Create(vm *v1.VirtualMachine) (*v1.VirtualMachine, error) { - newVm := &v1.VirtualMachine{} - err := o.restClient.Post(). - Resource(o.resource). - Namespace(o.namespace). - Body(vm). - Do(). - Into(newVm) - - newVm.SetGroupVersionKind(v1.VirtualMachineGroupVersionKind) - - return newVm, err -} - -// Get the Virtual machine from the cluster by its name and namespace -func (o *vm) Get(name string, options *k8smetav1.GetOptions) (*v1.VirtualMachine, error) { - newVm := &v1.VirtualMachine{} - err := o.restClient.Get(). - Resource(o.resource). - Namespace(o.namespace). - Name(name). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(newVm) - - newVm.SetGroupVersionKind(v1.VirtualMachineGroupVersionKind) - - return newVm, err -} - -// Update the VirtualMachine instance in the cluster in given namespace -func (o *vm) Update(vm *v1.VirtualMachine) (*v1.VirtualMachine, error) { - updatedVm := &v1.VirtualMachine{} - err := o.restClient.Put(). - Resource(o.resource). - Namespace(o.namespace). - Name(vm.Name). - Body(vm). - Do(). - Into(updatedVm) - - updatedVm.SetGroupVersionKind(v1.VirtualMachineGroupVersionKind) - - return updatedVm, err -} - -// Delete the defined VirtualMachine in the cluster in defined namespace -func (o *vm) Delete(name string, options *k8smetav1.DeleteOptions) error { - err := o.restClient.Delete(). - Resource(o.resource). - Namespace(o.namespace). - Name(name). - Body(options). - Do(). - Error() - - return err -} - -// List all VirtualMachines in given namespace -func (o *vm) List(options *k8smetav1.ListOptions) (*v1.VirtualMachineList, error) { - newVmList := &v1.VirtualMachineList{} - err := o.restClient.Get(). - Resource(o.resource). - Namespace(o.namespace). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(newVmList) - - for _, vm := range newVmList.Items { - vm.SetGroupVersionKind(v1.VirtualMachineGroupVersionKind) - } - - return newVmList, err -} - -func (v *vm) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachine, err error) { - result = &v1.VirtualMachine{} - err = v.restClient.Patch(pt). - Namespace(v.namespace). - Resource(v.resource). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return result, err -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmi.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmi.go deleted file mode 100644 index 6084397a4..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmi.go +++ /dev/null @@ -1,440 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2017 Red Hat, Inc. - * - */ - -package kubecli - -import ( - "bytes" - "fmt" - "io" - "net/http" - "net/url" - "time" - - "github.com/gorilla/websocket" - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" - "kubevirt.io/kubevirt/pkg/util/subresources" -) - -const ( - WebsocketMessageBufferSize = 10240 -) - -func (k *kubevirt) VirtualMachineInstance(namespace string) VirtualMachineInstanceInterface { - return &vmis{ - restClient: k.restClient, - config: k.config, - clientSet: k.Clientset, - namespace: namespace, - resource: "virtualmachineinstances", - } -} - -type vmis struct { - restClient *rest.RESTClient - config *rest.Config - clientSet *kubernetes.Clientset - namespace string - resource string - master string - kubeconfig string -} - -type BinaryReadWriter struct { - Conn *websocket.Conn -} - -func (s *BinaryReadWriter) Write(p []byte) (int, error) { - wsFrameHeaderSize := 2 + 8 + 4 // Fixed header + length + mask (RFC 6455) - // our websocket package has an issue where it truncates messages - // when the message+header is greater than the buffer size we allocate. - // because of this, we have to chunk messages - chunkSize := WebsocketMessageBufferSize - wsFrameHeaderSize - bytesWritten := 0 - - for i := 0; i < len(p); i += chunkSize { - w, err := s.Conn.NextWriter(websocket.BinaryMessage) - if err != nil { - return bytesWritten, s.err(err) - } - defer w.Close() - - end := i + chunkSize - if end > len(p) { - end = len(p) - } - n, err := w.Write(p[i:end]) - if err != nil { - return bytesWritten, err - } - - bytesWritten = n + bytesWritten - } - return bytesWritten, nil - -} - -func (s *BinaryReadWriter) Read(p []byte) (int, error) { - for { - msgType, r, err := s.Conn.NextReader() - if err != nil { - return 0, s.err(err) - } - - switch msgType { - case websocket.BinaryMessage: - n, err := r.Read(p) - return n, s.err(err) - - case websocket.CloseMessage: - return 0, io.EOF - } - } -} - -func (s *BinaryReadWriter) err(err error) error { - if err == nil { - return nil - } - if e, ok := err.(*websocket.CloseError); ok { - if e.Code == websocket.CloseNormalClosure { - return io.EOF - } - } - return err -} - -type RoundTripCallback func(conn *websocket.Conn, resp *http.Response, err error) error - -type WebsocketRoundTripper struct { - Dialer *websocket.Dialer - Do RoundTripCallback -} - -func (d *WebsocketRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { - conn, resp, err := d.Dialer.Dial(r.URL.String(), r.Header) - if err == nil { - defer conn.Close() - } - return resp, d.Do(conn, resp, err) -} - -type asyncWSRoundTripper struct { - Done chan struct{} - Connection chan *websocket.Conn -} - -func (aws *asyncWSRoundTripper) WebsocketCallback(ws *websocket.Conn, resp *http.Response, err error) error { - - if err != nil { - if resp != nil && resp.StatusCode != http.StatusOK { - buf := new(bytes.Buffer) - buf.ReadFrom(resp.Body) - return fmt.Errorf("Can't connect to websocket (%d): %s\n", resp.StatusCode, buf.String()) - } - return fmt.Errorf("Can't connect to websocket: %s\n", err.Error()) - } - aws.Connection <- ws - - // Keep the roundtripper open until we are done with the stream - <-aws.Done - return nil -} - -func roundTripperFromConfig(config *rest.Config, callback RoundTripCallback) (http.RoundTripper, error) { - - // Configure TLS - tlsConfig, err := rest.TLSConfigFor(config) - if err != nil { - return nil, err - } - - // Configure the websocket dialer - dialer := &websocket.Dialer{ - Proxy: http.ProxyFromEnvironment, - TLSClientConfig: tlsConfig, - WriteBufferSize: WebsocketMessageBufferSize, - ReadBufferSize: WebsocketMessageBufferSize, - Subprotocols: []string{subresources.PlainStreamProtocolName}, - } - - // Create a roundtripper which will pass in the final underlying websocket connection to a callback - rt := &WebsocketRoundTripper{ - Do: callback, - Dialer: dialer, - } - - // Make sure we inherit all relevant security headers - return rest.HTTPWrappersForConfig(config, rt) -} - -func RequestFromConfig(config *rest.Config, vmi string, namespace string, resource string) (*http.Request, error) { - - u, err := url.Parse(config.Host) - if err != nil { - return nil, err - } - - switch u.Scheme { - case "https": - u.Scheme = "wss" - case "http": - u.Scheme = "ws" - default: - return nil, fmt.Errorf("Unsupported Protocol %s", u.Scheme) - } - - u.Path = fmt.Sprintf("/apis/subresources.kubevirt.io/v1alpha2/namespaces/%s/virtualmachineinstances/%s/%s", namespace, vmi, resource) - req := &http.Request{ - Method: http.MethodGet, - URL: u, - } - - return req, nil -} - -type wsStreamer struct { - conn *websocket.Conn - done chan struct{} -} - -func (ws *wsStreamer) streamDone() { - close(ws.done) -} - -func (ws *wsStreamer) Stream(options StreamOptions) error { - wsReadWriter := &BinaryReadWriter{Conn: ws.conn} - - copyErr := make(chan error, 1) - - go func() { - _, err := io.Copy(wsReadWriter, options.In) - copyErr <- err - }() - - go func() { - _, err := io.Copy(options.Out, wsReadWriter) - copyErr <- err - }() - - defer ws.streamDone() - return <-copyErr -} - -func (v *vmis) VNC(name string) (StreamInterface, error) { - return v.asyncSubresourceHelper(name, "vnc") -} - -type connectionStruct struct { - con StreamInterface - err error -} - -func (v *vmis) SerialConsole(name string, timeout time.Duration) (StreamInterface, error) { - timeoutChan := time.Tick(timeout) - connectionChan := make(chan connectionStruct) - isWaiting := true - - go func() { - con, err := v.asyncSubresourceHelper(name, "console") - for err != nil && isWaiting { - if asyncSubresourceError, ok := err.(*AsyncSubresourceError); ok { - if asyncSubresourceError.GetStatusCode() == http.StatusBadRequest { - // Sleep to prevent denial of service on the api server - time.Sleep(1 * time.Second) - con, err = v.asyncSubresourceHelper(name, "console") - } else { - connectionChan <- connectionStruct{con: nil, err: asyncSubresourceError} - return - } - } else { - connectionChan <- connectionStruct{con: nil, err: err} - return - } - } - if isWaiting { - connectionChan <- connectionStruct{con: con, err: nil} - } - }() - - select { - case <-timeoutChan: - isWaiting = false - return nil, fmt.Errorf("Timeout trying to connect to the virtual machine instance") - case conStruct := <-connectionChan: - return conStruct.con, conStruct.err - } -} - -type AsyncSubresourceError struct { - err string - StatusCode int -} - -func (a *AsyncSubresourceError) Error() string { - return a.err -} - -func (a *AsyncSubresourceError) GetStatusCode() int { - return a.StatusCode -} - -func (v *vmis) asyncSubresourceHelper(name string, resource string) (StreamInterface, error) { - - done := make(chan struct{}) - - aws := &asyncWSRoundTripper{ - Connection: make(chan *websocket.Conn), - Done: done, - } - // Create a round tripper with all necessary kubernetes security details - wrappedRoundTripper, err := roundTripperFromConfig(v.config, aws.WebsocketCallback) - if err != nil { - return nil, fmt.Errorf("unable to create round tripper for remote execution: %v", err) - } - - // Create a request out of config and the query parameters - req, err := RequestFromConfig(v.config, name, v.namespace, resource) - if err != nil { - return nil, fmt.Errorf("unable to create request for remote execution: %v", err) - } - - errChan := make(chan error, 1) - - go func() { - // Send the request and let the callback do its work - response, err := wrappedRoundTripper.RoundTrip(req) - - if err != nil { - statusCode := 0 - if response != nil { - statusCode = response.StatusCode - } - errChan <- &AsyncSubresourceError{err: err.Error(), StatusCode: statusCode} - return - } - - if response != nil { - switch response.StatusCode { - case http.StatusOK: - case http.StatusNotFound: - err = &AsyncSubresourceError{err: "Virtual Machine not found.", StatusCode: response.StatusCode} - case http.StatusInternalServerError: - err = &AsyncSubresourceError{err: "Websocket failed due to internal server error.", StatusCode: response.StatusCode} - default: - err = &AsyncSubresourceError{err: fmt.Sprintf("Websocket failed with http status: %s", response.Status), StatusCode: response.StatusCode} - } - } else { - err = &AsyncSubresourceError{err: "no response received"} - } - errChan <- err - }() - - select { - case err = <-errChan: - return nil, err - case ws := <-aws.Connection: - return &wsStreamer{ - conn: ws, - done: done, - }, nil - } -} - -func (v *vmis) Get(name string, options *k8smetav1.GetOptions) (vmi *v1.VirtualMachineInstance, err error) { - vmi = &v1.VirtualMachineInstance{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - Name(name). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(vmi) - vmi.SetGroupVersionKind(v1.VirtualMachineInstanceGroupVersionKind) - return -} - -func (v *vmis) List(options *k8smetav1.ListOptions) (vmiList *v1.VirtualMachineInstanceList, err error) { - vmiList = &v1.VirtualMachineInstanceList{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - VersionedParams(options, scheme.ParameterCodec). - Do(). - Into(vmiList) - for _, vmi := range vmiList.Items { - vmi.SetGroupVersionKind(v1.VirtualMachineInstanceGroupVersionKind) - } - - return -} - -func (v *vmis) Create(vmi *v1.VirtualMachineInstance) (result *v1.VirtualMachineInstance, err error) { - result = &v1.VirtualMachineInstance{} - err = v.restClient.Post(). - Namespace(v.namespace). - Resource(v.resource). - Body(vmi). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstanceGroupVersionKind) - return -} - -func (v *vmis) Update(vmi *v1.VirtualMachineInstance) (result *v1.VirtualMachineInstance, err error) { - result = &v1.VirtualMachineInstance{} - err = v.restClient.Put(). - Name(vmi.ObjectMeta.Name). - Namespace(v.namespace). - Resource(v.resource). - Body(vmi). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstanceGroupVersionKind) - return -} - -func (v *vmis) Delete(name string, options *k8smetav1.DeleteOptions) error { - return v.restClient.Delete(). - Namespace(v.namespace). - Resource(v.resource). - Name(name). - Body(options). - Do(). - Error() -} - -func (v *vmis) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstance, err error) { - result = &v1.VirtualMachineInstance{} - err = v.restClient.Patch(pt). - Namespace(v.namespace). - Resource(v.resource). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmpreset.go b/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmpreset.go deleted file mode 100644 index 9edf8dcb8..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/kubecli/vmpreset.go +++ /dev/null @@ -1,115 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2017 Red Hat, Inc. - * - */ - -package kubecli - -import ( - k8smetav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" - - "kubevirt.io/kubevirt/pkg/api/v1" -) - -func (k *kubevirt) VMIPreset(namespace string) VMIPresetInterface { - return &vmiPresets{k.restClient, namespace, "virtualmachineinstancepresets"} -} - -type vmiPresets struct { - restClient *rest.RESTClient - namespace string - resource string -} - -func (v *vmiPresets) Get(name string, options k8smetav1.GetOptions) (vmi *v1.VirtualMachineInstancePreset, err error) { - vmi = &v1.VirtualMachineInstancePreset{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - Name(name). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(vmi) - vmi.SetGroupVersionKind(v1.VirtualMachineInstancePresetGroupVersionKind) - return -} - -func (v *vmiPresets) List(options k8smetav1.ListOptions) (vmiList *v1.VirtualMachineInstancePresetList, err error) { - vmiList = &v1.VirtualMachineInstancePresetList{} - err = v.restClient.Get(). - Resource(v.resource). - Namespace(v.namespace). - VersionedParams(&options, scheme.ParameterCodec). - Do(). - Into(vmiList) - for _, vmi := range vmiList.Items { - vmi.SetGroupVersionKind(v1.VirtualMachineInstancePresetGroupVersionKind) - } - - return -} - -func (v *vmiPresets) Create(vmi *v1.VirtualMachineInstancePreset) (result *v1.VirtualMachineInstancePreset, err error) { - result = &v1.VirtualMachineInstancePreset{} - err = v.restClient.Post(). - Namespace(v.namespace). - Resource(v.resource). - Body(vmi). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstancePresetGroupVersionKind) - return -} - -func (v *vmiPresets) Update(vmi *v1.VirtualMachineInstancePreset) (result *v1.VirtualMachineInstancePreset, err error) { - result = &v1.VirtualMachineInstancePreset{} - err = v.restClient.Put(). - Name(vmi.ObjectMeta.Name). - Namespace(v.namespace). - Resource(v.resource). - Body(vmi). - Do(). - Into(result) - result.SetGroupVersionKind(v1.VirtualMachineInstancePresetGroupVersionKind) - return -} - -func (v *vmiPresets) Delete(name string, options *k8smetav1.DeleteOptions) error { - return v.restClient.Delete(). - Namespace(v.namespace). - Resource(v.resource). - Name(name). - Body(options). - Do(). - Error() -} - -func (v *vmiPresets) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.VirtualMachineInstancePreset, err error) { - result = &v1.VirtualMachineInstancePreset{} - err = v.restClient.Patch(pt). - Namespace(v.namespace). - Resource(v.resource). - SubResource(subresources...). - Name(name). - Body(data). - Do(). - Into(result) - return -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/util/subresources/constants.go b/vendor/kubevirt.io/kubevirt/pkg/util/subresources/constants.go deleted file mode 100644 index d60d224ab..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/util/subresources/constants.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 The KubeVirt Authors - * - */ - -package subresources - -// PlainStreamProtocolName is a subprotocol which indicates a plain websocket stream. -// Mostly useful for browser connections which need to use the websocket subprotocol -// field to pass credentials. As a consequence they need to get a subprotocol back. -const PlainStreamProtocolName = "plain.kubevirt.io" diff --git a/vendor/kubevirt.io/kubevirt/pkg/version/base.go b/vendor/kubevirt.io/kubevirt/pkg/version/base.go deleted file mode 100644 index bd933defa..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/version/base.go +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package version - -var ( - gitVersion = "v0.0.0-master+$Format:%h$" - gitCommit = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) - gitTreeState = "" // state of git tree, either "clean" or "dirty" - - buildDate = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') -) diff --git a/vendor/kubevirt.io/kubevirt/pkg/version/types.go b/vendor/kubevirt.io/kubevirt/pkg/version/types.go deleted file mode 100644 index e90fb07d5..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/version/types.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ -package version - -type Info struct { - GitVersion string `json:"gitVersion"` - GitCommit string `json:"gitCommit"` - GitTreeState string `json:"gitTreeState"` - BuildDate string `json:"buildDate"` - GoVersion string `json:"goVersion"` - Compiler string `json:"compiler"` - Platform string `json:"platform"` -} - -// String returns info as a human-friendly version string. -func (info Info) String() string { - return info.GitVersion -} diff --git a/vendor/kubevirt.io/kubevirt/pkg/version/version.go b/vendor/kubevirt.io/kubevirt/pkg/version/version.go deleted file mode 100644 index 209a302c9..000000000 --- a/vendor/kubevirt.io/kubevirt/pkg/version/version.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the KubeVirt project - * - * 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. - * - * Copyright 2018 Red Hat, Inc. - * - */ - -package version - -import ( - "fmt" - "runtime" -) - -func Get() Info { - return Info{ - GitVersion: gitVersion, - GitCommit: gitCommit, - GitTreeState: gitTreeState, - BuildDate: buildDate, - GoVersion: runtime.Version(), - Compiler: runtime.Compiler, - Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), - } -}