diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 0000000..6b9210e --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,37 @@ +### 정리전 (서버용, 클라이언트용) + +아래 링크에서 후반부에서 빌드 참고.(서버 설치) +- https://podman.io/getting-started/installation + +빌드가 다 되면, 바이러니들을 /usr/local/bin 옮겨놓는다. + +바인딩할려면(바인딩도 결국 클라이언트이니까???) 소켓을 활성화 시켜야 한다.(클라이언트 설치) +아래 링크에서, +"systemctl --user enable --now podman.socket" +이 부분을 참고하자. rootless 임. + +- https://github.com/containers/podman/blob/main/docs/tutorials/remote_client.md +- https://github.com/containers/podman/tree/main/pkg/bindings + +그런다음에 +systemctl start podman.socket (rootful) + +또는 + +systemctl start --user podman.socket (rootless) + +기타, 3.x 설치후 여러 경험을 지운 후 문제점들. +apt purge 로 지워서 세팅들을 모두 날려야 한다. 안그럼 예전게 남아 에러 발생 + +User-selected graph driver "overlay" overwritten by graph driver "vfs" from database - delete libpod local files to resolve +발생시 + +https://github.com/containers/podman/issues/5114 +그냥 db 를 지우거나 세팅을 지우면 됨. + +- sudo rm -rf ~/.local/share/containers/ +- rm /var/lib/containers/storage/libpod/bolt_state.db + +### podman 상태 +- podman --remote info +- https://www.redhat.com/sysadmin/container-information-podman \ No newline at end of file diff --git a/README.md b/README.md index 50c5706..b256540 100644 --- a/README.md +++ b/README.md @@ -587,7 +587,7 @@ a process: ##### 5/15 일 할일 pod 로 연결된 container 들 에서 volume mount 하고 -- 그런데 네임스페이스에 마운트도 있다. 이경우 마운트도 share 되는지 확인해보자. +- 그런데 네임스페이스에 마운트도 있다. 이경우 마운트도 share 되는지 확인해보자. 관련 자료 읽어복 해당 내용 파악하자. 그리고 4.x 설치 부분도 살펴보자. - https://docs.podman.io/en/latest/markdown/podman-pod-create.1.html 여기서 mount 관련해서 찾아보자. - https://kubernetes.io/ko/docs/tasks/access-application-cluster/communicate-containers-same-pod-shared-volume/ diff --git a/examples/go.mod b/examples/go.mod deleted file mode 100644 index e7d2974..0000000 --- a/examples/go.mod +++ /dev/null @@ -1,113 +0,0 @@ -module github.com/seoyhaein/podman-document/examples - -go 1.18 - -require github.com/containers/podman/v3 v3.4.7 - -require ( - github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/BurntSushi/toml v0.4.1 // indirect - github.com/Microsoft/go-winio v0.5.0 // indirect - github.com/Microsoft/hcsshim v0.8.22 // indirect - github.com/VividCortex/ewma v1.2.0 // indirect - github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect - github.com/beorn7/perks v1.0.1 // indirect - github.com/blang/semver v3.5.1+incompatible // indirect - github.com/cespare/xxhash/v2 v2.1.1 // indirect - github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect - github.com/containerd/cgroups v1.0.1 // indirect - github.com/containerd/containerd v1.5.7 // indirect - github.com/containerd/stargz-snapshotter/estargz v0.9.0 // indirect - github.com/containernetworking/cni v0.8.1 // indirect - github.com/containernetworking/plugins v0.9.1 // indirect - github.com/containers/buildah v1.23.1 // indirect - github.com/containers/common v0.44.5 // indirect - github.com/containers/image/v5 v5.17.0 // indirect - github.com/containers/libtrust v0.0.0-20190913040956-14b96171aa3b // indirect - github.com/containers/ocicrypt v1.1.2 // indirect - github.com/containers/psgo v1.7.2-0.20220414132323-3ae304491648 // indirect - github.com/containers/storage v1.37.2 // indirect - github.com/coreos/go-systemd/v22 v22.3.2 // indirect - github.com/cri-o/ocicni v0.2.1-0.20210621164014-d0acc7862283 // indirect - github.com/cyphar/filepath-securejoin v0.2.3 // indirect - github.com/disiqueira/gotree/v3 v3.0.2 // indirect - github.com/docker/distribution v2.7.1+incompatible // indirect - github.com/docker/docker v20.10.11+incompatible // indirect - github.com/docker/docker-credential-helpers v0.6.4 // indirect - github.com/docker/go-connections v0.4.0 // indirect - github.com/docker/go-metrics v0.0.1 // indirect - github.com/docker/go-units v0.4.0 // indirect - github.com/fsnotify/fsnotify v1.5.1 // indirect - github.com/ghodss/yaml v1.0.0 // indirect - github.com/godbus/dbus/v5 v5.0.6 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/google/go-intervals v0.0.2 // indirect - github.com/google/uuid v1.3.0 // indirect - github.com/gorilla/mux v1.8.0 // indirect - github.com/gorilla/schema v1.2.0 // indirect - github.com/hashicorp/errwrap v1.0.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hpcloud/tail v1.0.0 // indirect - github.com/imdario/mergo v0.3.12 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jinzhu/copier v0.3.2 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.13.6 // indirect - github.com/klauspost/pgzip v1.2.5 // indirect - github.com/manifoldco/promptui v0.9.0 // indirect - github.com/mattn/go-runewidth v0.0.13 // indirect - github.com/mattn/go-shellwords v1.0.12 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect - github.com/miekg/pkcs11 v1.0.3 // indirect - github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible // indirect - github.com/moby/sys/mountinfo v0.4.1 // indirect - github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/mtrmac/gpgme v0.1.2 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.0.2-0.20210819154149-5ad6f50d6283 // indirect - github.com/opencontainers/runc v1.0.2 // indirect - github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 // indirect - github.com/opencontainers/runtime-tools v0.9.0 // indirect - github.com/opencontainers/selinux v1.9.1 // indirect - github.com/ostreedev/ostree-go v0.0.0-20190702140239-759a8c1ac913 // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/prometheus/client_golang v1.11.1 // indirect - github.com/prometheus/client_model v0.2.0 // indirect - github.com/prometheus/common v0.26.0 // indirect - github.com/prometheus/procfs v0.6.0 // indirect - github.com/rivo/uniseg v0.2.0 // indirect - github.com/sirupsen/logrus v1.8.1 // indirect - github.com/spf13/cobra v1.2.1 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980 // indirect - github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 // indirect - github.com/tchap/go-patricia v2.3.0+incompatible // indirect - github.com/ulikunitz/xz v0.5.10 // indirect - github.com/vbatts/tar-split v0.11.2 // indirect - github.com/vbauerster/mpb/v7 v7.1.5 // indirect - github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852 // indirect - github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190809123943-df4f5c81cb3b // indirect - github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect - github.com/xeipuuv/gojsonschema v1.2.0 // indirect - go.etcd.io/bbolt v1.3.6 // indirect - go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1 // indirect - go.opencensus.io v0.23.0 // indirect - golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect - golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect - golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 // indirect - golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect - golang.org/x/text v0.3.7 // indirect - google.golang.org/genproto v0.0.0-20211005153810-c76a74d43a8e // indirect - google.golang.org/grpc v1.41.0 // indirect - google.golang.org/protobuf v1.27.1 // indirect - gopkg.in/fsnotify.v1 v1.4.7 // indirect - gopkg.in/square/go-jose.v2 v2.5.1 // indirect - gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect -) diff --git a/examples/main.go b/examples/main.go_ similarity index 100% rename from examples/main.go rename to examples/main.go_ diff --git a/examples/vendor/github.com/BurntSushi/toml/deprecated.go b/examples/vendor/github.com/BurntSushi/toml/deprecated.go deleted file mode 100644 index db89eac..0000000 --- a/examples/vendor/github.com/BurntSushi/toml/deprecated.go +++ /dev/null @@ -1,33 +0,0 @@ -package toml - -import ( - "encoding" - "io" -) - -// DEPRECATED! -// -// Use the identical encoding.TextMarshaler instead. It is defined here to -// support Go 1.1 and older. -type TextMarshaler encoding.TextMarshaler - -// DEPRECATED! -// -// Use the identical encoding.TextUnmarshaler instead. It is defined here to -// support Go 1.1 and older. -type TextUnmarshaler encoding.TextUnmarshaler - -// DEPRECATED! -// -// Use MetaData.PrimitiveDecode instead. -func PrimitiveDecode(primValue Primitive, v interface{}) error { - md := MetaData{decoded: make(map[string]bool)} - return md.unify(primValue.undecoded, rvalue(v)) -} - -// DEPRECATED! -// -// Use NewDecoder(reader).Decode(&v) instead. -func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { - return NewDecoder(r).Decode(v) -} diff --git a/examples/vendor/github.com/Microsoft/go-winio/README.md b/examples/vendor/github.com/Microsoft/go-winio/README.md deleted file mode 100644 index 60c93fe..0000000 --- a/examples/vendor/github.com/Microsoft/go-winio/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# go-winio [![Build Status](https://github.com/microsoft/go-winio/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/go-winio/actions/workflows/ci.yml) - -This repository contains utilities for efficiently performing Win32 IO operations in -Go. Currently, this is focused on accessing named pipes and other file handles, and -for using named pipes as a net transport. - -This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go -to reuse the thread to schedule another goroutine. This limits support to Windows Vista and -newer operating systems. This is similar to the implementation of network sockets in Go's net -package. - -Please see the LICENSE file for licensing information. - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. - -Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe -for another named pipe implementation. diff --git a/examples/vendor/github.com/Microsoft/hcsshim/.gitignore b/examples/vendor/github.com/Microsoft/hcsshim/.gitignore deleted file mode 100644 index aec9bd4..0000000 --- a/examples/vendor/github.com/Microsoft/hcsshim/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.exe -.idea -.vscode diff --git a/examples/vendor/github.com/Microsoft/hcsshim/README.md b/examples/vendor/github.com/Microsoft/hcsshim/README.md deleted file mode 100644 index 95c3003..0000000 --- a/examples/vendor/github.com/Microsoft/hcsshim/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# hcsshim - -[![Build status](https://github.com/microsoft/hcsshim/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/microsoft/hcsshim/actions?query=branch%3Amaster) - -This package contains the Golang interface for using the Windows [Host Compute Service](https://techcommunity.microsoft.com/t5/containers/introducing-the-host-compute-service-hcs/ba-p/382332) (HCS) to launch and manage [Windows Containers](https://docs.microsoft.com/en-us/virtualization/windowscontainers/about/). It also contains other helpers and functions for managing Windows Containers such as the Golang interface for the Host Network Service (HNS). - -It is primarily used in the [Moby Project](https://github.com/moby/moby), but it can be freely used by other projects as well. - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require you to agree to a -Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us -the rights to use your contribution. For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. - -We also ask that contributors [sign their commits](https://git-scm.com/docs/git-commit) using `git commit -s` or `git commit --signoff` to certify they either authored the work themselves or otherwise have permission to use it in this project. - - -## Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -## Dependencies - -This project requires Golang 1.9 or newer to build. - -For system requirements to run this project, see the Microsoft docs on [Windows Container requirements](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/system-requirements). - -## Reporting Security Issues - -Security issues and bugs should be reported privately, via email, to the Microsoft Security -Response Center (MSRC) at [secure@microsoft.com](mailto:secure@microsoft.com). You should -receive a response within 24 hours. If for some reason you do not, please follow up via -email to ensure we received your original message. Further information, including the -[MSRC PGP](https://technet.microsoft.com/en-us/security/dn606155) key, can be found in -the [Security TechCenter](https://technet.microsoft.com/en-us/security/default). - -For additional details, see [Report a Computer Security Vulnerability](https://technet.microsoft.com/en-us/security/ff852094.aspx) on Technet - ---------------- -Copyright (c) 2018 Microsoft Corp. All rights reserved. diff --git a/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go b/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go deleted file mode 100644 index 83f7040..0000000 --- a/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go +++ /dev/null @@ -1,27 +0,0 @@ -package winapi - -// VOID RtlMoveMemory( -// _Out_ VOID UNALIGNED *Destination, -// _In_ const VOID UNALIGNED *Source, -// _In_ SIZE_T Length -// ); -//sys RtlMoveMemory(destination *byte, source *byte, length uintptr) (err error) = kernel32.RtlMoveMemory - -//sys LocalAlloc(flags uint32, size int) (ptr uintptr) = kernel32.LocalAlloc -//sys LocalFree(ptr uintptr) = kernel32.LocalFree - -// BOOL QueryWorkingSet( -// HANDLE hProcess, -// PVOID pv, -// DWORD cb -// ); -//sys QueryWorkingSet(handle windows.Handle, pv uintptr, cb uint32) (err error) = psapi.QueryWorkingSet - -type PSAPI_WORKING_SET_INFORMATION struct { - NumberOfEntries uintptr - WorkingSetInfo [1]PSAPI_WORKING_SET_BLOCK -} - -type PSAPI_WORKING_SET_BLOCK struct { - Flags uintptr -} diff --git a/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go b/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go deleted file mode 100644 index b870683..0000000 --- a/examples/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go +++ /dev/null @@ -1,10 +0,0 @@ -package winapi - -const PROCESS_ALL_ACCESS uint32 = 2097151 - -// DWORD GetProcessImageFileNameW( -// HANDLE hProcess, -// LPWSTR lpImageFileName, -// DWORD nSize -// ); -//sys GetProcessImageFileName(hProcess windows.Handle, imageFileName *uint16, nSize uint32) (size uint32, err error) = kernel32.GetProcessImageFileNameW diff --git a/examples/vendor/github.com/cespare/xxhash/v2/.travis.yml b/examples/vendor/github.com/cespare/xxhash/v2/.travis.yml deleted file mode 100644 index c516ea8..0000000 --- a/examples/vendor/github.com/cespare/xxhash/v2/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: go -go: - - "1.x" - - master -env: - - TAGS="" - - TAGS="-tags purego" -script: go test $TAGS -v ./... diff --git a/examples/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go b/examples/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go deleted file mode 100644 index 53bf76e..0000000 --- a/examples/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build !appengine - -// This file encapsulates usage of unsafe. -// xxhash_safe.go contains the safe implementations. - -package xxhash - -import ( - "reflect" - "unsafe" -) - -// Notes: -// -// See https://groups.google.com/d/msg/golang-nuts/dcjzJy-bSpw/tcZYBzQqAQAJ -// for some discussion about these unsafe conversions. -// -// In the future it's possible that compiler optimizations will make these -// unsafe operations unnecessary: https://golang.org/issue/2205. -// -// Both of these wrapper functions still incur function call overhead since they -// will not be inlined. We could write Go/asm copies of Sum64 and Digest.Write -// for strings to squeeze out a bit more speed. Mid-stack inlining should -// eventually fix this. - -// Sum64String computes the 64-bit xxHash digest of s. -// It may be faster than Sum64([]byte(s)) by avoiding a copy. -func Sum64String(s string) uint64 { - var b []byte - bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data - bh.Len = len(s) - bh.Cap = len(s) - return Sum64(b) -} - -// WriteString adds more data to d. It always returns len(s), nil. -// It may be faster than Write([]byte(s)) by avoiding a copy. -func (d *Digest) WriteString(s string) (n int, err error) { - var b []byte - bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) - bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data - bh.Len = len(s) - bh.Cap = len(s) - return d.Write(b) -} diff --git a/examples/vendor/github.com/containernetworking/cni/LICENSE b/examples/vendor/github.com/containernetworking/cni/LICENSE deleted file mode 100644 index 8f71f43..0000000 --- a/examples/vendor/github.com/containernetworking/cni/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/examples/vendor/github.com/containernetworking/cni/libcni/api.go b/examples/vendor/github.com/containernetworking/cni/libcni/api.go deleted file mode 100644 index 7e52bd8..0000000 --- a/examples/vendor/github.com/containernetworking/cni/libcni/api.go +++ /dev/null @@ -1,673 +0,0 @@ -// Copyright 2015 CNI 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 libcni - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/containernetworking/cni/pkg/invoke" - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/utils" - "github.com/containernetworking/cni/pkg/version" -) - -var ( - CacheDir = "/var/lib/cni" -) - -const ( - CNICacheV1 = "cniCacheV1" -) - -// A RuntimeConf holds the arguments to one invocation of a CNI plugin -// excepting the network configuration, with the nested exception that -// the `runtimeConfig` from the network configuration is included -// here. -type RuntimeConf struct { - ContainerID string - NetNS string - IfName string - Args [][2]string - // A dictionary of capability-specific data passed by the runtime - // to plugins as top-level keys in the 'runtimeConfig' dictionary - // of the plugin's stdin data. libcni will ensure that only keys - // in this map which match the capabilities of the plugin are passed - // to the plugin - CapabilityArgs map[string]interface{} - - // DEPRECATED. Will be removed in a future release. - CacheDir string -} - -type NetworkConfig struct { - Network *types.NetConf - Bytes []byte -} - -type NetworkConfigList struct { - Name string - CNIVersion string - DisableCheck bool - Plugins []*NetworkConfig - Bytes []byte -} - -type CNI interface { - AddNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) (types.Result, error) - CheckNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error - DelNetworkList(ctx context.Context, net *NetworkConfigList, rt *RuntimeConf) error - GetNetworkListCachedResult(net *NetworkConfigList, rt *RuntimeConf) (types.Result, error) - GetNetworkListCachedConfig(net *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) - - AddNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) (types.Result, error) - CheckNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error - DelNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error - GetNetworkCachedResult(net *NetworkConfig, rt *RuntimeConf) (types.Result, error) - GetNetworkCachedConfig(net *NetworkConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) - - ValidateNetworkList(ctx context.Context, net *NetworkConfigList) ([]string, error) - ValidateNetwork(ctx context.Context, net *NetworkConfig) ([]string, error) -} - -type CNIConfig struct { - Path []string - exec invoke.Exec - cacheDir string -} - -// CNIConfig implements the CNI interface -var _ CNI = &CNIConfig{} - -// NewCNIConfig returns a new CNIConfig object that will search for plugins -// in the given paths and use the given exec interface to run those plugins, -// or if the exec interface is not given, will use a default exec handler. -func NewCNIConfig(path []string, exec invoke.Exec) *CNIConfig { - return NewCNIConfigWithCacheDir(path, "", exec) -} - -// NewCNIConfigWithCacheDir returns a new CNIConfig object that will search for plugins -// in the given paths use the given exec interface to run those plugins, -// or if the exec interface is not given, will use a default exec handler. -// The given cache directory will be used for temporary data storage when needed. -func NewCNIConfigWithCacheDir(path []string, cacheDir string, exec invoke.Exec) *CNIConfig { - return &CNIConfig{ - Path: path, - cacheDir: cacheDir, - exec: exec, - } -} - -func buildOneConfig(name, cniVersion string, orig *NetworkConfig, prevResult types.Result, rt *RuntimeConf) (*NetworkConfig, error) { - var err error - - inject := map[string]interface{}{ - "name": name, - "cniVersion": cniVersion, - } - // Add previous plugin result - if prevResult != nil { - inject["prevResult"] = prevResult - } - - // Ensure every config uses the same name and version - orig, err = InjectConf(orig, inject) - if err != nil { - return nil, err - } - - return injectRuntimeConfig(orig, rt) -} - -// This function takes a libcni RuntimeConf structure and injects values into -// a "runtimeConfig" dictionary in the CNI network configuration JSON that -// will be passed to the plugin on stdin. -// -// Only "capabilities arguments" passed by the runtime are currently injected. -// These capabilities arguments are filtered through the plugin's advertised -// capabilities from its config JSON, and any keys in the CapabilityArgs -// matching plugin capabilities are added to the "runtimeConfig" dictionary -// sent to the plugin via JSON on stdin. For example, if the plugin's -// capabilities include "portMappings", and the CapabilityArgs map includes a -// "portMappings" key, that key and its value are added to the "runtimeConfig" -// dictionary to be passed to the plugin's stdin. -func injectRuntimeConfig(orig *NetworkConfig, rt *RuntimeConf) (*NetworkConfig, error) { - var err error - - rc := make(map[string]interface{}) - for capability, supported := range orig.Network.Capabilities { - if !supported { - continue - } - if data, ok := rt.CapabilityArgs[capability]; ok { - rc[capability] = data - } - } - - if len(rc) > 0 { - orig, err = InjectConf(orig, map[string]interface{}{"runtimeConfig": rc}) - if err != nil { - return nil, err - } - } - - return orig, nil -} - -// ensure we have a usable exec if the CNIConfig was not given one -func (c *CNIConfig) ensureExec() invoke.Exec { - if c.exec == nil { - c.exec = &invoke.DefaultExec{ - RawExec: &invoke.RawExec{Stderr: os.Stderr}, - PluginDecoder: version.PluginDecoder{}, - } - } - return c.exec -} - -type cachedInfo struct { - Kind string `json:"kind"` - ContainerID string `json:"containerId"` - Config []byte `json:"config"` - IfName string `json:"ifName"` - NetworkName string `json:"networkName"` - CniArgs [][2]string `json:"cniArgs,omitempty"` - CapabilityArgs map[string]interface{} `json:"capabilityArgs,omitempty"` - RawResult map[string]interface{} `json:"result,omitempty"` - Result types.Result `json:"-"` -} - -// getCacheDir returns the cache directory in this order: -// 1) global cacheDir from CNIConfig object -// 2) deprecated cacheDir from RuntimeConf object -// 3) fall back to default cache directory -func (c *CNIConfig) getCacheDir(rt *RuntimeConf) string { - if c.cacheDir != "" { - return c.cacheDir - } - if rt.CacheDir != "" { - return rt.CacheDir - } - return CacheDir -} - -func (c *CNIConfig) getCacheFilePath(netName string, rt *RuntimeConf) (string, error) { - if netName == "" || rt.ContainerID == "" || rt.IfName == "" { - return "", fmt.Errorf("cache file path requires network name (%q), container ID (%q), and interface name (%q)", netName, rt.ContainerID, rt.IfName) - } - return filepath.Join(c.getCacheDir(rt), "results", fmt.Sprintf("%s-%s-%s", netName, rt.ContainerID, rt.IfName)), nil -} - -func (c *CNIConfig) cacheAdd(result types.Result, config []byte, netName string, rt *RuntimeConf) error { - cached := cachedInfo{ - Kind: CNICacheV1, - ContainerID: rt.ContainerID, - Config: config, - IfName: rt.IfName, - NetworkName: netName, - CniArgs: rt.Args, - CapabilityArgs: rt.CapabilityArgs, - } - - // We need to get type.Result into cachedInfo as JSON map - // Marshal to []byte, then Unmarshal into cached.RawResult - data, err := json.Marshal(result) - if err != nil { - return err - } - - err = json.Unmarshal(data, &cached.RawResult) - if err != nil { - return err - } - - newBytes, err := json.Marshal(&cached) - if err != nil { - return err - } - - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return err - } - if err := os.MkdirAll(filepath.Dir(fname), 0700); err != nil { - return err - } - - return ioutil.WriteFile(fname, newBytes, 0600) -} - -func (c *CNIConfig) cacheDel(netName string, rt *RuntimeConf) error { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - // Ignore error - return nil - } - return os.Remove(fname) -} - -func (c *CNIConfig) getCachedConfig(netName string, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - var bytes []byte - - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, nil, err - } - bytes, err = ioutil.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil, nil - } - - unmarshaled := cachedInfo{} - if err := json.Unmarshal(bytes, &unmarshaled); err != nil { - return nil, nil, fmt.Errorf("failed to unmarshal cached network %q config: %v", netName, err) - } - if unmarshaled.Kind != CNICacheV1 { - return nil, nil, fmt.Errorf("read cached network %q config has wrong kind: %v", netName, unmarshaled.Kind) - } - - newRt := *rt - if unmarshaled.CniArgs != nil { - newRt.Args = unmarshaled.CniArgs - } - newRt.CapabilityArgs = unmarshaled.CapabilityArgs - - return unmarshaled.Config, &newRt, nil -} - -func (c *CNIConfig) getLegacyCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, err - } - data, err := ioutil.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil - } - - // Read the version of the cached result - decoder := version.ConfigDecoder{} - resultCniVersion, err := decoder.Decode(data) - if err != nil { - return nil, err - } - - // Ensure we can understand the result - result, err := version.NewResult(resultCniVersion, data) - if err != nil { - return nil, err - } - - // Convert to the config version to ensure plugins get prevResult - // in the same version as the config. The cached result version - // should match the config version unless the config was changed - // while the container was running. - result, err = result.GetAsVersion(cniVersion) - if err != nil && resultCniVersion != cniVersion { - return nil, fmt.Errorf("failed to convert cached result version %q to config version %q: %v", resultCniVersion, cniVersion, err) - } - return result, err -} - -func (c *CNIConfig) getCachedResult(netName, cniVersion string, rt *RuntimeConf) (types.Result, error) { - fname, err := c.getCacheFilePath(netName, rt) - if err != nil { - return nil, err - } - fdata, err := ioutil.ReadFile(fname) - if err != nil { - // Ignore read errors; the cached result may not exist on-disk - return nil, nil - } - - cachedInfo := cachedInfo{} - if err := json.Unmarshal(fdata, &cachedInfo); err != nil || cachedInfo.Kind != CNICacheV1 { - return c.getLegacyCachedResult(netName, cniVersion, rt) - } - - newBytes, err := json.Marshal(&cachedInfo.RawResult) - if err != nil { - return nil, fmt.Errorf("failed to marshal cached network %q config: %v", netName, err) - } - - // Read the version of the cached result - decoder := version.ConfigDecoder{} - resultCniVersion, err := decoder.Decode(newBytes) - if err != nil { - return nil, err - } - - // Ensure we can understand the result - result, err := version.NewResult(resultCniVersion, newBytes) - if err != nil { - return nil, err - } - - // Convert to the config version to ensure plugins get prevResult - // in the same version as the config. The cached result version - // should match the config version unless the config was changed - // while the container was running. - result, err = result.GetAsVersion(cniVersion) - if err != nil && resultCniVersion != cniVersion { - return nil, fmt.Errorf("failed to convert cached result version %q to config version %q: %v", resultCniVersion, cniVersion, err) - } - return result, err -} - -// GetNetworkListCachedResult returns the cached Result of the previous -// AddNetworkList() operation for a network list, or an error. -func (c *CNIConfig) GetNetworkListCachedResult(list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) { - return c.getCachedResult(list.Name, list.CNIVersion, rt) -} - -// GetNetworkCachedResult returns the cached Result of the previous -// AddNetwork() operation for a network, or an error. -func (c *CNIConfig) GetNetworkCachedResult(net *NetworkConfig, rt *RuntimeConf) (types.Result, error) { - return c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) -} - -// GetNetworkListCachedConfig copies the input RuntimeConf to output -// RuntimeConf with fields updated with info from the cached Config. -func (c *CNIConfig) GetNetworkListCachedConfig(list *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - return c.getCachedConfig(list.Name, rt) -} - -// GetNetworkCachedConfig copies the input RuntimeConf to output -// RuntimeConf with fields updated with info from the cached Config. -func (c *CNIConfig) GetNetworkCachedConfig(net *NetworkConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) { - return c.getCachedConfig(net.Network.Name, rt) -} - -func (c *CNIConfig) addNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) (types.Result, error) { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return nil, err - } - if err := utils.ValidateContainerID(rt.ContainerID); err != nil { - return nil, err - } - if err := utils.ValidateNetworkName(name); err != nil { - return nil, err - } - if err := utils.ValidateInterfaceName(rt.IfName); err != nil { - return nil, err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return nil, err - } - - return invoke.ExecPluginWithResult(ctx, pluginPath, newConf.Bytes, c.args("ADD", rt), c.exec) -} - -// AddNetworkList executes a sequence of plugins with the ADD command -func (c *CNIConfig) AddNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) { - var err error - var result types.Result - for _, net := range list.Plugins { - result, err = c.addNetwork(ctx, list.Name, list.CNIVersion, net, result, rt) - if err != nil { - return nil, err - } - } - - if err = c.cacheAdd(result, list.Bytes, list.Name, rt); err != nil { - return nil, fmt.Errorf("failed to set network %q cached result: %v", list.Name, err) - } - - return result, nil -} - -func (c *CNIConfig) checkNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return err - } - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("CHECK", rt), c.exec) -} - -// CheckNetworkList executes a sequence of plugins with the CHECK command -func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error { - // CHECK was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil { - return err - } else if !gtet { - return fmt.Errorf("configuration version %q does not support the CHECK command", list.CNIVersion) - } - - if list.DisableCheck { - return nil - } - - cachedResult, err := c.getCachedResult(list.Name, list.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %v", list.Name, err) - } - - for _, net := range list.Plugins { - if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil { - return err - } - } - - return nil -} - -func (c *CNIConfig) delNetwork(ctx context.Context, name, cniVersion string, net *NetworkConfig, prevResult types.Result, rt *RuntimeConf) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(net.Network.Type, c.Path) - if err != nil { - return err - } - - newConf, err := buildOneConfig(name, cniVersion, net, prevResult, rt) - if err != nil { - return err - } - - return invoke.ExecPluginWithoutResult(ctx, pluginPath, newConf.Bytes, c.args("DEL", rt), c.exec) -} - -// DelNetworkList executes a sequence of plugins with the DEL command -func (c *CNIConfig) DelNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error { - var cachedResult types.Result - - // Cached result on DEL was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil { - return err - } else if gtet { - cachedResult, err = c.getCachedResult(list.Name, list.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %v", list.Name, err) - } - } - - for i := len(list.Plugins) - 1; i >= 0; i-- { - net := list.Plugins[i] - if err := c.delNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil { - return err - } - } - _ = c.cacheDel(list.Name, rt) - - return nil -} - -// AddNetwork executes the plugin with the ADD command -func (c *CNIConfig) AddNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) (types.Result, error) { - result, err := c.addNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, nil, rt) - if err != nil { - return nil, err - } - - if err = c.cacheAdd(result, net.Bytes, net.Network.Name, rt); err != nil { - return nil, fmt.Errorf("failed to set network %q cached result: %v", net.Network.Name, err) - } - - return result, nil -} - -// CheckNetwork executes the plugin with the CHECK command -func (c *CNIConfig) CheckNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error { - // CHECK was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil { - return err - } else if !gtet { - return fmt.Errorf("configuration version %q does not support the CHECK command", net.Network.CNIVersion) - } - - cachedResult, err := c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %v", net.Network.Name, err) - } - return c.checkNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt) -} - -// DelNetwork executes the plugin with the DEL command -func (c *CNIConfig) DelNetwork(ctx context.Context, net *NetworkConfig, rt *RuntimeConf) error { - var cachedResult types.Result - - // Cached result on DEL was added in CNI spec version 0.4.0 and higher - if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil { - return err - } else if gtet { - cachedResult, err = c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt) - if err != nil { - return fmt.Errorf("failed to get network %q cached result: %v", net.Network.Name, err) - } - } - - if err := c.delNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt); err != nil { - return err - } - _ = c.cacheDel(net.Network.Name, rt) - return nil -} - -// ValidateNetworkList checks that a configuration is reasonably valid. -// - all the specified plugins exist on disk -// - every plugin supports the desired version. -// -// Returns a list of all capabilities supported by the configuration, or error -func (c *CNIConfig) ValidateNetworkList(ctx context.Context, list *NetworkConfigList) ([]string, error) { - version := list.CNIVersion - - // holding map for seen caps (in case of duplicates) - caps := map[string]interface{}{} - - errs := []error{} - for _, net := range list.Plugins { - if err := c.validatePlugin(ctx, net.Network.Type, version); err != nil { - errs = append(errs, err) - } - for c, enabled := range net.Network.Capabilities { - if !enabled { - continue - } - caps[c] = struct{}{} - } - } - - if len(errs) > 0 { - return nil, fmt.Errorf("%v", errs) - } - - // make caps list - cc := make([]string, 0, len(caps)) - for c := range caps { - cc = append(cc, c) - } - - return cc, nil -} - -// ValidateNetwork checks that a configuration is reasonably valid. -// It uses the same logic as ValidateNetworkList) -// Returns a list of capabilities -func (c *CNIConfig) ValidateNetwork(ctx context.Context, net *NetworkConfig) ([]string, error) { - caps := []string{} - for c, ok := range net.Network.Capabilities { - if ok { - caps = append(caps, c) - } - } - if err := c.validatePlugin(ctx, net.Network.Type, net.Network.CNIVersion); err != nil { - return nil, err - } - return caps, nil -} - -// validatePlugin checks that an individual plugin's configuration is sane -func (c *CNIConfig) validatePlugin(ctx context.Context, pluginName, expectedVersion string) error { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(pluginName, c.Path) - if err != nil { - return err - } - if expectedVersion == "" { - expectedVersion = "0.1.0" - } - - vi, err := invoke.GetVersionInfo(ctx, pluginPath, c.exec) - if err != nil { - return err - } - for _, vers := range vi.SupportedVersions() { - if vers == expectedVersion { - return nil - } - } - return fmt.Errorf("plugin %s does not support config version %q", pluginName, expectedVersion) -} - -// GetVersionInfo reports which versions of the CNI spec are supported by -// the given plugin. -func (c *CNIConfig) GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) { - c.ensureExec() - pluginPath, err := c.exec.FindInPath(pluginType, c.Path) - if err != nil { - return nil, err - } - - return invoke.GetVersionInfo(ctx, pluginPath, c.exec) -} - -// ===== -func (c *CNIConfig) args(action string, rt *RuntimeConf) *invoke.Args { - return &invoke.Args{ - Command: action, - ContainerID: rt.ContainerID, - NetNS: rt.NetNS, - PluginArgs: rt.Args, - IfName: rt.IfName, - Path: strings.Join(c.Path, string(os.PathListSeparator)), - } -} diff --git a/examples/vendor/github.com/containernetworking/cni/libcni/conf.go b/examples/vendor/github.com/containernetworking/cni/libcni/conf.go deleted file mode 100644 index d8920cf..0000000 --- a/examples/vendor/github.com/containernetworking/cni/libcni/conf.go +++ /dev/null @@ -1,268 +0,0 @@ -// Copyright 2015 CNI 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 libcni - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sort" -) - -type NotFoundError struct { - Dir string - Name string -} - -func (e NotFoundError) Error() string { - return fmt.Sprintf(`no net configuration with name "%s" in %s`, e.Name, e.Dir) -} - -type NoConfigsFoundError struct { - Dir string -} - -func (e NoConfigsFoundError) Error() string { - return fmt.Sprintf(`no net configurations found in %s`, e.Dir) -} - -func ConfFromBytes(bytes []byte) (*NetworkConfig, error) { - conf := &NetworkConfig{Bytes: bytes} - if err := json.Unmarshal(bytes, &conf.Network); err != nil { - return nil, fmt.Errorf("error parsing configuration: %s", err) - } - if conf.Network.Type == "" { - return nil, fmt.Errorf("error parsing configuration: missing 'type'") - } - return conf, nil -} - -func ConfFromFile(filename string) (*NetworkConfig, error) { - bytes, err := ioutil.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("error reading %s: %s", filename, err) - } - return ConfFromBytes(bytes) -} - -func ConfListFromBytes(bytes []byte) (*NetworkConfigList, error) { - rawList := make(map[string]interface{}) - if err := json.Unmarshal(bytes, &rawList); err != nil { - return nil, fmt.Errorf("error parsing configuration list: %s", err) - } - - rawName, ok := rawList["name"] - if !ok { - return nil, fmt.Errorf("error parsing configuration list: no name") - } - name, ok := rawName.(string) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid name type %T", rawName) - } - - var cniVersion string - rawVersion, ok := rawList["cniVersion"] - if ok { - cniVersion, ok = rawVersion.(string) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid cniVersion type %T", rawVersion) - } - } - - disableCheck := false - if rawDisableCheck, ok := rawList["disableCheck"]; ok { - disableCheck, ok = rawDisableCheck.(bool) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid disableCheck type %T", rawDisableCheck) - } - } - - list := &NetworkConfigList{ - Name: name, - DisableCheck: disableCheck, - CNIVersion: cniVersion, - Bytes: bytes, - } - - var plugins []interface{} - plug, ok := rawList["plugins"] - if !ok { - return nil, fmt.Errorf("error parsing configuration list: no 'plugins' key") - } - plugins, ok = plug.([]interface{}) - if !ok { - return nil, fmt.Errorf("error parsing configuration list: invalid 'plugins' type %T", plug) - } - if len(plugins) == 0 { - return nil, fmt.Errorf("error parsing configuration list: no plugins in list") - } - - for i, conf := range plugins { - newBytes, err := json.Marshal(conf) - if err != nil { - return nil, fmt.Errorf("failed to marshal plugin config %d: %v", i, err) - } - netConf, err := ConfFromBytes(newBytes) - if err != nil { - return nil, fmt.Errorf("failed to parse plugin config %d: %v", i, err) - } - list.Plugins = append(list.Plugins, netConf) - } - - return list, nil -} - -func ConfListFromFile(filename string) (*NetworkConfigList, error) { - bytes, err := ioutil.ReadFile(filename) - if err != nil { - return nil, fmt.Errorf("error reading %s: %s", filename, err) - } - return ConfListFromBytes(bytes) -} - -func ConfFiles(dir string, extensions []string) ([]string, error) { - // In part, adapted from rkt/networking/podenv.go#listFiles - files, err := ioutil.ReadDir(dir) - switch { - case err == nil: // break - case os.IsNotExist(err): - return nil, nil - default: - return nil, err - } - - confFiles := []string{} - for _, f := range files { - if f.IsDir() { - continue - } - fileExt := filepath.Ext(f.Name()) - for _, ext := range extensions { - if fileExt == ext { - confFiles = append(confFiles, filepath.Join(dir, f.Name())) - } - } - } - return confFiles, nil -} - -func LoadConf(dir, name string) (*NetworkConfig, error) { - files, err := ConfFiles(dir, []string{".conf", ".json"}) - switch { - case err != nil: - return nil, err - case len(files) == 0: - return nil, NoConfigsFoundError{Dir: dir} - } - sort.Strings(files) - - for _, confFile := range files { - conf, err := ConfFromFile(confFile) - if err != nil { - return nil, err - } - if conf.Network.Name == name { - return conf, nil - } - } - return nil, NotFoundError{dir, name} -} - -func LoadConfList(dir, name string) (*NetworkConfigList, error) { - files, err := ConfFiles(dir, []string{".conflist"}) - if err != nil { - return nil, err - } - sort.Strings(files) - - for _, confFile := range files { - conf, err := ConfListFromFile(confFile) - if err != nil { - return nil, err - } - if conf.Name == name { - return conf, nil - } - } - - // Try and load a network configuration file (instead of list) - // from the same name, then upconvert. - singleConf, err := LoadConf(dir, name) - if err != nil { - // A little extra logic so the error makes sense - if _, ok := err.(NoConfigsFoundError); len(files) != 0 && ok { - // Config lists found but no config files found - return nil, NotFoundError{dir, name} - } - - return nil, err - } - return ConfListFromConf(singleConf) -} - -func InjectConf(original *NetworkConfig, newValues map[string]interface{}) (*NetworkConfig, error) { - config := make(map[string]interface{}) - err := json.Unmarshal(original.Bytes, &config) - if err != nil { - return nil, fmt.Errorf("unmarshal existing network bytes: %s", err) - } - - for key, value := range newValues { - if key == "" { - return nil, fmt.Errorf("keys cannot be empty") - } - - if value == nil { - return nil, fmt.Errorf("key '%s' value must not be nil", key) - } - - config[key] = value - } - - newBytes, err := json.Marshal(config) - if err != nil { - return nil, err - } - - return ConfFromBytes(newBytes) -} - -// ConfListFromConf "upconverts" a network config in to a NetworkConfigList, -// with the single network as the only entry in the list. -func ConfListFromConf(original *NetworkConfig) (*NetworkConfigList, error) { - // Re-deserialize the config's json, then make a raw map configlist. - // This may seem a bit strange, but it's to make the Bytes fields - // actually make sense. Otherwise, the generated json is littered with - // golang default values. - - rawConfig := make(map[string]interface{}) - if err := json.Unmarshal(original.Bytes, &rawConfig); err != nil { - return nil, err - } - - rawConfigList := map[string]interface{}{ - "name": original.Network.Name, - "cniVersion": original.Network.CNIVersion, - "plugins": []interface{}{rawConfig}, - } - - b, err := json.Marshal(rawConfigList) - if err != nil { - return nil, err - } - return ConfListFromBytes(b) -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/args.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/args.go deleted file mode 100644 index 3cdb4bc..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/args.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "fmt" - "os" - "strings" -) - -type CNIArgs interface { - // For use with os/exec; i.e., return nil to inherit the - // environment from this process - // For use in delegation; inherit the environment from this - // process and allow overrides - AsEnv() []string -} - -type inherited struct{} - -var inheritArgsFromEnv inherited - -func (*inherited) AsEnv() []string { - return nil -} - -func ArgsFromEnv() CNIArgs { - return &inheritArgsFromEnv -} - -type Args struct { - Command string - ContainerID string - NetNS string - PluginArgs [][2]string - PluginArgsStr string - IfName string - Path string -} - -// Args implements the CNIArgs interface -var _ CNIArgs = &Args{} - -func (args *Args) AsEnv() []string { - env := os.Environ() - pluginArgsStr := args.PluginArgsStr - if pluginArgsStr == "" { - pluginArgsStr = stringify(args.PluginArgs) - } - - // Duplicated values which come first will be overridden, so we must put the - // custom values in the end to avoid being overridden by the process environments. - env = append(env, - "CNI_COMMAND="+args.Command, - "CNI_CONTAINERID="+args.ContainerID, - "CNI_NETNS="+args.NetNS, - "CNI_ARGS="+pluginArgsStr, - "CNI_IFNAME="+args.IfName, - "CNI_PATH="+args.Path, - ) - return dedupEnv(env) -} - -// taken from rkt/networking/net_plugin.go -func stringify(pluginArgs [][2]string) string { - entries := make([]string, len(pluginArgs)) - - for i, kv := range pluginArgs { - entries[i] = strings.Join(kv[:], "=") - } - - return strings.Join(entries, ";") -} - -// DelegateArgs implements the CNIArgs interface -// used for delegation to inherit from environments -// and allow some overrides like CNI_COMMAND -var _ CNIArgs = &DelegateArgs{} - -type DelegateArgs struct { - Command string -} - -func (d *DelegateArgs) AsEnv() []string { - env := os.Environ() - - // The custom values should come in the end to override the existing - // process environment of the same key. - env = append(env, - "CNI_COMMAND="+d.Command, - ) - return dedupEnv(env) -} - -// dedupEnv returns a copy of env with any duplicates removed, in favor of later values. -// Items not of the normal environment "key=value" form are preserved unchanged. -func dedupEnv(env []string) []string { - out := make([]string, 0, len(env)) - envMap := map[string]string{} - - for _, kv := range env { - // find the first "=" in environment, if not, just keep it - eq := strings.Index(kv, "=") - if eq < 0 { - out = append(out, kv) - continue - } - envMap[kv[:eq]] = kv[eq+1:] - } - - for k, v := range envMap { - out = append(out, fmt.Sprintf("%s=%s", k, v)) - } - - return out -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go deleted file mode 100644 index 8defe4d..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/delegate.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -import ( - "context" - "os" - "path/filepath" - - "github.com/containernetworking/cni/pkg/types" -) - -func delegateCommon(delegatePlugin string, exec Exec) (string, Exec, error) { - if exec == nil { - exec = defaultExec - } - - paths := filepath.SplitList(os.Getenv("CNI_PATH")) - pluginPath, err := exec.FindInPath(delegatePlugin, paths) - if err != nil { - return "", nil, err - } - - return pluginPath, exec, nil -} - -// DelegateAdd calls the given delegate plugin with the CNI ADD action and -// JSON configuration -func DelegateAdd(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) (types.Result, error) { - pluginPath, realExec, err := delegateCommon(delegatePlugin, exec) - if err != nil { - return nil, err - } - - // DelegateAdd will override the original "CNI_COMMAND" env from process with ADD - return ExecPluginWithResult(ctx, pluginPath, netconf, delegateArgs("ADD"), realExec) -} - -// DelegateCheck calls the given delegate plugin with the CNI CHECK action and -// JSON configuration -func DelegateCheck(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - pluginPath, realExec, err := delegateCommon(delegatePlugin, exec) - if err != nil { - return err - } - - // DelegateCheck will override the original CNI_COMMAND env from process with CHECK - return ExecPluginWithoutResult(ctx, pluginPath, netconf, delegateArgs("CHECK"), realExec) -} - -// DelegateDel calls the given delegate plugin with the CNI DEL action and -// JSON configuration -func DelegateDel(ctx context.Context, delegatePlugin string, netconf []byte, exec Exec) error { - pluginPath, realExec, err := delegateCommon(delegatePlugin, exec) - if err != nil { - return err - } - - // DelegateDel will override the original CNI_COMMAND env from process with DEL - return ExecPluginWithoutResult(ctx, pluginPath, netconf, delegateArgs("DEL"), realExec) -} - -// return CNIArgs used by delegation -func delegateArgs(action string) *DelegateArgs { - return &DelegateArgs{ - Command: action, - } -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go deleted file mode 100644 index 8e6d30b..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/exec.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "context" - "fmt" - "os" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/version" -) - -// Exec is an interface encapsulates all operations that deal with finding -// and executing a CNI plugin. Tests may provide a fake implementation -// to avoid writing fake plugins to temporary directories during the test. -type Exec interface { - ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error) - FindInPath(plugin string, paths []string) (string, error) - Decode(jsonBytes []byte) (version.PluginInfo, error) -} - -// For example, a testcase could pass an instance of the following fakeExec -// object to ExecPluginWithResult() to verify the incoming stdin and environment -// and provide a tailored response: -// -//import ( -// "encoding/json" -// "path" -// "strings" -//) -// -//type fakeExec struct { -// version.PluginDecoder -//} -// -//func (f *fakeExec) ExecPlugin(pluginPath string, stdinData []byte, environ []string) ([]byte, error) { -// net := &types.NetConf{} -// err := json.Unmarshal(stdinData, net) -// if err != nil { -// return nil, fmt.Errorf("failed to unmarshal configuration: %v", err) -// } -// pluginName := path.Base(pluginPath) -// if pluginName != net.Type { -// return nil, fmt.Errorf("plugin name %q did not match config type %q", pluginName, net.Type) -// } -// for _, e := range environ { -// // Check environment for forced failure request -// parts := strings.Split(e, "=") -// if len(parts) > 0 && parts[0] == "FAIL" { -// return nil, fmt.Errorf("failed to execute plugin %s", pluginName) -// } -// } -// return []byte("{\"CNIVersion\":\"0.4.0\"}"), nil -//} -// -//func (f *fakeExec) FindInPath(plugin string, paths []string) (string, error) { -// if len(paths) > 0 { -// return path.Join(paths[0], plugin), nil -// } -// return "", fmt.Errorf("failed to find plugin %s in paths %v", plugin, paths) -//} - -func ExecPluginWithResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) (types.Result, error) { - if exec == nil { - exec = defaultExec - } - - stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv()) - if err != nil { - return nil, err - } - - // Plugin must return result in same version as specified in netconf - versionDecoder := &version.ConfigDecoder{} - confVersion, err := versionDecoder.Decode(netconf) - if err != nil { - return nil, err - } - - return version.NewResult(confVersion, stdoutBytes) -} - -func ExecPluginWithoutResult(ctx context.Context, pluginPath string, netconf []byte, args CNIArgs, exec Exec) error { - if exec == nil { - exec = defaultExec - } - _, err := exec.ExecPlugin(ctx, pluginPath, netconf, args.AsEnv()) - return err -} - -// GetVersionInfo returns the version information available about the plugin. -// For recent-enough plugins, it uses the information returned by the VERSION -// command. For older plugins which do not recognize that command, it reports -// version 0.1.0 -func GetVersionInfo(ctx context.Context, pluginPath string, exec Exec) (version.PluginInfo, error) { - if exec == nil { - exec = defaultExec - } - args := &Args{ - Command: "VERSION", - - // set fake values required by plugins built against an older version of skel - NetNS: "dummy", - IfName: "dummy", - Path: "dummy", - } - stdin := []byte(fmt.Sprintf(`{"cniVersion":%q}`, version.Current())) - stdoutBytes, err := exec.ExecPlugin(ctx, pluginPath, stdin, args.AsEnv()) - if err != nil { - if err.Error() == "unknown CNI_COMMAND: VERSION" { - return version.PluginSupports("0.1.0"), nil - } - return nil, err - } - - return exec.Decode(stdoutBytes) -} - -// DefaultExec is an object that implements the Exec interface which looks -// for and executes plugins from disk. -type DefaultExec struct { - *RawExec - version.PluginDecoder -} - -// DefaultExec implements the Exec interface -var _ Exec = &DefaultExec{} - -var defaultExec = &DefaultExec{ - RawExec: &RawExec{Stderr: os.Stderr}, -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/find.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/find.go deleted file mode 100644 index e62029e..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/find.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015 CNI 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 invoke - -import ( - "fmt" - "os" - "path/filepath" - "strings" -) - -// FindInPath returns the full path of the plugin by searching in the provided path -func FindInPath(plugin string, paths []string) (string, error) { - if plugin == "" { - return "", fmt.Errorf("no plugin name provided") - } - - if strings.ContainsRune(plugin, os.PathSeparator) { - return "", fmt.Errorf("invalid plugin name: %s", plugin) - } - - if len(paths) == 0 { - return "", fmt.Errorf("no paths provided") - } - - for _, path := range paths { - for _, fe := range ExecutableFileExtensions { - fullpath := filepath.Join(path, plugin) + fe - if fi, err := os.Stat(fullpath); err == nil && fi.Mode().IsRegular() { - return fullpath, nil - } - } - } - - return "", fmt.Errorf("failed to find plugin %q in path %s", plugin, paths) -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go deleted file mode 100644 index 7665125..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/os_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -// Valid file extensions for plugin executables. -var ExecutableFileExtensions = []string{".exe", ""} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go b/examples/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go deleted file mode 100644 index 5ab5cc8..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/invoke/raw_exec.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2016 CNI 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 invoke - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os/exec" - "strings" - "time" - - "github.com/containernetworking/cni/pkg/types" -) - -type RawExec struct { - Stderr io.Writer -} - -func (e *RawExec) ExecPlugin(ctx context.Context, pluginPath string, stdinData []byte, environ []string) ([]byte, error) { - stdout := &bytes.Buffer{} - stderr := &bytes.Buffer{} - c := exec.CommandContext(ctx, pluginPath) - c.Env = environ - c.Stdin = bytes.NewBuffer(stdinData) - c.Stdout = stdout - c.Stderr = stderr - - // Retry the command on "text file busy" errors - for i := 0; i <= 5; i++ { - err := c.Run() - - // Command succeeded - if err == nil { - break - } - - // If the plugin is currently about to be written, then we wait a - // second and try it again - if strings.Contains(err.Error(), "text file busy") { - time.Sleep(time.Second) - continue - } - - // All other errors except than the busy text file - return nil, e.pluginErr(err, stdout.Bytes(), stderr.Bytes()) - } - - // Copy stderr to caller's buffer in case plugin printed to both - // stdout and stderr for some reason. Ignore failures as stderr is - // only informational. - if e.Stderr != nil && stderr.Len() > 0 { - _, _ = stderr.WriteTo(e.Stderr) - } - return stdout.Bytes(), nil -} - -func (e *RawExec) pluginErr(err error, stdout, stderr []byte) error { - emsg := types.Error{} - if len(stdout) == 0 { - if len(stderr) == 0 { - emsg.Msg = fmt.Sprintf("netplugin failed with no error message: %v", err) - } else { - emsg.Msg = fmt.Sprintf("netplugin failed: %q", string(stderr)) - } - } else if perr := json.Unmarshal(stdout, &emsg); perr != nil { - emsg.Msg = fmt.Sprintf("netplugin failed but error parsing its diagnostic message %q: %v", string(stdout), perr) - } - return &emsg -} - -func (e *RawExec) FindInPath(plugin string, paths []string) (string, error) { - return FindInPath(plugin, paths) -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/types/020/types.go b/examples/vendor/github.com/containernetworking/cni/pkg/types/020/types.go deleted file mode 100644 index 36f3167..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/types/020/types.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2016 CNI 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 types020 - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" - - "github.com/containernetworking/cni/pkg/types" -) - -const ImplementedSpecVersion string = "0.2.0" - -var SupportedVersions = []string{"", "0.1.0", ImplementedSpecVersion} - -// Compatibility types for CNI version 0.1.0 and 0.2.0 - -func NewResult(data []byte) (types.Result, error) { - result := &Result{} - if err := json.Unmarshal(data, result); err != nil { - return nil, err - } - return result, nil -} - -func GetResult(r types.Result) (*Result, error) { - // We expect version 0.1.0/0.2.0 results - result020, err := r.GetAsVersion(ImplementedSpecVersion) - if err != nil { - return nil, err - } - result, ok := result020.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - return result, nil -} - -// Result is what gets returned from the plugin (via stdout) to the caller -type Result struct { - CNIVersion string `json:"cniVersion,omitempty"` - IP4 *IPConfig `json:"ip4,omitempty"` - IP6 *IPConfig `json:"ip6,omitempty"` - DNS types.DNS `json:"dns,omitempty"` -} - -func (r *Result) Version() string { - return ImplementedSpecVersion -} - -func (r *Result) GetAsVersion(version string) (types.Result, error) { - for _, supportedVersion := range SupportedVersions { - if version == supportedVersion { - r.CNIVersion = version - return r, nil - } - } - return nil, fmt.Errorf("cannot convert version %q to %s", SupportedVersions, version) -} - -func (r *Result) Print() error { - return r.PrintTo(os.Stdout) -} - -func (r *Result) PrintTo(writer io.Writer) error { - data, err := json.MarshalIndent(r, "", " ") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// IPConfig contains values necessary to configure an interface -type IPConfig struct { - IP net.IPNet - Gateway net.IP - Routes []types.Route -} - -// net.IPNet is not JSON (un)marshallable so this duality is needed -// for our custom IPNet type - -// JSON (un)marshallable types -type ipConfig struct { - IP types.IPNet `json:"ip"` - Gateway net.IP `json:"gateway,omitempty"` - Routes []types.Route `json:"routes,omitempty"` -} - -func (c *IPConfig) MarshalJSON() ([]byte, error) { - ipc := ipConfig{ - IP: types.IPNet(c.IP), - Gateway: c.Gateway, - Routes: c.Routes, - } - - return json.Marshal(ipc) -} - -func (c *IPConfig) UnmarshalJSON(data []byte) error { - ipc := ipConfig{} - if err := json.Unmarshal(data, &ipc); err != nil { - return err - } - - c.IP = net.IPNet(ipc.IP) - c.Gateway = ipc.Gateway - c.Routes = ipc.Routes - return nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/types/args.go b/examples/vendor/github.com/containernetworking/cni/pkg/types/args.go deleted file mode 100644 index 4eac648..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/types/args.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2015 CNI 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 types - -import ( - "encoding" - "fmt" - "reflect" - "strings" -) - -// UnmarshallableBool typedef for builtin bool -// because builtin type's methods can't be declared -type UnmarshallableBool bool - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -// Returns boolean true if the string is "1" or "[Tt]rue" -// Returns boolean false if the string is "0" or "[Ff]alse" -func (b *UnmarshallableBool) UnmarshalText(data []byte) error { - s := strings.ToLower(string(data)) - switch s { - case "1", "true": - *b = true - case "0", "false": - *b = false - default: - return fmt.Errorf("boolean unmarshal error: invalid input %s", s) - } - return nil -} - -// UnmarshallableString typedef for builtin string -type UnmarshallableString string - -// UnmarshalText implements the encoding.TextUnmarshaler interface. -// Returns the string -func (s *UnmarshallableString) UnmarshalText(data []byte) error { - *s = UnmarshallableString(data) - return nil -} - -// CommonArgs contains the IgnoreUnknown argument -// and must be embedded by all Arg structs -type CommonArgs struct { - IgnoreUnknown UnmarshallableBool `json:"ignoreunknown,omitempty"` -} - -// GetKeyField is a helper function to receive Values -// Values that represent a pointer to a struct -func GetKeyField(keyString string, v reflect.Value) reflect.Value { - return v.Elem().FieldByName(keyString) -} - -// UnmarshalableArgsError is used to indicate error unmarshalling args -// from the args-string in the form "K=V;K2=V2;..." -type UnmarshalableArgsError struct { - error -} - -// LoadArgs parses args from a string in the form "K=V;K2=V2;..." -func LoadArgs(args string, container interface{}) error { - if args == "" { - return nil - } - - containerValue := reflect.ValueOf(container) - - pairs := strings.Split(args, ";") - unknownArgs := []string{} - for _, pair := range pairs { - kv := strings.Split(pair, "=") - if len(kv) != 2 { - return fmt.Errorf("ARGS: invalid pair %q", pair) - } - keyString := kv[0] - valueString := kv[1] - keyField := GetKeyField(keyString, containerValue) - if !keyField.IsValid() { - unknownArgs = append(unknownArgs, pair) - continue - } - keyFieldIface := keyField.Addr().Interface() - u, ok := keyFieldIface.(encoding.TextUnmarshaler) - if !ok { - return UnmarshalableArgsError{fmt.Errorf( - "ARGS: cannot unmarshal into field '%s' - type '%s' does not implement encoding.TextUnmarshaler", - keyString, reflect.TypeOf(keyFieldIface))} - } - err := u.UnmarshalText([]byte(valueString)) - if err != nil { - return fmt.Errorf("ARGS: error parsing value of pair %q: %v)", pair, err) - } - } - - isIgnoreUnknown := GetKeyField("IgnoreUnknown", containerValue).Bool() - if len(unknownArgs) > 0 && !isIgnoreUnknown { - return fmt.Errorf("ARGS: unknown args %q", unknownArgs) - } - return nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/types/current/types.go b/examples/vendor/github.com/containernetworking/cni/pkg/types/current/types.go deleted file mode 100644 index 754cc6e..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/types/current/types.go +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2016 CNI 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 current - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/020" -) - -const ImplementedSpecVersion string = "0.4.0" - -var SupportedVersions = []string{"0.3.0", "0.3.1", ImplementedSpecVersion} - -func NewResult(data []byte) (types.Result, error) { - result := &Result{} - if err := json.Unmarshal(data, result); err != nil { - return nil, err - } - return result, nil -} - -func GetResult(r types.Result) (*Result, error) { - resultCurrent, err := r.GetAsVersion(ImplementedSpecVersion) - if err != nil { - return nil, err - } - result, ok := resultCurrent.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - return result, nil -} - -var resultConverters = []struct { - versions []string - convert func(types.Result) (*Result, error) -}{ - {types020.SupportedVersions, convertFrom020}, - {SupportedVersions, convertFrom030}, -} - -func convertFrom020(result types.Result) (*Result, error) { - oldResult, err := types020.GetResult(result) - if err != nil { - return nil, err - } - - newResult := &Result{ - CNIVersion: ImplementedSpecVersion, - DNS: oldResult.DNS, - Routes: []*types.Route{}, - } - - if oldResult.IP4 != nil { - newResult.IPs = append(newResult.IPs, &IPConfig{ - Version: "4", - Address: oldResult.IP4.IP, - Gateway: oldResult.IP4.Gateway, - }) - for _, route := range oldResult.IP4.Routes { - newResult.Routes = append(newResult.Routes, &types.Route{ - Dst: route.Dst, - GW: route.GW, - }) - } - } - - if oldResult.IP6 != nil { - newResult.IPs = append(newResult.IPs, &IPConfig{ - Version: "6", - Address: oldResult.IP6.IP, - Gateway: oldResult.IP6.Gateway, - }) - for _, route := range oldResult.IP6.Routes { - newResult.Routes = append(newResult.Routes, &types.Route{ - Dst: route.Dst, - GW: route.GW, - }) - } - } - - return newResult, nil -} - -func convertFrom030(result types.Result) (*Result, error) { - newResult, ok := result.(*Result) - if !ok { - return nil, fmt.Errorf("failed to convert result") - } - newResult.CNIVersion = ImplementedSpecVersion - return newResult, nil -} - -func NewResultFromResult(result types.Result) (*Result, error) { - version := result.Version() - for _, converter := range resultConverters { - for _, supportedVersion := range converter.versions { - if version == supportedVersion { - return converter.convert(result) - } - } - } - return nil, fmt.Errorf("unsupported CNI result22 version %q", version) -} - -// Result is what gets returned from the plugin (via stdout) to the caller -type Result struct { - CNIVersion string `json:"cniVersion,omitempty"` - Interfaces []*Interface `json:"interfaces,omitempty"` - IPs []*IPConfig `json:"ips,omitempty"` - Routes []*types.Route `json:"routes,omitempty"` - DNS types.DNS `json:"dns,omitempty"` -} - -// Convert to the older 0.2.0 CNI spec Result type -func (r *Result) convertTo020() (*types020.Result, error) { - oldResult := &types020.Result{ - CNIVersion: types020.ImplementedSpecVersion, - DNS: r.DNS, - } - - for _, ip := range r.IPs { - // Only convert the first IP address of each version as 0.2.0 - // and earlier cannot handle multiple IP addresses - if ip.Version == "4" && oldResult.IP4 == nil { - oldResult.IP4 = &types020.IPConfig{ - IP: ip.Address, - Gateway: ip.Gateway, - } - } else if ip.Version == "6" && oldResult.IP6 == nil { - oldResult.IP6 = &types020.IPConfig{ - IP: ip.Address, - Gateway: ip.Gateway, - } - } - - if oldResult.IP4 != nil && oldResult.IP6 != nil { - break - } - } - - for _, route := range r.Routes { - is4 := route.Dst.IP.To4() != nil - if is4 && oldResult.IP4 != nil { - oldResult.IP4.Routes = append(oldResult.IP4.Routes, types.Route{ - Dst: route.Dst, - GW: route.GW, - }) - } else if !is4 && oldResult.IP6 != nil { - oldResult.IP6.Routes = append(oldResult.IP6.Routes, types.Route{ - Dst: route.Dst, - GW: route.GW, - }) - } - } - - if oldResult.IP4 == nil && oldResult.IP6 == nil { - return nil, fmt.Errorf("cannot convert: no valid IP addresses") - } - - return oldResult, nil -} - -func (r *Result) Version() string { - return ImplementedSpecVersion -} - -func (r *Result) GetAsVersion(version string) (types.Result, error) { - switch version { - case "0.3.0", "0.3.1", ImplementedSpecVersion: - r.CNIVersion = version - return r, nil - case types020.SupportedVersions[0], types020.SupportedVersions[1], types020.SupportedVersions[2]: - return r.convertTo020() - } - return nil, fmt.Errorf("cannot convert version 0.3.x to %q", version) -} - -func (r *Result) Print() error { - return r.PrintTo(os.Stdout) -} - -func (r *Result) PrintTo(writer io.Writer) error { - data, err := json.MarshalIndent(r, "", " ") - if err != nil { - return err - } - _, err = writer.Write(data) - return err -} - -// Convert this old version result to the current CNI version result -func (r *Result) Convert() (*Result, error) { - return r, nil -} - -// Interface contains values about the created interfaces -type Interface struct { - Name string `json:"name"` - Mac string `json:"mac,omitempty"` - Sandbox string `json:"sandbox,omitempty"` -} - -func (i *Interface) String() string { - return fmt.Sprintf("%+v", *i) -} - -// Int returns a pointer to the int value passed in. Used to -// set the IPConfig.Interface field. -func Int(v int) *int { - return &v -} - -// IPConfig contains values necessary to configure an IP address on an interface -type IPConfig struct { - // IP version, either "4" or "6" - Version string - // Index into Result structs Interfaces list - Interface *int - Address net.IPNet - Gateway net.IP -} - -func (i *IPConfig) String() string { - return fmt.Sprintf("%+v", *i) -} - -// JSON (un)marshallable types -type ipConfig struct { - Version string `json:"version"` - Interface *int `json:"interface,omitempty"` - Address types.IPNet `json:"address"` - Gateway net.IP `json:"gateway,omitempty"` -} - -func (c *IPConfig) MarshalJSON() ([]byte, error) { - ipc := ipConfig{ - Version: c.Version, - Interface: c.Interface, - Address: types.IPNet(c.Address), - Gateway: c.Gateway, - } - - return json.Marshal(ipc) -} - -func (c *IPConfig) UnmarshalJSON(data []byte) error { - ipc := ipConfig{} - if err := json.Unmarshal(data, &ipc); err != nil { - return err - } - - c.Version = ipc.Version - c.Interface = ipc.Interface - c.Address = net.IPNet(ipc.Address) - c.Gateway = ipc.Gateway - return nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/types/types.go b/examples/vendor/github.com/containernetworking/cni/pkg/types/types.go deleted file mode 100644 index 3fa757a..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/types/types.go +++ /dev/null @@ -1,207 +0,0 @@ -// Copyright 2015 CNI 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 types - -import ( - "encoding/json" - "fmt" - "io" - "net" - "os" -) - -// like net.IPNet but adds JSON marshalling and unmarshalling -type IPNet net.IPNet - -// ParseCIDR takes a string like "10.2.3.1/24" and -// return IPNet with "10.2.3.1" and /24 mask -func ParseCIDR(s string) (*net.IPNet, error) { - ip, ipn, err := net.ParseCIDR(s) - if err != nil { - return nil, err - } - - ipn.IP = ip - return ipn, nil -} - -func (n IPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(&n).String()) -} - -func (n *IPNet) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return err - } - - tmp, err := ParseCIDR(s) - if err != nil { - return err - } - - *n = IPNet(*tmp) - return nil -} - -// NetConf describes a network. -type NetConf struct { - CNIVersion string `json:"cniVersion,omitempty"` - - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Capabilities map[string]bool `json:"capabilities,omitempty"` - IPAM IPAM `json:"ipam,omitempty"` - DNS DNS `json:"dns"` - - RawPrevResult map[string]interface{} `json:"prevResult,omitempty"` - PrevResult Result `json:"-"` -} - -type IPAM struct { - Type string `json:"type,omitempty"` -} - -// NetConfList describes an ordered list of networks. -type NetConfList struct { - CNIVersion string `json:"cniVersion,omitempty"` - - Name string `json:"name,omitempty"` - DisableCheck bool `json:"disableCheck,omitempty"` - Plugins []*NetConf `json:"plugins,omitempty"` -} - -type ResultFactoryFunc func([]byte) (Result, error) - -// Result is an interface that provides the result of plugin execution -type Result interface { - // The highest CNI specification result version the result supports - // without having to convert - Version() string - - // Returns the result converted into the requested CNI specification - // result version, or an error if conversion failed - GetAsVersion(version string) (Result, error) - - // Prints the result in JSON format to stdout - Print() error - - // Prints the result in JSON format to provided writer - PrintTo(writer io.Writer) error -} - -func PrintResult(result Result, version string) error { - newResult, err := result.GetAsVersion(version) - if err != nil { - return err - } - return newResult.Print() -} - -// DNS contains values interesting for DNS resolvers -type DNS struct { - Nameservers []string `json:"nameservers,omitempty"` - Domain string `json:"domain,omitempty"` - Search []string `json:"search,omitempty"` - Options []string `json:"options,omitempty"` -} - -type Route struct { - Dst net.IPNet - GW net.IP -} - -func (r *Route) String() string { - return fmt.Sprintf("%+v", *r) -} - -// Well known error codes -// see https://github.com/containernetworking/cni/blob/master/SPEC.md#well-known-error-codes -const ( - ErrUnknown uint = iota // 0 - ErrIncompatibleCNIVersion // 1 - ErrUnsupportedField // 2 - ErrUnknownContainer // 3 - ErrInvalidEnvironmentVariables // 4 - ErrIOFailure // 5 - ErrDecodingFailure // 6 - ErrInvalidNetworkConfig // 7 - ErrTryAgainLater uint = 11 - ErrInternal uint = 999 -) - -type Error struct { - Code uint `json:"code"` - Msg string `json:"msg"` - Details string `json:"details,omitempty"` -} - -func NewError(code uint, msg, details string) *Error { - return &Error{ - Code: code, - Msg: msg, - Details: details, - } -} - -func (e *Error) Error() string { - details := "" - if e.Details != "" { - details = fmt.Sprintf("; %v", e.Details) - } - return fmt.Sprintf("%v%v", e.Msg, details) -} - -func (e *Error) Print() error { - return prettyPrint(e) -} - -// net.IPNet is not JSON (un)marshallable so this duality is needed -// for our custom IPNet type - -// JSON (un)marshallable types -type route struct { - Dst IPNet `json:"dst"` - GW net.IP `json:"gw,omitempty"` -} - -func (r *Route) UnmarshalJSON(data []byte) error { - rt := route{} - if err := json.Unmarshal(data, &rt); err != nil { - return err - } - - r.Dst = net.IPNet(rt.Dst) - r.GW = rt.GW - return nil -} - -func (r Route) MarshalJSON() ([]byte, error) { - rt := route{ - Dst: IPNet(r.Dst), - GW: r.GW, - } - - return json.Marshal(rt) -} - -func prettyPrint(obj interface{}) error { - data, err := json.MarshalIndent(obj, "", " ") - if err != nil { - return err - } - _, err = os.Stdout.Write(data) - return err -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/utils/utils.go b/examples/vendor/github.com/containernetworking/cni/pkg/utils/utils.go deleted file mode 100644 index b8ec388..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/utils/utils.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2019 CNI 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 utils - -import ( - "bytes" - "fmt" - "regexp" - "unicode" - - "github.com/containernetworking/cni/pkg/types" -) - -const ( - // cniValidNameChars is the regexp used to validate valid characters in - // containerID and networkName - cniValidNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.\-]` - - // maxInterfaceNameLength is the length max of a valid interface name - maxInterfaceNameLength = 15 -) - -var cniReg = regexp.MustCompile(`^` + cniValidNameChars + `*$`) - -// ValidateContainerID will validate that the supplied containerID is not empty does not contain invalid characters -func ValidateContainerID(containerID string) *types.Error { - - if containerID == "" { - return types.NewError(types.ErrUnknownContainer, "missing containerID", "") - } - if !cniReg.MatchString(containerID) { - return types.NewError(types.ErrInvalidEnvironmentVariables, "invalid characters in containerID", containerID) - } - return nil -} - -// ValidateNetworkName will validate that the supplied networkName does not contain invalid characters -func ValidateNetworkName(networkName string) *types.Error { - - if networkName == "" { - return types.NewError(types.ErrInvalidNetworkConfig, "missing network name:", "") - } - if !cniReg.MatchString(networkName) { - return types.NewError(types.ErrInvalidNetworkConfig, "invalid characters found in network name", networkName) - } - return nil -} - -// ValidateInterfaceName will validate the interface name based on the three rules below -// 1. The name must not be empty -// 2. The name must be less than 16 characters -// 3. The name must not be "." or ".." -// 3. The name must not contain / or : or any whitespace characters -// ref to https://github.com/torvalds/linux/blob/master/net/core/dev.c#L1024 -func ValidateInterfaceName(ifName string) *types.Error { - if len(ifName) == 0 { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is empty", "") - } - if len(ifName) > maxInterfaceNameLength { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is too long", fmt.Sprintf("interface name should be less than %d characters", maxInterfaceNameLength+1)) - } - if ifName == "." || ifName == ".." { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is . or ..", "") - } - for _, r := range bytes.Runes([]byte(ifName)) { - if r == '/' || r == ':' || unicode.IsSpace(r) { - return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name contains / or : or whitespace characters", "") - } - } - - return nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/version/conf.go b/examples/vendor/github.com/containernetworking/cni/pkg/version/conf.go deleted file mode 100644 index 3cca58b..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/version/conf.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "encoding/json" - "fmt" -) - -// ConfigDecoder can decode the CNI version available in network config data -type ConfigDecoder struct{} - -func (*ConfigDecoder) Decode(jsonBytes []byte) (string, error) { - var conf struct { - CNIVersion string `json:"cniVersion"` - } - err := json.Unmarshal(jsonBytes, &conf) - if err != nil { - return "", fmt.Errorf("decoding version from network config: %s", err) - } - if conf.CNIVersion == "" { - return "0.1.0", nil - } - return conf.CNIVersion, nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/version/plugin.go b/examples/vendor/github.com/containernetworking/cni/pkg/version/plugin.go deleted file mode 100644 index 1df4272..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/version/plugin.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "encoding/json" - "fmt" - "io" - "strconv" - "strings" -) - -// PluginInfo reports information about CNI versioning -type PluginInfo interface { - // SupportedVersions returns one or more CNI spec versions that the plugin - // supports. If input is provided in one of these versions, then the plugin - // promises to use the same CNI version in its response - SupportedVersions() []string - - // Encode writes this CNI version information as JSON to the given Writer - Encode(io.Writer) error -} - -type pluginInfo struct { - CNIVersion_ string `json:"cniVersion"` - SupportedVersions_ []string `json:"supportedVersions,omitempty"` -} - -// pluginInfo implements the PluginInfo interface -var _ PluginInfo = &pluginInfo{} - -func (p *pluginInfo) Encode(w io.Writer) error { - return json.NewEncoder(w).Encode(p) -} - -func (p *pluginInfo) SupportedVersions() []string { - return p.SupportedVersions_ -} - -// PluginSupports returns a new PluginInfo that will report the given versions -// as supported -func PluginSupports(supportedVersions ...string) PluginInfo { - if len(supportedVersions) < 1 { - panic("programmer error: you must support at least one version") - } - return &pluginInfo{ - CNIVersion_: Current(), - SupportedVersions_: supportedVersions, - } -} - -// PluginDecoder can decode the response returned by a plugin's VERSION command -type PluginDecoder struct{} - -func (*PluginDecoder) Decode(jsonBytes []byte) (PluginInfo, error) { - var info pluginInfo - err := json.Unmarshal(jsonBytes, &info) - if err != nil { - return nil, fmt.Errorf("decoding version info: %s", err) - } - if info.CNIVersion_ == "" { - return nil, fmt.Errorf("decoding version info: missing field cniVersion") - } - if len(info.SupportedVersions_) == 0 { - if info.CNIVersion_ == "0.2.0" { - return PluginSupports("0.1.0", "0.2.0"), nil - } - return nil, fmt.Errorf("decoding version info: missing field supportedVersions") - } - return &info, nil -} - -// ParseVersion parses a version string like "3.0.1" or "0.4.5" into major, -// minor, and micro numbers or returns an error -func ParseVersion(version string) (int, int, int, error) { - var major, minor, micro int - if version == "" { - return -1, -1, -1, fmt.Errorf("invalid version %q: the version is empty", version) - } - - parts := strings.Split(version, ".") - if len(parts) >= 4 { - return -1, -1, -1, fmt.Errorf("invalid version %q: too many parts", version) - } - - major, err := strconv.Atoi(parts[0]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert major version part %q: %v", parts[0], err) - } - - if len(parts) >= 2 { - minor, err = strconv.Atoi(parts[1]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert minor version part %q: %v", parts[1], err) - } - } - - if len(parts) >= 3 { - micro, err = strconv.Atoi(parts[2]) - if err != nil { - return -1, -1, -1, fmt.Errorf("failed to convert micro version part %q: %v", parts[2], err) - } - } - - return major, minor, micro, nil -} - -// GreaterThanOrEqualTo takes two string versions, parses them into major/minor/micro -// numbers, and compares them to determine whether the first version is greater -// than or equal to the second -func GreaterThanOrEqualTo(version, otherVersion string) (bool, error) { - firstMajor, firstMinor, firstMicro, err := ParseVersion(version) - if err != nil { - return false, err - } - - secondMajor, secondMinor, secondMicro, err := ParseVersion(otherVersion) - if err != nil { - return false, err - } - - if firstMajor > secondMajor { - return true, nil - } else if firstMajor == secondMajor { - if firstMinor > secondMinor { - return true, nil - } else if firstMinor == secondMinor && firstMicro >= secondMicro { - return true, nil - } - } - return false, nil -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go b/examples/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go deleted file mode 100644 index 25c3810..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/version/reconcile.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 CNI 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 version - -import "fmt" - -type ErrorIncompatible struct { - Config string - Supported []string -} - -func (e *ErrorIncompatible) Details() string { - return fmt.Sprintf("config is %q, plugin supports %q", e.Config, e.Supported) -} - -func (e *ErrorIncompatible) Error() string { - return fmt.Sprintf("incompatible CNI versions: %s", e.Details()) -} - -type Reconciler struct{} - -func (r *Reconciler) Check(configVersion string, pluginInfo PluginInfo) *ErrorIncompatible { - return r.CheckRaw(configVersion, pluginInfo.SupportedVersions()) -} - -func (*Reconciler) CheckRaw(configVersion string, supportedVersions []string) *ErrorIncompatible { - for _, supportedVersion := range supportedVersions { - if configVersion == supportedVersion { - return nil - } - } - - return &ErrorIncompatible{ - Config: configVersion, - Supported: supportedVersions, - } -} diff --git a/examples/vendor/github.com/containernetworking/cni/pkg/version/version.go b/examples/vendor/github.com/containernetworking/cni/pkg/version/version.go deleted file mode 100644 index 8f3508e..0000000 --- a/examples/vendor/github.com/containernetworking/cni/pkg/version/version.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2016 CNI 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 version - -import ( - "encoding/json" - "fmt" - - "github.com/containernetworking/cni/pkg/types" - "github.com/containernetworking/cni/pkg/types/020" - "github.com/containernetworking/cni/pkg/types/current" -) - -// Current reports the version of the CNI spec implemented by this library -func Current() string { - return "0.4.0" -} - -// Legacy PluginInfo describes a plugin that is backwards compatible with the -// CNI spec version 0.1.0. In particular, a runtime compiled against the 0.1.0 -// library ought to work correctly with a plugin that reports support for -// Legacy versions. -// -// Any future CNI spec versions which meet this definition should be added to -// this list. -var Legacy = PluginSupports("0.1.0", "0.2.0") -var All = PluginSupports("0.1.0", "0.2.0", "0.3.0", "0.3.1", "0.4.0") - -var resultFactories = []struct { - supportedVersions []string - newResult types.ResultFactoryFunc -}{ - {current.SupportedVersions, current.NewResult}, - {types020.SupportedVersions, types020.NewResult}, -} - -// Finds a Result object matching the requested version (if any) and asks -// that object to parse the plugin result, returning an error if parsing failed. -func NewResult(version string, resultBytes []byte) (types.Result, error) { - reconciler := &Reconciler{} - for _, resultFactory := range resultFactories { - err := reconciler.CheckRaw(version, resultFactory.supportedVersions) - if err == nil { - // Result supports this version - return resultFactory.newResult(resultBytes) - } - } - - return nil, fmt.Errorf("unsupported CNI result version %q", version) -} - -// ParsePrevResult parses a prevResult in a NetConf structure and sets -// the NetConf's PrevResult member to the parsed Result object. -func ParsePrevResult(conf *types.NetConf) error { - if conf.RawPrevResult == nil { - return nil - } - - resultBytes, err := json.Marshal(conf.RawPrevResult) - if err != nil { - return fmt.Errorf("could not serialize prevResult: %v", err) - } - - conf.RawPrevResult = nil - conf.PrevResult, err = NewResult(conf.CNIVersion, resultBytes) - if err != nil { - return fmt.Errorf("could not parse prevResult: %v", err) - } - - return nil -} diff --git a/examples/vendor/github.com/containernetworking/plugins/pkg/ns/README.md b/examples/vendor/github.com/containernetworking/plugins/pkg/ns/README.md deleted file mode 100644 index 1e265c7..0000000 --- a/examples/vendor/github.com/containernetworking/plugins/pkg/ns/README.md +++ /dev/null @@ -1,41 +0,0 @@ -### Namespaces, Threads, and Go -On Linux each OS thread can have a different network namespace. Go's thread scheduling model switches goroutines between OS threads based on OS thread load and whether the goroutine would block other goroutines. This can result in a goroutine switching network namespaces without notice and lead to errors in your code. - -### Namespace Switching -Switching namespaces with the `ns.Set()` method is not recommended without additional strategies to prevent unexpected namespace changes when your goroutines switch OS threads. - -Go provides the `runtime.LockOSThread()` function to ensure a specific goroutine executes on its current OS thread and prevents any other goroutine from running in that thread until the locked one exits. Careful usage of `LockOSThread()` and goroutines can provide good control over which network namespace a given goroutine executes in. - -For example, you cannot rely on the `ns.Set()` namespace being the current namespace after the `Set()` call unless you do two things. First, the goroutine calling `Set()` must have previously called `LockOSThread()`. Second, you must ensure `runtime.UnlockOSThread()` is not called somewhere in-between. You also cannot rely on the initial network namespace remaining the current network namespace if any other code in your program switches namespaces, unless you have already called `LockOSThread()` in that goroutine. Note that `LockOSThread()` prevents the Go scheduler from optimally scheduling goroutines for best performance, so `LockOSThread()` should only be used in small, isolated goroutines that release the lock quickly. - -### Do() The Recommended Thing -The `ns.Do()` method provides **partial** control over network namespaces for you by implementing these strategies. All code dependent on a particular network namespace (including the root namespace) should be wrapped in the `ns.Do()` method to ensure the correct namespace is selected for the duration of your code. For example: - -```go -err = targetNs.Do(func(hostNs ns.NetNS) error { - dummy := &netlink.Dummy{ - LinkAttrs: netlink.LinkAttrs{ - Name: "dummy0", - }, - } - return netlink.LinkAdd(dummy) -}) -``` - -Note this requirement to wrap every network call is very onerous - any libraries you call might call out to network services such as DNS, and all such calls need to be protected after you call `ns.Do()`. All goroutines spawned from within the `ns.Do` will not inherit the new namespace. The CNI plugins all exit very soon after calling `ns.Do()` which helps to minimize the problem. - -When a new thread is spawned in Linux, it inherits the namespace of its parent. In versions of go **prior to 1.10**, if the runtime spawns a new OS thread, it picks the parent randomly. If the chosen parent thread has been moved to a new namespace (even temporarily), the new OS thread will be permanently "stuck in the wrong namespace", and goroutines will non-deterministically switch namespaces as they are rescheduled. - -In short, **there was no safe way to change network namespaces, even temporarily, from within a long-lived, multithreaded Go process**. If you wish to do this, you must use go 1.10 or greater. - - -### Creating network namespaces -Earlier versions of this library managed namespace creation, but as CNI does not actually utilize this feature (and it was essentially unmaintained), it was removed. If you're writing a container runtime, you should implement namespace management yourself. However, there are some gotchas when doing so, especially around handling `/var/run/netns`. A reasonably correct reference implementation, borrowed from `rkt`, can be found in `pkg/testutils/netns_linux.go` if you're in need of a source of inspiration. - - -### Further Reading - - https://github.com/golang/go/wiki/LockOSThread - - http://morsmachine.dk/go-scheduler - - https://github.com/containernetworking/cni/issues/262 - - https://golang.org/pkg/runtime/ - - https://www.weave.works/blog/linux-namespaces-and-go-don-t-mix diff --git a/examples/vendor/github.com/containernetworking/plugins/pkg/ns/ns_linux.go b/examples/vendor/github.com/containernetworking/plugins/pkg/ns/ns_linux.go deleted file mode 100644 index 3b745d4..0000000 --- a/examples/vendor/github.com/containernetworking/plugins/pkg/ns/ns_linux.go +++ /dev/null @@ -1,234 +0,0 @@ -// Copyright 2015-2017 CNI 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 ns - -import ( - "fmt" - "os" - "runtime" - "sync" - "syscall" - - "golang.org/x/sys/unix" -) - -// Returns an object representing the current OS thread's network namespace -func GetCurrentNS() (NetNS, error) { - // Lock the thread in case other goroutine executes in it and changes its - // network namespace after getCurrentThreadNetNSPath(), otherwise it might - // return an unexpected network namespace. - runtime.LockOSThread() - defer runtime.UnlockOSThread() - return GetNS(getCurrentThreadNetNSPath()) -} - -func getCurrentThreadNetNSPath() string { - // /proc/self/ns/net returns the namespace of the main thread, not - // of whatever thread this goroutine is running on. Make sure we - // use the thread's net namespace since the thread is switching around - return fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), unix.Gettid()) -} - -func (ns *netNS) Close() error { - if err := ns.errorIfClosed(); err != nil { - return err - } - - if err := ns.file.Close(); err != nil { - return fmt.Errorf("Failed to close %q: %v", ns.file.Name(), err) - } - ns.closed = true - - return nil -} - -func (ns *netNS) Set() error { - if err := ns.errorIfClosed(); err != nil { - return err - } - - if err := unix.Setns(int(ns.Fd()), unix.CLONE_NEWNET); err != nil { - return fmt.Errorf("Error switching to ns %v: %v", ns.file.Name(), err) - } - - return nil -} - -type NetNS interface { - // Executes the passed closure in this object's network namespace, - // attempting to restore the original namespace before returning. - // However, since each OS thread can have a different network namespace, - // and Go's thread scheduling is highly variable, callers cannot - // guarantee any specific namespace is set unless operations that - // require that namespace are wrapped with Do(). Also, no code called - // from Do() should call runtime.UnlockOSThread(), or the risk - // of executing code in an incorrect namespace will be greater. See - // https://github.com/golang/go/wiki/LockOSThread for further details. - Do(toRun func(NetNS) error) error - - // Sets the current network namespace to this object's network namespace. - // Note that since Go's thread scheduling is highly variable, callers - // cannot guarantee the requested namespace will be the current namespace - // after this function is called; to ensure this wrap operations that - // require the namespace with Do() instead. - Set() error - - // Returns the filesystem path representing this object's network namespace - Path() string - - // Returns a file descriptor representing this object's network namespace - Fd() uintptr - - // Cleans up this instance of the network namespace; if this instance - // is the last user the namespace will be destroyed - Close() error -} - -type netNS struct { - file *os.File - closed bool -} - -// netNS implements the NetNS interface -var _ NetNS = &netNS{} - -const ( - // https://github.com/torvalds/linux/blob/master/include/uapi/linux/magic.h - NSFS_MAGIC = 0x6e736673 - PROCFS_MAGIC = 0x9fa0 -) - -type NSPathNotExistErr struct{ msg string } - -func (e NSPathNotExistErr) Error() string { return e.msg } - -type NSPathNotNSErr struct{ msg string } - -func (e NSPathNotNSErr) Error() string { return e.msg } - -func IsNSorErr(nspath string) error { - stat := syscall.Statfs_t{} - if err := syscall.Statfs(nspath, &stat); err != nil { - if os.IsNotExist(err) { - err = NSPathNotExistErr{msg: fmt.Sprintf("failed to Statfs %q: %v", nspath, err)} - } else { - err = fmt.Errorf("failed to Statfs %q: %v", nspath, err) - } - return err - } - - switch stat.Type { - case PROCFS_MAGIC, NSFS_MAGIC: - return nil - default: - return NSPathNotNSErr{msg: fmt.Sprintf("unknown FS magic on %q: %x", nspath, stat.Type)} - } -} - -// Returns an object representing the namespace referred to by @path -func GetNS(nspath string) (NetNS, error) { - err := IsNSorErr(nspath) - if err != nil { - return nil, err - } - - fd, err := os.Open(nspath) - if err != nil { - return nil, err - } - - return &netNS{file: fd}, nil -} - -func (ns *netNS) Path() string { - return ns.file.Name() -} - -func (ns *netNS) Fd() uintptr { - return ns.file.Fd() -} - -func (ns *netNS) errorIfClosed() error { - if ns.closed { - return fmt.Errorf("%q has already been closed", ns.file.Name()) - } - return nil -} - -func (ns *netNS) Do(toRun func(NetNS) error) error { - if err := ns.errorIfClosed(); err != nil { - return err - } - - containedCall := func(hostNS NetNS) error { - threadNS, err := GetCurrentNS() - if err != nil { - return fmt.Errorf("failed to open current netns: %v", err) - } - defer threadNS.Close() - - // switch to target namespace - if err = ns.Set(); err != nil { - return fmt.Errorf("error switching to ns %v: %v", ns.file.Name(), err) - } - defer func() { - err := threadNS.Set() // switch back - if err == nil { - // Unlock the current thread only when we successfully switched back - // to the original namespace; otherwise leave the thread locked which - // will force the runtime to scrap the current thread, that is maybe - // not as optimal but at least always safe to do. - runtime.UnlockOSThread() - } - }() - - return toRun(hostNS) - } - - // save a handle to current network namespace - hostNS, err := GetCurrentNS() - if err != nil { - return fmt.Errorf("Failed to open current namespace: %v", err) - } - defer hostNS.Close() - - var wg sync.WaitGroup - wg.Add(1) - - // Start the callback in a new green thread so that if we later fail - // to switch the namespace back to the original one, we can safely - // leave the thread locked to die without a risk of the current thread - // left lingering with incorrect namespace. - var innerError error - go func() { - defer wg.Done() - runtime.LockOSThread() - innerError = containedCall(hostNS) - }() - wg.Wait() - - return innerError -} - -// WithNetNSPath executes the passed closure under the given network -// namespace, restoring the original namespace afterwards. -func WithNetNSPath(nspath string, toRun func(NetNS) error) error { - ns, err := GetNS(nspath) - if err != nil { - return err - } - defer ns.Close() - return ns.Do(toRun) -} diff --git a/examples/vendor/github.com/containers/common/libimage/download.go b/examples/vendor/github.com/containers/common/libimage/download.go deleted file mode 100644 index 54edf1b..0000000 --- a/examples/vendor/github.com/containers/common/libimage/download.go +++ /dev/null @@ -1,46 +0,0 @@ -package libimage - -import ( - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - - "github.com/pkg/errors" -) - -// tmpdir returns a path to a temporary directory. -func tmpdir() string { - tmpdir := os.Getenv("TMPDIR") - if tmpdir == "" { - tmpdir = "/var/tmp" - } - - return tmpdir -} - -// downloadFromURL downloads an image in the format "https:/example.com/myimage.tar" -// and temporarily saves in it $TMPDIR/importxyz, which is deleted after the image is imported -func (r *Runtime) downloadFromURL(source string) (string, error) { - fmt.Printf("Downloading from %q\n", source) - - outFile, err := ioutil.TempFile(r.systemContext.BigFilesTemporaryDir, "import") - if err != nil { - return "", errors.Wrap(err, "error creating file") - } - defer outFile.Close() - - response, err := http.Get(source) // nolint:noctx - if err != nil { - return "", errors.Wrapf(err, "error downloading %q", source) - } - defer response.Body.Close() - - _, err = io.Copy(outFile, response.Body) - if err != nil { - return "", errors.Wrapf(err, "error saving %s to %s", source, outFile.Name()) - } - - return outFile.Name(), nil -} diff --git a/examples/vendor/github.com/containers/common/libimage/filters.go b/examples/vendor/github.com/containers/common/libimage/filters.go deleted file mode 100644 index 447ea57..0000000 --- a/examples/vendor/github.com/containers/common/libimage/filters.go +++ /dev/null @@ -1,252 +0,0 @@ -package libimage - -import ( - "context" - "fmt" - "path/filepath" - "strconv" - "strings" - "time" - - filtersPkg "github.com/containers/common/pkg/filters" - "github.com/containers/common/pkg/timetype" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// filterFunc is a prototype for a positive image filter. Returning `true` -// indicates that the image matches the criteria. -type filterFunc func(*Image) (bool, error) - -// filterImages returns a slice of images which are passing all specified -// filters. -func filterImages(images []*Image, filters []filterFunc) ([]*Image, error) { - if len(filters) == 0 { - return images, nil - } - result := []*Image{} - for i := range images { - include := true - var err error - for _, filter := range filters { - include, err = filter(images[i]) - if err != nil { - return nil, err - } - if !include { - break - } - } - if include { - result = append(result, images[i]) - } - } - return result, nil -} - -// compileImageFilters creates `filterFunc`s for the specified filters. The -// required format is `key=value` with the following supported keys: -// after, since, before, containers, dangling, id, label, readonly, reference, intermediate -func (r *Runtime) compileImageFilters(ctx context.Context, filters []string) ([]filterFunc, error) { - logrus.Tracef("Parsing image filters %s", filters) - - var tree *layerTree - getTree := func() (*layerTree, error) { - if tree == nil { - t, err := r.layerTree() - if err != nil { - return nil, err - } - tree = t - } - return tree, nil - } - - filterFuncs := []filterFunc{} - for _, filter := range filters { - var key, value string - split := strings.SplitN(filter, "=", 2) - if len(split) != 2 { - return nil, errors.Errorf("invalid image filter %q: must be in the format %q", filter, "filter=value") - } - - key = split[0] - value = split[1] - switch key { - - case "after", "since": - img, _, err := r.LookupImage(value, nil) - if err != nil { - return nil, errors.Wrapf(err, "could not find local image for filter %q", filter) - } - filterFuncs = append(filterFuncs, filterAfter(img.Created())) - - case "before": - img, _, err := r.LookupImage(value, nil) - if err != nil { - return nil, errors.Wrapf(err, "could not find local image for filter %q", filter) - } - filterFuncs = append(filterFuncs, filterBefore(img.Created())) - - case "containers": - containers, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.Wrapf(err, "non-boolean value %q for dangling filter", value) - } - filterFuncs = append(filterFuncs, filterContainers(containers)) - - case "dangling": - dangling, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.Wrapf(err, "non-boolean value %q for dangling filter", value) - } - t, err := getTree() - if err != nil { - return nil, err - } - filterFuncs = append(filterFuncs, filterDangling(ctx, dangling, t)) - - case "id": - filterFuncs = append(filterFuncs, filterID(value)) - - case "intermediate": - intermediate, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.Wrapf(err, "non-boolean value %q for intermediate filter", value) - } - t, err := getTree() - if err != nil { - return nil, err - } - filterFuncs = append(filterFuncs, filterIntermediate(ctx, intermediate, t)) - - case "label": - filterFuncs = append(filterFuncs, filterLabel(ctx, value)) - - case "readonly": - readOnly, err := strconv.ParseBool(value) - if err != nil { - return nil, errors.Wrapf(err, "non-boolean value %q for readonly filter", value) - } - filterFuncs = append(filterFuncs, filterReadOnly(readOnly)) - - case "reference": - filterFuncs = append(filterFuncs, filterReference(value)) - - case "until": - ts, err := timetype.GetTimestamp(value, time.Now()) - if err != nil { - return nil, err - } - seconds, nanoseconds, err := timetype.ParseTimestamps(ts, 0) - if err != nil { - return nil, err - } - until := time.Unix(seconds, nanoseconds) - filterFuncs = append(filterFuncs, filterBefore(until)) - - default: - return nil, errors.Errorf("unsupported image filter %q", key) - } - } - - return filterFuncs, nil -} - -// filterReference creates a reference filter for matching the specified value. -func filterReference(value string) filterFunc { - // Replacing all '/' with '|' so that filepath.Match() can work '|' - // character is not valid in image name, so this is safe. - // - // TODO: this has been copied from Podman and requires some more review - // and especially tests. - filter := fmt.Sprintf("*%s*", value) - filter = strings.ReplaceAll(filter, "/", "|") - return func(img *Image) (bool, error) { - if len(value) < 1 { - return true, nil - } - for _, name := range img.Names() { - newName := strings.ReplaceAll(name, "/", "|") - match, _ := filepath.Match(filter, newName) - if match { - return true, nil - } - } - return false, nil - } -} - -// filterLabel creates a label for matching the specified value. -func filterLabel(ctx context.Context, value string) filterFunc { - return func(img *Image) (bool, error) { - labels, err := img.Labels(ctx) - if err != nil { - return false, err - } - return filtersPkg.MatchLabelFilters([]string{value}, labels), nil - } -} - -// filterAfter creates an after filter for matching the specified value. -func filterAfter(value time.Time) filterFunc { - return func(img *Image) (bool, error) { - return img.Created().After(value), nil - } -} - -// filterBefore creates a before filter for matching the specified value. -func filterBefore(value time.Time) filterFunc { - return func(img *Image) (bool, error) { - return img.Created().Before(value), nil - } -} - -// filterReadOnly creates a readonly filter for matching the specified value. -func filterReadOnly(value bool) filterFunc { - return func(img *Image) (bool, error) { - return img.IsReadOnly() == value, nil - } -} - -// filterContainers creates a container filter for matching the specified value. -func filterContainers(value bool) filterFunc { - return func(img *Image) (bool, error) { - ctrs, err := img.Containers() - if err != nil { - return false, err - } - return (len(ctrs) > 0) == value, nil - } -} - -// filterDangling creates a dangling filter for matching the specified value. -func filterDangling(ctx context.Context, value bool, tree *layerTree) filterFunc { - return func(img *Image) (bool, error) { - isDangling, err := img.isDangling(ctx, tree) - if err != nil { - return false, err - } - return isDangling == value, nil - } -} - -// filterID creates an image-ID filter for matching the specified value. -func filterID(value string) filterFunc { - return func(img *Image) (bool, error) { - return img.ID() == value, nil - } -} - -// filterIntermediate creates an intermediate filter for images. An image is -// considered to be an intermediate image if it is dangling (i.e., no tags) and -// has no children (i.e., no other image depends on it). -func filterIntermediate(ctx context.Context, value bool, tree *layerTree) filterFunc { - return func(img *Image) (bool, error) { - isIntermediate, err := img.isIntermediate(ctx, tree) - if err != nil { - return false, err - } - return isIntermediate == value, nil - } -} diff --git a/examples/vendor/github.com/containers/common/libimage/manifests/copy.go b/examples/vendor/github.com/containers/common/libimage/manifests/copy.go deleted file mode 100644 index 7e651a4..0000000 --- a/examples/vendor/github.com/containers/common/libimage/manifests/copy.go +++ /dev/null @@ -1,15 +0,0 @@ -package manifests - -import ( - "github.com/containers/image/v5/signature" -) - -var ( - // storageAllowedPolicyScopes overrides the policy for local storage - // to ensure that we can read images from it. - storageAllowedPolicyScopes = signature.PolicyTransportScopes{ - "": []signature.PolicyRequirement{ - signature.NewPRInsecureAcceptAnything(), - }, - } -) diff --git a/examples/vendor/github.com/containers/common/pkg/config/default_unsupported.go b/examples/vendor/github.com/containers/common/pkg/config/default_unsupported.go deleted file mode 100644 index e38fb81..0000000 --- a/examples/vendor/github.com/containers/common/pkg/config/default_unsupported.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !linux - -package config - -// getDefaultRootlessNetwork returns the default rootless network configuration. -// It is "cni" for non-Linux OSes (to better support `podman-machine` usecases). -func getDefaultRootlessNetwork() string { - return "cni" -} - -// isCgroup2UnifiedMode returns whether we are running in cgroup2 mode. -func isCgroup2UnifiedMode() (isUnified bool, isUnifiedErr error) { - return false, nil -} - -// getDefaultProcessLimits returns the nofile and nproc for the current process in ulimits format -func getDefaultProcessLimits() []string { - return []string{} -} diff --git a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/key.go b/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/key.go deleted file mode 100644 index bf6cc87..0000000 --- a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/key.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2015 Jesse Sipprell. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux -// +build linux - -package keyctl - -import ( - "golang.org/x/sys/unix" -) - -// Key represents a single key linked to one or more kernel keyrings. -type Key struct { - Name string - - id, ring keyID - size int -} - -// ID returns the 32-bit kernel identifier for a specific key -func (k *Key) ID() int32 { - return int32(k.id) -} - -// Get the key's value as a byte slice -func (k *Key) Get() ([]byte, error) { - var ( - b []byte - err error - sizeRead int - ) - - if k.size == 0 { - k.size = 512 - } - - size := k.size - - b = make([]byte, int(size)) - sizeRead = size + 1 - for sizeRead > size { - r1, err := unix.KeyctlBuffer(unix.KEYCTL_READ, int(k.id), b, size) - if err != nil { - return nil, err - } - - if sizeRead = int(r1); sizeRead > size { - b = make([]byte, sizeRead) - size = sizeRead - sizeRead = size + 1 - } else { - k.size = sizeRead - } - } - return b[:k.size], err -} - -// Unlink a key from the keyring it was loaded from (or added to). If the key -// is not linked to any other keyrings, it is destroyed. -func (k *Key) Unlink() error { - _, err := unix.KeyctlInt(unix.KEYCTL_UNLINK, int(k.id), int(k.ring), 0, 0) - return err -} - -// Describe returns a string describing the attributes of a specified key -func (k *Key) Describe() (string, error) { - keyAttr, err := unix.KeyctlString(unix.KEYCTL_DESCRIBE, int(k.id)) - if err != nil { - return "", err - } - return keyAttr, nil -} diff --git a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/keyring.go b/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/keyring.go deleted file mode 100644 index 5eaad61..0000000 --- a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/keyring.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2015 Jesse Sipprell. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux -// +build linux - -// Package keyctl is a Go interface to linux kernel keyrings (keyctl interface) -package keyctl - -import ( - "unsafe" - - "golang.org/x/sys/unix" -) - -// Keyring is the basic interface to a linux keyctl keyring. -type Keyring interface { - ID - Add(string, []byte) (*Key, error) - Search(string) (*Key, error) -} - -type keyring struct { - id keyID -} - -// ID is unique 32-bit serial number identifiers for all Keys and Keyrings have. -type ID interface { - ID() int32 -} - -// Add a new key to a keyring. The key can be searched for later by name. -func (kr *keyring) Add(name string, key []byte) (*Key, error) { - r, err := unix.AddKey("user", name, key, int(kr.id)) - if err == nil { - key := &Key{Name: name, id: keyID(r), ring: kr.id} - return key, nil - } - return nil, err -} - -// Search for a key by name, this also searches child keyrings linked to this -// one. The key, if found, is linked to the top keyring that Search() was called -// from. -func (kr *keyring) Search(name string) (*Key, error) { - id, err := unix.KeyctlSearch(int(kr.id), "user", name, 0) - if err == nil { - return &Key{Name: name, id: keyID(id), ring: kr.id}, nil - } - return nil, err -} - -// ID returns the 32-bit kernel identifier of a keyring -func (kr *keyring) ID() int32 { - return int32(kr.id) -} - -// SessionKeyring returns the current login session keyring -func SessionKeyring() (Keyring, error) { - return newKeyring(unix.KEY_SPEC_SESSION_KEYRING) -} - -// UserKeyring returns the keyring specific to the current user. -func UserKeyring() (Keyring, error) { - return newKeyring(unix.KEY_SPEC_USER_KEYRING) -} - -// Unlink an object from a keyring -func Unlink(parent Keyring, child ID) error { - _, err := unix.KeyctlInt(unix.KEYCTL_UNLINK, int(child.ID()), int(parent.ID()), 0, 0) - return err -} - -// Link a key into a keyring -func Link(parent Keyring, child ID) error { - _, err := unix.KeyctlInt(unix.KEYCTL_LINK, int(child.ID()), int(parent.ID()), 0, 0) - return err -} - -// ReadUserKeyring reads user keyring and returns slice of key with id(key_serial_t) representing the IDs of all the keys that are linked to it -func ReadUserKeyring() ([]*Key, error) { - var ( - b []byte - err error - sizeRead int - ) - krSize := 4 - size := krSize - b = make([]byte, size) - sizeRead = size + 1 - for sizeRead > size { - r1, err := unix.KeyctlBuffer(unix.KEYCTL_READ, unix.KEY_SPEC_USER_KEYRING, b, size) - if err != nil { - return nil, err - } - - if sizeRead = int(r1); sizeRead > size { - b = make([]byte, sizeRead) - size = sizeRead - sizeRead = size + 1 - } else { - krSize = sizeRead - } - } - keyIDs := getKeyIDsFromByte(b[:krSize]) - return keyIDs, err -} - -func getKeyIDsFromByte(byteKeyIDs []byte) []*Key { - idSize := 4 - var keys []*Key - for idx := 0; idx+idSize <= len(byteKeyIDs); idx = idx + idSize { - tempID := *(*int32)(unsafe.Pointer(&byteKeyIDs[idx])) - keys = append(keys, &Key{id: keyID(tempID)}) - } - return keys -} diff --git a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/perm.go b/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/perm.go deleted file mode 100644 index 5f4d215..0000000 --- a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/perm.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2015 Jesse Sipprell. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux -// +build linux - -package keyctl - -import ( - "golang.org/x/sys/unix" -) - -// KeyPerm represents in-kernel access control permission to keys and keyrings -// as a 32-bit integer broken up into four permission sets, one per byte. -// In MSB order, the perms are: Processor, User, Group, Other. -type KeyPerm uint32 - -const ( - // PermOtherAll sets all permission for Other - PermOtherAll KeyPerm = 0x3f << (8 * iota) - // PermGroupAll sets all permission for Group - PermGroupAll - // PermUserAll sets all permission for User - PermUserAll - // PermProcessAll sets all permission for Processor - PermProcessAll -) - -// SetPerm sets the permissions on a key or keyring. -func SetPerm(k ID, p KeyPerm) error { - err := unix.KeyctlSetperm(int(k.ID()), uint32(p)) - return err -} diff --git a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/sys_linux.go b/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/sys_linux.go deleted file mode 100644 index f61666e..0000000 --- a/examples/vendor/github.com/containers/image/v5/internal/pkg/keyctl/sys_linux.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2015 Jesse Sipprell. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build linux -// +build linux - -package keyctl - -import ( - "golang.org/x/sys/unix" -) - -type keyID int32 - -func newKeyring(id keyID) (*keyring, error) { - r1, err := unix.KeyctlGetKeyringID(int(id), true) - if err != nil { - return nil, err - } - - if id < 0 { - r1 = int(id) - } - return &keyring{id: keyID(r1)}, nil -} diff --git a/examples/vendor/github.com/containers/image/v5/internal/types/types.go b/examples/vendor/github.com/containers/image/v5/internal/types/types.go deleted file mode 100644 index 388f8cf..0000000 --- a/examples/vendor/github.com/containers/image/v5/internal/types/types.go +++ /dev/null @@ -1,91 +0,0 @@ -package types - -import ( - "context" - "io" - - "github.com/containers/image/v5/docker/reference" - publicTypes "github.com/containers/image/v5/types" -) - -// ImageDestinationWithOptions is an internal extension to the ImageDestination -// interface. -type ImageDestinationWithOptions interface { - publicTypes.ImageDestination - - // PutBlobWithOptions is a wrapper around PutBlob. If - // options.LayerIndex is set, the blob will be committed directly. - // Either by the calling goroutine or by another goroutine already - // committing layers. - // - // Please note that TryReusingBlobWithOptions and PutBlobWithOptions - // *must* be used the together. Mixing the two with non "WithOptions" - // functions is not supported. - PutBlobWithOptions(ctx context.Context, stream io.Reader, blobinfo publicTypes.BlobInfo, options PutBlobOptions) (publicTypes.BlobInfo, error) - - // TryReusingBlobWithOptions is a wrapper around TryReusingBlob. If - // options.LayerIndex is set, the reused blob will be recoreded as - // already pulled. - // - // Please note that TryReusingBlobWithOptions and PutBlobWithOptions - // *must* be used the together. Mixing the two with non "WithOptions" - // functions is not supported. - TryReusingBlobWithOptions(ctx context.Context, blobinfo publicTypes.BlobInfo, options TryReusingBlobOptions) (bool, publicTypes.BlobInfo, error) -} - -// PutBlobOptions are used in PutBlobWithOptions. -type PutBlobOptions struct { - // Cache to look up blob infos. - Cache publicTypes.BlobInfoCache - // Denotes whether the blob is a config or not. - IsConfig bool - // Indicates an empty layer. - EmptyLayer bool - // The corresponding index in the layer slice. - LayerIndex *int -} - -// TryReusingBlobOptions are used in TryReusingBlobWithOptions. -type TryReusingBlobOptions struct { - // Cache to look up blob infos. - Cache publicTypes.BlobInfoCache - // Use an equivalent of the desired blob. - CanSubstitute bool - // Indicates an empty layer. - EmptyLayer bool - // The corresponding index in the layer slice. - LayerIndex *int - // The reference of the image that contains the target blob. - SrcRef reference.Named -} - -// ImageSourceChunk is a portion of a blob. -// This API is experimental and can be changed without bumping the major version number. -type ImageSourceChunk struct { - Offset uint64 - Length uint64 -} - -// ImageSourceSeekable is an image source that permits to fetch chunks of the entire blob. -// This API is experimental and can be changed without bumping the major version number. -type ImageSourceSeekable interface { - // GetBlobAt returns a stream for the specified blob. - // The specified chunks must be not overlapping and sorted by their offset. - GetBlobAt(context.Context, publicTypes.BlobInfo, []ImageSourceChunk) (chan io.ReadCloser, chan error, error) -} - -// ImageDestinationPartial is a service to store a blob by requesting the missing chunks to a ImageSourceSeekable. -// This API is experimental and can be changed without bumping the major version number. -type ImageDestinationPartial interface { - // PutBlobPartial writes contents of stream and returns data representing the result. - PutBlobPartial(ctx context.Context, stream ImageSourceSeekable, srcInfo publicTypes.BlobInfo, cache publicTypes.BlobInfoCache) (publicTypes.BlobInfo, error) -} - -// BadPartialRequestError is returned by ImageSourceSeekable.GetBlobAt on an invalid request. -type BadPartialRequestError struct { - Status string -} - -func (e BadPartialRequestError) Error() string { - return e.Status -} diff --git a/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_linux.go b/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_linux.go deleted file mode 100644 index 0bf1612..0000000 --- a/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_linux.go +++ /dev/null @@ -1,119 +0,0 @@ -package config - -import ( - "fmt" - "strings" - - "github.com/containers/image/v5/internal/pkg/keyctl" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -// NOTE: none of the functions here are currently used. If we ever want to -// re-enable keyring support, we should introduce a similar built-in credential -// helpers as for `sysregistriesv2.AuthenticationFileHelper`. - -const keyDescribePrefix = "container-registry-login:" //nolint:deadcode,unused - -func getAuthFromKernelKeyring(registry string) (string, string, error) { //nolint:deadcode,unused - userkeyring, err := keyctl.UserKeyring() - if err != nil { - return "", "", err - } - key, err := userkeyring.Search(genDescription(registry)) - if err != nil { - return "", "", err - } - authData, err := key.Get() - if err != nil { - return "", "", err - } - parts := strings.SplitN(string(authData), "\x00", 2) - if len(parts) != 2 { - return "", "", nil - } - return parts[0], parts[1], nil -} - -func deleteAuthFromKernelKeyring(registry string) error { //nolint:deadcode,unused - userkeyring, err := keyctl.UserKeyring() - - if err != nil { - return err - } - key, err := userkeyring.Search(genDescription(registry)) - if err != nil { - return err - } - return key.Unlink() -} - -func removeAllAuthFromKernelKeyring() error { //nolint:deadcode,unused - keys, err := keyctl.ReadUserKeyring() - if err != nil { - return err - } - - userkeyring, err := keyctl.UserKeyring() - if err != nil { - return err - } - - for _, k := range keys { - keyAttr, err := k.Describe() - if err != nil { - return err - } - // split string "type;uid;gid;perm;description" - keyAttrs := strings.SplitN(keyAttr, ";", 5) - if len(keyAttrs) < 5 { - return errors.Errorf("Key attributes of %d are not available", k.ID()) - } - keyDescribe := keyAttrs[4] - if strings.HasPrefix(keyDescribe, keyDescribePrefix) { - err := keyctl.Unlink(userkeyring, k) - if err != nil { - return errors.Wrapf(err, "unlinking key %d", k.ID()) - } - logrus.Debugf("unlinked key %d:%s", k.ID(), keyAttr) - } - } - return nil -} - -func setAuthToKernelKeyring(registry, username, password string) error { //nolint:deadcode,unused - keyring, err := keyctl.SessionKeyring() - if err != nil { - return err - } - id, err := keyring.Add(genDescription(registry), []byte(fmt.Sprintf("%s\x00%s", username, password))) - if err != nil { - return err - } - - // sets all permission(view,read,write,search,link,set attribute) for current user - // it enables the user to search the key after it linked to user keyring and unlinked from session keyring - err = keyctl.SetPerm(id, keyctl.PermUserAll) - if err != nil { - return err - } - // link the key to userKeyring - userKeyring, err := keyctl.UserKeyring() - if err != nil { - return errors.Wrapf(err, "getting user keyring") - } - err = keyctl.Link(userKeyring, id) - if err != nil { - return errors.Wrapf(err, "linking the key to user keyring") - } - // unlink the key from session keyring - err = keyctl.Unlink(keyring, id) - if err != nil { - return errors.Wrapf(err, "unlinking the key from session keyring") - } - return nil -} - -func genDescription(registry string) string { //nolint:deadcode,unused - return fmt.Sprintf("%s%s", keyDescribePrefix, registry) -} diff --git a/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_unsupported.go b/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_unsupported.go deleted file mode 100644 index d9827d8..0000000 --- a/examples/vendor/github.com/containers/image/v5/pkg/docker/config/config_unsupported.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build !linux && (!386 || !amd64) -// +build !linux -// +build !386 !amd64 - -package config - -func getAuthFromKernelKeyring(registry string) (string, string, error) { //nolint:deadcode,unused - return "", "", ErrNotSupported -} - -func deleteAuthFromKernelKeyring(registry string) error { //nolint:deadcode,unused - return ErrNotSupported -} - -func setAuthToKernelKeyring(registry, username, password string) error { //nolint:deadcode,unused - return ErrNotSupported -} - -func removeAllAuthFromKernelKeyring() error { //nolint:deadcode,unused - return ErrNotSupported -} diff --git a/examples/vendor/github.com/containers/podman/v3/libpod/define/annotations.go b/examples/vendor/github.com/containers/podman/v3/libpod/define/annotations.go deleted file mode 100644 index f6b1c06..0000000 --- a/examples/vendor/github.com/containers/podman/v3/libpod/define/annotations.go +++ /dev/null @@ -1,68 +0,0 @@ -package define - -const ( - // InspectAnnotationCIDFile is used by Inspect to determine if a - // container ID file was created for the container. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationCIDFile = "io.podman.annotations.cid-file" - // InspectAnnotationAutoremove is used by Inspect to determine if a - // container will be automatically removed on exit. - // If an annotation with this key is found in the OCI spec and is one of - // the two supported boolean values (InspectResponseTrue and - // InspectResponseFalse) it will be used in the output of Inspect(). - InspectAnnotationAutoremove = "io.podman.annotations.autoremove" - // InspectAnnotationVolumesFrom is used by Inspect to identify - // containers whose volumes are are being used by this container. - // It is expected to be a comma-separated list of container names and/or - // IDs. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationVolumesFrom = "io.podman.annotations.volumes-from" - // InspectAnnotationPrivileged is used by Inspect to identify containers - // which are privileged (IE, running with elevated privileges). - // It is expected to be a boolean, populated by one of - // InspectResponseTrue or InspectResponseFalse. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationPrivileged = "io.podman.annotations.privileged" - // InspectAnnotationPublishAll is used by Inspect to identify containers - // which have all the ports from their image published. - // It is expected to be a boolean, populated by one of - // InspectResponseTrue or InspectResponseFalse. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationPublishAll = "io.podman.annotations.publish-all" - // InspectAnnotationInit is used by Inspect to identify containers that - // mount an init binary in. - // It is expected to be a boolean, populated by one of - // InspectResponseTrue or InspectResponseFalse. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationInit = "io.podman.annotations.init" - // InspectAnnotationLabel is used by Inspect to identify containers with - // special SELinux-related settings. It is used to populate the output - // of the SecurityOpt setting. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationLabel = "io.podman.annotations.label" - // InspectAnnotationSeccomp is used by Inspect to identify containers - // with special Seccomp-related settings. It is used to populate the - // output of the SecurityOpt setting in Inspect. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationSeccomp = "io.podman.annotations.seccomp" - // InspectAnnotationApparmor is used by Inspect to identify containers - // with special Apparmor-related settings. It is used to populate the - // output of the SecurityOpt setting. - // If an annotation with this key is found in the OCI spec, it will be - // used in the output of Inspect(). - InspectAnnotationApparmor = "io.podman.annotations.apparmor" - - // InspectResponseTrue is a boolean True response for an inspect - // annotation. - InspectResponseTrue = "TRUE" - // InspectResponseFalse is a boolean False response for an inspect - // annotation. - InspectResponseFalse = "FALSE" -) diff --git a/examples/vendor/github.com/containers/podman/v3/libpod/events/logfile.go b/examples/vendor/github.com/containers/podman/v3/libpod/events/logfile.go deleted file mode 100644 index e3f0ab8..0000000 --- a/examples/vendor/github.com/containers/podman/v3/libpod/events/logfile.go +++ /dev/null @@ -1,106 +0,0 @@ -package events - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/containers/podman/v3/pkg/util" - "github.com/containers/storage/pkg/lockfile" - "github.com/pkg/errors" -) - -// EventLogFile is the structure for event writing to a logfile. It contains the eventer -// options and the event itself. Methods for reading and writing are also defined from it. -type EventLogFile struct { - options EventerOptions -} - -// Writes to the log file -func (e EventLogFile) Write(ee Event) error { - // We need to lock events file - lock, err := lockfile.GetLockfile(e.options.LogFilePath + ".lock") - if err != nil { - return err - } - lock.Lock() - defer lock.Unlock() - f, err := os.OpenFile(e.options.LogFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0700) - if err != nil { - return err - } - defer f.Close() - eventJSONString, err := ee.ToJSONString() - if err != nil { - return err - } - if _, err := f.WriteString(fmt.Sprintf("%s\n", eventJSONString)); err != nil { - return err - } - return nil -} - -// Reads from the log file -func (e EventLogFile) Read(ctx context.Context, options ReadOptions) error { - defer close(options.EventChannel) - filterMap, err := generateEventFilters(options.Filters, options.Since, options.Until) - if err != nil { - return errors.Wrapf(err, "failed to parse event filters") - } - t, err := e.getTail(options) - if err != nil { - return err - } - if len(options.Until) > 0 { - untilTime, err := util.ParseInputTime(options.Until, false) - if err != nil { - return err - } - go func() { - time.Sleep(time.Until(untilTime)) - t.Stop() - }() - } - funcDone := make(chan bool) - copy := true - go func() { - select { - case <-funcDone: - // Do nothing - case <-ctx.Done(): - copy = false - t.Kill(errors.New("hangup by client")) - } - }() - for line := range t.Lines { - select { - case <-ctx.Done(): - // the consumer has cancelled - return nil - default: - // fallthrough - } - - event, err := newEventFromJSONString(line.Text) - if err != nil { - return err - } - switch event.Type { - case Image, Volume, Pod, System, Container, Network: - // no-op - default: - return errors.Errorf("event type %s is not valid in %s", event.Type.String(), e.options.LogFilePath) - } - if copy && applyFilters(event, filterMap) { - options.EventChannel <- event - } - } - funcDone <- true - return nil -} - -// String returns a string representation of the logger -func (e EventLogFile) String() string { - return LogFile.String() -} diff --git a/examples/vendor/github.com/containers/podman/v3/libpod/network/types/const.go b/examples/vendor/github.com/containers/podman/v3/libpod/network/types/const.go deleted file mode 100644 index be7ef03..0000000 --- a/examples/vendor/github.com/containers/podman/v3/libpod/network/types/const.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -const ( - // BridgeNetworkDriver defines the bridge driver - BridgeNetworkDriver = "bridge" - // DefaultNetworkDriver is the default network type used - DefaultNetworkDriver = BridgeNetworkDriver - // MacVLANNetworkDriver defines the macvlan driver - MacVLANNetworkDriver = "macvlan" - - // IPAM drivers - // HostLocalIPAMDriver store the ip - HostLocalIPAMDriver = "host-local" - // DHCPIPAMDriver get subnet and ip from dhcp server - DHCPIPAMDriver = "dhcp" - - // DefaultSubnet is the name that will be used for the default CNI network. - DefaultNetworkName = "podman" - // DefaultSubnet is the subnet that will be used for the default CNI network. - DefaultSubnet = "10.88.0.0/16" -) diff --git a/examples/vendor/github.com/containers/podman/v3/pkg/bindings/containers/checkpoint.go b/examples/vendor/github.com/containers/podman/v3/pkg/bindings/containers/checkpoint.go deleted file mode 100644 index 7f7080f..0000000 --- a/examples/vendor/github.com/containers/podman/v3/pkg/bindings/containers/checkpoint.go +++ /dev/null @@ -1,62 +0,0 @@ -package containers - -import ( - "context" - "net/http" - - "github.com/containers/podman/v3/pkg/bindings" - "github.com/containers/podman/v3/pkg/domain/entities" -) - -// Checkpoint checkpoints the given container (identified by nameOrID). All additional -// options are options and allow for more fine grained control of the checkpoint process. -func Checkpoint(ctx context.Context, nameOrID string, options *CheckpointOptions) (*entities.CheckpointReport, error) { - var report entities.CheckpointReport - if options == nil { - options = new(CheckpointOptions) - } - conn, err := bindings.GetClient(ctx) - if err != nil { - return nil, err - } - params, err := options.ToParams() - if err != nil { - return nil, err - } - response, err := conn.DoRequest(nil, http.MethodPost, "/containers/%s/checkpoint", params, nil, nameOrID) - if err != nil { - return nil, err - } - defer response.Body.Close() - - return &report, response.Process(&report) -} - -// Restore restores a checkpointed container to running. The container is identified by the nameOrID option. All -// additional options are optional and allow finer control of the restore process. -func Restore(ctx context.Context, nameOrID string, options *RestoreOptions) (*entities.RestoreReport, error) { - var report entities.RestoreReport - if options == nil { - options = new(RestoreOptions) - } - conn, err := bindings.GetClient(ctx) - if err != nil { - return nil, err - } - params, err := options.ToParams() - if err != nil { - return nil, err - } - // The import key is a reserved golang term - params.Del("ImportArchive") - if i := options.GetImportAchive(); options.Changed("ImportArchive") { - params.Set("import", i) - } - response, err := conn.DoRequest(nil, http.MethodPost, "/containers/%s/restore", params, nil, nameOrID) - if err != nil { - return nil, err - } - defer response.Body.Close() - - return &report, response.Process(&report) -} diff --git a/examples/vendor/github.com/containers/podman/v3/pkg/bindings/images/types_remove_options.go b/examples/vendor/github.com/containers/podman/v3/pkg/bindings/images/types_remove_options.go deleted file mode 100644 index 30321db..0000000 --- a/examples/vendor/github.com/containers/podman/v3/pkg/bindings/images/types_remove_options.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by go generate; DO NOT EDIT. -package images - -import ( - "net/url" - - "github.com/containers/podman/v3/pkg/bindings/internal/util" -) - -// Changed returns true if named field has been set -func (o *RemoveOptions) Changed(fieldName string) bool { - return util.Changed(o, fieldName) -} - -// ToParams formats struct fields to be passed to API service -func (o *RemoveOptions) ToParams() (url.Values, error) { - return util.ToParams(o) -} - -// WithAll set field All to given value -func (o *RemoveOptions) WithAll(value bool) *RemoveOptions { - o.All = &value - return o -} - -// GetAll returns value of field All -func (o *RemoveOptions) GetAll() bool { - if o.All == nil { - var z bool - return z - } - return *o.All -} - -// WithForce set field Force to given value -func (o *RemoveOptions) WithForce(value bool) *RemoveOptions { - o.Force = &value - return o -} - -// GetForce returns value of field Force -func (o *RemoveOptions) GetForce() bool { - if o.Force == nil { - var z bool - return z - } - return *o.Force -} diff --git a/examples/vendor/github.com/containers/podman/v3/pkg/domain/entities/manifest.go b/examples/vendor/github.com/containers/podman/v3/pkg/domain/entities/manifest.go deleted file mode 100644 index 3f89e4d..0000000 --- a/examples/vendor/github.com/containers/podman/v3/pkg/domain/entities/manifest.go +++ /dev/null @@ -1,36 +0,0 @@ -package entities - -import "github.com/containers/image/v5/types" - -// TODO: add comments to *all* types and fields. - -type ManifestCreateOptions struct { - All bool `schema:"all"` -} - -// swagger:model ManifestAddOpts -type ManifestAddOptions struct { - All bool `json:"all" schema:"all"` - Annotation []string `json:"annotation" schema:"annotation"` - Arch string `json:"arch" schema:"arch"` - Authfile string `json:"-" schema:"-"` - CertDir string `json:"-" schema:"-"` - Features []string `json:"features" schema:"features"` - Images []string `json:"images" schema:"images"` - OS string `json:"os" schema:"os"` - OSVersion string `json:"os_version" schema:"os_version"` - Password string `json:"-" schema:"-"` - SkipTLSVerify types.OptionalBool `json:"-" schema:"-"` - Username string `json:"-" schema:"-"` - Variant string `json:"variant" schema:"variant"` -} - -type ManifestAnnotateOptions struct { - Annotation []string `json:"annotation"` - Arch string `json:"arch" schema:"arch"` - Features []string `json:"features" schema:"features"` - OS string `json:"os" schema:"os"` - OSFeatures []string `json:"os_features" schema:"os_features"` - OSVersion string `json:"os_version" schema:"os_version"` - Variant string `json:"variant" schema:"variant"` -} diff --git a/examples/vendor/github.com/containers/storage/VERSION b/examples/vendor/github.com/containers/storage/VERSION deleted file mode 100644 index bbb542a..0000000 --- a/examples/vendor/github.com/containers/storage/VERSION +++ /dev/null @@ -1 +0,0 @@ -1.37.2 diff --git a/examples/vendor/github.com/containers/storage/Vagrantfile b/examples/vendor/github.com/containers/storage/Vagrantfile deleted file mode 100644 index c82c1f8..0000000 --- a/examples/vendor/github.com/containers/storage/Vagrantfile +++ /dev/null @@ -1,25 +0,0 @@ -# -*- mode: ruby -*- -# vi: set ft=ruby : -# -# The fedora/28-cloud-base and debian/jessie64 boxes are also available for -# the "virtualbox" provider. Set the VAGRANT_PROVIDER environment variable to -# "virtualbox" to use them instead. -# -Vagrant.configure("2") do |config| - config.vm.define "fedora" do |c| - c.vm.box = "fedora/28-cloud-base" - c.vm.synced_folder ".", "/vagrant", type: "rsync", - rsync__exclude: "bundles", rsync__args: ["-vadz", "--delete"] - c.vm.provision "shell", inline: <<-SHELL - sudo /vagrant/vagrant/provision.sh - SHELL - end - config.vm.define "debian" do |c| - c.vm.box = "debian/jessie64" - c.vm.synced_folder ".", "/vagrant", type: "rsync", - rsync__exclude: "bundles", rsync__args: ["-vadz", "--delete"] - c.vm.provision "shell", inline: <<-SHELL - sudo /vagrant/vagrant/provision.sh - SHELL - end -end diff --git a/examples/vendor/github.com/containers/storage/drivers/chown_windows.go b/examples/vendor/github.com/containers/storage/drivers/chown_windows.go deleted file mode 100644 index 31bd5bb..0000000 --- a/examples/vendor/github.com/containers/storage/drivers/chown_windows.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build windows - -package graphdriver - -import ( - "os" - "syscall" - - "github.com/containers/storage/pkg/idtools" -) - -func platformLChown(path string, info os.FileInfo, toHost, toContainer *idtools.IDMappings) error { - return &os.PathError{"lchown", path, syscall.EWINDOWS} -} diff --git a/examples/vendor/github.com/containers/storage/drivers/driver_freebsd.go b/examples/vendor/github.com/containers/storage/drivers/driver_freebsd.go deleted file mode 100644 index e1320ee..0000000 --- a/examples/vendor/github.com/containers/storage/drivers/driver_freebsd.go +++ /dev/null @@ -1,21 +0,0 @@ -package graphdriver - -import ( - "golang.org/x/sys/unix" -) - -var ( - // Slice of drivers that should be used in an order - priority = []string{ - "zfs", - } -) - -// Mounted checks if the given path is mounted as the fs type -func Mounted(fsType FsMagic, mountPath string) (bool, error) { - var buf unix.Statfs_t - if err := unix.Statfs(mountPath, &buf); err != nil { - return false, err - } - return FsMagic(buf.Type) == fsType, nil -} diff --git a/examples/vendor/github.com/containers/storage/drivers/overlay/check_115.go b/examples/vendor/github.com/containers/storage/drivers/overlay/check_115.go deleted file mode 100644 index 9ad1b86..0000000 --- a/examples/vendor/github.com/containers/storage/drivers/overlay/check_115.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build !go1.16 - -package overlay - -import ( - "os" - "path/filepath" - "strings" - - "github.com/containers/storage/pkg/archive" - "github.com/containers/storage/pkg/system" -) - -func scanForMountProgramIndicators(home string) (detected bool, err error) { - err = filepath.Walk(home, func(path string, info os.FileInfo, err error) error { - if detected { - return filepath.SkipDir - } - if err != nil { - return err - } - basename := filepath.Base(path) - if strings.HasPrefix(basename, archive.WhiteoutPrefix) { - detected = true - return filepath.SkipDir - } - if info.IsDir() { - xattrs, err := system.Llistxattr(path) - if err != nil { - return err - } - for _, xattr := range xattrs { - if strings.HasPrefix(xattr, "user.fuseoverlayfs.") || strings.HasPrefix(xattr, "user.containers.") { - detected = true - return filepath.SkipDir - } - } - } - return nil - }) - return detected, err -} diff --git a/examples/vendor/github.com/containers/storage/pkg/chunked/compressor/compressor.go b/examples/vendor/github.com/containers/storage/pkg/chunked/compressor/compressor.go deleted file mode 100644 index 092cf58..0000000 --- a/examples/vendor/github.com/containers/storage/pkg/chunked/compressor/compressor.go +++ /dev/null @@ -1,220 +0,0 @@ -package compressor - -// NOTE: This is used from github.com/containers/image by callers that -// don't otherwise use containers/storage, so don't make this depend on any -// larger software like the graph drivers. - -import ( - "encoding/base64" - "io" - "io/ioutil" - - "github.com/containers/storage/pkg/chunked/internal" - "github.com/containers/storage/pkg/ioutils" - "github.com/opencontainers/go-digest" - "github.com/vbatts/tar-split/archive/tar" -) - -func writeZstdChunkedStream(destFile io.Writer, outMetadata map[string]string, reader io.Reader, level int) error { - // total written so far. Used to retrieve partial offsets in the file - dest := ioutils.NewWriteCounter(destFile) - - tr := tar.NewReader(reader) - tr.RawAccounting = true - - buf := make([]byte, 4096) - - zstdWriter, err := internal.ZstdWriterWithLevel(dest, level) - if err != nil { - return err - } - defer func() { - if zstdWriter != nil { - zstdWriter.Close() - zstdWriter.Flush() - } - }() - - restartCompression := func() (int64, error) { - var offset int64 - if zstdWriter != nil { - if err := zstdWriter.Close(); err != nil { - return 0, err - } - if err := zstdWriter.Flush(); err != nil { - return 0, err - } - offset = dest.Count - zstdWriter.Reset(dest) - } - return offset, nil - } - - var metadata []internal.FileMetadata - for { - hdr, err := tr.Next() - if err != nil { - if err == io.EOF { - break - } - return err - } - - rawBytes := tr.RawBytes() - if _, err := zstdWriter.Write(rawBytes); err != nil { - return err - } - payloadDigester := digest.Canonical.Digester() - payloadChecksum := payloadDigester.Hash() - - payloadDest := io.MultiWriter(payloadChecksum, zstdWriter) - - // Now handle the payload, if any - var startOffset, endOffset int64 - checksum := "" - for { - read, errRead := tr.Read(buf) - if errRead != nil && errRead != io.EOF { - return err - } - - // restart the compression only if there is - // a payload. - if read > 0 { - if startOffset == 0 { - startOffset, err = restartCompression() - if err != nil { - return err - } - } - _, err := payloadDest.Write(buf[:read]) - if err != nil { - return err - } - } - if errRead == io.EOF { - if startOffset > 0 { - endOffset, err = restartCompression() - if err != nil { - return err - } - checksum = payloadDigester.Digest().String() - } - break - } - } - - typ, err := internal.GetType(hdr.Typeflag) - if err != nil { - return err - } - xattrs := make(map[string]string) - for k, v := range hdr.Xattrs { - xattrs[k] = base64.StdEncoding.EncodeToString([]byte(v)) - } - m := internal.FileMetadata{ - Type: typ, - Name: hdr.Name, - Linkname: hdr.Linkname, - Mode: hdr.Mode, - Size: hdr.Size, - UID: hdr.Uid, - GID: hdr.Gid, - ModTime: hdr.ModTime, - AccessTime: hdr.AccessTime, - ChangeTime: hdr.ChangeTime, - Devmajor: hdr.Devmajor, - Devminor: hdr.Devminor, - Xattrs: xattrs, - Digest: checksum, - Offset: startOffset, - EndOffset: endOffset, - - // ChunkSize is 0 for the last chunk - ChunkSize: 0, - ChunkOffset: 0, - ChunkDigest: checksum, - } - metadata = append(metadata, m) - } - - rawBytes := tr.RawBytes() - if _, err := zstdWriter.Write(rawBytes); err != nil { - return err - } - if err := zstdWriter.Flush(); err != nil { - return err - } - if err := zstdWriter.Close(); err != nil { - return err - } - zstdWriter = nil - - return internal.WriteZstdChunkedManifest(dest, outMetadata, uint64(dest.Count), metadata, level) -} - -type zstdChunkedWriter struct { - tarSplitOut *io.PipeWriter - tarSplitErr chan error -} - -func (w zstdChunkedWriter) Close() error { - err := <-w.tarSplitErr - if err != nil { - w.tarSplitOut.Close() - return err - } - return w.tarSplitOut.Close() -} - -func (w zstdChunkedWriter) Write(p []byte) (int, error) { - select { - case err := <-w.tarSplitErr: - w.tarSplitOut.Close() - return 0, err - default: - return w.tarSplitOut.Write(p) - } -} - -// zstdChunkedWriterWithLevel writes a zstd compressed tarball where each file is -// compressed separately so it can be addressed separately. Idea based on CRFS: -// https://github.com/google/crfs -// The difference with CRFS is that the zstd compression is used instead of gzip. -// The reason for it is that zstd supports embedding metadata ignored by the decoder -// as part of the compressed stream. -// A manifest json file with all the metadata is appended at the end of the tarball -// stream, using zstd skippable frames. -// The final file will look like: -// [FILE_1][FILE_2]..[FILE_N][SKIPPABLE FRAME 1][SKIPPABLE FRAME 2] -// Where: -// [FILE_N]: [ZSTD HEADER][TAR HEADER][PAYLOAD FILE_N][ZSTD FOOTER] -// [SKIPPABLE FRAME 1]: [ZSTD SKIPPABLE FRAME, SIZE=MANIFEST LENGTH][MANIFEST] -// [SKIPPABLE FRAME 2]: [ZSTD SKIPPABLE FRAME, SIZE=16][MANIFEST_OFFSET][MANIFEST_LENGTH][MANIFEST_LENGTH_UNCOMPRESSED][MANIFEST_TYPE][CHUNKED_ZSTD_MAGIC_NUMBER] -// MANIFEST_OFFSET, MANIFEST_LENGTH, MANIFEST_LENGTH_UNCOMPRESSED and CHUNKED_ZSTD_MAGIC_NUMBER are 64 bits unsigned in little endian format. -func zstdChunkedWriterWithLevel(out io.Writer, metadata map[string]string, level int) (io.WriteCloser, error) { - ch := make(chan error, 1) - r, w := io.Pipe() - - go func() { - ch <- writeZstdChunkedStream(out, metadata, r, level) - io.Copy(ioutil.Discard, r) - r.Close() - close(ch) - }() - - return zstdChunkedWriter{ - tarSplitOut: w, - tarSplitErr: ch, - }, nil -} - -// ZstdCompressor is a CompressorFunc for the zstd compression algorithm. -func ZstdCompressor(r io.Writer, metadata map[string]string, level *int) (io.WriteCloser, error) { - if level == nil { - l := 3 - level = &l - } - - return zstdChunkedWriterWithLevel(r, metadata, *level) -} diff --git a/examples/vendor/github.com/containers/storage/pkg/chunked/storage_linux.go b/examples/vendor/github.com/containers/storage/pkg/chunked/storage_linux.go deleted file mode 100644 index 6efc6a4..0000000 --- a/examples/vendor/github.com/containers/storage/pkg/chunked/storage_linux.go +++ /dev/null @@ -1,1181 +0,0 @@ -package chunked - -import ( - archivetar "archive/tar" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "reflect" - "sort" - "strings" - "syscall" - "time" - - "github.com/containerd/stargz-snapshotter/estargz" - storage "github.com/containers/storage" - graphdriver "github.com/containers/storage/drivers" - driversCopy "github.com/containers/storage/drivers/copy" - "github.com/containers/storage/pkg/archive" - "github.com/containers/storage/pkg/chunked/internal" - "github.com/containers/storage/pkg/idtools" - "github.com/containers/storage/pkg/system" - "github.com/containers/storage/types" - "github.com/klauspost/compress/zstd" - "github.com/klauspost/pgzip" - digest "github.com/opencontainers/go-digest" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "github.com/vbatts/tar-split/archive/tar" - "golang.org/x/sys/unix" -) - -const ( - maxNumberMissingChunks = 1024 - newFileFlags = (unix.O_CREAT | unix.O_TRUNC | unix.O_EXCL | unix.O_WRONLY) - containersOverrideXattr = "user.containers.override_stat" - bigDataKey = "zstd-chunked-manifest" - - fileTypeZstdChunked = iota - fileTypeEstargz = iota -) - -type compressedFileType int - -type chunkedDiffer struct { - stream ImageSourceSeekable - manifest []byte - layersMetadata map[string][]internal.FileMetadata - layersTarget map[string]string - tocOffset int64 - fileType compressedFileType - - gzipReader *pgzip.Reader -} - -func timeToTimespec(time time.Time) (ts unix.Timespec) { - if time.IsZero() { - // Return UTIME_OMIT special value - ts.Sec = 0 - ts.Nsec = ((1 << 30) - 2) - return - } - return unix.NsecToTimespec(time.UnixNano()) -} - -func copyFileContent(srcFd int, destFile string, dirfd int, mode os.FileMode, useHardLinks bool) (*os.File, int64, error) { - src := fmt.Sprintf("/proc/self/fd/%d", srcFd) - st, err := os.Stat(src) - if err != nil { - return nil, -1, err - } - - copyWithFileRange, copyWithFileClone := true, true - - if useHardLinks { - destDirPath := filepath.Dir(destFile) - destBase := filepath.Base(destFile) - destDir, err := openFileUnderRoot(destDirPath, dirfd, 0, mode) - if err == nil { - defer destDir.Close() - - doLink := func() error { - // Using unix.AT_EMPTY_PATH requires CAP_DAC_READ_SEARCH while this variant that uses - // /proc/self/fd doesn't and can be used with rootless. - srcPath := fmt.Sprintf("/proc/self/fd/%d", srcFd) - return unix.Linkat(unix.AT_FDCWD, srcPath, int(destDir.Fd()), destBase, unix.AT_SYMLINK_FOLLOW) - } - - err := doLink() - - // if the destination exists, unlink it first and try again - if err != nil && os.IsExist(err) { - unix.Unlinkat(int(destDir.Fd()), destBase, 0) - err = doLink() - } - if err == nil { - return nil, st.Size(), nil - } - } - } - - // If the destination file already exists, we shouldn't blow it away - dstFile, err := openFileUnderRoot(destFile, dirfd, newFileFlags, mode) - if err != nil { - return nil, -1, err - } - - err = driversCopy.CopyRegularToFile(src, dstFile, st, ©WithFileRange, ©WithFileClone) - if err != nil { - dstFile.Close() - return nil, -1, err - } - return dstFile, st.Size(), err -} - -func prepareOtherLayersCache(layersMetadata map[string][]internal.FileMetadata) map[string]map[string][]*internal.FileMetadata { - maps := make(map[string]map[string][]*internal.FileMetadata) - - for layerID, v := range layersMetadata { - r := make(map[string][]*internal.FileMetadata) - for i := range v { - if v[i].Digest != "" { - r[v[i].Digest] = append(r[v[i].Digest], &v[i]) - } - } - maps[layerID] = r - } - return maps -} - -func getLayersCache(store storage.Store) (map[string][]internal.FileMetadata, map[string]string, error) { - allLayers, err := store.Layers() - if err != nil { - return nil, nil, err - } - - layersMetadata := make(map[string][]internal.FileMetadata) - layersTarget := make(map[string]string) - for _, r := range allLayers { - manifestReader, err := store.LayerBigData(r.ID, bigDataKey) - if err != nil { - continue - } - defer manifestReader.Close() - manifest, err := ioutil.ReadAll(manifestReader) - if err != nil { - return nil, nil, err - } - var toc internal.TOC - if err := json.Unmarshal(manifest, &toc); err != nil { - continue - } - layersMetadata[r.ID] = toc.Entries - target, err := store.DifferTarget(r.ID) - if err != nil { - return nil, nil, err - } - layersTarget[r.ID] = target - } - - return layersMetadata, layersTarget, nil -} - -// GetDiffer returns a differ than can be used with ApplyDiffWithDiffer. -func GetDiffer(ctx context.Context, store storage.Store, blobSize int64, annotations map[string]string, iss ImageSourceSeekable) (graphdriver.Differ, error) { - if _, ok := annotations[internal.ManifestChecksumKey]; ok { - return makeZstdChunkedDiffer(ctx, store, blobSize, annotations, iss) - } - if _, ok := annotations[estargz.TOCJSONDigestAnnotation]; ok { - return makeEstargzChunkedDiffer(ctx, store, blobSize, annotations, iss) - } - return nil, errors.New("blob type not supported for partial retrieval") -} - -func makeZstdChunkedDiffer(ctx context.Context, store storage.Store, blobSize int64, annotations map[string]string, iss ImageSourceSeekable) (*chunkedDiffer, error) { - manifest, tocOffset, err := readZstdChunkedManifest(iss, blobSize, annotations) - if err != nil { - return nil, err - } - layersMetadata, layersTarget, err := getLayersCache(store) - if err != nil { - return nil, err - } - - return &chunkedDiffer{ - stream: iss, - manifest: manifest, - layersMetadata: layersMetadata, - layersTarget: layersTarget, - tocOffset: tocOffset, - fileType: fileTypeZstdChunked, - }, nil -} - -func makeEstargzChunkedDiffer(ctx context.Context, store storage.Store, blobSize int64, annotations map[string]string, iss ImageSourceSeekable) (*chunkedDiffer, error) { - manifest, tocOffset, err := readEstargzChunkedManifest(iss, blobSize, annotations) - if err != nil { - return nil, err - } - layersMetadata, layersTarget, err := getLayersCache(store) - if err != nil { - return nil, err - } - - return &chunkedDiffer{ - stream: iss, - manifest: manifest, - layersMetadata: layersMetadata, - layersTarget: layersTarget, - tocOffset: tocOffset, - fileType: fileTypeEstargz, - }, nil -} - -// copyFileFromOtherLayer copies a file from another layer -// file is the file to look for. -// source is the path to the source layer checkout. -// otherFile contains the metadata for the file. -// dirfd is an open file descriptor to the destination root directory. -// useHardLinks defines whether the deduplication can be performed using hard links. -func copyFileFromOtherLayer(file *internal.FileMetadata, source string, otherFile *internal.FileMetadata, dirfd int, useHardLinks bool) (bool, *os.File, int64, error) { - srcDirfd, err := unix.Open(source, unix.O_RDONLY, 0) - if err != nil { - return false, nil, 0, err - } - defer unix.Close(srcDirfd) - - srcFile, err := openFileUnderRoot(otherFile.Name, srcDirfd, unix.O_RDONLY, 0) - if err != nil { - return false, nil, 0, err - } - defer srcFile.Close() - - dstFile, written, err := copyFileContent(int(srcFile.Fd()), file.Name, dirfd, 0, useHardLinks) - if err != nil { - return false, nil, 0, err - } - return true, dstFile, written, err -} - -// canDedupMetadataWithHardLink says whether it is possible to deduplicate file with otherFile. -// It checks that the two files have the same UID, GID, file mode and xattrs. -func canDedupMetadataWithHardLink(file *internal.FileMetadata, otherFile *internal.FileMetadata) bool { - if file.UID != otherFile.UID { - return false - } - if file.GID != otherFile.GID { - return false - } - if file.Mode != otherFile.Mode { - return false - } - if !reflect.DeepEqual(file.Xattrs, otherFile.Xattrs) { - return false - } - return true -} - -// canDedupFileWithHardLink checks if the specified file can be deduplicated by an -// open file, given its descriptor and stat data. -func canDedupFileWithHardLink(file *internal.FileMetadata, fd int, s os.FileInfo) bool { - st, ok := s.Sys().(*syscall.Stat_t) - if !ok { - return false - } - - path := fmt.Sprintf("/proc/self/fd/%d", fd) - - listXattrs, err := system.Llistxattr(path) - if err != nil { - return false - } - - xattrsToIgnore := map[string]interface{}{ - "security.selinux": true, - } - - xattrs := make(map[string]string) - for _, x := range listXattrs { - v, err := system.Lgetxattr(path, x) - if err != nil { - return false - } - - if _, found := xattrsToIgnore[x]; found { - continue - } - xattrs[x] = string(v) - } - // fill only the attributes used by canDedupMetadataWithHardLink. - otherFile := internal.FileMetadata{ - UID: int(st.Uid), - GID: int(st.Gid), - Mode: int64(st.Mode), - Xattrs: xattrs, - } - return canDedupMetadataWithHardLink(file, &otherFile) -} - -// findFileInOtherLayers finds the specified file in other layers. -// file is the file to look for. -// dirfd is an open file descriptor to the checkout root directory. -// layersMetadata contains the metadata for each layer in the storage. -// layersTarget maps each layer to its checkout on disk. -// useHardLinks defines whether the deduplication can be performed using hard links. -func findFileInOtherLayers(file *internal.FileMetadata, dirfd int, layersMetadata map[string]map[string][]*internal.FileMetadata, layersTarget map[string]string, useHardLinks bool) (bool, *os.File, int64, error) { - // this is ugly, needs to be indexed - for layerID, checksums := range layersMetadata { - source, ok := layersTarget[layerID] - if !ok { - continue - } - files, found := checksums[file.Digest] - if !found { - continue - } - for _, candidate := range files { - // check if it is a valid candidate to dedup file - if useHardLinks && !canDedupMetadataWithHardLink(file, candidate) { - continue - } - - found, dstFile, written, err := copyFileFromOtherLayer(file, source, candidate, dirfd, useHardLinks) - if found && err == nil { - return found, dstFile, written, err - } - } - } - // If hard links deduplication was used and it has failed, try again without hard links. - if useHardLinks { - return findFileInOtherLayers(file, dirfd, layersMetadata, layersTarget, false) - } - return false, nil, 0, nil -} - -func getFileDigest(f *os.File) (digest.Digest, error) { - digester := digest.Canonical.Digester() - if _, err := io.Copy(digester.Hash(), f); err != nil { - return "", err - } - return digester.Digest(), nil -} - -// findFileInOSTreeRepos checks whether the requested file already exist in one of the OSTree repo and copies the file content from there if possible. -// file is the file to look for. -// ostreeRepos is a list of OSTree repos. -// dirfd is an open fd to the destination checkout. -// useHardLinks defines whether the deduplication can be performed using hard links. -func findFileInOSTreeRepos(file *internal.FileMetadata, ostreeRepos []string, dirfd int, useHardLinks bool) (bool, *os.File, int64, error) { - digest, err := digest.Parse(file.Digest) - if err != nil { - return false, nil, 0, nil - } - payloadLink := digest.Encoded() + ".payload-link" - if len(payloadLink) < 2 { - return false, nil, 0, nil - } - - for _, repo := range ostreeRepos { - sourceFile := filepath.Join(repo, "objects", payloadLink[:2], payloadLink[2:]) - st, err := os.Stat(sourceFile) - if err != nil || !st.Mode().IsRegular() { - continue - } - if st.Size() != file.Size { - continue - } - fd, err := unix.Open(sourceFile, unix.O_RDONLY|unix.O_NONBLOCK, 0) - if err != nil { - return false, nil, 0, nil - } - f := os.NewFile(uintptr(fd), "fd") - defer f.Close() - - // check if the open file can be deduplicated with hard links - if useHardLinks && !canDedupFileWithHardLink(file, fd, st) { - continue - } - - dstFile, written, err := copyFileContent(fd, file.Name, dirfd, 0, useHardLinks) - if err != nil { - return false, nil, 0, nil - } - return true, dstFile, written, nil - } - // If hard links deduplication was used and it has failed, try again without hard links. - if useHardLinks { - return findFileInOSTreeRepos(file, ostreeRepos, dirfd, false) - } - - return false, nil, 0, nil -} - -// findFileOnTheHost checks whether the requested file already exist on the host and copies the file content from there if possible. -// It is currently implemented to look only at the file with the same path. Ideally it can detect the same content also at different -// paths. -// file is the file to look for. -// dirfd is an open fd to the destination checkout. -// useHardLinks defines whether the deduplication can be performed using hard links. -func findFileOnTheHost(file *internal.FileMetadata, dirfd int, useHardLinks bool) (bool, *os.File, int64, error) { - sourceFile := filepath.Clean(filepath.Join("/", file.Name)) - if !strings.HasPrefix(sourceFile, "/usr/") { - // limit host deduplication to files under /usr. - return false, nil, 0, nil - } - - st, err := os.Stat(sourceFile) - if err != nil || !st.Mode().IsRegular() { - return false, nil, 0, nil - } - - if st.Size() != file.Size { - return false, nil, 0, nil - } - - fd, err := unix.Open(sourceFile, unix.O_RDONLY|unix.O_NONBLOCK, 0) - if err != nil { - return false, nil, 0, nil - } - - f := os.NewFile(uintptr(fd), "fd") - defer f.Close() - - manifestChecksum, err := digest.Parse(file.Digest) - if err != nil { - return false, nil, 0, err - } - - checksum, err := getFileDigest(f) - if err != nil { - return false, nil, 0, err - } - - if checksum != manifestChecksum { - return false, nil, 0, nil - } - - // check if the open file can be deduplicated with hard links - useHardLinks = useHardLinks && canDedupFileWithHardLink(file, fd, st) - - dstFile, written, err := copyFileContent(fd, file.Name, dirfd, 0, useHardLinks) - if err != nil { - return false, nil, 0, nil - } - - // calculate the checksum again to make sure the file wasn't modified while it was copied - if _, err := f.Seek(0, 0); err != nil { - dstFile.Close() - return false, nil, 0, err - } - checksum, err = getFileDigest(f) - if err != nil { - dstFile.Close() - return false, nil, 0, err - } - if checksum != manifestChecksum { - dstFile.Close() - return false, nil, 0, nil - } - return true, dstFile, written, nil -} - -func maybeDoIDRemap(manifest []internal.FileMetadata, options *archive.TarOptions) error { - if options.ChownOpts == nil && len(options.UIDMaps) == 0 || len(options.GIDMaps) == 0 { - return nil - } - - idMappings := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) - - for i := range manifest { - if options.ChownOpts != nil { - manifest[i].UID = options.ChownOpts.UID - manifest[i].GID = options.ChownOpts.GID - } else { - pair := idtools.IDPair{ - UID: manifest[i].UID, - GID: manifest[i].GID, - } - var err error - manifest[i].UID, manifest[i].GID, err = idMappings.ToContainer(pair) - if err != nil { - return err - } - } - } - return nil -} - -type missingFile struct { - File *internal.FileMetadata - Gap int64 -} - -func (m missingFile) Length() int64 { - return m.File.EndOffset - m.File.Offset -} - -type missingChunk struct { - RawChunk ImageSourceChunk - Files []missingFile -} - -// setFileAttrs sets the file attributes for file given metadata -func setFileAttrs(file *os.File, mode os.FileMode, metadata *internal.FileMetadata, options *archive.TarOptions) error { - if file == nil || file.Fd() < 0 { - return errors.Errorf("invalid file") - } - fd := int(file.Fd()) - - t, err := typeToTarType(metadata.Type) - if err != nil { - return err - } - if t == tar.TypeSymlink { - return nil - } - - if err := unix.Fchown(fd, metadata.UID, metadata.GID); err != nil { - if !options.IgnoreChownErrors { - return err - } - } - - for k, v := range metadata.Xattrs { - data, err := base64.StdEncoding.DecodeString(v) - if err != nil { - return err - } - if err := unix.Fsetxattr(fd, k, data, 0); err != nil { - return err - } - } - - ts := []unix.Timespec{timeToTimespec(metadata.AccessTime), timeToTimespec(metadata.ModTime)} - if err := unix.UtimesNanoAt(fd, "", ts, 0); err != nil && errors.Is(err, unix.ENOSYS) { - return err - } - - if err := unix.Fchmod(fd, uint32(mode)); err != nil { - return err - } - return nil -} - -// openFileUnderRoot safely opens a file under the specified root directory using openat2 -// name is the path to open relative to dirfd. -// dirfd is an open file descriptor to the target checkout directory. -// flags are the flags top pass to the open syscall. -// mode specifies the mode to use for newly created files. -func openFileUnderRoot(name string, dirfd int, flags uint64, mode os.FileMode) (*os.File, error) { - how := unix.OpenHow{ - Flags: flags, - Mode: uint64(mode & 07777), - Resolve: unix.RESOLVE_IN_ROOT, - } - - fd, err := unix.Openat2(dirfd, name, &how) - if err != nil { - return nil, err - } - return os.NewFile(uintptr(fd), name), nil -} - -func (c *chunkedDiffer) createFileFromCompressedStream(dest string, dirfd int, reader io.Reader, mode os.FileMode, metadata *internal.FileMetadata, options *archive.TarOptions) (err error) { - file, err := openFileUnderRoot(metadata.Name, dirfd, newFileFlags, 0) - if err != nil { - return err - } - defer func() { - err2 := file.Close() - if err == nil { - err = err2 - } - }() - - digester := digest.Canonical.Digester() - checksum := digester.Hash() - to := io.MultiWriter(file, checksum) - - switch c.fileType { - case fileTypeZstdChunked: - z, err := zstd.NewReader(reader) - if err != nil { - return err - } - defer z.Close() - - if _, err := io.Copy(to, io.LimitReader(z, metadata.Size)); err != nil { - return err - } - if _, err := io.Copy(ioutil.Discard, reader); err != nil { - return err - } - case fileTypeEstargz: - if c.gzipReader == nil { - r, err := pgzip.NewReader(reader) - if err != nil { - return err - } - c.gzipReader = r - } else { - if err := c.gzipReader.Reset(reader); err != nil { - return err - } - } - defer c.gzipReader.Close() - - if _, err := io.Copy(to, io.LimitReader(c.gzipReader, metadata.Size)); err != nil { - return err - } - if _, err := io.Copy(ioutil.Discard, reader); err != nil { - return err - } - default: - return fmt.Errorf("unknown file type %q", c.fileType) - } - - manifestChecksum, err := digest.Parse(metadata.Digest) - if err != nil { - return err - } - if digester.Digest() != manifestChecksum { - return fmt.Errorf("checksum mismatch for %q", dest) - } - return setFileAttrs(file, mode, metadata, options) -} - -func (c *chunkedDiffer) storeMissingFiles(streams chan io.ReadCloser, errs chan error, dest string, dirfd int, missingChunks []missingChunk, options *archive.TarOptions) error { - for mc := 0; ; mc++ { - var part io.ReadCloser - select { - case p := <-streams: - part = p - case err := <-errs: - return err - } - if part == nil { - if mc == len(missingChunks) { - break - } - return errors.Errorf("invalid stream returned") - } - if mc == len(missingChunks) { - part.Close() - return errors.Errorf("too many chunks returned") - } - - for _, mf := range missingChunks[mc].Files { - if mf.Gap > 0 { - limitReader := io.LimitReader(part, mf.Gap) - _, err := io.Copy(ioutil.Discard, limitReader) - if err != nil { - part.Close() - return err - } - continue - } - - limitReader := io.LimitReader(part, mf.Length()) - - if err := c.createFileFromCompressedStream(dest, dirfd, limitReader, os.FileMode(mf.File.Mode), mf.File, options); err != nil { - part.Close() - return err - } - } - part.Close() - } - return nil -} - -func mergeMissingChunks(missingChunks []missingChunk, target int) []missingChunk { - if len(missingChunks) <= target { - return missingChunks - } - - getGap := func(missingChunks []missingChunk, i int) int { - prev := missingChunks[i-1].RawChunk.Offset + missingChunks[i-1].RawChunk.Length - return int(missingChunks[i].RawChunk.Offset - prev) - } - - // this implementation doesn't account for duplicates, so it could merge - // more than necessary to reach the specified target. Since target itself - // is a heuristic value, it doesn't matter. - var gaps []int - for i := 1; i < len(missingChunks); i++ { - gaps = append(gaps, getGap(missingChunks, i)) - } - sort.Ints(gaps) - - toShrink := len(missingChunks) - target - targetValue := gaps[toShrink-1] - - newMissingChunks := missingChunks[0:1] - for i := 1; i < len(missingChunks); i++ { - gap := getGap(missingChunks, i) - if gap > targetValue { - newMissingChunks = append(newMissingChunks, missingChunks[i]) - } else { - prev := &newMissingChunks[len(newMissingChunks)-1] - prev.RawChunk.Length += uint64(gap) + missingChunks[i].RawChunk.Length - if gap > 0 { - gapFile := missingFile{ - Gap: int64(gap), - } - prev.Files = append(prev.Files, gapFile) - } - prev.Files = append(prev.Files, missingChunks[i].Files...) - } - } - return newMissingChunks -} - -func (c *chunkedDiffer) retrieveMissingFiles(dest string, dirfd int, missingChunks []missingChunk, options *archive.TarOptions) error { - var chunksToRequest []ImageSourceChunk - for _, c := range missingChunks { - chunksToRequest = append(chunksToRequest, c.RawChunk) - } - - // There are some missing files. Prepare a multirange request for the missing chunks. - var streams chan io.ReadCloser - var err error - var errs chan error - for { - streams, errs, err = c.stream.GetBlobAt(chunksToRequest) - if err == nil { - break - } - - if _, ok := err.(ErrBadRequest); ok { - requested := len(missingChunks) - // If the server cannot handle at least 64 chunks in a single request, just give up. - if requested < 64 { - return err - } - - // Merge more chunks to request - missingChunks = mergeMissingChunks(missingChunks, requested/2) - continue - } - return err - } - - if err := c.storeMissingFiles(streams, errs, dest, dirfd, missingChunks, options); err != nil { - return err - } - return nil -} - -func safeMkdir(dirfd int, mode os.FileMode, metadata *internal.FileMetadata, options *archive.TarOptions) error { - parent := filepath.Dir(metadata.Name) - base := filepath.Base(metadata.Name) - - parentFd := dirfd - if parent != "." { - parentFile, err := openFileUnderRoot(parent, dirfd, unix.O_DIRECTORY|unix.O_PATH|unix.O_RDONLY, 0) - if err != nil { - return err - } - defer parentFile.Close() - parentFd = int(parentFile.Fd()) - } - - if err := unix.Mkdirat(parentFd, base, uint32(mode)); err != nil { - if !os.IsExist(err) { - return err - } - } - - file, err := openFileUnderRoot(metadata.Name, dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer file.Close() - - return setFileAttrs(file, mode, metadata, options) -} - -func safeLink(dirfd int, mode os.FileMode, metadata *internal.FileMetadata, options *archive.TarOptions) error { - sourceFile, err := openFileUnderRoot(metadata.Linkname, dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer sourceFile.Close() - - destDir, destBase := filepath.Dir(metadata.Name), filepath.Base(metadata.Name) - destDirFd := dirfd - if destDir != "." { - f, err := openFileUnderRoot(destDir, dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer f.Close() - destDirFd = int(f.Fd()) - } - - err = unix.Linkat(int(sourceFile.Fd()), "", destDirFd, destBase, unix.AT_EMPTY_PATH) - if err != nil { - return err - } - - newFile, err := openFileUnderRoot(metadata.Name, dirfd, unix.O_WRONLY, 0) - if err != nil { - return err - } - defer newFile.Close() - - return setFileAttrs(newFile, mode, metadata, options) -} - -func safeSymlink(dirfd int, mode os.FileMode, metadata *internal.FileMetadata, options *archive.TarOptions) error { - destDir, destBase := filepath.Dir(metadata.Name), filepath.Base(metadata.Name) - destDirFd := dirfd - if destDir != "." { - f, err := openFileUnderRoot(destDir, dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer f.Close() - destDirFd = int(f.Fd()) - } - - return unix.Symlinkat(metadata.Linkname, destDirFd, destBase) -} - -type whiteoutHandler struct { - Dirfd int - Root string -} - -func (d whiteoutHandler) Setxattr(path, name string, value []byte) error { - file, err := openFileUnderRoot(path, d.Dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer file.Close() - - return unix.Fsetxattr(int(file.Fd()), name, value, 0) -} - -func (d whiteoutHandler) Mknod(path string, mode uint32, dev int) error { - dir := filepath.Dir(path) - base := filepath.Base(path) - - dirfd := d.Dirfd - if dir != "" { - dir, err := openFileUnderRoot(dir, d.Dirfd, unix.O_RDONLY, 0) - if err != nil { - return err - } - defer dir.Close() - - dirfd = int(dir.Fd()) - } - - return unix.Mknodat(dirfd, base, mode, dev) -} - -func checkChownErr(err error, name string, uid, gid int) error { - if errors.Is(err, syscall.EINVAL) { - return errors.Wrapf(err, "potentially insufficient UIDs or GIDs available in user namespace (requested %d:%d for %s): Check /etc/subuid and /etc/subgid", uid, gid, name) - } - return err -} - -func (d whiteoutHandler) Chown(path string, uid, gid int) error { - file, err := openFileUnderRoot(path, d.Dirfd, unix.O_PATH, 0) - if err != nil { - return err - } - defer file.Close() - - if err := unix.Fchownat(int(file.Fd()), "", uid, gid, unix.AT_EMPTY_PATH); err != nil { - var stat unix.Stat_t - if unix.Fstat(int(file.Fd()), &stat) == nil { - if stat.Uid == uint32(uid) && stat.Gid == uint32(gid) { - return nil - } - } - return checkChownErr(err, path, uid, gid) - } - return nil -} - -type hardLinkToCreate struct { - dest string - dirfd int - mode os.FileMode - metadata *internal.FileMetadata -} - -func parseBooleanPullOption(storeOpts *storage.StoreOptions, name string, def bool) bool { - if value, ok := storeOpts.PullOptions[name]; ok { - return strings.ToLower(value) == "true" - } - return def -} - -func (c *chunkedDiffer) ApplyDiff(dest string, options *archive.TarOptions) (graphdriver.DriverWithDifferOutput, error) { - bigData := map[string][]byte{ - bigDataKey: c.manifest, - } - output := graphdriver.DriverWithDifferOutput{ - Differ: c, - BigData: bigData, - } - - storeOpts, err := types.DefaultStoreOptionsAutoDetectUID() - if err != nil { - return output, err - } - - if !parseBooleanPullOption(&storeOpts, "enable_partial_images", false) { - return output, errors.New("enable_partial_images not configured") - } - - enableHostDedup := parseBooleanPullOption(&storeOpts, "enable_host_deduplication", false) - - // When the hard links deduplication is used, file attributes are ignored because setting them - // modifies the source file as well. - useHardLinks := parseBooleanPullOption(&storeOpts, "use_hard_links", false) - - // List of OSTree repositories to use for deduplication - ostreeRepos := strings.Split(storeOpts.PullOptions["ostree_repos"], ":") - - // Generate the manifest - var toc internal.TOC - if err := json.Unmarshal(c.manifest, &toc); err != nil { - return output, err - } - - whiteoutConverter := archive.GetWhiteoutConverter(options.WhiteoutFormat, options.WhiteoutData) - - var missingChunks []missingChunk - - mergedEntries, err := c.mergeTocEntries(c.fileType, toc.Entries) - if err != nil { - return output, err - } - if err := maybeDoIDRemap(mergedEntries, options); err != nil { - return output, err - } - - if options.ForceMask != nil { - uid, gid, mode, err := archive.GetFileOwner(dest) - if err == nil { - value := fmt.Sprintf("%d:%d:0%o", uid, gid, mode) - if err := unix.Setxattr(dest, containersOverrideXattr, []byte(value), 0); err != nil { - return output, err - } - } - } - - dirfd, err := unix.Open(dest, unix.O_RDONLY|unix.O_PATH, 0) - if err != nil { - return output, err - } - defer unix.Close(dirfd) - - otherLayersCache := prepareOtherLayersCache(c.layersMetadata) - - // hardlinks can point to missing files. So create them after all files - // are retrieved - var hardLinks []hardLinkToCreate - - missingChunksSize, totalChunksSize := int64(0), int64(0) - for i, r := range mergedEntries { - if options.ForceMask != nil { - value := fmt.Sprintf("%d:%d:0%o", r.UID, r.GID, r.Mode&07777) - r.Xattrs[containersOverrideXattr] = base64.StdEncoding.EncodeToString([]byte(value)) - r.Mode = int64(*options.ForceMask) - } - - mode := os.FileMode(r.Mode) - - r.Name = filepath.Clean(r.Name) - r.Linkname = filepath.Clean(r.Linkname) - - t, err := typeToTarType(r.Type) - if err != nil { - return output, err - } - if whiteoutConverter != nil { - hdr := archivetar.Header{ - Typeflag: t, - Name: r.Name, - Linkname: r.Linkname, - Size: r.Size, - Mode: r.Mode, - Uid: r.UID, - Gid: r.GID, - } - handler := whiteoutHandler{ - Dirfd: dirfd, - Root: dest, - } - writeFile, err := whiteoutConverter.ConvertReadWithHandler(&hdr, r.Name, &handler) - if err != nil { - return output, err - } - if !writeFile { - continue - } - } - switch t { - case tar.TypeReg: - // Create directly empty files. - if r.Size == 0 { - // Used to have a scope for cleanup. - createEmptyFile := func() error { - file, err := openFileUnderRoot(r.Name, dirfd, newFileFlags, 0) - if err != nil { - return err - } - defer file.Close() - if err := setFileAttrs(file, mode, &r, options); err != nil { - return err - } - return nil - } - if err := createEmptyFile(); err != nil { - return output, err - } - continue - } - - case tar.TypeDir: - if err := safeMkdir(dirfd, mode, &r, options); err != nil { - return output, err - } - continue - - case tar.TypeLink: - dest := dest - dirfd := dirfd - mode := mode - r := r - hardLinks = append(hardLinks, hardLinkToCreate{ - dest: dest, - dirfd: dirfd, - mode: mode, - metadata: &r, - }) - continue - - case tar.TypeSymlink: - if err := safeSymlink(dirfd, mode, &r, options); err != nil { - return output, err - } - continue - - case tar.TypeChar: - case tar.TypeBlock: - case tar.TypeFifo: - /* Ignore. */ - default: - return output, fmt.Errorf("invalid type %q", t) - } - - totalChunksSize += r.Size - - finalizeFile := func(dstFile *os.File) error { - if dstFile != nil { - defer dstFile.Close() - if err := setFileAttrs(dstFile, mode, &r, options); err != nil { - return err - } - } - return nil - } - - found, dstFile, _, err := findFileInOtherLayers(&r, dirfd, otherLayersCache, c.layersTarget, useHardLinks) - if err != nil { - return output, err - } - if found { - if err := finalizeFile(dstFile); err != nil { - return output, err - } - continue - } - - found, dstFile, _, err = findFileInOSTreeRepos(&r, ostreeRepos, dirfd, useHardLinks) - if err != nil { - return output, err - } - if found { - if err := finalizeFile(dstFile); err != nil { - return output, err - } - continue - } - - if enableHostDedup { - found, dstFile, _, err = findFileOnTheHost(&r, dirfd, useHardLinks) - if err != nil { - return output, err - } - if found { - if err := finalizeFile(dstFile); err != nil { - return output, err - } - continue - } - } - - missingChunksSize += r.Size - if t == tar.TypeReg { - rawChunk := ImageSourceChunk{ - Offset: uint64(r.Offset), - Length: uint64(r.EndOffset - r.Offset), - } - - file := missingFile{ - File: &mergedEntries[i], - } - - missingChunks = append(missingChunks, missingChunk{ - RawChunk: rawChunk, - Files: []missingFile{ - file, - }, - }) - } - } - // There are some missing files. Prepare a multirange request for the missing chunks. - if len(missingChunks) > 0 { - missingChunks = mergeMissingChunks(missingChunks, maxNumberMissingChunks) - if err := c.retrieveMissingFiles(dest, dirfd, missingChunks, options); err != nil { - return output, err - } - } - - for _, m := range hardLinks { - if err := safeLink(m.dirfd, m.mode, m.metadata, options); err != nil { - return output, err - } - } - - if totalChunksSize > 0 { - logrus.Debugf("Missing %d bytes out of %d (%.2f %%)", missingChunksSize, totalChunksSize, float32(missingChunksSize*100.0)/float32(totalChunksSize)) - } - return output, nil -} - -func (c *chunkedDiffer) mergeTocEntries(fileType compressedFileType, entries []internal.FileMetadata) ([]internal.FileMetadata, error) { - var mergedEntries []internal.FileMetadata - var prevEntry *internal.FileMetadata - for _, entry := range entries { - e := entry - - // ignore the metadata files for the estargz format. - if fileType == fileTypeEstargz && (e.Name == estargz.PrefetchLandmark || e.Name == estargz.NoPrefetchLandmark || e.Name == estargz.TOCTarName) { - continue - } - - if e.Type == TypeChunk { - if prevEntry == nil || prevEntry.Type != TypeReg { - return nil, errors.New("chunk type without a regular file") - } - prevEntry.EndOffset = e.EndOffset - continue - } - mergedEntries = append(mergedEntries, e) - prevEntry = &e - } - // stargz/estargz doesn't store EndOffset so let's calculate it here - lastOffset := c.tocOffset - for i := len(mergedEntries) - 1; i >= 0; i-- { - if mergedEntries[i].EndOffset == 0 { - mergedEntries[i].EndOffset = lastOffset - } - if mergedEntries[i].Offset != 0 { - lastOffset = mergedEntries[i].Offset - } - } - return mergedEntries, nil -} diff --git a/examples/vendor/github.com/cri-o/ocicni/LICENSE b/examples/vendor/github.com/cri-o/ocicni/LICENSE deleted file mode 100644 index 3fd7030..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2016 Red Hat, 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. diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/ocicni.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/ocicni.go deleted file mode 100644 index 90d5b6c..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/ocicni.go +++ /dev/null @@ -1,870 +0,0 @@ -package ocicni - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "os" - "path" - "path/filepath" - "sort" - "strings" - "sync" - - "github.com/containernetworking/cni/libcni" - cniinvoke "github.com/containernetworking/cni/pkg/invoke" - cnitypes "github.com/containernetworking/cni/pkg/types" - cnicurrent "github.com/containernetworking/cni/pkg/types/current" - cniversion "github.com/containernetworking/cni/pkg/version" - "github.com/fsnotify/fsnotify" - "github.com/sirupsen/logrus" -) - -type cniNetworkPlugin struct { - cniConfig *libcni.CNIConfig - - sync.RWMutex - defaultNetName netName - networks map[string]*cniNetwork - - nsManager *nsManager - confDir string - binDirs []string - - shutdownChan chan struct{} - watcher *fsnotify.Watcher - done *sync.WaitGroup - - // The pod map provides synchronization for a given pod's network - // operations. Each pod's setup/teardown/status operations - // are synchronized against each other, but network operations of other - // pods can proceed in parallel. - podsLock sync.Mutex - pods map[string]*podLock - - // For testcases - exec cniinvoke.Exec - cacheDir string -} - -type netName struct { - name string - changeable bool -} - -type cniNetwork struct { - name string - filePath string - config *libcni.NetworkConfigList -} - -var errMissingDefaultNetwork = "No CNI configuration file in %s. Has your network provider started?" - -type podLock struct { - // Count of in-flight operations for this pod; when this reaches zero - // the lock can be removed from the pod map - refcount uint - - // Lock to synchronize operations for this specific pod - mu sync.Mutex -} - -func buildFullPodName(podNetwork PodNetwork) string { - return podNetwork.Namespace + "_" + podNetwork.Name -} - -// Lock network operations for a specific pod. If that pod is not yet in -// the pod map, it will be added. The reference count for the pod will -// be increased. -func (plugin *cniNetworkPlugin) podLock(podNetwork PodNetwork) *sync.Mutex { - plugin.podsLock.Lock() - defer plugin.podsLock.Unlock() - - fullPodName := buildFullPodName(podNetwork) - lock, ok := plugin.pods[fullPodName] - if !ok { - lock = &podLock{} - plugin.pods[fullPodName] = lock - } - lock.refcount++ - return &lock.mu -} - -// Unlock network operations for a specific pod. The reference count for the -// pod will be decreased. If the reference count reaches zero, the pod will be -// removed from the pod map. -func (plugin *cniNetworkPlugin) podUnlock(podNetwork PodNetwork) { - plugin.podsLock.Lock() - defer plugin.podsLock.Unlock() - - fullPodName := buildFullPodName(podNetwork) - lock, ok := plugin.pods[fullPodName] - if !ok { - logrus.Errorf("Cannot find reference in refcount map for %s. Refcount cannot be determined.", fullPodName) - return - } else if lock.refcount == 0 { - // This should never ever happen, but handle it anyway - delete(plugin.pods, fullPodName) - logrus.Errorf("Pod lock for %s still in map with zero refcount", fullPodName) - return - } - lock.refcount-- - lock.mu.Unlock() - if lock.refcount == 0 { - delete(plugin.pods, fullPodName) - } -} - -func newWatcher(confDir string) (*fsnotify.Watcher, error) { - // Ensure plugin directory exists, because the following monitoring logic - // relies on that. - if err := os.MkdirAll(confDir, 0755); err != nil { - return nil, fmt.Errorf("failed to create directory %q: %v", confDir, err) - } - - watcher, err := fsnotify.NewWatcher() - if err != nil { - return nil, fmt.Errorf("failed to create new watcher %v", err) - } - defer func() { - // Close watcher on error - if err != nil { - watcher.Close() - } - }() - - if err = watcher.Add(confDir); err != nil { - return nil, fmt.Errorf("failed to add watch on %q: %v", confDir, err) - } - - return watcher, nil -} - -func (plugin *cniNetworkPlugin) monitorConfDir(start *sync.WaitGroup) { - start.Done() - plugin.done.Add(1) - defer plugin.done.Done() - for { - select { - case event := <-plugin.watcher.Events: - logrus.Infof("CNI monitoring event %v", event) - - var defaultDeleted bool - createWrite := (event.Op&fsnotify.Create == fsnotify.Create || - event.Op&fsnotify.Write == fsnotify.Write) - if event.Op&fsnotify.Remove == fsnotify.Remove { - // Care about the event if the default network - // was just deleted - defNet := plugin.getDefaultNetwork() - if defNet != nil && event.Name == defNet.filePath { - defaultDeleted = true - } - - } - if !createWrite && !defaultDeleted { - continue - } - - if err := plugin.syncNetworkConfig(); err != nil { - logrus.Errorf("CNI config loading failed, continue monitoring: %v", err) - continue - } - - case err := <-plugin.watcher.Errors: - if err == nil { - continue - } - logrus.Errorf("CNI monitoring error %v", err) - return - - case <-plugin.shutdownChan: - return - } - } -} - -// InitCNI takes a binary directory in which to search for CNI plugins, and -// a configuration directory in which to search for CNI JSON config files. -// If no valid CNI configs exist, network requests will fail until valid CNI -// config files are present in the config directory. -// If defaultNetName is not empty, a CNI config with that network name will -// be used as the default CNI network, and container network operations will -// fail until that network config is present and valid. -// If defaultNetName is empty, CNI config files should be reloaded real-time and -// defaultNetName should be changeable and determined by file sorting. -func InitCNI(defaultNetName string, confDir string, binDirs ...string) (CNIPlugin, error) { - return initCNI(nil, "", defaultNetName, confDir, true, binDirs...) -} - -// InitCNIWithCache works like InitCNI except that it takes the cni cache directory as third param. -func InitCNIWithCache(defaultNetName, confDir, cacheDir string, binDirs ...string) (CNIPlugin, error) { - return initCNI(nil, cacheDir, defaultNetName, confDir, true, binDirs...) -} - -// InitCNINoInotify works like InitCNI except that it does not use inotify to watch for changes in the CNI config dir. -func InitCNINoInotify(defaultNetName, confDir, cacheDir string, binDirs ...string) (CNIPlugin, error) { - return initCNI(nil, cacheDir, defaultNetName, confDir, false, binDirs...) -} - -// Internal function to allow faking out exec functions for testing -func initCNI(exec cniinvoke.Exec, cacheDir, defaultNetName string, confDir string, useInotify bool, binDirs ...string) (CNIPlugin, error) { - if confDir == "" { - confDir = DefaultConfDir - } - if len(binDirs) == 0 { - binDirs = []string{DefaultBinDir} - } - - plugin := &cniNetworkPlugin{ - cniConfig: libcni.NewCNIConfigWithCacheDir(binDirs, cacheDir, exec), - defaultNetName: netName{ - name: defaultNetName, - // If defaultNetName is not assigned in initialization, - // it should be changeable - changeable: defaultNetName == "", - }, - networks: make(map[string]*cniNetwork), - confDir: confDir, - binDirs: binDirs, - shutdownChan: make(chan struct{}), - done: &sync.WaitGroup{}, - pods: make(map[string]*podLock), - exec: exec, - cacheDir: cacheDir, - } - - if exec == nil { - exec = &cniinvoke.DefaultExec{ - RawExec: &cniinvoke.RawExec{Stderr: os.Stderr}, - PluginDecoder: cniversion.PluginDecoder{}, - } - } - - nsm, err := newNSManager() - if err != nil { - return nil, err - } - plugin.nsManager = nsm - - plugin.syncNetworkConfig() - - if useInotify { - plugin.watcher, err = newWatcher(plugin.confDir) - if err != nil { - return nil, err - } - - startWg := sync.WaitGroup{} - startWg.Add(1) - go plugin.monitorConfDir(&startWg) - startWg.Wait() - } - - return plugin, nil -} - -func (plugin *cniNetworkPlugin) Shutdown() error { - close(plugin.shutdownChan) - if plugin.watcher != nil { - plugin.watcher.Close() - } - plugin.done.Wait() - return nil -} - -func loadNetworks(confDir string, cni *libcni.CNIConfig) (map[string]*cniNetwork, string, error) { - files, err := libcni.ConfFiles(confDir, []string{".conf", ".conflist", ".json"}) - if err != nil { - return nil, "", err - } - - networks := make(map[string]*cniNetwork) - defaultNetName := "" - - sort.Strings(files) - for _, confFile := range files { - var confList *libcni.NetworkConfigList - if strings.HasSuffix(confFile, ".conflist") { - confList, err = libcni.ConfListFromFile(confFile) - if err != nil { - // do not log ENOENT errors - if !os.IsNotExist(err) { - logrus.Errorf("Error loading CNI config list file %s: %v", confFile, err) - } - continue - } - } else { - conf, err := libcni.ConfFromFile(confFile) - if err != nil { - // do not log ENOENT errors - if !os.IsNotExist(err) { - logrus.Errorf("Error loading CNI config file %s: %v", confFile, err) - } - continue - } - if conf.Network.Type == "" { - logrus.Warningf("Error loading CNI config file %s: no 'type'; perhaps this is a .conflist?", confFile) - continue - } - confList, err = libcni.ConfListFromConf(conf) - if err != nil { - logrus.Errorf("Error converting CNI config file %s to list: %v", confFile, err) - continue - } - } - if len(confList.Plugins) == 0 { - logrus.Infof("CNI config list %s has no networks, skipping", confFile) - continue - } - - // Validation on CNI config should be done to pre-check presence - // of plugins which are necessary. - if _, err := cni.ValidateNetworkList(context.TODO(), confList); err != nil { - logrus.Warningf("Error validating CNI config file %s: %v", confFile, err) - continue - } - - if confList.Name == "" { - confList.Name = path.Base(confFile) - } - - cniNet := &cniNetwork{ - name: confList.Name, - filePath: confFile, - config: confList, - } - - logrus.Infof("Found CNI network %s (type=%v) at %s", confList.Name, confList.Plugins[0].Network.Type, confFile) - - if _, ok := networks[confList.Name]; !ok { - networks[confList.Name] = cniNet - } else { - logrus.Infof("Ignored CNI network %s (type=%v) at %s because already exists", confList.Name, confList.Plugins[0].Network.Type, confFile) - } - - if defaultNetName == "" { - defaultNetName = confList.Name - } - } - - return networks, defaultNetName, nil -} - -const ( - loIfname string = "lo" -) - -func (plugin *cniNetworkPlugin) syncNetworkConfig() error { - networks, defaultNetName, err := loadNetworks(plugin.confDir, plugin.cniConfig) - if err != nil { - return err - } - - plugin.Lock() - defer plugin.Unlock() - - // Update defaultNetName if it is changeable - if plugin.defaultNetName.changeable { - plugin.defaultNetName.name = defaultNetName - logrus.Infof("Updated default CNI network name to %s", defaultNetName) - } else { - logrus.Debugf("Default CNI network name %s is unchangeable", plugin.defaultNetName.name) - } - - plugin.networks = networks - - return nil -} - -func (plugin *cniNetworkPlugin) getNetwork(name string) (*cniNetwork, error) { - plugin.RLock() - defer plugin.RUnlock() - net, ok := plugin.networks[name] - if !ok { - return nil, fmt.Errorf("CNI network %q not found", name) - } - return net, nil -} - -func (plugin *cniNetworkPlugin) GetDefaultNetworkName() string { - plugin.RLock() - defer plugin.RUnlock() - return plugin.defaultNetName.name -} - -func (plugin *cniNetworkPlugin) getDefaultNetwork() *cniNetwork { - defaultNetName := plugin.GetDefaultNetworkName() - if defaultNetName == "" { - return nil - } - network, _ := plugin.getNetwork(defaultNetName) - return network -} - -// networksAvailable returns an error if the pod requests no networks and the -// plugin has no default network, and thus the plugin has no idea what network -// to attach the pod to. -func (plugin *cniNetworkPlugin) networksAvailable(podNetwork *PodNetwork) error { - if len(podNetwork.Networks) == 0 && plugin.getDefaultNetwork() == nil { - return fmt.Errorf(errMissingDefaultNetwork, plugin.confDir) - } - return nil -} - -func (plugin *cniNetworkPlugin) Name() string { - return CNIPluginName -} - -func (plugin *cniNetworkPlugin) loadNetworkFromCache(name string, rt *libcni.RuntimeConf) (*cniNetwork, *libcni.RuntimeConf, error) { - cniNet := &cniNetwork{ - name: name, - config: &libcni.NetworkConfigList{ - Name: name, - }, - } - - var confBytes []byte - var err error - confBytes, rt, err = plugin.cniConfig.GetNetworkListCachedConfig(cniNet.config, rt) - if err != nil { - return nil, nil, err - } else if confBytes == nil { - return nil, nil, fmt.Errorf("network %q not found in CNI cache", name) - } - - cniNet.config, err = libcni.ConfListFromBytes(confBytes) - if err != nil { - // Might be a plain NetworkConfig - netConf, err := libcni.ConfFromBytes(confBytes) - if err != nil { - return nil, nil, err - } - // Up-convert to a NetworkConfigList - cniNet.config, err = libcni.ConfListFromConf(netConf) - if err != nil { - return nil, nil, err - } - } - - return cniNet, rt, nil -} - -type forEachNetworkFn func(*cniNetwork, *PodNetwork, *libcni.RuntimeConf) error - -func (plugin *cniNetworkPlugin) forEachNetwork(podNetwork *PodNetwork, fromCache bool, actionFn forEachNetworkFn) error { - networks := podNetwork.Networks - if len(networks) == 0 { - networks = append(networks, NetAttachment{ - Name: plugin.GetDefaultNetworkName(), - }) - } - - allIfNames := make(map[string]bool) - for _, req := range networks { - if req.Ifname != "" { - // Make sure the requested name isn't already assigned - if allIfNames[req.Ifname] { - return fmt.Errorf("network %q requested interface name %q already assigned", req.Name, req.Ifname) - } - allIfNames[req.Ifname] = true - } - } - - for _, network := range networks { - ifName := network.Ifname - if ifName == "" { - for i := 0; i < 10000; i++ { - candidate := fmt.Sprintf("eth%d", i) - if !allIfNames[candidate] { - allIfNames[candidate] = true - ifName = candidate - break - } - } - if ifName == "" { - return fmt.Errorf("failed to find free interface name for network %q", network.Name) - } - } - - rt, err := buildCNIRuntimeConf(podNetwork, ifName, podNetwork.RuntimeConfig[network.Name]) - if err != nil { - logrus.Errorf("error building CNI runtime config: %v", err) - return err - } - - var cniNet *cniNetwork - if fromCache { - var newRt *libcni.RuntimeConf - cniNet, newRt, err = plugin.loadNetworkFromCache(network.Name, rt) - if err != nil { - logrus.Errorf("error loading cached network config: %v", err) - logrus.Warningf("falling back to loading from existing plugins on disk") - } else { - // Use the updated RuntimeConf - rt = newRt - } - } - if cniNet == nil { - cniNet, err = plugin.getNetwork(network.Name) - if err != nil { - // try to load the networks again - if err2 := plugin.syncNetworkConfig(); err2 != nil { - logrus.Error(err2) - return err - } - cniNet, err = plugin.getNetwork(network.Name) - if err != nil { - return err - } - } - } - - if err := actionFn(cniNet, podNetwork, rt); err != nil { - return err - } - } - return nil -} - -func (plugin *cniNetworkPlugin) SetUpPod(podNetwork PodNetwork) ([]NetResult, error) { - return plugin.SetUpPodWithContext(context.Background(), podNetwork) -} - -func (plugin *cniNetworkPlugin) SetUpPodWithContext(ctx context.Context, podNetwork PodNetwork) ([]NetResult, error) { - if err := plugin.networksAvailable(&podNetwork); err != nil { - return nil, err - } - - plugin.podLock(podNetwork).Lock() - defer plugin.podUnlock(podNetwork) - - // Set up loopback interface - if err := bringUpLoopback(podNetwork.NetNS); err != nil { - logrus.Errorf(err.Error()) - return nil, err - } - - results := make([]NetResult, 0) - if err := plugin.forEachNetwork(&podNetwork, false, func(network *cniNetwork, podNetwork *PodNetwork, rt *libcni.RuntimeConf) error { - fullPodName := buildFullPodName(*podNetwork) - logrus.Infof("Adding pod %s to CNI network %q (type=%v)", fullPodName, network.name, network.config.Plugins[0].Network.Type) - result, err := network.addToNetwork(ctx, rt, plugin.cniConfig) - if err != nil { - return fmt.Errorf("error adding pod %s to CNI network %q: %v", fullPodName, network.name, err) - } - results = append(results, NetResult{ - Result: result, - NetAttachment: NetAttachment{ - Name: network.name, - Ifname: rt.IfName, - }, - }) - return nil - }); err != nil { - return nil, err - } - - return results, nil -} - -func (plugin *cniNetworkPlugin) getCachedNetworkInfo(containerID string) ([]NetAttachment, error) { - cacheDir := libcni.CacheDir - if plugin.cacheDir != "" { - cacheDir = plugin.cacheDir - } - - dirPath := filepath.Join(cacheDir, "results") - entries, err := ioutil.ReadDir(dirPath) - if err != nil { - return nil, err - } - - fileNames := make([]string, 0, len(entries)) - for _, e := range entries { - fileNames = append(fileNames, e.Name()) - } - sort.Strings(fileNames) - - attachments := []NetAttachment{} - for _, fname := range fileNames { - part := fmt.Sprintf("-%s-", containerID) - pos := strings.Index(fname, part) - if pos <= 0 || pos+len(part) >= len(fname) { - continue - } - - cacheFile := filepath.Join(dirPath, fname) - bytes, err := ioutil.ReadFile(cacheFile) - if err != nil { - logrus.Errorf("failed to read CNI cache file %s: %v", cacheFile, err) - continue - } - - cachedInfo := struct { - Kind string `json:"kind"` - IfName string `json:"ifName"` - ContainerID string `json:"containerID"` - NetName string `json:"networkName"` - }{} - - if err := json.Unmarshal(bytes, &cachedInfo); err != nil { - logrus.Errorf("failed to unmarshal CNI cache file %s: %v", cacheFile, err) - continue - } - if cachedInfo.Kind != libcni.CNICacheV1 { - logrus.Warningf("unknown CNI cache file %s kind %q", cacheFile, cachedInfo.Kind) - continue - } - if cachedInfo.ContainerID != containerID { - continue - } - // Ignore the loopback interface; it's handled separately - if cachedInfo.IfName == loIfname && cachedInfo.NetName == "cni-loopback" { - continue - } - if cachedInfo.IfName == "" || cachedInfo.NetName == "" { - logrus.Warningf("missing CNI cache file %s ifname %q or netname %q", cacheFile, cachedInfo.IfName, cachedInfo.NetName) - continue - } - - attachments = append(attachments, NetAttachment{ - Name: cachedInfo.NetName, - Ifname: cachedInfo.IfName, - }) - } - return attachments, nil -} - -// TearDownPod tears down pod networks. Prefers cached pod attachment information -// but falls back to given network attachment information. -func (plugin *cniNetworkPlugin) TearDownPod(podNetwork PodNetwork) error { - return plugin.TearDownPodWithContext(context.Background(), podNetwork) -} - -func (plugin *cniNetworkPlugin) TearDownPodWithContext(ctx context.Context, podNetwork PodNetwork) error { - if len(podNetwork.Networks) == 0 { - attachments, err := plugin.getCachedNetworkInfo(podNetwork.ID) - if err == nil && len(attachments) > 0 { - podNetwork.Networks = attachments - } - } - - if err := plugin.networksAvailable(&podNetwork); err != nil { - return err - } - - plugin.podLock(podNetwork).Lock() - defer plugin.podUnlock(podNetwork) - - if err := tearDownLoopback(podNetwork.NetNS); err != nil { - // ignore error - logrus.Warningf("Ignoring error tearing down loopback interface: %v", err) - } - - return plugin.forEachNetwork(&podNetwork, true, func(network *cniNetwork, podNetwork *PodNetwork, rt *libcni.RuntimeConf) error { - fullPodName := buildFullPodName(*podNetwork) - logrus.Infof("Deleting pod %s from CNI network %q (type=%v)", fullPodName, network.name, network.config.Plugins[0].Network.Type) - if err := network.deleteFromNetwork(ctx, rt, plugin.cniConfig); err != nil { - return fmt.Errorf("error removing pod %s from CNI network %q: %v", fullPodName, network.name, err) - } - return nil - }) -} - -// GetPodNetworkStatus returns IP addressing and interface details for all -// networks attached to the pod. -func (plugin *cniNetworkPlugin) GetPodNetworkStatus(podNetwork PodNetwork) ([]NetResult, error) { - return plugin.GetPodNetworkStatusWithContext(context.Background(), podNetwork) -} - -// GetPodNetworkStatusWithContext returns IP addressing and interface details for all -// networks attached to the pod. -func (plugin *cniNetworkPlugin) GetPodNetworkStatusWithContext(ctx context.Context, podNetwork PodNetwork) ([]NetResult, error) { - plugin.podLock(podNetwork).Lock() - defer plugin.podUnlock(podNetwork) - - if err := checkLoopback(podNetwork.NetNS); err != nil { - logrus.Errorf(err.Error()) - return nil, err - } - - results := make([]NetResult, 0) - if err := plugin.forEachNetwork(&podNetwork, true, func(network *cniNetwork, podNetwork *PodNetwork, rt *libcni.RuntimeConf) error { - fullPodName := buildFullPodName(*podNetwork) - logrus.Infof("Checking pod %s for CNI network %s (type=%v)", fullPodName, network.name, network.config.Plugins[0].Network.Type) - result, err := network.checkNetwork(ctx, rt, plugin.cniConfig, plugin.nsManager, podNetwork.NetNS) - if err != nil { - return fmt.Errorf("error checking pod %s for CNI network %q: %v", fullPodName, network.name, err) - } - if result != nil { - results = append(results, NetResult{ - Result: result, - NetAttachment: NetAttachment{ - Name: network.name, - Ifname: rt.IfName, - }, - }) - } - return nil - }); err != nil { - return nil, err - } - - return results, nil -} - -func (network *cniNetwork) addToNetwork(ctx context.Context, rt *libcni.RuntimeConf, cni *libcni.CNIConfig) (cnitypes.Result, error) { - return cni.AddNetworkList(ctx, network.config, rt) -} - -func (network *cniNetwork) checkNetwork(ctx context.Context, rt *libcni.RuntimeConf, cni *libcni.CNIConfig, nsManager *nsManager, netns string) (cnitypes.Result, error) { - gtet, err := cniversion.GreaterThanOrEqualTo(network.config.CNIVersion, "0.4.0") - if err != nil { - return nil, err - } - - var result cnitypes.Result - - // When CNIVersion supports Check, use it. Otherwise fall back on what was done initially. - if gtet { - err = cni.CheckNetworkList(ctx, network.config, rt) - logrus.Infof("Checking CNI network %s (config version=%v)", network.name, network.config.CNIVersion) - if err != nil { - logrus.Errorf("Error checking network: %v", err) - return nil, err - } - } - - result, err = cni.GetNetworkListCachedResult(network.config, rt) - if err != nil { - logrus.Errorf("Error getting network list cached result: %v", err) - return nil, err - } else if result != nil { - return result, nil - } - - // result doesn't exist, create one - logrus.Infof("Checking CNI network %s (config version=%v) nsManager=%v", network.name, network.config.CNIVersion, nsManager) - - var cniInterface *cnicurrent.Interface - ips := []*cnicurrent.IPConfig{} - errs := []error{} - for _, version := range []string{"4", "6"} { - ip, mac, err := getContainerDetails(nsManager, netns, rt.IfName, "-"+version) - if err == nil { - if cniInterface == nil { - cniInterface = &cnicurrent.Interface{ - Name: rt.IfName, - Mac: mac.String(), - Sandbox: netns, - } - } - ips = append(ips, &cnicurrent.IPConfig{ - Version: version, - Interface: cnicurrent.Int(0), - Address: *ip, - }) - } else { - errs = append(errs, err) - } - } - if cniInterface == nil || len(ips) == 0 { - return nil, fmt.Errorf("neither IPv4 nor IPv6 found when retrieving network status: %v", errs) - } - - result = &cnicurrent.Result{ - CNIVersion: network.config.CNIVersion, - Interfaces: []*cnicurrent.Interface{cniInterface}, - IPs: ips, - } - - // Result must be the same CNIVersion as the CNI config - converted, err := result.GetAsVersion(network.config.CNIVersion) - if err != nil { - return nil, err - } - - return converted, nil -} - -func (network *cniNetwork) deleteFromNetwork(ctx context.Context, rt *libcni.RuntimeConf, cni *libcni.CNIConfig) error { - return cni.DelNetworkList(ctx, network.config, rt) -} - -func buildCNIRuntimeConf(podNetwork *PodNetwork, ifName string, runtimeConfig RuntimeConfig) (*libcni.RuntimeConf, error) { - logrus.Infof("Got pod network %+v", podNetwork) - - rt := &libcni.RuntimeConf{ - ContainerID: podNetwork.ID, - NetNS: podNetwork.NetNS, - IfName: ifName, - Args: [][2]string{ - {"IgnoreUnknown", "1"}, - {"K8S_POD_NAMESPACE", podNetwork.Namespace}, - {"K8S_POD_NAME", podNetwork.Name}, - {"K8S_POD_INFRA_CONTAINER_ID", podNetwork.ID}, - }, - CapabilityArgs: map[string]interface{}{}, - } - - // Propagate existing CNI_ARGS to non-k8s consumers - for _, kvpairs := range strings.Split(os.Getenv("CNI_ARGS"), ";") { - if keyval := strings.SplitN(kvpairs, "=", 2); len(keyval) == 2 { - rt.Args = append(rt.Args, [2]string{keyval[0], keyval[1]}) - } - } - - // Add requested static IP to CNI_ARGS - ip := runtimeConfig.IP - if ip != "" { - if tstIP := net.ParseIP(ip); tstIP == nil { - return nil, fmt.Errorf("unable to parse IP address %q", ip) - } - rt.Args = append(rt.Args, [2]string{"IP", ip}) - } - - // Add the requested static MAC to CNI_ARGS - mac := runtimeConfig.MAC - if mac != "" { - _, err := net.ParseMAC(mac) - if err != nil { - return nil, fmt.Errorf("unable to parse MAC address %q: %v", mac, err) - } - rt.Args = append(rt.Args, [2]string{"MAC", mac}) - } - - // Set PortMappings in Capabilities - if len(runtimeConfig.PortMappings) != 0 { - rt.CapabilityArgs["portMappings"] = runtimeConfig.PortMappings - } - - // Set Bandwidth in Capabilities - if runtimeConfig.Bandwidth != nil { - rt.CapabilityArgs["bandwidth"] = map[string]uint64{ - "ingressRate": runtimeConfig.Bandwidth.IngressRate, - "ingressBurst": runtimeConfig.Bandwidth.IngressBurst, - "egressRate": runtimeConfig.Bandwidth.EgressRate, - "egressBurst": runtimeConfig.Bandwidth.EgressBurst, - } - } - - // Set IpRanges in Capabilities - if len(runtimeConfig.IpRanges) > 0 { - rt.CapabilityArgs["ipRanges"] = runtimeConfig.IpRanges - } - - // Set Aliases in Capabilities - if len(podNetwork.Aliases) > 0 { - rt.CapabilityArgs["aliases"] = podNetwork.Aliases - } - return rt, nil -} - -func (plugin *cniNetworkPlugin) Status() error { - if plugin.getDefaultNetwork() == nil { - return fmt.Errorf(errMissingDefaultNetwork, plugin.confDir) - } - return nil -} diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types.go deleted file mode 100644 index 7326b4b..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types.go +++ /dev/null @@ -1,152 +0,0 @@ -package ocicni - -import ( - "context" - - "github.com/containernetworking/cni/pkg/types" -) - -const ( - // DefaultInterfaceName is the string to be used for the interface name inside the net namespace - DefaultInterfaceName = "eth0" - // CNIPluginName is the default name of the plugin - CNIPluginName = "cni" -) - -// PortMapping maps to the standard CNI portmapping Capability -// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md -type PortMapping struct { - // HostPort is the port number on the host. - HostPort int32 `json:"hostPort"` - // ContainerPort is the port number inside the sandbox. - ContainerPort int32 `json:"containerPort"` - // Protocol is the protocol of the port mapping. - Protocol string `json:"protocol"` - // HostIP is the host ip to use. - HostIP string `json:"hostIP"` -} - -// IpRange maps to the standard CNI ipRanges Capability -// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md -type IpRange struct { - // Subnet is the whole CIDR - Subnet string `json:"subnet"` - // RangeStart is the first available IP in subnet - RangeStart string `json:"rangeStart,omitempty"` - // RangeEnd is the last available IP in subnet - RangeEnd string `json:"rangeEnd,omitempty"` - // Gateway is the gateway of subnet - Gateway string `json:"gateway,omitempty"` -} - -// RuntimeConfig is additional configuration for a single CNI network that -// is pod-specific rather than general to the network. -type RuntimeConfig struct { - // IP is a static IP to be specified in the network. Can only be used - // with the hostlocal IP allocator. If left unset, an IP will be - // dynamically allocated. - IP string - // MAC is a static MAC address to be assigned to the network interface. - // If left unset, a MAC will be dynamically allocated. - MAC string - // PortMappings is the port mapping of the sandbox. - PortMappings []PortMapping - // Bandwidth is the bandwidth limiting of the pod - Bandwidth *BandwidthConfig - // IpRanges is the ip range gather which is used for address allocation - IpRanges [][]IpRange -} - -// BandwidthConfig maps to the standard CNI bandwidth Capability -// see: https://github.com/containernetworking/cni/blob/master/CONVENTIONS.md -type BandwidthConfig struct { - // IngressRate is a limit for incoming traffic in bps - IngressRate uint64 - IngressBurst uint64 - - // EgressRate is a limit for outgoing traffic in bps - EgressRate uint64 - EgressBurst uint64 -} - -// PodNetwork configures the network of a pod sandbox. -type PodNetwork struct { - // Name is the name of the sandbox. - Name string - // Namespace is the namespace of the sandbox. - Namespace string - // ID is the id of the sandbox container. - ID string - // NetNS is the network namespace path of the sandbox. - NetNS string - - // Networks is a list of CNI network names (and optional interface - // names) to attach to the sandbox. Leave this list empty to attach the - // default network to the sandbox - Networks []NetAttachment - - // NetworkConfig is configuration specific to a single CNI network. - // It is optional, and can be omitted for some or all specified networks - // without issue. - RuntimeConfig map[string]RuntimeConfig - - // Aliases are network-scoped names for resolving a container - // by name. The key value is the network name and the value is - // is a string slice of aliases - Aliases map[string][]string -} - -// NetAttachment describes a container network attachment -type NetAttachment struct { - // NetName contains the name of the CNI network to which the container - // should be or is attached - Name string - // Ifname contains the optional interface name of the attachment - Ifname string -} - -// NetResult contains the result the network attachment operation -type NetResult struct { - // Result is the CNI Result - Result types.Result - // NetAttachment contains the network and interface names of this - // network attachment - NetAttachment -} - -// CNIPlugin is the interface that needs to be implemented by a plugin -type CNIPlugin interface { - // Name returns the plugin's name. This will be used when searching - // for a plugin by name, e.g. - Name() string - - // GetDefaultNetworkName returns the name of the plugin's default - // network. - GetDefaultNetworkName() string - - // SetUpPod is the method called after the sandbox container of - // the pod has been created but before the other containers of the - // pod are launched. - SetUpPod(network PodNetwork) ([]NetResult, error) - - // SetUpPodWithContext is the same as SetUpPod but takes a context - SetUpPodWithContext(ctx context.Context, network PodNetwork) ([]NetResult, error) - - // TearDownPod is the method called before a pod's sandbox container will be deleted - TearDownPod(network PodNetwork) error - - // TearDownPodWithContext is the same as TearDownPod but takes a context - TearDownPodWithContext(ctx context.Context, network PodNetwork) error - - // GetPodNetworkStatus is the method called to obtain the ipv4 or ipv6 addresses of the pod sandbox - GetPodNetworkStatus(network PodNetwork) ([]NetResult, error) - - // GetPodNetworkStatusWithContext is the same as GetPodNetworkStatus but takes a context - GetPodNetworkStatusWithContext(ctx context.Context, network PodNetwork) ([]NetResult, error) - - // NetworkStatus returns error if the network plugin is in error state - Status() error - - // Shutdown terminates all driver operations - Shutdown() error -} diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_unix.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_unix.go deleted file mode 100644 index 88010f7..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package ocicni - -const ( - // DefaultConfDir is the default place to look for CNI Network - DefaultConfDir = "/etc/cni/net.d" - // DefaultBinDir is the default place to look for CNI config files - DefaultBinDir = "/opt/cni/bin" -) diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_windows.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_windows.go deleted file mode 100644 index 061ecae..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/types_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build windows - -package ocicni - -const ( - // DefaultConfDir is the default place to look for CNI Network - DefaultConfDir = "C:\\cni\\etc\\net.d" - // DefaultBinDir is the default place to look for cni config files - DefaultBinDir = "C:\\cni\\bin" -) diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util.go deleted file mode 100644 index 2af7865..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util.go +++ /dev/null @@ -1,8 +0,0 @@ -package ocicni - -// newNSManager initializes a new namespace manager, which is a platform dependent struct. -func newNSManager() (*nsManager, error) { - nsm := &nsManager{} - err := nsm.init() - return nsm, err -} diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_linux.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_linux.go deleted file mode 100644 index 53c22f8..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_linux.go +++ /dev/null @@ -1,150 +0,0 @@ -// +build linux - -package ocicni - -import ( - "fmt" - "net" - "os/exec" - "strings" - - "github.com/containernetworking/plugins/pkg/ns" - "github.com/vishvananda/netlink" -) - -var defaultNamespaceEnterCommandName = "nsenter" - -type nsManager struct { - nsenterPath string -} - -func (nsm *nsManager) init() error { - var err error - nsm.nsenterPath, err = exec.LookPath(defaultNamespaceEnterCommandName) - return err -} - -func getContainerDetails(nsm *nsManager, netnsPath, interfaceName, addrType string) (*net.IPNet, *net.HardwareAddr, error) { - // Try to retrieve ip inside container network namespace - output, err := exec.Command(nsm.nsenterPath, fmt.Sprintf("--net=%s", netnsPath), "-F", "--", - "ip", "-o", addrType, "addr", "show", "dev", interfaceName, "scope", "global").CombinedOutput() - if err != nil { - return nil, nil, fmt.Errorf("Unexpected command output %s with error: %v", output, err) - } - - lines := strings.Split(string(output), "\n") - if len(lines) < 1 { - return nil, nil, fmt.Errorf("Unexpected command output %s", output) - } - fields := strings.Fields(lines[0]) - if len(fields) < 4 { - return nil, nil, fmt.Errorf("Unexpected address output %s ", lines[0]) - } - ip, ipNet, err := net.ParseCIDR(fields[3]) - if err != nil { - return nil, nil, fmt.Errorf("CNI failed to parse ip from output %s due to %v", output, err) - } - if ip.To4() == nil { - ipNet.IP = ip - } else { - ipNet.IP = ip.To4() - } - - // Try to retrieve MAC inside container network namespace - output, err = exec.Command(nsm.nsenterPath, fmt.Sprintf("--net=%s", netnsPath), "-F", "--", - "ip", "link", "show", "dev", interfaceName).CombinedOutput() - if err != nil { - return nil, nil, fmt.Errorf("unexpected 'ip link' command output %s with error: %v", output, err) - } - - lines = strings.Split(string(output), "\n") - if len(lines) < 2 { - return nil, nil, fmt.Errorf("unexpected 'ip link' command output %s", output) - } - fields = strings.Fields(lines[1]) - if len(fields) < 4 { - return nil, nil, fmt.Errorf("unexpected link output %s ", lines[0]) - } - mac, err := net.ParseMAC(fields[1]) - if err != nil { - return nil, nil, fmt.Errorf("failed to parse MAC from output %s due to %v", output, err) - } - - return ipNet, &mac, nil -} - -func tearDownLoopback(netns string) error { - return ns.WithNetNSPath(netns, func(_ ns.NetNS) error { - link, err := netlink.LinkByName(loIfname) - if err != nil { - return err // not tested - } - err = netlink.LinkSetDown(link) - if err != nil { - return err // not tested - } - return nil - }) -} - -func bringUpLoopback(netns string) error { - if err := ns.WithNetNSPath(netns, func(_ ns.NetNS) error { - link, err := netlink.LinkByName(loIfname) - if err == nil { - err = netlink.LinkSetUp(link) - } - if err != nil { - return err - } - - v4Addrs, err := netlink.AddrList(link, netlink.FAMILY_V4) - if err != nil { - return err - } - if len(v4Addrs) != 0 { - // sanity check that this is a loopback address - for _, addr := range v4Addrs { - if !addr.IP.IsLoopback() { - return fmt.Errorf("loopback interface found with non-loopback address %q", addr.IP) - } - } - } - - v6Addrs, err := netlink.AddrList(link, netlink.FAMILY_V6) - if err != nil { - return err - } - if len(v6Addrs) != 0 { - // sanity check that this is a loopback address - for _, addr := range v6Addrs { - if !addr.IP.IsLoopback() { - return fmt.Errorf("loopback interface found with non-loopback address %q", addr.IP) - } - } - } - - return nil - }); err != nil { - return fmt.Errorf("error adding loopback interface: %s", err) - } - return nil -} - -func checkLoopback(netns string) error { - // Make sure loopback interface is up - if err := ns.WithNetNSPath(netns, func(_ ns.NetNS) error { - link, err := netlink.LinkByName(loIfname) - if err != nil { - return err - } - - if link.Attrs().Flags&net.FlagUp != net.FlagUp { - return fmt.Errorf("loopback interface is down") - } - - return nil - }); err != nil { - return fmt.Errorf("error checking loopback interface: %v", err) - } - return nil -} diff --git a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_unsupported.go b/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_unsupported.go deleted file mode 100644 index b87f0d3..0000000 --- a/examples/vendor/github.com/cri-o/ocicni/pkg/ocicni/util_unsupported.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build !linux - -package ocicni - -import ( - "errors" - "net" -) - -type nsManager struct { -} - -var errUnsupportedPlatform = errors.New("unsupported platform") - -func (nsm *nsManager) init() error { - return nil -} - -func getContainerDetails(nsm *nsManager, netnsPath, interfaceName, addrType string) (*net.IPNet, *net.HardwareAddr, error) { - return nil, nil, errUnsupportedPlatform -} - -func tearDownLoopback(netns string) error { - return errUnsupportedPlatform -} - -func bringUpLoopback(netns string) error { - return errUnsupportedPlatform -} - -func checkLoopback(netns string) error { - return errUnsupportedPlatform - -} diff --git a/examples/vendor/github.com/docker/distribution/.gometalinter.json b/examples/vendor/github.com/docker/distribution/.gometalinter.json deleted file mode 100644 index 9df5b14..0000000 --- a/examples/vendor/github.com/docker/distribution/.gometalinter.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Vendor": true, - "Deadline": "2m", - "Sort": ["linter", "severity", "path", "line"], - "EnableGC": true, - "Enable": [ - "structcheck", - "staticcheck", - "unconvert", - - "gofmt", - "goimports", - "golint", - "vet" - ] -} diff --git a/examples/vendor/github.com/docker/distribution/.travis.yml b/examples/vendor/github.com/docker/distribution/.travis.yml deleted file mode 100644 index 44ced60..0000000 --- a/examples/vendor/github.com/docker/distribution/.travis.yml +++ /dev/null @@ -1,51 +0,0 @@ -dist: trusty -sudo: required -# setup travis so that we can run containers for integration tests -services: - - docker - -language: go - -go: - - "1.11.x" - -go_import_path: github.com/docker/distribution - -addons: - apt: - packages: - - python-minimal - - -env: - - TRAVIS_GOOS=linux DOCKER_BUILDTAGS="include_oss include_gcs" TRAVIS_CGO_ENABLED=1 - -before_install: - - uname -r - - sudo apt-get -q update - -install: - - go get -u github.com/vbatts/git-validation - # TODO: Add enforcement of license - # - go get -u github.com/kunalkushwaha/ltag - - cd $TRAVIS_BUILD_DIR - -script: - - export GOOS=$TRAVIS_GOOS - - export CGO_ENABLED=$TRAVIS_CGO_ENABLED - - DCO_VERBOSITY=-q script/validate/dco - - GOOS=linux script/setup/install-dev-tools - - script/validate/vendor - - go build -i . - - make check - - make build - - make binaries - # Currently takes too long - #- if [ "$GOOS" = "linux" ]; then make test-race ; fi - - if [ "$GOOS" = "linux" ]; then make coverage ; fi - -after_success: - - bash <(curl -s https://codecov.io/bash) -F linux - -before_deploy: - # Run tests with storage driver configurations diff --git a/examples/vendor/github.com/docker/distribution/Dockerfile b/examples/vendor/github.com/docker/distribution/Dockerfile deleted file mode 100644 index 9537817..0000000 --- a/examples/vendor/github.com/docker/distribution/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -FROM golang:1.11-alpine AS build - -ENV DISTRIBUTION_DIR /go/src/github.com/docker/distribution -ENV BUILDTAGS include_oss include_gcs - -ARG GOOS=linux -ARG GOARCH=amd64 -ARG GOARM=6 - -RUN set -ex \ - && apk add --no-cache make git file - -WORKDIR $DISTRIBUTION_DIR -COPY . $DISTRIBUTION_DIR -RUN CGO_ENABLED=0 make PREFIX=/go clean binaries && file ./bin/registry | grep "statically linked" - -FROM alpine -COPY cmd/registry/config-dev.yml /etc/docker/registry/config.yml -COPY --from=build /go/src/github.com/docker/distribution/bin/registry /bin/registry -VOLUME ["/var/lib/registry"] -EXPOSE 5000 -ENTRYPOINT ["registry"] -CMD ["serve", "/etc/docker/registry/config.yml"] diff --git a/examples/vendor/github.com/docker/go-connections/sockets/README.md b/examples/vendor/github.com/docker/go-connections/sockets/README.md deleted file mode 100644 index e69de29..0000000 diff --git a/examples/vendor/github.com/docker/go-connections/sockets/proxy.go b/examples/vendor/github.com/docker/go-connections/sockets/proxy.go deleted file mode 100644 index 98e9a1d..0000000 --- a/examples/vendor/github.com/docker/go-connections/sockets/proxy.go +++ /dev/null @@ -1,51 +0,0 @@ -package sockets - -import ( - "net" - "net/url" - "os" - "strings" - - "golang.org/x/net/proxy" -) - -// GetProxyEnv allows access to the uppercase and the lowercase forms of -// proxy-related variables. See the Go specification for details on these -// variables. https://golang.org/pkg/net/http/ -func GetProxyEnv(key string) string { - proxyValue := os.Getenv(strings.ToUpper(key)) - if proxyValue == "" { - return os.Getenv(strings.ToLower(key)) - } - return proxyValue -} - -// DialerFromEnvironment takes in a "direct" *net.Dialer and returns a -// proxy.Dialer which will route the connections through the proxy using the -// given dialer. -func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) { - allProxy := GetProxyEnv("all_proxy") - if len(allProxy) == 0 { - return direct, nil - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return direct, err - } - - proxyFromURL, err := proxy.FromURL(proxyURL, direct) - if err != nil { - return direct, err - } - - noProxy := GetProxyEnv("no_proxy") - if len(noProxy) == 0 { - return proxyFromURL, nil - } - - perHost := proxy.NewPerHost(proxyFromURL, direct) - perHost.AddFromString(noProxy) - - return perHost, nil -} diff --git a/examples/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/examples/vendor/github.com/docker/go-connections/sockets/unix_socket.go deleted file mode 100644 index a8b5dbb..0000000 --- a/examples/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package sockets - -import ( - "net" - "os" - "syscall" -) - -// NewUnixSocket creates a unix socket with the specified path and group. -func NewUnixSocket(path string, gid int) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - mask := syscall.Umask(0777) - defer syscall.Umask(mask) - - l, err := net.Listen("unix", path) - if err != nil { - return nil, err - } - if err := os.Chown(path, 0, gid); err != nil { - l.Close() - return nil, err - } - if err := os.Chmod(path, 0660); err != nil { - l.Close() - return nil, err - } - return l, nil -} diff --git a/examples/vendor/github.com/godbus/dbus/v5/homedir.go b/examples/vendor/github.com/godbus/dbus/v5/homedir.go deleted file mode 100644 index 0b745f9..0000000 --- a/examples/vendor/github.com/godbus/dbus/v5/homedir.go +++ /dev/null @@ -1,28 +0,0 @@ -package dbus - -import ( - "os" - "sync" -) - -var ( - homeDir string - homeDirLock sync.Mutex -) - -func getHomeDir() string { - homeDirLock.Lock() - defer homeDirLock.Unlock() - - if homeDir != "" { - return homeDir - } - - homeDir = os.Getenv("HOME") - if homeDir != "" { - return homeDir - } - - homeDir = lookupHomeDir() - return homeDir -} diff --git a/examples/vendor/github.com/godbus/dbus/v5/homedir_dynamic.go b/examples/vendor/github.com/godbus/dbus/v5/homedir_dynamic.go deleted file mode 100644 index 2732081..0000000 --- a/examples/vendor/github.com/godbus/dbus/v5/homedir_dynamic.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !static_build - -package dbus - -import ( - "os/user" -) - -func lookupHomeDir() string { - u, err := user.Current() - if err != nil { - return "/" - } - return u.HomeDir -} diff --git a/examples/vendor/github.com/godbus/dbus/v5/homedir_static.go b/examples/vendor/github.com/godbus/dbus/v5/homedir_static.go deleted file mode 100644 index b9d9cb5..0000000 --- a/examples/vendor/github.com/godbus/dbus/v5/homedir_static.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build static_build - -package dbus - -import ( - "bufio" - "os" - "strconv" - "strings" -) - -func lookupHomeDir() string { - myUid := os.Getuid() - - f, err := os.Open("/etc/passwd") - if err != nil { - return "/" - } - defer f.Close() - - s := bufio.NewScanner(f) - - for s.Scan() { - if err := s.Err(); err != nil { - break - } - - line := strings.TrimSpace(s.Text()) - if line == "" { - continue - } - - parts := strings.Split(line, ":") - - if len(parts) >= 6 { - uid, err := strconv.Atoi(parts[2]) - if err == nil && uid == myUid { - return parts[5] - } - } - } - - // Default to / if we can't get a better value - return "/" -} diff --git a/examples/vendor/github.com/hpcloud/tail/.gitignore b/examples/vendor/github.com/hpcloud/tail/.gitignore deleted file mode 100644 index 6d9953c..0000000 --- a/examples/vendor/github.com/hpcloud/tail/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.test -.go - diff --git a/examples/vendor/github.com/hpcloud/tail/.travis.yml b/examples/vendor/github.com/hpcloud/tail/.travis.yml deleted file mode 100644 index 9cf8bb7..0000000 --- a/examples/vendor/github.com/hpcloud/tail/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go - -script: - - go test -race -v ./... - -go: - - 1.4 - - 1.5 - - 1.6 - - tip - -matrix: - allow_failures: - - go: tip - -install: - - go get gopkg.in/fsnotify.v1 - - go get gopkg.in/tomb.v1 diff --git a/examples/vendor/github.com/hpcloud/tail/CHANGES.md b/examples/vendor/github.com/hpcloud/tail/CHANGES.md deleted file mode 100644 index 422790c..0000000 --- a/examples/vendor/github.com/hpcloud/tail/CHANGES.md +++ /dev/null @@ -1,63 +0,0 @@ -# API v1 (gopkg.in/hpcloud/tail.v1) - -## April, 2016 - -* Migrated to godep, as depman is not longer supported -* Introduced golang vendoring feature -* Fixed issue [#57](https://github.com/hpcloud/tail/issues/57) related to reopen deleted file - -## July, 2015 - -* Fix inotify watcher leak; remove `Cleanup` (#51) - -# API v0 (gopkg.in/hpcloud/tail.v0) - -## June, 2015 - -* Don't return partial lines (PR #40) -* Use stable version of fsnotify (#46) - -## July, 2014 - -* Fix tail for Windows (PR #36) - -## May, 2014 - -* Improved rate limiting using leaky bucket (PR #29) -* Fix odd line splitting (PR #30) - -## Apr, 2014 - -* LimitRate now discards read buffer (PR #28) -* allow reading of longer lines if MaxLineSize is unset (PR #24) -* updated deps.json to latest fsnotify (441bbc86b1) - -## Feb, 2014 - -* added `Config.Logger` to suppress library logging - -## Nov, 2013 - -* add Cleanup to remove leaky inotify watches (PR #20) - -## Aug, 2013 - -* redesigned Location field (PR #12) -* add tail.Tell (PR #14) - -## July, 2013 - -* Rate limiting (PR #10) - -## May, 2013 - -* Detect file deletions/renames in polling file watcher (PR #1) -* Detect file truncation -* Fix potential race condition when reopening the file (issue 5) -* Fix potential blocking of `tail.Stop` (issue 4) -* Fix uncleaned up ChangeEvents goroutines after calling tail.Stop -* Support Follow=false - -## Feb, 2013 - -* Initial open source release diff --git a/examples/vendor/github.com/hpcloud/tail/Dockerfile b/examples/vendor/github.com/hpcloud/tail/Dockerfile deleted file mode 100644 index cd297b9..0000000 --- a/examples/vendor/github.com/hpcloud/tail/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM golang - -RUN mkdir -p $GOPATH/src/github.com/hpcloud/tail/ -ADD . $GOPATH/src/github.com/hpcloud/tail/ - -# expecting to fetch dependencies successfully. -RUN go get -v github.com/hpcloud/tail - -# expecting to run the test successfully. -RUN go test -v github.com/hpcloud/tail - -# expecting to install successfully -RUN go install -v github.com/hpcloud/tail -RUN go install -v github.com/hpcloud/tail/cmd/gotail - -RUN $GOPATH/bin/gotail -h || true - -ENV PATH $GOPATH/bin:$PATH -CMD ["gotail"] diff --git a/examples/vendor/github.com/hpcloud/tail/Makefile b/examples/vendor/github.com/hpcloud/tail/Makefile deleted file mode 100644 index 6591b24..0000000 --- a/examples/vendor/github.com/hpcloud/tail/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -default: test - -test: *.go - go test -v -race ./... - -fmt: - gofmt -w . - -# Run the test in an isolated environment. -fulltest: - docker build -t hpcloud/tail . diff --git a/examples/vendor/github.com/hpcloud/tail/README.md b/examples/vendor/github.com/hpcloud/tail/README.md deleted file mode 100644 index fb7fbc2..0000000 --- a/examples/vendor/github.com/hpcloud/tail/README.md +++ /dev/null @@ -1,28 +0,0 @@ -[![Build Status](https://travis-ci.org/hpcloud/tail.svg)](https://travis-ci.org/hpcloud/tail) -[![Build status](https://ci.appveyor.com/api/projects/status/kohpsf3rvhjhrox6?svg=true)](https://ci.appveyor.com/project/HelionCloudFoundry/tail) - -# Go package for tail-ing files - -A Go package striving to emulate the features of the BSD `tail` program. - -```Go -t, err := tail.TailFile("/var/log/nginx.log", tail.Config{Follow: true}) -for line := range t.Lines { - fmt.Println(line.Text) -} -``` - -See [API documentation](http://godoc.org/github.com/hpcloud/tail). - -## Log rotation - -Tail comes with full support for truncation/move detection as it is -designed to work with log rotation tools. - -## Installing - - go get github.com/hpcloud/tail/... - -## Windows support - -This package [needs assistance](https://github.com/hpcloud/tail/labels/Windows) for full Windows support. diff --git a/examples/vendor/github.com/hpcloud/tail/appveyor.yml b/examples/vendor/github.com/hpcloud/tail/appveyor.yml deleted file mode 100644 index d370055..0000000 --- a/examples/vendor/github.com/hpcloud/tail/appveyor.yml +++ /dev/null @@ -1,11 +0,0 @@ -version: 0.{build} -skip_tags: true -cache: C:\Users\appveyor\AppData\Local\NuGet\Cache -build_script: -- SET GOPATH=c:\workspace -- go test -v -race ./... -test: off -clone_folder: c:\workspace\src\github.com\hpcloud\tail -branches: - only: - - master diff --git a/examples/vendor/github.com/hpcloud/tail/tail_posix.go b/examples/vendor/github.com/hpcloud/tail/tail_posix.go deleted file mode 100644 index bc4dc33..0000000 --- a/examples/vendor/github.com/hpcloud/tail/tail_posix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux darwin freebsd netbsd openbsd - -package tail - -import ( - "os" -) - -func OpenFile(name string) (file *os.File, err error) { - return os.Open(name) -} diff --git a/examples/vendor/github.com/hpcloud/tail/tail_windows.go b/examples/vendor/github.com/hpcloud/tail/tail_windows.go deleted file mode 100644 index ef2cfca..0000000 --- a/examples/vendor/github.com/hpcloud/tail/tail_windows.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build windows - -package tail - -import ( - "github.com/hpcloud/tail/winfile" - "os" -) - -func OpenFile(name string) (file *os.File, err error) { - return winfile.OpenFile(name, os.O_RDONLY, 0) -} diff --git a/examples/vendor/github.com/inconshreveable/mousetrap/LICENSE b/examples/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f0d1fb..0000000 --- a/examples/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2014 Alan Shreve - -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/examples/vendor/github.com/inconshreveable/mousetrap/README.md b/examples/vendor/github.com/inconshreveable/mousetrap/README.md deleted file mode 100644 index 7a950d1..0000000 --- a/examples/vendor/github.com/inconshreveable/mousetrap/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# mousetrap - -mousetrap is a tiny library that answers a single question. - -On a Windows machine, was the process invoked by someone double clicking on -the executable file while browsing in explorer? - -### Motivation - -Windows developers unfamiliar with command line tools will often "double-click" -the executable for a tool. Because most CLI tools print the help and then exit -when invoked without arguments, this is often very frustrating for those users. - -mousetrap provides a way to detect these invocations so that you can provide -more helpful behavior and instructions on how to run the CLI tool. To see what -this looks like, both from an organizational and a technical perspective, see -https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ - -### The interface - -The library exposes a single interface: - - func StartedByExplorer() (bool) diff --git a/examples/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/examples/vendor/github.com/inconshreveable/mousetrap/trap_others.go deleted file mode 100644 index 9d2d8a4..0000000 --- a/examples/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !windows - -package mousetrap - -// StartedByExplorer returns true if the program was invoked by the user -// double-clicking on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -// -// On non-Windows platforms, it always returns false. -func StartedByExplorer() bool { - return false -} diff --git a/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows.go deleted file mode 100644 index 336142a..0000000 --- a/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows -// +build !go1.4 - -package mousetrap - -import ( - "fmt" - "os" - "syscall" - "unsafe" -) - -const ( - // defined by the Win32 API - th32cs_snapprocess uintptr = 0x2 -) - -var ( - kernel = syscall.MustLoadDLL("kernel32.dll") - CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot") - Process32First = kernel.MustFindProc("Process32FirstW") - Process32Next = kernel.MustFindProc("Process32NextW") -) - -// ProcessEntry32 structure defined by the Win32 API -type processEntry32 struct { - dwSize uint32 - cntUsage uint32 - th32ProcessID uint32 - th32DefaultHeapID int - th32ModuleID uint32 - cntThreads uint32 - th32ParentProcessID uint32 - pcPriClassBase int32 - dwFlags uint32 - szExeFile [syscall.MAX_PATH]uint16 -} - -func getProcessEntry(pid int) (pe *processEntry32, err error) { - snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0)) - if snapshot == uintptr(syscall.InvalidHandle) { - err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1) - return - } - defer syscall.CloseHandle(syscall.Handle(snapshot)) - - var processEntry processEntry32 - processEntry.dwSize = uint32(unsafe.Sizeof(processEntry)) - ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32First: %v", e1) - return - } - - for { - if processEntry.th32ProcessID == uint32(pid) { - pe = &processEntry - return - } - - ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry))) - if ok == 0 { - err = fmt.Errorf("Process32Next: %v", e1) - return - } - } -} - -func getppid() (pid int, err error) { - pe, err := getProcessEntry(os.Getpid()) - if err != nil { - return - } - - pid = int(pe.th32ParentProcessID) - return -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - ppid, err := getppid() - if err != nil { - return false - } - - pe, err := getProcessEntry(ppid) - if err != nil { - return false - } - - name := syscall.UTF16ToString(pe.szExeFile[:]) - return name == "explorer.exe" -} diff --git a/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go deleted file mode 100644 index 9a28e57..0000000 --- a/examples/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ /dev/null @@ -1,46 +0,0 @@ -// +build windows -// +build go1.4 - -package mousetrap - -import ( - "os" - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(os.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/examples/vendor/github.com/klauspost/compress/zstd/decoder.go b/examples/vendor/github.com/klauspost/compress/zstd/decoder.go deleted file mode 100644 index f430f58..0000000 --- a/examples/vendor/github.com/klauspost/compress/zstd/decoder.go +++ /dev/null @@ -1,555 +0,0 @@ -// Copyright 2019+ Klaus Post. All rights reserved. -// License information can be found in the LICENSE file. -// Based on work by Yann Collet, released under BSD License. - -package zstd - -import ( - "errors" - "io" - "sync" -) - -// Decoder provides decoding of zstandard streams. -// The decoder has been designed to operate without allocations after a warmup. -// This means that you should store the decoder for best performance. -// To re-use a stream decoder, use the Reset(r io.Reader) error to switch to another stream. -// A decoder can safely be re-used even if the previous stream failed. -// To release the resources, you must call the Close() function on a decoder. -type Decoder struct { - o decoderOptions - - // Unreferenced decoders, ready for use. - decoders chan *blockDec - - // Streams ready to be decoded. - stream chan decodeStream - - // Current read position used for Reader functionality. - current decoderState - - // Custom dictionaries. - // Always uses copies. - dicts map[uint32]dict - - // streamWg is the waitgroup for all streams - streamWg sync.WaitGroup -} - -// decoderState is used for maintaining state when the decoder -// is used for streaming. -type decoderState struct { - // current block being written to stream. - decodeOutput - - // output in order to be written to stream. - output chan decodeOutput - - // cancel remaining output. - cancel chan struct{} - - flushed bool -} - -var ( - // Check the interfaces we want to support. - _ = io.WriterTo(&Decoder{}) - _ = io.Reader(&Decoder{}) -) - -// NewReader creates a new decoder. -// A nil Reader can be provided in which case Reset can be used to start a decode. -// -// A Decoder can be used in two modes: -// -// 1) As a stream, or -// 2) For stateless decoding using DecodeAll. -// -// Only a single stream can be decoded concurrently, but the same decoder -// can run multiple concurrent stateless decodes. It is even possible to -// use stateless decodes while a stream is being decoded. -// -// The Reset function can be used to initiate a new stream, which is will considerably -// reduce the allocations normally caused by NewReader. -func NewReader(r io.Reader, opts ...DOption) (*Decoder, error) { - initPredefined() - var d Decoder - d.o.setDefault() - for _, o := range opts { - err := o(&d.o) - if err != nil { - return nil, err - } - } - d.current.output = make(chan decodeOutput, d.o.concurrent) - d.current.flushed = true - - if r == nil { - d.current.err = ErrDecoderNilInput - } - - // Transfer option dicts. - d.dicts = make(map[uint32]dict, len(d.o.dicts)) - for _, dc := range d.o.dicts { - d.dicts[dc.id] = dc - } - d.o.dicts = nil - - // Create decoders - d.decoders = make(chan *blockDec, d.o.concurrent) - for i := 0; i < d.o.concurrent; i++ { - dec := newBlockDec(d.o.lowMem) - dec.localFrame = newFrameDec(d.o) - d.decoders <- dec - } - - if r == nil { - return &d, nil - } - return &d, d.Reset(r) -} - -// Read bytes from the decompressed stream into p. -// Returns the number of bytes written and any error that occurred. -// When the stream is done, io.EOF will be returned. -func (d *Decoder) Read(p []byte) (int, error) { - var n int - for { - if len(d.current.b) > 0 { - filled := copy(p, d.current.b) - p = p[filled:] - d.current.b = d.current.b[filled:] - n += filled - } - if len(p) == 0 { - break - } - if len(d.current.b) == 0 { - // We have an error and no more data - if d.current.err != nil { - break - } - if !d.nextBlock(n == 0) { - return n, nil - } - } - } - if len(d.current.b) > 0 { - if debugDecoder { - println("returning", n, "still bytes left:", len(d.current.b)) - } - // Only return error at end of block - return n, nil - } - if d.current.err != nil { - d.drainOutput() - } - if debugDecoder { - println("returning", n, d.current.err, len(d.decoders)) - } - return n, d.current.err -} - -// Reset will reset the decoder the supplied stream after the current has finished processing. -// Note that this functionality cannot be used after Close has been called. -// Reset can be called with a nil reader to release references to the previous reader. -// After being called with a nil reader, no other operations than Reset or DecodeAll or Close -// should be used. -func (d *Decoder) Reset(r io.Reader) error { - if d.current.err == ErrDecoderClosed { - return d.current.err - } - - d.drainOutput() - - if r == nil { - d.current.err = ErrDecoderNilInput - if len(d.current.b) > 0 { - d.current.b = d.current.b[:0] - } - d.current.flushed = true - return nil - } - - // If bytes buffer and < 5MB, do sync decoding anyway. - if bb, ok := r.(byter); ok && bb.Len() < 5<<20 { - bb2 := bb - if debugDecoder { - println("*bytes.Buffer detected, doing sync decode, len:", bb.Len()) - } - b := bb2.Bytes() - var dst []byte - if cap(d.current.b) > 0 { - dst = d.current.b - } - - dst, err := d.DecodeAll(b, dst[:0]) - if err == nil { - err = io.EOF - } - d.current.b = dst - d.current.err = err - d.current.flushed = true - if debugDecoder { - println("sync decode to", len(dst), "bytes, err:", err) - } - return nil - } - - if d.stream == nil { - d.stream = make(chan decodeStream, 1) - d.streamWg.Add(1) - go d.startStreamDecoder(d.stream) - } - - // Remove current block. - d.current.decodeOutput = decodeOutput{} - d.current.err = nil - d.current.cancel = make(chan struct{}) - d.current.flushed = false - d.current.d = nil - - d.stream <- decodeStream{ - r: r, - output: d.current.output, - cancel: d.current.cancel, - } - return nil -} - -// drainOutput will drain the output until errEndOfStream is sent. -func (d *Decoder) drainOutput() { - if d.current.cancel != nil { - println("cancelling current") - close(d.current.cancel) - d.current.cancel = nil - } - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p, decoders: %d", d.current.d, len(d.decoders)) - } - d.decoders <- d.current.d - d.current.d = nil - d.current.b = nil - } - if d.current.output == nil || d.current.flushed { - println("current already flushed") - return - } - for v := range d.current.output { - if v.d != nil { - if debugDecoder { - printf("re-adding decoder %p", v.d) - } - d.decoders <- v.d - } - if v.err == errEndOfStream { - println("current flushed") - d.current.flushed = true - return - } - } -} - -// WriteTo writes data to w until there's no more data to write or when an error occurs. -// The return value n is the number of bytes written. -// Any error encountered during the write is also returned. -func (d *Decoder) WriteTo(w io.Writer) (int64, error) { - var n int64 - for { - if len(d.current.b) > 0 { - n2, err2 := w.Write(d.current.b) - n += int64(n2) - if err2 != nil && (d.current.err == nil || d.current.err == io.EOF) { - d.current.err = err2 - } else if n2 != len(d.current.b) { - d.current.err = io.ErrShortWrite - } - } - if d.current.err != nil { - break - } - d.nextBlock(true) - } - err := d.current.err - if err != nil { - d.drainOutput() - } - if err == io.EOF { - err = nil - } - return n, err -} - -// DecodeAll allows stateless decoding of a blob of bytes. -// Output will be appended to dst, so if the destination size is known -// you can pre-allocate the destination slice to avoid allocations. -// DecodeAll can be used concurrently. -// The Decoder concurrency limits will be respected. -func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { - if d.current.err == ErrDecoderClosed { - return dst, ErrDecoderClosed - } - - // Grab a block decoder and frame decoder. - block := <-d.decoders - frame := block.localFrame - defer func() { - if debugDecoder { - printf("re-adding decoder: %p", block) - } - frame.rawInput = nil - frame.bBuf = nil - d.decoders <- block - }() - frame.bBuf = input - - for { - frame.history.reset() - err := frame.reset(&frame.bBuf) - if err == io.EOF { - if debugDecoder { - println("frame reset return EOF") - } - return dst, nil - } - if frame.DictionaryID != nil { - dict, ok := d.dicts[*frame.DictionaryID] - if !ok { - return nil, ErrUnknownDictionary - } - frame.history.setDict(&dict) - } - if err != nil { - return dst, err - } - if frame.FrameContentSize > d.o.maxDecodedSize-uint64(len(dst)) { - return dst, ErrDecoderSizeExceeded - } - if frame.FrameContentSize > 0 && frame.FrameContentSize < 1<<30 { - // Never preallocate moe than 1 GB up front. - if cap(dst)-len(dst) < int(frame.FrameContentSize) { - dst2 := make([]byte, len(dst), len(dst)+int(frame.FrameContentSize)) - copy(dst2, dst) - dst = dst2 - } - } - if cap(dst) == 0 { - // Allocate len(input) * 2 by default if nothing is provided - // and we didn't get frame content size. - size := len(input) * 2 - // Cap to 1 MB. - if size > 1<<20 { - size = 1 << 20 - } - if uint64(size) > d.o.maxDecodedSize { - size = int(d.o.maxDecodedSize) - } - dst = make([]byte, 0, size) - } - - dst, err = frame.runDecoder(dst, block) - if err != nil { - return dst, err - } - if len(frame.bBuf) == 0 { - if debugDecoder { - println("frame dbuf empty") - } - break - } - } - return dst, nil -} - -// nextBlock returns the next block. -// If an error occurs d.err will be set. -// Optionally the function can block for new output. -// If non-blocking mode is used the returned boolean will be false -// if no data was available without blocking. -func (d *Decoder) nextBlock(blocking bool) (ok bool) { - if d.current.d != nil { - if debugDecoder { - printf("re-adding current decoder %p", d.current.d) - } - d.decoders <- d.current.d - d.current.d = nil - } - if d.current.err != nil { - // Keep error state. - return blocking - } - - if blocking { - d.current.decodeOutput = <-d.current.output - } else { - select { - case d.current.decodeOutput = <-d.current.output: - default: - return false - } - } - if debugDecoder { - println("got", len(d.current.b), "bytes, error:", d.current.err) - } - return true -} - -// Close will release all resources. -// It is NOT possible to reuse the decoder after this. -func (d *Decoder) Close() { - if d.current.err == ErrDecoderClosed { - return - } - d.drainOutput() - if d.stream != nil { - close(d.stream) - d.streamWg.Wait() - d.stream = nil - } - if d.decoders != nil { - close(d.decoders) - for dec := range d.decoders { - dec.Close() - } - d.decoders = nil - } - if d.current.d != nil { - d.current.d.Close() - d.current.d = nil - } - d.current.err = ErrDecoderClosed -} - -// IOReadCloser returns the decoder as an io.ReadCloser for convenience. -// Any changes to the decoder will be reflected, so the returned ReadCloser -// can be reused along with the decoder. -// io.WriterTo is also supported by the returned ReadCloser. -func (d *Decoder) IOReadCloser() io.ReadCloser { - return closeWrapper{d: d} -} - -// closeWrapper wraps a function call as a closer. -type closeWrapper struct { - d *Decoder -} - -// WriteTo forwards WriteTo calls to the decoder. -func (c closeWrapper) WriteTo(w io.Writer) (n int64, err error) { - return c.d.WriteTo(w) -} - -// Read forwards read calls to the decoder. -func (c closeWrapper) Read(p []byte) (n int, err error) { - return c.d.Read(p) -} - -// Close closes the decoder. -func (c closeWrapper) Close() error { - c.d.Close() - return nil -} - -type decodeOutput struct { - d *blockDec - b []byte - err error -} - -type decodeStream struct { - r io.Reader - - // Blocks ready to be written to output. - output chan decodeOutput - - // cancel reading from the input - cancel chan struct{} -} - -// errEndOfStream indicates that everything from the stream was read. -var errEndOfStream = errors.New("end-of-stream") - -// Create Decoder: -// Spawn n block decoders. These accept tasks to decode a block. -// Create goroutine that handles stream processing, this will send history to decoders as they are available. -// Decoders update the history as they decode. -// When a block is returned: -// a) history is sent to the next decoder, -// b) content written to CRC. -// c) return data to WRITER. -// d) wait for next block to return data. -// Once WRITTEN, the decoders reused by the writer frame decoder for re-use. -func (d *Decoder) startStreamDecoder(inStream chan decodeStream) { - defer d.streamWg.Done() - frame := newFrameDec(d.o) - for stream := range inStream { - if debugDecoder { - println("got new stream") - } - br := readerWrapper{r: stream.r} - decodeStream: - for { - frame.history.reset() - err := frame.reset(&br) - if debugDecoder && err != nil { - println("Frame decoder returned", err) - } - if err == nil && frame.DictionaryID != nil { - dict, ok := d.dicts[*frame.DictionaryID] - if !ok { - err = ErrUnknownDictionary - } else { - frame.history.setDict(&dict) - } - } - if err != nil { - stream.output <- decodeOutput{ - err: err, - } - break - } - if debugDecoder { - println("starting frame decoder") - } - - // This goroutine will forward history between frames. - frame.frameDone.Add(1) - frame.initAsync() - - go frame.startDecoder(stream.output) - decodeFrame: - // Go through all blocks of the frame. - for { - dec := <-d.decoders - select { - case <-stream.cancel: - if !frame.sendErr(dec, io.EOF) { - // To not let the decoder dangle, send it back. - stream.output <- decodeOutput{d: dec} - } - break decodeStream - default: - } - err := frame.next(dec) - switch err { - case io.EOF: - // End of current frame, no error - println("EOF on next block") - break decodeFrame - case nil: - continue - default: - println("block decoder returned", err) - break decodeStream - } - } - // All blocks have started decoding, check if there are more frames. - println("waiting for done") - frame.frameDone.Wait() - println("done waiting...") - } - frame.frameDone.Wait() - println("Sending EOS") - stream.output <- decodeOutput{err: errEndOfStream} - } -} diff --git a/examples/vendor/github.com/miekg/pkcs11/.travis.yml b/examples/vendor/github.com/miekg/pkcs11/.travis.yml deleted file mode 100644 index 687044d..0000000 --- a/examples/vendor/github.com/miekg/pkcs11/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -sudo: required -dist: trusty - -go: - - 1.9 - - tip - -script: - - go test -v ./... - -before_script: - - sudo apt-get update - - sudo apt-get -y install libsofthsm diff --git a/examples/vendor/github.com/moby/sys/mountinfo/mounted_linux.go b/examples/vendor/github.com/moby/sys/mountinfo/mounted_linux.go deleted file mode 100644 index bc9f6b2..0000000 --- a/examples/vendor/github.com/moby/sys/mountinfo/mounted_linux.go +++ /dev/null @@ -1,58 +0,0 @@ -package mountinfo - -import ( - "os" - "path/filepath" - - "golang.org/x/sys/unix" -) - -// mountedByOpenat2 is a method of detecting a mount that works for all kinds -// of mounts (incl. bind mounts), but requires a recent (v5.6+) linux kernel. -func mountedByOpenat2(path string) (bool, error) { - dir, last := filepath.Split(path) - - dirfd, err := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{ - Flags: unix.O_PATH | unix.O_CLOEXEC, - }) - if err != nil { - if err == unix.ENOENT { // not a mount - return false, nil - } - return false, &os.PathError{Op: "openat2", Path: dir, Err: err} - } - fd, err := unix.Openat2(dirfd, last, &unix.OpenHow{ - Flags: unix.O_PATH | unix.O_CLOEXEC | unix.O_NOFOLLOW, - Resolve: unix.RESOLVE_NO_XDEV, - }) - _ = unix.Close(dirfd) - switch err { - case nil: // definitely not a mount - _ = unix.Close(fd) - return false, nil - case unix.EXDEV: // definitely a mount - return true, nil - case unix.ENOENT: // not a mount - return false, nil - } - // not sure - return false, &os.PathError{Op: "openat2", Path: path, Err: err} -} - -func mounted(path string) (bool, error) { - // Try a fast path, using openat2() with RESOLVE_NO_XDEV. - mounted, err := mountedByOpenat2(path) - if err == nil { - return mounted, nil - } - // Another fast path: compare st.st_dev fields. - mounted, err = mountedByStat(path) - // This does not work for bind mounts, so false negative - // is possible, therefore only trust if return is true. - if mounted && err == nil { - return mounted, nil - } - - // Fallback to parsing mountinfo - return mountedByMountinfo(path) -} diff --git a/examples/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go b/examples/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go deleted file mode 100644 index eade571..0000000 --- a/examples/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go +++ /dev/null @@ -1,12 +0,0 @@ -package seccomp - -const ( - seccompOverwrite = "overwrite" - seccompAppend = "append" - nothing = "nothing" - kill = "kill" - trap = "trap" - trace = "trace" - allow = "allow" - errno = "errno" -) diff --git a/examples/vendor/github.com/spf13/cobra/.gitignore b/examples/vendor/github.com/spf13/cobra/.gitignore deleted file mode 100644 index c7b459e..0000000 --- a/examples/vendor/github.com/spf13/cobra/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - -*.exe -cobra.test -bin - -.idea/ -*.iml diff --git a/examples/vendor/github.com/spf13/cobra/.golangci.yml b/examples/vendor/github.com/spf13/cobra/.golangci.yml deleted file mode 100644 index 0d6e617..0000000 --- a/examples/vendor/github.com/spf13/cobra/.golangci.yml +++ /dev/null @@ -1,48 +0,0 @@ -run: - deadline: 5m - -linters: - disable-all: true - enable: - #- bodyclose - - deadcode - #- depguard - #- dogsled - #- dupl - - errcheck - #- exhaustive - #- funlen - - gas - #- gochecknoinits - - goconst - #- gocritic - #- gocyclo - #- gofmt - - goimports - - golint - #- gomnd - #- goprintffuncname - #- gosec - #- gosimple - - govet - - ineffassign - - interfacer - #- lll - - maligned - - megacheck - #- misspell - #- nakedret - #- noctx - #- nolintlint - #- rowserrcheck - #- scopelint - #- staticcheck - - structcheck - #- stylecheck - #- typecheck - - unconvert - #- unparam - #- unused - - varcheck - #- whitespace - fast: false diff --git a/examples/vendor/github.com/spf13/cobra/.mailmap b/examples/vendor/github.com/spf13/cobra/.mailmap deleted file mode 100644 index 94ec530..0000000 --- a/examples/vendor/github.com/spf13/cobra/.mailmap +++ /dev/null @@ -1,3 +0,0 @@ -Steve Francia -Bjørn Erik Pedersen -Fabiano Franz diff --git a/examples/vendor/github.com/spf13/cobra/CHANGELOG.md b/examples/vendor/github.com/spf13/cobra/CHANGELOG.md deleted file mode 100644 index 8a23b4f..0000000 --- a/examples/vendor/github.com/spf13/cobra/CHANGELOG.md +++ /dev/null @@ -1,51 +0,0 @@ -# Cobra Changelog - -## v1.1.3 - -* **Fix:** release-branch.cobra1.1 only: Revert "Deprecate Go < 1.14" to maintain backward compatibility - -## v1.1.2 - -### Notable Changes - -* Bump license year to 2021 in golden files (#1309) @Bowbaq -* Enhance PowerShell completion with custom comp (#1208) @Luap99 -* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670 -* Documentation readability improvements (#1228 etc.) @zaataylor etc. -* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor - -## v1.1.1 - -* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context. -* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context. - -## v1.1.0 - -### Notable Changes - -* Extend Go completions and revamp zsh comp (#1070) -* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb -* Add completion for help command (#1136) -* Complete subcommands when TraverseChildren is set (#1171) -* Fix stderr printing functions (#894) -* fix: fish output redirection (#1247) - -## v1.0.0 - -Announcing v1.0.0 of Cobra. 🎉 - -### Notable Changes -* Fish completion (including support for Go custom completion) @marckhouzam -* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam -* Remove/replace SetOutput on Command - deprecated @jpmcb -* add support for autolabel stale PR @xchapter7x -* Add Labeler Actions @xchapter7x -* Custom completions coded in Go (instead of Bash) @marckhouzam -* Partial Revert of #922 @jharshman -* Add Makefile to project @jharshman -* Correct documentation for InOrStdin @desponda -* Apply formatting to templates @jharshman -* Revert change so help is printed on stdout again @marckhouzam -* Update md2man to v2.0.0 @pdf -* update viper to v1.4.0 @umarcor -* Update cmd/root.go example in README.md @jharshman diff --git a/examples/vendor/github.com/spf13/cobra/CONDUCT.md b/examples/vendor/github.com/spf13/cobra/CONDUCT.md deleted file mode 100644 index 9d16f88..0000000 --- a/examples/vendor/github.com/spf13/cobra/CONDUCT.md +++ /dev/null @@ -1,37 +0,0 @@ -## Cobra User Contract - -### Versioning -Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release. - -### Backward Compatibility -We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released. - -### Deprecation -Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github. - -### CVE -Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one. - -### Communication -Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors. - -### Breaking Changes -Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra. - -There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version. - -Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release. - -Examples of breaking changes include: -- Removing or renaming exported constant, variable, type, or function. -- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc... - - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing. - -There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging. - -### CI Testing -Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang. - -### Disclaimer -Changes to this document and the contents therein are at the discretion of the maintainers. -None of the contents of this document are legally binding in any way to the maintainers or the users. diff --git a/examples/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/examples/vendor/github.com/spf13/cobra/CONTRIBUTING.md deleted file mode 100644 index 6f356e6..0000000 --- a/examples/vendor/github.com/spf13/cobra/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# Contributing to Cobra - -Thank you so much for contributing to Cobra. We appreciate your time and help. -Here are some guidelines to help you get started. - -## Code of Conduct - -Be kind and respectful to the members of the community. Take time to educate -others who are seeking help. Harassment of any kind will not be tolerated. - -## Questions - -If you have questions regarding Cobra, feel free to ask it in the community -[#cobra Slack channel][cobra-slack] - -## Filing a bug or feature - -1. Before filing an issue, please check the existing issues to see if a - similar one was already opened. If there is one already opened, feel free - to comment on it. -1. If you believe you've found a bug, please provide detailed steps of - reproduction, the version of Cobra and anything else you believe will be - useful to help troubleshoot it (e.g. OS environment, environment variables, - etc...). Also state the current behavior vs. the expected behavior. -1. If you'd like to see a feature or an enhancement please open an issue with - a clear title and description of what the feature is and why it would be - beneficial to the project and its users. - -## Submitting changes - -1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to - sign a CLA. Please sign the CLA :slightly_smiling_face: -1. Tests: If you are submitting code, please ensure you have adequate tests - for the feature. Tests can be run via `go test ./...` or `make test`. -1. Since this is golang project, ensure the new code is properly formatted to - ensure code consistency. Run `make all`. - -### Quick steps to contribute - -1. Fork the project. -1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) -1. Create your feature branch (`git checkout -b my-new-feature`) -1. Make changes and run tests (`make test`) -1. Add them to staging (`git add .`) -1. Commit your changes (`git commit -m 'Add some feature'`) -1. Push to the branch (`git push origin my-new-feature`) -1. Create new pull request - - -[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199 diff --git a/examples/vendor/github.com/spf13/cobra/LICENSE.txt b/examples/vendor/github.com/spf13/cobra/LICENSE.txt deleted file mode 100644 index 298f0e2..0000000 --- a/examples/vendor/github.com/spf13/cobra/LICENSE.txt +++ /dev/null @@ -1,174 +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. diff --git a/examples/vendor/github.com/spf13/cobra/Makefile b/examples/vendor/github.com/spf13/cobra/Makefile deleted file mode 100644 index 472c73b..0000000 --- a/examples/vendor/github.com/spf13/cobra/Makefile +++ /dev/null @@ -1,40 +0,0 @@ -BIN="./bin" -SRC=$(shell find . -name "*.go") - -ifeq (, $(shell which golangci-lint)) -$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") -endif - -ifeq (, $(shell which richgo)) -$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo") -endif - -.PHONY: fmt lint test cobra_generator install_deps clean - -default: all - -all: fmt test cobra_generator - -fmt: - $(info ******************** checking formatting ********************) - @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) - -lint: - $(info ******************** running lint tools ********************) - golangci-lint run -v - -test: install_deps lint - $(info ******************** running tests ********************) - richgo test -v ./... - -cobra_generator: install_deps - $(info ******************** building generator ********************) - mkdir -p $(BIN) - make -C cobra all - -install_deps: - $(info ******************** downloading dependencies ********************) - go get -v ./... - -clean: - rm -rf $(BIN) diff --git a/examples/vendor/github.com/spf13/cobra/README.md b/examples/vendor/github.com/spf13/cobra/README.md deleted file mode 100644 index 074e397..0000000 --- a/examples/vendor/github.com/spf13/cobra/README.md +++ /dev/null @@ -1,125 +0,0 @@ -![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png) - -Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files. - -Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/), -[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to -name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra. - -[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) -[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) -[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) - -# Table of Contents - -- [Overview](#overview) -- [Concepts](#concepts) - * [Commands](#commands) - * [Flags](#flags) -- [Installing](#installing) -- [Usage](#usage) - * [Using the Cobra Generator](user_guide.md#using-the-cobra-generator) - * [Using the Cobra Library](user_guide.md#using-the-cobra-library) - * [Working with Flags](user_guide.md#working-with-flags) - * [Positional and Custom Arguments](user_guide.md#positional-and-custom-arguments) - * [Example](user_guide.md#example) - * [Help Command](user_guide.md#help-command) - * [Usage Message](user_guide.md#usage-message) - * [PreRun and PostRun Hooks](user_guide.md#prerun-and-postrun-hooks) - * [Suggestions when "unknown command" happens](user_guide.md#suggestions-when-unknown-command-happens) - * [Generating documentation for your command](user_guide.md#generating-documentation-for-your-command) - * [Generating shell completions](user_guide.md#generating-shell-completions) -- [Contributing](CONTRIBUTING.md) -- [License](#license) - -# Overview - -Cobra is a library providing a simple interface to create powerful modern CLI -interfaces similar to git & go tools. - -Cobra is also an application that will generate your application scaffolding to rapidly -develop a Cobra-based application. - -Cobra provides: -* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. -* Fully POSIX-compliant flags (including short & long versions) -* Nested subcommands -* Global, local and cascading flags -* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname` -* Intelligent suggestions (`app srver`... did you mean `app server`?) -* Automatic help generation for commands and flags -* Automatic help flag recognition of `-h`, `--help`, etc. -* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) -* Automatically generated man pages for your application -* Command aliases so you can change things without breaking them -* The flexibility to define your own help, usage, etc. -* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps - -# Concepts - -Cobra is built on a structure of commands, arguments & flags. - -**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. - -The best applications read like sentences when used, and as a result, users -intuitively know how to interact with them. - -The pattern to follow is -`APPNAME VERB NOUN --ADJECTIVE.` - or -`APPNAME COMMAND ARG --FLAG` - -A few good real world examples may better illustrate this point. - -In the following example, 'server' is a command, and 'port' is a flag: - - hugo server --port=1313 - -In this command we are telling Git to clone the url bare. - - git clone URL --bare - -## Commands - -Command is the central point of the application. Each interaction that -the application supports will be contained in a Command. A command can -have children commands and optionally run an action. - -In the example above, 'server' is the command. - -[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command) - -## Flags - -A flag is a way to modify the behavior of a command. Cobra supports -fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). -A Cobra command can define flags that persist through to children commands -and flags that are only available to that command. - -In the example above, 'port' is the flag. - -Flag functionality is provided by the [pflag -library](https://github.com/spf13/pflag), a fork of the flag standard library -which maintains the same interface while adding POSIX compliance. - -# Installing -Using Cobra is easy. First, use `go get` to install the latest version -of the library. This command will install the `cobra` generator executable -along with the library and its dependencies: - - go get -u github.com/spf13/cobra - -Next, include Cobra in your application: - -```go -import "github.com/spf13/cobra" -``` - -# Usage - -See [User Guide](user_guide.md). - -# License - -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) diff --git a/examples/vendor/github.com/spf13/cobra/args.go b/examples/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index 70e9b26..0000000 --- a/examples/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,109 +0,0 @@ -package cobra - -import ( - "fmt" - "strings" -) - -type PositionalArgs func(cmd *Command, args []string) error - -// Legacy arg validation has the following behaviour: -// - root commands with no subcommands can take arbitrary arguments -// - root commands with subcommands will do subcommand validity checking -// - subcommands will always accept arbitrary arguments -func legacyArgs(cmd *Command, args []string) error { - // no subcommand, always take args - if !cmd.HasSubCommands() { - return nil - } - - // root command with subcommands, do subcommand checking. - if !cmd.HasParent() && len(args) > 0 { - return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - return nil -} - -// NoArgs returns an error if any args are included. -func NoArgs(cmd *Command, args []string) error { - if len(args) > 0 { - return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) - } - return nil -} - -// OnlyValidArgs returns an error if any args are not in the list of ValidArgs. -func OnlyValidArgs(cmd *Command, args []string) error { - if len(cmd.ValidArgs) > 0 { - // Remove any description that may be included in ValidArgs. - // A description is following a tab character. - var validArgs []string - for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.Split(v, "\t")[0]) - } - - for _, v := range args { - if !stringInSlice(v, validArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - } - } - return nil -} - -// ArbitraryArgs never returns an error. -func ArbitraryArgs(cmd *Command, args []string) error { - return nil -} - -// MinimumNArgs returns an error if there is not at least N args. -func MinimumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < n { - return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) - } - return nil - } -} - -// MaximumNArgs returns an error if there are more than N args. -func MaximumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) > n { - return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactArgs returns an error if there are not exactly n args. -func ExactArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) != n { - return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactValidArgs returns an error if -// there are not exactly N positional args OR -// there are any positional args that are not in the `ValidArgs` field of `Command` -func ExactValidArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if err := ExactArgs(n)(cmd, args); err != nil { - return err - } - return OnlyValidArgs(cmd, args) - } -} - -// RangeArgs returns an error if the number of args is not within the expected range. -func RangeArgs(min int, max int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < min || len(args) > max { - return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) - } - return nil - } -} diff --git a/examples/vendor/github.com/spf13/cobra/bash_completions.go b/examples/vendor/github.com/spf13/cobra/bash_completions.go deleted file mode 100644 index 733f4d1..0000000 --- a/examples/vendor/github.com/spf13/cobra/bash_completions.go +++ /dev/null @@ -1,685 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "sort" - "strings" - - "github.com/spf13/pflag" -) - -// Annotations for Bash completion. -const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" - BashCompCustom = "cobra_annotation_bash_completion_custom" - BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" - BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" -) - -func writePreamble(buf io.StringWriter, name string) { - WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__%[1]s_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 -} - -__%[1]s_contains_word() -{ - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 -} - -__%[1]s_handle_go_custom_completion() -{ - __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" - - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - local out requestComp lastParam lastChar comp directive args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases - args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" - __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no space" - compopt -o nospace - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" - compopt +o default - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - # Use printf to strip any trailing newline - subdir=$(printf "%%s" "${out[0]}") - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - __%[1]s_handle_subdirs_in_dir_flag "$subdir" - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${out[*]}" -- "$cur") - fi -} - -__%[1]s_handle_reply() -{ - __%[1]s_debug "${FUNCNAME[0]}" - local comp - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${allflags[*]}" -- "$cur") - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi - return 0; - ;; - esac - - # check if we are handling a flag with special work handling - local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi - - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions+=("${must_have_one_noun[@]}") - elif [[ -n "${has_completion_function}" ]]; then - # if a go completion function is provided, defer to that function - __%[1]s_handle_go_custom_completion - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${noun_aliases[*]}" -- "$cur") - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - if declare -F __%[1]s_custom_func >/dev/null; then - # try command name qualified custom func - __%[1]s_custom_func - else - # otherwise fall back to unqualified for compatibility - declare -F __custom_func >/dev/null && __custom_func - fi - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__%[1]s_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return -} - -__%[1]s_handle_flag() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then - __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() - fi - fi - - c=$((c+1)) - -} - -__%[1]s_handle_noun() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() - fi - - nouns+=("${words[c]}") - c=$((c+1)) -} - -__%[1]s_handle_command() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" - else - next_command="_${words[c]//:/__}" - fi - fi - c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} - -__%[1]s_handle_word() -{ - if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return - fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command - elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __%[1]s_handle_command - else - __%[1]s_handle_noun - fi - else - __%[1]s_handle_noun - fi - __%[1]s_handle_word -} - -`, name, ShellCompNoDescRequestCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -func writePostscript(buf io.StringWriter, name string) { - name = strings.Replace(name, ":", "__", -1) - WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(`{ - local cur prev words cword split - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi - - local c=0 - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("%[1]s") - local command_aliases=() - local must_have_one_flag=() - local must_have_one_noun=() - local has_completion_function - local last_command - local nouns=() - local noun_aliases=() - - __%[1]s_handle_word -} - -`, name)) - WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%s %s -else - complete -o default -o nospace -F __start_%s %s -fi - -`, name, name, name, name)) - WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n") -} - -func writeCommands(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " commands=()\n") - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name())) - writeCmdAliases(buf, c) - } - WriteStringAndCheck(buf, "\n") -} - -func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) { - for key, value := range annotations { - switch key { - case BashCompFilenameExt: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") - } else { - ext = "_filedir" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - if len(value) > 0 { - handlers := strings.Join(value, "; ") - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - WriteStringAndCheck(buf, " flags_completion+=(:)\n") - } - case BashCompSubdirsInDir: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] - } else { - ext = "_filedir -d" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - } - } -} - -const cbn = "\")\n" - -func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Shorthand - format := " " - if len(flag.NoOptDefVal) == 0 { - format += "two_word_" - } - format += "flags+=(\"-%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) -} - -func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Name - format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.NoOptDefVal) == 0 { - format = " two_word_flags+=(\"--%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - } - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) -} - -func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn - if len(flag.NoOptDefVal) == 0 { - format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn - } - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) - } -} - -// Setup annotations for go completions for registered flags -func prepareCustomAnnotationsForFlags(cmd *Command) { - flagCompletionMutex.RLock() - defer flagCompletionMutex.RUnlock() - for flag := range flagCompletionFunctions { - // Make sure the completion script calls the __*_go_custom_completion function for - // every registered flag. We need to do this here (and not when the flag was registered - // for completion) so that we can know the root command name for the prefix - // of ___go_custom_completion - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} - } -} - -func writeFlags(buf io.StringWriter, cmd *Command) { - prepareCustomAnnotationsForFlags(cmd) - WriteStringAndCheck(buf, ` flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - -`) - localNonPersistentFlags := cmd.LocalNonPersistentFlags() - cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - // localNonPersistentFlags are used to stop the completion of subcommands when one is set - // if TraverseChildren is true we should allow to complete subcommands - if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - }) - - WriteStringAndCheck(buf, "\n") -} - -func writeRequiredFlag(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_flag=()\n") - flags := cmd.NonInheritedFlags() - flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) - } - } - } - }) -} - -func writeRequiredNouns(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_noun=()\n") - sort.Strings(cmd.ValidArgs) - for _, value := range cmd.ValidArgs { - // Remove any description that may be included following a tab character. - // Descriptions are not supported by bash completion. - value = strings.Split(value, "\t")[0] - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) - } - if cmd.ValidArgsFunction != nil { - WriteStringAndCheck(buf, " has_completion_function=1\n") - } -} - -func writeCmdAliases(buf io.StringWriter, cmd *Command) { - if len(cmd.Aliases) == 0 { - return - } - - sort.Strings(cmd.Aliases) - - WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n")) - for _, value := range cmd.Aliases { - WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value)) - WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) - } - WriteStringAndCheck(buf, ` fi`) - WriteStringAndCheck(buf, "\n") -} -func writeArgAliases(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " noun_aliases=()\n") - sort.Strings(cmd.ArgAliases) - for _, value := range cmd.ArgAliases { - WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf io.StringWriter, cmd *Command) { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - gen(buf, c) - } - commandName := cmd.CommandPath() - commandName = strings.Replace(commandName, " ", "_", -1) - commandName = strings.Replace(commandName, ":", "__", -1) - - if cmd.Root() == cmd { - WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName)) - } - - WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName)) - WriteStringAndCheck(buf, "\n") - WriteStringAndCheck(buf, " command_aliases=()\n") - WriteStringAndCheck(buf, "\n") - - writeCommands(buf, cmd) - writeFlags(buf, cmd) - writeRequiredFlag(buf, cmd) - writeRequiredNouns(buf, cmd) - writeArgAliases(buf, cmd) - WriteStringAndCheck(buf, "}\n\n") -} - -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) - - _, err := buf.WriteTo(w) - return err -} - -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletion(outFile) -} diff --git a/examples/vendor/github.com/spf13/cobra/bash_completions.md b/examples/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2..0000000 --- a/examples/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/examples/vendor/github.com/spf13/cobra/bash_completionsV2.go b/examples/vendor/github.com/spf13/cobra/bash_completionsV2.go deleted file mode 100644 index 8859b57..0000000 --- a/examples/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ /dev/null @@ -1,302 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genBashComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genBashComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - - WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Macs have bash3 for which the bash-completion package doesn't include -# _init_completion. This is a minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -# This function calls the %[1]s program to obtain the completion -# results and the directive. It fills the 'out' and 'directive' vars. -__%[1]s_get_completion_results() { - local requestComp lastParam lastChar args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows to handle aliases - args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} ''" - fi - - # When completing a flag with an = (e.g., %[1]s -n=) - # bash focuses on the part after the =, so we need to remove - # the flag part from $cur - if [[ "${cur}" == -*=* ]]; then - cur="${cur#*=}" - fi - - __%[1]s_debug "Calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "The completion directive is: ${directive}" - __%[1]s_debug "The completions are: ${out[*]}" -} - -__%[1]s_process_completion_results() { - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "Activating no space" - compopt -o nospace - else - __%[1]s_debug "No space directive not supported in this version of bash" - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "Activating no file completion" - compopt +o default - else - __%[1]s_debug "No file completion directive not supported in this version of bash" - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - - # Use printf to strip any trailing newline - local subdir - subdir=$(printf "%%s" "${out[0]}") - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - __%[1]s_handle_standard_completion_case - fi - - __%[1]s_handle_special_char "$cur" : - __%[1]s_handle_special_char "$cur" = -} - -__%[1]s_handle_standard_completion_case() { - local tab comp - tab=$(printf '\t') - - local longest=0 - # Look for the longest completion so that we can format things nicely - while IFS='' read -r comp; do - # Strip any description before checking the length - comp=${comp%%%%$tab*} - # Only consider the completions that match - comp=$(compgen -W "$comp" -- "$cur") - if ((${#comp}>longest)); then - longest=${#comp} - fi - done < <(printf "%%s\n" "${out[@]}") - - local completions=() - while IFS='' read -r comp; do - if [ -z "$comp" ]; then - continue - fi - - __%[1]s_debug "Original comp: $comp" - comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")" - __%[1]s_debug "Final comp: $comp" - completions+=("$comp") - done < <(printf "%%s\n" "${out[@]}") - - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - # If there is a single completion left, remove the description text - if [ ${#COMPREPLY[*]} -eq 1 ]; then - __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" - comp="${COMPREPLY[0]%%%% *}" - __%[1]s_debug "Removed description from single completion, which is now: ${comp}" - COMPREPLY=() - COMPREPLY+=("$comp") - fi -} - -__%[1]s_handle_special_char() -{ - local comp="$1" - local char=$2 - if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then - local word=${comp%%"${comp##*${char}}"} - local idx=${#COMPREPLY[*]} - while [[ $((--idx)) -ge 0 ]]; do - COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"} - done - fi -} - -__%[1]s_format_comp_descriptions() -{ - local tab - tab=$(printf '\t') - local comp="$1" - local longest=$2 - - # Properly format the description string which follows a tab character if there is one - if [[ "$comp" == *$tab* ]]; then - desc=${comp#*$tab} - comp=${comp%%%%$tab*} - - # $COLUMNS stores the current shell width. - # Remove an extra 4 because we add 2 spaces and 2 parentheses. - maxdesclength=$(( COLUMNS - longest - 4 )) - - # Make sure we can fit a description of at least 8 characters - # if we are to align the descriptions. - if [[ $maxdesclength -gt 8 ]]; then - # Add the proper number of spaces to align the descriptions - for ((i = ${#comp} ; i < longest ; i++)); do - comp+=" " - done - else - # Don't pad the descriptions so we can fit more text after the completion - maxdesclength=$(( COLUMNS - ${#comp} - 4 )) - fi - - # If there is enough space for any description text, - # truncate the descriptions that are too long for the shell width - if [ $maxdesclength -gt 0 ]; then - if [ ${#desc} -gt $maxdesclength ]; then - desc=${desc:0:$(( maxdesclength - 1 ))} - desc+="…" - fi - comp+=" ($desc)" - fi - fi - - # Must use printf to escape all special characters - printf "%%q" "${comp}" -} - -__start_%[1]s() -{ - local cur prev words cword split - - COMPREPLY=() - - # Call _init_completion from the bash-completion package - # to prepare the arguments properly - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -n "=:" || return - else - __%[1]s_init_completion -n "=:" || return - fi - - __%[1]s_debug - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $cword location, so we need - # to truncate the command-line ($words) up to the $cword location. - words=("${words[@]:0:$cword+1}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - local out directive - __%[1]s_get_completion_results - __%[1]s_process_completion_results -} - -if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%[1]s %[1]s -else - complete -o default -o nospace -F __start_%[1]s %[1]s -fi - -# ex: ts=4 sw=4 et filetype=sh -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -// GenBashCompletionFileV2 generates Bash completion version 2. -func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletionV2(outFile, includeDesc) -} - -// GenBashCompletionV2 generates Bash completion file version 2 -// and writes it to the passed writer. -func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { - return c.genBashCompletion(w, includeDesc) -} diff --git a/examples/vendor/github.com/spf13/cobra/cobra.go b/examples/vendor/github.com/spf13/cobra/cobra.go deleted file mode 100644 index d6cbfd7..0000000 --- a/examples/vendor/github.com/spf13/cobra/cobra.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// 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. - -// Commands similar to git, go tools and other modern CLI tools -// inspired by go, go-Commander, gh and subcommand - -package cobra - -import ( - "fmt" - "io" - "os" - "reflect" - "strconv" - "strings" - "text/template" - "time" - "unicode" -) - -var templateFuncs = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "trimTrailingWhitespaces": trimRightSpace, - "appendIfNotPresent": appendIfNotPresent, - "rpad": rpad, - "gt": Gt, - "eq": Eq, -} - -var initializers []func() - -// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing -// to automatically enable in CLI tools. -// Set this to true to enable it. -var EnablePrefixMatching = false - -// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. -// To disable sorting, set it to false. -var EnableCommandSorting = true - -// MousetrapHelpText enables an information splash screen on Windows -// if the CLI is started from explorer.exe. -// To disable the mousetrap, just set this variable to blank string (""). -// Works only on Microsoft Windows. -var MousetrapHelpText = `This is a command line tool. - -You need to open cmd.exe and run it from there. -` - -// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows -// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. -// To disable the mousetrap, just set MousetrapHelpText to blank string (""). -// Works only on Microsoft Windows. -var MousetrapDisplayDuration = 5 * time.Second - -// AddTemplateFunc adds a template function that's available to Usage and Help -// template generation. -func AddTemplateFunc(name string, tmplFunc interface{}) { - templateFuncs[name] = tmplFunc -} - -// AddTemplateFuncs adds multiple template functions that are available to Usage and -// Help template generation. -func AddTemplateFuncs(tmplFuncs template.FuncMap) { - for k, v := range tmplFuncs { - templateFuncs[k] = v - } -} - -// OnInitialize sets the passed functions to be run when each command's -// Execute method is called. -func OnInitialize(y ...func()) { - initializers = append(initializers, y...) -} - -// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, -// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as -// ints and then compared. -func Gt(a interface{}, b interface{}) bool { - var left, right int64 - av := reflect.ValueOf(a) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - left = int64(av.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - left = av.Int() - case reflect.String: - left, _ = strconv.ParseInt(av.String(), 10, 64) - } - - bv := reflect.ValueOf(b) - - switch bv.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - right = int64(bv.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - right = bv.Int() - case reflect.String: - right, _ = strconv.ParseInt(bv.String(), 10, 64) - } - - return left > right -} - -// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. -func Eq(a interface{}, b interface{}) bool { - av := reflect.ValueOf(a) - bv := reflect.ValueOf(b) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - panic("Eq called on unsupported type") - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return av.Int() == bv.Int() - case reflect.String: - return av.String() == bv.String() - } - return false -} - -func trimRightSpace(s string) string { - return strings.TrimRightFunc(s, unicode.IsSpace) -} - -// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. -func appendIfNotPresent(s, stringToAppend string) string { - if strings.Contains(s, stringToAppend) { - return s - } - return s + " " + stringToAppend -} - -// rpad adds padding to the right of a string. -func rpad(s string, padding int) string { - template := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(template, s) -} - -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) error { - t := template.New("top") - t.Funcs(templateFuncs) - template.Must(t.Parse(text)) - return t.Execute(w, data) -} - -// ld compares two strings and returns the levenshtein distance between them. -func ld(s, t string, ignoreCase bool) int { - if ignoreCase { - s = strings.ToLower(s) - t = strings.ToLower(t) - } - d := make([][]int, len(s)+1) - for i := range d { - d[i] = make([]int, len(t)+1) - } - for i := range d { - d[i][0] = i - } - for j := range d[0] { - d[0][j] = j - } - for j := 1; j <= len(t); j++ { - for i := 1; i <= len(s); i++ { - if s[i-1] == t[j-1] { - d[i][j] = d[i-1][j-1] - } else { - min := d[i-1][j] - if d[i][j-1] < min { - min = d[i][j-1] - } - if d[i-1][j-1] < min { - min = d[i-1][j-1] - } - d[i][j] = min + 1 - } - } - - } - return d[len(s)][len(t)] -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} - -// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing. -func CheckErr(msg interface{}) { - if msg != nil { - fmt.Fprintln(os.Stderr, "Error:", msg) - os.Exit(1) - } -} - -// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil. -func WriteStringAndCheck(b io.StringWriter, s string) { - _, err := b.WriteString(s) - CheckErr(err) -} diff --git a/examples/vendor/github.com/spf13/cobra/command.go b/examples/vendor/github.com/spf13/cobra/command.go deleted file mode 100644 index 2cc1889..0000000 --- a/examples/vendor/github.com/spf13/cobra/command.go +++ /dev/null @@ -1,1680 +0,0 @@ -// Copyright © 2013 Steve Francia . -// -// 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 cobra is a commander providing a simple interface to create powerful modern CLI interfaces. -// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. -package cobra - -import ( - "bytes" - "context" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - - flag "github.com/spf13/pflag" -) - -// FParseErrWhitelist configures Flag parse errors to be ignored -type FParseErrWhitelist flag.ParseErrorsWhitelist - -// Command is just that, a command for your application. -// E.g. 'go run ...' - 'run' is the command. Cobra requires -// you to define the usage and description as part of your command -// definition to ensure usability. -type Command struct { - // Use is the one-line usage message. - // Recommended syntax is as follow: - // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. - // ... indicates that you can specify multiple values for the previous argument. - // | indicates mutually exclusive information. You can use the argument to the left of the separator or the - // argument to the right of the separator. You cannot use both arguments in a single use of the command. - // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are - // optional, they are enclosed in brackets ([ ]). - // Example: add [-F file | -D dir]... [-f format] profile - Use string - - // Aliases is an array of aliases that can be used instead of the first word in Use. - Aliases []string - - // SuggestFor is an array of command names for which this command will be suggested - - // similar to aliases but only suggests. - SuggestFor []string - - // Short is the short description shown in the 'help' output. - Short string - - // Long is the long message shown in the 'help ' output. - Long string - - // Example is examples of how to use the command. - Example string - - // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions - ValidArgs []string - // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. - // It is a dynamic version of using ValidArgs. - // Only one of ValidArgs and ValidArgsFunction can be used for a command. - ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - - // Expected arguments - Args PositionalArgs - - // ArgAliases is List of aliases for ValidArgs. - // These are not suggested to the user in the shell completion, - // but accepted if entered manually. - ArgAliases []string - - // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - // For portability with other shells, it is recommended to instead use ValidArgsFunction - BashCompletionFunction string - - // Deprecated defines, if this command is deprecated and should print this string when used. - Deprecated string - - // Annotations are key/value pairs that can be used by applications to identify or - // group commands. - Annotations map[string]string - - // Version defines the version for this command. If this value is non-empty and the command does not - // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. A shorthand "v" flag will also be added if the - // command does not define one. - Version string - - // The *Run functions are executed in the following order: - // * PersistentPreRun() - // * PreRun() - // * Run() - // * PostRun() - // * PersistentPostRun() - // All functions get the same args, the arguments after the command name. - // - // PersistentPreRun: children of this command will inherit and execute. - PersistentPreRun func(cmd *Command, args []string) - // PersistentPreRunE: PersistentPreRun but returns an error. - PersistentPreRunE func(cmd *Command, args []string) error - // PreRun: children of this command will not inherit. - PreRun func(cmd *Command, args []string) - // PreRunE: PreRun but returns an error. - PreRunE func(cmd *Command, args []string) error - // Run: Typically the actual work function. Most commands will only implement this. - Run func(cmd *Command, args []string) - // RunE: Run but returns an error. - RunE func(cmd *Command, args []string) error - // PostRun: run after the Run command. - PostRun func(cmd *Command, args []string) - // PostRunE: PostRun but returns an error. - PostRunE func(cmd *Command, args []string) error - // PersistentPostRun: children of this command will inherit and execute after PostRun. - PersistentPostRun func(cmd *Command, args []string) - // PersistentPostRunE: PersistentPostRun but returns an error. - PersistentPostRunE func(cmd *Command, args []string) error - - // args is actual args parsed from flags. - args []string - // flagErrorBuf contains all error messages from pflag. - flagErrorBuf *bytes.Buffer - // flags is full set of flags. - flags *flag.FlagSet - // pflags contains persistent flags. - pflags *flag.FlagSet - // lflags contains local flags. - lflags *flag.FlagSet - // iflags contains inherited flags. - iflags *flag.FlagSet - // parentsPflags is all persistent flags of cmd's parents. - parentsPflags *flag.FlagSet - // globNormFunc is the global normalization function - // that we can use on every pflag set and children commands - globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName - - // usageFunc is usage func defined by user. - usageFunc func(*Command) error - // usageTemplate is usage template defined by user. - usageTemplate string - // flagErrorFunc is func defined by user and it's called when the parsing of - // flags returns an error. - flagErrorFunc func(*Command, error) error - // helpTemplate is help template defined by user. - helpTemplate string - // helpFunc is help func defined by user. - helpFunc func(*Command, []string) - // helpCommand is command with usage 'help'. If it's not defined by user, - // cobra uses default help command. - helpCommand *Command - // versionTemplate is the version template defined by user. - versionTemplate string - - // inReader is a reader defined by the user that replaces stdin - inReader io.Reader - // outWriter is a writer defined by the user that replaces stdout - outWriter io.Writer - // errWriter is a writer defined by the user that replaces stderr - errWriter io.Writer - - //FParseErrWhitelist flag parse errors to be ignored - FParseErrWhitelist FParseErrWhitelist - - // CompletionOptions is a set of options to control the handling of shell completion - CompletionOptions CompletionOptions - - // commandsAreSorted defines, if command slice are sorted or not. - commandsAreSorted bool - // commandCalledAs is the name or alias value used to call this command. - commandCalledAs struct { - name string - called bool - } - - ctx context.Context - - // commands is the list of commands supported by this program. - commands []*Command - // parent is a parent command for this command. - parent *Command - // Max lengths of commands' string lengths for use in padding. - commandsMaxUseLen int - commandsMaxCommandPathLen int - commandsMaxNameLen int - - // TraverseChildren parses flags on all parents before executing child command. - TraverseChildren bool - - // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. - Hidden bool - - // SilenceErrors is an option to quiet errors down stream. - SilenceErrors bool - - // SilenceUsage is an option to silence usage when an error occurs. - SilenceUsage bool - - // DisableFlagParsing disables the flag parsing. - // If this is true all flags will be passed to the command as arguments. - DisableFlagParsing bool - - // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - // will be printed by generating docs for this command. - DisableAutoGenTag bool - - // DisableFlagsInUseLine will disable the addition of [flags] to the usage - // line of a command when printing help or generating docs - DisableFlagsInUseLine bool - - // DisableSuggestions disables the suggestions based on Levenshtein distance - // that go along with 'unknown command' messages. - DisableSuggestions bool - - // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - // Must be > 0. - SuggestionsMinimumDistance int -} - -// Context returns underlying command context. If command wasn't -// executed with ExecuteContext Context returns Background context. -func (c *Command) Context() context.Context { - return c.ctx -} - -// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden -// particularly useful when testing. -func (c *Command) SetArgs(a []string) { - c.args = a -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -// Deprecated: Use SetOut and/or SetErr instead -func (c *Command) SetOutput(output io.Writer) { - c.outWriter = output - c.errWriter = output -} - -// SetOut sets the destination for usage messages. -// If newOut is nil, os.Stdout is used. -func (c *Command) SetOut(newOut io.Writer) { - c.outWriter = newOut -} - -// SetErr sets the destination for error messages. -// If newErr is nil, os.Stderr is used. -func (c *Command) SetErr(newErr io.Writer) { - c.errWriter = newErr -} - -// SetIn sets the source for input data -// If newIn is nil, os.Stdin is used. -func (c *Command) SetIn(newIn io.Reader) { - c.inReader = newIn -} - -// SetUsageFunc sets usage function. Usage can be defined by application. -func (c *Command) SetUsageFunc(f func(*Command) error) { - c.usageFunc = f -} - -// SetUsageTemplate sets usage template. Can be defined by Application. -func (c *Command) SetUsageTemplate(s string) { - c.usageTemplate = s -} - -// SetFlagErrorFunc sets a function to generate an error when flag parsing -// fails. -func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { - c.flagErrorFunc = f -} - -// SetHelpFunc sets help function. Can be defined by Application. -func (c *Command) SetHelpFunc(f func(*Command, []string)) { - c.helpFunc = f -} - -// SetHelpCommand sets help command. -func (c *Command) SetHelpCommand(cmd *Command) { - c.helpCommand = cmd -} - -// SetHelpTemplate sets help template to be used. Application can use it to set custom template. -func (c *Command) SetHelpTemplate(s string) { - c.helpTemplate = s -} - -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s -} - -// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. -// The user should not have a cyclic dependency on commands. -func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { - c.Flags().SetNormalizeFunc(n) - c.PersistentFlags().SetNormalizeFunc(n) - c.globNormFunc = n - - for _, command := range c.commands { - command.SetGlobalNormalizationFunc(n) - } -} - -// OutOrStdout returns output to stdout. -func (c *Command) OutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - -// OutOrStderr returns output to stderr -func (c *Command) OutOrStderr() io.Writer { - return c.getOut(os.Stderr) -} - -// ErrOrStderr returns output to stderr -func (c *Command) ErrOrStderr() io.Writer { - return c.getErr(os.Stderr) -} - -// InOrStdin returns input to stdin -func (c *Command) InOrStdin() io.Reader { - return c.getIn(os.Stdin) -} - -func (c *Command) getOut(def io.Writer) io.Writer { - if c.outWriter != nil { - return c.outWriter - } - if c.HasParent() { - return c.parent.getOut(def) - } - return def -} - -func (c *Command) getErr(def io.Writer) io.Writer { - if c.errWriter != nil { - return c.errWriter - } - if c.HasParent() { - return c.parent.getErr(def) - } - return def -} - -func (c *Command) getIn(def io.Reader) io.Reader { - if c.inReader != nil { - return c.inReader - } - if c.HasParent() { - return c.parent.getIn(def) - } - return def -} - -// UsageFunc returns either the function set by SetUsageFunc for this command -// or a parent, or it returns a default usage function. -func (c *Command) UsageFunc() (f func(*Command) error) { - if c.usageFunc != nil { - return c.usageFunc - } - if c.HasParent() { - return c.Parent().UsageFunc() - } - return func(c *Command) error { - c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - return err - } -} - -// Usage puts out the usage for the command. -// Used when a user provides invalid input. -// Can be defined by user by overriding UsageFunc. -func (c *Command) Usage() error { - return c.UsageFunc()(c) -} - -// HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function with default help behavior. -func (c *Command) HelpFunc() func(*Command, []string) { - if c.helpFunc != nil { - return c.helpFunc - } - if c.HasParent() { - return c.Parent().HelpFunc() - } - return func(c *Command, a []string) { - c.mergePersistentFlags() - // The help should be sent to stdout - // See https://github.com/spf13/cobra/issues/1002 - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - } -} - -// Help puts out the help for the command. -// Used when a user calls help [command]. -// Can be defined by user by overriding HelpFunc. -func (c *Command) Help() error { - c.HelpFunc()(c, []string{}) - return nil -} - -// UsageString returns usage string. -func (c *Command) UsageString() string { - // Storing normal writers - tmpOutput := c.outWriter - tmpErr := c.errWriter - - bb := new(bytes.Buffer) - c.outWriter = bb - c.errWriter = bb - - CheckErr(c.Usage()) - - // Setting things back to normal - c.outWriter = tmpOutput - c.errWriter = tmpErr - - return bb.String() -} - -// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this -// command or a parent, or it returns a function which returns the original -// error. -func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { - if c.flagErrorFunc != nil { - return c.flagErrorFunc - } - - if c.HasParent() { - return c.parent.FlagErrorFunc() - } - return func(c *Command, err error) error { - return err - } -} - -var minUsagePadding = 25 - -// UsagePadding return padding for the usage. -func (c *Command) UsagePadding() int { - if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { - return minUsagePadding - } - return c.parent.commandsMaxUseLen -} - -var minCommandPathPadding = 11 - -// CommandPathPadding return padding for the command path. -func (c *Command) CommandPathPadding() int { - if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { - return minCommandPathPadding - } - return c.parent.commandsMaxCommandPathLen -} - -var minNamePadding = 11 - -// NamePadding returns padding for the name. -func (c *Command) NamePadding() int { - if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { - return minNamePadding - } - return c.parent.commandsMaxNameLen -} - -// UsageTemplate returns usage template for the command. -func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate - } - - if c.HasParent() { - return c.parent.UsageTemplate() - } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}} - -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} - -Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} - -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} - -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` -} - -// HelpTemplate return help template for the command. -func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate - } - - if c.HasParent() { - return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` -} - -func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { - flag := fs.Lookup(name) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { - if len(name) == 0 { - return false - } - - flag := fs.ShorthandLookup(name[:1]) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func stripFlags(args []string, c *Command) []string { - if len(args) == 0 { - return args - } - c.mergePersistentFlags() - - commands := []string{} - flags := c.Flags() - -Loop: - for len(args) > 0 { - s := args[0] - args = args[1:] - switch { - case s == "--": - // "--" terminates the flags - break Loop - case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): - // If '--flag arg' then - // delete arg from args. - fallthrough // (do the same as below) - case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): - // If '-f arg' then - // delete 'arg' from args or break the loop if len(args) <= 1. - if len(args) <= 1 { - break Loop - } else { - args = args[1:] - continue - } - case s != "" && !strings.HasPrefix(s, "-"): - commands = append(commands, s) - } - } - - return commands -} - -// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like -// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -func argsMinusFirstX(args []string, x string) []string { - for i, y := range args { - if x == y { - ret := []string{} - ret = append(ret, args[:i]...) - ret = append(ret, args[i+1:]...) - return ret - } - } - return args -} - -func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[1] == '-') || - (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) -} - -// Find the target command given the args and command tree -// Meant to be run on the highest node. Only searches down. -func (c *Command) Find(args []string) (*Command, []string, error) { - var innerfind func(*Command, []string) (*Command, []string) - - innerfind = func(c *Command, innerArgs []string) (*Command, []string) { - argsWOflags := stripFlags(innerArgs, c) - if len(argsWOflags) == 0 { - return c, innerArgs - } - nextSubCmd := argsWOflags[0] - - cmd := c.findNext(nextSubCmd) - if cmd != nil { - return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) - } - return c, innerArgs - } - - commandFound, a := innerfind(c, args) - if commandFound.Args == nil { - return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) - } - return commandFound, a, nil -} - -func (c *Command) findSuggestions(arg string) string { - if c.DisableSuggestions { - return "" - } - if c.SuggestionsMinimumDistance <= 0 { - c.SuggestionsMinimumDistance = 2 - } - suggestionsString := "" - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" - for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) - } - } - return suggestionsString -} - -func (c *Command) findNext(next string) *Command { - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if cmd.Name() == next || cmd.HasAlias(next) { - cmd.commandCalledAs.name = next - return cmd - } - if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { - matches = append(matches, cmd) - } - } - - if len(matches) == 1 { - return matches[0] - } - - return nil -} - -// Traverse the command tree to find the command, and parse args for -// each parent. -func (c *Command) Traverse(args []string) (*Command, []string, error) { - flags := []string{} - inFlag := false - - for i, arg := range args { - switch { - // A long flag with a space separated value - case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) - flags = append(flags, arg) - continue - // A short flag with a space separated value - case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): - inFlag = true - flags = append(flags, arg) - continue - // The value for a flag - case inFlag: - inFlag = false - flags = append(flags, arg) - continue - // A flag without a value, or with an `=` separated value - case isFlagArg(arg): - flags = append(flags, arg) - continue - } - - cmd := c.findNext(arg) - if cmd == nil { - return c, args, nil - } - - if err := c.ParseFlags(flags); err != nil { - return nil, args, err - } - return cmd.Traverse(args[i+1:]) - } - return c, args, nil -} - -// SuggestionsFor provides suggestions for the typedName. -func (c *Command) SuggestionsFor(typedName string) []string { - suggestions := []string{} - for _, cmd := range c.commands { - if cmd.IsAvailableCommand() { - levenshteinDistance := ld(typedName, cmd.Name(), true) - suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance - suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) - if suggestByLevenshtein || suggestByPrefix { - suggestions = append(suggestions, cmd.Name()) - } - for _, explicitSuggestion := range cmd.SuggestFor { - if strings.EqualFold(typedName, explicitSuggestion) { - suggestions = append(suggestions, cmd.Name()) - } - } - } - } - return suggestions -} - -// VisitParents visits all parents of the command and invokes fn on each parent. -func (c *Command) VisitParents(fn func(*Command)) { - if c.HasParent() { - fn(c.Parent()) - c.Parent().VisitParents(fn) - } -} - -// Root finds root command. -func (c *Command) Root() *Command { - if c.HasParent() { - return c.Parent().Root() - } - return c -} - -// ArgsLenAtDash will return the length of c.Flags().Args at the moment -// when a -- was found during args parsing. -func (c *Command) ArgsLenAtDash() int { - return c.Flags().ArgsLenAtDash() -} - -func (c *Command) execute(a []string) (err error) { - if c == nil { - return fmt.Errorf("Called Execute() on a nil Command") - } - - if len(c.Deprecated) > 0 { - c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) - } - - // initialize help and version flag at the last point possible to allow for user - // overriding - c.InitDefaultHelpFlag() - c.InitDefaultVersionFlag() - - err = c.ParseFlags(a) - if err != nil { - return c.FlagErrorFunc()(c, err) - } - - // If help is called, regardless of other flags, return we want help. - // Also say we need help if the command isn't runnable. - helpVal, err := c.Flags().GetBool("help") - if err != nil { - // should be impossible to get here as we always declare a help - // flag in InitDefaultHelpFlag() - c.Println("\"help\" flag declared as non-bool. Please correct your code") - return err - } - - if helpVal { - return flag.ErrHelp - } - - // for back-compat, only add version flag behavior if version is defined - if c.Version != "" { - versionVal, err := c.Flags().GetBool("version") - if err != nil { - c.Println("\"version\" flag declared as non-bool. Please correct your code") - return err - } - if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } - } - - if !c.Runnable() { - return flag.ErrHelp - } - - c.preRun() - - argWoFlags := c.Flags().Args() - if c.DisableFlagParsing { - argWoFlags = a - } - - if err := c.ValidateArgs(argWoFlags); err != nil { - return err - } - - for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPreRun != nil { - p.PersistentPreRun(c, argWoFlags) - break - } - } - if c.PreRunE != nil { - if err := c.PreRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PreRun != nil { - c.PreRun(c, argWoFlags) - } - - if err := c.validateRequiredFlags(); err != nil { - return err - } - if c.RunE != nil { - if err := c.RunE(c, argWoFlags); err != nil { - return err - } - } else { - c.Run(c, argWoFlags) - } - if c.PostRunE != nil { - if err := c.PostRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PostRun != nil { - c.PostRun(c, argWoFlags) - } - for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRunE != nil { - if err := p.PersistentPostRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPostRun != nil { - p.PersistentPostRun(c, argWoFlags) - break - } - } - - return nil -} - -func (c *Command) preRun() { - for _, x := range initializers { - x() - } -} - -// ExecuteContext is the same as Execute(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContext(ctx context.Context) error { - c.ctx = ctx - return c.Execute() -} - -// Execute uses the args (os.Args[1:] by default) -// and run through the command tree finding appropriate matches -// for commands and then corresponding flags. -func (c *Command) Execute() error { - _, err := c.ExecuteC() - return err -} - -// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { - c.ctx = ctx - return c.ExecuteC() -} - -// ExecuteC executes the command. -func (c *Command) ExecuteC() (cmd *Command, err error) { - if c.ctx == nil { - c.ctx = context.Background() - } - - // Regardless of what command execute is called on, run on Root only - if c.HasParent() { - return c.Root().ExecuteC() - } - - // windows hook - if preExecHookFn != nil { - preExecHookFn(c) - } - - // initialize help at the last point to allow for user overriding - c.InitDefaultHelpCmd() - // initialize completion at the last point to allow for user overriding - c.initDefaultCompletionCmd() - - args := c.args - - // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 - if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { - args = os.Args[1:] - } - - // initialize the hidden command to be used for shell completion - c.initCompleteCmd(args) - - var flags []string - if c.TraverseChildren { - cmd, flags, err = c.Traverse(args) - } else { - cmd, flags, err = c.Find(args) - } - if err != nil { - // If found parse to a subcommand and then failed, talk about the subcommand - if cmd != nil { - c = cmd - } - if !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) - c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) - } - return c, err - } - - cmd.commandCalledAs.called = true - if cmd.commandCalledAs.name == "" { - cmd.commandCalledAs.name = cmd.Name() - } - - // We have to pass global context to children command - // if context is present on the parent command. - if cmd.ctx == nil { - cmd.ctx = c.ctx - } - - err = cmd.execute(flags) - if err != nil { - // Always show help if requested, even if SilenceErrors is in - // effect - if err == flag.ErrHelp { - cmd.HelpFunc()(cmd, args) - return cmd, nil - } - - // If root command has SilenceErrors flagged, - // all subcommands should respect it - if !cmd.SilenceErrors && !c.SilenceErrors { - c.PrintErrln("Error:", err.Error()) - } - - // If root command has SilenceUsage flagged, - // all subcommands should respect it - if !cmd.SilenceUsage && !c.SilenceUsage { - c.Println(cmd.UsageString()) - } - } - return cmd, err -} - -func (c *Command) ValidateArgs(args []string) error { - if c.Args == nil { - return nil - } - return c.Args(c, args) -} - -func (c *Command) validateRequiredFlags() error { - if c.DisableFlagParsing { - return nil - } - - flags := c.Flags() - missingFlagNames := []string{} - flags.VisitAll(func(pflag *flag.Flag) { - requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] - if !found { - return - } - if (requiredAnnotation[0] == "true") && !pflag.Changed { - missingFlagNames = append(missingFlagNames, pflag.Name) - } - }) - - if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) - } - return nil -} - -// InitDefaultHelpFlag adds default help flag to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help flag, it will do nothing. -func (c *Command) InitDefaultHelpFlag() { - c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { - usage := "help for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().BoolP("help", "h", false, usage) - } -} - -// InitDefaultVersionFlag adds default version flag to c. -// It is called automatically by executing the c. -// If c already has a version flag, it will do nothing. -// If c.Version is empty, it will do nothing. -func (c *Command) InitDefaultVersionFlag() { - if c.Version == "" { - return - } - - c.mergePersistentFlags() - if c.Flags().Lookup("version") == nil { - usage := "version for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - if c.Flags().ShorthandLookup("v") == nil { - c.Flags().BoolP("version", "v", false, usage) - } else { - c.Flags().Bool("version", false, usage) - } - } -} - -// InitDefaultHelpCmd adds default help command to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help command or c has no subcommands, it will do nothing. -func (c *Command) InitDefaultHelpCmd() { - if !c.HasSubCommands() { - return - } - - if c.helpCommand == nil { - c.helpCommand = &Command{ - Use: "help [command]", - Short: "Help about any command", - Long: `Help provides help for any command in the application. -Simply type ` + c.Name() + ` help [path to command] for full details.`, - ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - var completions []string - cmd, _, e := c.Root().Find(args) - if e != nil { - return nil, ShellCompDirectiveNoFileComp - } - if cmd == nil { - // Root help command. - cmd = c.Root() - } - for _, subCmd := range cmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - } - } - return completions, ShellCompDirectiveNoFileComp - }, - Run: func(c *Command, args []string) { - cmd, _, e := c.Root().Find(args) - if cmd == nil || e != nil { - c.Printf("Unknown help topic %#q\n", args) - CheckErr(c.Root().Usage()) - } else { - cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown - CheckErr(cmd.Help()) - } - }, - } - } - c.RemoveCommand(c.helpCommand) - c.AddCommand(c.helpCommand) -} - -// ResetCommands delete parent, subcommand and help command from c. -func (c *Command) ResetCommands() { - c.parent = nil - c.commands = nil - c.helpCommand = nil - c.parentsPflags = nil -} - -// Sorts commands by their names. -type commandSorterByName []*Command - -func (c commandSorterByName) Len() int { return len(c) } -func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } -func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } - -// Commands returns a sorted slice of child commands. -func (c *Command) Commands() []*Command { - // do not sort commands if it already sorted or sorting was disabled - if EnableCommandSorting && !c.commandsAreSorted { - sort.Sort(commandSorterByName(c.commands)) - c.commandsAreSorted = true - } - return c.commands -} - -// AddCommand adds one or more commands to this parent command. -func (c *Command) AddCommand(cmds ...*Command) { - for i, x := range cmds { - if cmds[i] == c { - panic("Command can't be a child of itself") - } - cmds[i].parent = c - // update max lengths - usageLen := len(x.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(x.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(x.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - // If global normalization function exists, update all children - if c.globNormFunc != nil { - x.SetGlobalNormalizationFunc(c.globNormFunc) - } - c.commands = append(c.commands, x) - c.commandsAreSorted = false - } -} - -// RemoveCommand removes one or more commands from a parent command. -func (c *Command) RemoveCommand(cmds ...*Command) { - commands := []*Command{} -main: - for _, command := range c.commands { - for _, cmd := range cmds { - if command == cmd { - command.parent = nil - continue main - } - } - commands = append(commands, command) - } - c.commands = commands - // recompute all lengths - c.commandsMaxUseLen = 0 - c.commandsMaxCommandPathLen = 0 - c.commandsMaxNameLen = 0 - for _, command := range c.commands { - usageLen := len(command.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(command.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(command.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - } -} - -// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. -func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.OutOrStderr(), i...) -} - -// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. -func (c *Command) Println(i ...interface{}) { - c.Print(fmt.Sprintln(i...)) -} - -// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. -func (c *Command) Printf(format string, i ...interface{}) { - c.Print(fmt.Sprintf(format, i...)) -} - -// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErr(i ...interface{}) { - fmt.Fprint(c.ErrOrStderr(), i...) -} - -// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrln(i ...interface{}) { - c.PrintErr(fmt.Sprintln(i...)) -} - -// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrf(format string, i ...interface{}) { - c.PrintErr(fmt.Sprintf(format, i...)) -} - -// CommandPath returns the full path to this command. -func (c *Command) CommandPath() string { - if c.HasParent() { - return c.Parent().CommandPath() + " " + c.Name() - } - return c.Name() -} - -// UseLine puts out the full usage for a given command (including parents). -func (c *Command) UseLine() string { - var useline string - if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use - } else { - useline = c.Use - } - if c.DisableFlagsInUseLine { - return useline - } - if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { - useline += " [flags]" - } - return useline -} - -// DebugFlags used to determine which flags have been assigned to which commands -// and which persist. -func (c *Command) DebugFlags() { - c.Println("DebugFlags called on", c.Name()) - var debugflags func(*Command) - - debugflags = func(x *Command) { - if x.HasFlags() || x.HasPersistentFlags() { - c.Println(x.Name()) - } - if x.HasFlags() { - x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") - } - }) - } - if x.HasPersistentFlags() { - x.pflags.VisitAll(func(f *flag.Flag) { - if x.HasFlags() { - if x.flags.Lookup(f.Name) == nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - }) - } - c.Println(x.flagErrorBuf) - if x.HasSubCommands() { - for _, y := range x.commands { - debugflags(y) - } - } - } - - debugflags(c) -} - -// Name returns the command's name: the first word in the use line. -func (c *Command) Name() string { - name := c.Use - i := strings.Index(name, " ") - if i >= 0 { - name = name[:i] - } - return name -} - -// HasAlias determines if a given string is an alias of the command. -func (c *Command) HasAlias(s string) bool { - for _, a := range c.Aliases { - if a == s { - return true - } - } - return false -} - -// CalledAs returns the command name or alias that was used to invoke -// this command or an empty string if the command has not been called. -func (c *Command) CalledAs() string { - if c.commandCalledAs.called { - return c.commandCalledAs.name - } - return "" -} - -// hasNameOrAliasPrefix returns true if the Name or any of aliases start -// with prefix -func (c *Command) hasNameOrAliasPrefix(prefix string) bool { - if strings.HasPrefix(c.Name(), prefix) { - c.commandCalledAs.name = c.Name() - return true - } - for _, alias := range c.Aliases { - if strings.HasPrefix(alias, prefix) { - c.commandCalledAs.name = alias - return true - } - } - return false -} - -// NameAndAliases returns a list of the command name and all aliases -func (c *Command) NameAndAliases() string { - return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") -} - -// HasExample determines if the command has example. -func (c *Command) HasExample() bool { - return len(c.Example) > 0 -} - -// Runnable determines if the command is itself runnable. -func (c *Command) Runnable() bool { - return c.Run != nil || c.RunE != nil -} - -// HasSubCommands determines if the command has children commands. -func (c *Command) HasSubCommands() bool { - return len(c.commands) > 0 -} - -// IsAvailableCommand determines if a command is available as a non-help command -// (this includes all non deprecated/hidden commands). -func (c *Command) IsAvailableCommand() bool { - if len(c.Deprecated) != 0 || c.Hidden { - return false - } - - if c.HasParent() && c.Parent().helpCommand == c { - return false - } - - if c.Runnable() || c.HasAvailableSubCommands() { - return true - } - - return false -} - -// IsAdditionalHelpTopicCommand determines if a command is an additional -// help topic command; additional help topic command is determined by the -// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that -// are runnable/hidden/deprecated. -// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. -func (c *Command) IsAdditionalHelpTopicCommand() bool { - // if a command is runnable, deprecated, or hidden it is not a 'help' command - if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { - return false - } - - // if any non-help sub commands are found, the command is not a 'help' command - for _, sub := range c.commands { - if !sub.IsAdditionalHelpTopicCommand() { - return false - } - } - - // the command either has no sub commands, or no non-help sub commands - return true -} - -// HasHelpSubCommands determines if a command has any available 'help' sub commands -// that need to be shown in the usage/help default template under 'additional help -// topics'. -func (c *Command) HasHelpSubCommands() bool { - // return true on the first found available 'help' sub command - for _, sub := range c.commands { - if sub.IsAdditionalHelpTopicCommand() { - return true - } - } - - // the command either has no sub commands, or no available 'help' sub commands - return false -} - -// HasAvailableSubCommands determines if a command has available sub commands that -// need to be shown in the usage/help default template under 'available commands'. -func (c *Command) HasAvailableSubCommands() bool { - // return true on the first found available (non deprecated/help/hidden) - // sub command - for _, sub := range c.commands { - if sub.IsAvailableCommand() { - return true - } - } - - // the command either has no sub commands, or no available (non deprecated/help/hidden) - // sub commands - return false -} - -// HasParent determines if the command is a child command. -func (c *Command) HasParent() bool { - return c.parent != nil -} - -// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. -func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { - return c.globNormFunc -} - -// Flags returns the complete FlagSet that applies -// to this command (local and persistent declared here and by all parents). -func (c *Command) Flags() *flag.FlagSet { - if c.flags == nil { - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.flags.SetOutput(c.flagErrorBuf) - } - - return c.flags -} - -// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.LocalFlags().VisitAll(func(f *flag.Flag) { - if persistentFlags.Lookup(f.Name) == nil { - out.AddFlag(f) - } - }) - return out -} - -// LocalFlags returns the local FlagSet specifically set in the current command. -func (c *Command) LocalFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - } - c.lflags.SortFlags = c.Flags().SortFlags - if c.globNormFunc != nil { - c.lflags.SetNormalizeFunc(c.globNormFunc) - } - - addToLocal := func(f *flag.Flag) { - if c.lflags.Lookup(f.Name) == nil && c.parentsPflags.Lookup(f.Name) == nil { - c.lflags.AddFlag(f) - } - } - c.Flags().VisitAll(addToLocal) - c.PersistentFlags().VisitAll(addToLocal) - return c.lflags -} - -// InheritedFlags returns all flags which were inherited from parent commands. -func (c *Command) InheritedFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.iflags.SetOutput(c.flagErrorBuf) - } - - local := c.LocalFlags() - if c.globNormFunc != nil { - c.iflags.SetNormalizeFunc(c.globNormFunc) - } - - c.parentsPflags.VisitAll(func(f *flag.Flag) { - if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - c.iflags.AddFlag(f) - } - }) - return c.iflags -} - -// NonInheritedFlags returns all flags which were not inherited from parent commands. -func (c *Command) NonInheritedFlags() *flag.FlagSet { - return c.LocalFlags() -} - -// PersistentFlags returns the persistent FlagSet specifically set in the current command. -func (c *Command) PersistentFlags() *flag.FlagSet { - if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.pflags.SetOutput(c.flagErrorBuf) - } - return c.pflags -} - -// ResetFlags deletes all flags from command. -func (c *Command) ResetFlags() { - c.flagErrorBuf = new(bytes.Buffer) - c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.pflags.SetOutput(c.flagErrorBuf) - - c.lflags = nil - c.iflags = nil - c.parentsPflags = nil -} - -// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). -func (c *Command) HasFlags() bool { - return c.Flags().HasFlags() -} - -// HasPersistentFlags checks if the command contains persistent flags. -func (c *Command) HasPersistentFlags() bool { - return c.PersistentFlags().HasFlags() -} - -// HasLocalFlags checks if the command has flags specifically declared locally. -func (c *Command) HasLocalFlags() bool { - return c.LocalFlags().HasFlags() -} - -// HasInheritedFlags checks if the command has flags inherited from its parent command. -func (c *Command) HasInheritedFlags() bool { - return c.InheritedFlags().HasFlags() -} - -// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire -// structure) which are not hidden or deprecated. -func (c *Command) HasAvailableFlags() bool { - return c.Flags().HasAvailableFlags() -} - -// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. -func (c *Command) HasAvailablePersistentFlags() bool { - return c.PersistentFlags().HasAvailableFlags() -} - -// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden -// or deprecated. -func (c *Command) HasAvailableLocalFlags() bool { - return c.LocalFlags().HasAvailableFlags() -} - -// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are -// not hidden or deprecated. -func (c *Command) HasAvailableInheritedFlags() bool { - return c.InheritedFlags().HasAvailableFlags() -} - -// Flag climbs up the command tree looking for matching flag. -func (c *Command) Flag(name string) (flag *flag.Flag) { - flag = c.Flags().Lookup(name) - - if flag == nil { - flag = c.persistentFlag(name) - } - - return -} - -// Recursively find matching persistent flag. -func (c *Command) persistentFlag(name string) (flag *flag.Flag) { - if c.HasPersistentFlags() { - flag = c.PersistentFlags().Lookup(name) - } - - if flag == nil { - c.updateParentsPflags() - flag = c.parentsPflags.Lookup(name) - } - return -} - -// ParseFlags parses persistent flag tree and local flags. -func (c *Command) ParseFlags(args []string) error { - if c.DisableFlagParsing { - return nil - } - - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - beforeErrorBufLen := c.flagErrorBuf.Len() - c.mergePersistentFlags() - - // do it here after merging all flags and just before parse - c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) - - err := c.Flags().Parse(args) - // Print warnings if they occurred (e.g. deprecated flag messages). - if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { - c.Print(c.flagErrorBuf.String()) - } - - return err -} - -// Parent returns a commands parent command. -func (c *Command) Parent() *Command { - return c.parent -} - -// mergePersistentFlags merges c.PersistentFlags() to c.Flags() -// and adds missing persistent flags of all parents. -func (c *Command) mergePersistentFlags() { - c.updateParentsPflags() - c.Flags().AddFlagSet(c.PersistentFlags()) - c.Flags().AddFlagSet(c.parentsPflags) -} - -// updateParentsPflags updates c.parentsPflags by adding -// new persistent flags of all parents. -// If c.parentsPflags == nil, it makes new. -func (c *Command) updateParentsPflags() { - if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) - c.parentsPflags.SetOutput(c.flagErrorBuf) - c.parentsPflags.SortFlags = false - } - - if c.globNormFunc != nil { - c.parentsPflags.SetNormalizeFunc(c.globNormFunc) - } - - c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) - - c.VisitParents(func(parent *Command) { - c.parentsPflags.AddFlagSet(parent.PersistentFlags()) - }) -} diff --git a/examples/vendor/github.com/spf13/cobra/command_notwin.go b/examples/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 6159c1c..0000000 --- a/examples/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,5 +0,0 @@ -// +build !windows - -package cobra - -var preExecHookFn func(*Command) diff --git a/examples/vendor/github.com/spf13/cobra/command_win.go b/examples/vendor/github.com/spf13/cobra/command_win.go deleted file mode 100644 index 8768b17..0000000 --- a/examples/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build windows - -package cobra - -import ( - "fmt" - "os" - "time" - - "github.com/inconshreveable/mousetrap" -) - -var preExecHookFn = preExecHook - -func preExecHook(c *Command) { - if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - if MousetrapDisplayDuration > 0 { - time.Sleep(MousetrapDisplayDuration) - } else { - c.Println("Press return to continue...") - fmt.Scanln() - } - os.Exit(1) - } -} diff --git a/examples/vendor/github.com/spf13/cobra/completions.go b/examples/vendor/github.com/spf13/cobra/completions.go deleted file mode 100644 index b849b9c..0000000 --- a/examples/vendor/github.com/spf13/cobra/completions.go +++ /dev/null @@ -1,781 +0,0 @@ -package cobra - -import ( - "fmt" - "os" - "strings" - "sync" - - "github.com/spf13/pflag" -) - -const ( - // ShellCompRequestCmd is the name of the hidden command that is used to request - // completion results from the program. It is used by the shell completion scripts. - ShellCompRequestCmd = "__complete" - // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request - // completion results without their description. It is used by the shell completion scripts. - ShellCompNoDescRequestCmd = "__completeNoDesc" -) - -// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. -var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} - -// lock for reading and writing from flagCompletionFunctions -var flagCompletionMutex = &sync.RWMutex{} - -// ShellCompDirective is a bit map representing the different behaviors the shell -// can be instructed to have once completions have been provided. -type ShellCompDirective int - -type flagCompError struct { - subCommand string - flagName string -} - -func (e *flagCompError) Error() string { - return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" -} - -const ( - // ShellCompDirectiveError indicates an error occurred and completions should be ignored. - ShellCompDirectiveError ShellCompDirective = 1 << iota - - // ShellCompDirectiveNoSpace indicates that the shell should not add a space - // after the completion even if there is a single completion provided. - ShellCompDirectiveNoSpace - - // ShellCompDirectiveNoFileComp indicates that the shell should not provide - // file completion even when no completion is provided. - ShellCompDirectiveNoFileComp - - // ShellCompDirectiveFilterFileExt indicates that the provided completions - // should be used as file extension filters. - // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() - // is a shortcut to using this directive explicitly. The BashCompFilenameExt - // annotation can also be used to obtain the same behavior for flags. - ShellCompDirectiveFilterFileExt - - // ShellCompDirectiveFilterDirs indicates that only directory names should - // be provided in file completion. To request directory names within another - // directory, the returned completions should specify the directory within - // which to search. The BashCompSubdirsInDir annotation can be used to - // obtain the same behavior but only for flags. - ShellCompDirectiveFilterDirs - - // =========================================================================== - - // All directives using iota should be above this one. - // For internal use. - shellCompDirectiveMaxValue - - // ShellCompDirectiveDefault indicates to let the shell perform its default - // behavior after completions have been provided. - // This one must be last to avoid messing up the iota count. - ShellCompDirectiveDefault ShellCompDirective = 0 -) - -const ( - // Constants for the completion command - compCmdName = "completion" - compCmdNoDescFlagName = "no-descriptions" - compCmdNoDescFlagDesc = "disable completion descriptions" - compCmdNoDescFlagDefault = false -) - -// CompletionOptions are the options to control shell completion -type CompletionOptions struct { - // DisableDefaultCmd prevents Cobra from creating a default 'completion' command - DisableDefaultCmd bool - // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - // for shells that support completion descriptions - DisableNoDescFlag bool - // DisableDescriptions turns off all completion descriptions for shells - // that support them - DisableDescriptions bool -} - -// NoFileCompletions can be used to disable file completion for commands that should -// not trigger file completions. -func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return nil, ShellCompDirectiveNoFileComp -} - -// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. -func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { - flag := c.Flag(flagName) - if flag == nil { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) - } - flagCompletionMutex.Lock() - defer flagCompletionMutex.Unlock() - - if _, exists := flagCompletionFunctions[flag]; exists { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) - } - flagCompletionFunctions[flag] = f - return nil -} - -// Returns a string listing the different directive enabled in the specified parameter -func (d ShellCompDirective) string() string { - var directives []string - if d&ShellCompDirectiveError != 0 { - directives = append(directives, "ShellCompDirectiveError") - } - if d&ShellCompDirectiveNoSpace != 0 { - directives = append(directives, "ShellCompDirectiveNoSpace") - } - if d&ShellCompDirectiveNoFileComp != 0 { - directives = append(directives, "ShellCompDirectiveNoFileComp") - } - if d&ShellCompDirectiveFilterFileExt != 0 { - directives = append(directives, "ShellCompDirectiveFilterFileExt") - } - if d&ShellCompDirectiveFilterDirs != 0 { - directives = append(directives, "ShellCompDirectiveFilterDirs") - } - if len(directives) == 0 { - directives = append(directives, "ShellCompDirectiveDefault") - } - - if d >= shellCompDirectiveMaxValue { - return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) - } - return strings.Join(directives, ", ") -} - -// Adds a special hidden command that can be used to request custom completions. -func (c *Command) initCompleteCmd(args []string) { - completeCmd := &Command{ - Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), - Aliases: []string{ShellCompNoDescRequestCmd}, - DisableFlagsInUseLine: true, - Hidden: true, - DisableFlagParsing: true, - Args: MinimumNArgs(1), - Short: "Request shell completion choices for the specified command-line", - Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", - "to request completion choices for the specified command-line.", ShellCompRequestCmd), - Run: func(cmd *Command, args []string) { - finalCmd, completions, directive, err := cmd.getCompletions(args) - if err != nil { - CompErrorln(err.Error()) - // Keep going for multiple reasons: - // 1- There could be some valid completions even though there was an error - // 2- Even without completions, we need to print the directive - } - - noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd) - for _, comp := range completions { - if noDescriptions { - // Remove any description that may be included following a tab character. - comp = strings.Split(comp, "\t")[0] - } - - // Make sure we only write the first line to the output. - // This is needed if a description contains a linebreak. - // Otherwise the shell scripts will interpret the other lines as new flags - // and could therefore provide a wrong completion. - comp = strings.Split(comp, "\n")[0] - - // Finally trim the completion. This is especially important to get rid - // of a trailing tab when there are no description following it. - // For example, a sub-command without a description should not be completed - // with a tab at the end (or else zsh will show a -- following it - // although there is no description). - comp = strings.TrimSpace(comp) - - // Print each possible completion to stdout for the completion script to consume. - fmt.Fprintln(finalCmd.OutOrStdout(), comp) - } - - // As the last printout, print the completion directive for the completion script to parse. - // The directive integer must be that last character following a single colon (:). - // The completion script expects : - fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive) - - // Print some helpful info to stderr for the user to understand. - // Output from stderr must be ignored by the completion script. - fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) - }, - } - c.AddCommand(completeCmd) - subCmd, _, err := c.Find(args) - if err != nil || subCmd.Name() != ShellCompRequestCmd { - // Only create this special command if it is actually being called. - // This reduces possible side-effects of creating such a command; - // for example, having this command would cause problems to a - // cobra program that only consists of the root command, since this - // command would cause the root command to suddenly have a subcommand. - c.RemoveCommand(completeCmd) - } -} - -func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { - // The last argument, which is not completely typed by the user, - // should not be part of the list of arguments - toComplete := args[len(args)-1] - trimmedArgs := args[:len(args)-1] - - var finalCmd *Command - var finalArgs []string - var err error - // Find the real command for which completion must be performed - // check if we need to traverse here to parse local flags on parent commands - if c.Root().TraverseChildren { - finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) - } else { - finalCmd, finalArgs, err = c.Root().Find(trimmedArgs) - } - if err != nil { - // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs) - } - finalCmd.ctx = c.ctx - - // Check if we are doing flag value completion before parsing the flags. - // This is important because if we are completing a flag value, we need to also - // remove the flag name argument from the list of finalArgs or else the parsing - // could fail due to an invalid value (incomplete) for the flag. - flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) - - // Check if interspersed is false or -- was set on a previous arg. - // This works by counting the arguments. Normally -- is not counted as arg but - // if -- was already set or interspersed is false and there is already one arg then - // the extra added -- is counted as arg. - flagCompletion := true - _ = finalCmd.ParseFlags(append(finalArgs, "--")) - newArgCount := finalCmd.Flags().NArg() - - // Parse the flags early so we can check if required flags are set - if err = finalCmd.ParseFlags(finalArgs); err != nil { - return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) - } - - realArgCount := finalCmd.Flags().NArg() - if newArgCount > realArgCount { - // don't do flag completion (see above) - flagCompletion = false - } - // Error while attempting to parse flags - if flagErr != nil { - // If error type is flagCompError and we don't want flagCompletion we should ignore the error - if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { - return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr - } - } - - if flag != nil && flagCompletion { - // Check if we are completing a flag value subject to annotations - if validExts, present := flag.Annotations[BashCompFilenameExt]; present { - if len(validExts) != 0 { - // File completion filtered by extensions - return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil - } - - // The annotation requests simple file completion. There is no reason to do - // that since it is the default behavior anyway. Let's ignore this annotation - // in case the program also registered a completion function for this flag. - // Even though it is a mistake on the program's side, let's be nice when we can. - } - - if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { - if len(subDir) == 1 { - // Directory completion from within a directory - return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil - } - // Directory completion - return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil - } - } - - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires - // the flag name to be complete - if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { - var completions []string - - // First check for required flags - completions = completeRequireFlags(finalCmd, toComplete) - - // If we have not found any required flags, only then can we show regular flags - if len(completions) == 0 { - doCompleteFlags := func(flag *pflag.Flag) { - if !flag.Changed || - strings.Contains(flag.Value.Type(), "Slice") || - strings.Contains(flag.Value.Type(), "Array") { - // If the flag is not already present, or if it can be specified multiple times (Array or Slice) - // we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - } - - directive := ShellCompDirectiveNoFileComp - if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { - // If there is a single completion, the shell usually adds a space - // after the completion. We don't want that if the flag ends with an = - directive = ShellCompDirectiveNoSpace - } - return finalCmd, completions, directive, nil - } - - // We only remove the flags from the arguments if DisableFlagParsing is not set. - // This is important for commands which have requested to do their own flag completion. - if !finalCmd.DisableFlagParsing { - finalArgs = finalCmd.Flags().Args() - } - - var completions []string - directive := ShellCompDirectiveDefault - if flag == nil { - foundLocalNonPersistentFlag := false - // If TraverseChildren is true on the root command we don't check for - // local flags because we can use a local flag on a parent command - if !finalCmd.Root().TraverseChildren { - // Check if there are any local, non-persistent flags on the command-line - localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { - foundLocalNonPersistentFlag = true - } - }) - } - - // Complete subcommand names, including the help command - if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { - // We only complete sub-commands if: - // - there are no arguments on the command-line and - // - there are no local, non-persistent flags on the command-line or TraverseChildren is true - for _, subCmd := range finalCmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - directive = ShellCompDirectiveNoFileComp - } - } - } - - // Complete required flags even without the '-' prefix - completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) - - // Always complete ValidArgs, even if we are completing a subcommand name. - // This is for commands that have both subcommands and ValidArgs. - if len(finalCmd.ValidArgs) > 0 { - if len(finalArgs) == 0 { - // ValidArgs are only for the first argument - for _, validArg := range finalCmd.ValidArgs { - if strings.HasPrefix(validArg, toComplete) { - completions = append(completions, validArg) - } - } - directive = ShellCompDirectiveNoFileComp - - // If no completions were found within commands or ValidArgs, - // see if there are any ArgAliases that should be completed. - if len(completions) == 0 { - for _, argAlias := range finalCmd.ArgAliases { - if strings.HasPrefix(argAlias, toComplete) { - completions = append(completions, argAlias) - } - } - } - } - - // If there are ValidArgs specified (even if they don't match), we stop completion. - // Only one of ValidArgs or ValidArgsFunction can be used for a single command. - return finalCmd, completions, directive, nil - } - - // Let the logic continue so as to add any ValidArgsFunction completions, - // even if we already found sub-commands. - // This is for commands that have subcommands but also specify a ValidArgsFunction. - } - - // Find the completion function for the flag or command - var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - if flag != nil && flagCompletion { - flagCompletionMutex.RLock() - completionFn = flagCompletionFunctions[flag] - flagCompletionMutex.RUnlock() - } else { - completionFn = finalCmd.ValidArgsFunction - } - if completionFn != nil { - // Go custom completion defined for this flag or command. - // Call the registered completion function to get the completions. - var comps []string - comps, directive = completionFn(finalCmd, finalArgs, toComplete) - completions = append(completions, comps...) - } - - return finalCmd, completions, directive, nil -} - -func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { - if nonCompletableFlag(flag) { - return []string{} - } - - var completions []string - flagName := "--" + flag.Name - if strings.HasPrefix(flagName, toComplete) { - // Flag without the = - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - - // Why suggest both long forms: --flag and --flag= ? - // This forces the user to *always* have to type either an = or a space after the flag name. - // Let's be nice and avoid making users have to do that. - // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. - // The = form will still work, we just won't suggest it. - // This also makes the list of suggested flags shorter as we avoid all the = forms. - // - // if len(flag.NoOptDefVal) == 0 { - // // Flag requires a value, so it can be suffixed with = - // flagName += "=" - // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - // } - } - - flagName = "-" + flag.Shorthand - if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - } - - return completions -} - -func completeRequireFlags(finalCmd *Command, toComplete string) []string { - var completions []string - - doCompleteRequiredFlags := func(flag *pflag.Flag) { - if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { - if !flag.Changed { - // If the flag is not already present, we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - - return completions -} - -func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { - if finalCmd.DisableFlagParsing { - // We only do flag completion if we are allowed to parse flags - // This is important for commands which have requested to do their own flag completion. - return nil, args, lastArg, nil - } - - var flagName string - trimmedArgs := args - flagWithEqual := false - orgLastArg := lastArg - - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as that function - // requires the flag name to be complete - if len(lastArg) > 0 && lastArg[0] == '-' { - if index := strings.Index(lastArg, "="); index >= 0 { - // Flag with an = - if strings.HasPrefix(lastArg[:index], "--") { - // Flag has full name - flagName = lastArg[2:index] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = lastArg[index-1 : index] - } - lastArg = lastArg[index+1:] - flagWithEqual = true - } else { - // Normal flag completion - return nil, args, lastArg, nil - } - } - - if len(flagName) == 0 { - if len(args) > 0 { - prevArg := args[len(args)-1] - if isFlagArg(prevArg) { - // Only consider the case where the flag does not contain an =. - // If the flag contains an = it means it has already been fully processed, - // so we don't need to deal with it here. - if index := strings.Index(prevArg, "="); index < 0 { - if strings.HasPrefix(prevArg, "--") { - // Flag has full name - flagName = prevArg[2:] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = prevArg[len(prevArg)-1:] - } - // Remove the uncompleted flag or else there could be an error created - // for an invalid value for that flag - trimmedArgs = args[:len(args)-1] - } - } - } - } - - if len(flagName) == 0 { - // Not doing flag completion - return nil, trimmedArgs, lastArg, nil - } - - flag := findFlag(finalCmd, flagName) - if flag == nil { - // Flag not supported by this command, the interspersed option might be set so return the original args - return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} - } - - if !flagWithEqual { - if len(flag.NoOptDefVal) != 0 { - // We had assumed dealing with a two-word flag but the flag is a boolean flag. - // In that case, there is no value following it, so we are not really doing flag completion. - // Reset everything to do noun completion. - trimmedArgs = args - flag = nil - } - } - - return flag, trimmedArgs, lastArg, nil -} - -// initDefaultCompletionCmd adds a default 'completion' command to c. -// This function will do nothing if any of the following is true: -// 1- the feature has been explicitly disabled by the program, -// 2- c has no subcommands (to avoid creating one), -// 3- c already has a 'completion' command provided by the program. -func (c *Command) initDefaultCompletionCmd() { - if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { - return - } - - for _, cmd := range c.commands { - if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { - // A completion command is already available - return - } - } - - haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions - - completionCmd := &Command{ - Use: compCmdName, - Short: "generate the autocompletion script for the specified shell", - Long: fmt.Sprintf(` -Generate the autocompletion script for %[1]s for the specified shell. -See each sub-command's help for details on how to use the generated script. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - } - c.AddCommand(completionCmd) - - out := c.OutOrStdout() - noDesc := c.CompletionOptions.DisableDescriptions - shortDesc := "generate the autocompletion script for %s" - bash := &Command{ - Use: "bash", - Short: fmt.Sprintf(shortDesc, "bash"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the bash shell. - -This script depends on the 'bash-completion' package. -If it is not installed already, you can install it via your OS's package manager. - -To load completions in your current shell session: -$ source <(%[1]s completion bash) - -To load completions for every new session, execute once: -Linux: - $ %[1]s completion bash > /etc/bash_completion.d/%[1]s -MacOS: - $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s - -You will need to start a new shell for this setup to take effect. - `, c.Root().Name()), - Args: NoArgs, - DisableFlagsInUseLine: true, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenBashCompletionV2(out, !noDesc) - }, - } - if haveNoDescFlag { - bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - zsh := &Command{ - Use: "zsh", - Short: fmt.Sprintf(shortDesc, "zsh"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the zsh shell. - -If shell completion is not already enabled in your environment you will need -to enable it. You can execute the following once: - -$ echo "autoload -U compinit; compinit" >> ~/.zshrc - -To load completions for every new session, execute once: -# Linux: -$ %[1]s completion zsh > "${fpath[1]}/_%[1]s" -# macOS: -$ %[1]s completion zsh > /usr/local/share/zsh/site-functions/_%[1]s - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenZshCompletionNoDesc(out) - } - return cmd.Root().GenZshCompletion(out) - }, - } - if haveNoDescFlag { - zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - fish := &Command{ - Use: "fish", - Short: fmt.Sprintf(shortDesc, "fish"), - Long: fmt.Sprintf(` -Generate the autocompletion script for the fish shell. - -To load completions in your current shell session: -$ %[1]s completion fish | source - -To load completions for every new session, execute once: -$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenFishCompletion(out, !noDesc) - }, - } - if haveNoDescFlag { - fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - powershell := &Command{ - Use: "powershell", - Short: fmt.Sprintf(shortDesc, "powershell"), - Long: fmt.Sprintf(` -Generate the autocompletion script for powershell. - -To load completions in your current shell session: -PS C:\> %[1]s completion powershell | Out-String | Invoke-Expression - -To load completions for every new session, add the output of the above command -to your powershell profile. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenPowerShellCompletion(out) - } - return cmd.Root().GenPowerShellCompletionWithDesc(out) - - }, - } - if haveNoDescFlag { - powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - completionCmd.AddCommand(bash, zsh, fish, powershell) -} - -func findFlag(cmd *Command, name string) *pflag.Flag { - flagSet := cmd.Flags() - if len(name) == 1 { - // First convert the short flag into a long flag - // as the cmd.Flag() search only accepts long flags - if short := flagSet.ShorthandLookup(name); short != nil { - name = short.Name - } else { - set := cmd.InheritedFlags() - if short = set.ShorthandLookup(name); short != nil { - name = short.Name - } else { - return nil - } - } - } - return cmd.Flag(name) -} - -// CompDebug prints the specified string to the same file as where the -// completion script prints its logs. -// Note that completion printouts should never be on stdout as they would -// be wrongly interpreted as actual completion choices by the completion script. -func CompDebug(msg string, printToStdErr bool) { - msg = fmt.Sprintf("[Debug] %s", msg) - - // Such logs are only printed when the user has set the environment - // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. - if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { - f, err := os.OpenFile(path, - os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err == nil { - defer f.Close() - WriteStringAndCheck(f, msg) - } - } - - if printToStdErr { - // Must print to stderr for this not to be read by the completion script. - fmt.Fprint(os.Stderr, msg) - } -} - -// CompDebugln prints the specified string with a newline at the end -// to the same file as where the completion script prints its logs. -// Such logs are only printed when the user has set the environment -// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. -func CompDebugln(msg string, printToStdErr bool) { - CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) -} - -// CompError prints the specified completion message to stderr. -func CompError(msg string) { - msg = fmt.Sprintf("[Error] %s", msg) - CompDebug(msg, true) -} - -// CompErrorln prints the specified completion message to stderr with a newline at the end. -func CompErrorln(msg string) { - CompError(fmt.Sprintf("%s\n", msg)) -} diff --git a/examples/vendor/github.com/spf13/cobra/fish_completions.go b/examples/vendor/github.com/spf13/cobra/fish_completions.go deleted file mode 100644 index bb57fd5..0000000 --- a/examples/vendor/github.com/spf13/cobra/fish_completions.go +++ /dev/null @@ -1,219 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -func genFishComp(buf io.StringWriter, name string, includeDesc bool) { - // Variables should not contain a '-' or ':' character - nameForVar := name - nameForVar = strings.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) - - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -function __%[1]s_debug - set -l file "$BASH_COMP_DEBUG_FILE" - if test -n "$file" - echo "$argv" >> $file - end -end - -function __%[1]s_perform_completion - __%[1]s_debug "Starting __%[1]s_perform_completion" - - # Extract all args except the last one - set -l args (commandline -opc) - # Extract the last arg and escape it in case it is a space - set -l lastArg (string escape -- (commandline -ct)) - - __%[1]s_debug "args: $args" - __%[1]s_debug "last arg: $lastArg" - - set -l requestComp "$args[1] %[3]s $args[2..-1] $lastArg" - - __%[1]s_debug "Calling $requestComp" - set -l results (eval $requestComp 2> /dev/null) - - # Some programs may output extra empty lines after the directive. - # Let's ignore them or else it will break completion. - # Ref: https://github.com/spf13/cobra/issues/1279 - for line in $results[-1..1] - if test (string trim -- $line) = "" - # Found an empty line, remove it - set results $results[1..-2] - else - # Found non-empty line, we have our proper output - break - end - end - - set -l comps $results[1..-2] - set -l directiveLine $results[-1] - - # For Fish, when completing a flag with an = (e.g., -n=) - # completions must be prefixed with the flag - set -l flagPrefix (string match -r -- '-.*=' "$lastArg") - - __%[1]s_debug "Comps: $comps" - __%[1]s_debug "DirectiveLine: $directiveLine" - __%[1]s_debug "flagPrefix: $flagPrefix" - - for comp in $comps - printf "%%s%%s\n" "$flagPrefix" "$comp" - end - - printf "%%s\n" "$directiveLine" -end - -# This function does two things: -# - Obtain the completions and store them in the global __%[1]s_comp_results -# - Return false if file completion should be performed -function __%[1]s_prepare_completions - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - - # Start fresh - set --erase __%[1]s_comp_results - - set -l results (__%[1]s_perform_completion) - __%[1]s_debug "Completion results: $results" - - if test -z "$results" - __%[1]s_debug "No completion, probably due to a failure" - # Might as well do file completion, in case it helps - return 1 - end - - set -l directive (string sub --start 2 $results[-1]) - set --global __%[1]s_comp_results $results[1..-2] - - __%[1]s_debug "Completions are: $__%[1]s_comp_results" - __%[1]s_debug "Directive is: $directive" - - set -l shellCompDirectiveError %[4]d - set -l shellCompDirectiveNoSpace %[5]d - set -l shellCompDirectiveNoFileComp %[6]d - set -l shellCompDirectiveFilterFileExt %[7]d - set -l shellCompDirectiveFilterDirs %[8]d - - if test -z "$directive" - set directive 0 - end - - set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) - if test $compErr -eq 1 - __%[1]s_debug "Received error directive: aborting." - # Might as well do file completion, in case it helps - return 1 - end - - set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) - set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) - if test $filefilter -eq 1; or test $dirfilter -eq 1 - __%[1]s_debug "File extension filtering or directory filtering not supported" - # Do full file completion instead - return 1 - end - - set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) - set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) - - __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" - - # If we want to prevent a space, or if file completion is NOT disabled, - # we need to count the number of valid completions. - # To do so, we will filter on prefix as the completions we have received - # may not already be filtered so as to allow fish to match on different - # criteria than the prefix. - if test $nospace -ne 0; or test $nofiles -eq 0 - set -l prefix (commandline -t | string escape --style=regex) - __%[1]s_debug "prefix: $prefix" - - set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) - set --global __%[1]s_comp_results $completions - __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" - - # Important not to quote the variable for count to work - set -l numComps (count $__%[1]s_comp_results) - __%[1]s_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # We must first split on \t to get rid of the descriptions to be - # able to check what the actual completion will be. - # We don't need descriptions anyway since there is only a single - # real completion which the shell will expand immediately. - set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) - - # Fish won't add a space if the completion ends with any - # of the following characters: @=/:., - set -l lastChar (string sub -s -1 -- $split) - if not string match -r -q "[@=/:.,]" -- "$lastChar" - # In other cases, to support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __%[1]s_debug "Adding second completion to perform nospace directive" - set --global __%[1]s_comp_results $split[1] $split[1]. - __%[1]s_debug "Completions are now: $__%[1]s_comp_results" - end - end - - if test $numComps -eq 0; and test $nofiles -eq 0 - # To be consistent with bash and zsh, we only trigger file - # completion when there are no other completions - __%[1]s_debug "Requesting file completion" - return 1 - end - end - - return 0 -end - -# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves -# so we can properly delete any completions provided by another script. -# Only do this if the program can be found, or else fish may print some errors; besides, -# the existing completions will only be loaded if the program can be found. -if type -q "%[2]s" - # The space after the program name is essential to trigger completion for the program - # and not completion of the program name itself. - # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. - complete --do-complete "%[2]s " > /dev/null 2>&1 -end - -# Remove any pre-existing completions for the program since we will be handling all of them. -complete -c %[2]s -e - -# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results -# which provides the program's completion choices. -complete -c %[2]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' - -`, nameForVar, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -// GenFishCompletion generates fish completion file and writes to the passed writer. -func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genFishComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -// GenFishCompletionFile generates fish completion file. -func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenFishCompletion(outFile, includeDesc) -} diff --git a/examples/vendor/github.com/spf13/cobra/fish_completions.md b/examples/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed1..0000000 --- a/examples/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/examples/vendor/github.com/spf13/cobra/powershell_completions.go b/examples/vendor/github.com/spf13/cobra/powershell_completions.go deleted file mode 100644 index 59234c0..0000000 --- a/examples/vendor/github.com/spf13/cobra/powershell_completions.go +++ /dev/null @@ -1,285 +0,0 @@ -// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but -// can be downloaded separately for windows 7 or 8.1). - -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*- - -function __%[1]s_debug { - if ($env:BASH_COMP_DEBUG_FILE) { - "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" - } -} - -filter __%[1]s_escapeStringWithSpecialChars { -`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` -} - -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock { - param( - $WordToComplete, - $CommandAst, - $CursorPosition - ) - - # Get the current command line and convert into a string - $Command = $CommandAst.CommandElements - $Command = "$Command" - - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CursorPosition location, so we need - # to truncate the command-line ($Command) up to the $CursorPosition location. - # Make sure the $Command is longer then the $CursorPosition before we truncate. - # This happens because the $Command does not include the last space. - if ($Command.Length -gt $CursorPosition) { - $Command=$Command.Substring(0,$CursorPosition) - } - __%[1]s_debug "Truncated command: $Command" - - $ShellCompDirectiveError=%[3]d - $ShellCompDirectiveNoSpace=%[4]d - $ShellCompDirectiveNoFileComp=%[5]d - $ShellCompDirectiveFilterFileExt=%[6]d - $ShellCompDirectiveFilterDirs=%[7]d - - # Prepare the command to request completions for the program. - # Split the command at the first space to separate the program and arguments. - $Program,$Arguments = $Command.Split(" ",2) - $RequestComp="$Program %[2]s $Arguments" - __%[1]s_debug "RequestComp: $RequestComp" - - # we cannot use $WordToComplete because it - # has the wrong values if the cursor was moved - # so use the last argument - if ($WordToComplete -ne "" ) { - $WordToComplete = $Arguments.Split(" ")[-1] - } - __%[1]s_debug "New WordToComplete: $WordToComplete" - - - # Check for flag with equal sign - $IsEqualFlag = ($WordToComplete -Like "--*=*" ) - if ( $IsEqualFlag ) { - __%[1]s_debug "Completing equal sign flag" - # Remove the flag part - $Flag,$WordToComplete = $WordToComplete.Split("=",2) - } - - if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" -`+" # We need to use `\"`\" to pass an empty argument a \"\" or '' does not work!!!"+` -`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` - } - - __%[1]s_debug "Calling $RequestComp" - #call the command store the output in $out and redirect stderr and stdout to null - # $Out is an array contains each line per element - Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null - - - # get directive from last line - [int]$Directive = $Out[-1].TrimStart(':') - if ($Directive -eq "") { - # There is no directive specified - $Directive = 0 - } - __%[1]s_debug "The completion directive is: $Directive" - - # remove directive (last element) from out - $Out = $Out | Where-Object { $_ -ne $Out[-1] } - __%[1]s_debug "The completions are: $Out" - - if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - } - - $Longest = 0 - $Values = $Out | ForEach-Object { - #Split the output in name and description -`+" $Name, $Description = $_.Split(\"`t\",2)"+` - __%[1]s_debug "Name: $Name Description: $Description" - - # Look for the longest completion so that we can format things nicely - if ($Longest -lt $Name.Length) { - $Longest = $Name.Length - } - - # Set the description to a one space string if there is none set. - # This is needed because the CompletionResult does not accept an empty string as argument - if (-Not $Description) { - $Description = " " - } - @{Name="$Name";Description="$Description"} - } - - - $Space = " " - if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { - # remove the space here - __%[1]s_debug "ShellCompDirectiveNoSpace is called" - $Space = "" - } - - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or - (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { - __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" - - # return here to prevent the completion of the extensions - return - } - - $Values = $Values | Where-Object { - # filter the result - $_.Name -like "$WordToComplete*" - - # Join the flag back if we have an equal sign flag - if ( $IsEqualFlag ) { - __%[1]s_debug "Join the equal sign flag back to the completion value" - $_.Name = $Flag + "=" + $_.Name - } - } - - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __%[1]s_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - - # Get the current mode - $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function - __%[1]s_debug "Mode: $Mode" - - $Values | ForEach-Object { - - # store temporary because switch will overwrite $_ - $comp = $_ - - # PowerShell supports three different completion modes - # - TabCompleteNext (default windows style - on each key press the next option is displayed) - # - Complete (works like bash) - # - MenuComplete (works like zsh) - # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function - - # CompletionResult Arguments: - # 1) CompletionText text to be used as the auto completion result - # 2) ListItemText text to be displayed in the suggestion list - # 3) ResultType type of completion result - # 4) ToolTip text for the tooltip with details about the object - - switch ($Mode) { - - # bash like - "Complete" { - - if ($Values.Length -eq 1) { - __%[1]s_debug "Only one completion left" - - # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } else { - # Add the proper number of spaces to align the descriptions - while($comp.Name.Length -lt $Longest) { - $comp.Name = $comp.Name + " " - } - - # Check for empty description and only add parentheses if needed - if ($($comp.Description) -eq " " ) { - $Description = "" - } else { - $Description = " ($($comp.Description))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # TabCompleteNext and in case we get something unknown - Default { - # Like MenuComplete but we don't want to add a space here because - # the user need to press space anyway to get the completion. - # Description will not be shown because thats not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - } - - } -} -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} - -func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genPowerShellComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genPowerShellCompletion(outFile, includeDesc) -} - -// GenPowerShellCompletionFile generates powershell completion file without descriptions. -func (c *Command) GenPowerShellCompletionFile(filename string) error { - return c.genPowerShellCompletionFile(filename, false) -} - -// GenPowerShellCompletion generates powershell completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletion(w io.Writer) error { - return c.genPowerShellCompletion(w, false) -} - -// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. -func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error { - return c.genPowerShellCompletionFile(filename, true) -} - -// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error { - return c.genPowerShellCompletion(w, true) -} diff --git a/examples/vendor/github.com/spf13/cobra/powershell_completions.md b/examples/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e..0000000 --- a/examples/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/examples/vendor/github.com/spf13/cobra/projects_using_cobra.md b/examples/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index d98a71e..0000000 --- a/examples/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,38 +0,0 @@ -## Projects using Cobra - -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](http://www.blevesearch.com/) -- [CockroachDB](http://www.cockroachlabs.com/) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [Github CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](http://www.gopherjs.org/) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](http://kubernetes.io/) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](http://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [Werf](https://werf.io/) diff --git a/examples/vendor/github.com/spf13/cobra/shell_completions.go b/examples/vendor/github.com/spf13/cobra/shell_completions.go deleted file mode 100644 index d99bf91..0000000 --- a/examples/vendor/github.com/spf13/cobra/shell_completions.go +++ /dev/null @@ -1,84 +0,0 @@ -package cobra - -import ( - "github.com/spf13/pflag" -) - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(c.Flags(), name) -} - -// MarkPersistentFlagRequired instructs the various shell completion implementations to -// prioritize the named persistent flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkPersistentFlagRequired(name string) error { - return MarkFlagRequired(c.PersistentFlags(), name) -} - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func MarkFlagRequired(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func (c *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.Flags(), name, extensions...) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func (c *Command) MarkFlagCustom(name string, f string) error { - return MarkFlagCustom(c.Flags(), name, f) -} - -// MarkPersistentFlagFilename instructs the various shell completion -// implementations to limit completions for the named persistent flag to the -// specified file extensions. -func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.PersistentFlags(), name, extensions...) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { - return flags.SetAnnotation(name, BashCompFilenameExt, extensions) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { - return flags.SetAnnotation(name, BashCompCustom, []string{f}) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func (c *Command) MarkFlagDirname(name string) error { - return MarkFlagDirname(c.Flags(), name) -} - -// MarkPersistentFlagDirname instructs the various shell completion -// implementations to limit completions for the named persistent flag to -// directory names. -func (c *Command) MarkPersistentFlagDirname(name string) error { - return MarkFlagDirname(c.PersistentFlags(), name) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func MarkFlagDirname(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{}) -} diff --git a/examples/vendor/github.com/spf13/cobra/shell_completions.md b/examples/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 4ba06a1..0000000 --- a/examples/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,546 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the generator, you can create a completion command by running - -```bash -cobra add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: `To load completions: - -Bash: - - $ source <(yourprogram completion bash) - - # To load completions for each session, execute once: - # Linux: - $ yourprogram completion bash > /etc/bash_completion.d/yourprogram - # macOS: - $ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram - -Zsh: - - # If shell completion is not already enabled in your environment, - # you will need to enable it. You can execute the following once: - - $ echo "autoload -U compinit; compinit" >> ~/.zshrc - - # To load completions for each session, execute once: - $ yourprogram completion zsh > "${fpath[1]}/_yourprogram" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ yourprogram completion fish | source - - # To load completions for each session, execute once: - $ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish - -PowerShell: - - PS> yourprogram completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> yourprogram completion powershell > yourprogram.ps1 - # and source this file from your PowerShell profile. -`, - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.ExactValidArgs(1), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs []string = { "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by -the completion algorithm if entered manually, e.g. in: - -```bash -$ kubectl get rc [tab][tab] -backend frontend database -``` - -Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of -replication controllers following `rc`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell completion modes: - -* TabCompleteNext (default windows style - on each key press the next option is displayed) -* Complete (works like bash) -* MenuComplete (works like zsh) - -You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/examples/vendor/github.com/spf13/cobra/user_guide.md b/examples/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index 311abce..0000000 --- a/examples/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,637 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra provides its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it. - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at http://hugo.spf13.com`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is not provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field -of `Command`. - -The following validators are built in: - -- `NoArgs` - the command will report an error if there are any positional args. -- `ArbitraryArgs` - the command will accept any args. -- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`. -- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args. -- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args. -- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args. -- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command` -- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args. - -An example of setting the custom validator: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - if len(args) < 1 { - return errors.New("requires a color argument") - } - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra --invalid - Error: unknown flag: --invalid - Usage: - cobra [command] - - Available Commands: - add Add a command to a Cobra Application - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra - -l, --license string name of license for the project - --viper use Viper for configuration (default true) - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). diff --git a/examples/vendor/github.com/spf13/cobra/zsh_completions.go b/examples/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 1afec30..0000000 --- a/examples/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,258 +0,0 @@ -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// GenZshCompletionFile generates zsh completion file including descriptions. -func (c *Command) GenZshCompletionFile(filename string) error { - return c.genZshCompletionFile(filename, true) -} - -// GenZshCompletion generates zsh completion file including descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletion(w io.Writer) error { - return c.genZshCompletion(w, true) -} - -// GenZshCompletionFileNoDesc generates zsh completion file without descriptions. -func (c *Command) GenZshCompletionFileNoDesc(filename string) error { - return c.genZshCompletionFile(filename, false) -} - -// GenZshCompletionNoDesc generates zsh completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletionNoDesc(w io.Writer) error { - return c.genZshCompletion(w, false) -} - -// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was -// not consistent with Bash completion. It has therefore been disabled. -// Instead, when no other completion is specified, file completion is done by -// default for every argument. One can disable file completion on a per-argument -// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. -// To achieve file extension filtering, one can use ValidArgsFunction and -// ShellCompDirectiveFilterFileExt. -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error { - return nil -} - -// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore -// been disabled. -// To achieve the same behavior across all shells, one can use -// ValidArgs (for the first argument only) or ValidArgsFunction for -// any argument (can include the first one also). -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error { - return nil -} - -func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genZshCompletion(outFile, includeDesc) -} - -func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genZshComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genZshComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s - -# zsh completion for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - local file="$BASH_COMP_DEBUG_FILE" - if [[ -n ${file} ]]; then - echo "$*" >> "${file}" - fi -} - -_%[1]s() -{ - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace - local -a completions - - __%[1]s_debug "\n========= starting completion logic ==========" - __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CURRENT location, so we need - # to truncate the command-line ($words) up to the $CURRENT location. - # (We cannot use $CURSOR as its value does not work when a command is an alias.) - words=("${=words[1,CURRENT]}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - lastParam=${words[-1]} - lastChar=${lastParam[-1]} - __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" - - # For zsh, when completing a flag with an = (e.g., %[1]s -n=) - # completions must be prefixed with the flag - setopt local_options BASH_REMATCH - if [[ "${lastParam}" =~ '-.*=' ]]; then - # We are dealing with a flag with an = - flagPrefix="-P ${BASH_REMATCH}" - fi - - # Prepare the command to obtain completions - requestComp="${words[1]} %[2]s ${words[2,-1]}" - if [ "${lastChar}" = "" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go completion code. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "About to call: eval ${requestComp}" - - # Use eval to handle any environment variables and such - out=$(eval ${requestComp} 2>/dev/null) - __%[1]s_debug "completion output: ${out}" - - # Extract the directive integer following a : from the last line - local lastLine - while IFS='\n' read -r line; do - lastLine=${line} - done < <(printf "%%s\n" "${out[@]}") - __%[1]s_debug "last line: ${lastLine}" - - if [ "${lastLine[1]}" = : ]; then - directive=${lastLine[2,-1]} - # Remove the directive including the : and the newline - local suffix - (( suffix=${#lastLine}+2)) - out=${out[1,-$suffix]} - else - # There is no directive specified. Leave $out as is. - __%[1]s_debug "No directive found. Setting do default" - directive=0 - fi - - __%[1]s_debug "directive: ${directive}" - __%[1]s_debug "completions: ${out}" - __%[1]s_debug "flagPrefix: ${flagPrefix}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - __%[1]s_debug "Completion received error. Ignoring completions." - return - fi - - while IFS='\n' read -r comp; do - if [ -n "$comp" ]; then - # If requested, completions are returned with a description. - # The description is preceded by a TAB character. - # For zsh's _describe, we need to use a : instead of a TAB. - # We first need to escape any : as part of the completion itself. - comp=${comp//:/\\:} - - local tab=$(printf '\t') - comp=${comp//$tab/:} - - __%[1]s_debug "Adding completion: ${comp}" - completions+=${comp} - lastComp=$comp - fi - done < <(printf "%%s\n" "${out[@]}") - - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - __%[1]s_debug "Activating nospace." - noSpace="-S ''" - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local filteringCmd - filteringCmd='_files' - for filter in ${completions[@]}; do - if [ ${filter[1]} != '*' ]; then - # zsh requires a glob pattern to do file filtering - filter="\*.$filter" - fi - filteringCmd+=" -g $filter" - done - filteringCmd+=" ${flagPrefix}" - - __%[1]s_debug "File filtering command: $filteringCmd" - _arguments '*:filename:'"$filteringCmd" - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subDir - subdir="${completions[1]}" - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "${subdir}" >/dev/null 2>&1 - else - __%[1]s_debug "Listing directories in ." - fi - - local result - _arguments '*:dirname:_files -/'" ${flagPrefix}" - result=$? - if [ -n "$subdir" ]; then - popd >/dev/null 2>&1 - fi - return $result - else - __%[1]s_debug "Calling _describe" - if eval _describe "completions" completions $flagPrefix $noSpace; then - __%[1]s_debug "_describe found some completions" - - # Return the success of having called _describe - return 0 - else - __%[1]s_debug "_describe did not find completions." - __%[1]s_debug "Checking if we should do file completion." - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __%[1]s_debug "deactivating file completion" - - # We must return an error code here to let zsh know that there were no - # completions found by _describe; this is what will trigger other - # matching algorithms to attempt to find completions. - # For example zsh can match letters in the middle of words. - return 1 - else - # Perform file completion - __%[1]s_debug "Activating file completion" - - # We must return the result of this command, so it must be the - # last command, or else we must store its result to return it. - _arguments '*:filename:_files'" ${flagPrefix}" - fi - fi - fi -} - -# don't run the completion function when being source-ed or eval-ed -if [ "$funcstack[1]" = "_%[1]s" ]; then - _%[1]s -fi -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs)) -} diff --git a/examples/vendor/github.com/spf13/cobra/zsh_completions.md b/examples/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff617..0000000 --- a/examples/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/examples/vendor/github.com/vbauerster/mpb/v7/.travis.yml b/examples/vendor/github.com/vbauerster/mpb/v7/.travis.yml deleted file mode 100644 index 9a203a6..0000000 --- a/examples/vendor/github.com/vbauerster/mpb/v7/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: go -arch: - - amd64 - - ppc64le - -go: - - 1.14.x - -script: - - go test -race ./... - - for i in _examples/*/; do go build $i/*.go || exit 1; done diff --git a/examples/vendor/github.com/vbauerster/mpb/v7/internal/predicate.go b/examples/vendor/github.com/vbauerster/mpb/v7/internal/predicate.go deleted file mode 100644 index 1e4dd24..0000000 --- a/examples/vendor/github.com/vbauerster/mpb/v7/internal/predicate.go +++ /dev/null @@ -1,6 +0,0 @@ -package internal - -// Predicate helper for internal use. -func Predicate(pick bool) func() bool { - return func() bool { return pick } -} diff --git a/examples/vendor/github.com/vbauerster/mpb/v7/proxyreader.go b/examples/vendor/github.com/vbauerster/mpb/v7/proxyreader.go deleted file mode 100644 index 316f438..0000000 --- a/examples/vendor/github.com/vbauerster/mpb/v7/proxyreader.go +++ /dev/null @@ -1,90 +0,0 @@ -package mpb - -import ( - "io" - "io/ioutil" - "time" -) - -type proxyReader struct { - io.ReadCloser - bar *Bar -} - -func (x *proxyReader) Read(p []byte) (int, error) { - n, err := x.ReadCloser.Read(p) - x.bar.IncrBy(n) - if err == io.EOF { - go x.bar.SetTotal(0, true) - } - return n, err -} - -type proxyWriterTo struct { - io.ReadCloser // *proxyReader - wt io.WriterTo - bar *Bar -} - -func (x *proxyWriterTo) WriteTo(w io.Writer) (int64, error) { - n, err := x.wt.WriteTo(w) - x.bar.IncrInt64(n) - if err == io.EOF { - go x.bar.SetTotal(0, true) - } - return n, err -} - -type ewmaProxyReader struct { - io.ReadCloser // *proxyReader - bar *Bar - iT time.Time -} - -func (x *ewmaProxyReader) Read(p []byte) (int, error) { - n, err := x.ReadCloser.Read(p) - if n > 0 { - x.bar.DecoratorEwmaUpdate(time.Since(x.iT)) - x.iT = time.Now() - } - return n, err -} - -type ewmaProxyWriterTo struct { - io.ReadCloser // *ewmaProxyReader - wt io.WriterTo // *proxyWriterTo - bar *Bar - iT time.Time -} - -func (x *ewmaProxyWriterTo) WriteTo(w io.Writer) (int64, error) { - n, err := x.wt.WriteTo(w) - if n > 0 { - x.bar.DecoratorEwmaUpdate(time.Since(x.iT)) - x.iT = time.Now() - } - return n, err -} - -func newProxyReader(r io.Reader, bar *Bar) io.ReadCloser { - rc := toReadCloser(r) - rc = &proxyReader{rc, bar} - - if wt, isWriterTo := r.(io.WriterTo); bar.hasEwmaDecorators { - now := time.Now() - rc = &ewmaProxyReader{rc, bar, now} - if isWriterTo { - rc = &ewmaProxyWriterTo{rc, wt, bar, now} - } - } else if isWriterTo { - rc = &proxyWriterTo{rc, wt, bar} - } - return rc -} - -func toReadCloser(r io.Reader) io.ReadCloser { - if rc, ok := r.(io.ReadCloser); ok { - return rc - } - return ioutil.NopCloser(r) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/.gitignore b/examples/vendor/github.com/vishvananda/netlink/.gitignore deleted file mode 100644 index 9f11b75..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.idea/ diff --git a/examples/vendor/github.com/vishvananda/netlink/.travis.yml b/examples/vendor/github.com/vishvananda/netlink/.travis.yml deleted file mode 100644 index 80219c6..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: go -go: - - "1.12.x" - - "1.13.x" - - "1.14.x" -before_script: - # make sure we keep path in tact when we sudo - - sudo sed -i -e 's/^Defaults\tsecure_path.*$//' /etc/sudoers - # modprobe ip_gre or else the first gre device can't be deleted - - sudo modprobe ip_gre - # modprobe nf_conntrack for the conntrack testing - - sudo modprobe nf_conntrack - - sudo modprobe nf_conntrack_netlink - - sudo modprobe nf_conntrack_ipv4 - - sudo modprobe nf_conntrack_ipv6 - - sudo modprobe sch_hfsc - - sudo modprobe sch_sfq -install: - - go get -v -t ./... -go_import_path: github.com/vishvananda/netlink diff --git a/examples/vendor/github.com/vishvananda/netlink/CHANGELOG.md b/examples/vendor/github.com/vishvananda/netlink/CHANGELOG.md deleted file mode 100644 index b11e59f..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -# Changelog - -## 1.0.0 (2018-03-15) - -Initial release tagging \ No newline at end of file diff --git a/examples/vendor/github.com/vishvananda/netlink/LICENSE b/examples/vendor/github.com/vishvananda/netlink/LICENSE deleted file mode 100644 index 9f64db8..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/LICENSE +++ /dev/null @@ -1,192 +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 - - Copyright 2014 Vishvananda Ishaya. - Copyright 2014 Docker, 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. diff --git a/examples/vendor/github.com/vishvananda/netlink/Makefile b/examples/vendor/github.com/vishvananda/netlink/Makefile deleted file mode 100644 index a0e68e7..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -DIRS := \ - . \ - nl - -DEPS = \ - github.com/vishvananda/netns \ - golang.org/x/sys/unix - -uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1))) -testdirs = $(call uniq,$(foreach d,$(1),$(dir $(wildcard $(d)/*_test.go)))) -goroot = $(addprefix ../../../,$(1)) -unroot = $(subst ../../../,,$(1)) -fmt = $(addprefix fmt-,$(1)) - -all: test - -$(call goroot,$(DEPS)): - go get $(call unroot,$@) - -.PHONY: $(call testdirs,$(DIRS)) -$(call testdirs,$(DIRS)): - go test -test.exec sudo -test.parallel 4 -timeout 60s -test.v github.com/vishvananda/netlink/$@ - -$(call fmt,$(call testdirs,$(DIRS))): - ! gofmt -l $(subst fmt-,,$@)/*.go | grep -q . - -.PHONY: fmt -fmt: $(call fmt,$(call testdirs,$(DIRS))) - -test: fmt $(call goroot,$(DEPS)) $(call testdirs,$(DIRS)) diff --git a/examples/vendor/github.com/vishvananda/netlink/README.md b/examples/vendor/github.com/vishvananda/netlink/README.md deleted file mode 100644 index a88e2f4..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/README.md +++ /dev/null @@ -1,92 +0,0 @@ -# netlink - netlink library for go # - -[![Build Status](https://travis-ci.org/vishvananda/netlink.png?branch=master)](https://travis-ci.org/vishvananda/netlink) [![GoDoc](https://godoc.org/github.com/vishvananda/netlink?status.svg)](https://godoc.org/github.com/vishvananda/netlink) - -The netlink package provides a simple netlink library for go. Netlink -is the interface a user-space program in linux uses to communicate with -the kernel. It can be used to add and remove interfaces, set ip addresses -and routes, and configure ipsec. Netlink communication requires elevated -privileges, so in most cases this code needs to be run as root. Since -low-level netlink messages are inscrutable at best, the library attempts -to provide an api that is loosely modeled on the CLI provided by iproute2. -Actions like `ip link add` will be accomplished via a similarly named -function like AddLink(). This library began its life as a fork of the -netlink functionality in -[docker/libcontainer](https://github.com/docker/libcontainer) but was -heavily rewritten to improve testability, performance, and to add new -functionality like ipsec xfrm handling. - -## Local Build and Test ## - -You can use go get command: - - go get github.com/vishvananda/netlink - -Testing dependencies: - - go get github.com/vishvananda/netns - -Testing (requires root): - - sudo -E go test github.com/vishvananda/netlink - -## Examples ## - -Add a new bridge and add eth1 into it: - -```go -package main - -import ( - "fmt" - "github.com/vishvananda/netlink" -) - -func main() { - la := netlink.NewLinkAttrs() - la.Name = "foo" - mybridge := &netlink.Bridge{LinkAttrs: la} - err := netlink.LinkAdd(mybridge) - if err != nil { - fmt.Printf("could not add %s: %v\n", la.Name, err) - } - eth1, _ := netlink.LinkByName("eth1") - netlink.LinkSetMaster(eth1, mybridge) -} - -``` -Note `NewLinkAttrs` constructor, it sets default values in structure. For now -it sets only `TxQLen` to `-1`, so kernel will set default by itself. If you're -using simple initialization(`LinkAttrs{Name: "foo"}`) `TxQLen` will be set to -`0` unless you specify it like `LinkAttrs{Name: "foo", TxQLen: 1000}`. - -Add a new ip address to loopback: - -```go -package main - -import ( - "github.com/vishvananda/netlink" -) - -func main() { - lo, _ := netlink.LinkByName("lo") - addr, _ := netlink.ParseAddr("169.254.169.254/32") - netlink.AddrAdd(lo, addr) -} - -``` - -## Future Work ## - -Many pieces of netlink are not yet fully supported in the high-level -interface. Aspects of virtually all of the high-level objects don't exist. -Many of the underlying primitives are there, so its a matter of putting -the right fields into the high-level objects and making sure that they -are serialized and deserialized correctly in the Add and List methods. - -There are also a few pieces of low level netlink functionality that still -need to be implemented. Routing rules are not in place and some of the -more advanced link types. Hopefully there is decent structure and testing -in place to make these fairly straightforward to add. - diff --git a/examples/vendor/github.com/vishvananda/netlink/addr.go b/examples/vendor/github.com/vishvananda/netlink/addr.go deleted file mode 100644 index 653f540..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/addr.go +++ /dev/null @@ -1,57 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "strings" -) - -// Addr represents an IP address from netlink. Netlink ip addresses -// include a mask, so it stores the address as a net.IPNet. -type Addr struct { - *net.IPNet - Label string - Flags int - Scope int - Peer *net.IPNet - Broadcast net.IP - PreferedLft int - ValidLft int - LinkIndex int -} - -// String returns $ip/$netmask $label -func (a Addr) String() string { - return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label)) -} - -// ParseAddr parses the string representation of an address in the -// form $ip/$netmask $label. The label portion is optional -func ParseAddr(s string) (*Addr, error) { - label := "" - parts := strings.Split(s, " ") - if len(parts) > 1 { - s = parts[0] - label = parts[1] - } - m, err := ParseIPNet(s) - if err != nil { - return nil, err - } - return &Addr{IPNet: m, Label: label}, nil -} - -// Equal returns true if both Addrs have the same net.IPNet value. -func (a Addr) Equal(x Addr) bool { - sizea, _ := a.Mask.Size() - sizeb, _ := x.Mask.Size() - // ignore label for comparison - return a.IP.Equal(x.IP) && sizea == sizeb -} - -func (a Addr) PeerEqual(x Addr) bool { - sizea, _ := a.Peer.Mask.Size() - sizeb, _ := x.Peer.Mask.Size() - // ignore label for comparison - return a.Peer.IP.Equal(x.Peer.IP) && sizea == sizeb -} diff --git a/examples/vendor/github.com/vishvananda/netlink/addr_linux.go b/examples/vendor/github.com/vishvananda/netlink/addr_linux.go deleted file mode 100644 index 71da251..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/addr_linux.go +++ /dev/null @@ -1,414 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "strings" - "syscall" - - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -// AddrAdd will add an IP address to a link device. -// -// Equivalent to: `ip addr add $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func AddrAdd(link Link, addr *Addr) error { - return pkgHandle.AddrAdd(link, addr) -} - -// AddrAdd will add an IP address to a link device. -// -// Equivalent to: `ip addr add $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func (h *Handle) AddrAdd(link Link, addr *Addr) error { - req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) - return h.addrHandle(link, addr, req) -} - -// AddrReplace will replace (or, if not present, add) an IP address on a link device. -// -// Equivalent to: `ip addr replace $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func AddrReplace(link Link, addr *Addr) error { - return pkgHandle.AddrReplace(link, addr) -} - -// AddrReplace will replace (or, if not present, add) an IP address on a link device. -// -// Equivalent to: `ip addr replace $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func (h *Handle) AddrReplace(link Link, addr *Addr) error { - req := h.newNetlinkRequest(unix.RTM_NEWADDR, unix.NLM_F_CREATE|unix.NLM_F_REPLACE|unix.NLM_F_ACK) - return h.addrHandle(link, addr, req) -} - -// AddrDel will delete an IP address from a link device. -// -// Equivalent to: `ip addr del $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func AddrDel(link Link, addr *Addr) error { - return pkgHandle.AddrDel(link, addr) -} - -// AddrDel will delete an IP address from a link device. -// Equivalent to: `ip addr del $addr dev $link` -// -// If `addr` is an IPv4 address and the broadcast address is not given, it -// will be automatically computed based on the IP mask if /30 or larger. -func (h *Handle) AddrDel(link Link, addr *Addr) error { - req := h.newNetlinkRequest(unix.RTM_DELADDR, unix.NLM_F_ACK) - return h.addrHandle(link, addr, req) -} - -func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error { - base := link.Attrs() - if addr.Label != "" && !strings.HasPrefix(addr.Label, base.Name) { - return fmt.Errorf("label must begin with interface name") - } - h.ensureIndex(base) - - family := nl.GetIPFamily(addr.IP) - - msg := nl.NewIfAddrmsg(family) - msg.Index = uint32(base.Index) - msg.Scope = uint8(addr.Scope) - mask := addr.Mask - if addr.Peer != nil { - mask = addr.Peer.Mask - } - prefixlen, masklen := mask.Size() - msg.Prefixlen = uint8(prefixlen) - req.AddData(msg) - - var localAddrData []byte - if family == FAMILY_V4 { - localAddrData = addr.IP.To4() - } else { - localAddrData = addr.IP.To16() - } - - localData := nl.NewRtAttr(unix.IFA_LOCAL, localAddrData) - req.AddData(localData) - var peerAddrData []byte - if addr.Peer != nil { - if family == FAMILY_V4 { - peerAddrData = addr.Peer.IP.To4() - } else { - peerAddrData = addr.Peer.IP.To16() - } - } else { - peerAddrData = localAddrData - } - - addressData := nl.NewRtAttr(unix.IFA_ADDRESS, peerAddrData) - req.AddData(addressData) - - if addr.Flags != 0 { - if addr.Flags <= 0xff { - msg.IfAddrmsg.Flags = uint8(addr.Flags) - } else { - b := make([]byte, 4) - native.PutUint32(b, uint32(addr.Flags)) - flagsData := nl.NewRtAttr(unix.IFA_FLAGS, b) - req.AddData(flagsData) - } - } - - if family == FAMILY_V4 { - // Automatically set the broadcast address if it is unset and the - // subnet is large enough to sensibly have one (/30 or larger). - // See: RFC 3021 - if addr.Broadcast == nil && prefixlen < 31 { - calcBroadcast := make(net.IP, masklen/8) - for i := range localAddrData { - calcBroadcast[i] = localAddrData[i] | ^mask[i] - } - addr.Broadcast = calcBroadcast - } - - if addr.Broadcast != nil { - req.AddData(nl.NewRtAttr(unix.IFA_BROADCAST, addr.Broadcast)) - } - - if addr.Label != "" { - labelData := nl.NewRtAttr(unix.IFA_LABEL, nl.ZeroTerminated(addr.Label)) - req.AddData(labelData) - } - } - - // 0 is the default value for these attributes. However, 0 means "expired", while the least-surprising default - // value should be "forever". To compensate for that, only add the attributes if at least one of the values is - // non-zero, which means the caller has explicitly set them - if addr.ValidLft > 0 || addr.PreferedLft > 0 { - cachedata := nl.IfaCacheInfo{unix.IfaCacheinfo{ - Valid: uint32(addr.ValidLft), - Prefered: uint32(addr.PreferedLft), - }} - req.AddData(nl.NewRtAttr(unix.IFA_CACHEINFO, cachedata.Serialize())) - } - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// AddrList gets a list of IP addresses in the system. -// Equivalent to: `ip addr show`. -// The list can be filtered by link and ip family. -func AddrList(link Link, family int) ([]Addr, error) { - return pkgHandle.AddrList(link, family) -} - -// AddrList gets a list of IP addresses in the system. -// Equivalent to: `ip addr show`. -// The list can be filtered by link and ip family. -func (h *Handle) AddrList(link Link, family int) ([]Addr, error) { - req := h.newNetlinkRequest(unix.RTM_GETADDR, unix.NLM_F_DUMP) - msg := nl.NewIfInfomsg(family) - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWADDR) - if err != nil { - return nil, err - } - - indexFilter := 0 - if link != nil { - base := link.Attrs() - h.ensureIndex(base) - indexFilter = base.Index - } - - var res []Addr - for _, m := range msgs { - addr, msgFamily, err := parseAddr(m) - if err != nil { - return res, err - } - - if link != nil && addr.LinkIndex != indexFilter { - // Ignore messages from other interfaces - continue - } - - if family != FAMILY_ALL && msgFamily != family { - continue - } - - res = append(res, addr) - } - - return res, nil -} - -func parseAddr(m []byte) (addr Addr, family int, err error) { - msg := nl.DeserializeIfAddrmsg(m) - - family = -1 - addr.LinkIndex = -1 - - attrs, err1 := nl.ParseRouteAttr(m[msg.Len():]) - if err1 != nil { - err = err1 - return - } - - family = int(msg.Family) - addr.LinkIndex = int(msg.Index) - - var local, dst *net.IPNet - for _, attr := range attrs { - switch attr.Attr.Type { - case unix.IFA_ADDRESS: - dst = &net.IPNet{ - IP: attr.Value, - Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)), - } - case unix.IFA_LOCAL: - // iproute2 manual: - // If a peer address is specified, the local address - // cannot have a prefix length. The network prefix is - // associated with the peer rather than with the local - // address. - n := 8 * len(attr.Value) - local = &net.IPNet{ - IP: attr.Value, - Mask: net.CIDRMask(n, n), - } - case unix.IFA_BROADCAST: - addr.Broadcast = attr.Value - case unix.IFA_LABEL: - addr.Label = string(attr.Value[:len(attr.Value)-1]) - case unix.IFA_FLAGS: - addr.Flags = int(native.Uint32(attr.Value[0:4])) - case unix.IFA_CACHEINFO: - ci := nl.DeserializeIfaCacheInfo(attr.Value) - addr.PreferedLft = int(ci.Prefered) - addr.ValidLft = int(ci.Valid) - } - } - - // libnl addr.c comment: - // IPv6 sends the local address as IFA_ADDRESS with no - // IFA_LOCAL, IPv4 sends both IFA_LOCAL and IFA_ADDRESS - // with IFA_ADDRESS being the peer address if they differ - // - // But obviously, as there are IPv6 PtP addresses, too, - // IFA_LOCAL should also be handled for IPv6. - if local != nil { - if family == FAMILY_V4 && local.IP.Equal(dst.IP) { - addr.IPNet = dst - } else { - addr.IPNet = local - addr.Peer = dst - } - } else { - addr.IPNet = dst - } - - addr.Scope = int(msg.Scope) - - return -} - -type AddrUpdate struct { - LinkAddress net.IPNet - LinkIndex int - Flags int - Scope int - PreferedLft int - ValidLft int - NewAddr bool // true=added false=deleted -} - -// AddrSubscribe takes a chan down which notifications will be sent -// when addresses change. Close the 'done' chan to stop subscription. -func AddrSubscribe(ch chan<- AddrUpdate, done <-chan struct{}) error { - return addrSubscribeAt(netns.None(), netns.None(), ch, done, nil, false, 0) -} - -// AddrSubscribeAt works like AddrSubscribe plus it allows the caller -// to choose the network namespace in which to subscribe (ns). -func AddrSubscribeAt(ns netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}) error { - return addrSubscribeAt(ns, netns.None(), ch, done, nil, false, 0) -} - -// AddrSubscribeOptions contains a set of options to use with -// AddrSubscribeWithOptions. -type AddrSubscribeOptions struct { - Namespace *netns.NsHandle - ErrorCallback func(error) - ListExisting bool - ReceiveBufferSize int -} - -// AddrSubscribeWithOptions work like AddrSubscribe but enable to -// provide additional options to modify the behavior. Currently, the -// namespace can be provided as well as an error callback. -func AddrSubscribeWithOptions(ch chan<- AddrUpdate, done <-chan struct{}, options AddrSubscribeOptions) error { - if options.Namespace == nil { - none := netns.None() - options.Namespace = &none - } - return addrSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting, options.ReceiveBufferSize) -} - -func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-chan struct{}, cberr func(error), listExisting bool, rcvbuf int) error { - s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_IPV4_IFADDR, unix.RTNLGRP_IPV6_IFADDR) - if err != nil { - return err - } - if done != nil { - go func() { - <-done - s.Close() - }() - } - if rcvbuf != 0 { - err = pkgHandle.SetSocketReceiveBufferSize(rcvbuf, false) - if err != nil { - return err - } - } - if listExisting { - req := pkgHandle.newNetlinkRequest(unix.RTM_GETADDR, - unix.NLM_F_DUMP) - infmsg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(infmsg) - if err := s.Send(req); err != nil { - return err - } - } - go func() { - defer close(ch) - for { - msgs, from, err := s.Receive() - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - if from.Pid != nl.PidKernel { - if cberr != nil { - cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)) - } - continue - } - for _, m := range msgs { - if m.Header.Type == unix.NLMSG_DONE { - continue - } - if m.Header.Type == unix.NLMSG_ERROR { - native := nl.NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - if error == 0 { - continue - } - if cberr != nil { - cberr(fmt.Errorf("error message: %v", - syscall.Errno(-error))) - } - continue - } - msgType := m.Header.Type - if msgType != unix.RTM_NEWADDR && msgType != unix.RTM_DELADDR { - if cberr != nil { - cberr(fmt.Errorf("bad message type: %d", msgType)) - } - continue - } - - addr, _, err := parseAddr(m.Data) - if err != nil { - if cberr != nil { - cberr(fmt.Errorf("could not parse address: %v", err)) - } - continue - } - - ch <- AddrUpdate{LinkAddress: *addr.IPNet, - LinkIndex: addr.LinkIndex, - NewAddr: msgType == unix.RTM_NEWADDR, - Flags: addr.Flags, - Scope: addr.Scope, - PreferedLft: addr.PreferedLft, - ValidLft: addr.ValidLft} - } - } - }() - - return nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/bpf_linux.go b/examples/vendor/github.com/vishvananda/netlink/bpf_linux.go deleted file mode 100644 index 6631626..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/bpf_linux.go +++ /dev/null @@ -1,53 +0,0 @@ -package netlink - -import ( - "unsafe" - - "golang.org/x/sys/unix" -) - -type BpfProgType uint32 - -const ( - BPF_PROG_TYPE_UNSPEC BpfProgType = iota - BPF_PROG_TYPE_SOCKET_FILTER - BPF_PROG_TYPE_KPROBE - BPF_PROG_TYPE_SCHED_CLS - BPF_PROG_TYPE_SCHED_ACT - BPF_PROG_TYPE_TRACEPOINT - BPF_PROG_TYPE_XDP -) - -type BPFAttr struct { - ProgType uint32 - InsnCnt uint32 - Insns uintptr - License uintptr - LogLevel uint32 - LogSize uint32 - LogBuf uintptr - KernVersion uint32 -} - -// loadSimpleBpf loads a trivial bpf program for testing purposes. -func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) { - insns := []uint64{ - 0x00000000000000b7 | (uint64(ret) << 32), - 0x0000000000000095, - } - license := []byte{'A', 'S', 'L', '2', '\x00'} - attr := BPFAttr{ - ProgType: uint32(progType), - InsnCnt: uint32(len(insns)), - Insns: uintptr(unsafe.Pointer(&insns[0])), - License: uintptr(unsafe.Pointer(&license[0])), - } - fd, _, errno := unix.Syscall(unix.SYS_BPF, - 5, /* bpf cmd */ - uintptr(unsafe.Pointer(&attr)), - unsafe.Sizeof(attr)) - if errno != 0 { - return 0, errno - } - return int(fd), nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/bridge_linux.go b/examples/vendor/github.com/vishvananda/netlink/bridge_linux.go deleted file mode 100644 index 6e1224c..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/bridge_linux.go +++ /dev/null @@ -1,112 +0,0 @@ -package netlink - -import ( - "fmt" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// BridgeVlanList gets a map of device id to bridge vlan infos. -// Equivalent to: `bridge vlan show` -func BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) { - return pkgHandle.BridgeVlanList() -} - -// BridgeVlanList gets a map of device id to bridge vlan infos. -// Equivalent to: `bridge vlan show` -func (h *Handle) BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) { - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP) - msg := nl.NewIfInfomsg(unix.AF_BRIDGE) - req.AddData(msg) - req.AddData(nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(uint32(nl.RTEXT_FILTER_BRVLAN)))) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK) - if err != nil { - return nil, err - } - ret := make(map[int32][]*nl.BridgeVlanInfo) - for _, m := range msgs { - msg := nl.DeserializeIfInfomsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - for _, attr := range attrs { - switch attr.Attr.Type { - case unix.IFLA_AF_SPEC: - //nested attr - nestAttrs, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, fmt.Errorf("failed to parse nested attr %v", err) - } - for _, nestAttr := range nestAttrs { - switch nestAttr.Attr.Type { - case nl.IFLA_BRIDGE_VLAN_INFO: - vlanInfo := nl.DeserializeBridgeVlanInfo(nestAttr.Value) - ret[msg.Index] = append(ret[msg.Index], vlanInfo) - } - } - } - } - } - return ret, nil -} - -// BridgeVlanAdd adds a new vlan filter entry -// Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` -func BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error { - return pkgHandle.BridgeVlanAdd(link, vid, pvid, untagged, self, master) -} - -// BridgeVlanAdd adds a new vlan filter entry -// Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` -func (h *Handle) BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error { - return h.bridgeVlanModify(unix.RTM_SETLINK, link, vid, pvid, untagged, self, master) -} - -// BridgeVlanDel adds a new vlan filter entry -// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` -func BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error { - return pkgHandle.BridgeVlanDel(link, vid, pvid, untagged, self, master) -} - -// BridgeVlanDel adds a new vlan filter entry -// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` -func (h *Handle) BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error { - return h.bridgeVlanModify(unix.RTM_DELLINK, link, vid, pvid, untagged, self, master) -} - -func (h *Handle) bridgeVlanModify(cmd int, link Link, vid uint16, pvid, untagged, self, master bool) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(cmd, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_BRIDGE) - msg.Index = int32(base.Index) - req.AddData(msg) - - br := nl.NewRtAttr(unix.IFLA_AF_SPEC, nil) - var flags uint16 - if self { - flags |= nl.BRIDGE_FLAGS_SELF - } - if master { - flags |= nl.BRIDGE_FLAGS_MASTER - } - if flags > 0 { - br.AddRtAttr(nl.IFLA_BRIDGE_FLAGS, nl.Uint16Attr(flags)) - } - vlanInfo := &nl.BridgeVlanInfo{Vid: vid} - if pvid { - vlanInfo.Flags |= nl.BRIDGE_VLAN_INFO_PVID - } - if untagged { - vlanInfo.Flags |= nl.BRIDGE_VLAN_INFO_UNTAGGED - } - br.AddRtAttr(nl.IFLA_BRIDGE_VLAN_INFO, vlanInfo.Serialize()) - req.AddData(br) - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} diff --git a/examples/vendor/github.com/vishvananda/netlink/class.go b/examples/vendor/github.com/vishvananda/netlink/class.go deleted file mode 100644 index 10ceffe..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/class.go +++ /dev/null @@ -1,239 +0,0 @@ -package netlink - -import ( - "fmt" -) - -// Class interfaces for all classes -type Class interface { - Attrs() *ClassAttrs - Type() string -} - -// Generic networking statistics for netlink users. -// This file contains "gnet_" prefixed structs and relevant functions. -// See Documentation/networking/getn_stats.txt in Linux source code for more details. - -// GnetStatsBasic Ref: struct gnet_stats_basic { ... } -type GnetStatsBasic struct { - Bytes uint64 // number of seen bytes - Packets uint32 // number of seen packets -} - -// GnetStatsRateEst Ref: struct gnet_stats_rate_est { ... } -type GnetStatsRateEst struct { - Bps uint32 // current byte rate - Pps uint32 // current packet rate -} - -// GnetStatsRateEst64 Ref: struct gnet_stats_rate_est64 { ... } -type GnetStatsRateEst64 struct { - Bps uint64 // current byte rate - Pps uint64 // current packet rate -} - -// GnetStatsQueue Ref: struct gnet_stats_queue { ... } -type GnetStatsQueue struct { - Qlen uint32 // queue length - Backlog uint32 // backlog size of queue - Drops uint32 // number of dropped packets - Requeues uint32 // number of requues - Overlimits uint32 // number of enqueues over the limit -} - -// ClassStatistics representation based on generic networking statistics for netlink. -// See Documentation/networking/gen_stats.txt in Linux source code for more details. -type ClassStatistics struct { - Basic *GnetStatsBasic - Queue *GnetStatsQueue - RateEst *GnetStatsRateEst -} - -// NewClassStatistics Construct a ClassStatistics struct which fields are all initialized by 0. -func NewClassStatistics() *ClassStatistics { - return &ClassStatistics{ - Basic: &GnetStatsBasic{}, - Queue: &GnetStatsQueue{}, - RateEst: &GnetStatsRateEst{}, - } -} - -// ClassAttrs represents a netlink class. A filter is associated with a link, -// has a handle and a parent. The root filter of a device should have a -// parent == HANDLE_ROOT. -type ClassAttrs struct { - LinkIndex int - Handle uint32 - Parent uint32 - Leaf uint32 - Statistics *ClassStatistics -} - -func (q ClassAttrs) String() string { - return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Leaf: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Leaf) -} - -// HtbClassAttrs stores the attributes of HTB class -type HtbClassAttrs struct { - // TODO handle all attributes - Rate uint64 - Ceil uint64 - Buffer uint32 - Cbuffer uint32 - Quantum uint32 - Level uint32 - Prio uint32 -} - -func (q HtbClassAttrs) String() string { - return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer) -} - -// HtbClass represents an Htb class -type HtbClass struct { - ClassAttrs - Rate uint64 - Ceil uint64 - Buffer uint32 - Cbuffer uint32 - Quantum uint32 - Level uint32 - Prio uint32 -} - -func (q HtbClass) String() string { - return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer) -} - -// Attrs returns the class attributes -func (q *HtbClass) Attrs() *ClassAttrs { - return &q.ClassAttrs -} - -// Type return the class type -func (q *HtbClass) Type() string { - return "htb" -} - -// GenericClass classes represent types that are not currently understood -// by this netlink library. -type GenericClass struct { - ClassAttrs - ClassType string -} - -// Attrs return the class attributes -func (class *GenericClass) Attrs() *ClassAttrs { - return &class.ClassAttrs -} - -// Type return the class type -func (class *GenericClass) Type() string { - return class.ClassType -} - -// ServiceCurve is a nondecreasing function of some time unit, returning the amount of service -// (an allowed or allocated amount of bandwidth) at some specific point in time. The purpose of it -// should be subconsciously obvious: if a class was allowed to transfer not less than the amount -// specified by its service curve, then the service curve is not violated. -type ServiceCurve struct { - m1 uint32 - d uint32 - m2 uint32 -} - -// Attrs return the parameters of the service curve -func (c *ServiceCurve) Attrs() (uint32, uint32, uint32) { - return c.m1, c.d, c.m2 -} - -// Burst returns the burst rate (m1) of the curve -func (c *ServiceCurve) Burst() uint32 { - return c.m1 -} - -// Delay return the delay (d) of the curve -func (c *ServiceCurve) Delay() uint32 { - return c.d -} - -// Rate returns the rate (m2) of the curve -func (c *ServiceCurve) Rate() uint32 { - return c.m2 -} - -// HfscClass is a representation of the HFSC class -type HfscClass struct { - ClassAttrs - Rsc ServiceCurve - Fsc ServiceCurve - Usc ServiceCurve -} - -// SetUsc sets the USC curve. The bandwidth (m1 and m2) is specified in bits and the delay in -// seconds. -func (hfsc *HfscClass) SetUsc(m1 uint32, d uint32, m2 uint32) { - hfsc.Usc = ServiceCurve{m1: m1, d: d, m2: m2} -} - -// SetFsc sets the Fsc curve. The bandwidth (m1 and m2) is specified in bits and the delay in -// seconds. -func (hfsc *HfscClass) SetFsc(m1 uint32, d uint32, m2 uint32) { - hfsc.Fsc = ServiceCurve{m1: m1, d: d, m2: m2} -} - -// SetRsc sets the Rsc curve. The bandwidth (m1 and m2) is specified in bits and the delay in -// seconds. -func (hfsc *HfscClass) SetRsc(m1 uint32, d uint32, m2 uint32) { - hfsc.Rsc = ServiceCurve{m1: m1, d: d, m2: m2} -} - -// SetSC implements the SC from the `tc` CLI. This function behaves the same as if one would set the -// USC through the `tc` command-line tool. This means bandwidth (m1 and m2) is specified in bits and -// the delay in ms. -func (hfsc *HfscClass) SetSC(m1 uint32, d uint32, m2 uint32) { - hfsc.SetRsc(m1, d, m2) - hfsc.SetFsc(m1, d, m2) -} - -// SetUL implements the UL from the `tc` CLI. This function behaves the same as if one would set the -// USC through the `tc` command-line tool. This means bandwidth (m1 and m2) is specified in bits and -// the delay in ms. -func (hfsc *HfscClass) SetUL(m1 uint32, d uint32, m2 uint32) { - hfsc.SetUsc(m1, d, m2) -} - -// SetLS implements the LS from the `tc` CLI. This function behaves the same as if one would set the -// USC through the `tc` command-line tool. This means bandwidth (m1 and m2) is specified in bits and -// the delay in ms. -func (hfsc *HfscClass) SetLS(m1 uint32, d uint32, m2 uint32) { - hfsc.SetFsc(m1, d, m2) -} - -// NewHfscClass returns a new HFSC struct with the set parameters -func NewHfscClass(attrs ClassAttrs) *HfscClass { - return &HfscClass{ - ClassAttrs: attrs, - Rsc: ServiceCurve{}, - Fsc: ServiceCurve{}, - Usc: ServiceCurve{}, - } -} - -// String() returns a string that contains the information and attributes of the HFSC class -func (hfsc *HfscClass) String() string { - return fmt.Sprintf( - "{%s -- {RSC: {m1=%d d=%d m2=%d}} {FSC: {m1=%d d=%d m2=%d}} {USC: {m1=%d d=%d m2=%d}}}", - hfsc.Attrs(), hfsc.Rsc.m1*8, hfsc.Rsc.d, hfsc.Rsc.m2*8, hfsc.Fsc.m1*8, hfsc.Fsc.d, hfsc.Fsc.m2*8, hfsc.Usc.m1*8, hfsc.Usc.d, hfsc.Usc.m2*8, - ) -} - -// Attrs return the Hfsc parameters -func (hfsc *HfscClass) Attrs() *ClassAttrs { - return &hfsc.ClassAttrs -} - -// Type return the type of the class -func (hfsc *HfscClass) Type() string { - return "hfsc" -} diff --git a/examples/vendor/github.com/vishvananda/netlink/class_linux.go b/examples/vendor/github.com/vishvananda/netlink/class_linux.go deleted file mode 100644 index e664ade..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/class_linux.go +++ /dev/null @@ -1,387 +0,0 @@ -package netlink - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "syscall" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// Internal tc_stats representation in Go struct. -// This is for internal uses only to deserialize the payload of rtattr. -// After the deserialization, this should be converted into the canonical stats -// struct, ClassStatistics, in case of statistics of a class. -// Ref: struct tc_stats { ... } -type tcStats struct { - Bytes uint64 // Number of enqueued bytes - Packets uint32 // Number of enqueued packets - Drops uint32 // Packets dropped because of lack of resources - Overlimits uint32 // Number of throttle events when this flow goes out of allocated bandwidth - Bps uint32 // Current flow byte rate - Pps uint32 // Current flow packet rate - Qlen uint32 - Backlog uint32 -} - -// NewHtbClass NOTE: function is in here because it uses other linux functions -func NewHtbClass(attrs ClassAttrs, cattrs HtbClassAttrs) *HtbClass { - mtu := 1600 - rate := cattrs.Rate / 8 - ceil := cattrs.Ceil / 8 - buffer := cattrs.Buffer - cbuffer := cattrs.Cbuffer - - if ceil == 0 { - ceil = rate - } - - if buffer == 0 { - buffer = uint32(float64(rate)/Hz() + float64(mtu)) - } - buffer = Xmittime(rate, buffer) - - if cbuffer == 0 { - cbuffer = uint32(float64(ceil)/Hz() + float64(mtu)) - } - cbuffer = Xmittime(ceil, cbuffer) - - return &HtbClass{ - ClassAttrs: attrs, - Rate: rate, - Ceil: ceil, - Buffer: buffer, - Cbuffer: cbuffer, - Level: 0, - Prio: cattrs.Prio, - Quantum: cattrs.Quantum, - } -} - -// ClassDel will delete a class from the system. -// Equivalent to: `tc class del $class` -func ClassDel(class Class) error { - return pkgHandle.ClassDel(class) -} - -// ClassDel will delete a class from the system. -// Equivalent to: `tc class del $class` -func (h *Handle) ClassDel(class Class) error { - return h.classModify(unix.RTM_DELTCLASS, 0, class) -} - -// ClassChange will change a class in place -// Equivalent to: `tc class change $class` -// The parent and handle MUST NOT be changed. -func ClassChange(class Class) error { - return pkgHandle.ClassChange(class) -} - -// ClassChange will change a class in place -// Equivalent to: `tc class change $class` -// The parent and handle MUST NOT be changed. -func (h *Handle) ClassChange(class Class) error { - return h.classModify(unix.RTM_NEWTCLASS, 0, class) -} - -// ClassReplace will replace a class to the system. -// quivalent to: `tc class replace $class` -// The handle MAY be changed. -// If a class already exist with this parent/handle pair, the class is changed. -// If a class does not already exist with this parent/handle, a new class is created. -func ClassReplace(class Class) error { - return pkgHandle.ClassReplace(class) -} - -// ClassReplace will replace a class to the system. -// quivalent to: `tc class replace $class` -// The handle MAY be changed. -// If a class already exist with this parent/handle pair, the class is changed. -// If a class does not already exist with this parent/handle, a new class is created. -func (h *Handle) ClassReplace(class Class) error { - return h.classModify(unix.RTM_NEWTCLASS, unix.NLM_F_CREATE, class) -} - -// ClassAdd will add a class to the system. -// Equivalent to: `tc class add $class` -func ClassAdd(class Class) error { - return pkgHandle.ClassAdd(class) -} - -// ClassAdd will add a class to the system. -// Equivalent to: `tc class add $class` -func (h *Handle) ClassAdd(class Class) error { - return h.classModify( - unix.RTM_NEWTCLASS, - unix.NLM_F_CREATE|unix.NLM_F_EXCL, - class, - ) -} - -func (h *Handle) classModify(cmd, flags int, class Class) error { - req := h.newNetlinkRequest(cmd, flags|unix.NLM_F_ACK) - base := class.Attrs() - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Ifindex: int32(base.LinkIndex), - Handle: base.Handle, - Parent: base.Parent, - } - req.AddData(msg) - - if cmd != unix.RTM_DELTCLASS { - if err := classPayload(req, class); err != nil { - return err - } - } - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func classPayload(req *nl.NetlinkRequest, class Class) error { - req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(class.Type()))) - - options := nl.NewRtAttr(nl.TCA_OPTIONS, nil) - switch class.Type() { - case "htb": - htb := class.(*HtbClass) - opt := nl.TcHtbCopt{} - opt.Buffer = htb.Buffer - opt.Cbuffer = htb.Cbuffer - opt.Quantum = htb.Quantum - opt.Level = htb.Level - opt.Prio = htb.Prio - // TODO: Handle Debug properly. For now default to 0 - /* Calculate {R,C}Tab and set Rate and Ceil */ - cellLog := -1 - ccellLog := -1 - linklayer := nl.LINKLAYER_ETHERNET - mtu := 1600 - var rtab [256]uint32 - var ctab [256]uint32 - tcrate := nl.TcRateSpec{Rate: uint32(htb.Rate)} - if CalcRtable(&tcrate, rtab[:], cellLog, uint32(mtu), linklayer) < 0 { - return errors.New("HTB: failed to calculate rate table") - } - opt.Rate = tcrate - tcceil := nl.TcRateSpec{Rate: uint32(htb.Ceil)} - if CalcRtable(&tcceil, ctab[:], ccellLog, uint32(mtu), linklayer) < 0 { - return errors.New("HTB: failed to calculate ceil rate table") - } - opt.Ceil = tcceil - options.AddRtAttr(nl.TCA_HTB_PARMS, opt.Serialize()) - options.AddRtAttr(nl.TCA_HTB_RTAB, SerializeRtab(rtab)) - options.AddRtAttr(nl.TCA_HTB_CTAB, SerializeRtab(ctab)) - case "hfsc": - hfsc := class.(*HfscClass) - opt := nl.HfscCopt{} - rm1, rd, rm2 := hfsc.Rsc.Attrs() - opt.Rsc.Set(rm1/8, rd, rm2/8) - fm1, fd, fm2 := hfsc.Fsc.Attrs() - opt.Fsc.Set(fm1/8, fd, fm2/8) - um1, ud, um2 := hfsc.Usc.Attrs() - opt.Usc.Set(um1/8, ud, um2/8) - nl.NewRtAttrChild(options, nl.TCA_HFSC_RSC, nl.SerializeHfscCurve(&opt.Rsc)) - nl.NewRtAttrChild(options, nl.TCA_HFSC_FSC, nl.SerializeHfscCurve(&opt.Fsc)) - nl.NewRtAttrChild(options, nl.TCA_HFSC_USC, nl.SerializeHfscCurve(&opt.Usc)) - } - req.AddData(options) - return nil -} - -// ClassList gets a list of classes in the system. -// Equivalent to: `tc class show`. -// Generally returns nothing if link and parent are not specified. -func ClassList(link Link, parent uint32) ([]Class, error) { - return pkgHandle.ClassList(link, parent) -} - -// ClassList gets a list of classes in the system. -// Equivalent to: `tc class show`. -// Generally returns nothing if link and parent are not specified. -func (h *Handle) ClassList(link Link, parent uint32) ([]Class, error) { - req := h.newNetlinkRequest(unix.RTM_GETTCLASS, unix.NLM_F_DUMP) - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Parent: parent, - } - if link != nil { - base := link.Attrs() - h.ensureIndex(base) - msg.Ifindex = int32(base.Index) - } - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWTCLASS) - if err != nil { - return nil, err - } - - var res []Class - for _, m := range msgs { - msg := nl.DeserializeTcMsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - base := ClassAttrs{ - LinkIndex: int(msg.Ifindex), - Handle: msg.Handle, - Parent: msg.Parent, - Statistics: nil, - } - - var class Class - classType := "" - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.TCA_KIND: - classType = string(attr.Value[:len(attr.Value)-1]) - switch classType { - case "htb": - class = &HtbClass{} - case "hfsc": - class = &HfscClass{} - default: - class = &GenericClass{ClassType: classType} - } - case nl.TCA_OPTIONS: - switch classType { - case "htb": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - _, err = parseHtbClassData(class, data) - if err != nil { - return nil, err - } - case "hfsc": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - _, err = parseHfscClassData(class, data) - if err != nil { - return nil, err - } - } - // For backward compatibility. - case nl.TCA_STATS: - base.Statistics, err = parseTcStats(attr.Value) - if err != nil { - return nil, err - } - case nl.TCA_STATS2: - base.Statistics, err = parseTcStats2(attr.Value) - if err != nil { - return nil, err - } - } - } - *class.Attrs() = base - res = append(res, class) - } - - return res, nil -} - -func parseHtbClassData(class Class, data []syscall.NetlinkRouteAttr) (bool, error) { - htb := class.(*HtbClass) - detailed := false - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_HTB_PARMS: - opt := nl.DeserializeTcHtbCopt(datum.Value) - htb.Rate = uint64(opt.Rate.Rate) - htb.Ceil = uint64(opt.Ceil.Rate) - htb.Buffer = opt.Buffer - htb.Cbuffer = opt.Cbuffer - htb.Quantum = opt.Quantum - htb.Level = opt.Level - htb.Prio = opt.Prio - } - } - return detailed, nil -} - -func parseHfscClassData(class Class, data []syscall.NetlinkRouteAttr) (bool, error) { - hfsc := class.(*HfscClass) - detailed := false - for _, datum := range data { - m1, d, m2 := nl.DeserializeHfscCurve(datum.Value).Attrs() - switch datum.Attr.Type { - case nl.TCA_HFSC_RSC: - hfsc.Rsc = ServiceCurve{m1: m1 * 8, d: d, m2: m2 * 8} - case nl.TCA_HFSC_FSC: - hfsc.Fsc = ServiceCurve{m1: m1 * 8, d: d, m2: m2 * 8} - case nl.TCA_HFSC_USC: - hfsc.Usc = ServiceCurve{m1: m1 * 8, d: d, m2: m2 * 8} - } - } - return detailed, nil -} - -func parseTcStats(data []byte) (*ClassStatistics, error) { - buf := &bytes.Buffer{} - buf.Write(data) - native := nl.NativeEndian() - tcStats := &tcStats{} - if err := binary.Read(buf, native, tcStats); err != nil { - return nil, err - } - - stats := NewClassStatistics() - stats.Basic.Bytes = tcStats.Bytes - stats.Basic.Packets = tcStats.Packets - stats.Queue.Qlen = tcStats.Qlen - stats.Queue.Backlog = tcStats.Backlog - stats.Queue.Drops = tcStats.Drops - stats.Queue.Overlimits = tcStats.Overlimits - stats.RateEst.Bps = tcStats.Bps - stats.RateEst.Pps = tcStats.Pps - - return stats, nil -} - -func parseGnetStats(data []byte, gnetStats interface{}) error { - buf := &bytes.Buffer{} - buf.Write(data) - native := nl.NativeEndian() - return binary.Read(buf, native, gnetStats) -} - -func parseTcStats2(data []byte) (*ClassStatistics, error) { - rtAttrs, err := nl.ParseRouteAttr(data) - if err != nil { - return nil, err - } - stats := NewClassStatistics() - for _, datum := range rtAttrs { - switch datum.Attr.Type { - case nl.TCA_STATS_BASIC: - if err := parseGnetStats(datum.Value, stats.Basic); err != nil { - return nil, fmt.Errorf("Failed to parse ClassStatistics.Basic with: %v\n%s", - err, hex.Dump(datum.Value)) - } - case nl.TCA_STATS_QUEUE: - if err := parseGnetStats(datum.Value, stats.Queue); err != nil { - return nil, fmt.Errorf("Failed to parse ClassStatistics.Queue with: %v\n%s", - err, hex.Dump(datum.Value)) - } - case nl.TCA_STATS_RATE_EST: - if err := parseGnetStats(datum.Value, stats.RateEst); err != nil { - return nil, fmt.Errorf("Failed to parse ClassStatistics.RateEst with: %v\n%s", - err, hex.Dump(datum.Value)) - } - } - } - - return stats, nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/conntrack_linux.go b/examples/vendor/github.com/vishvananda/netlink/conntrack_linux.go deleted file mode 100644 index ab91f4e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/conntrack_linux.go +++ /dev/null @@ -1,454 +0,0 @@ -package netlink - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "net" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// ConntrackTableType Conntrack table for the netlink operation -type ConntrackTableType uint8 - -const ( - // ConntrackTable Conntrack table - // https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink.h -> #define NFNL_SUBSYS_CTNETLINK 1 - ConntrackTable = 1 - // ConntrackExpectTable Conntrack expect table - // https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink.h -> #define NFNL_SUBSYS_CTNETLINK_EXP 2 - ConntrackExpectTable = 2 -) - -const ( - // backward compatibility with golang 1.6 which does not have io.SeekCurrent - seekCurrent = 1 -) - -// InetFamily Family type -type InetFamily uint8 - -// -L [table] [options] List conntrack or expectation table -// -G [table] parameters Get conntrack or expectation - -// -I [table] parameters Create a conntrack or expectation -// -U [table] parameters Update a conntrack -// -E [table] [options] Show events - -// -C [table] Show counter -// -S Show statistics - -// ConntrackTableList returns the flow list of a table of a specific family -// conntrack -L [table] [options] List conntrack or expectation table -func ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) { - return pkgHandle.ConntrackTableList(table, family) -} - -// ConntrackTableFlush flushes all the flows of a specified table -// conntrack -F [table] Flush table -// The flush operation applies to all the family types -func ConntrackTableFlush(table ConntrackTableType) error { - return pkgHandle.ConntrackTableFlush(table) -} - -// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter -// conntrack -D [table] parameters Delete conntrack or expectation -func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter CustomConntrackFilter) (uint, error) { - return pkgHandle.ConntrackDeleteFilter(table, family, filter) -} - -// ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed -// conntrack -L [table] [options] List conntrack or expectation table -func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) { - res, err := h.dumpConntrackTable(table, family) - if err != nil { - return nil, err - } - - // Deserialize all the flows - var result []*ConntrackFlow - for _, dataRaw := range res { - result = append(result, parseRawData(dataRaw)) - } - - return result, nil -} - -// ConntrackTableFlush flushes all the flows of a specified table using the netlink handle passed -// conntrack -F [table] Flush table -// The flush operation applies to all the family types -func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error { - req := h.newConntrackRequest(table, unix.AF_INET, nl.IPCTNL_MSG_CT_DELETE, unix.NLM_F_ACK) - _, err := req.Execute(unix.NETLINK_NETFILTER, 0) - return err -} - -// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter using the netlink handle passed -// conntrack -D [table] parameters Delete conntrack or expectation -func (h *Handle) ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter CustomConntrackFilter) (uint, error) { - res, err := h.dumpConntrackTable(table, family) - if err != nil { - return 0, err - } - - var matched uint - for _, dataRaw := range res { - flow := parseRawData(dataRaw) - if match := filter.MatchConntrackFlow(flow); match { - req2 := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_DELETE, unix.NLM_F_ACK) - // skip the first 4 byte that are the netfilter header, the newConntrackRequest is adding it already - req2.AddRawData(dataRaw[4:]) - req2.Execute(unix.NETLINK_NETFILTER, 0) - matched++ - } - } - - return matched, nil -} - -func (h *Handle) newConntrackRequest(table ConntrackTableType, family InetFamily, operation, flags int) *nl.NetlinkRequest { - // Create the Netlink request object - req := h.newNetlinkRequest((int(table)<<8)|operation, flags) - // Add the netfilter header - msg := &nl.Nfgenmsg{ - NfgenFamily: uint8(family), - Version: nl.NFNETLINK_V0, - ResId: 0, - } - req.AddData(msg) - return req -} - -func (h *Handle) dumpConntrackTable(table ConntrackTableType, family InetFamily) ([][]byte, error) { - req := h.newConntrackRequest(table, family, nl.IPCTNL_MSG_CT_GET, unix.NLM_F_DUMP) - return req.Execute(unix.NETLINK_NETFILTER, 0) -} - -// The full conntrack flow structure is very complicated and can be found in the file: -// http://git.netfilter.org/libnetfilter_conntrack/tree/include/internal/object.h -// For the time being, the structure below allows to parse and extract the base information of a flow -type ipTuple struct { - Bytes uint64 - DstIP net.IP - DstPort uint16 - Packets uint64 - Protocol uint8 - SrcIP net.IP - SrcPort uint16 -} - -type ConntrackFlow struct { - FamilyType uint8 - Forward ipTuple - Reverse ipTuple - Mark uint32 -} - -func (s *ConntrackFlow) String() string { - // conntrack cmd output: - // udp 17 src=127.0.0.1 dst=127.0.0.1 sport=4001 dport=1234 packets=5 bytes=532 [UNREPLIED] src=127.0.0.1 dst=127.0.0.1 sport=1234 dport=4001 packets=10 bytes=1078 mark=0 - return fmt.Sprintf("%s\t%d src=%s dst=%s sport=%d dport=%d packets=%d bytes=%d\tsrc=%s dst=%s sport=%d dport=%d packets=%d bytes=%d mark=%d", - nl.L4ProtoMap[s.Forward.Protocol], s.Forward.Protocol, - s.Forward.SrcIP.String(), s.Forward.DstIP.String(), s.Forward.SrcPort, s.Forward.DstPort, s.Forward.Packets, s.Forward.Bytes, - s.Reverse.SrcIP.String(), s.Reverse.DstIP.String(), s.Reverse.SrcPort, s.Reverse.DstPort, s.Reverse.Packets, s.Reverse.Bytes, - s.Mark) -} - -// This method parse the ip tuple structure -// The message structure is the following: -// -// -// -// -// -func parseIpTuple(reader *bytes.Reader, tpl *ipTuple) uint8 { - for i := 0; i < 2; i++ { - _, t, _, v := parseNfAttrTLV(reader) - switch t { - case nl.CTA_IP_V4_SRC, nl.CTA_IP_V6_SRC: - tpl.SrcIP = v - case nl.CTA_IP_V4_DST, nl.CTA_IP_V6_DST: - tpl.DstIP = v - } - } - // Skip the next 4 bytes nl.NLA_F_NESTED|nl.CTA_TUPLE_PROTO - reader.Seek(4, seekCurrent) - _, t, _, v := parseNfAttrTLV(reader) - if t == nl.CTA_PROTO_NUM { - tpl.Protocol = uint8(v[0]) - } - // Skip some padding 3 bytes - reader.Seek(3, seekCurrent) - for i := 0; i < 2; i++ { - _, t, _ := parseNfAttrTL(reader) - switch t { - case nl.CTA_PROTO_SRC_PORT: - parseBERaw16(reader, &tpl.SrcPort) - case nl.CTA_PROTO_DST_PORT: - parseBERaw16(reader, &tpl.DstPort) - } - // Skip some padding 2 byte - reader.Seek(2, seekCurrent) - } - return tpl.Protocol -} - -func parseNfAttrTLV(r *bytes.Reader) (isNested bool, attrType, len uint16, value []byte) { - isNested, attrType, len = parseNfAttrTL(r) - - value = make([]byte, len) - binary.Read(r, binary.BigEndian, &value) - return isNested, attrType, len, value -} - -func parseNfAttrTL(r *bytes.Reader) (isNested bool, attrType, len uint16) { - binary.Read(r, nl.NativeEndian(), &len) - len -= nl.SizeofNfattr - - binary.Read(r, nl.NativeEndian(), &attrType) - isNested = (attrType & nl.NLA_F_NESTED) == nl.NLA_F_NESTED - attrType = attrType & (nl.NLA_F_NESTED - 1) - - return isNested, attrType, len -} - -func parseBERaw16(r *bytes.Reader, v *uint16) { - binary.Read(r, binary.BigEndian, v) -} - -func parseBERaw32(r *bytes.Reader, v *uint32) { - binary.Read(r, binary.BigEndian, v) -} - -func parseBERaw64(r *bytes.Reader, v *uint64) { - binary.Read(r, binary.BigEndian, v) -} - -func parseByteAndPacketCounters(r *bytes.Reader) (bytes, packets uint64) { - for i := 0; i < 2; i++ { - switch _, t, _ := parseNfAttrTL(r); t { - case nl.CTA_COUNTERS_BYTES: - parseBERaw64(r, &bytes) - case nl.CTA_COUNTERS_PACKETS: - parseBERaw64(r, &packets) - default: - return - } - } - return -} - -func parseConnectionMark(r *bytes.Reader) (mark uint32) { - parseBERaw32(r, &mark) - return -} - -func parseRawData(data []byte) *ConntrackFlow { - s := &ConntrackFlow{} - // First there is the Nfgenmsg header - // consume only the family field - reader := bytes.NewReader(data) - binary.Read(reader, nl.NativeEndian(), &s.FamilyType) - - // skip rest of the Netfilter header - reader.Seek(3, seekCurrent) - // The message structure is the following: - // 4 bytes - // 4 bytes - // flow information of the forward flow - // 4 bytes - // 4 bytes - // flow information of the reverse flow - for reader.Len() > 0 { - if nested, t, l := parseNfAttrTL(reader); nested { - switch t { - case nl.CTA_TUPLE_ORIG: - if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP { - parseIpTuple(reader, &s.Forward) - } - case nl.CTA_TUPLE_REPLY: - if nested, t, _ = parseNfAttrTL(reader); nested && t == nl.CTA_TUPLE_IP { - parseIpTuple(reader, &s.Reverse) - } else { - // Header not recognized skip it - reader.Seek(int64(l), seekCurrent) - } - case nl.CTA_COUNTERS_ORIG: - s.Forward.Bytes, s.Forward.Packets = parseByteAndPacketCounters(reader) - case nl.CTA_COUNTERS_REPLY: - s.Reverse.Bytes, s.Reverse.Packets = parseByteAndPacketCounters(reader) - } - } else { - switch t { - case nl.CTA_MARK: - s.Mark = parseConnectionMark(reader) - } - } - } - return s -} - -// Conntrack parameters and options: -// -n, --src-nat ip source NAT ip -// -g, --dst-nat ip destination NAT ip -// -j, --any-nat ip source or destination NAT ip -// -m, --mark mark Set mark -// -c, --secmark secmark Set selinux secmark -// -e, --event-mask eventmask Event mask, eg. NEW,DESTROY -// -z, --zero Zero counters while listing -// -o, --output type[,...] Output format, eg. xml -// -l, --label label[,...] conntrack labels - -// Common parameters and options: -// -s, --src, --orig-src ip Source address from original direction -// -d, --dst, --orig-dst ip Destination address from original direction -// -r, --reply-src ip Source address from reply direction -// -q, --reply-dst ip Destination address from reply direction -// -p, --protonum proto Layer 4 Protocol, eg. 'tcp' -// -f, --family proto Layer 3 Protocol, eg. 'ipv6' -// -t, --timeout timeout Set timeout -// -u, --status status Set status, eg. ASSURED -// -w, --zone value Set conntrack zone -// --orig-zone value Set zone for original direction -// --reply-zone value Set zone for reply direction -// -b, --buffer-size Netlink socket buffer size -// --mask-src ip Source mask address -// --mask-dst ip Destination mask address - -// Layer 4 Protocol common parameters and options: -// TCP, UDP, SCTP, UDPLite and DCCP -// --sport, --orig-port-src port Source port in original direction -// --dport, --orig-port-dst port Destination port in original direction - -// Filter types -type ConntrackFilterType uint8 - -const ( - ConntrackOrigSrcIP = iota // -orig-src ip Source address from original direction - ConntrackOrigDstIP // -orig-dst ip Destination address from original direction - ConntrackReplySrcIP // --reply-src ip Reply Source IP - ConntrackReplyDstIP // --reply-dst ip Reply Destination IP - ConntrackReplyAnyIP // Match source or destination reply IP - ConntrackOrigSrcPort // --orig-port-src port Source port in original direction - ConntrackOrigDstPort // --orig-port-dst port Destination port in original direction - ConntrackNatSrcIP = ConntrackReplySrcIP // deprecated use instead ConntrackReplySrcIP - ConntrackNatDstIP = ConntrackReplyDstIP // deprecated use instead ConntrackReplyDstIP - ConntrackNatAnyIP = ConntrackReplyAnyIP // deprecated use instead ConntrackReplyAnyIP -) - -type CustomConntrackFilter interface { - // MatchConntrackFlow applies the filter to the flow and returns true if the flow matches - // the filter or false otherwise - MatchConntrackFlow(flow *ConntrackFlow) bool -} - -type ConntrackFilter struct { - ipFilter map[ConntrackFilterType]net.IP - portFilter map[ConntrackFilterType]uint16 - protoFilter uint8 -} - -// AddIP adds an IP to the conntrack filter -func (f *ConntrackFilter) AddIP(tp ConntrackFilterType, ip net.IP) error { - if f.ipFilter == nil { - f.ipFilter = make(map[ConntrackFilterType]net.IP) - } - if _, ok := f.ipFilter[tp]; ok { - return errors.New("Filter attribute already present") - } - f.ipFilter[tp] = ip - return nil -} - -// AddPort adds a Port to the conntrack filter if the Layer 4 protocol allows it -func (f *ConntrackFilter) AddPort(tp ConntrackFilterType, port uint16) error { - switch f.protoFilter { - // TCP, UDP, DCCP, SCTP, UDPLite - case 6, 17, 33, 132, 136: - default: - return fmt.Errorf("Filter attribute not available without a valid Layer 4 protocol: %d", f.protoFilter) - } - - if f.portFilter == nil { - f.portFilter = make(map[ConntrackFilterType]uint16) - } - if _, ok := f.portFilter[tp]; ok { - return errors.New("Filter attribute already present") - } - f.portFilter[tp] = port - return nil -} - -// AddProtocol adds the Layer 4 protocol to the conntrack filter -func (f *ConntrackFilter) AddProtocol(proto uint8) error { - if f.protoFilter != 0 { - return errors.New("Filter attribute already present") - } - f.protoFilter = proto - return nil -} - -// MatchConntrackFlow applies the filter to the flow and returns true if the flow matches the filter -// false otherwise -func (f *ConntrackFilter) MatchConntrackFlow(flow *ConntrackFlow) bool { - if len(f.ipFilter) == 0 && len(f.portFilter) == 0 && f.protoFilter == 0 { - // empty filter always not match - return false - } - - // -p, --protonum proto Layer 4 Protocol, eg. 'tcp' - if f.protoFilter != 0 && flow.Forward.Protocol != f.protoFilter { - // different Layer 4 protocol always not match - return false - } - - match := true - - // IP conntrack filter - if len(f.ipFilter) > 0 { - // -orig-src ip Source address from original direction - if elem, found := f.ipFilter[ConntrackOrigSrcIP]; found { - match = match && elem.Equal(flow.Forward.SrcIP) - } - - // -orig-dst ip Destination address from original direction - if elem, found := f.ipFilter[ConntrackOrigDstIP]; match && found { - match = match && elem.Equal(flow.Forward.DstIP) - } - - // -src-nat ip Source NAT ip - if elem, found := f.ipFilter[ConntrackReplySrcIP]; match && found { - match = match && elem.Equal(flow.Reverse.SrcIP) - } - - // -dst-nat ip Destination NAT ip - if elem, found := f.ipFilter[ConntrackReplyDstIP]; match && found { - match = match && elem.Equal(flow.Reverse.DstIP) - } - - // Match source or destination reply IP - if elem, found := f.ipFilter[ConntrackReplyAnyIP]; match && found { - match = match && (elem.Equal(flow.Reverse.SrcIP) || elem.Equal(flow.Reverse.DstIP)) - } - } - - // Layer 4 Port filter - if len(f.portFilter) > 0 { - // -orig-port-src port Source port from original direction - if elem, found := f.portFilter[ConntrackOrigSrcPort]; match && found { - match = match && elem == flow.Forward.SrcPort - } - - // -orig-port-dst port Destination port from original direction - if elem, found := f.portFilter[ConntrackOrigDstPort]; match && found { - match = match && elem == flow.Forward.DstPort - } - } - - return match -} - -var _ CustomConntrackFilter = (*ConntrackFilter)(nil) diff --git a/examples/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go b/examples/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go deleted file mode 100644 index af7af79..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/conntrack_unspecified.go +++ /dev/null @@ -1,53 +0,0 @@ -// +build !linux - -package netlink - -// ConntrackTableType Conntrack table for the netlink operation -type ConntrackTableType uint8 - -// InetFamily Family type -type InetFamily uint8 - -// ConntrackFlow placeholder -type ConntrackFlow struct{} - -// ConntrackFilter placeholder -type ConntrackFilter struct{} - -// ConntrackTableList returns the flow list of a table of a specific family -// conntrack -L [table] [options] List conntrack or expectation table -func ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) { - return nil, ErrNotImplemented -} - -// ConntrackTableFlush flushes all the flows of a specified table -// conntrack -F [table] Flush table -// The flush operation applies to all the family types -func ConntrackTableFlush(table ConntrackTableType) error { - return ErrNotImplemented -} - -// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter -// conntrack -D [table] parameters Delete conntrack or expectation -func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) { - return 0, ErrNotImplemented -} - -// ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed -// conntrack -L [table] [options] List conntrack or expectation table -func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) { - return nil, ErrNotImplemented -} - -// ConntrackTableFlush flushes all the flows of a specified table using the netlink handle passed -// conntrack -F [table] Flush table -// The flush operation applies to all the family types -func (h *Handle) ConntrackTableFlush(table ConntrackTableType) error { - return ErrNotImplemented -} - -// ConntrackDeleteFilter deletes entries on the specified table on the base of the filter using the netlink handle passed -// conntrack -D [table] parameters Delete conntrack or expectation -func (h *Handle) ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) { - return 0, ErrNotImplemented -} diff --git a/examples/vendor/github.com/vishvananda/netlink/devlink_linux.go b/examples/vendor/github.com/vishvananda/netlink/devlink_linux.go deleted file mode 100644 index 29b3f8e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/devlink_linux.go +++ /dev/null @@ -1,272 +0,0 @@ -package netlink - -import ( - "syscall" - - "fmt" - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// DevlinkDevEswitchAttr represents device's eswitch attributes -type DevlinkDevEswitchAttr struct { - Mode string - InlineMode string - EncapMode string -} - -// DevlinkDevAttrs represents device attributes -type DevlinkDevAttrs struct { - Eswitch DevlinkDevEswitchAttr -} - -// DevlinkDevice represents device and its attributes -type DevlinkDevice struct { - BusName string - DeviceName string - Attrs DevlinkDevAttrs -} - -func parseDevLinkDeviceList(msgs [][]byte) ([]*DevlinkDevice, error) { - devices := make([]*DevlinkDevice, 0, len(msgs)) - for _, m := range msgs { - attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:]) - if err != nil { - return nil, err - } - dev := &DevlinkDevice{} - if err = dev.parseAttributes(attrs); err != nil { - return nil, err - } - devices = append(devices, dev) - } - return devices, nil -} - -func eswitchStringToMode(modeName string) (uint16, error) { - if modeName == "legacy" { - return nl.DEVLINK_ESWITCH_MODE_LEGACY, nil - } else if modeName == "switchdev" { - return nl.DEVLINK_ESWITCH_MODE_SWITCHDEV, nil - } else { - return 0xffff, fmt.Errorf("invalid switchdev mode") - } -} - -func parseEswitchMode(mode uint16) string { - var eswitchMode = map[uint16]string{ - nl.DEVLINK_ESWITCH_MODE_LEGACY: "legacy", - nl.DEVLINK_ESWITCH_MODE_SWITCHDEV: "switchdev", - } - if eswitchMode[mode] == "" { - return "unknown" - } else { - return eswitchMode[mode] - } -} - -func parseEswitchInlineMode(inlinemode uint8) string { - var eswitchInlineMode = map[uint8]string{ - nl.DEVLINK_ESWITCH_INLINE_MODE_NONE: "none", - nl.DEVLINK_ESWITCH_INLINE_MODE_LINK: "link", - nl.DEVLINK_ESWITCH_INLINE_MODE_NETWORK: "network", - nl.DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT: "transport", - } - if eswitchInlineMode[inlinemode] == "" { - return "unknown" - } else { - return eswitchInlineMode[inlinemode] - } -} - -func parseEswitchEncapMode(encapmode uint8) string { - var eswitchEncapMode = map[uint8]string{ - nl.DEVLINK_ESWITCH_ENCAP_MODE_NONE: "disable", - nl.DEVLINK_ESWITCH_ENCAP_MODE_BASIC: "enable", - } - if eswitchEncapMode[encapmode] == "" { - return "unknown" - } else { - return eswitchEncapMode[encapmode] - } -} - -func (d *DevlinkDevice) parseAttributes(attrs []syscall.NetlinkRouteAttr) error { - for _, a := range attrs { - switch a.Attr.Type { - case nl.DEVLINK_ATTR_BUS_NAME: - d.BusName = string(a.Value) - case nl.DEVLINK_ATTR_DEV_NAME: - d.DeviceName = string(a.Value) - case nl.DEVLINK_ATTR_ESWITCH_MODE: - d.Attrs.Eswitch.Mode = parseEswitchMode(native.Uint16(a.Value)) - case nl.DEVLINK_ATTR_ESWITCH_INLINE_MODE: - d.Attrs.Eswitch.InlineMode = parseEswitchInlineMode(uint8(a.Value[0])) - case nl.DEVLINK_ATTR_ESWITCH_ENCAP_MODE: - d.Attrs.Eswitch.EncapMode = parseEswitchEncapMode(uint8(a.Value[0])) - } - } - return nil -} - -func (dev *DevlinkDevice) parseEswitchAttrs(msgs [][]byte) { - m := msgs[0] - attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:]) - if err != nil { - return - } - dev.parseAttributes(attrs) -} - -func (h *Handle) getEswitchAttrs(family *GenlFamily, dev *DevlinkDevice) { - msg := &nl.Genlmsg{ - Command: nl.DEVLINK_CMD_ESWITCH_GET, - Version: nl.GENL_DEVLINK_VERSION, - } - req := h.newNetlinkRequest(int(family.ID), unix.NLM_F_REQUEST|unix.NLM_F_ACK) - req.AddData(msg) - - b := make([]byte, len(dev.BusName)) - copy(b, dev.BusName) - data := nl.NewRtAttr(nl.DEVLINK_ATTR_BUS_NAME, b) - req.AddData(data) - - b = make([]byte, len(dev.DeviceName)) - copy(b, dev.DeviceName) - data = nl.NewRtAttr(nl.DEVLINK_ATTR_DEV_NAME, b) - req.AddData(data) - - msgs, err := req.Execute(unix.NETLINK_GENERIC, 0) - if err != nil { - return - } - dev.parseEswitchAttrs(msgs) -} - -// DevLinkGetDeviceList provides a pointer to devlink devices and nil error, -// otherwise returns an error code. -func (h *Handle) DevLinkGetDeviceList() ([]*DevlinkDevice, error) { - f, err := h.GenlFamilyGet(nl.GENL_DEVLINK_NAME) - if err != nil { - return nil, err - } - msg := &nl.Genlmsg{ - Command: nl.DEVLINK_CMD_GET, - Version: nl.GENL_DEVLINK_VERSION, - } - req := h.newNetlinkRequest(int(f.ID), - unix.NLM_F_REQUEST|unix.NLM_F_ACK|unix.NLM_F_DUMP) - req.AddData(msg) - msgs, err := req.Execute(unix.NETLINK_GENERIC, 0) - if err != nil { - return nil, err - } - devices, err := parseDevLinkDeviceList(msgs) - if err != nil { - return nil, err - } - for _, d := range devices { - h.getEswitchAttrs(f, d) - } - return devices, nil -} - -// DevLinkGetDeviceList provides a pointer to devlink devices and nil error, -// otherwise returns an error code. -func DevLinkGetDeviceList() ([]*DevlinkDevice, error) { - return pkgHandle.DevLinkGetDeviceList() -} - -func parseDevlinkDevice(msgs [][]byte) (*DevlinkDevice, error) { - m := msgs[0] - attrs, err := nl.ParseRouteAttr(m[nl.SizeofGenlmsg:]) - if err != nil { - return nil, err - } - dev := &DevlinkDevice{} - if err = dev.parseAttributes(attrs); err != nil { - return nil, err - } - return dev, nil -} - -func (h *Handle) createCmdReq(cmd uint8, bus string, device string) (*GenlFamily, *nl.NetlinkRequest, error) { - f, err := h.GenlFamilyGet(nl.GENL_DEVLINK_NAME) - if err != nil { - return nil, nil, err - } - - msg := &nl.Genlmsg{ - Command: cmd, - Version: nl.GENL_DEVLINK_VERSION, - } - req := h.newNetlinkRequest(int(f.ID), - unix.NLM_F_REQUEST|unix.NLM_F_ACK) - req.AddData(msg) - - b := make([]byte, len(bus)+1) - copy(b, bus) - data := nl.NewRtAttr(nl.DEVLINK_ATTR_BUS_NAME, b) - req.AddData(data) - - b = make([]byte, len(device)+1) - copy(b, device) - data = nl.NewRtAttr(nl.DEVLINK_ATTR_DEV_NAME, b) - req.AddData(data) - - return f, req, nil -} - -// DevlinkGetDeviceByName provides a pointer to devlink device and nil error, -// otherwise returns an error code. -func (h *Handle) DevLinkGetDeviceByName(Bus string, Device string) (*DevlinkDevice, error) { - f, req, err := h.createCmdReq(nl.DEVLINK_CMD_GET, Bus, Device) - if err != nil { - return nil, err - } - - respmsg, err := req.Execute(unix.NETLINK_GENERIC, 0) - if err != nil { - return nil, err - } - dev, err := parseDevlinkDevice(respmsg) - if err == nil { - h.getEswitchAttrs(f, dev) - } - return dev, err -} - -// DevlinkGetDeviceByName provides a pointer to devlink device and nil error, -// otherwise returns an error code. -func DevLinkGetDeviceByName(Bus string, Device string) (*DevlinkDevice, error) { - return pkgHandle.DevLinkGetDeviceByName(Bus, Device) -} - -// DevLinkSetEswitchMode sets eswitch mode if able to set successfully or -// returns an error code. -// Equivalent to: `devlink dev eswitch set $dev mode switchdev` -// Equivalent to: `devlink dev eswitch set $dev mode legacy` -func (h *Handle) DevLinkSetEswitchMode(Dev *DevlinkDevice, NewMode string) error { - mode, err := eswitchStringToMode(NewMode) - if err != nil { - return err - } - - _, req, err := h.createCmdReq(nl.DEVLINK_CMD_ESWITCH_SET, Dev.BusName, Dev.DeviceName) - if err != nil { - return err - } - - req.AddData(nl.NewRtAttr(nl.DEVLINK_ATTR_ESWITCH_MODE, nl.Uint16Attr(mode))) - - _, err = req.Execute(unix.NETLINK_GENERIC, 0) - return err -} - -// DevLinkSetEswitchMode sets eswitch mode if able to set successfully or -// returns an error code. -// Equivalent to: `devlink dev eswitch set $dev mode switchdev` -// Equivalent to: `devlink dev eswitch set $dev mode legacy` -func DevLinkSetEswitchMode(Dev *DevlinkDevice, NewMode string) error { - return pkgHandle.DevLinkSetEswitchMode(Dev, NewMode) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/filter.go b/examples/vendor/github.com/vishvananda/netlink/filter.go deleted file mode 100644 index 2dc34b9..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/filter.go +++ /dev/null @@ -1,325 +0,0 @@ -package netlink - -import ( - "fmt" - "net" -) - -type Filter interface { - Attrs() *FilterAttrs - Type() string -} - -// FilterAttrs represents a netlink filter. A filter is associated with a link, -// has a handle and a parent. The root filter of a device should have a -// parent == HANDLE_ROOT. -type FilterAttrs struct { - LinkIndex int - Handle uint32 - Parent uint32 - Priority uint16 // lower is higher priority - Protocol uint16 // unix.ETH_P_* -} - -func (q FilterAttrs) String() string { - return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol) -} - -type TcAct int32 - -const ( - TC_ACT_UNSPEC TcAct = -1 - TC_ACT_OK TcAct = 0 - TC_ACT_RECLASSIFY TcAct = 1 - TC_ACT_SHOT TcAct = 2 - TC_ACT_PIPE TcAct = 3 - TC_ACT_STOLEN TcAct = 4 - TC_ACT_QUEUED TcAct = 5 - TC_ACT_REPEAT TcAct = 6 - TC_ACT_REDIRECT TcAct = 7 - TC_ACT_JUMP TcAct = 0x10000000 -) - -func (a TcAct) String() string { - switch a { - case TC_ACT_UNSPEC: - return "unspec" - case TC_ACT_OK: - return "ok" - case TC_ACT_RECLASSIFY: - return "reclassify" - case TC_ACT_SHOT: - return "shot" - case TC_ACT_PIPE: - return "pipe" - case TC_ACT_STOLEN: - return "stolen" - case TC_ACT_QUEUED: - return "queued" - case TC_ACT_REPEAT: - return "repeat" - case TC_ACT_REDIRECT: - return "redirect" - case TC_ACT_JUMP: - return "jump" - } - return fmt.Sprintf("0x%x", int32(a)) -} - -type TcPolAct int32 - -const ( - TC_POLICE_UNSPEC TcPolAct = TcPolAct(TC_ACT_UNSPEC) - TC_POLICE_OK TcPolAct = TcPolAct(TC_ACT_OK) - TC_POLICE_RECLASSIFY TcPolAct = TcPolAct(TC_ACT_RECLASSIFY) - TC_POLICE_SHOT TcPolAct = TcPolAct(TC_ACT_SHOT) - TC_POLICE_PIPE TcPolAct = TcPolAct(TC_ACT_PIPE) -) - -func (a TcPolAct) String() string { - switch a { - case TC_POLICE_UNSPEC: - return "unspec" - case TC_POLICE_OK: - return "ok" - case TC_POLICE_RECLASSIFY: - return "reclassify" - case TC_POLICE_SHOT: - return "shot" - case TC_POLICE_PIPE: - return "pipe" - } - return fmt.Sprintf("0x%x", int32(a)) -} - -type ActionAttrs struct { - Index int - Capab int - Action TcAct - Refcnt int - Bindcnt int -} - -func (q ActionAttrs) String() string { - return fmt.Sprintf("{Index: %d, Capab: %x, Action: %s, Refcnt: %d, Bindcnt: %d}", q.Index, q.Capab, q.Action.String(), q.Refcnt, q.Bindcnt) -} - -// Action represents an action in any supported filter. -type Action interface { - Attrs() *ActionAttrs - Type() string -} - -type GenericAction struct { - ActionAttrs -} - -func (action *GenericAction) Type() string { - return "generic" -} - -func (action *GenericAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -type BpfAction struct { - ActionAttrs - Fd int - Name string -} - -func (action *BpfAction) Type() string { - return "bpf" -} - -func (action *BpfAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -type ConnmarkAction struct { - ActionAttrs - Zone uint16 -} - -func (action *ConnmarkAction) Type() string { - return "connmark" -} - -func (action *ConnmarkAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -func NewConnmarkAction() *ConnmarkAction { - return &ConnmarkAction{ - ActionAttrs: ActionAttrs{ - Action: TC_ACT_PIPE, - }, - } -} - -type MirredAct uint8 - -func (a MirredAct) String() string { - switch a { - case TCA_EGRESS_REDIR: - return "egress redir" - case TCA_EGRESS_MIRROR: - return "egress mirror" - case TCA_INGRESS_REDIR: - return "ingress redir" - case TCA_INGRESS_MIRROR: - return "ingress mirror" - } - return "unknown" -} - -const ( - TCA_EGRESS_REDIR MirredAct = 1 /* packet redirect to EGRESS*/ - TCA_EGRESS_MIRROR MirredAct = 2 /* mirror packet to EGRESS */ - TCA_INGRESS_REDIR MirredAct = 3 /* packet redirect to INGRESS*/ - TCA_INGRESS_MIRROR MirredAct = 4 /* mirror packet to INGRESS */ -) - -type MirredAction struct { - ActionAttrs - MirredAction MirredAct - Ifindex int -} - -func (action *MirredAction) Type() string { - return "mirred" -} - -func (action *MirredAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -func NewMirredAction(redirIndex int) *MirredAction { - return &MirredAction{ - ActionAttrs: ActionAttrs{ - Action: TC_ACT_STOLEN, - }, - MirredAction: TCA_EGRESS_REDIR, - Ifindex: redirIndex, - } -} - -type TunnelKeyAct int8 - -const ( - TCA_TUNNEL_KEY_SET TunnelKeyAct = 1 // set tunnel key - TCA_TUNNEL_KEY_UNSET TunnelKeyAct = 2 // unset tunnel key -) - -type TunnelKeyAction struct { - ActionAttrs - Action TunnelKeyAct - SrcAddr net.IP - DstAddr net.IP - KeyID uint32 - DestPort uint16 -} - -func (action *TunnelKeyAction) Type() string { - return "tunnel_key" -} - -func (action *TunnelKeyAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -func NewTunnelKeyAction() *TunnelKeyAction { - return &TunnelKeyAction{ - ActionAttrs: ActionAttrs{ - Action: TC_ACT_PIPE, - }, - } -} - -type SkbEditAction struct { - ActionAttrs - QueueMapping *uint16 - PType *uint16 - Priority *uint32 - Mark *uint32 -} - -func (action *SkbEditAction) Type() string { - return "skbedit" -} - -func (action *SkbEditAction) Attrs() *ActionAttrs { - return &action.ActionAttrs -} - -func NewSkbEditAction() *SkbEditAction { - return &SkbEditAction{ - ActionAttrs: ActionAttrs{ - Action: TC_ACT_PIPE, - }, - } -} - -// MatchAll filters match all packets -type MatchAll struct { - FilterAttrs - ClassId uint32 - Actions []Action -} - -func (filter *MatchAll) Attrs() *FilterAttrs { - return &filter.FilterAttrs -} - -func (filter *MatchAll) Type() string { - return "matchall" -} - -type FilterFwAttrs struct { - ClassId uint32 - InDev string - Mask uint32 - Index uint32 - Buffer uint32 - Mtu uint32 - Mpu uint16 - Rate uint32 - AvRate uint32 - PeakRate uint32 - Action TcPolAct - Overhead uint16 - LinkLayer int -} - -type BpfFilter struct { - FilterAttrs - ClassId uint32 - Fd int - Name string - DirectAction bool - Id int - Tag string -} - -func (filter *BpfFilter) Type() string { - return "bpf" -} - -func (filter *BpfFilter) Attrs() *FilterAttrs { - return &filter.FilterAttrs -} - -// GenericFilter filters represent types that are not currently understood -// by this netlink library. -type GenericFilter struct { - FilterAttrs - FilterType string -} - -func (filter *GenericFilter) Attrs() *FilterAttrs { - return &filter.FilterAttrs -} - -func (filter *GenericFilter) Type() string { - return filter.FilterType -} diff --git a/examples/vendor/github.com/vishvananda/netlink/filter_linux.go b/examples/vendor/github.com/vishvananda/netlink/filter_linux.go deleted file mode 100644 index ef6fabe..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/filter_linux.go +++ /dev/null @@ -1,809 +0,0 @@ -package netlink - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "errors" - "fmt" - "syscall" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// Constants used in TcU32Sel.Flags. -const ( - TC_U32_TERMINAL = nl.TC_U32_TERMINAL - TC_U32_OFFSET = nl.TC_U32_OFFSET - TC_U32_VAROFFSET = nl.TC_U32_VAROFFSET - TC_U32_EAT = nl.TC_U32_EAT -) - -// Sel of the U32 filters that contains multiple TcU32Key. This is the type -// alias and the frontend representation of nl.TcU32Sel. It is serialized into -// canonical nl.TcU32Sel with the appropriate endianness. -type TcU32Sel = nl.TcU32Sel - -// TcU32Key contained of Sel in the U32 filters. This is the type alias and the -// frontend representation of nl.TcU32Key. It is serialized into chanonical -// nl.TcU32Sel with the appropriate endianness. -type TcU32Key = nl.TcU32Key - -// U32 filters on many packet related properties -type U32 struct { - FilterAttrs - ClassId uint32 - Divisor uint32 // Divisor MUST be power of 2. - Hash uint32 - RedirIndex int - Sel *TcU32Sel - Actions []Action -} - -func (filter *U32) Attrs() *FilterAttrs { - return &filter.FilterAttrs -} - -func (filter *U32) Type() string { - return "u32" -} - -// Fw filter filters on firewall marks -// NOTE: this is in filter_linux because it refers to nl.TcPolice which -// is defined in nl/tc_linux.go -type Fw struct { - FilterAttrs - ClassId uint32 - // TODO remove nl type from interface - Police nl.TcPolice - InDev string - // TODO Action - Mask uint32 - AvRate uint32 - Rtab [256]uint32 - Ptab [256]uint32 -} - -func NewFw(attrs FilterAttrs, fattrs FilterFwAttrs) (*Fw, error) { - var rtab [256]uint32 - var ptab [256]uint32 - rcellLog := -1 - pcellLog := -1 - avrate := fattrs.AvRate / 8 - police := nl.TcPolice{} - police.Rate.Rate = fattrs.Rate / 8 - police.PeakRate.Rate = fattrs.PeakRate / 8 - buffer := fattrs.Buffer - linklayer := nl.LINKLAYER_ETHERNET - - if fattrs.LinkLayer != nl.LINKLAYER_UNSPEC { - linklayer = fattrs.LinkLayer - } - - police.Action = int32(fattrs.Action) - if police.Rate.Rate != 0 { - police.Rate.Mpu = fattrs.Mpu - police.Rate.Overhead = fattrs.Overhead - if CalcRtable(&police.Rate, rtab[:], rcellLog, fattrs.Mtu, linklayer) < 0 { - return nil, errors.New("TBF: failed to calculate rate table") - } - police.Burst = Xmittime(uint64(police.Rate.Rate), uint32(buffer)) - } - police.Mtu = fattrs.Mtu - if police.PeakRate.Rate != 0 { - police.PeakRate.Mpu = fattrs.Mpu - police.PeakRate.Overhead = fattrs.Overhead - if CalcRtable(&police.PeakRate, ptab[:], pcellLog, fattrs.Mtu, linklayer) < 0 { - return nil, errors.New("POLICE: failed to calculate peak rate table") - } - } - - return &Fw{ - FilterAttrs: attrs, - ClassId: fattrs.ClassId, - InDev: fattrs.InDev, - Mask: fattrs.Mask, - Police: police, - AvRate: avrate, - Rtab: rtab, - Ptab: ptab, - }, nil -} - -func (filter *Fw) Attrs() *FilterAttrs { - return &filter.FilterAttrs -} - -func (filter *Fw) Type() string { - return "fw" -} - -// FilterDel will delete a filter from the system. -// Equivalent to: `tc filter del $filter` -func FilterDel(filter Filter) error { - return pkgHandle.FilterDel(filter) -} - -// FilterDel will delete a filter from the system. -// Equivalent to: `tc filter del $filter` -func (h *Handle) FilterDel(filter Filter) error { - req := h.newNetlinkRequest(unix.RTM_DELTFILTER, unix.NLM_F_ACK) - base := filter.Attrs() - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Ifindex: int32(base.LinkIndex), - Handle: base.Handle, - Parent: base.Parent, - Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)), - } - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// FilterAdd will add a filter to the system. -// Equivalent to: `tc filter add $filter` -func FilterAdd(filter Filter) error { - return pkgHandle.FilterAdd(filter) -} - -// FilterAdd will add a filter to the system. -// Equivalent to: `tc filter add $filter` -func (h *Handle) FilterAdd(filter Filter) error { - return h.filterModify(filter, unix.NLM_F_CREATE|unix.NLM_F_EXCL) -} - -// FilterReplace will replace a filter. -// Equivalent to: `tc filter replace $filter` -func FilterReplace(filter Filter) error { - return pkgHandle.FilterReplace(filter) -} - -// FilterReplace will replace a filter. -// Equivalent to: `tc filter replace $filter` -func (h *Handle) FilterReplace(filter Filter) error { - return h.filterModify(filter, unix.NLM_F_CREATE) -} - -func (h *Handle) filterModify(filter Filter, flags int) error { - native = nl.NativeEndian() - req := h.newNetlinkRequest(unix.RTM_NEWTFILTER, flags|unix.NLM_F_ACK) - base := filter.Attrs() - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Ifindex: int32(base.LinkIndex), - Handle: base.Handle, - Parent: base.Parent, - Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)), - } - req.AddData(msg) - req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(filter.Type()))) - - options := nl.NewRtAttr(nl.TCA_OPTIONS, nil) - - switch filter := filter.(type) { - case *U32: - sel := filter.Sel - if sel == nil { - // match all - sel = &nl.TcU32Sel{ - Nkeys: 1, - Flags: nl.TC_U32_TERMINAL, - } - sel.Keys = append(sel.Keys, nl.TcU32Key{}) - } - - if native != networkOrder { - // Copy TcU32Sel. - cSel := *sel - keys := make([]nl.TcU32Key, cap(sel.Keys)) - copy(keys, sel.Keys) - cSel.Keys = keys - sel = &cSel - - // Handle the endianness of attributes - sel.Offmask = native.Uint16(htons(sel.Offmask)) - sel.Hmask = native.Uint32(htonl(sel.Hmask)) - for i, key := range sel.Keys { - sel.Keys[i].Mask = native.Uint32(htonl(key.Mask)) - sel.Keys[i].Val = native.Uint32(htonl(key.Val)) - } - } - sel.Nkeys = uint8(len(sel.Keys)) - options.AddRtAttr(nl.TCA_U32_SEL, sel.Serialize()) - if filter.ClassId != 0 { - options.AddRtAttr(nl.TCA_U32_CLASSID, nl.Uint32Attr(filter.ClassId)) - } - if filter.Divisor != 0 { - if (filter.Divisor-1)&filter.Divisor != 0 { - return fmt.Errorf("illegal divisor %d. Must be a power of 2", filter.Divisor) - } - options.AddRtAttr(nl.TCA_U32_DIVISOR, nl.Uint32Attr(filter.Divisor)) - } - if filter.Hash != 0 { - options.AddRtAttr(nl.TCA_U32_HASH, nl.Uint32Attr(filter.Hash)) - } - actionsAttr := options.AddRtAttr(nl.TCA_U32_ACT, nil) - // backwards compatibility - if filter.RedirIndex != 0 { - filter.Actions = append([]Action{NewMirredAction(filter.RedirIndex)}, filter.Actions...) - } - if err := EncodeActions(actionsAttr, filter.Actions); err != nil { - return err - } - case *Fw: - if filter.Mask != 0 { - b := make([]byte, 4) - native.PutUint32(b, filter.Mask) - options.AddRtAttr(nl.TCA_FW_MASK, b) - } - if filter.InDev != "" { - options.AddRtAttr(nl.TCA_FW_INDEV, nl.ZeroTerminated(filter.InDev)) - } - if (filter.Police != nl.TcPolice{}) { - - police := options.AddRtAttr(nl.TCA_FW_POLICE, nil) - police.AddRtAttr(nl.TCA_POLICE_TBF, filter.Police.Serialize()) - if (filter.Police.Rate != nl.TcRateSpec{}) { - payload := SerializeRtab(filter.Rtab) - police.AddRtAttr(nl.TCA_POLICE_RATE, payload) - } - if (filter.Police.PeakRate != nl.TcRateSpec{}) { - payload := SerializeRtab(filter.Ptab) - police.AddRtAttr(nl.TCA_POLICE_PEAKRATE, payload) - } - } - if filter.ClassId != 0 { - b := make([]byte, 4) - native.PutUint32(b, filter.ClassId) - options.AddRtAttr(nl.TCA_FW_CLASSID, b) - } - case *BpfFilter: - var bpfFlags uint32 - if filter.ClassId != 0 { - options.AddRtAttr(nl.TCA_BPF_CLASSID, nl.Uint32Attr(filter.ClassId)) - } - if filter.Fd >= 0 { - options.AddRtAttr(nl.TCA_BPF_FD, nl.Uint32Attr((uint32(filter.Fd)))) - } - if filter.Name != "" { - options.AddRtAttr(nl.TCA_BPF_NAME, nl.ZeroTerminated(filter.Name)) - } - if filter.DirectAction { - bpfFlags |= nl.TCA_BPF_FLAG_ACT_DIRECT - } - options.AddRtAttr(nl.TCA_BPF_FLAGS, nl.Uint32Attr(bpfFlags)) - case *MatchAll: - actionsAttr := options.AddRtAttr(nl.TCA_MATCHALL_ACT, nil) - if err := EncodeActions(actionsAttr, filter.Actions); err != nil { - return err - } - if filter.ClassId != 0 { - options.AddRtAttr(nl.TCA_MATCHALL_CLASSID, nl.Uint32Attr(filter.ClassId)) - } - } - - req.AddData(options) - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// FilterList gets a list of filters in the system. -// Equivalent to: `tc filter show`. -// Generally returns nothing if link and parent are not specified. -func FilterList(link Link, parent uint32) ([]Filter, error) { - return pkgHandle.FilterList(link, parent) -} - -// FilterList gets a list of filters in the system. -// Equivalent to: `tc filter show`. -// Generally returns nothing if link and parent are not specified. -func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) { - req := h.newNetlinkRequest(unix.RTM_GETTFILTER, unix.NLM_F_DUMP) - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Parent: parent, - } - if link != nil { - base := link.Attrs() - h.ensureIndex(base) - msg.Ifindex = int32(base.Index) - } - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWTFILTER) - if err != nil { - return nil, err - } - - var res []Filter - for _, m := range msgs { - msg := nl.DeserializeTcMsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - base := FilterAttrs{ - LinkIndex: int(msg.Ifindex), - Handle: msg.Handle, - Parent: msg.Parent, - } - base.Priority, base.Protocol = MajorMinor(msg.Info) - base.Protocol = nl.Swap16(base.Protocol) - - var filter Filter - filterType := "" - detailed := false - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.TCA_KIND: - filterType = string(attr.Value[:len(attr.Value)-1]) - switch filterType { - case "u32": - filter = &U32{} - case "fw": - filter = &Fw{} - case "bpf": - filter = &BpfFilter{} - case "matchall": - filter = &MatchAll{} - default: - filter = &GenericFilter{FilterType: filterType} - } - case nl.TCA_OPTIONS: - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - switch filterType { - case "u32": - detailed, err = parseU32Data(filter, data) - if err != nil { - return nil, err - } - case "fw": - detailed, err = parseFwData(filter, data) - if err != nil { - return nil, err - } - case "bpf": - detailed, err = parseBpfData(filter, data) - if err != nil { - return nil, err - } - case "matchall": - detailed, err = parseMatchAllData(filter, data) - if err != nil { - return nil, err - } - default: - detailed = true - } - } - } - // only return the detailed version of the filter - if detailed { - *filter.Attrs() = base - res = append(res, filter) - } - } - - return res, nil -} - -func toTcGen(attrs *ActionAttrs, tcgen *nl.TcGen) { - tcgen.Index = uint32(attrs.Index) - tcgen.Capab = uint32(attrs.Capab) - tcgen.Action = int32(attrs.Action) - tcgen.Refcnt = int32(attrs.Refcnt) - tcgen.Bindcnt = int32(attrs.Bindcnt) -} - -func toAttrs(tcgen *nl.TcGen, attrs *ActionAttrs) { - attrs.Index = int(tcgen.Index) - attrs.Capab = int(tcgen.Capab) - attrs.Action = TcAct(tcgen.Action) - attrs.Refcnt = int(tcgen.Refcnt) - attrs.Bindcnt = int(tcgen.Bindcnt) -} - -func EncodeActions(attr *nl.RtAttr, actions []Action) error { - tabIndex := int(nl.TCA_ACT_TAB) - - for _, action := range actions { - switch action := action.(type) { - default: - return fmt.Errorf("unknown action type %s", action.Type()) - case *MirredAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("mirred")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - mirred := nl.TcMirred{ - Eaction: int32(action.MirredAction), - Ifindex: uint32(action.Ifindex), - } - toTcGen(action.Attrs(), &mirred.TcGen) - aopts.AddRtAttr(nl.TCA_MIRRED_PARMS, mirred.Serialize()) - case *TunnelKeyAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("tunnel_key")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - tun := nl.TcTunnelKey{ - Action: int32(action.Action), - } - toTcGen(action.Attrs(), &tun.TcGen) - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_PARMS, tun.Serialize()) - if action.Action == TCA_TUNNEL_KEY_SET { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_KEY_ID, htonl(action.KeyID)) - if v4 := action.SrcAddr.To4(); v4 != nil { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV4_SRC, v4[:]) - } else if v6 := action.SrcAddr.To16(); v6 != nil { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV6_SRC, v6[:]) - } else { - return fmt.Errorf("invalid src addr %s for tunnel_key action", action.SrcAddr) - } - if v4 := action.DstAddr.To4(); v4 != nil { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV4_DST, v4[:]) - } else if v6 := action.DstAddr.To16(); v6 != nil { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_IPV6_DST, v6[:]) - } else { - return fmt.Errorf("invalid dst addr %s for tunnel_key action", action.DstAddr) - } - if action.DestPort != 0 { - aopts.AddRtAttr(nl.TCA_TUNNEL_KEY_ENC_DST_PORT, htons(action.DestPort)) - } - } - case *SkbEditAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("skbedit")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - skbedit := nl.TcSkbEdit{} - toTcGen(action.Attrs(), &skbedit.TcGen) - aopts.AddRtAttr(nl.TCA_SKBEDIT_PARMS, skbedit.Serialize()) - if action.QueueMapping != nil { - aopts.AddRtAttr(nl.TCA_SKBEDIT_QUEUE_MAPPING, nl.Uint16Attr(*action.QueueMapping)) - } - if action.Priority != nil { - aopts.AddRtAttr(nl.TCA_SKBEDIT_PRIORITY, nl.Uint32Attr(*action.Priority)) - } - if action.PType != nil { - aopts.AddRtAttr(nl.TCA_SKBEDIT_PTYPE, nl.Uint16Attr(*action.PType)) - } - if action.Mark != nil { - aopts.AddRtAttr(nl.TCA_SKBEDIT_MARK, nl.Uint32Attr(*action.Mark)) - } - case *ConnmarkAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("connmark")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - connmark := nl.TcConnmark{ - Zone: action.Zone, - } - toTcGen(action.Attrs(), &connmark.TcGen) - aopts.AddRtAttr(nl.TCA_CONNMARK_PARMS, connmark.Serialize()) - case *BpfAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("bpf")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - gen := nl.TcGen{} - toTcGen(action.Attrs(), &gen) - aopts.AddRtAttr(nl.TCA_ACT_BPF_PARMS, gen.Serialize()) - aopts.AddRtAttr(nl.TCA_ACT_BPF_FD, nl.Uint32Attr(uint32(action.Fd))) - aopts.AddRtAttr(nl.TCA_ACT_BPF_NAME, nl.ZeroTerminated(action.Name)) - case *GenericAction: - table := attr.AddRtAttr(tabIndex, nil) - tabIndex++ - table.AddRtAttr(nl.TCA_ACT_KIND, nl.ZeroTerminated("gact")) - aopts := table.AddRtAttr(nl.TCA_ACT_OPTIONS, nil) - gen := nl.TcGen{} - toTcGen(action.Attrs(), &gen) - aopts.AddRtAttr(nl.TCA_GACT_PARMS, gen.Serialize()) - } - } - return nil -} - -func parseActions(tables []syscall.NetlinkRouteAttr) ([]Action, error) { - var actions []Action - for _, table := range tables { - var action Action - var actionType string - aattrs, err := nl.ParseRouteAttr(table.Value) - if err != nil { - return nil, err - } - nextattr: - for _, aattr := range aattrs { - switch aattr.Attr.Type { - case nl.TCA_KIND: - actionType = string(aattr.Value[:len(aattr.Value)-1]) - // only parse if the action is mirred or bpf - switch actionType { - case "mirred": - action = &MirredAction{} - case "bpf": - action = &BpfAction{} - case "connmark": - action = &ConnmarkAction{} - case "gact": - action = &GenericAction{} - case "tunnel_key": - action = &TunnelKeyAction{} - case "skbedit": - action = &SkbEditAction{} - default: - break nextattr - } - case nl.TCA_OPTIONS: - adata, err := nl.ParseRouteAttr(aattr.Value) - if err != nil { - return nil, err - } - for _, adatum := range adata { - switch actionType { - case "mirred": - switch adatum.Attr.Type { - case nl.TCA_MIRRED_PARMS: - mirred := *nl.DeserializeTcMirred(adatum.Value) - action.(*MirredAction).ActionAttrs = ActionAttrs{} - toAttrs(&mirred.TcGen, action.Attrs()) - action.(*MirredAction).Ifindex = int(mirred.Ifindex) - action.(*MirredAction).MirredAction = MirredAct(mirred.Eaction) - } - case "tunnel_key": - switch adatum.Attr.Type { - case nl.TCA_TUNNEL_KEY_PARMS: - tun := *nl.DeserializeTunnelKey(adatum.Value) - action.(*TunnelKeyAction).ActionAttrs = ActionAttrs{} - toAttrs(&tun.TcGen, action.Attrs()) - action.(*TunnelKeyAction).Action = TunnelKeyAct(tun.Action) - case nl.TCA_TUNNEL_KEY_ENC_KEY_ID: - action.(*TunnelKeyAction).KeyID = networkOrder.Uint32(adatum.Value[0:4]) - case nl.TCA_TUNNEL_KEY_ENC_IPV6_SRC, nl.TCA_TUNNEL_KEY_ENC_IPV4_SRC: - action.(*TunnelKeyAction).SrcAddr = adatum.Value[:] - case nl.TCA_TUNNEL_KEY_ENC_IPV6_DST, nl.TCA_TUNNEL_KEY_ENC_IPV4_DST: - action.(*TunnelKeyAction).DstAddr = adatum.Value[:] - case nl.TCA_TUNNEL_KEY_ENC_DST_PORT: - action.(*TunnelKeyAction).DestPort = ntohs(adatum.Value) - } - case "skbedit": - switch adatum.Attr.Type { - case nl.TCA_SKBEDIT_PARMS: - skbedit := *nl.DeserializeSkbEdit(adatum.Value) - action.(*SkbEditAction).ActionAttrs = ActionAttrs{} - toAttrs(&skbedit.TcGen, action.Attrs()) - case nl.TCA_SKBEDIT_MARK: - mark := native.Uint32(adatum.Value[0:4]) - action.(*SkbEditAction).Mark = &mark - case nl.TCA_SKBEDIT_PRIORITY: - priority := native.Uint32(adatum.Value[0:4]) - action.(*SkbEditAction).Priority = &priority - case nl.TCA_SKBEDIT_PTYPE: - ptype := native.Uint16(adatum.Value[0:2]) - action.(*SkbEditAction).PType = &ptype - case nl.TCA_SKBEDIT_QUEUE_MAPPING: - mapping := native.Uint16(adatum.Value[0:2]) - action.(*SkbEditAction).QueueMapping = &mapping - } - case "bpf": - switch adatum.Attr.Type { - case nl.TCA_ACT_BPF_PARMS: - gen := *nl.DeserializeTcGen(adatum.Value) - toAttrs(&gen, action.Attrs()) - case nl.TCA_ACT_BPF_FD: - action.(*BpfAction).Fd = int(native.Uint32(adatum.Value[0:4])) - case nl.TCA_ACT_BPF_NAME: - action.(*BpfAction).Name = string(adatum.Value[:len(adatum.Value)-1]) - } - case "connmark": - switch adatum.Attr.Type { - case nl.TCA_CONNMARK_PARMS: - connmark := *nl.DeserializeTcConnmark(adatum.Value) - action.(*ConnmarkAction).ActionAttrs = ActionAttrs{} - toAttrs(&connmark.TcGen, action.Attrs()) - action.(*ConnmarkAction).Zone = connmark.Zone - } - case "gact": - switch adatum.Attr.Type { - case nl.TCA_GACT_PARMS: - gen := *nl.DeserializeTcGen(adatum.Value) - toAttrs(&gen, action.Attrs()) - } - } - } - } - } - actions = append(actions, action) - } - return actions, nil -} - -func parseU32Data(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) { - native = nl.NativeEndian() - u32 := filter.(*U32) - detailed := false - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_U32_SEL: - detailed = true - sel := nl.DeserializeTcU32Sel(datum.Value) - u32.Sel = sel - if native != networkOrder { - // Handle the endianness of attributes - u32.Sel.Offmask = native.Uint16(htons(sel.Offmask)) - u32.Sel.Hmask = native.Uint32(htonl(sel.Hmask)) - for i, key := range u32.Sel.Keys { - u32.Sel.Keys[i].Mask = native.Uint32(htonl(key.Mask)) - u32.Sel.Keys[i].Val = native.Uint32(htonl(key.Val)) - } - } - case nl.TCA_U32_ACT: - tables, err := nl.ParseRouteAttr(datum.Value) - if err != nil { - return detailed, err - } - u32.Actions, err = parseActions(tables) - if err != nil { - return detailed, err - } - for _, action := range u32.Actions { - if action, ok := action.(*MirredAction); ok { - u32.RedirIndex = int(action.Ifindex) - } - } - case nl.TCA_U32_CLASSID: - u32.ClassId = native.Uint32(datum.Value) - case nl.TCA_U32_DIVISOR: - u32.Divisor = native.Uint32(datum.Value) - case nl.TCA_U32_HASH: - u32.Hash = native.Uint32(datum.Value) - } - } - return detailed, nil -} - -func parseFwData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) { - native = nl.NativeEndian() - fw := filter.(*Fw) - detailed := true - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_FW_MASK: - fw.Mask = native.Uint32(datum.Value[0:4]) - case nl.TCA_FW_CLASSID: - fw.ClassId = native.Uint32(datum.Value[0:4]) - case nl.TCA_FW_INDEV: - fw.InDev = string(datum.Value[:len(datum.Value)-1]) - case nl.TCA_FW_POLICE: - adata, _ := nl.ParseRouteAttr(datum.Value) - for _, aattr := range adata { - switch aattr.Attr.Type { - case nl.TCA_POLICE_TBF: - fw.Police = *nl.DeserializeTcPolice(aattr.Value) - case nl.TCA_POLICE_RATE: - fw.Rtab = DeserializeRtab(aattr.Value) - case nl.TCA_POLICE_PEAKRATE: - fw.Ptab = DeserializeRtab(aattr.Value) - } - } - } - } - return detailed, nil -} - -func parseBpfData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) { - native = nl.NativeEndian() - bpf := filter.(*BpfFilter) - detailed := true - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_BPF_FD: - bpf.Fd = int(native.Uint32(datum.Value[0:4])) - case nl.TCA_BPF_NAME: - bpf.Name = string(datum.Value[:len(datum.Value)-1]) - case nl.TCA_BPF_CLASSID: - bpf.ClassId = native.Uint32(datum.Value[0:4]) - case nl.TCA_BPF_FLAGS: - flags := native.Uint32(datum.Value[0:4]) - if (flags & nl.TCA_BPF_FLAG_ACT_DIRECT) != 0 { - bpf.DirectAction = true - } - case nl.TCA_BPF_ID: - bpf.Id = int(native.Uint32(datum.Value[0:4])) - case nl.TCA_BPF_TAG: - bpf.Tag = hex.EncodeToString(datum.Value[:len(datum.Value)-1]) - } - } - return detailed, nil -} - -func parseMatchAllData(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) { - native = nl.NativeEndian() - matchall := filter.(*MatchAll) - detailed := true - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_MATCHALL_CLASSID: - matchall.ClassId = native.Uint32(datum.Value[0:4]) - case nl.TCA_MATCHALL_ACT: - tables, err := nl.ParseRouteAttr(datum.Value) - if err != nil { - return detailed, err - } - matchall.Actions, err = parseActions(tables) - if err != nil { - return detailed, err - } - } - } - return detailed, nil -} - -func AlignToAtm(size uint) uint { - var linksize, cells int - cells = int(size / nl.ATM_CELL_PAYLOAD) - if (size % nl.ATM_CELL_PAYLOAD) > 0 { - cells++ - } - linksize = cells * nl.ATM_CELL_SIZE - return uint(linksize) -} - -func AdjustSize(sz uint, mpu uint, linklayer int) uint { - if sz < mpu { - sz = mpu - } - switch linklayer { - case nl.LINKLAYER_ATM: - return AlignToAtm(sz) - default: - return sz - } -} - -func CalcRtable(rate *nl.TcRateSpec, rtab []uint32, cellLog int, mtu uint32, linklayer int) int { - bps := rate.Rate - mpu := rate.Mpu - var sz uint - if mtu == 0 { - mtu = 2047 - } - if cellLog < 0 { - cellLog = 0 - for (mtu >> uint(cellLog)) > 255 { - cellLog++ - } - } - for i := 0; i < 256; i++ { - sz = AdjustSize(uint((i+1)<= nl.IPSET_ERR_PRIVATE { - err = nl.IPSetError(uintptr(errno)) - } - } - return -} - -func ipsetUnserialize(msgs [][]byte) (result IPSetResult) { - for _, msg := range msgs { - result.unserialize(msg) - } - return result -} - -func (result *IPSetResult) unserialize(msg []byte) { - result.Nfgenmsg = nl.DeserializeNfgenmsg(msg) - - for attr := range nl.ParseAttributes(msg[4:]) { - switch attr.Type { - case nl.IPSET_ATTR_PROTOCOL: - result.Protocol = attr.Value[0] - case nl.IPSET_ATTR_SETNAME: - result.SetName = nl.BytesToString(attr.Value) - case nl.IPSET_ATTR_TYPENAME: - result.TypeName = nl.BytesToString(attr.Value) - case nl.IPSET_ATTR_REVISION: - result.Revision = attr.Value[0] - case nl.IPSET_ATTR_FAMILY: - result.Family = attr.Value[0] - case nl.IPSET_ATTR_FLAGS: - result.Flags = attr.Value[0] - case nl.IPSET_ATTR_DATA | nl.NLA_F_NESTED: - result.parseAttrData(attr.Value) - case nl.IPSET_ATTR_ADT | nl.NLA_F_NESTED: - result.parseAttrADT(attr.Value) - default: - log.Printf("unknown ipset attribute from kernel: %+v %v", attr, attr.Type&nl.NLA_TYPE_MASK) - } - } -} - -func (result *IPSetResult) parseAttrData(data []byte) { - for attr := range nl.ParseAttributes(data) { - switch attr.Type { - case nl.IPSET_ATTR_HASHSIZE | nl.NLA_F_NET_BYTEORDER: - result.HashSize = attr.Uint32() - case nl.IPSET_ATTR_MAXELEM | nl.NLA_F_NET_BYTEORDER: - result.MaxElements = attr.Uint32() - case nl.IPSET_ATTR_TIMEOUT | nl.NLA_F_NET_BYTEORDER: - val := attr.Uint32() - result.Timeout = &val - case nl.IPSET_ATTR_ELEMENTS | nl.NLA_F_NET_BYTEORDER: - result.NumEntries = attr.Uint32() - case nl.IPSET_ATTR_REFERENCES | nl.NLA_F_NET_BYTEORDER: - result.References = attr.Uint32() - case nl.IPSET_ATTR_MEMSIZE | nl.NLA_F_NET_BYTEORDER: - result.SizeInMemory = attr.Uint32() - case nl.IPSET_ATTR_CADT_FLAGS | nl.NLA_F_NET_BYTEORDER: - result.CadtFlags = attr.Uint32() - default: - log.Printf("unknown ipset data attribute from kernel: %+v %v", attr, attr.Type&nl.NLA_TYPE_MASK) - } - } -} - -func (result *IPSetResult) parseAttrADT(data []byte) { - for attr := range nl.ParseAttributes(data) { - switch attr.Type { - case nl.IPSET_ATTR_DATA | nl.NLA_F_NESTED: - result.Entries = append(result.Entries, parseIPSetEntry(attr.Value)) - default: - log.Printf("unknown ADT attribute from kernel: %+v %v", attr, attr.Type&nl.NLA_TYPE_MASK) - } - } -} - -func parseIPSetEntry(data []byte) (entry IPSetEntry) { - for attr := range nl.ParseAttributes(data) { - switch attr.Type { - case nl.IPSET_ATTR_TIMEOUT | nl.NLA_F_NET_BYTEORDER: - val := attr.Uint32() - entry.Timeout = &val - case nl.IPSET_ATTR_BYTES | nl.NLA_F_NET_BYTEORDER: - val := attr.Uint64() - entry.Bytes = &val - case nl.IPSET_ATTR_PACKETS | nl.NLA_F_NET_BYTEORDER: - val := attr.Uint64() - entry.Packets = &val - case nl.IPSET_ATTR_ETHER: - entry.MAC = net.HardwareAddr(attr.Value) - case nl.IPSET_ATTR_COMMENT: - entry.Comment = nl.BytesToString(attr.Value) - case nl.IPSET_ATTR_IP | nl.NLA_F_NESTED: - for attr := range nl.ParseAttributes(attr.Value) { - switch attr.Type { - case nl.IPSET_ATTR_IP: - entry.IP = net.IP(attr.Value) - default: - log.Printf("unknown nested ADT attribute from kernel: %+v", attr) - } - } - default: - log.Printf("unknown ADT attribute from kernel: %+v", attr) - } - } - return -} diff --git a/examples/vendor/github.com/vishvananda/netlink/link.go b/examples/vendor/github.com/vishvananda/netlink/link.go deleted file mode 100644 index e2441bd..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/link.go +++ /dev/null @@ -1,1098 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "os" - "strconv" -) - -// Link represents a link device from netlink. Shared link attributes -// like name may be retrieved using the Attrs() method. Unique data -// can be retrieved by casting the object to the proper type. -type Link interface { - Attrs() *LinkAttrs - Type() string -} - -type ( - NsPid int - NsFd int -) - -// LinkAttrs represents data shared by most link types -type LinkAttrs struct { - Index int - MTU int - TxQLen int // Transmit Queue Length - Name string - HardwareAddr net.HardwareAddr - Flags net.Flags - RawFlags uint32 - ParentIndex int // index of the parent link device - MasterIndex int // must be the index of a bridge - Namespace interface{} // nil | NsPid | NsFd - Alias string - Statistics *LinkStatistics - Promisc int - Xdp *LinkXdp - EncapType string - Protinfo *Protinfo - OperState LinkOperState - NetNsID int - NumTxQueues int - NumRxQueues int - GSOMaxSize uint32 - GSOMaxSegs uint32 - Vfs []VfInfo // virtual functions available on link - Group uint32 - Slave LinkSlave -} - -// LinkSlave represents a slave device. -type LinkSlave interface { - SlaveType() string -} - -// VfInfo represents configuration of virtual function -type VfInfo struct { - ID int - Mac net.HardwareAddr - Vlan int - Qos int - TxRate int // IFLA_VF_TX_RATE Max TxRate - Spoofchk bool - LinkState uint32 - MaxTxRate uint32 // IFLA_VF_RATE Max TxRate - MinTxRate uint32 // IFLA_VF_RATE Min TxRate - RxPackets uint64 - TxPackets uint64 - RxBytes uint64 - TxBytes uint64 - Multicast uint64 - Broadcast uint64 - RxDropped uint64 - TxDropped uint64 - - RssQuery uint32 - Trust uint32 -} - -// LinkOperState represents the values of the IFLA_OPERSTATE link -// attribute, which contains the RFC2863 state of the interface. -type LinkOperState uint8 - -const ( - OperUnknown = iota // Status can't be determined. - OperNotPresent // Some component is missing. - OperDown // Down. - OperLowerLayerDown // Down due to state of lower layer. - OperTesting // In some test mode. - OperDormant // Not up but pending an external event. - OperUp // Up, ready to send packets. -) - -func (s LinkOperState) String() string { - switch s { - case OperNotPresent: - return "not-present" - case OperDown: - return "down" - case OperLowerLayerDown: - return "lower-layer-down" - case OperTesting: - return "testing" - case OperDormant: - return "dormant" - case OperUp: - return "up" - default: - return "unknown" - } -} - -// NewLinkAttrs returns LinkAttrs structure filled with default values -func NewLinkAttrs() LinkAttrs { - return LinkAttrs{ - NetNsID: -1, - TxQLen: -1, - } -} - -type LinkStatistics LinkStatistics64 - -/* -Ref: struct rtnl_link_stats {...} -*/ -type LinkStatistics32 struct { - RxPackets uint32 - TxPackets uint32 - RxBytes uint32 - TxBytes uint32 - RxErrors uint32 - TxErrors uint32 - RxDropped uint32 - TxDropped uint32 - Multicast uint32 - Collisions uint32 - RxLengthErrors uint32 - RxOverErrors uint32 - RxCrcErrors uint32 - RxFrameErrors uint32 - RxFifoErrors uint32 - RxMissedErrors uint32 - TxAbortedErrors uint32 - TxCarrierErrors uint32 - TxFifoErrors uint32 - TxHeartbeatErrors uint32 - TxWindowErrors uint32 - RxCompressed uint32 - TxCompressed uint32 -} - -func (s32 LinkStatistics32) to64() *LinkStatistics64 { - return &LinkStatistics64{ - RxPackets: uint64(s32.RxPackets), - TxPackets: uint64(s32.TxPackets), - RxBytes: uint64(s32.RxBytes), - TxBytes: uint64(s32.TxBytes), - RxErrors: uint64(s32.RxErrors), - TxErrors: uint64(s32.TxErrors), - RxDropped: uint64(s32.RxDropped), - TxDropped: uint64(s32.TxDropped), - Multicast: uint64(s32.Multicast), - Collisions: uint64(s32.Collisions), - RxLengthErrors: uint64(s32.RxLengthErrors), - RxOverErrors: uint64(s32.RxOverErrors), - RxCrcErrors: uint64(s32.RxCrcErrors), - RxFrameErrors: uint64(s32.RxFrameErrors), - RxFifoErrors: uint64(s32.RxFifoErrors), - RxMissedErrors: uint64(s32.RxMissedErrors), - TxAbortedErrors: uint64(s32.TxAbortedErrors), - TxCarrierErrors: uint64(s32.TxCarrierErrors), - TxFifoErrors: uint64(s32.TxFifoErrors), - TxHeartbeatErrors: uint64(s32.TxHeartbeatErrors), - TxWindowErrors: uint64(s32.TxWindowErrors), - RxCompressed: uint64(s32.RxCompressed), - TxCompressed: uint64(s32.TxCompressed), - } -} - -/* -Ref: struct rtnl_link_stats64 {...} -*/ -type LinkStatistics64 struct { - RxPackets uint64 - TxPackets uint64 - RxBytes uint64 - TxBytes uint64 - RxErrors uint64 - TxErrors uint64 - RxDropped uint64 - TxDropped uint64 - Multicast uint64 - Collisions uint64 - RxLengthErrors uint64 - RxOverErrors uint64 - RxCrcErrors uint64 - RxFrameErrors uint64 - RxFifoErrors uint64 - RxMissedErrors uint64 - TxAbortedErrors uint64 - TxCarrierErrors uint64 - TxFifoErrors uint64 - TxHeartbeatErrors uint64 - TxWindowErrors uint64 - RxCompressed uint64 - TxCompressed uint64 -} - -type LinkXdp struct { - Fd int - Attached bool - AttachMode uint32 - Flags uint32 - ProgId uint32 -} - -// Device links cannot be created via netlink. These links -// are links created by udev like 'lo' and 'etho0' -type Device struct { - LinkAttrs -} - -func (device *Device) Attrs() *LinkAttrs { - return &device.LinkAttrs -} - -func (device *Device) Type() string { - return "device" -} - -// Dummy links are dummy ethernet devices -type Dummy struct { - LinkAttrs -} - -func (dummy *Dummy) Attrs() *LinkAttrs { - return &dummy.LinkAttrs -} - -func (dummy *Dummy) Type() string { - return "dummy" -} - -// Ifb links are advanced dummy devices for packet filtering -type Ifb struct { - LinkAttrs -} - -func (ifb *Ifb) Attrs() *LinkAttrs { - return &ifb.LinkAttrs -} - -func (ifb *Ifb) Type() string { - return "ifb" -} - -// Bridge links are simple linux bridges -type Bridge struct { - LinkAttrs - MulticastSnooping *bool - AgeingTime *uint32 - HelloTime *uint32 - VlanFiltering *bool -} - -func (bridge *Bridge) Attrs() *LinkAttrs { - return &bridge.LinkAttrs -} - -func (bridge *Bridge) Type() string { - return "bridge" -} - -// Vlan links have ParentIndex set in their Attrs() -type Vlan struct { - LinkAttrs - VlanId int - VlanProtocol VlanProtocol -} - -func (vlan *Vlan) Attrs() *LinkAttrs { - return &vlan.LinkAttrs -} - -func (vlan *Vlan) Type() string { - return "vlan" -} - -type MacvlanMode uint16 - -const ( - MACVLAN_MODE_DEFAULT MacvlanMode = iota - MACVLAN_MODE_PRIVATE - MACVLAN_MODE_VEPA - MACVLAN_MODE_BRIDGE - MACVLAN_MODE_PASSTHRU - MACVLAN_MODE_SOURCE -) - -// Macvlan links have ParentIndex set in their Attrs() -type Macvlan struct { - LinkAttrs - Mode MacvlanMode - - // MACAddrs is only populated for Macvlan SOURCE links - MACAddrs []net.HardwareAddr -} - -func (macvlan *Macvlan) Attrs() *LinkAttrs { - return &macvlan.LinkAttrs -} - -func (macvlan *Macvlan) Type() string { - return "macvlan" -} - -// Macvtap - macvtap is a virtual interfaces based on macvlan -type Macvtap struct { - Macvlan -} - -func (macvtap Macvtap) Type() string { - return "macvtap" -} - -type TuntapMode uint16 -type TuntapFlag uint16 - -// Tuntap links created via /dev/tun/tap, but can be destroyed via netlink -type Tuntap struct { - LinkAttrs - Mode TuntapMode - Flags TuntapFlag - NonPersist bool - Queues int - Fds []*os.File - Owner uint32 - Group uint32 -} - -func (tuntap *Tuntap) Attrs() *LinkAttrs { - return &tuntap.LinkAttrs -} - -func (tuntap *Tuntap) Type() string { - return "tuntap" -} - -// Veth devices must specify PeerName on create -type Veth struct { - LinkAttrs - PeerName string // veth on create only - PeerHardwareAddr net.HardwareAddr - PeerNamespace interface{} -} - -func (veth *Veth) Attrs() *LinkAttrs { - return &veth.LinkAttrs -} - -func (veth *Veth) Type() string { - return "veth" -} - -// Wireguard represent links of type "wireguard", see https://www.wireguard.com/ -type Wireguard struct { - LinkAttrs -} - -func (wg *Wireguard) Attrs() *LinkAttrs { - return &wg.LinkAttrs -} - -func (wg *Wireguard) Type() string { - return "wireguard" -} - -// GenericLink links represent types that are not currently understood -// by this netlink library. -type GenericLink struct { - LinkAttrs - LinkType string -} - -func (generic *GenericLink) Attrs() *LinkAttrs { - return &generic.LinkAttrs -} - -func (generic *GenericLink) Type() string { - return generic.LinkType -} - -type Vxlan struct { - LinkAttrs - VxlanId int - VtepDevIndex int - SrcAddr net.IP - Group net.IP - TTL int - TOS int - Learning bool - Proxy bool - RSC bool - L2miss bool - L3miss bool - UDPCSum bool - UDP6ZeroCSumTx bool - UDP6ZeroCSumRx bool - NoAge bool - GBP bool - FlowBased bool - Age int - Limit int - Port int - PortLow int - PortHigh int -} - -func (vxlan *Vxlan) Attrs() *LinkAttrs { - return &vxlan.LinkAttrs -} - -func (vxlan *Vxlan) Type() string { - return "vxlan" -} - -type IPVlanMode uint16 - -const ( - IPVLAN_MODE_L2 IPVlanMode = iota - IPVLAN_MODE_L3 - IPVLAN_MODE_L3S - IPVLAN_MODE_MAX -) - -type IPVlanFlag uint16 - -const ( - IPVLAN_FLAG_BRIDGE IPVlanFlag = iota - IPVLAN_FLAG_PRIVATE - IPVLAN_FLAG_VEPA -) - -type IPVlan struct { - LinkAttrs - Mode IPVlanMode - Flag IPVlanFlag -} - -func (ipvlan *IPVlan) Attrs() *LinkAttrs { - return &ipvlan.LinkAttrs -} - -func (ipvlan *IPVlan) Type() string { - return "ipvlan" -} - -// VlanProtocol type -type VlanProtocol int - -func (p VlanProtocol) String() string { - s, ok := VlanProtocolToString[p] - if !ok { - return fmt.Sprintf("VlanProtocol(%d)", p) - } - return s -} - -// StringToVlanProtocol returns vlan protocol, or unknown is the s is invalid. -func StringToVlanProtocol(s string) VlanProtocol { - mode, ok := StringToVlanProtocolMap[s] - if !ok { - return VLAN_PROTOCOL_UNKNOWN - } - return mode -} - -// VlanProtocol possible values -const ( - VLAN_PROTOCOL_UNKNOWN VlanProtocol = 0 - VLAN_PROTOCOL_8021Q VlanProtocol = 0x8100 - VLAN_PROTOCOL_8021AD VlanProtocol = 0x88A8 -) - -var VlanProtocolToString = map[VlanProtocol]string{ - VLAN_PROTOCOL_8021Q: "802.1q", - VLAN_PROTOCOL_8021AD: "802.1ad", -} - -var StringToVlanProtocolMap = map[string]VlanProtocol{ - "802.1q": VLAN_PROTOCOL_8021Q, - "802.1ad": VLAN_PROTOCOL_8021AD, -} - -// BondMode type -type BondMode int - -func (b BondMode) String() string { - s, ok := bondModeToString[b] - if !ok { - return fmt.Sprintf("BondMode(%d)", b) - } - return s -} - -// StringToBondMode returns bond mode, or unknown is the s is invalid. -func StringToBondMode(s string) BondMode { - mode, ok := StringToBondModeMap[s] - if !ok { - return BOND_MODE_UNKNOWN - } - return mode -} - -// Possible BondMode -const ( - BOND_MODE_BALANCE_RR BondMode = iota - BOND_MODE_ACTIVE_BACKUP - BOND_MODE_BALANCE_XOR - BOND_MODE_BROADCAST - BOND_MODE_802_3AD - BOND_MODE_BALANCE_TLB - BOND_MODE_BALANCE_ALB - BOND_MODE_UNKNOWN -) - -var bondModeToString = map[BondMode]string{ - BOND_MODE_BALANCE_RR: "balance-rr", - BOND_MODE_ACTIVE_BACKUP: "active-backup", - BOND_MODE_BALANCE_XOR: "balance-xor", - BOND_MODE_BROADCAST: "broadcast", - BOND_MODE_802_3AD: "802.3ad", - BOND_MODE_BALANCE_TLB: "balance-tlb", - BOND_MODE_BALANCE_ALB: "balance-alb", -} -var StringToBondModeMap = map[string]BondMode{ - "balance-rr": BOND_MODE_BALANCE_RR, - "active-backup": BOND_MODE_ACTIVE_BACKUP, - "balance-xor": BOND_MODE_BALANCE_XOR, - "broadcast": BOND_MODE_BROADCAST, - "802.3ad": BOND_MODE_802_3AD, - "balance-tlb": BOND_MODE_BALANCE_TLB, - "balance-alb": BOND_MODE_BALANCE_ALB, -} - -// BondArpValidate type -type BondArpValidate int - -// Possible BondArpValidate value -const ( - BOND_ARP_VALIDATE_NONE BondArpValidate = iota - BOND_ARP_VALIDATE_ACTIVE - BOND_ARP_VALIDATE_BACKUP - BOND_ARP_VALIDATE_ALL -) - -// BondPrimaryReselect type -type BondPrimaryReselect int - -// Possible BondPrimaryReselect value -const ( - BOND_PRIMARY_RESELECT_ALWAYS BondPrimaryReselect = iota - BOND_PRIMARY_RESELECT_BETTER - BOND_PRIMARY_RESELECT_FAILURE -) - -// BondArpAllTargets type -type BondArpAllTargets int - -// Possible BondArpAllTargets value -const ( - BOND_ARP_ALL_TARGETS_ANY BondArpAllTargets = iota - BOND_ARP_ALL_TARGETS_ALL -) - -// BondFailOverMac type -type BondFailOverMac int - -// Possible BondFailOverMac value -const ( - BOND_FAIL_OVER_MAC_NONE BondFailOverMac = iota - BOND_FAIL_OVER_MAC_ACTIVE - BOND_FAIL_OVER_MAC_FOLLOW -) - -// BondXmitHashPolicy type -type BondXmitHashPolicy int - -func (b BondXmitHashPolicy) String() string { - s, ok := bondXmitHashPolicyToString[b] - if !ok { - return fmt.Sprintf("XmitHashPolicy(%d)", b) - } - return s -} - -// StringToBondXmitHashPolicy returns bond lacp arte, or unknown is the s is invalid. -func StringToBondXmitHashPolicy(s string) BondXmitHashPolicy { - lacp, ok := StringToBondXmitHashPolicyMap[s] - if !ok { - return BOND_XMIT_HASH_POLICY_UNKNOWN - } - return lacp -} - -// Possible BondXmitHashPolicy value -const ( - BOND_XMIT_HASH_POLICY_LAYER2 BondXmitHashPolicy = iota - BOND_XMIT_HASH_POLICY_LAYER3_4 - BOND_XMIT_HASH_POLICY_LAYER2_3 - BOND_XMIT_HASH_POLICY_ENCAP2_3 - BOND_XMIT_HASH_POLICY_ENCAP3_4 - BOND_XMIT_HASH_POLICY_UNKNOWN -) - -var bondXmitHashPolicyToString = map[BondXmitHashPolicy]string{ - BOND_XMIT_HASH_POLICY_LAYER2: "layer2", - BOND_XMIT_HASH_POLICY_LAYER3_4: "layer3+4", - BOND_XMIT_HASH_POLICY_LAYER2_3: "layer2+3", - BOND_XMIT_HASH_POLICY_ENCAP2_3: "encap2+3", - BOND_XMIT_HASH_POLICY_ENCAP3_4: "encap3+4", -} -var StringToBondXmitHashPolicyMap = map[string]BondXmitHashPolicy{ - "layer2": BOND_XMIT_HASH_POLICY_LAYER2, - "layer3+4": BOND_XMIT_HASH_POLICY_LAYER3_4, - "layer2+3": BOND_XMIT_HASH_POLICY_LAYER2_3, - "encap2+3": BOND_XMIT_HASH_POLICY_ENCAP2_3, - "encap3+4": BOND_XMIT_HASH_POLICY_ENCAP3_4, -} - -// BondLacpRate type -type BondLacpRate int - -func (b BondLacpRate) String() string { - s, ok := bondLacpRateToString[b] - if !ok { - return fmt.Sprintf("LacpRate(%d)", b) - } - return s -} - -// StringToBondLacpRate returns bond lacp arte, or unknown is the s is invalid. -func StringToBondLacpRate(s string) BondLacpRate { - lacp, ok := StringToBondLacpRateMap[s] - if !ok { - return BOND_LACP_RATE_UNKNOWN - } - return lacp -} - -// Possible BondLacpRate value -const ( - BOND_LACP_RATE_SLOW BondLacpRate = iota - BOND_LACP_RATE_FAST - BOND_LACP_RATE_UNKNOWN -) - -var bondLacpRateToString = map[BondLacpRate]string{ - BOND_LACP_RATE_SLOW: "slow", - BOND_LACP_RATE_FAST: "fast", -} -var StringToBondLacpRateMap = map[string]BondLacpRate{ - "slow": BOND_LACP_RATE_SLOW, - "fast": BOND_LACP_RATE_FAST, -} - -// BondAdSelect type -type BondAdSelect int - -// Possible BondAdSelect value -const ( - BOND_AD_SELECT_STABLE BondAdSelect = iota - BOND_AD_SELECT_BANDWIDTH - BOND_AD_SELECT_COUNT -) - -// BondAdInfo represents ad info for bond -type BondAdInfo struct { - AggregatorId int - NumPorts int - ActorKey int - PartnerKey int - PartnerMac net.HardwareAddr -} - -// Bond representation -type Bond struct { - LinkAttrs - Mode BondMode - ActiveSlave int - Miimon int - UpDelay int - DownDelay int - UseCarrier int - ArpInterval int - ArpIpTargets []net.IP - ArpValidate BondArpValidate - ArpAllTargets BondArpAllTargets - Primary int - PrimaryReselect BondPrimaryReselect - FailOverMac BondFailOverMac - XmitHashPolicy BondXmitHashPolicy - ResendIgmp int - NumPeerNotif int - AllSlavesActive int - MinLinks int - LpInterval int - PackersPerSlave int - LacpRate BondLacpRate - AdSelect BondAdSelect - // looking at iproute tool AdInfo can only be retrived. It can't be set. - AdInfo *BondAdInfo - AdActorSysPrio int - AdUserPortKey int - AdActorSystem net.HardwareAddr - TlbDynamicLb int -} - -func NewLinkBond(atr LinkAttrs) *Bond { - return &Bond{ - LinkAttrs: atr, - Mode: -1, - ActiveSlave: -1, - Miimon: -1, - UpDelay: -1, - DownDelay: -1, - UseCarrier: -1, - ArpInterval: -1, - ArpIpTargets: nil, - ArpValidate: -1, - ArpAllTargets: -1, - Primary: -1, - PrimaryReselect: -1, - FailOverMac: -1, - XmitHashPolicy: -1, - ResendIgmp: -1, - NumPeerNotif: -1, - AllSlavesActive: -1, - MinLinks: -1, - LpInterval: -1, - PackersPerSlave: -1, - LacpRate: -1, - AdSelect: -1, - AdActorSysPrio: -1, - AdUserPortKey: -1, - AdActorSystem: nil, - TlbDynamicLb: -1, - } -} - -// Flag mask for bond options. Bond.Flagmask must be set to on for option to work. -const ( - BOND_MODE_MASK uint64 = 1 << (1 + iota) - BOND_ACTIVE_SLAVE_MASK - BOND_MIIMON_MASK - BOND_UPDELAY_MASK - BOND_DOWNDELAY_MASK - BOND_USE_CARRIER_MASK - BOND_ARP_INTERVAL_MASK - BOND_ARP_VALIDATE_MASK - BOND_ARP_ALL_TARGETS_MASK - BOND_PRIMARY_MASK - BOND_PRIMARY_RESELECT_MASK - BOND_FAIL_OVER_MAC_MASK - BOND_XMIT_HASH_POLICY_MASK - BOND_RESEND_IGMP_MASK - BOND_NUM_PEER_NOTIF_MASK - BOND_ALL_SLAVES_ACTIVE_MASK - BOND_MIN_LINKS_MASK - BOND_LP_INTERVAL_MASK - BOND_PACKETS_PER_SLAVE_MASK - BOND_LACP_RATE_MASK - BOND_AD_SELECT_MASK -) - -// Attrs implementation. -func (bond *Bond) Attrs() *LinkAttrs { - return &bond.LinkAttrs -} - -// Type implementation fro Vxlan. -func (bond *Bond) Type() string { - return "bond" -} - -// BondSlaveState represents the values of the IFLA_BOND_SLAVE_STATE bond slave -// attribute, which contains the state of the bond slave. -type BondSlaveState uint8 - -const ( - BondStateActive = iota // Link is active. - BondStateBackup // Link is backup. -) - -func (s BondSlaveState) String() string { - switch s { - case BondStateActive: - return "ACTIVE" - case BondStateBackup: - return "BACKUP" - default: - return strconv.Itoa(int(s)) - } -} - -// BondSlaveState represents the values of the IFLA_BOND_SLAVE_MII_STATUS bond slave -// attribute, which contains the status of MII link monitoring -type BondSlaveMiiStatus uint8 - -const ( - BondLinkUp = iota // link is up and running. - BondLinkFail // link has just gone down. - BondLinkDown // link has been down for too long time. - BondLinkBack // link is going back. -) - -func (s BondSlaveMiiStatus) String() string { - switch s { - case BondLinkUp: - return "UP" - case BondLinkFail: - return "GOING_DOWN" - case BondLinkDown: - return "DOWN" - case BondLinkBack: - return "GOING_BACK" - default: - return strconv.Itoa(int(s)) - } -} - -type BondSlave struct { - State BondSlaveState - MiiStatus BondSlaveMiiStatus - LinkFailureCount uint32 - PermHardwareAddr net.HardwareAddr - QueueId uint16 - AggregatorId uint16 - AdActorOperPortState uint8 - AdPartnerOperPortState uint16 -} - -func (b *BondSlave) SlaveType() string { - return "bond" -} - -// Gretap devices must specify LocalIP and RemoteIP on create -type Gretap struct { - LinkAttrs - IKey uint32 - OKey uint32 - EncapSport uint16 - EncapDport uint16 - Local net.IP - Remote net.IP - IFlags uint16 - OFlags uint16 - PMtuDisc uint8 - Ttl uint8 - Tos uint8 - EncapType uint16 - EncapFlags uint16 - Link uint32 - FlowBased bool -} - -func (gretap *Gretap) Attrs() *LinkAttrs { - return &gretap.LinkAttrs -} - -func (gretap *Gretap) Type() string { - if gretap.Local.To4() == nil { - return "ip6gretap" - } - return "gretap" -} - -type Iptun struct { - LinkAttrs - Ttl uint8 - Tos uint8 - PMtuDisc uint8 - Link uint32 - Local net.IP - Remote net.IP - EncapSport uint16 - EncapDport uint16 - EncapType uint16 - EncapFlags uint16 - FlowBased bool -} - -func (iptun *Iptun) Attrs() *LinkAttrs { - return &iptun.LinkAttrs -} - -func (iptun *Iptun) Type() string { - return "ipip" -} - -type Ip6tnl struct { - LinkAttrs - Link uint32 - Local net.IP - Remote net.IP - Ttl uint8 - Tos uint8 - Flags uint32 - Proto uint8 - FlowInfo uint32 - EncapLimit uint8 - EncapType uint16 - EncapFlags uint16 - EncapSport uint16 - EncapDport uint16 -} - -func (ip6tnl *Ip6tnl) Attrs() *LinkAttrs { - return &ip6tnl.LinkAttrs -} - -func (ip6tnl *Ip6tnl) Type() string { - return "ip6tnl" -} - -type Sittun struct { - LinkAttrs - Link uint32 - Ttl uint8 - Tos uint8 - PMtuDisc uint8 - Proto uint8 - Local net.IP - Remote net.IP - EncapLimit uint8 - EncapType uint16 - EncapFlags uint16 - EncapSport uint16 - EncapDport uint16 -} - -func (sittun *Sittun) Attrs() *LinkAttrs { - return &sittun.LinkAttrs -} - -func (sittun *Sittun) Type() string { - return "sit" -} - -type Vti struct { - LinkAttrs - IKey uint32 - OKey uint32 - Link uint32 - Local net.IP - Remote net.IP -} - -func (vti *Vti) Attrs() *LinkAttrs { - return &vti.LinkAttrs -} - -func (vti *Vti) Type() string { - if vti.Local.To4() == nil { - return "vti6" - } - return "vti" -} - -type Gretun struct { - LinkAttrs - Link uint32 - IFlags uint16 - OFlags uint16 - IKey uint32 - OKey uint32 - Local net.IP - Remote net.IP - Ttl uint8 - Tos uint8 - PMtuDisc uint8 - EncapType uint16 - EncapFlags uint16 - EncapSport uint16 - EncapDport uint16 -} - -func (gretun *Gretun) Attrs() *LinkAttrs { - return &gretun.LinkAttrs -} - -func (gretun *Gretun) Type() string { - if gretun.Local.To4() == nil { - return "ip6gre" - } - return "gre" -} - -type Vrf struct { - LinkAttrs - Table uint32 -} - -func (vrf *Vrf) Attrs() *LinkAttrs { - return &vrf.LinkAttrs -} - -func (vrf *Vrf) Type() string { - return "vrf" -} - -type GTP struct { - LinkAttrs - FD0 int - FD1 int - Role int - PDPHashsize int -} - -func (gtp *GTP) Attrs() *LinkAttrs { - return >p.LinkAttrs -} - -func (gtp *GTP) Type() string { - return "gtp" -} - -// Virtual XFRM Interfaces -// Named "xfrmi" to prevent confusion with XFRM objects -type Xfrmi struct { - LinkAttrs - Ifid uint32 -} - -func (xfrm *Xfrmi) Attrs() *LinkAttrs { - return &xfrm.LinkAttrs -} - -func (xfrm *Xfrmi) Type() string { - return "xfrm" -} - -// IPoIB interface - -type IPoIBMode uint16 - -func (m *IPoIBMode) String() string { - str, ok := iPoIBModeToString[*m] - if !ok { - return fmt.Sprintf("mode(%d)", *m) - } - return str -} - -const ( - IPOIB_MODE_DATAGRAM = iota - IPOIB_MODE_CONNECTED -) - -var iPoIBModeToString = map[IPoIBMode]string{ - IPOIB_MODE_DATAGRAM: "datagram", - IPOIB_MODE_CONNECTED: "connected", -} - -var StringToIPoIBMode = map[string]IPoIBMode{ - "datagram": IPOIB_MODE_DATAGRAM, - "connected": IPOIB_MODE_CONNECTED, -} - -type IPoIB struct { - LinkAttrs - Pkey uint16 - Mode IPoIBMode - Umcast uint16 -} - -func (ipoib *IPoIB) Attrs() *LinkAttrs { - return &ipoib.LinkAttrs -} - -func (ipoib *IPoIB) Type() string { - return "ipoib" -} - -// iproute2 supported devices; -// vlan | veth | vcan | dummy | ifb | macvlan | macvtap | -// bridge | bond | ipoib | ip6tnl | ipip | sit | vxlan | -// gre | gretap | ip6gre | ip6gretap | vti | vti6 | nlmon | -// bond_slave | ipvlan | xfrm - -// LinkNotFoundError wraps the various not found errors when -// getting/reading links. This is intended for better error -// handling by dependent code so that "not found error" can -// be distinguished from other errors -type LinkNotFoundError struct { - error -} diff --git a/examples/vendor/github.com/vishvananda/netlink/link_linux.go b/examples/vendor/github.com/vishvananda/netlink/link_linux.go deleted file mode 100644 index c02fa63..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/link_linux.go +++ /dev/null @@ -1,3180 +0,0 @@ -package netlink - -import ( - "bytes" - "encoding/binary" - "fmt" - "io/ioutil" - "net" - "os" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -const ( - SizeofLinkStats32 = 0x5c - SizeofLinkStats64 = 0xb8 -) - -const ( - TUNTAP_MODE_TUN TuntapMode = unix.IFF_TUN - TUNTAP_MODE_TAP TuntapMode = unix.IFF_TAP - TUNTAP_DEFAULTS TuntapFlag = unix.IFF_TUN_EXCL | unix.IFF_ONE_QUEUE - TUNTAP_VNET_HDR TuntapFlag = unix.IFF_VNET_HDR - TUNTAP_TUN_EXCL TuntapFlag = unix.IFF_TUN_EXCL - TUNTAP_NO_PI TuntapFlag = unix.IFF_NO_PI - TUNTAP_ONE_QUEUE TuntapFlag = unix.IFF_ONE_QUEUE - TUNTAP_MULTI_QUEUE TuntapFlag = unix.IFF_MULTI_QUEUE - TUNTAP_MULTI_QUEUE_DEFAULTS TuntapFlag = TUNTAP_MULTI_QUEUE | TUNTAP_NO_PI -) - -const ( - VF_LINK_STATE_AUTO uint32 = 0 - VF_LINK_STATE_ENABLE uint32 = 1 - VF_LINK_STATE_DISABLE uint32 = 2 -) - -var lookupByDump = false - -var macvlanModes = [...]uint32{ - 0, - nl.MACVLAN_MODE_PRIVATE, - nl.MACVLAN_MODE_VEPA, - nl.MACVLAN_MODE_BRIDGE, - nl.MACVLAN_MODE_PASSTHRU, - nl.MACVLAN_MODE_SOURCE, -} - -func ensureIndex(link *LinkAttrs) { - if link != nil && link.Index == 0 { - newlink, _ := LinkByName(link.Name) - if newlink != nil { - link.Index = newlink.Attrs().Index - } - } -} - -func (h *Handle) ensureIndex(link *LinkAttrs) { - if link != nil && link.Index == 0 { - newlink, _ := h.LinkByName(link.Name) - if newlink != nil { - link.Index = newlink.Attrs().Index - } - } -} - -func (h *Handle) LinkSetARPOff(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change |= unix.IFF_NOARP - msg.Flags |= unix.IFF_NOARP - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func LinkSetARPOff(link Link) error { - return pkgHandle.LinkSetARPOff(link) -} - -func (h *Handle) LinkSetARPOn(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change |= unix.IFF_NOARP - msg.Flags &= ^uint32(unix.IFF_NOARP) - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func LinkSetARPOn(link Link) error { - return pkgHandle.LinkSetARPOn(link) -} - -func (h *Handle) SetPromiscOn(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_PROMISC - msg.Flags = unix.IFF_PROMISC - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetAllmulticastOn enables the reception of all hardware multicast packets for the link device. -// Equivalent to: `ip link set $link allmulticast on` -func LinkSetAllmulticastOn(link Link) error { - return pkgHandle.LinkSetAllmulticastOn(link) -} - -// LinkSetAllmulticastOn enables the reception of all hardware multicast packets for the link device. -// Equivalent to: `ip link set $link allmulticast on` -func (h *Handle) LinkSetAllmulticastOn(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_ALLMULTI - msg.Flags = unix.IFF_ALLMULTI - - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetAllmulticastOff disables the reception of all hardware multicast packets for the link device. -// Equivalent to: `ip link set $link allmulticast off` -func LinkSetAllmulticastOff(link Link) error { - return pkgHandle.LinkSetAllmulticastOff(link) -} - -// LinkSetAllmulticastOff disables the reception of all hardware multicast packets for the link device. -// Equivalent to: `ip link set $link allmulticast off` -func (h *Handle) LinkSetAllmulticastOff(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_ALLMULTI - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error { - return pkgHandle.MacvlanMACAddrAdd(link, addr) -} - -func (h *Handle) MacvlanMACAddrAdd(link Link, addr net.HardwareAddr) error { - return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_ADD) -} - -func MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error { - return pkgHandle.MacvlanMACAddrDel(link, addr) -} - -func (h *Handle) MacvlanMACAddrDel(link Link, addr net.HardwareAddr) error { - return h.macvlanMACAddrChange(link, []net.HardwareAddr{addr}, nl.MACVLAN_MACADDR_DEL) -} - -func MacvlanMACAddrFlush(link Link) error { - return pkgHandle.MacvlanMACAddrFlush(link) -} - -func (h *Handle) MacvlanMACAddrFlush(link Link) error { - return h.macvlanMACAddrChange(link, nil, nl.MACVLAN_MACADDR_FLUSH) -} - -func MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error { - return pkgHandle.MacvlanMACAddrSet(link, addrs) -} - -func (h *Handle) MacvlanMACAddrSet(link Link, addrs []net.HardwareAddr) error { - return h.macvlanMACAddrChange(link, addrs, nl.MACVLAN_MACADDR_SET) -} - -func (h *Handle) macvlanMACAddrChange(link Link, addrs []net.HardwareAddr, mode uint32) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) - linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) - inner := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - // IFLA_MACVLAN_MACADDR_MODE = mode - b := make([]byte, 4) - native.PutUint32(b, mode) - inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_MODE, b) - - // populate message with MAC addrs, if necessary - switch mode { - case nl.MACVLAN_MACADDR_ADD, nl.MACVLAN_MACADDR_DEL: - if len(addrs) == 1 { - inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addrs[0])) - } - case nl.MACVLAN_MACADDR_SET: - mad := inner.AddRtAttr(nl.IFLA_MACVLAN_MACADDR_DATA, nil) - for _, addr := range addrs { - mad.AddRtAttr(nl.IFLA_MACVLAN_MACADDR, []byte(addr)) - } - } - - req.AddData(linkInfo) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetMacvlanMode sets the mode of a macvlan or macvtap link device. -// Note that passthrough mode cannot be set to and from and will fail. -// Equivalent to: `ip link set $link type (macvlan|macvtap) mode $mode -func LinkSetMacvlanMode(link Link, mode MacvlanMode) error { - return pkgHandle.LinkSetMacvlanMode(link, mode) -} - -// LinkSetMacvlanMode sets the mode of the macvlan or macvtap link device. -// Note that passthrough mode cannot be set to and from and will fail. -// Equivalent to: `ip link set $link type (macvlan|macvtap) mode $mode -func (h *Handle) LinkSetMacvlanMode(link Link, mode MacvlanMode) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) - linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) - - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[mode])) - - req.AddData(linkInfo) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func BridgeSetMcastSnoop(link Link, on bool) error { - return pkgHandle.BridgeSetMcastSnoop(link, on) -} - -func (h *Handle) BridgeSetMcastSnoop(link Link, on bool) error { - bridge := link.(*Bridge) - bridge.MulticastSnooping = &on - return h.linkModify(bridge, unix.NLM_F_ACK) -} - -func BridgeSetVlanFiltering(link Link, on bool) error { - return pkgHandle.BridgeSetVlanFiltering(link, on) -} - -func (h *Handle) BridgeSetVlanFiltering(link Link, on bool) error { - bridge := link.(*Bridge) - bridge.VlanFiltering = &on - return h.linkModify(bridge, unix.NLM_F_ACK) -} - -func SetPromiscOn(link Link) error { - return pkgHandle.SetPromiscOn(link) -} - -func (h *Handle) SetPromiscOff(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_PROMISC - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func SetPromiscOff(link Link) error { - return pkgHandle.SetPromiscOff(link) -} - -// LinkSetUp enables the link device. -// Equivalent to: `ip link set $link up` -func LinkSetUp(link Link) error { - return pkgHandle.LinkSetUp(link) -} - -// LinkSetUp enables the link device. -// Equivalent to: `ip link set $link up` -func (h *Handle) LinkSetUp(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_UP - msg.Flags = unix.IFF_UP - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetDown disables link device. -// Equivalent to: `ip link set $link down` -func LinkSetDown(link Link) error { - return pkgHandle.LinkSetDown(link) -} - -// LinkSetDown disables link device. -// Equivalent to: `ip link set $link down` -func (h *Handle) LinkSetDown(link Link) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_NEWLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Change = unix.IFF_UP - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetMTU sets the mtu of the link device. -// Equivalent to: `ip link set $link mtu $mtu` -func LinkSetMTU(link Link, mtu int) error { - return pkgHandle.LinkSetMTU(link, mtu) -} - -// LinkSetMTU sets the mtu of the link device. -// Equivalent to: `ip link set $link mtu $mtu` -func (h *Handle) LinkSetMTU(link Link, mtu int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(mtu)) - - data := nl.NewRtAttr(unix.IFLA_MTU, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetName sets the name of the link device. -// Equivalent to: `ip link set $link name $name` -func LinkSetName(link Link, name string) error { - return pkgHandle.LinkSetName(link, name) -} - -// LinkSetName sets the name of the link device. -// Equivalent to: `ip link set $link name $name` -func (h *Handle) LinkSetName(link Link, name string) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_IFNAME, []byte(name)) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetAlias sets the alias of the link device. -// Equivalent to: `ip link set dev $link alias $name` -func LinkSetAlias(link Link, name string) error { - return pkgHandle.LinkSetAlias(link, name) -} - -// LinkSetAlias sets the alias of the link device. -// Equivalent to: `ip link set dev $link alias $name` -func (h *Handle) LinkSetAlias(link Link, name string) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_IFALIAS, []byte(name)) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetHardwareAddr sets the hardware address of the link device. -// Equivalent to: `ip link set $link address $hwaddr` -func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { - return pkgHandle.LinkSetHardwareAddr(link, hwaddr) -} - -// LinkSetHardwareAddr sets the hardware address of the link device. -// Equivalent to: `ip link set $link address $hwaddr` -func (h *Handle) LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(hwaddr)) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfHardwareAddr sets the hardware address of a vf for the link. -// Equivalent to: `ip link set $link vf $vf mac $hwaddr` -func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { - return pkgHandle.LinkSetVfHardwareAddr(link, vf, hwaddr) -} - -// LinkSetVfHardwareAddr sets the hardware address of a vf for the link. -// Equivalent to: `ip link set $link vf $vf mac $hwaddr` -func (h *Handle) LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfMac{ - Vf: uint32(vf), - } - copy(vfmsg.Mac[:], []byte(hwaddr)) - info.AddRtAttr(nl.IFLA_VF_MAC, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfVlan sets the vlan of a vf for the link. -// Equivalent to: `ip link set $link vf $vf vlan $vlan` -func LinkSetVfVlan(link Link, vf, vlan int) error { - return pkgHandle.LinkSetVfVlan(link, vf, vlan) -} - -// LinkSetVfVlan sets the vlan of a vf for the link. -// Equivalent to: `ip link set $link vf $vf vlan $vlan` -func (h *Handle) LinkSetVfVlan(link Link, vf, vlan int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfVlan{ - Vf: uint32(vf), - Vlan: uint32(vlan), - } - info.AddRtAttr(nl.IFLA_VF_VLAN, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link. -// Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos` -func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error { - return pkgHandle.LinkSetVfVlanQos(link, vf, vlan, qos) -} - -// LinkSetVfVlanQos sets the vlan and qos priority of a vf for the link. -// Equivalent to: `ip link set $link vf $vf vlan $vlan qos $qos` -func (h *Handle) LinkSetVfVlanQos(link Link, vf, vlan, qos int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := nl.NewRtAttrChild(data, nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfVlan{ - Vf: uint32(vf), - Vlan: uint32(vlan), - Qos: uint32(qos), - } - nl.NewRtAttrChild(info, nl.IFLA_VF_VLAN, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfTxRate sets the tx rate of a vf for the link. -// Equivalent to: `ip link set $link vf $vf rate $rate` -func LinkSetVfTxRate(link Link, vf, rate int) error { - return pkgHandle.LinkSetVfTxRate(link, vf, rate) -} - -// LinkSetVfTxRate sets the tx rate of a vf for the link. -// Equivalent to: `ip link set $link vf $vf rate $rate` -func (h *Handle) LinkSetVfTxRate(link Link, vf, rate int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfTxRate{ - Vf: uint32(vf), - Rate: uint32(rate), - } - info.AddRtAttr(nl.IFLA_VF_TX_RATE, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfRate sets the min and max tx rate of a vf for the link. -// Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate` -func LinkSetVfRate(link Link, vf, minRate, maxRate int) error { - return pkgHandle.LinkSetVfRate(link, vf, minRate, maxRate) -} - -// LinkSetVfRate sets the min and max tx rate of a vf for the link. -// Equivalent to: `ip link set $link vf $vf min_tx_rate $min_rate max_tx_rate $max_rate` -func (h *Handle) LinkSetVfRate(link Link, vf, minRate, maxRate int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfRate{ - Vf: uint32(vf), - MinTxRate: uint32(minRate), - MaxTxRate: uint32(maxRate), - } - info.AddRtAttr(nl.IFLA_VF_RATE, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfState enables/disables virtual link state on a vf. -// Equivalent to: `ip link set $link vf $vf state $state` -func LinkSetVfState(link Link, vf int, state uint32) error { - return pkgHandle.LinkSetVfState(link, vf, state) -} - -// LinkSetVfState enables/disables virtual link state on a vf. -// Equivalent to: `ip link set $link vf $vf state $state` -func (h *Handle) LinkSetVfState(link Link, vf int, state uint32) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfLinkState{ - Vf: uint32(vf), - LinkState: state, - } - info.AddRtAttr(nl.IFLA_VF_LINK_STATE, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfSpoofchk enables/disables spoof check on a vf for the link. -// Equivalent to: `ip link set $link vf $vf spoofchk $check` -func LinkSetVfSpoofchk(link Link, vf int, check bool) error { - return pkgHandle.LinkSetVfSpoofchk(link, vf, check) -} - -// LinkSetVfSpoofchk enables/disables spoof check on a vf for the link. -// Equivalent to: `ip link set $link vf $vf spoofchk $check` -func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error { - var setting uint32 - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - if check { - setting = 1 - } - vfmsg := nl.VfSpoofchk{ - Vf: uint32(vf), - Setting: setting, - } - info.AddRtAttr(nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfTrust enables/disables trust state on a vf for the link. -// Equivalent to: `ip link set $link vf $vf trust $state` -func LinkSetVfTrust(link Link, vf int, state bool) error { - return pkgHandle.LinkSetVfTrust(link, vf, state) -} - -// LinkSetVfTrust enables/disables trust state on a vf for the link. -// Equivalent to: `ip link set $link vf $vf trust $state` -func (h *Handle) LinkSetVfTrust(link Link, vf int, state bool) error { - var setting uint32 - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - if state { - setting = 1 - } - vfmsg := nl.VfTrust{ - Vf: uint32(vf), - Setting: setting, - } - info.AddRtAttr(nl.IFLA_VF_TRUST, vfmsg.Serialize()) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetVfNodeGUID sets the node GUID of a vf for the link. -// Equivalent to: `ip link set dev $link vf $vf node_guid $nodeguid` -func LinkSetVfNodeGUID(link Link, vf int, nodeguid net.HardwareAddr) error { - return pkgHandle.LinkSetVfGUID(link, vf, nodeguid, nl.IFLA_VF_IB_NODE_GUID) -} - -// LinkSetVfPortGUID sets the port GUID of a vf for the link. -// Equivalent to: `ip link set dev $link vf $vf port_guid $portguid` -func LinkSetVfPortGUID(link Link, vf int, portguid net.HardwareAddr) error { - return pkgHandle.LinkSetVfGUID(link, vf, portguid, nl.IFLA_VF_IB_PORT_GUID) -} - -// LinkSetVfGUID sets the node or port GUID of a vf for the link. -func (h *Handle) LinkSetVfGUID(link Link, vf int, vfGuid net.HardwareAddr, guidType int) error { - var err error - var guid uint64 - - buf := bytes.NewBuffer(vfGuid) - err = binary.Read(buf, binary.BigEndian, &guid) - if err != nil { - return err - } - - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil) - info := data.AddRtAttr(nl.IFLA_VF_INFO, nil) - vfmsg := nl.VfGUID{ - Vf: uint32(vf), - GUID: guid, - } - info.AddRtAttr(guidType, vfmsg.Serialize()) - req.AddData(data) - - _, err = req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetMaster sets the master of the link device. -// Equivalent to: `ip link set $link master $master` -func LinkSetMaster(link Link, master Link) error { - return pkgHandle.LinkSetMaster(link, master) -} - -// LinkSetMaster sets the master of the link device. -// Equivalent to: `ip link set $link master $master` -func (h *Handle) LinkSetMaster(link Link, master Link) error { - index := 0 - if master != nil { - masterBase := master.Attrs() - h.ensureIndex(masterBase) - index = masterBase.Index - } - if index <= 0 { - return fmt.Errorf("Device does not exist") - } - return h.LinkSetMasterByIndex(link, index) -} - -// LinkSetNoMaster removes the master of the link device. -// Equivalent to: `ip link set $link nomaster` -func LinkSetNoMaster(link Link) error { - return pkgHandle.LinkSetNoMaster(link) -} - -// LinkSetNoMaster removes the master of the link device. -// Equivalent to: `ip link set $link nomaster` -func (h *Handle) LinkSetNoMaster(link Link) error { - return h.LinkSetMasterByIndex(link, 0) -} - -// LinkSetMasterByIndex sets the master of the link device. -// Equivalent to: `ip link set $link master $master` -func LinkSetMasterByIndex(link Link, masterIndex int) error { - return pkgHandle.LinkSetMasterByIndex(link, masterIndex) -} - -// LinkSetMasterByIndex sets the master of the link device. -// Equivalent to: `ip link set $link master $master` -func (h *Handle) LinkSetMasterByIndex(link Link, masterIndex int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(masterIndex)) - - data := nl.NewRtAttr(unix.IFLA_MASTER, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetNsPid puts the device into a new network namespace. The -// pid must be a pid of a running process. -// Equivalent to: `ip link set $link netns $pid` -func LinkSetNsPid(link Link, nspid int) error { - return pkgHandle.LinkSetNsPid(link, nspid) -} - -// LinkSetNsPid puts the device into a new network namespace. The -// pid must be a pid of a running process. -// Equivalent to: `ip link set $link netns $pid` -func (h *Handle) LinkSetNsPid(link Link, nspid int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(nspid)) - - data := nl.NewRtAttr(unix.IFLA_NET_NS_PID, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetNsFd puts the device into a new network namespace. The -// fd must be an open file descriptor to a network namespace. -// Similar to: `ip link set $link netns $ns` -func LinkSetNsFd(link Link, fd int) error { - return pkgHandle.LinkSetNsFd(link, fd) -} - -// LinkSetNsFd puts the device into a new network namespace. The -// fd must be an open file descriptor to a network namespace. -// Similar to: `ip link set $link netns $ns` -func (h *Handle) LinkSetNsFd(link Link, fd int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(fd)) - - data := nl.NewRtAttr(unix.IFLA_NET_NS_FD, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetXdpFd adds a bpf function to the driver. The fd must be a bpf -// program loaded with bpf(type=BPF_PROG_TYPE_XDP) -func LinkSetXdpFd(link Link, fd int) error { - return LinkSetXdpFdWithFlags(link, fd, 0) -} - -// LinkSetXdpFdWithFlags adds a bpf function to the driver with the given -// options. The fd must be a bpf program loaded with bpf(type=BPF_PROG_TYPE_XDP) -func LinkSetXdpFdWithFlags(link Link, fd, flags int) error { - base := link.Attrs() - ensureIndex(base) - req := nl.NewNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - addXdpAttrs(&LinkXdp{Fd: fd, Flags: uint32(flags)}, req) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func boolAttr(val bool) []byte { - var v uint8 - if val { - v = 1 - } - return nl.Uint8Attr(v) -} - -type vxlanPortRange struct { - Lo, Hi uint16 -} - -func addVxlanAttrs(vxlan *Vxlan, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - if vxlan.FlowBased { - vxlan.VxlanId = 0 - } - - data.AddRtAttr(nl.IFLA_VXLAN_ID, nl.Uint32Attr(uint32(vxlan.VxlanId))) - - if vxlan.VtepDevIndex != 0 { - data.AddRtAttr(nl.IFLA_VXLAN_LINK, nl.Uint32Attr(uint32(vxlan.VtepDevIndex))) - } - if vxlan.SrcAddr != nil { - ip := vxlan.SrcAddr.To4() - if ip != nil { - data.AddRtAttr(nl.IFLA_VXLAN_LOCAL, []byte(ip)) - } else { - ip = vxlan.SrcAddr.To16() - if ip != nil { - data.AddRtAttr(nl.IFLA_VXLAN_LOCAL6, []byte(ip)) - } - } - } - if vxlan.Group != nil { - group := vxlan.Group.To4() - if group != nil { - data.AddRtAttr(nl.IFLA_VXLAN_GROUP, []byte(group)) - } else { - group = vxlan.Group.To16() - if group != nil { - data.AddRtAttr(nl.IFLA_VXLAN_GROUP6, []byte(group)) - } - } - } - - data.AddRtAttr(nl.IFLA_VXLAN_TTL, nl.Uint8Attr(uint8(vxlan.TTL))) - data.AddRtAttr(nl.IFLA_VXLAN_TOS, nl.Uint8Attr(uint8(vxlan.TOS))) - data.AddRtAttr(nl.IFLA_VXLAN_LEARNING, boolAttr(vxlan.Learning)) - data.AddRtAttr(nl.IFLA_VXLAN_PROXY, boolAttr(vxlan.Proxy)) - data.AddRtAttr(nl.IFLA_VXLAN_RSC, boolAttr(vxlan.RSC)) - data.AddRtAttr(nl.IFLA_VXLAN_L2MISS, boolAttr(vxlan.L2miss)) - data.AddRtAttr(nl.IFLA_VXLAN_L3MISS, boolAttr(vxlan.L3miss)) - data.AddRtAttr(nl.IFLA_VXLAN_UDP_ZERO_CSUM6_TX, boolAttr(vxlan.UDP6ZeroCSumTx)) - data.AddRtAttr(nl.IFLA_VXLAN_UDP_ZERO_CSUM6_RX, boolAttr(vxlan.UDP6ZeroCSumRx)) - - if vxlan.UDPCSum { - data.AddRtAttr(nl.IFLA_VXLAN_UDP_CSUM, boolAttr(vxlan.UDPCSum)) - } - if vxlan.GBP { - data.AddRtAttr(nl.IFLA_VXLAN_GBP, []byte{}) - } - if vxlan.FlowBased { - data.AddRtAttr(nl.IFLA_VXLAN_FLOWBASED, boolAttr(vxlan.FlowBased)) - } - if vxlan.NoAge { - data.AddRtAttr(nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(0)) - } else if vxlan.Age > 0 { - data.AddRtAttr(nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(uint32(vxlan.Age))) - } - if vxlan.Limit > 0 { - data.AddRtAttr(nl.IFLA_VXLAN_LIMIT, nl.Uint32Attr(uint32(vxlan.Limit))) - } - if vxlan.Port > 0 { - data.AddRtAttr(nl.IFLA_VXLAN_PORT, htons(uint16(vxlan.Port))) - } - if vxlan.PortLow > 0 || vxlan.PortHigh > 0 { - pr := vxlanPortRange{uint16(vxlan.PortLow), uint16(vxlan.PortHigh)} - - buf := new(bytes.Buffer) - binary.Write(buf, binary.BigEndian, &pr) - - data.AddRtAttr(nl.IFLA_VXLAN_PORT_RANGE, buf.Bytes()) - } -} - -func addBondAttrs(bond *Bond, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - if bond.Mode >= 0 { - data.AddRtAttr(nl.IFLA_BOND_MODE, nl.Uint8Attr(uint8(bond.Mode))) - } - if bond.ActiveSlave >= 0 { - data.AddRtAttr(nl.IFLA_BOND_ACTIVE_SLAVE, nl.Uint32Attr(uint32(bond.ActiveSlave))) - } - if bond.Miimon >= 0 { - data.AddRtAttr(nl.IFLA_BOND_MIIMON, nl.Uint32Attr(uint32(bond.Miimon))) - } - if bond.UpDelay >= 0 { - data.AddRtAttr(nl.IFLA_BOND_UPDELAY, nl.Uint32Attr(uint32(bond.UpDelay))) - } - if bond.DownDelay >= 0 { - data.AddRtAttr(nl.IFLA_BOND_DOWNDELAY, nl.Uint32Attr(uint32(bond.DownDelay))) - } - if bond.UseCarrier >= 0 { - data.AddRtAttr(nl.IFLA_BOND_USE_CARRIER, nl.Uint8Attr(uint8(bond.UseCarrier))) - } - if bond.ArpInterval >= 0 { - data.AddRtAttr(nl.IFLA_BOND_ARP_INTERVAL, nl.Uint32Attr(uint32(bond.ArpInterval))) - } - if bond.ArpIpTargets != nil { - msg := data.AddRtAttr(nl.IFLA_BOND_ARP_IP_TARGET, nil) - for i := range bond.ArpIpTargets { - ip := bond.ArpIpTargets[i].To4() - if ip != nil { - msg.AddRtAttr(i, []byte(ip)) - continue - } - ip = bond.ArpIpTargets[i].To16() - if ip != nil { - msg.AddRtAttr(i, []byte(ip)) - } - } - } - if bond.ArpValidate >= 0 { - data.AddRtAttr(nl.IFLA_BOND_ARP_VALIDATE, nl.Uint32Attr(uint32(bond.ArpValidate))) - } - if bond.ArpAllTargets >= 0 { - data.AddRtAttr(nl.IFLA_BOND_ARP_ALL_TARGETS, nl.Uint32Attr(uint32(bond.ArpAllTargets))) - } - if bond.Primary >= 0 { - data.AddRtAttr(nl.IFLA_BOND_PRIMARY, nl.Uint32Attr(uint32(bond.Primary))) - } - if bond.PrimaryReselect >= 0 { - data.AddRtAttr(nl.IFLA_BOND_PRIMARY_RESELECT, nl.Uint8Attr(uint8(bond.PrimaryReselect))) - } - if bond.FailOverMac >= 0 { - data.AddRtAttr(nl.IFLA_BOND_FAIL_OVER_MAC, nl.Uint8Attr(uint8(bond.FailOverMac))) - } - if bond.XmitHashPolicy >= 0 { - data.AddRtAttr(nl.IFLA_BOND_XMIT_HASH_POLICY, nl.Uint8Attr(uint8(bond.XmitHashPolicy))) - } - if bond.ResendIgmp >= 0 { - data.AddRtAttr(nl.IFLA_BOND_RESEND_IGMP, nl.Uint32Attr(uint32(bond.ResendIgmp))) - } - if bond.NumPeerNotif >= 0 { - data.AddRtAttr(nl.IFLA_BOND_NUM_PEER_NOTIF, nl.Uint8Attr(uint8(bond.NumPeerNotif))) - } - if bond.AllSlavesActive >= 0 { - data.AddRtAttr(nl.IFLA_BOND_ALL_SLAVES_ACTIVE, nl.Uint8Attr(uint8(bond.AllSlavesActive))) - } - if bond.MinLinks >= 0 { - data.AddRtAttr(nl.IFLA_BOND_MIN_LINKS, nl.Uint32Attr(uint32(bond.MinLinks))) - } - if bond.LpInterval >= 0 { - data.AddRtAttr(nl.IFLA_BOND_LP_INTERVAL, nl.Uint32Attr(uint32(bond.LpInterval))) - } - if bond.PackersPerSlave >= 0 { - data.AddRtAttr(nl.IFLA_BOND_PACKETS_PER_SLAVE, nl.Uint32Attr(uint32(bond.PackersPerSlave))) - } - if bond.LacpRate >= 0 { - data.AddRtAttr(nl.IFLA_BOND_AD_LACP_RATE, nl.Uint8Attr(uint8(bond.LacpRate))) - } - if bond.AdSelect >= 0 { - data.AddRtAttr(nl.IFLA_BOND_AD_SELECT, nl.Uint8Attr(uint8(bond.AdSelect))) - } - if bond.AdActorSysPrio >= 0 { - data.AddRtAttr(nl.IFLA_BOND_AD_ACTOR_SYS_PRIO, nl.Uint16Attr(uint16(bond.AdActorSysPrio))) - } - if bond.AdUserPortKey >= 0 { - data.AddRtAttr(nl.IFLA_BOND_AD_USER_PORT_KEY, nl.Uint16Attr(uint16(bond.AdUserPortKey))) - } - if bond.AdActorSystem != nil { - data.AddRtAttr(nl.IFLA_BOND_AD_ACTOR_SYSTEM, []byte(bond.AdActorSystem)) - } - if bond.TlbDynamicLb >= 0 { - data.AddRtAttr(nl.IFLA_BOND_TLB_DYNAMIC_LB, nl.Uint8Attr(uint8(bond.TlbDynamicLb))) - } -} - -func cleanupFds(fds []*os.File) { - for _, f := range fds { - f.Close() - } -} - -// LinkAdd adds a new link device. The type and features of the device -// are taken from the parameters in the link object. -// Equivalent to: `ip link add $link` -func LinkAdd(link Link) error { - return pkgHandle.LinkAdd(link) -} - -// LinkAdd adds a new link device. The type and features of the device -// are taken from the parameters in the link object. -// Equivalent to: `ip link add $link` -func (h *Handle) LinkAdd(link Link) error { - return h.linkModify(link, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) -} - -func (h *Handle) LinkModify(link Link) error { - return h.linkModify(link, unix.NLM_F_REQUEST|unix.NLM_F_ACK) -} - -func (h *Handle) linkModify(link Link, flags int) error { - // TODO: support extra data for macvlan - base := link.Attrs() - - // if tuntap, then the name can be empty, OS will provide a name - tuntap, isTuntap := link.(*Tuntap) - - if base.Name == "" && !isTuntap { - return fmt.Errorf("LinkAttrs.Name cannot be empty") - } - - if isTuntap { - if tuntap.Mode < unix.IFF_TUN || tuntap.Mode > unix.IFF_TAP { - return fmt.Errorf("Tuntap.Mode %v unknown", tuntap.Mode) - } - - queues := tuntap.Queues - - var fds []*os.File - var req ifReq - copy(req.Name[:15], base.Name) - - req.Flags = uint16(tuntap.Flags) - - if queues == 0 { //Legacy compatibility - queues = 1 - if tuntap.Flags == 0 { - req.Flags = uint16(TUNTAP_DEFAULTS) - } - } else { - // For best peformance set Flags to TUNTAP_MULTI_QUEUE_DEFAULTS | TUNTAP_VNET_HDR - // when a) KVM has support for this ABI and - // b) the value of the flag is queryable using the TUNGETIFF ioctl - if tuntap.Flags == 0 { - req.Flags = uint16(TUNTAP_MULTI_QUEUE_DEFAULTS) - } - } - - req.Flags |= uint16(tuntap.Mode) - const TUN = "/dev/net/tun" - for i := 0; i < queues; i++ { - localReq := req - fd, err := unix.Open(TUN, os.O_RDWR|syscall.O_CLOEXEC, 0) - if err != nil { - cleanupFds(fds) - return err - } - - _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&localReq))) - if errno != 0 { - // close the new fd - unix.Close(fd) - // and the already opened ones - cleanupFds(fds) - return fmt.Errorf("Tuntap IOCTL TUNSETIFF failed [%d], errno %v", i, errno) - } - - _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TUNSETOWNER, uintptr(tuntap.Owner)) - if errno != 0 { - cleanupFds(fds) - return fmt.Errorf("Tuntap IOCTL TUNSETOWNER failed [%d], errno %v", i, errno) - } - - _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.TUNSETGROUP, uintptr(tuntap.Group)) - if errno != 0 { - cleanupFds(fds) - return fmt.Errorf("Tuntap IOCTL TUNSETGROUP failed [%d], errno %v", i, errno) - } - - // Set the tun device to non-blocking before use. The below comment - // taken from: - // - // https://github.com/mistsys/tuntap/commit/161418c25003bbee77d085a34af64d189df62bea - // - // Note there is a complication because in go, if a device node is - // opened, go sets it to use nonblocking I/O. However a /dev/net/tun - // doesn't work with epoll until after the TUNSETIFF ioctl has been - // done. So we open the unix fd directly, do the ioctl, then put the - // fd in nonblocking mode, an then finally wrap it in a os.File, - // which will see the nonblocking mode and add the fd to the - // pollable set, so later on when we Read() from it blocked the - // calling thread in the kernel. - // - // See - // https://github.com/golang/go/issues/30426 - // which got exposed in go 1.13 by the fix to - // https://github.com/golang/go/issues/30624 - err = unix.SetNonblock(fd, true) - if err != nil { - cleanupFds(fds) - return fmt.Errorf("Tuntap set to non-blocking failed [%d], err %v", i, err) - } - - // create the file from the file descriptor and store it - file := os.NewFile(uintptr(fd), TUN) - fds = append(fds, file) - - // 1) we only care for the name of the first tap in the multi queue set - // 2) if the original name was empty, the localReq has now the actual name - // - // In addition: - // This ensures that the link name is always identical to what the kernel returns. - // Not only in case of an empty name, but also when using name templates. - // e.g. when the provided name is "tap%d", the kernel replaces %d with the next available number. - if i == 0 { - link.Attrs().Name = strings.Trim(string(localReq.Name[:]), "\x00") - } - - } - - // only persist interface if NonPersist is NOT set - if !tuntap.NonPersist { - _, _, errno := unix.Syscall(unix.SYS_IOCTL, fds[0].Fd(), uintptr(unix.TUNSETPERSIST), 1) - if errno != 0 { - cleanupFds(fds) - return fmt.Errorf("Tuntap IOCTL TUNSETPERSIST failed, errno %v", errno) - } - } - - h.ensureIndex(base) - - // can't set master during create, so set it afterwards - if base.MasterIndex != 0 { - // TODO: verify MasterIndex is actually a bridge? - err := h.LinkSetMasterByIndex(link, base.MasterIndex) - if err != nil { - // un-persist (e.g. allow the interface to be removed) the tuntap - // should not hurt if not set prior, condition might be not needed - if !tuntap.NonPersist { - _, _, _ = unix.Syscall(unix.SYS_IOCTL, fds[0].Fd(), uintptr(unix.TUNSETPERSIST), 0) - } - cleanupFds(fds) - return err - } - } - - if tuntap.Queues == 0 { - cleanupFds(fds) - } else { - tuntap.Fds = fds - } - - return nil - } - - req := h.newNetlinkRequest(unix.RTM_NEWLINK, flags) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - // TODO: make it shorter - if base.Flags&net.FlagUp != 0 { - msg.Change = unix.IFF_UP - msg.Flags = unix.IFF_UP - } - if base.Flags&net.FlagBroadcast != 0 { - msg.Change |= unix.IFF_BROADCAST - msg.Flags |= unix.IFF_BROADCAST - } - if base.Flags&net.FlagLoopback != 0 { - msg.Change |= unix.IFF_LOOPBACK - msg.Flags |= unix.IFF_LOOPBACK - } - if base.Flags&net.FlagPointToPoint != 0 { - msg.Change |= unix.IFF_POINTOPOINT - msg.Flags |= unix.IFF_POINTOPOINT - } - if base.Flags&net.FlagMulticast != 0 { - msg.Change |= unix.IFF_MULTICAST - msg.Flags |= unix.IFF_MULTICAST - } - if base.Index != 0 { - msg.Index = int32(base.Index) - } - - req.AddData(msg) - - if base.ParentIndex != 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(base.ParentIndex)) - data := nl.NewRtAttr(unix.IFLA_LINK, b) - req.AddData(data) - } else if link.Type() == "ipvlan" || link.Type() == "ipoib" { - return fmt.Errorf("Can't create %s link without ParentIndex", link.Type()) - } - - nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(base.Name)) - req.AddData(nameData) - - if base.Alias != "" { - alias := nl.NewRtAttr(unix.IFLA_IFALIAS, []byte(base.Alias)) - req.AddData(alias) - } - - if base.MTU > 0 { - mtu := nl.NewRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) - req.AddData(mtu) - } - - if base.TxQLen >= 0 { - qlen := nl.NewRtAttr(unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) - req.AddData(qlen) - } - - if base.HardwareAddr != nil { - hwaddr := nl.NewRtAttr(unix.IFLA_ADDRESS, []byte(base.HardwareAddr)) - req.AddData(hwaddr) - } - - if base.NumTxQueues > 0 { - txqueues := nl.NewRtAttr(unix.IFLA_NUM_TX_QUEUES, nl.Uint32Attr(uint32(base.NumTxQueues))) - req.AddData(txqueues) - } - - if base.NumRxQueues > 0 { - rxqueues := nl.NewRtAttr(unix.IFLA_NUM_RX_QUEUES, nl.Uint32Attr(uint32(base.NumRxQueues))) - req.AddData(rxqueues) - } - - if base.GSOMaxSegs > 0 { - gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SEGS, nl.Uint32Attr(base.GSOMaxSegs)) - req.AddData(gsoAttr) - } - - if base.GSOMaxSize > 0 { - gsoAttr := nl.NewRtAttr(unix.IFLA_GSO_MAX_SIZE, nl.Uint32Attr(base.GSOMaxSize)) - req.AddData(gsoAttr) - } - - if base.Group > 0 { - groupAttr := nl.NewRtAttr(unix.IFLA_GROUP, nl.Uint32Attr(base.Group)) - req.AddData(groupAttr) - } - - if base.Namespace != nil { - var attr *nl.RtAttr - switch ns := base.Namespace.(type) { - case NsPid: - val := nl.Uint32Attr(uint32(ns)) - attr = nl.NewRtAttr(unix.IFLA_NET_NS_PID, val) - case NsFd: - val := nl.Uint32Attr(uint32(ns)) - attr = nl.NewRtAttr(unix.IFLA_NET_NS_FD, val) - } - - req.AddData(attr) - } - - if base.Xdp != nil { - addXdpAttrs(base.Xdp, req) - } - - linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) - linkInfo.AddRtAttr(nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type())) - - switch link := link.(type) { - case *Vlan: - b := make([]byte, 2) - native.PutUint16(b, uint16(link.VlanId)) - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_VLAN_ID, b) - - if link.VlanProtocol != VLAN_PROTOCOL_UNKNOWN { - data.AddRtAttr(nl.IFLA_VLAN_PROTOCOL, htons(uint16(link.VlanProtocol))) - } - case *Veth: - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - peer := data.AddRtAttr(nl.VETH_INFO_PEER, nil) - nl.NewIfInfomsgChild(peer, unix.AF_UNSPEC) - peer.AddRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(link.PeerName)) - if base.TxQLen >= 0 { - peer.AddRtAttr(unix.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen))) - } - if base.NumTxQueues > 0 { - peer.AddRtAttr(unix.IFLA_NUM_TX_QUEUES, nl.Uint32Attr(uint32(base.NumTxQueues))) - } - if base.NumRxQueues > 0 { - peer.AddRtAttr(unix.IFLA_NUM_RX_QUEUES, nl.Uint32Attr(uint32(base.NumRxQueues))) - } - if base.MTU > 0 { - peer.AddRtAttr(unix.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU))) - } - if link.PeerHardwareAddr != nil { - peer.AddRtAttr(unix.IFLA_ADDRESS, []byte(link.PeerHardwareAddr)) - } - if link.PeerNamespace != nil { - switch ns := link.PeerNamespace.(type) { - case NsPid: - val := nl.Uint32Attr(uint32(ns)) - peer.AddRtAttr(unix.IFLA_NET_NS_PID, val) - case NsFd: - val := nl.Uint32Attr(uint32(ns)) - peer.AddRtAttr(unix.IFLA_NET_NS_FD, val) - } - } - case *Vxlan: - addVxlanAttrs(link, linkInfo) - case *Bond: - addBondAttrs(link, linkInfo) - case *IPVlan: - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(link.Mode))) - data.AddRtAttr(nl.IFLA_IPVLAN_FLAG, nl.Uint16Attr(uint16(link.Flag))) - case *Macvlan: - if link.Mode != MACVLAN_MODE_DEFAULT { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[link.Mode])) - } - case *Macvtap: - if link.Mode != MACVLAN_MODE_DEFAULT { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[link.Mode])) - } - case *Gretap: - addGretapAttrs(link, linkInfo) - case *Iptun: - addIptunAttrs(link, linkInfo) - case *Ip6tnl: - addIp6tnlAttrs(link, linkInfo) - case *Sittun: - addSittunAttrs(link, linkInfo) - case *Gretun: - addGretunAttrs(link, linkInfo) - case *Vti: - addVtiAttrs(link, linkInfo) - case *Vrf: - addVrfAttrs(link, linkInfo) - case *Bridge: - addBridgeAttrs(link, linkInfo) - case *GTP: - addGTPAttrs(link, linkInfo) - case *Xfrmi: - addXfrmiAttrs(link, linkInfo) - case *IPoIB: - addIPoIBAttrs(link, linkInfo) - } - - req.AddData(linkInfo) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - if err != nil { - return err - } - - h.ensureIndex(base) - - // can't set master during create, so set it afterwards - if base.MasterIndex != 0 { - // TODO: verify MasterIndex is actually a bridge? - return h.LinkSetMasterByIndex(link, base.MasterIndex) - } - return nil -} - -// LinkDel deletes link device. Either Index or Name must be set in -// the link object for it to be deleted. The other values are ignored. -// Equivalent to: `ip link del $link` -func LinkDel(link Link) error { - return pkgHandle.LinkDel(link) -} - -// LinkDel deletes link device. Either Index or Name must be set in -// the link object for it to be deleted. The other values are ignored. -// Equivalent to: `ip link del $link` -func (h *Handle) LinkDel(link Link) error { - base := link.Attrs() - - h.ensureIndex(base) - - req := h.newNetlinkRequest(unix.RTM_DELLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func (h *Handle) linkByNameDump(name string) (Link, error) { - links, err := h.LinkList() - if err != nil { - return nil, err - } - - for _, link := range links { - if link.Attrs().Name == name { - return link, nil - } - } - return nil, LinkNotFoundError{fmt.Errorf("Link %s not found", name)} -} - -func (h *Handle) linkByAliasDump(alias string) (Link, error) { - links, err := h.LinkList() - if err != nil { - return nil, err - } - - for _, link := range links { - if link.Attrs().Alias == alias { - return link, nil - } - } - return nil, LinkNotFoundError{fmt.Errorf("Link alias %s not found", alias)} -} - -// LinkByName finds a link by name and returns a pointer to the object. -func LinkByName(name string) (Link, error) { - return pkgHandle.LinkByName(name) -} - -// LinkByName finds a link by name and returns a pointer to the object. -func (h *Handle) LinkByName(name string) (Link, error) { - if h.lookupByDump { - return h.linkByNameDump(name) - } - - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(msg) - - attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) - req.AddData(attr) - - nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(name)) - req.AddData(nameData) - - link, err := execGetLink(req) - if err == unix.EINVAL { - // older kernels don't support looking up via IFLA_IFNAME - // so fall back to dumping all links - h.lookupByDump = true - return h.linkByNameDump(name) - } - - return link, err -} - -// LinkByAlias finds a link by its alias and returns a pointer to the object. -// If there are multiple links with the alias it returns the first one -func LinkByAlias(alias string) (Link, error) { - return pkgHandle.LinkByAlias(alias) -} - -// LinkByAlias finds a link by its alias and returns a pointer to the object. -// If there are multiple links with the alias it returns the first one -func (h *Handle) LinkByAlias(alias string) (Link, error) { - if h.lookupByDump { - return h.linkByAliasDump(alias) - } - - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(msg) - - attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) - req.AddData(attr) - - nameData := nl.NewRtAttr(unix.IFLA_IFALIAS, nl.ZeroTerminated(alias)) - req.AddData(nameData) - - link, err := execGetLink(req) - if err == unix.EINVAL { - // older kernels don't support looking up via IFLA_IFALIAS - // so fall back to dumping all links - h.lookupByDump = true - return h.linkByAliasDump(alias) - } - - return link, err -} - -// LinkByIndex finds a link by index and returns a pointer to the object. -func LinkByIndex(index int) (Link, error) { - return pkgHandle.LinkByIndex(index) -} - -// LinkByIndex finds a link by index and returns a pointer to the object. -func (h *Handle) LinkByIndex(index int) (Link, error) { - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(index) - req.AddData(msg) - attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) - req.AddData(attr) - - return execGetLink(req) -} - -func execGetLink(req *nl.NetlinkRequest) (Link, error) { - msgs, err := req.Execute(unix.NETLINK_ROUTE, 0) - if err != nil { - if errno, ok := err.(syscall.Errno); ok { - if errno == unix.ENODEV { - return nil, LinkNotFoundError{fmt.Errorf("Link not found")} - } - } - return nil, err - } - - switch { - case len(msgs) == 0: - return nil, LinkNotFoundError{fmt.Errorf("Link not found")} - - case len(msgs) == 1: - return LinkDeserialize(nil, msgs[0]) - - default: - return nil, fmt.Errorf("More than one link found") - } -} - -// linkDeserialize deserializes a raw message received from netlink into -// a link object. -func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) { - msg := nl.DeserializeIfInfomsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - base := NewLinkAttrs() - base.Index = int(msg.Index) - base.RawFlags = msg.Flags - base.Flags = linkFlags(msg.Flags) - base.EncapType = msg.EncapType() - if msg.Flags&unix.IFF_PROMISC != 0 { - base.Promisc = 1 - } - var ( - link Link - stats32 *LinkStatistics32 - stats64 *LinkStatistics64 - linkType string - linkSlave LinkSlave - slaveType string - ) - for _, attr := range attrs { - switch attr.Attr.Type { - case unix.IFLA_LINKINFO: - infos, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - for _, info := range infos { - switch info.Attr.Type { - case nl.IFLA_INFO_KIND: - linkType = string(info.Value[:len(info.Value)-1]) - switch linkType { - case "dummy": - link = &Dummy{} - case "ifb": - link = &Ifb{} - case "bridge": - link = &Bridge{} - case "vlan": - link = &Vlan{} - case "veth": - link = &Veth{} - case "wireguard": - link = &Wireguard{} - case "vxlan": - link = &Vxlan{} - case "bond": - link = &Bond{} - case "ipvlan": - link = &IPVlan{} - case "macvlan": - link = &Macvlan{} - case "macvtap": - link = &Macvtap{} - case "gretap": - link = &Gretap{} - case "ip6gretap": - link = &Gretap{} - case "ipip": - link = &Iptun{} - case "ip6tnl": - link = &Ip6tnl{} - case "sit": - link = &Sittun{} - case "gre": - link = &Gretun{} - case "ip6gre": - link = &Gretun{} - case "vti", "vti6": - link = &Vti{} - case "vrf": - link = &Vrf{} - case "gtp": - link = >P{} - case "xfrm": - link = &Xfrmi{} - case "tun": - link = &Tuntap{} - case "ipoib": - link = &IPoIB{} - default: - link = &GenericLink{LinkType: linkType} - } - case nl.IFLA_INFO_DATA: - data, err := nl.ParseRouteAttr(info.Value) - if err != nil { - return nil, err - } - switch linkType { - case "vlan": - parseVlanData(link, data) - case "vxlan": - parseVxlanData(link, data) - case "bond": - parseBondData(link, data) - case "ipvlan": - parseIPVlanData(link, data) - case "macvlan": - parseMacvlanData(link, data) - case "macvtap": - parseMacvtapData(link, data) - case "gretap": - parseGretapData(link, data) - case "ip6gretap": - parseGretapData(link, data) - case "ipip": - parseIptunData(link, data) - case "ip6tnl": - parseIp6tnlData(link, data) - case "sit": - parseSittunData(link, data) - case "gre": - parseGretunData(link, data) - case "ip6gre": - parseGretunData(link, data) - case "vti", "vti6": - parseVtiData(link, data) - case "vrf": - parseVrfData(link, data) - case "bridge": - parseBridgeData(link, data) - case "gtp": - parseGTPData(link, data) - case "xfrm": - parseXfrmiData(link, data) - case "tun": - parseTuntapData(link, data) - case "ipoib": - parseIPoIBData(link, data) - } - case nl.IFLA_INFO_SLAVE_KIND: - slaveType = string(info.Value[:len(info.Value)-1]) - switch slaveType { - case "bond": - linkSlave = &BondSlave{} - } - case nl.IFLA_INFO_SLAVE_DATA: - switch slaveType { - case "bond": - data, err := nl.ParseRouteAttr(info.Value) - if err != nil { - return nil, err - } - parseBondSlaveData(linkSlave, data) - } - } - } - case unix.IFLA_ADDRESS: - var nonzero bool - for _, b := range attr.Value { - if b != 0 { - nonzero = true - } - } - if nonzero { - base.HardwareAddr = attr.Value[:] - } - case unix.IFLA_IFNAME: - base.Name = string(attr.Value[:len(attr.Value)-1]) - case unix.IFLA_MTU: - base.MTU = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_LINK: - base.ParentIndex = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_MASTER: - base.MasterIndex = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_TXQLEN: - base.TxQLen = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_IFALIAS: - base.Alias = string(attr.Value[:len(attr.Value)-1]) - case unix.IFLA_STATS: - stats32 = new(LinkStatistics32) - if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats32); err != nil { - return nil, err - } - case unix.IFLA_STATS64: - stats64 = new(LinkStatistics64) - if err := binary.Read(bytes.NewBuffer(attr.Value[:]), nl.NativeEndian(), stats64); err != nil { - return nil, err - } - case unix.IFLA_XDP: - xdp, err := parseLinkXdp(attr.Value[:]) - if err != nil { - return nil, err - } - base.Xdp = xdp - case unix.IFLA_PROTINFO | unix.NLA_F_NESTED: - if hdr != nil && hdr.Type == unix.RTM_NEWLINK && - msg.Family == unix.AF_BRIDGE { - attrs, err := nl.ParseRouteAttr(attr.Value[:]) - if err != nil { - return nil, err - } - protinfo := parseProtinfo(attrs) - base.Protinfo = &protinfo - } - case unix.IFLA_OPERSTATE: - base.OperState = LinkOperState(uint8(attr.Value[0])) - case unix.IFLA_LINK_NETNSID: - base.NetNsID = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_GSO_MAX_SIZE: - base.GSOMaxSize = native.Uint32(attr.Value[0:4]) - case unix.IFLA_GSO_MAX_SEGS: - base.GSOMaxSegs = native.Uint32(attr.Value[0:4]) - case unix.IFLA_VFINFO_LIST: - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - vfs, err := parseVfInfoList(data) - if err != nil { - return nil, err - } - base.Vfs = vfs - case unix.IFLA_NUM_TX_QUEUES: - base.NumTxQueues = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_NUM_RX_QUEUES: - base.NumRxQueues = int(native.Uint32(attr.Value[0:4])) - case unix.IFLA_GROUP: - base.Group = native.Uint32(attr.Value[0:4]) - } - } - - if stats64 != nil { - base.Statistics = (*LinkStatistics)(stats64) - } else if stats32 != nil { - base.Statistics = (*LinkStatistics)(stats32.to64()) - } - - // Links that don't have IFLA_INFO_KIND are hardware devices - if link == nil { - link = &Device{} - } - *link.Attrs() = base - link.Attrs().Slave = linkSlave - - // If the tuntap attributes are not updated by netlink due to - // an older driver, use sysfs - if link != nil && linkType == "tun" { - tuntap := link.(*Tuntap) - - if tuntap.Mode == 0 { - ifname := tuntap.Attrs().Name - if flags, err := readSysPropAsInt64(ifname, "tun_flags"); err == nil { - - if flags&unix.IFF_TUN != 0 { - tuntap.Mode = unix.IFF_TUN - } else if flags&unix.IFF_TAP != 0 { - tuntap.Mode = unix.IFF_TAP - } - - tuntap.NonPersist = false - if flags&unix.IFF_PERSIST == 0 { - tuntap.NonPersist = true - } - } - - // The sysfs interface for owner/group returns -1 for root user, instead of returning 0. - // So explicitly check for negative value, before assigning the owner uid/gid. - if owner, err := readSysPropAsInt64(ifname, "owner"); err == nil && owner > 0 { - tuntap.Owner = uint32(owner) - } - - if group, err := readSysPropAsInt64(ifname, "group"); err == nil && group > 0 { - tuntap.Group = uint32(group) - } - } - } - - return link, nil -} - -func readSysPropAsInt64(ifname, prop string) (int64, error) { - fname := fmt.Sprintf("/sys/class/net/%s/%s", ifname, prop) - contents, err := ioutil.ReadFile(fname) - if err != nil { - return 0, err - } - - num, err := strconv.ParseInt(strings.TrimSpace(string(contents)), 0, 64) - if err == nil { - return num, nil - } - - return 0, err -} - -// LinkList gets a list of link devices. -// Equivalent to: `ip link show` -func LinkList() ([]Link, error) { - return pkgHandle.LinkList() -} - -// LinkList gets a list of link devices. -// Equivalent to: `ip link show` -func (h *Handle) LinkList() ([]Link, error) { - // NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need - // to get the message ourselves to parse link type. - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(msg) - attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF)) - req.AddData(attr) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK) - if err != nil { - return nil, err - } - - var res []Link - for _, m := range msgs { - link, err := LinkDeserialize(nil, m) - if err != nil { - return nil, err - } - res = append(res, link) - } - - return res, nil -} - -// LinkUpdate is used to pass information back from LinkSubscribe() -type LinkUpdate struct { - nl.IfInfomsg - Header unix.NlMsghdr - Link -} - -// LinkSubscribe takes a chan down which notifications will be sent -// when links change. Close the 'done' chan to stop subscription. -func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error { - return linkSubscribeAt(netns.None(), netns.None(), ch, done, nil, false) -} - -// LinkSubscribeAt works like LinkSubscribe plus it allows the caller -// to choose the network namespace in which to subscribe (ns). -func LinkSubscribeAt(ns netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error { - return linkSubscribeAt(ns, netns.None(), ch, done, nil, false) -} - -// LinkSubscribeOptions contains a set of options to use with -// LinkSubscribeWithOptions. -type LinkSubscribeOptions struct { - Namespace *netns.NsHandle - ErrorCallback func(error) - ListExisting bool -} - -// LinkSubscribeWithOptions work like LinkSubscribe but enable to -// provide additional options to modify the behavior. Currently, the -// namespace can be provided as well as an error callback. -func LinkSubscribeWithOptions(ch chan<- LinkUpdate, done <-chan struct{}, options LinkSubscribeOptions) error { - if options.Namespace == nil { - none := netns.None() - options.Namespace = &none - } - return linkSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting) -} - -func linkSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error { - s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_LINK) - if err != nil { - return err - } - if done != nil { - go func() { - <-done - s.Close() - }() - } - if listExisting { - req := pkgHandle.newNetlinkRequest(unix.RTM_GETLINK, - unix.NLM_F_DUMP) - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(msg) - if err := s.Send(req); err != nil { - return err - } - } - go func() { - defer close(ch) - for { - msgs, from, err := s.Receive() - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - if from.Pid != nl.PidKernel { - if cberr != nil { - cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)) - } - continue - } - for _, m := range msgs { - if m.Header.Type == unix.NLMSG_DONE { - continue - } - if m.Header.Type == unix.NLMSG_ERROR { - native := nl.NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - if error == 0 { - continue - } - if cberr != nil { - cberr(syscall.Errno(-error)) - } - return - } - ifmsg := nl.DeserializeIfInfomsg(m.Data) - header := unix.NlMsghdr(m.Header) - link, err := LinkDeserialize(&header, m.Data) - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - ch <- LinkUpdate{IfInfomsg: *ifmsg, Header: header, Link: link} - } - } - }() - - return nil -} - -func LinkSetHairpin(link Link, mode bool) error { - return pkgHandle.LinkSetHairpin(link, mode) -} - -func (h *Handle) LinkSetHairpin(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE) -} - -func LinkSetGuard(link Link, mode bool) error { - return pkgHandle.LinkSetGuard(link, mode) -} - -func (h *Handle) LinkSetGuard(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_GUARD) -} - -func LinkSetFastLeave(link Link, mode bool) error { - return pkgHandle.LinkSetFastLeave(link, mode) -} - -func (h *Handle) LinkSetFastLeave(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_FAST_LEAVE) -} - -func LinkSetLearning(link Link, mode bool) error { - return pkgHandle.LinkSetLearning(link, mode) -} - -func (h *Handle) LinkSetLearning(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_LEARNING) -} - -func LinkSetRootBlock(link Link, mode bool) error { - return pkgHandle.LinkSetRootBlock(link, mode) -} - -func (h *Handle) LinkSetRootBlock(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROTECT) -} - -func LinkSetFlood(link Link, mode bool) error { - return pkgHandle.LinkSetFlood(link, mode) -} - -func (h *Handle) LinkSetFlood(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_UNICAST_FLOOD) -} - -func LinkSetBrProxyArp(link Link, mode bool) error { - return pkgHandle.LinkSetBrProxyArp(link, mode) -} - -func (h *Handle) LinkSetBrProxyArp(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP) -} - -func LinkSetBrProxyArpWiFi(link Link, mode bool) error { - return pkgHandle.LinkSetBrProxyArpWiFi(link, mode) -} - -func (h *Handle) LinkSetBrProxyArpWiFi(link Link, mode bool) error { - return h.setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROXYARP_WIFI) -} - -func (h *Handle) setProtinfoAttr(link Link, mode bool, attr int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_BRIDGE) - msg.Index = int32(base.Index) - req.AddData(msg) - - br := nl.NewRtAttr(unix.IFLA_PROTINFO|unix.NLA_F_NESTED, nil) - br.AddRtAttr(attr, boolToByte(mode)) - req.AddData(br) - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - if err != nil { - return err - } - return nil -} - -// LinkSetTxQLen sets the transaction queue length for the link. -// Equivalent to: `ip link set $link txqlen $qlen` -func LinkSetTxQLen(link Link, qlen int) error { - return pkgHandle.LinkSetTxQLen(link, qlen) -} - -// LinkSetTxQLen sets the transaction queue length for the link. -// Equivalent to: `ip link set $link txqlen $qlen` -func (h *Handle) LinkSetTxQLen(link Link, qlen int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(qlen)) - - data := nl.NewRtAttr(unix.IFLA_TXQLEN, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetGroup sets the link group id which can be used to perform mass actions -// with iproute2 as well use it as a reference in nft filters. -// Equivalent to: `ip link set $link group $id` -func LinkSetGroup(link Link, group int) error { - return pkgHandle.LinkSetGroup(link, group) -} - -// LinkSetGroup sets the link group id which can be used to perform mass actions -// with iproute2 as well use it as a reference in nft filters. -// Equivalent to: `ip link set $link group $id` -func (h *Handle) LinkSetGroup(link Link, group int) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - b := make([]byte, 4) - native.PutUint32(b, uint32(group)) - - data := nl.NewRtAttr(unix.IFLA_GROUP, b) - req.AddData(data) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) { - vlan := link.(*Vlan) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_VLAN_ID: - vlan.VlanId = int(native.Uint16(datum.Value[0:2])) - case nl.IFLA_VLAN_PROTOCOL: - vlan.VlanProtocol = VlanProtocol(int(ntohs(datum.Value[0:2]))) - } - } -} - -func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) { - vxlan := link.(*Vxlan) - for _, datum := range data { - // NOTE(vish): Apparently some messages can be sent with no value. - // We special case GBP here to not change existing - // functionality. It appears that GBP sends a datum.Value - // of null. - if len(datum.Value) == 0 && datum.Attr.Type != nl.IFLA_VXLAN_GBP { - continue - } - switch datum.Attr.Type { - case nl.IFLA_VXLAN_ID: - vxlan.VxlanId = int(native.Uint32(datum.Value[0:4])) - case nl.IFLA_VXLAN_LINK: - vxlan.VtepDevIndex = int(native.Uint32(datum.Value[0:4])) - case nl.IFLA_VXLAN_LOCAL: - vxlan.SrcAddr = net.IP(datum.Value[0:4]) - case nl.IFLA_VXLAN_LOCAL6: - vxlan.SrcAddr = net.IP(datum.Value[0:16]) - case nl.IFLA_VXLAN_GROUP: - vxlan.Group = net.IP(datum.Value[0:4]) - case nl.IFLA_VXLAN_GROUP6: - vxlan.Group = net.IP(datum.Value[0:16]) - case nl.IFLA_VXLAN_TTL: - vxlan.TTL = int(datum.Value[0]) - case nl.IFLA_VXLAN_TOS: - vxlan.TOS = int(datum.Value[0]) - case nl.IFLA_VXLAN_LEARNING: - vxlan.Learning = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_PROXY: - vxlan.Proxy = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_RSC: - vxlan.RSC = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_L2MISS: - vxlan.L2miss = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_L3MISS: - vxlan.L3miss = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_UDP_CSUM: - vxlan.UDPCSum = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_UDP_ZERO_CSUM6_TX: - vxlan.UDP6ZeroCSumTx = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_UDP_ZERO_CSUM6_RX: - vxlan.UDP6ZeroCSumRx = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_GBP: - vxlan.GBP = true - case nl.IFLA_VXLAN_FLOWBASED: - vxlan.FlowBased = int8(datum.Value[0]) != 0 - case nl.IFLA_VXLAN_AGEING: - vxlan.Age = int(native.Uint32(datum.Value[0:4])) - vxlan.NoAge = vxlan.Age == 0 - case nl.IFLA_VXLAN_LIMIT: - vxlan.Limit = int(native.Uint32(datum.Value[0:4])) - case nl.IFLA_VXLAN_PORT: - vxlan.Port = int(ntohs(datum.Value[0:2])) - case nl.IFLA_VXLAN_PORT_RANGE: - buf := bytes.NewBuffer(datum.Value[0:4]) - var pr vxlanPortRange - if binary.Read(buf, binary.BigEndian, &pr) != nil { - vxlan.PortLow = int(pr.Lo) - vxlan.PortHigh = int(pr.Hi) - } - } - } -} - -func parseBondData(link Link, data []syscall.NetlinkRouteAttr) { - bond := link.(*Bond) - for i := range data { - switch data[i].Attr.Type { - case nl.IFLA_BOND_MODE: - bond.Mode = BondMode(data[i].Value[0]) - case nl.IFLA_BOND_ACTIVE_SLAVE: - bond.ActiveSlave = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_MIIMON: - bond.Miimon = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_UPDELAY: - bond.UpDelay = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_DOWNDELAY: - bond.DownDelay = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_USE_CARRIER: - bond.UseCarrier = int(data[i].Value[0]) - case nl.IFLA_BOND_ARP_INTERVAL: - bond.ArpInterval = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_ARP_IP_TARGET: - bond.ArpIpTargets = parseBondArpIpTargets(data[i].Value) - case nl.IFLA_BOND_ARP_VALIDATE: - bond.ArpValidate = BondArpValidate(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_ARP_ALL_TARGETS: - bond.ArpAllTargets = BondArpAllTargets(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_PRIMARY: - bond.Primary = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_PRIMARY_RESELECT: - bond.PrimaryReselect = BondPrimaryReselect(data[i].Value[0]) - case nl.IFLA_BOND_FAIL_OVER_MAC: - bond.FailOverMac = BondFailOverMac(data[i].Value[0]) - case nl.IFLA_BOND_XMIT_HASH_POLICY: - bond.XmitHashPolicy = BondXmitHashPolicy(data[i].Value[0]) - case nl.IFLA_BOND_RESEND_IGMP: - bond.ResendIgmp = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_NUM_PEER_NOTIF: - bond.NumPeerNotif = int(data[i].Value[0]) - case nl.IFLA_BOND_ALL_SLAVES_ACTIVE: - bond.AllSlavesActive = int(data[i].Value[0]) - case nl.IFLA_BOND_MIN_LINKS: - bond.MinLinks = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_LP_INTERVAL: - bond.LpInterval = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_PACKETS_PER_SLAVE: - bond.PackersPerSlave = int(native.Uint32(data[i].Value[0:4])) - case nl.IFLA_BOND_AD_LACP_RATE: - bond.LacpRate = BondLacpRate(data[i].Value[0]) - case nl.IFLA_BOND_AD_SELECT: - bond.AdSelect = BondAdSelect(data[i].Value[0]) - case nl.IFLA_BOND_AD_INFO: - // TODO: implement - case nl.IFLA_BOND_AD_ACTOR_SYS_PRIO: - bond.AdActorSysPrio = int(native.Uint16(data[i].Value[0:2])) - case nl.IFLA_BOND_AD_USER_PORT_KEY: - bond.AdUserPortKey = int(native.Uint16(data[i].Value[0:2])) - case nl.IFLA_BOND_AD_ACTOR_SYSTEM: - bond.AdActorSystem = net.HardwareAddr(data[i].Value[0:6]) - case nl.IFLA_BOND_TLB_DYNAMIC_LB: - bond.TlbDynamicLb = int(data[i].Value[0]) - } - } -} - -func parseBondArpIpTargets(value []byte) []net.IP { - data, err := nl.ParseRouteAttr(value) - if err != nil { - return nil - } - - targets := []net.IP{} - for i := range data { - target := net.IP(data[i].Value) - if ip := target.To4(); ip != nil { - targets = append(targets, ip) - continue - } - if ip := target.To16(); ip != nil { - targets = append(targets, ip) - } - } - - return targets -} - -func addBondSlaveAttrs(bondSlave *BondSlave, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil) - - data.AddRtAttr(nl.IFLA_BOND_SLAVE_STATE, nl.Uint8Attr(uint8(bondSlave.State))) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_MII_STATUS, nl.Uint8Attr(uint8(bondSlave.MiiStatus))) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT, nl.Uint32Attr(bondSlave.LinkFailureCount)) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(bondSlave.QueueId)) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID, nl.Uint16Attr(bondSlave.AggregatorId)) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE, nl.Uint8Attr(bondSlave.AdActorOperPortState)) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE, nl.Uint16Attr(bondSlave.AdPartnerOperPortState)) - - if mac := bondSlave.PermHardwareAddr; mac != nil { - data.AddRtAttr(nl.IFLA_BOND_SLAVE_PERM_HWADDR, []byte(mac)) - } -} - -func parseBondSlaveData(slave LinkSlave, data []syscall.NetlinkRouteAttr) { - bondSlave := slave.(*BondSlave) - for i := range data { - switch data[i].Attr.Type { - case nl.IFLA_BOND_SLAVE_STATE: - bondSlave.State = BondSlaveState(data[i].Value[0]) - case nl.IFLA_BOND_SLAVE_MII_STATUS: - bondSlave.MiiStatus = BondSlaveMiiStatus(data[i].Value[0]) - case nl.IFLA_BOND_SLAVE_LINK_FAILURE_COUNT: - bondSlave.LinkFailureCount = native.Uint32(data[i].Value[0:4]) - case nl.IFLA_BOND_SLAVE_PERM_HWADDR: - bondSlave.PermHardwareAddr = net.HardwareAddr(data[i].Value[0:6]) - case nl.IFLA_BOND_SLAVE_QUEUE_ID: - bondSlave.QueueId = native.Uint16(data[i].Value[0:2]) - case nl.IFLA_BOND_SLAVE_AD_AGGREGATOR_ID: - bondSlave.AggregatorId = native.Uint16(data[i].Value[0:2]) - case nl.IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE: - bondSlave.AdActorOperPortState = uint8(data[i].Value[0]) - case nl.IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE: - bondSlave.AdPartnerOperPortState = native.Uint16(data[i].Value[0:2]) - } - } -} - -func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) { - ipv := link.(*IPVlan) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_IPVLAN_MODE: - ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4])) - case nl.IFLA_IPVLAN_FLAG: - ipv.Flag = IPVlanFlag(native.Uint32(datum.Value[0:4])) - } - } -} - -func parseMacvtapData(link Link, data []syscall.NetlinkRouteAttr) { - macv := link.(*Macvtap) - parseMacvlanData(&macv.Macvlan, data) -} - -func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) { - macv := link.(*Macvlan) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_MACVLAN_MODE: - switch native.Uint32(datum.Value[0:4]) { - case nl.MACVLAN_MODE_PRIVATE: - macv.Mode = MACVLAN_MODE_PRIVATE - case nl.MACVLAN_MODE_VEPA: - macv.Mode = MACVLAN_MODE_VEPA - case nl.MACVLAN_MODE_BRIDGE: - macv.Mode = MACVLAN_MODE_BRIDGE - case nl.MACVLAN_MODE_PASSTHRU: - macv.Mode = MACVLAN_MODE_PASSTHRU - case nl.MACVLAN_MODE_SOURCE: - macv.Mode = MACVLAN_MODE_SOURCE - } - case nl.IFLA_MACVLAN_MACADDR_COUNT: - macv.MACAddrs = make([]net.HardwareAddr, 0, int(native.Uint32(datum.Value[0:4]))) - case nl.IFLA_MACVLAN_MACADDR_DATA: - macs, err := nl.ParseRouteAttr(datum.Value[:]) - if err != nil { - panic(fmt.Sprintf("failed to ParseRouteAttr for IFLA_MACVLAN_MACADDR_DATA: %v", err)) - } - for _, macDatum := range macs { - macv.MACAddrs = append(macv.MACAddrs, net.HardwareAddr(macDatum.Value[0:6])) - } - } - } -} - -// copied from pkg/net_linux.go -func linkFlags(rawFlags uint32) net.Flags { - var f net.Flags - if rawFlags&unix.IFF_UP != 0 { - f |= net.FlagUp - } - if rawFlags&unix.IFF_BROADCAST != 0 { - f |= net.FlagBroadcast - } - if rawFlags&unix.IFF_LOOPBACK != 0 { - f |= net.FlagLoopback - } - if rawFlags&unix.IFF_POINTOPOINT != 0 { - f |= net.FlagPointToPoint - } - if rawFlags&unix.IFF_MULTICAST != 0 { - f |= net.FlagMulticast - } - return f -} - -func addGretapAttrs(gretap *Gretap, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - if gretap.FlowBased { - // In flow based mode, no other attributes need to be configured - data.AddRtAttr(nl.IFLA_GRE_COLLECT_METADATA, boolAttr(gretap.FlowBased)) - return - } - - if ip := gretap.Local; ip != nil { - if ip.To4() != nil { - ip = ip.To4() - } - data.AddRtAttr(nl.IFLA_GRE_LOCAL, []byte(ip)) - } - - if ip := gretap.Remote; ip != nil { - if ip.To4() != nil { - ip = ip.To4() - } - data.AddRtAttr(nl.IFLA_GRE_REMOTE, []byte(ip)) - } - - if gretap.IKey != 0 { - data.AddRtAttr(nl.IFLA_GRE_IKEY, htonl(gretap.IKey)) - gretap.IFlags |= uint16(nl.GRE_KEY) - } - - if gretap.OKey != 0 { - data.AddRtAttr(nl.IFLA_GRE_OKEY, htonl(gretap.OKey)) - gretap.OFlags |= uint16(nl.GRE_KEY) - } - - data.AddRtAttr(nl.IFLA_GRE_IFLAGS, htons(gretap.IFlags)) - data.AddRtAttr(nl.IFLA_GRE_OFLAGS, htons(gretap.OFlags)) - - if gretap.Link != 0 { - data.AddRtAttr(nl.IFLA_GRE_LINK, nl.Uint32Attr(gretap.Link)) - } - - data.AddRtAttr(nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gretap.PMtuDisc)) - data.AddRtAttr(nl.IFLA_GRE_TTL, nl.Uint8Attr(gretap.Ttl)) - data.AddRtAttr(nl.IFLA_GRE_TOS, nl.Uint8Attr(gretap.Tos)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gretap.EncapType)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gretap.EncapFlags)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_SPORT, htons(gretap.EncapSport)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_DPORT, htons(gretap.EncapDport)) -} - -func parseGretapData(link Link, data []syscall.NetlinkRouteAttr) { - gre := link.(*Gretap) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_GRE_OKEY: - gre.IKey = ntohl(datum.Value[0:4]) - case nl.IFLA_GRE_IKEY: - gre.OKey = ntohl(datum.Value[0:4]) - case nl.IFLA_GRE_LOCAL: - gre.Local = net.IP(datum.Value) - case nl.IFLA_GRE_REMOTE: - gre.Remote = net.IP(datum.Value) - case nl.IFLA_GRE_ENCAP_SPORT: - gre.EncapSport = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_ENCAP_DPORT: - gre.EncapDport = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_IFLAGS: - gre.IFlags = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_OFLAGS: - gre.OFlags = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_TTL: - gre.Ttl = uint8(datum.Value[0]) - case nl.IFLA_GRE_TOS: - gre.Tos = uint8(datum.Value[0]) - case nl.IFLA_GRE_PMTUDISC: - gre.PMtuDisc = uint8(datum.Value[0]) - case nl.IFLA_GRE_ENCAP_TYPE: - gre.EncapType = native.Uint16(datum.Value[0:2]) - case nl.IFLA_GRE_ENCAP_FLAGS: - gre.EncapFlags = native.Uint16(datum.Value[0:2]) - case nl.IFLA_GRE_COLLECT_METADATA: - gre.FlowBased = true - } - } -} - -func addGretunAttrs(gre *Gretun, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - if ip := gre.Local; ip != nil { - if ip.To4() != nil { - ip = ip.To4() - } - data.AddRtAttr(nl.IFLA_GRE_LOCAL, []byte(ip)) - } - - if ip := gre.Remote; ip != nil { - if ip.To4() != nil { - ip = ip.To4() - } - data.AddRtAttr(nl.IFLA_GRE_REMOTE, []byte(ip)) - } - - if gre.IKey != 0 { - data.AddRtAttr(nl.IFLA_GRE_IKEY, htonl(gre.IKey)) - gre.IFlags |= uint16(nl.GRE_KEY) - } - - if gre.OKey != 0 { - data.AddRtAttr(nl.IFLA_GRE_OKEY, htonl(gre.OKey)) - gre.OFlags |= uint16(nl.GRE_KEY) - } - - data.AddRtAttr(nl.IFLA_GRE_IFLAGS, htons(gre.IFlags)) - data.AddRtAttr(nl.IFLA_GRE_OFLAGS, htons(gre.OFlags)) - - if gre.Link != 0 { - data.AddRtAttr(nl.IFLA_GRE_LINK, nl.Uint32Attr(gre.Link)) - } - - data.AddRtAttr(nl.IFLA_GRE_PMTUDISC, nl.Uint8Attr(gre.PMtuDisc)) - data.AddRtAttr(nl.IFLA_GRE_TTL, nl.Uint8Attr(gre.Ttl)) - data.AddRtAttr(nl.IFLA_GRE_TOS, nl.Uint8Attr(gre.Tos)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_TYPE, nl.Uint16Attr(gre.EncapType)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_FLAGS, nl.Uint16Attr(gre.EncapFlags)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_SPORT, htons(gre.EncapSport)) - data.AddRtAttr(nl.IFLA_GRE_ENCAP_DPORT, htons(gre.EncapDport)) -} - -func parseGretunData(link Link, data []syscall.NetlinkRouteAttr) { - gre := link.(*Gretun) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_GRE_IKEY: - gre.IKey = ntohl(datum.Value[0:4]) - case nl.IFLA_GRE_OKEY: - gre.OKey = ntohl(datum.Value[0:4]) - case nl.IFLA_GRE_LOCAL: - gre.Local = net.IP(datum.Value) - case nl.IFLA_GRE_REMOTE: - gre.Remote = net.IP(datum.Value) - case nl.IFLA_GRE_IFLAGS: - gre.IFlags = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_OFLAGS: - gre.OFlags = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_TTL: - gre.Ttl = uint8(datum.Value[0]) - case nl.IFLA_GRE_TOS: - gre.Tos = uint8(datum.Value[0]) - case nl.IFLA_GRE_PMTUDISC: - gre.PMtuDisc = uint8(datum.Value[0]) - case nl.IFLA_GRE_ENCAP_TYPE: - gre.EncapType = native.Uint16(datum.Value[0:2]) - case nl.IFLA_GRE_ENCAP_FLAGS: - gre.EncapFlags = native.Uint16(datum.Value[0:2]) - case nl.IFLA_GRE_ENCAP_SPORT: - gre.EncapSport = ntohs(datum.Value[0:2]) - case nl.IFLA_GRE_ENCAP_DPORT: - gre.EncapDport = ntohs(datum.Value[0:2]) - } - } -} - -func addXdpAttrs(xdp *LinkXdp, req *nl.NetlinkRequest) { - attrs := nl.NewRtAttr(unix.IFLA_XDP|unix.NLA_F_NESTED, nil) - b := make([]byte, 4) - native.PutUint32(b, uint32(xdp.Fd)) - attrs.AddRtAttr(nl.IFLA_XDP_FD, b) - if xdp.Flags != 0 { - b := make([]byte, 4) - native.PutUint32(b, xdp.Flags) - attrs.AddRtAttr(nl.IFLA_XDP_FLAGS, b) - } - req.AddData(attrs) -} - -func parseLinkXdp(data []byte) (*LinkXdp, error) { - attrs, err := nl.ParseRouteAttr(data) - if err != nil { - return nil, err - } - xdp := &LinkXdp{} - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.IFLA_XDP_FD: - xdp.Fd = int(native.Uint32(attr.Value[0:4])) - case nl.IFLA_XDP_ATTACHED: - xdp.AttachMode = uint32(attr.Value[0]) - xdp.Attached = xdp.AttachMode != 0 - case nl.IFLA_XDP_FLAGS: - xdp.Flags = native.Uint32(attr.Value[0:4]) - case nl.IFLA_XDP_PROG_ID: - xdp.ProgId = native.Uint32(attr.Value[0:4]) - } - } - return xdp, nil -} - -func addIptunAttrs(iptun *Iptun, linkInfo *nl.RtAttr) { - if iptun.FlowBased { - // In flow based mode, no other attributes need to be configured - linkInfo.AddRtAttr(nl.IFLA_IPTUN_COLLECT_METADATA, boolAttr(iptun.FlowBased)) - return - } - - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - ip := iptun.Local.To4() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) - } - - ip = iptun.Remote.To4() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) - } - - if iptun.Link != 0 { - data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(iptun.Link)) - } - data.AddRtAttr(nl.IFLA_IPTUN_PMTUDISC, nl.Uint8Attr(iptun.PMtuDisc)) - data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(iptun.Ttl)) - data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(iptun.Tos)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_TYPE, nl.Uint16Attr(iptun.EncapType)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_FLAGS, nl.Uint16Attr(iptun.EncapFlags)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_SPORT, htons(iptun.EncapSport)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_DPORT, htons(iptun.EncapDport)) -} - -func parseIptunData(link Link, data []syscall.NetlinkRouteAttr) { - iptun := link.(*Iptun) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_IPTUN_LOCAL: - iptun.Local = net.IP(datum.Value[0:4]) - case nl.IFLA_IPTUN_REMOTE: - iptun.Remote = net.IP(datum.Value[0:4]) - case nl.IFLA_IPTUN_TTL: - iptun.Ttl = uint8(datum.Value[0]) - case nl.IFLA_IPTUN_TOS: - iptun.Tos = uint8(datum.Value[0]) - case nl.IFLA_IPTUN_PMTUDISC: - iptun.PMtuDisc = uint8(datum.Value[0]) - case nl.IFLA_IPTUN_ENCAP_SPORT: - iptun.EncapSport = ntohs(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_DPORT: - iptun.EncapDport = ntohs(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_TYPE: - iptun.EncapType = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_FLAGS: - iptun.EncapFlags = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_COLLECT_METADATA: - iptun.FlowBased = true - } - } -} - -func addIp6tnlAttrs(ip6tnl *Ip6tnl, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - if ip6tnl.Link != 0 { - data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(ip6tnl.Link)) - } - - ip := ip6tnl.Local.To16() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) - } - - ip = ip6tnl.Remote.To16() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) - } - - data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(ip6tnl.Ttl)) - data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(ip6tnl.Tos)) - data.AddRtAttr(nl.IFLA_IPTUN_FLAGS, nl.Uint32Attr(ip6tnl.Flags)) - data.AddRtAttr(nl.IFLA_IPTUN_PROTO, nl.Uint8Attr(ip6tnl.Proto)) - data.AddRtAttr(nl.IFLA_IPTUN_FLOWINFO, nl.Uint32Attr(ip6tnl.FlowInfo)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_LIMIT, nl.Uint8Attr(ip6tnl.EncapLimit)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_TYPE, nl.Uint16Attr(ip6tnl.EncapType)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_FLAGS, nl.Uint16Attr(ip6tnl.EncapFlags)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_SPORT, htons(ip6tnl.EncapSport)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_DPORT, htons(ip6tnl.EncapDport)) -} - -func parseIp6tnlData(link Link, data []syscall.NetlinkRouteAttr) { - ip6tnl := link.(*Ip6tnl) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_IPTUN_LOCAL: - ip6tnl.Local = net.IP(datum.Value[:16]) - case nl.IFLA_IPTUN_REMOTE: - ip6tnl.Remote = net.IP(datum.Value[:16]) - case nl.IFLA_IPTUN_TTL: - ip6tnl.Ttl = datum.Value[0] - case nl.IFLA_IPTUN_TOS: - ip6tnl.Tos = datum.Value[0] - case nl.IFLA_IPTUN_FLAGS: - ip6tnl.Flags = native.Uint32(datum.Value[:4]) - case nl.IFLA_IPTUN_PROTO: - ip6tnl.Proto = datum.Value[0] - case nl.IFLA_IPTUN_FLOWINFO: - ip6tnl.FlowInfo = native.Uint32(datum.Value[:4]) - case nl.IFLA_IPTUN_ENCAP_LIMIT: - ip6tnl.EncapLimit = datum.Value[0] - case nl.IFLA_IPTUN_ENCAP_TYPE: - ip6tnl.EncapType = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_FLAGS: - ip6tnl.EncapFlags = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_SPORT: - ip6tnl.EncapSport = ntohs(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_DPORT: - ip6tnl.EncapDport = ntohs(datum.Value[0:2]) - } - } -} - -func addSittunAttrs(sittun *Sittun, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - if sittun.Link != 0 { - data.AddRtAttr(nl.IFLA_IPTUN_LINK, nl.Uint32Attr(sittun.Link)) - } - - ip := sittun.Local.To4() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_LOCAL, []byte(ip)) - } - - ip = sittun.Remote.To4() - if ip != nil { - data.AddRtAttr(nl.IFLA_IPTUN_REMOTE, []byte(ip)) - } - - if sittun.Ttl > 0 { - // Would otherwise fail on 3.10 kernel - data.AddRtAttr(nl.IFLA_IPTUN_TTL, nl.Uint8Attr(sittun.Ttl)) - } - - data.AddRtAttr(nl.IFLA_IPTUN_PROTO, nl.Uint8Attr(sittun.Proto)) - data.AddRtAttr(nl.IFLA_IPTUN_TOS, nl.Uint8Attr(sittun.Tos)) - data.AddRtAttr(nl.IFLA_IPTUN_PMTUDISC, nl.Uint8Attr(sittun.PMtuDisc)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_LIMIT, nl.Uint8Attr(sittun.EncapLimit)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_TYPE, nl.Uint16Attr(sittun.EncapType)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_FLAGS, nl.Uint16Attr(sittun.EncapFlags)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_SPORT, htons(sittun.EncapSport)) - data.AddRtAttr(nl.IFLA_IPTUN_ENCAP_DPORT, htons(sittun.EncapDport)) -} - -func parseSittunData(link Link, data []syscall.NetlinkRouteAttr) { - sittun := link.(*Sittun) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_IPTUN_LOCAL: - sittun.Local = net.IP(datum.Value[0:4]) - case nl.IFLA_IPTUN_REMOTE: - sittun.Remote = net.IP(datum.Value[0:4]) - case nl.IFLA_IPTUN_TTL: - sittun.Ttl = datum.Value[0] - case nl.IFLA_IPTUN_TOS: - sittun.Tos = datum.Value[0] - case nl.IFLA_IPTUN_PMTUDISC: - sittun.PMtuDisc = datum.Value[0] - case nl.IFLA_IPTUN_PROTO: - sittun.Proto = datum.Value[0] - case nl.IFLA_IPTUN_ENCAP_TYPE: - sittun.EncapType = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_FLAGS: - sittun.EncapFlags = native.Uint16(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_SPORT: - sittun.EncapSport = ntohs(datum.Value[0:2]) - case nl.IFLA_IPTUN_ENCAP_DPORT: - sittun.EncapDport = ntohs(datum.Value[0:2]) - } - } -} - -func addVtiAttrs(vti *Vti, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - - family := FAMILY_V4 - if vti.Local.To4() == nil { - family = FAMILY_V6 - } - - var ip net.IP - - if family == FAMILY_V4 { - ip = vti.Local.To4() - } else { - ip = vti.Local - } - if ip != nil { - data.AddRtAttr(nl.IFLA_VTI_LOCAL, []byte(ip)) - } - - if family == FAMILY_V4 { - ip = vti.Remote.To4() - } else { - ip = vti.Remote - } - if ip != nil { - data.AddRtAttr(nl.IFLA_VTI_REMOTE, []byte(ip)) - } - - if vti.Link != 0 { - data.AddRtAttr(nl.IFLA_VTI_LINK, nl.Uint32Attr(vti.Link)) - } - - data.AddRtAttr(nl.IFLA_VTI_IKEY, htonl(vti.IKey)) - data.AddRtAttr(nl.IFLA_VTI_OKEY, htonl(vti.OKey)) -} - -func parseVtiData(link Link, data []syscall.NetlinkRouteAttr) { - vti := link.(*Vti) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_VTI_LOCAL: - vti.Local = net.IP(datum.Value) - case nl.IFLA_VTI_REMOTE: - vti.Remote = net.IP(datum.Value) - case nl.IFLA_VTI_IKEY: - vti.IKey = ntohl(datum.Value[0:4]) - case nl.IFLA_VTI_OKEY: - vti.OKey = ntohl(datum.Value[0:4]) - } - } -} - -func addVrfAttrs(vrf *Vrf, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - b := make([]byte, 4) - native.PutUint32(b, uint32(vrf.Table)) - data.AddRtAttr(nl.IFLA_VRF_TABLE, b) -} - -func parseVrfData(link Link, data []syscall.NetlinkRouteAttr) { - vrf := link.(*Vrf) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_VRF_TABLE: - vrf.Table = native.Uint32(datum.Value[0:4]) - } - } -} - -func addBridgeAttrs(bridge *Bridge, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - if bridge.MulticastSnooping != nil { - data.AddRtAttr(nl.IFLA_BR_MCAST_SNOOPING, boolToByte(*bridge.MulticastSnooping)) - } - if bridge.AgeingTime != nil { - data.AddRtAttr(nl.IFLA_BR_AGEING_TIME, nl.Uint32Attr(*bridge.AgeingTime)) - } - if bridge.HelloTime != nil { - data.AddRtAttr(nl.IFLA_BR_HELLO_TIME, nl.Uint32Attr(*bridge.HelloTime)) - } - if bridge.VlanFiltering != nil { - data.AddRtAttr(nl.IFLA_BR_VLAN_FILTERING, boolToByte(*bridge.VlanFiltering)) - } -} - -func parseBridgeData(bridge Link, data []syscall.NetlinkRouteAttr) { - br := bridge.(*Bridge) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_BR_AGEING_TIME: - ageingTime := native.Uint32(datum.Value[0:4]) - br.AgeingTime = &ageingTime - case nl.IFLA_BR_HELLO_TIME: - helloTime := native.Uint32(datum.Value[0:4]) - br.HelloTime = &helloTime - case nl.IFLA_BR_MCAST_SNOOPING: - mcastSnooping := datum.Value[0] == 1 - br.MulticastSnooping = &mcastSnooping - case nl.IFLA_BR_VLAN_FILTERING: - vlanFiltering := datum.Value[0] == 1 - br.VlanFiltering = &vlanFiltering - } - } -} - -func addGTPAttrs(gtp *GTP, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_GTP_FD0, nl.Uint32Attr(uint32(gtp.FD0))) - data.AddRtAttr(nl.IFLA_GTP_FD1, nl.Uint32Attr(uint32(gtp.FD1))) - data.AddRtAttr(nl.IFLA_GTP_PDP_HASHSIZE, nl.Uint32Attr(131072)) - if gtp.Role != nl.GTP_ROLE_GGSN { - data.AddRtAttr(nl.IFLA_GTP_ROLE, nl.Uint32Attr(uint32(gtp.Role))) - } -} - -func parseGTPData(link Link, data []syscall.NetlinkRouteAttr) { - gtp := link.(*GTP) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_GTP_FD0: - gtp.FD0 = int(native.Uint32(datum.Value)) - case nl.IFLA_GTP_FD1: - gtp.FD1 = int(native.Uint32(datum.Value)) - case nl.IFLA_GTP_PDP_HASHSIZE: - gtp.PDPHashsize = int(native.Uint32(datum.Value)) - case nl.IFLA_GTP_ROLE: - gtp.Role = int(native.Uint32(datum.Value)) - } - } -} - -func parseVfInfoList(data []syscall.NetlinkRouteAttr) ([]VfInfo, error) { - var vfs []VfInfo - - for i, element := range data { - if element.Attr.Type != nl.IFLA_VF_INFO { - return nil, fmt.Errorf("Incorrect element type in vf info list: %d", element.Attr.Type) - } - vfAttrs, err := nl.ParseRouteAttr(element.Value) - if err != nil { - return nil, err - } - vfs = append(vfs, parseVfInfo(vfAttrs, i)) - } - return vfs, nil -} - -func parseVfInfo(data []syscall.NetlinkRouteAttr, id int) VfInfo { - vf := VfInfo{ID: id} - for _, element := range data { - switch element.Attr.Type { - case nl.IFLA_VF_MAC: - mac := nl.DeserializeVfMac(element.Value[:]) - vf.Mac = mac.Mac[:6] - case nl.IFLA_VF_VLAN: - vl := nl.DeserializeVfVlan(element.Value[:]) - vf.Vlan = int(vl.Vlan) - vf.Qos = int(vl.Qos) - case nl.IFLA_VF_TX_RATE: - txr := nl.DeserializeVfTxRate(element.Value[:]) - vf.TxRate = int(txr.Rate) - case nl.IFLA_VF_SPOOFCHK: - sp := nl.DeserializeVfSpoofchk(element.Value[:]) - vf.Spoofchk = sp.Setting != 0 - case nl.IFLA_VF_LINK_STATE: - ls := nl.DeserializeVfLinkState(element.Value[:]) - vf.LinkState = ls.LinkState - case nl.IFLA_VF_RATE: - vfr := nl.DeserializeVfRate(element.Value[:]) - vf.MaxTxRate = vfr.MaxTxRate - vf.MinTxRate = vfr.MinTxRate - case nl.IFLA_VF_STATS: - vfstats := nl.DeserializeVfStats(element.Value[:]) - vf.RxPackets = vfstats.RxPackets - vf.TxPackets = vfstats.TxPackets - vf.RxBytes = vfstats.RxBytes - vf.TxBytes = vfstats.TxBytes - vf.Multicast = vfstats.Multicast - vf.Broadcast = vfstats.Broadcast - vf.RxDropped = vfstats.RxDropped - vf.TxDropped = vfstats.TxDropped - - case nl.IFLA_VF_RSS_QUERY_EN: - result := nl.DeserializeVfRssQueryEn(element.Value) - vf.RssQuery = result.Setting - - case nl.IFLA_VF_TRUST: - result := nl.DeserializeVfTrust(element.Value) - vf.Trust = result.Setting - } - } - return vf -} - -func addXfrmiAttrs(xfrmi *Xfrmi, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_XFRM_LINK, nl.Uint32Attr(uint32(xfrmi.ParentIndex))) - data.AddRtAttr(nl.IFLA_XFRM_IF_ID, nl.Uint32Attr(xfrmi.Ifid)) - -} - -func parseXfrmiData(link Link, data []syscall.NetlinkRouteAttr) { - xfrmi := link.(*Xfrmi) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_XFRM_LINK: - xfrmi.ParentIndex = int(native.Uint32(datum.Value)) - case nl.IFLA_XFRM_IF_ID: - xfrmi.Ifid = native.Uint32(datum.Value) - } - } -} - -// LinkSetBondSlave add slave to bond link via ioctl interface. -func LinkSetBondSlave(link Link, master *Bond) error { - fd, err := getSocketUDP() - if err != nil { - return err - } - defer syscall.Close(fd) - - ifreq := newIocltSlaveReq(link.Attrs().Name, master.Attrs().Name) - - _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), unix.SIOCBONDENSLAVE, uintptr(unsafe.Pointer(ifreq))) - if errno != 0 { - return fmt.Errorf("Failed to enslave %q to %q, errno=%v", link.Attrs().Name, master.Attrs().Name, errno) - } - return nil -} - -// LinkSetBondSlaveQueueId modify bond slave queue-id. -func (h *Handle) LinkSetBondSlaveQueueId(link Link, queueId uint16) error { - base := link.Attrs() - h.ensureIndex(base) - req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK) - - msg := nl.NewIfInfomsg(unix.AF_UNSPEC) - msg.Index = int32(base.Index) - req.AddData(msg) - - linkInfo := nl.NewRtAttr(unix.IFLA_LINKINFO, nil) - data := linkInfo.AddRtAttr(nl.IFLA_INFO_SLAVE_DATA, nil) - data.AddRtAttr(nl.IFLA_BOND_SLAVE_QUEUE_ID, nl.Uint16Attr(queueId)) - - req.AddData(linkInfo) - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// LinkSetBondSlaveQueueId modify bond slave queue-id. -func LinkSetBondSlaveQueueId(link Link, queueId uint16) error { - return pkgHandle.LinkSetBondSlaveQueueId(link, queueId) -} - -func vethStatsSerialize(stats ethtoolStats) ([]byte, error) { - statsSize := int(unsafe.Sizeof(stats)) + int(stats.nStats)*int(unsafe.Sizeof(uint64(0))) - b := make([]byte, 0, statsSize) - buf := bytes.NewBuffer(b) - err := binary.Write(buf, nl.NativeEndian(), stats) - return buf.Bytes()[:statsSize], err -} - -type vethEthtoolStats struct { - Cmd uint32 - NStats uint32 - Peer uint64 - // Newer kernels have XDP stats in here, but we only care - // to extract the peer ifindex here. -} - -func vethStatsDeserialize(b []byte) (vethEthtoolStats, error) { - var stats = vethEthtoolStats{} - err := binary.Read(bytes.NewReader(b), nl.NativeEndian(), &stats) - return stats, err -} - -// VethPeerIndex get veth peer index. -func VethPeerIndex(link *Veth) (int, error) { - fd, err := getSocketUDP() - if err != nil { - return -1, err - } - defer syscall.Close(fd) - - ifreq, sSet := newIocltStringSetReq(link.Name) - _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq))) - if errno != 0 { - return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno) - } - - stats := ethtoolStats{ - cmd: ETHTOOL_GSTATS, - nStats: sSet.data[0], - } - - buffer, err := vethStatsSerialize(stats) - if err != nil { - return -1, err - } - - ifreq.Data = uintptr(unsafe.Pointer(&buffer[0])) - _, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq))) - if errno != 0 { - return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno) - } - - vstats, err := vethStatsDeserialize(buffer) - if err != nil { - return -1, err - } - - return int(vstats.Peer), nil -} - -func parseTuntapData(link Link, data []syscall.NetlinkRouteAttr) { - tuntap := link.(*Tuntap) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_TUN_OWNER: - tuntap.Owner = native.Uint32(datum.Value) - case nl.IFLA_TUN_GROUP: - tuntap.Group = native.Uint32(datum.Value) - case nl.IFLA_TUN_TYPE: - tuntap.Mode = TuntapMode(uint8(datum.Value[0])) - case nl.IFLA_TUN_PERSIST: - tuntap.NonPersist = false - if uint8(datum.Value[0]) == 0 { - tuntap.NonPersist = true - } - } - } -} - -func parseIPoIBData(link Link, data []syscall.NetlinkRouteAttr) { - ipoib := link.(*IPoIB) - for _, datum := range data { - switch datum.Attr.Type { - case nl.IFLA_IPOIB_PKEY: - ipoib.Pkey = uint16(native.Uint16(datum.Value)) - case nl.IFLA_IPOIB_MODE: - ipoib.Mode = IPoIBMode(native.Uint16(datum.Value)) - case nl.IFLA_IPOIB_UMCAST: - ipoib.Umcast = uint16(native.Uint16(datum.Value)) - } - } -} - -func addIPoIBAttrs(ipoib *IPoIB, linkInfo *nl.RtAttr) { - data := linkInfo.AddRtAttr(nl.IFLA_INFO_DATA, nil) - data.AddRtAttr(nl.IFLA_IPOIB_PKEY, nl.Uint16Attr(uint16(ipoib.Pkey))) - data.AddRtAttr(nl.IFLA_IPOIB_MODE, nl.Uint16Attr(uint16(ipoib.Mode))) - data.AddRtAttr(nl.IFLA_IPOIB_UMCAST, nl.Uint16Attr(uint16(ipoib.Umcast))) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go b/examples/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go deleted file mode 100644 index 310bd33..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/link_tuntap_linux.go +++ /dev/null @@ -1,14 +0,0 @@ -package netlink - -// ideally golang.org/x/sys/unix would define IfReq but it only has -// IFNAMSIZ, hence this minimalistic implementation -const ( - SizeOfIfReq = 40 - IFNAMSIZ = 16 -) - -type ifReq struct { - Name [IFNAMSIZ]byte - Flags uint16 - pad [SizeOfIfReq - IFNAMSIZ - 2]byte -} diff --git a/examples/vendor/github.com/vishvananda/netlink/neigh.go b/examples/vendor/github.com/vishvananda/netlink/neigh.go deleted file mode 100644 index 379e565..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/neigh.go +++ /dev/null @@ -1,32 +0,0 @@ -package netlink - -import ( - "fmt" - "net" -) - -// Neigh represents a link layer neighbor from netlink. -type Neigh struct { - LinkIndex int - Family int - State int - Type int - Flags int - IP net.IP - HardwareAddr net.HardwareAddr - LLIPAddr net.IP //Used in the case of NHRP - Vlan int - VNI int - MasterIndex int -} - -// String returns $ip/$hwaddr $label -func (neigh *Neigh) String() string { - return fmt.Sprintf("%s %s", neigh.IP, neigh.HardwareAddr) -} - -// NeighUpdate is sent when a neighbor changes - type is RTM_NEWNEIGH or RTM_DELNEIGH. -type NeighUpdate struct { - Type uint16 - Neigh -} diff --git a/examples/vendor/github.com/vishvananda/netlink/neigh_linux.go b/examples/vendor/github.com/vishvananda/netlink/neigh_linux.go deleted file mode 100644 index fb220d1..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/neigh_linux.go +++ /dev/null @@ -1,434 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "syscall" - "unsafe" - - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -const ( - NDA_UNSPEC = iota - NDA_DST - NDA_LLADDR - NDA_CACHEINFO - NDA_PROBES - NDA_VLAN - NDA_PORT - NDA_VNI - NDA_IFINDEX - NDA_MASTER - NDA_LINK_NETNSID - NDA_SRC_VNI - NDA_MAX = NDA_SRC_VNI -) - -// Neighbor Cache Entry States. -const ( - NUD_NONE = 0x00 - NUD_INCOMPLETE = 0x01 - NUD_REACHABLE = 0x02 - NUD_STALE = 0x04 - NUD_DELAY = 0x08 - NUD_PROBE = 0x10 - NUD_FAILED = 0x20 - NUD_NOARP = 0x40 - NUD_PERMANENT = 0x80 -) - -// Neighbor Flags -const ( - NTF_USE = 0x01 - NTF_SELF = 0x02 - NTF_MASTER = 0x04 - NTF_PROXY = 0x08 - NTF_ROUTER = 0x80 -) - -// Ndmsg is for adding, removing or receiving information about a neighbor table entry -type Ndmsg struct { - Family uint8 - Index uint32 - State uint16 - Flags uint8 - Type uint8 -} - -func deserializeNdmsg(b []byte) *Ndmsg { - var dummy Ndmsg - return (*Ndmsg)(unsafe.Pointer(&b[0:unsafe.Sizeof(dummy)][0])) -} - -func (msg *Ndmsg) Serialize() []byte { - return (*(*[unsafe.Sizeof(*msg)]byte)(unsafe.Pointer(msg)))[:] -} - -func (msg *Ndmsg) Len() int { - return int(unsafe.Sizeof(*msg)) -} - -// NeighAdd will add an IP to MAC mapping to the ARP table -// Equivalent to: `ip neigh add ....` -func NeighAdd(neigh *Neigh) error { - return pkgHandle.NeighAdd(neigh) -} - -// NeighAdd will add an IP to MAC mapping to the ARP table -// Equivalent to: `ip neigh add ....` -func (h *Handle) NeighAdd(neigh *Neigh) error { - return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_EXCL) -} - -// NeighSet will add or replace an IP to MAC mapping to the ARP table -// Equivalent to: `ip neigh replace....` -func NeighSet(neigh *Neigh) error { - return pkgHandle.NeighSet(neigh) -} - -// NeighSet will add or replace an IP to MAC mapping to the ARP table -// Equivalent to: `ip neigh replace....` -func (h *Handle) NeighSet(neigh *Neigh) error { - return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_REPLACE) -} - -// NeighAppend will append an entry to FDB -// Equivalent to: `bridge fdb append...` -func NeighAppend(neigh *Neigh) error { - return pkgHandle.NeighAppend(neigh) -} - -// NeighAppend will append an entry to FDB -// Equivalent to: `bridge fdb append...` -func (h *Handle) NeighAppend(neigh *Neigh) error { - return h.neighAdd(neigh, unix.NLM_F_CREATE|unix.NLM_F_APPEND) -} - -// NeighAppend will append an entry to FDB -// Equivalent to: `bridge fdb append...` -func neighAdd(neigh *Neigh, mode int) error { - return pkgHandle.neighAdd(neigh, mode) -} - -// NeighAppend will append an entry to FDB -// Equivalent to: `bridge fdb append...` -func (h *Handle) neighAdd(neigh *Neigh, mode int) error { - req := h.newNetlinkRequest(unix.RTM_NEWNEIGH, mode|unix.NLM_F_ACK) - return neighHandle(neigh, req) -} - -// NeighDel will delete an IP address from a link device. -// Equivalent to: `ip addr del $addr dev $link` -func NeighDel(neigh *Neigh) error { - return pkgHandle.NeighDel(neigh) -} - -// NeighDel will delete an IP address from a link device. -// Equivalent to: `ip addr del $addr dev $link` -func (h *Handle) NeighDel(neigh *Neigh) error { - req := h.newNetlinkRequest(unix.RTM_DELNEIGH, unix.NLM_F_ACK) - return neighHandle(neigh, req) -} - -func neighHandle(neigh *Neigh, req *nl.NetlinkRequest) error { - var family int - - if neigh.Family > 0 { - family = neigh.Family - } else { - family = nl.GetIPFamily(neigh.IP) - } - - msg := Ndmsg{ - Family: uint8(family), - Index: uint32(neigh.LinkIndex), - State: uint16(neigh.State), - Type: uint8(neigh.Type), - Flags: uint8(neigh.Flags), - } - req.AddData(&msg) - - ipData := neigh.IP.To4() - if ipData == nil { - ipData = neigh.IP.To16() - } - - dstData := nl.NewRtAttr(NDA_DST, ipData) - req.AddData(dstData) - - if neigh.LLIPAddr != nil { - llIPData := nl.NewRtAttr(NDA_LLADDR, neigh.LLIPAddr.To4()) - req.AddData(llIPData) - } else if neigh.Flags != NTF_PROXY || neigh.HardwareAddr != nil { - hwData := nl.NewRtAttr(NDA_LLADDR, []byte(neigh.HardwareAddr)) - req.AddData(hwData) - } - - if neigh.Vlan != 0 { - vlanData := nl.NewRtAttr(NDA_VLAN, nl.Uint16Attr(uint16(neigh.Vlan))) - req.AddData(vlanData) - } - - if neigh.VNI != 0 { - vniData := nl.NewRtAttr(NDA_VNI, nl.Uint32Attr(uint32(neigh.VNI))) - req.AddData(vniData) - } - - if neigh.MasterIndex != 0 { - masterData := nl.NewRtAttr(NDA_MASTER, nl.Uint32Attr(uint32(neigh.MasterIndex))) - req.AddData(masterData) - } - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// NeighList returns a list of IP-MAC mappings in the system (ARP table). -// Equivalent to: `ip neighbor show`. -// The list can be filtered by link and ip family. -func NeighList(linkIndex, family int) ([]Neigh, error) { - return pkgHandle.NeighList(linkIndex, family) -} - -// NeighProxyList returns a list of neighbor proxies in the system. -// Equivalent to: `ip neighbor show proxy`. -// The list can be filtered by link and ip family. -func NeighProxyList(linkIndex, family int) ([]Neigh, error) { - return pkgHandle.NeighProxyList(linkIndex, family) -} - -// NeighList returns a list of IP-MAC mappings in the system (ARP table). -// Equivalent to: `ip neighbor show`. -// The list can be filtered by link and ip family. -func (h *Handle) NeighList(linkIndex, family int) ([]Neigh, error) { - return h.NeighListExecute(Ndmsg{ - Family: uint8(family), - Index: uint32(linkIndex), - }) -} - -// NeighProxyList returns a list of neighbor proxies in the system. -// Equivalent to: `ip neighbor show proxy`. -// The list can be filtered by link, ip family. -func (h *Handle) NeighProxyList(linkIndex, family int) ([]Neigh, error) { - return h.NeighListExecute(Ndmsg{ - Family: uint8(family), - Index: uint32(linkIndex), - Flags: NTF_PROXY, - }) -} - -// NeighListExecute returns a list of neighbour entries filtered by link, ip family, flag and state. -func NeighListExecute(msg Ndmsg) ([]Neigh, error) { - return pkgHandle.NeighListExecute(msg) -} - -// NeighListExecute returns a list of neighbour entries filtered by link, ip family, flag and state. -func (h *Handle) NeighListExecute(msg Ndmsg) ([]Neigh, error) { - req := h.newNetlinkRequest(unix.RTM_GETNEIGH, unix.NLM_F_DUMP) - req.AddData(&msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNEIGH) - if err != nil { - return nil, err - } - - var res []Neigh - for _, m := range msgs { - ndm := deserializeNdmsg(m) - if msg.Index != 0 && ndm.Index != msg.Index { - // Ignore messages from other interfaces - continue - } - if msg.Family != 0 && ndm.Family != msg.Family { - continue - } - if msg.State != 0 && ndm.State != msg.State { - continue - } - if msg.Type != 0 && ndm.Type != msg.Type { - continue - } - if msg.Flags != 0 && ndm.Flags != msg.Flags { - continue - } - - neigh, err := NeighDeserialize(m) - if err != nil { - continue - } - - res = append(res, *neigh) - } - - return res, nil -} - -func NeighDeserialize(m []byte) (*Neigh, error) { - msg := deserializeNdmsg(m) - - neigh := Neigh{ - LinkIndex: int(msg.Index), - Family: int(msg.Family), - State: int(msg.State), - Type: int(msg.Type), - Flags: int(msg.Flags), - } - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - for _, attr := range attrs { - switch attr.Attr.Type { - case NDA_DST: - neigh.IP = net.IP(attr.Value) - case NDA_LLADDR: - // BUG: Is this a bug in the netlink library? - // #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len)) - // #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0)) - attrLen := attr.Attr.Len - unix.SizeofRtAttr - if attrLen == 4 { - neigh.LLIPAddr = net.IP(attr.Value) - } else if attrLen == 16 { - // Can be IPv6 or FireWire HWAddr - link, err := LinkByIndex(neigh.LinkIndex) - if err == nil && link.Attrs().EncapType == "tunnel6" { - neigh.IP = net.IP(attr.Value) - } else { - neigh.HardwareAddr = net.HardwareAddr(attr.Value) - } - } else { - neigh.HardwareAddr = net.HardwareAddr(attr.Value) - } - case NDA_VLAN: - neigh.Vlan = int(native.Uint16(attr.Value[0:2])) - case NDA_VNI: - neigh.VNI = int(native.Uint32(attr.Value[0:4])) - case NDA_MASTER: - neigh.MasterIndex = int(native.Uint32(attr.Value[0:4])) - } - } - - return &neigh, nil -} - -// NeighSubscribe takes a chan down which notifications will be sent -// when neighbors are added or deleted. Close the 'done' chan to stop subscription. -func NeighSubscribe(ch chan<- NeighUpdate, done <-chan struct{}) error { - return neighSubscribeAt(netns.None(), netns.None(), ch, done, nil, false) -} - -// NeighSubscribeAt works like NeighSubscribe plus it allows the caller -// to choose the network namespace in which to subscribe (ns). -func NeighSubscribeAt(ns netns.NsHandle, ch chan<- NeighUpdate, done <-chan struct{}) error { - return neighSubscribeAt(ns, netns.None(), ch, done, nil, false) -} - -// NeighSubscribeOptions contains a set of options to use with -// NeighSubscribeWithOptions. -type NeighSubscribeOptions struct { - Namespace *netns.NsHandle - ErrorCallback func(error) - ListExisting bool -} - -// NeighSubscribeWithOptions work like NeighSubscribe but enable to -// provide additional options to modify the behavior. Currently, the -// namespace can be provided as well as an error callback. -func NeighSubscribeWithOptions(ch chan<- NeighUpdate, done <-chan struct{}, options NeighSubscribeOptions) error { - if options.Namespace == nil { - none := netns.None() - options.Namespace = &none - } - return neighSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting) -} - -func neighSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- NeighUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error { - s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_NEIGH) - makeRequest := func(family int) error { - req := pkgHandle.newNetlinkRequest(unix.RTM_GETNEIGH, - unix.NLM_F_DUMP) - infmsg := nl.NewIfInfomsg(family) - req.AddData(infmsg) - if err := s.Send(req); err != nil { - return err - } - return nil - } - if err != nil { - return err - } - if done != nil { - go func() { - <-done - s.Close() - }() - } - if listExisting { - if err := makeRequest(unix.AF_UNSPEC); err != nil { - return err - } - // We have to wait for NLMSG_DONE before making AF_BRIDGE request - } - go func() { - defer close(ch) - for { - msgs, from, err := s.Receive() - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - if from.Pid != nl.PidKernel { - if cberr != nil { - cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)) - } - continue - } - for _, m := range msgs { - if m.Header.Type == unix.NLMSG_DONE { - if listExisting { - // This will be called after handling AF_UNSPEC - // list request, we have to wait for NLMSG_DONE - // before making another request - if err := makeRequest(unix.AF_BRIDGE); err != nil { - if cberr != nil { - cberr(err) - } - return - } - listExisting = false - } - continue - } - if m.Header.Type == unix.NLMSG_ERROR { - native := nl.NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - if error == 0 { - continue - } - if cberr != nil { - cberr(syscall.Errno(-error)) - } - return - } - neigh, err := NeighDeserialize(m.Data) - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - ch <- NeighUpdate{Type: m.Header.Type, Neigh: *neigh} - } - } - }() - - return nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/netlink.go b/examples/vendor/github.com/vishvananda/netlink/netlink.go deleted file mode 100644 index 9cb685d..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/netlink.go +++ /dev/null @@ -1,40 +0,0 @@ -// Package netlink provides a simple library for netlink. Netlink is -// the interface a user-space program in linux uses to communicate with -// the kernel. It can be used to add and remove interfaces, set up ip -// addresses and routes, and confiugre ipsec. Netlink communication -// requires elevated privileges, so in most cases this code needs to -// be run as root. The low level primitives for netlink are contained -// in the nl subpackage. This package attempts to provide a high-level -// interface that is loosly modeled on the iproute2 cli. -package netlink - -import ( - "errors" - "net" -) - -var ( - // ErrNotImplemented is returned when a requested feature is not implemented. - ErrNotImplemented = errors.New("not implemented") -) - -// ParseIPNet parses a string in ip/net format and returns a net.IPNet. -// This is valuable because addresses in netlink are often IPNets and -// ParseCIDR returns an IPNet with the IP part set to the base IP of the -// range. -func ParseIPNet(s string) (*net.IPNet, error) { - ip, ipNet, err := net.ParseCIDR(s) - if err != nil { - return nil, err - } - ipNet.IP = ip - return ipNet, nil -} - -// NewIPNet generates an IPNet from an ip address using a netmask of 32 or 128. -func NewIPNet(ip net.IP) *net.IPNet { - if ip.To4() != nil { - return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)} - } - return &net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)} -} diff --git a/examples/vendor/github.com/vishvananda/netlink/netlink_linux.go b/examples/vendor/github.com/vishvananda/netlink/netlink_linux.go deleted file mode 100644 index a20d293..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/netlink_linux.go +++ /dev/null @@ -1,11 +0,0 @@ -package netlink - -import "github.com/vishvananda/netlink/nl" - -// Family type definitions -const ( - FAMILY_ALL = nl.FAMILY_ALL - FAMILY_V4 = nl.FAMILY_V4 - FAMILY_V6 = nl.FAMILY_V6 - FAMILY_MPLS = nl.FAMILY_MPLS -) diff --git a/examples/vendor/github.com/vishvananda/netlink/netlink_unspecified.go b/examples/vendor/github.com/vishvananda/netlink/netlink_unspecified.go deleted file mode 100644 index 71436f2..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/netlink_unspecified.go +++ /dev/null @@ -1,241 +0,0 @@ -// +build !linux - -package netlink - -import "net" - -func LinkSetUp(link Link) error { - return ErrNotImplemented -} - -func LinkSetDown(link Link) error { - return ErrNotImplemented -} - -func LinkSetMTU(link Link, mtu int) error { - return ErrNotImplemented -} - -func LinkSetMaster(link Link, master Link) error { - return ErrNotImplemented -} - -func LinkSetNsPid(link Link, nspid int) error { - return ErrNotImplemented -} - -func LinkSetNsFd(link Link, fd int) error { - return ErrNotImplemented -} - -func LinkSetName(link Link, name string) error { - return ErrNotImplemented -} - -func LinkSetAlias(link Link, name string) error { - return ErrNotImplemented -} - -func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error { - return ErrNotImplemented -} - -func LinkSetVfHardwareAddr(link Link, vf int, hwaddr net.HardwareAddr) error { - return ErrNotImplemented -} - -func LinkSetVfVlan(link Link, vf, vlan int) error { - return ErrNotImplemented -} - -func LinkSetVfVlanQos(link Link, vf, vlan, qos int) error { - return ErrNotImplemented -} - -func LinkSetVfTxRate(link Link, vf, rate int) error { - return ErrNotImplemented -} - -func LinkSetVfRate(link Link, vf, minRate, maxRate int) error { - return ErrNotImplemented -} - -func LinkSetNoMaster(link Link) error { - return ErrNotImplemented -} - -func LinkSetMasterByIndex(link Link, masterIndex int) error { - return ErrNotImplemented -} - -func LinkSetXdpFd(link Link, fd int) error { - return ErrNotImplemented -} - -func LinkSetXdpFdWithFlags(link Link, fd, flags int) error { - return ErrNotImplemented -} - -func LinkSetARPOff(link Link) error { - return ErrNotImplemented -} - -func LinkSetARPOn(link Link) error { - return ErrNotImplemented -} - -func LinkByName(name string) (Link, error) { - return nil, ErrNotImplemented -} - -func LinkByAlias(alias string) (Link, error) { - return nil, ErrNotImplemented -} - -func LinkByIndex(index int) (Link, error) { - return nil, ErrNotImplemented -} - -func LinkSetHairpin(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetGuard(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetFastLeave(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetLearning(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetRootBlock(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetFlood(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkSetTxQLen(link Link, qlen int) error { - return ErrNotImplemented -} - -func LinkAdd(link Link) error { - return ErrNotImplemented -} - -func LinkDel(link Link) error { - return ErrNotImplemented -} - -func SetHairpin(link Link, mode bool) error { - return ErrNotImplemented -} - -func SetGuard(link Link, mode bool) error { - return ErrNotImplemented -} - -func SetFastLeave(link Link, mode bool) error { - return ErrNotImplemented -} - -func SetLearning(link Link, mode bool) error { - return ErrNotImplemented -} - -func SetRootBlock(link Link, mode bool) error { - return ErrNotImplemented -} - -func SetFlood(link Link, mode bool) error { - return ErrNotImplemented -} - -func LinkList() ([]Link, error) { - return nil, ErrNotImplemented -} - -func AddrAdd(link Link, addr *Addr) error { - return ErrNotImplemented -} - -func AddrReplace(link Link, addr *Addr) error { - return ErrNotImplemented -} - -func AddrDel(link Link, addr *Addr) error { - return ErrNotImplemented -} - -func AddrList(link Link, family int) ([]Addr, error) { - return nil, ErrNotImplemented -} - -func RouteAdd(route *Route) error { - return ErrNotImplemented -} - -func RouteDel(route *Route) error { - return ErrNotImplemented -} - -func RouteList(link Link, family int) ([]Route, error) { - return nil, ErrNotImplemented -} - -func XfrmPolicyAdd(policy *XfrmPolicy) error { - return ErrNotImplemented -} - -func XfrmPolicyDel(policy *XfrmPolicy) error { - return ErrNotImplemented -} - -func XfrmPolicyList(family int) ([]XfrmPolicy, error) { - return nil, ErrNotImplemented -} - -func XfrmStateAdd(policy *XfrmState) error { - return ErrNotImplemented -} - -func XfrmStateDel(policy *XfrmState) error { - return ErrNotImplemented -} - -func XfrmStateList(family int) ([]XfrmState, error) { - return nil, ErrNotImplemented -} - -func NeighAdd(neigh *Neigh) error { - return ErrNotImplemented -} - -func NeighSet(neigh *Neigh) error { - return ErrNotImplemented -} - -func NeighAppend(neigh *Neigh) error { - return ErrNotImplemented -} - -func NeighDel(neigh *Neigh) error { - return ErrNotImplemented -} - -func NeighList(linkIndex, family int) ([]Neigh, error) { - return nil, ErrNotImplemented -} - -func NeighDeserialize(m []byte) (*Neigh, error) { - return nil, ErrNotImplemented -} - -func SocketGet(local, remote net.Addr) (*Socket, error) { - return nil, ErrNotImplemented -} diff --git a/examples/vendor/github.com/vishvananda/netlink/netns_linux.go b/examples/vendor/github.com/vishvananda/netlink/netns_linux.go deleted file mode 100644 index 77cf6f4..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/netns_linux.go +++ /dev/null @@ -1,141 +0,0 @@ -package netlink - -// Network namespace ID functions -// -// The kernel has a weird concept called the network namespace ID. -// This is different from the file reference in proc (and any bind-mounted -// namespaces, etc.) -// -// Instead, namespaces can be assigned a numeric ID at any time. Once set, -// the ID is fixed. The ID can either be set manually by the user, or -// automatically, triggered by certain kernel actions. The most common kernel -// action that triggers namespace ID creation is moving one end of a veth pair -// in to that namespace. - -import ( - "fmt" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// These can be replaced by the values from sys/unix when it is next released. -const ( - _ = iota - NETNSA_NSID - NETNSA_PID - NETNSA_FD -) - -// GetNetNsIdByPid looks up the network namespace ID for a given pid (really thread id). -// Returns -1 if the namespace does not have an ID set. -func (h *Handle) GetNetNsIdByPid(pid int) (int, error) { - return h.getNetNsId(NETNSA_PID, uint32(pid)) -} - -// GetNetNsIdByPid looks up the network namespace ID for a given pid (really thread id). -// Returns -1 if the namespace does not have an ID set. -func GetNetNsIdByPid(pid int) (int, error) { - return pkgHandle.GetNetNsIdByPid(pid) -} - -// SetNetNSIdByPid sets the ID of the network namespace for a given pid (really thread id). -// The ID can only be set for namespaces without an ID already set. -func (h *Handle) SetNetNsIdByPid(pid, nsid int) error { - return h.setNetNsId(NETNSA_PID, uint32(pid), uint32(nsid)) -} - -// SetNetNSIdByPid sets the ID of the network namespace for a given pid (really thread id). -// The ID can only be set for namespaces without an ID already set. -func SetNetNsIdByPid(pid, nsid int) error { - return pkgHandle.SetNetNsIdByPid(pid, nsid) -} - -// GetNetNsIdByFd looks up the network namespace ID for a given fd. -// fd must be an open file descriptor to a namespace file. -// Returns -1 if the namespace does not have an ID set. -func (h *Handle) GetNetNsIdByFd(fd int) (int, error) { - return h.getNetNsId(NETNSA_FD, uint32(fd)) -} - -// GetNetNsIdByFd looks up the network namespace ID for a given fd. -// fd must be an open file descriptor to a namespace file. -// Returns -1 if the namespace does not have an ID set. -func GetNetNsIdByFd(fd int) (int, error) { - return pkgHandle.GetNetNsIdByFd(fd) -} - -// SetNetNSIdByFd sets the ID of the network namespace for a given fd. -// fd must be an open file descriptor to a namespace file. -// The ID can only be set for namespaces without an ID already set. -func (h *Handle) SetNetNsIdByFd(fd, nsid int) error { - return h.setNetNsId(NETNSA_FD, uint32(fd), uint32(nsid)) -} - -// SetNetNSIdByFd sets the ID of the network namespace for a given fd. -// fd must be an open file descriptor to a namespace file. -// The ID can only be set for namespaces without an ID already set. -func SetNetNsIdByFd(fd, nsid int) error { - return pkgHandle.SetNetNsIdByFd(fd, nsid) -} - -// getNetNsId requests the netnsid for a given type-val pair -// type should be either NETNSA_PID or NETNSA_FD -func (h *Handle) getNetNsId(attrType int, val uint32) (int, error) { - req := h.newNetlinkRequest(unix.RTM_GETNSID, unix.NLM_F_REQUEST) - - rtgen := nl.NewRtGenMsg() - req.AddData(rtgen) - - b := make([]byte, 4, 4) - native.PutUint32(b, val) - attr := nl.NewRtAttr(attrType, b) - req.AddData(attr) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID) - - if err != nil { - return 0, err - } - - for _, m := range msgs { - msg := nl.DeserializeRtGenMsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return 0, err - } - - for _, attr := range attrs { - switch attr.Attr.Type { - case NETNSA_NSID: - return int(int32(native.Uint32(attr.Value))), nil - } - } - } - - return 0, fmt.Errorf("unexpected empty result") -} - -// setNetNsId sets the netnsid for a given type-val pair -// type should be either NETNSA_PID or NETNSA_FD -// The ID can only be set for namespaces without an ID already set -func (h *Handle) setNetNsId(attrType int, val uint32, newnsid uint32) error { - req := h.newNetlinkRequest(unix.RTM_NEWNSID, unix.NLM_F_REQUEST|unix.NLM_F_ACK) - - rtgen := nl.NewRtGenMsg() - req.AddData(rtgen) - - b := make([]byte, 4, 4) - native.PutUint32(b, val) - attr := nl.NewRtAttr(attrType, b) - req.AddData(attr) - - b1 := make([]byte, 4, 4) - native.PutUint32(b1, newnsid) - attr1 := nl.NewRtAttr(NETNSA_NSID, b1) - req.AddData(attr1) - - _, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID) - return err -} diff --git a/examples/vendor/github.com/vishvananda/netlink/netns_unspecified.go b/examples/vendor/github.com/vishvananda/netlink/netns_unspecified.go deleted file mode 100644 index 5c5899e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/netns_unspecified.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !linux - -package netlink - -func GetNetNsIdByPid(pid int) (int, error) { - return 0, ErrNotImplemented -} - -func SetNetNsIdByPid(pid, nsid int) error { - return ErrNotImplemented -} - -func GetNetNsIdByFd(fd int) (int, error) { - return 0, ErrNotImplemented -} - -func SetNetNsIdByFd(fd, nsid int) error { - return ErrNotImplemented -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/addr_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/addr_linux.go deleted file mode 100644 index 6bea4ed..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/addr_linux.go +++ /dev/null @@ -1,71 +0,0 @@ -package nl - -import ( - "unsafe" - - "golang.org/x/sys/unix" -) - -type IfAddrmsg struct { - unix.IfAddrmsg -} - -func NewIfAddrmsg(family int) *IfAddrmsg { - return &IfAddrmsg{ - IfAddrmsg: unix.IfAddrmsg{ - Family: uint8(family), - }, - } -} - -// struct ifaddrmsg { -// __u8 ifa_family; -// __u8 ifa_prefixlen; /* The prefix length */ -// __u8 ifa_flags; /* Flags */ -// __u8 ifa_scope; /* Address scope */ -// __u32 ifa_index; /* Link index */ -// }; - -// type IfAddrmsg struct { -// Family uint8 -// Prefixlen uint8 -// Flags uint8 -// Scope uint8 -// Index uint32 -// } -// SizeofIfAddrmsg = 0x8 - -func DeserializeIfAddrmsg(b []byte) *IfAddrmsg { - return (*IfAddrmsg)(unsafe.Pointer(&b[0:unix.SizeofIfAddrmsg][0])) -} - -func (msg *IfAddrmsg) Serialize() []byte { - return (*(*[unix.SizeofIfAddrmsg]byte)(unsafe.Pointer(msg)))[:] -} - -func (msg *IfAddrmsg) Len() int { - return unix.SizeofIfAddrmsg -} - -// struct ifa_cacheinfo { -// __u32 ifa_prefered; -// __u32 ifa_valid; -// __u32 cstamp; /* created timestamp, hundredths of seconds */ -// __u32 tstamp; /* updated timestamp, hundredths of seconds */ -// }; - -type IfaCacheInfo struct { - unix.IfaCacheinfo -} - -func (msg *IfaCacheInfo) Len() int { - return unix.SizeofIfaCacheinfo -} - -func DeserializeIfaCacheInfo(b []byte) *IfaCacheInfo { - return (*IfaCacheInfo)(unsafe.Pointer(&b[0:unix.SizeofIfaCacheinfo][0])) -} - -func (msg *IfaCacheInfo) Serialize() []byte { - return (*(*[unix.SizeofIfaCacheinfo]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/bridge_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/bridge_linux.go deleted file mode 100644 index 34e78ba..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/bridge_linux.go +++ /dev/null @@ -1,74 +0,0 @@ -package nl - -import ( - "fmt" - "unsafe" -) - -const ( - SizeofBridgeVlanInfo = 0x04 -) - -/* Bridge Flags */ -const ( - BRIDGE_FLAGS_MASTER = iota + 1 /* Bridge command to/from master */ - BRIDGE_FLAGS_SELF /* Bridge command to/from lowerdev */ -) - -/* Bridge management nested attributes - * [IFLA_AF_SPEC] = { - * [IFLA_BRIDGE_FLAGS] - * [IFLA_BRIDGE_MODE] - * [IFLA_BRIDGE_VLAN_INFO] - * } - */ -const ( - IFLA_BRIDGE_FLAGS = iota - IFLA_BRIDGE_MODE - IFLA_BRIDGE_VLAN_INFO -) - -const ( - BRIDGE_VLAN_INFO_MASTER = 1 << iota - BRIDGE_VLAN_INFO_PVID - BRIDGE_VLAN_INFO_UNTAGGED - BRIDGE_VLAN_INFO_RANGE_BEGIN - BRIDGE_VLAN_INFO_RANGE_END -) - -// struct bridge_vlan_info { -// __u16 flags; -// __u16 vid; -// }; - -type BridgeVlanInfo struct { - Flags uint16 - Vid uint16 -} - -func (b *BridgeVlanInfo) Serialize() []byte { - return (*(*[SizeofBridgeVlanInfo]byte)(unsafe.Pointer(b)))[:] -} - -func DeserializeBridgeVlanInfo(b []byte) *BridgeVlanInfo { - return (*BridgeVlanInfo)(unsafe.Pointer(&b[0:SizeofBridgeVlanInfo][0])) -} - -func (b *BridgeVlanInfo) PortVID() bool { - return b.Flags&BRIDGE_VLAN_INFO_PVID > 0 -} - -func (b *BridgeVlanInfo) EngressUntag() bool { - return b.Flags&BRIDGE_VLAN_INFO_UNTAGGED > 0 -} - -func (b *BridgeVlanInfo) String() string { - return fmt.Sprintf("%+v", *b) -} - -/* New extended info filters for IFLA_EXT_MASK */ -const ( - RTEXT_FILTER_VF = 1 << iota - RTEXT_FILTER_BRVLAN - RTEXT_FILTER_BRVLAN_COMPRESSED -) diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go deleted file mode 100644 index 1492402..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/conntrack_linux.go +++ /dev/null @@ -1,218 +0,0 @@ -package nl - -import "unsafe" - -// Track the message sizes for the correct serialization/deserialization -const ( - SizeofNfgenmsg = 4 - SizeofNfattr = 4 - SizeofNfConntrack = 376 - SizeofNfctTupleHead = 52 -) - -var L4ProtoMap = map[uint8]string{ - 6: "tcp", - 17: "udp", -} - -// All the following constants are coming from: -// https://github.com/torvalds/linux/blob/master/include/uapi/linux/netfilter/nfnetlink_conntrack.h - -// enum cntl_msg_types { -// IPCTNL_MSG_CT_NEW, -// IPCTNL_MSG_CT_GET, -// IPCTNL_MSG_CT_DELETE, -// IPCTNL_MSG_CT_GET_CTRZERO, -// IPCTNL_MSG_CT_GET_STATS_CPU, -// IPCTNL_MSG_CT_GET_STATS, -// IPCTNL_MSG_CT_GET_DYING, -// IPCTNL_MSG_CT_GET_UNCONFIRMED, -// -// IPCTNL_MSG_MAX -// }; -const ( - IPCTNL_MSG_CT_GET = 1 - IPCTNL_MSG_CT_DELETE = 2 -) - -// #define NFNETLINK_V0 0 -const ( - NFNETLINK_V0 = 0 -) - -const ( - NLA_F_NESTED uint16 = (1 << 15) // #define NLA_F_NESTED (1 << 15) - NLA_F_NET_BYTEORDER uint16 = (1 << 14) // #define NLA_F_NESTED (1 << 14) - NLA_TYPE_MASK = ^(NLA_F_NESTED | NLA_F_NET_BYTEORDER) -) - -// enum ctattr_type { -// CTA_UNSPEC, -// CTA_TUPLE_ORIG, -// CTA_TUPLE_REPLY, -// CTA_STATUS, -// CTA_PROTOINFO, -// CTA_HELP, -// CTA_NAT_SRC, -// #define CTA_NAT CTA_NAT_SRC /* backwards compatibility */ -// CTA_TIMEOUT, -// CTA_MARK, -// CTA_COUNTERS_ORIG, -// CTA_COUNTERS_REPLY, -// CTA_USE, -// CTA_ID, -// CTA_NAT_DST, -// CTA_TUPLE_MASTER, -// CTA_SEQ_ADJ_ORIG, -// CTA_NAT_SEQ_ADJ_ORIG = CTA_SEQ_ADJ_ORIG, -// CTA_SEQ_ADJ_REPLY, -// CTA_NAT_SEQ_ADJ_REPLY = CTA_SEQ_ADJ_REPLY, -// CTA_SECMARK, /* obsolete */ -// CTA_ZONE, -// CTA_SECCTX, -// CTA_TIMESTAMP, -// CTA_MARK_MASK, -// CTA_LABELS, -// CTA_LABELS_MASK, -// __CTA_MAX -// }; -const ( - CTA_TUPLE_ORIG = 1 - CTA_TUPLE_REPLY = 2 - CTA_STATUS = 3 - CTA_PROTOINFO = 4 - CTA_TIMEOUT = 7 - CTA_MARK = 8 - CTA_COUNTERS_ORIG = 9 - CTA_COUNTERS_REPLY = 10 - CTA_USE = 11 - CTA_ID = 12 - CTA_TIMESTAMP = 20 -) - -// enum ctattr_tuple { -// CTA_TUPLE_UNSPEC, -// CTA_TUPLE_IP, -// CTA_TUPLE_PROTO, -// CTA_TUPLE_ZONE, -// __CTA_TUPLE_MAX -// }; -// #define CTA_TUPLE_MAX (__CTA_TUPLE_MAX - 1) -const ( - CTA_TUPLE_IP = 1 - CTA_TUPLE_PROTO = 2 -) - -// enum ctattr_ip { -// CTA_IP_UNSPEC, -// CTA_IP_V4_SRC, -// CTA_IP_V4_DST, -// CTA_IP_V6_SRC, -// CTA_IP_V6_DST, -// __CTA_IP_MAX -// }; -// #define CTA_IP_MAX (__CTA_IP_MAX - 1) -const ( - CTA_IP_V4_SRC = 1 - CTA_IP_V4_DST = 2 - CTA_IP_V6_SRC = 3 - CTA_IP_V6_DST = 4 -) - -// enum ctattr_l4proto { -// CTA_PROTO_UNSPEC, -// CTA_PROTO_NUM, -// CTA_PROTO_SRC_PORT, -// CTA_PROTO_DST_PORT, -// CTA_PROTO_ICMP_ID, -// CTA_PROTO_ICMP_TYPE, -// CTA_PROTO_ICMP_CODE, -// CTA_PROTO_ICMPV6_ID, -// CTA_PROTO_ICMPV6_TYPE, -// CTA_PROTO_ICMPV6_CODE, -// __CTA_PROTO_MAX -// }; -// #define CTA_PROTO_MAX (__CTA_PROTO_MAX - 1) -const ( - CTA_PROTO_NUM = 1 - CTA_PROTO_SRC_PORT = 2 - CTA_PROTO_DST_PORT = 3 -) - -// enum ctattr_protoinfo { -// CTA_PROTOINFO_UNSPEC, -// CTA_PROTOINFO_TCP, -// CTA_PROTOINFO_DCCP, -// CTA_PROTOINFO_SCTP, -// __CTA_PROTOINFO_MAX -// }; -// #define CTA_PROTOINFO_MAX (__CTA_PROTOINFO_MAX - 1) -const ( - CTA_PROTOINFO_TCP = 1 -) - -// enum ctattr_protoinfo_tcp { -// CTA_PROTOINFO_TCP_UNSPEC, -// CTA_PROTOINFO_TCP_STATE, -// CTA_PROTOINFO_TCP_WSCALE_ORIGINAL, -// CTA_PROTOINFO_TCP_WSCALE_REPLY, -// CTA_PROTOINFO_TCP_FLAGS_ORIGINAL, -// CTA_PROTOINFO_TCP_FLAGS_REPLY, -// __CTA_PROTOINFO_TCP_MAX -// }; -// #define CTA_PROTOINFO_TCP_MAX (__CTA_PROTOINFO_TCP_MAX - 1) -const ( - CTA_PROTOINFO_TCP_STATE = 1 - CTA_PROTOINFO_TCP_WSCALE_ORIGINAL = 2 - CTA_PROTOINFO_TCP_WSCALE_REPLY = 3 - CTA_PROTOINFO_TCP_FLAGS_ORIGINAL = 4 - CTA_PROTOINFO_TCP_FLAGS_REPLY = 5 -) - -// enum ctattr_counters { -// CTA_COUNTERS_UNSPEC, -// CTA_COUNTERS_PACKETS, /* 64bit counters */ -// CTA_COUNTERS_BYTES, /* 64bit counters */ -// CTA_COUNTERS32_PACKETS, /* old 32bit counters, unused */ -// CTA_COUNTERS32_BYTES, /* old 32bit counters, unused */ -// CTA_COUNTERS_PAD, -// __CTA_COUNTERS_M -// }; -// #define CTA_COUNTERS_MAX (__CTA_COUNTERS_MAX - 1) -const ( - CTA_COUNTERS_PACKETS = 1 - CTA_COUNTERS_BYTES = 2 -) - -// enum CTA TIMESTAMP TLVs -// CTA_TIMESTAMP_START /* 64bit value */ -// CTA_TIMESTAMP_STOP /* 64bit value */ -const ( - CTA_TIMESTAMP_START = 1 - CTA_TIMESTAMP_STOP = 2 -) - -// /* General form of address family dependent message. -// */ -// struct nfgenmsg { -// __u8 nfgen_family; /* AF_xxx */ -// __u8 version; /* nfnetlink version */ -// __be16 res_id; /* resource id */ -// }; -type Nfgenmsg struct { - NfgenFamily uint8 - Version uint8 - ResId uint16 // big endian -} - -func (msg *Nfgenmsg) Len() int { - return SizeofNfgenmsg -} - -func DeserializeNfgenmsg(b []byte) *Nfgenmsg { - return (*Nfgenmsg)(unsafe.Pointer(&b[0:SizeofNfgenmsg][0])) -} - -func (msg *Nfgenmsg) Serialize() []byte { - return (*(*[SizeofNfgenmsg]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/devlink_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/devlink_linux.go deleted file mode 100644 index db66faa..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/devlink_linux.go +++ /dev/null @@ -1,40 +0,0 @@ -package nl - -// All the following constants are coming from: -// https://github.com/torvalds/linux/blob/master/include/uapi/linux/devlink.h - -const ( - GENL_DEVLINK_VERSION = 1 - GENL_DEVLINK_NAME = "devlink" -) - -const ( - DEVLINK_CMD_GET = 1 - DEVLINK_CMD_ESWITCH_GET = 29 - DEVLINK_CMD_ESWITCH_SET = 30 -) - -const ( - DEVLINK_ATTR_BUS_NAME = 1 - DEVLINK_ATTR_DEV_NAME = 2 - DEVLINK_ATTR_ESWITCH_MODE = 25 - DEVLINK_ATTR_ESWITCH_INLINE_MODE = 26 - DEVLINK_ATTR_ESWITCH_ENCAP_MODE = 62 -) - -const ( - DEVLINK_ESWITCH_MODE_LEGACY = 0 - DEVLINK_ESWITCH_MODE_SWITCHDEV = 1 -) - -const ( - DEVLINK_ESWITCH_INLINE_MODE_NONE = 0 - DEVLINK_ESWITCH_INLINE_MODE_LINK = 1 - DEVLINK_ESWITCH_INLINE_MODE_NETWORK = 2 - DEVLINK_ESWITCH_INLINE_MODE_TRANSPORT = 3 -) - -const ( - DEVLINK_ESWITCH_ENCAP_MODE_NONE = 0 - DEVLINK_ESWITCH_ENCAP_MODE_BASIC = 1 -) diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go deleted file mode 100644 index 81b46f2..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/genetlink_linux.go +++ /dev/null @@ -1,89 +0,0 @@ -package nl - -import ( - "unsafe" -) - -const SizeofGenlmsg = 4 - -const ( - GENL_ID_CTRL = 0x10 - GENL_CTRL_VERSION = 2 - GENL_CTRL_NAME = "nlctrl" -) - -const ( - GENL_CTRL_CMD_GETFAMILY = 3 -) - -const ( - GENL_CTRL_ATTR_UNSPEC = iota - GENL_CTRL_ATTR_FAMILY_ID - GENL_CTRL_ATTR_FAMILY_NAME - GENL_CTRL_ATTR_VERSION - GENL_CTRL_ATTR_HDRSIZE - GENL_CTRL_ATTR_MAXATTR - GENL_CTRL_ATTR_OPS - GENL_CTRL_ATTR_MCAST_GROUPS -) - -const ( - GENL_CTRL_ATTR_OP_UNSPEC = iota - GENL_CTRL_ATTR_OP_ID - GENL_CTRL_ATTR_OP_FLAGS -) - -const ( - GENL_ADMIN_PERM = 1 << iota - GENL_CMD_CAP_DO - GENL_CMD_CAP_DUMP - GENL_CMD_CAP_HASPOL -) - -const ( - GENL_CTRL_ATTR_MCAST_GRP_UNSPEC = iota - GENL_CTRL_ATTR_MCAST_GRP_NAME - GENL_CTRL_ATTR_MCAST_GRP_ID -) - -const ( - GENL_GTP_VERSION = 0 - GENL_GTP_NAME = "gtp" -) - -const ( - GENL_GTP_CMD_NEWPDP = iota - GENL_GTP_CMD_DELPDP - GENL_GTP_CMD_GETPDP -) - -const ( - GENL_GTP_ATTR_UNSPEC = iota - GENL_GTP_ATTR_LINK - GENL_GTP_ATTR_VERSION - GENL_GTP_ATTR_TID - GENL_GTP_ATTR_PEER_ADDRESS - GENL_GTP_ATTR_MS_ADDRESS - GENL_GTP_ATTR_FLOW - GENL_GTP_ATTR_NET_NS_FD - GENL_GTP_ATTR_I_TEI - GENL_GTP_ATTR_O_TEI - GENL_GTP_ATTR_PAD -) - -type Genlmsg struct { - Command uint8 - Version uint8 -} - -func (msg *Genlmsg) Len() int { - return SizeofGenlmsg -} - -func DeserializeGenlmsg(b []byte) *Genlmsg { - return (*Genlmsg)(unsafe.Pointer(&b[0:SizeofGenlmsg][0])) -} - -func (msg *Genlmsg) Serialize() []byte { - return (*(*[SizeofGenlmsg]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/ipset_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/ipset_linux.go deleted file mode 100644 index a60b4b0..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/ipset_linux.go +++ /dev/null @@ -1,222 +0,0 @@ -package nl - -import ( - "strconv" - - "golang.org/x/sys/unix" -) - -const ( - /* The protocol version */ - IPSET_PROTOCOL = 6 - - /* The max length of strings including NUL: set and type identifiers */ - IPSET_MAXNAMELEN = 32 - - /* The maximum permissible comment length we will accept over netlink */ - IPSET_MAX_COMMENT_SIZE = 255 -) - -const ( - _ = iota - IPSET_CMD_PROTOCOL /* 1: Return protocol version */ - IPSET_CMD_CREATE /* 2: Create a new (empty) set */ - IPSET_CMD_DESTROY /* 3: Destroy a (empty) set */ - IPSET_CMD_FLUSH /* 4: Remove all elements from a set */ - IPSET_CMD_RENAME /* 5: Rename a set */ - IPSET_CMD_SWAP /* 6: Swap two sets */ - IPSET_CMD_LIST /* 7: List sets */ - IPSET_CMD_SAVE /* 8: Save sets */ - IPSET_CMD_ADD /* 9: Add an element to a set */ - IPSET_CMD_DEL /* 10: Delete an element from a set */ - IPSET_CMD_TEST /* 11: Test an element in a set */ - IPSET_CMD_HEADER /* 12: Get set header data only */ - IPSET_CMD_TYPE /* 13: Get set type */ -) - -/* Attributes at command level */ -const ( - _ = iota - IPSET_ATTR_PROTOCOL /* 1: Protocol version */ - IPSET_ATTR_SETNAME /* 2: Name of the set */ - IPSET_ATTR_TYPENAME /* 3: Typename */ - IPSET_ATTR_REVISION /* 4: Settype revision */ - IPSET_ATTR_FAMILY /* 5: Settype family */ - IPSET_ATTR_FLAGS /* 6: Flags at command level */ - IPSET_ATTR_DATA /* 7: Nested attributes */ - IPSET_ATTR_ADT /* 8: Multiple data containers */ - IPSET_ATTR_LINENO /* 9: Restore lineno */ - IPSET_ATTR_PROTOCOL_MIN /* 10: Minimal supported version number */ - - IPSET_ATTR_SETNAME2 = IPSET_ATTR_TYPENAME /* Setname at rename/swap */ - IPSET_ATTR_REVISION_MIN = IPSET_ATTR_PROTOCOL_MIN /* type rev min */ -) - -/* CADT specific attributes */ -const ( - IPSET_ATTR_IP = 1 - IPSET_ATTR_IP_FROM = 1 - IPSET_ATTR_IP_TO = 2 - IPSET_ATTR_CIDR = 3 - IPSET_ATTR_PORT = 4 - IPSET_ATTR_PORT_FROM = 4 - IPSET_ATTR_PORT_TO = 5 - IPSET_ATTR_TIMEOUT = 6 - IPSET_ATTR_PROTO = 7 - IPSET_ATTR_CADT_FLAGS = 8 - IPSET_ATTR_CADT_LINENO = IPSET_ATTR_LINENO /* 9 */ - IPSET_ATTR_MARK = 10 - IPSET_ATTR_MARKMASK = 11 - - /* Reserve empty slots */ - IPSET_ATTR_CADT_MAX = 16 - - /* Create-only specific attributes */ - IPSET_ATTR_GC = 3 + iota - IPSET_ATTR_HASHSIZE - IPSET_ATTR_MAXELEM - IPSET_ATTR_NETMASK - IPSET_ATTR_PROBES - IPSET_ATTR_RESIZE - IPSET_ATTR_SIZE - - /* Kernel-only */ - IPSET_ATTR_ELEMENTS - IPSET_ATTR_REFERENCES - IPSET_ATTR_MEMSIZE - - SET_ATTR_CREATE_MAX -) - -/* ADT specific attributes */ -const ( - IPSET_ATTR_ETHER = IPSET_ATTR_CADT_MAX + iota + 1 - IPSET_ATTR_NAME - IPSET_ATTR_NAMEREF - IPSET_ATTR_IP2 - IPSET_ATTR_CIDR2 - IPSET_ATTR_IP2_TO - IPSET_ATTR_IFACE - IPSET_ATTR_BYTES - IPSET_ATTR_PACKETS - IPSET_ATTR_COMMENT - IPSET_ATTR_SKBMARK - IPSET_ATTR_SKBPRIO - IPSET_ATTR_SKBQUEUE -) - -/* Flags at CADT attribute level, upper half of cmdattrs */ -const ( - IPSET_FLAG_BIT_BEFORE = 0 - IPSET_FLAG_BEFORE = (1 << IPSET_FLAG_BIT_BEFORE) - IPSET_FLAG_BIT_PHYSDEV = 1 - IPSET_FLAG_PHYSDEV = (1 << IPSET_FLAG_BIT_PHYSDEV) - IPSET_FLAG_BIT_NOMATCH = 2 - IPSET_FLAG_NOMATCH = (1 << IPSET_FLAG_BIT_NOMATCH) - IPSET_FLAG_BIT_WITH_COUNTERS = 3 - IPSET_FLAG_WITH_COUNTERS = (1 << IPSET_FLAG_BIT_WITH_COUNTERS) - IPSET_FLAG_BIT_WITH_COMMENT = 4 - IPSET_FLAG_WITH_COMMENT = (1 << IPSET_FLAG_BIT_WITH_COMMENT) - IPSET_FLAG_BIT_WITH_FORCEADD = 5 - IPSET_FLAG_WITH_FORCEADD = (1 << IPSET_FLAG_BIT_WITH_FORCEADD) - IPSET_FLAG_BIT_WITH_SKBINFO = 6 - IPSET_FLAG_WITH_SKBINFO = (1 << IPSET_FLAG_BIT_WITH_SKBINFO) - IPSET_FLAG_CADT_MAX = 15 -) - -const ( - IPSET_ERR_PRIVATE = 4096 + iota - IPSET_ERR_PROTOCOL - IPSET_ERR_FIND_TYPE - IPSET_ERR_MAX_SETS - IPSET_ERR_BUSY - IPSET_ERR_EXIST_SETNAME2 - IPSET_ERR_TYPE_MISMATCH - IPSET_ERR_EXIST - IPSET_ERR_INVALID_CIDR - IPSET_ERR_INVALID_NETMASK - IPSET_ERR_INVALID_FAMILY - IPSET_ERR_TIMEOUT - IPSET_ERR_REFERENCED - IPSET_ERR_IPADDR_IPV4 - IPSET_ERR_IPADDR_IPV6 - IPSET_ERR_COUNTER - IPSET_ERR_COMMENT - IPSET_ERR_INVALID_MARKMASK - IPSET_ERR_SKBINFO - - /* Type specific error codes */ - IPSET_ERR_TYPE_SPECIFIC = 4352 -) - -type IPSetError uintptr - -func (e IPSetError) Error() string { - switch int(e) { - case IPSET_ERR_PRIVATE: - return "private" - case IPSET_ERR_PROTOCOL: - return "invalid protocol" - case IPSET_ERR_FIND_TYPE: - return "invalid type" - case IPSET_ERR_MAX_SETS: - return "max sets reached" - case IPSET_ERR_BUSY: - return "busy" - case IPSET_ERR_EXIST_SETNAME2: - return "exist_setname2" - case IPSET_ERR_TYPE_MISMATCH: - return "type mismatch" - case IPSET_ERR_EXIST: - return "exist" - case IPSET_ERR_INVALID_CIDR: - return "invalid cidr" - case IPSET_ERR_INVALID_NETMASK: - return "invalid netmask" - case IPSET_ERR_INVALID_FAMILY: - return "invalid family" - case IPSET_ERR_TIMEOUT: - return "timeout" - case IPSET_ERR_REFERENCED: - return "referenced" - case IPSET_ERR_IPADDR_IPV4: - return "invalid ipv4 address" - case IPSET_ERR_IPADDR_IPV6: - return "invalid ipv6 address" - case IPSET_ERR_COUNTER: - return "invalid counter" - case IPSET_ERR_COMMENT: - return "invalid comment" - case IPSET_ERR_INVALID_MARKMASK: - return "invalid markmask" - case IPSET_ERR_SKBINFO: - return "skbinfo" - default: - return "errno " + strconv.Itoa(int(e)) - } -} - -func GetIpsetFlags(cmd int) int { - switch cmd { - case IPSET_CMD_CREATE: - return unix.NLM_F_REQUEST | unix.NLM_F_ACK | unix.NLM_F_CREATE - case IPSET_CMD_DESTROY, - IPSET_CMD_FLUSH, - IPSET_CMD_RENAME, - IPSET_CMD_SWAP, - IPSET_CMD_TEST: - return unix.NLM_F_REQUEST | unix.NLM_F_ACK - case IPSET_CMD_LIST, - IPSET_CMD_SAVE: - return unix.NLM_F_REQUEST | unix.NLM_F_ACK | unix.NLM_F_ROOT | unix.NLM_F_MATCH | unix.NLM_F_DUMP - case IPSET_CMD_ADD, - IPSET_CMD_DEL: - return unix.NLM_F_REQUEST | unix.NLM_F_ACK - case IPSET_CMD_HEADER, - IPSET_CMD_TYPE, - IPSET_CMD_PROTOCOL: - return unix.NLM_F_REQUEST - default: - return 0 - } -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/link_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/link_linux.go deleted file mode 100644 index faee2fa..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/link_linux.go +++ /dev/null @@ -1,675 +0,0 @@ -package nl - -import ( - "bytes" - "encoding/binary" - "unsafe" -) - -const ( - DEFAULT_CHANGE = 0xFFFFFFFF -) - -const ( - IFLA_INFO_UNSPEC = iota - IFLA_INFO_KIND - IFLA_INFO_DATA - IFLA_INFO_XSTATS - IFLA_INFO_SLAVE_KIND - IFLA_INFO_SLAVE_DATA - IFLA_INFO_MAX = IFLA_INFO_SLAVE_DATA -) - -const ( - IFLA_VLAN_UNSPEC = iota - IFLA_VLAN_ID - IFLA_VLAN_FLAGS - IFLA_VLAN_EGRESS_QOS - IFLA_VLAN_INGRESS_QOS - IFLA_VLAN_PROTOCOL - IFLA_VLAN_MAX = IFLA_VLAN_PROTOCOL -) - -const ( - VETH_INFO_UNSPEC = iota - VETH_INFO_PEER - VETH_INFO_MAX = VETH_INFO_PEER -) - -const ( - IFLA_VXLAN_UNSPEC = iota - IFLA_VXLAN_ID - IFLA_VXLAN_GROUP - IFLA_VXLAN_LINK - IFLA_VXLAN_LOCAL - IFLA_VXLAN_TTL - IFLA_VXLAN_TOS - IFLA_VXLAN_LEARNING - IFLA_VXLAN_AGEING - IFLA_VXLAN_LIMIT - IFLA_VXLAN_PORT_RANGE - IFLA_VXLAN_PROXY - IFLA_VXLAN_RSC - IFLA_VXLAN_L2MISS - IFLA_VXLAN_L3MISS - IFLA_VXLAN_PORT - IFLA_VXLAN_GROUP6 - IFLA_VXLAN_LOCAL6 - IFLA_VXLAN_UDP_CSUM - IFLA_VXLAN_UDP_ZERO_CSUM6_TX - IFLA_VXLAN_UDP_ZERO_CSUM6_RX - IFLA_VXLAN_REMCSUM_TX - IFLA_VXLAN_REMCSUM_RX - IFLA_VXLAN_GBP - IFLA_VXLAN_REMCSUM_NOPARTIAL - IFLA_VXLAN_FLOWBASED - IFLA_VXLAN_MAX = IFLA_VXLAN_FLOWBASED -) - -const ( - BRIDGE_MODE_UNSPEC = iota - BRIDGE_MODE_HAIRPIN -) - -const ( - IFLA_BRPORT_UNSPEC = iota - IFLA_BRPORT_STATE - IFLA_BRPORT_PRIORITY - IFLA_BRPORT_COST - IFLA_BRPORT_MODE - IFLA_BRPORT_GUARD - IFLA_BRPORT_PROTECT - IFLA_BRPORT_FAST_LEAVE - IFLA_BRPORT_LEARNING - IFLA_BRPORT_UNICAST_FLOOD - IFLA_BRPORT_PROXYARP - IFLA_BRPORT_LEARNING_SYNC - IFLA_BRPORT_PROXYARP_WIFI - IFLA_BRPORT_MAX = IFLA_BRPORT_PROXYARP_WIFI -) - -const ( - IFLA_IPVLAN_UNSPEC = iota - IFLA_IPVLAN_MODE - IFLA_IPVLAN_FLAG - IFLA_IPVLAN_MAX = IFLA_IPVLAN_FLAG -) - -const ( - IFLA_MACVLAN_UNSPEC = iota - IFLA_MACVLAN_MODE - IFLA_MACVLAN_FLAGS - IFLA_MACVLAN_MACADDR_MODE - IFLA_MACVLAN_MACADDR - IFLA_MACVLAN_MACADDR_DATA - IFLA_MACVLAN_MACADDR_COUNT - IFLA_MACVLAN_MAX = IFLA_MACVLAN_FLAGS -) - -const ( - MACVLAN_MODE_PRIVATE = 1 - MACVLAN_MODE_VEPA = 2 - MACVLAN_MODE_BRIDGE = 4 - MACVLAN_MODE_PASSTHRU = 8 - MACVLAN_MODE_SOURCE = 16 -) - -const ( - MACVLAN_MACADDR_ADD = iota - MACVLAN_MACADDR_DEL - MACVLAN_MACADDR_FLUSH - MACVLAN_MACADDR_SET -) - -const ( - IFLA_BOND_UNSPEC = iota - IFLA_BOND_MODE - IFLA_BOND_ACTIVE_SLAVE - IFLA_BOND_MIIMON - IFLA_BOND_UPDELAY - IFLA_BOND_DOWNDELAY - IFLA_BOND_USE_CARRIER - IFLA_BOND_ARP_INTERVAL - IFLA_BOND_ARP_IP_TARGET - IFLA_BOND_ARP_VALIDATE - IFLA_BOND_ARP_ALL_TARGETS - IFLA_BOND_PRIMARY - IFLA_BOND_PRIMARY_RESELECT - IFLA_BOND_FAIL_OVER_MAC - IFLA_BOND_XMIT_HASH_POLICY - IFLA_BOND_RESEND_IGMP - IFLA_BOND_NUM_PEER_NOTIF - IFLA_BOND_ALL_SLAVES_ACTIVE - IFLA_BOND_MIN_LINKS - IFLA_BOND_LP_INTERVAL - IFLA_BOND_PACKETS_PER_SLAVE - IFLA_BOND_AD_LACP_RATE - IFLA_BOND_AD_SELECT - IFLA_BOND_AD_INFO - IFLA_BOND_AD_ACTOR_SYS_PRIO - IFLA_BOND_AD_USER_PORT_KEY - IFLA_BOND_AD_ACTOR_SYSTEM - IFLA_BOND_TLB_DYNAMIC_LB -) - -const ( - IFLA_BOND_AD_INFO_UNSPEC = iota - IFLA_BOND_AD_INFO_AGGREGATOR - IFLA_BOND_AD_INFO_NUM_PORTS - IFLA_BOND_AD_INFO_ACTOR_KEY - IFLA_BOND_AD_INFO_PARTNER_KEY - IFLA_BOND_AD_INFO_PARTNER_MAC -) - -const ( - IFLA_BOND_SLAVE_UNSPEC = iota - IFLA_BOND_SLAVE_STATE - IFLA_BOND_SLAVE_MII_STATUS - IFLA_BOND_SLAVE_LINK_FAILURE_COUNT - IFLA_BOND_SLAVE_PERM_HWADDR - IFLA_BOND_SLAVE_QUEUE_ID - IFLA_BOND_SLAVE_AD_AGGREGATOR_ID - IFLA_BOND_SLAVE_AD_ACTOR_OPER_PORT_STATE - IFLA_BOND_SLAVE_AD_PARTNER_OPER_PORT_STATE -) - -const ( - IFLA_GRE_UNSPEC = iota - IFLA_GRE_LINK - IFLA_GRE_IFLAGS - IFLA_GRE_OFLAGS - IFLA_GRE_IKEY - IFLA_GRE_OKEY - IFLA_GRE_LOCAL - IFLA_GRE_REMOTE - IFLA_GRE_TTL - IFLA_GRE_TOS - IFLA_GRE_PMTUDISC - IFLA_GRE_ENCAP_LIMIT - IFLA_GRE_FLOWINFO - IFLA_GRE_FLAGS - IFLA_GRE_ENCAP_TYPE - IFLA_GRE_ENCAP_FLAGS - IFLA_GRE_ENCAP_SPORT - IFLA_GRE_ENCAP_DPORT - IFLA_GRE_COLLECT_METADATA - IFLA_GRE_MAX = IFLA_GRE_COLLECT_METADATA -) - -const ( - GRE_CSUM = 0x8000 - GRE_ROUTING = 0x4000 - GRE_KEY = 0x2000 - GRE_SEQ = 0x1000 - GRE_STRICT = 0x0800 - GRE_REC = 0x0700 - GRE_FLAGS = 0x00F8 - GRE_VERSION = 0x0007 -) - -const ( - IFLA_VF_INFO_UNSPEC = iota - IFLA_VF_INFO - IFLA_VF_INFO_MAX = IFLA_VF_INFO -) - -const ( - IFLA_VF_UNSPEC = iota - IFLA_VF_MAC /* Hardware queue specific attributes */ - IFLA_VF_VLAN - IFLA_VF_TX_RATE /* Max TX Bandwidth Allocation */ - IFLA_VF_SPOOFCHK /* Spoof Checking on/off switch */ - IFLA_VF_LINK_STATE /* link state enable/disable/auto switch */ - IFLA_VF_RATE /* Min and Max TX Bandwidth Allocation */ - IFLA_VF_RSS_QUERY_EN /* RSS Redirection Table and Hash Key query - * on/off switch - */ - IFLA_VF_STATS /* network device statistics */ - IFLA_VF_TRUST /* Trust state of VF */ - IFLA_VF_IB_NODE_GUID /* VF Infiniband node GUID */ - IFLA_VF_IB_PORT_GUID /* VF Infiniband port GUID */ - IFLA_VF_MAX = IFLA_VF_IB_PORT_GUID -) - -const ( - IFLA_VF_LINK_STATE_AUTO = iota /* link state of the uplink */ - IFLA_VF_LINK_STATE_ENABLE /* link always up */ - IFLA_VF_LINK_STATE_DISABLE /* link always down */ - IFLA_VF_LINK_STATE_MAX = IFLA_VF_LINK_STATE_DISABLE -) - -const ( - IFLA_VF_STATS_RX_PACKETS = iota - IFLA_VF_STATS_TX_PACKETS - IFLA_VF_STATS_RX_BYTES - IFLA_VF_STATS_TX_BYTES - IFLA_VF_STATS_BROADCAST - IFLA_VF_STATS_MULTICAST - IFLA_VF_STATS_RX_DROPPED - IFLA_VF_STATS_TX_DROPPED - IFLA_VF_STATS_MAX = IFLA_VF_STATS_TX_DROPPED -) - -const ( - SizeofVfMac = 0x24 - SizeofVfVlan = 0x0c - SizeofVfTxRate = 0x08 - SizeofVfRate = 0x0c - SizeofVfSpoofchk = 0x08 - SizeofVfLinkState = 0x08 - SizeofVfRssQueryEn = 0x08 - SizeofVfTrust = 0x08 - SizeofVfGUID = 0x10 -) - -// struct ifla_vf_mac { -// __u32 vf; -// __u8 mac[32]; /* MAX_ADDR_LEN */ -// }; - -type VfMac struct { - Vf uint32 - Mac [32]byte -} - -func (msg *VfMac) Len() int { - return SizeofVfMac -} - -func DeserializeVfMac(b []byte) *VfMac { - return (*VfMac)(unsafe.Pointer(&b[0:SizeofVfMac][0])) -} - -func (msg *VfMac) Serialize() []byte { - return (*(*[SizeofVfMac]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_vlan { -// __u32 vf; -// __u32 vlan; /* 0 - 4095, 0 disables VLAN filter */ -// __u32 qos; -// }; - -type VfVlan struct { - Vf uint32 - Vlan uint32 - Qos uint32 -} - -func (msg *VfVlan) Len() int { - return SizeofVfVlan -} - -func DeserializeVfVlan(b []byte) *VfVlan { - return (*VfVlan)(unsafe.Pointer(&b[0:SizeofVfVlan][0])) -} - -func (msg *VfVlan) Serialize() []byte { - return (*(*[SizeofVfVlan]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_tx_rate { -// __u32 vf; -// __u32 rate; /* Max TX bandwidth in Mbps, 0 disables throttling */ -// }; - -type VfTxRate struct { - Vf uint32 - Rate uint32 -} - -func (msg *VfTxRate) Len() int { - return SizeofVfTxRate -} - -func DeserializeVfTxRate(b []byte) *VfTxRate { - return (*VfTxRate)(unsafe.Pointer(&b[0:SizeofVfTxRate][0])) -} - -func (msg *VfTxRate) Serialize() []byte { - return (*(*[SizeofVfTxRate]byte)(unsafe.Pointer(msg)))[:] -} - -//struct ifla_vf_stats { -// __u64 rx_packets; -// __u64 tx_packets; -// __u64 rx_bytes; -// __u64 tx_bytes; -// __u64 broadcast; -// __u64 multicast; -//}; - -type VfStats struct { - RxPackets uint64 - TxPackets uint64 - RxBytes uint64 - TxBytes uint64 - Multicast uint64 - Broadcast uint64 - RxDropped uint64 - TxDropped uint64 -} - -func DeserializeVfStats(b []byte) VfStats { - var vfstat VfStats - stats, err := ParseRouteAttr(b) - if err != nil { - return vfstat - } - var valueVar uint64 - for _, stat := range stats { - if err := binary.Read(bytes.NewBuffer(stat.Value), NativeEndian(), &valueVar); err != nil { - break - } - switch stat.Attr.Type { - case IFLA_VF_STATS_RX_PACKETS: - vfstat.RxPackets = valueVar - case IFLA_VF_STATS_TX_PACKETS: - vfstat.TxPackets = valueVar - case IFLA_VF_STATS_RX_BYTES: - vfstat.RxBytes = valueVar - case IFLA_VF_STATS_TX_BYTES: - vfstat.TxBytes = valueVar - case IFLA_VF_STATS_MULTICAST: - vfstat.Multicast = valueVar - case IFLA_VF_STATS_BROADCAST: - vfstat.Broadcast = valueVar - case IFLA_VF_STATS_RX_DROPPED: - vfstat.RxDropped = valueVar - case IFLA_VF_STATS_TX_DROPPED: - vfstat.TxDropped = valueVar - } - } - return vfstat -} - -// struct ifla_vf_rate { -// __u32 vf; -// __u32 min_tx_rate; /* Min Bandwidth in Mbps */ -// __u32 max_tx_rate; /* Max Bandwidth in Mbps */ -// }; - -type VfRate struct { - Vf uint32 - MinTxRate uint32 - MaxTxRate uint32 -} - -func (msg *VfRate) Len() int { - return SizeofVfRate -} - -func DeserializeVfRate(b []byte) *VfRate { - return (*VfRate)(unsafe.Pointer(&b[0:SizeofVfRate][0])) -} - -func (msg *VfRate) Serialize() []byte { - return (*(*[SizeofVfRate]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_spoofchk { -// __u32 vf; -// __u32 setting; -// }; - -type VfSpoofchk struct { - Vf uint32 - Setting uint32 -} - -func (msg *VfSpoofchk) Len() int { - return SizeofVfSpoofchk -} - -func DeserializeVfSpoofchk(b []byte) *VfSpoofchk { - return (*VfSpoofchk)(unsafe.Pointer(&b[0:SizeofVfSpoofchk][0])) -} - -func (msg *VfSpoofchk) Serialize() []byte { - return (*(*[SizeofVfSpoofchk]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_link_state { -// __u32 vf; -// __u32 link_state; -// }; - -type VfLinkState struct { - Vf uint32 - LinkState uint32 -} - -func (msg *VfLinkState) Len() int { - return SizeofVfLinkState -} - -func DeserializeVfLinkState(b []byte) *VfLinkState { - return (*VfLinkState)(unsafe.Pointer(&b[0:SizeofVfLinkState][0])) -} - -func (msg *VfLinkState) Serialize() []byte { - return (*(*[SizeofVfLinkState]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_rss_query_en { -// __u32 vf; -// __u32 setting; -// }; - -type VfRssQueryEn struct { - Vf uint32 - Setting uint32 -} - -func (msg *VfRssQueryEn) Len() int { - return SizeofVfRssQueryEn -} - -func DeserializeVfRssQueryEn(b []byte) *VfRssQueryEn { - return (*VfRssQueryEn)(unsafe.Pointer(&b[0:SizeofVfRssQueryEn][0])) -} - -func (msg *VfRssQueryEn) Serialize() []byte { - return (*(*[SizeofVfRssQueryEn]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_trust { -// __u32 vf; -// __u32 setting; -// }; - -type VfTrust struct { - Vf uint32 - Setting uint32 -} - -func (msg *VfTrust) Len() int { - return SizeofVfTrust -} - -func DeserializeVfTrust(b []byte) *VfTrust { - return (*VfTrust)(unsafe.Pointer(&b[0:SizeofVfTrust][0])) -} - -func (msg *VfTrust) Serialize() []byte { - return (*(*[SizeofVfTrust]byte)(unsafe.Pointer(msg)))[:] -} - -// struct ifla_vf_guid { -// __u32 vf; -// __u32 rsvd; -// __u64 guid; -// }; - -type VfGUID struct { - Vf uint32 - Rsvd uint32 - GUID uint64 -} - -func (msg *VfGUID) Len() int { - return SizeofVfGUID -} - -func DeserializeVfGUID(b []byte) *VfGUID { - return (*VfGUID)(unsafe.Pointer(&b[0:SizeofVfGUID][0])) -} - -func (msg *VfGUID) Serialize() []byte { - return (*(*[SizeofVfGUID]byte)(unsafe.Pointer(msg)))[:] -} - -const ( - XDP_FLAGS_UPDATE_IF_NOEXIST = 1 << iota - XDP_FLAGS_SKB_MODE - XDP_FLAGS_DRV_MODE - XDP_FLAGS_MASK = XDP_FLAGS_UPDATE_IF_NOEXIST | XDP_FLAGS_SKB_MODE | XDP_FLAGS_DRV_MODE -) - -const ( - IFLA_XDP_UNSPEC = iota - IFLA_XDP_FD /* fd of xdp program to attach, or -1 to remove */ - IFLA_XDP_ATTACHED /* read-only bool indicating if prog is attached */ - IFLA_XDP_FLAGS /* xdp prog related flags */ - IFLA_XDP_PROG_ID /* xdp prog id */ - IFLA_XDP_MAX = IFLA_XDP_PROG_ID -) - -// XDP program attach mode (used as dump value for IFLA_XDP_ATTACHED) -const ( - XDP_ATTACHED_NONE = iota - XDP_ATTACHED_DRV - XDP_ATTACHED_SKB - XDP_ATTACHED_HW -) - -const ( - IFLA_IPTUN_UNSPEC = iota - IFLA_IPTUN_LINK - IFLA_IPTUN_LOCAL - IFLA_IPTUN_REMOTE - IFLA_IPTUN_TTL - IFLA_IPTUN_TOS - IFLA_IPTUN_ENCAP_LIMIT - IFLA_IPTUN_FLOWINFO - IFLA_IPTUN_FLAGS - IFLA_IPTUN_PROTO - IFLA_IPTUN_PMTUDISC - IFLA_IPTUN_6RD_PREFIX - IFLA_IPTUN_6RD_RELAY_PREFIX - IFLA_IPTUN_6RD_PREFIXLEN - IFLA_IPTUN_6RD_RELAY_PREFIXLEN - IFLA_IPTUN_ENCAP_TYPE - IFLA_IPTUN_ENCAP_FLAGS - IFLA_IPTUN_ENCAP_SPORT - IFLA_IPTUN_ENCAP_DPORT - IFLA_IPTUN_COLLECT_METADATA - IFLA_IPTUN_MAX = IFLA_IPTUN_COLLECT_METADATA -) - -const ( - IFLA_VTI_UNSPEC = iota - IFLA_VTI_LINK - IFLA_VTI_IKEY - IFLA_VTI_OKEY - IFLA_VTI_LOCAL - IFLA_VTI_REMOTE - IFLA_VTI_MAX = IFLA_VTI_REMOTE -) - -const ( - IFLA_VRF_UNSPEC = iota - IFLA_VRF_TABLE -) - -const ( - IFLA_BR_UNSPEC = iota - IFLA_BR_FORWARD_DELAY - IFLA_BR_HELLO_TIME - IFLA_BR_MAX_AGE - IFLA_BR_AGEING_TIME - IFLA_BR_STP_STATE - IFLA_BR_PRIORITY - IFLA_BR_VLAN_FILTERING - IFLA_BR_VLAN_PROTOCOL - IFLA_BR_GROUP_FWD_MASK - IFLA_BR_ROOT_ID - IFLA_BR_BRIDGE_ID - IFLA_BR_ROOT_PORT - IFLA_BR_ROOT_PATH_COST - IFLA_BR_TOPOLOGY_CHANGE - IFLA_BR_TOPOLOGY_CHANGE_DETECTED - IFLA_BR_HELLO_TIMER - IFLA_BR_TCN_TIMER - IFLA_BR_TOPOLOGY_CHANGE_TIMER - IFLA_BR_GC_TIMER - IFLA_BR_GROUP_ADDR - IFLA_BR_FDB_FLUSH - IFLA_BR_MCAST_ROUTER - IFLA_BR_MCAST_SNOOPING - IFLA_BR_MCAST_QUERY_USE_IFADDR - IFLA_BR_MCAST_QUERIER - IFLA_BR_MCAST_HASH_ELASTICITY - IFLA_BR_MCAST_HASH_MAX - IFLA_BR_MCAST_LAST_MEMBER_CNT - IFLA_BR_MCAST_STARTUP_QUERY_CNT - IFLA_BR_MCAST_LAST_MEMBER_INTVL - IFLA_BR_MCAST_MEMBERSHIP_INTVL - IFLA_BR_MCAST_QUERIER_INTVL - IFLA_BR_MCAST_QUERY_INTVL - IFLA_BR_MCAST_QUERY_RESPONSE_INTVL - IFLA_BR_MCAST_STARTUP_QUERY_INTVL - IFLA_BR_NF_CALL_IPTABLES - IFLA_BR_NF_CALL_IP6TABLES - IFLA_BR_NF_CALL_ARPTABLES - IFLA_BR_VLAN_DEFAULT_PVID - IFLA_BR_PAD - IFLA_BR_VLAN_STATS_ENABLED - IFLA_BR_MCAST_STATS_ENABLED - IFLA_BR_MCAST_IGMP_VERSION - IFLA_BR_MCAST_MLD_VERSION - IFLA_BR_MAX = IFLA_BR_MCAST_MLD_VERSION -) - -const ( - IFLA_GTP_UNSPEC = iota - IFLA_GTP_FD0 - IFLA_GTP_FD1 - IFLA_GTP_PDP_HASHSIZE - IFLA_GTP_ROLE -) - -const ( - GTP_ROLE_GGSN = iota - GTP_ROLE_SGSN -) - -const ( - IFLA_XFRM_UNSPEC = iota - IFLA_XFRM_LINK - IFLA_XFRM_IF_ID - - IFLA_XFRM_MAX = iota - 1 -) - -const ( - IFLA_TUN_UNSPEC = iota - IFLA_TUN_OWNER - IFLA_TUN_GROUP - IFLA_TUN_TYPE - IFLA_TUN_PI - IFLA_TUN_VNET_HDR - IFLA_TUN_PERSIST - IFLA_TUN_MULTI_QUEUE - IFLA_TUN_NUM_QUEUES - IFLA_TUN_NUM_DISABLED_QUEUES - IFLA_TUN_MAX = IFLA_TUN_NUM_DISABLED_QUEUES -) - -const ( - IFLA_IPOIB_UNSPEC = iota - IFLA_IPOIB_PKEY - IFLA_IPOIB_MODE - IFLA_IPOIB_UMCAST - IFLA_IPOIB_MAX = IFLA_IPOIB_UMCAST -) diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go deleted file mode 100644 index 3915b7e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/mpls_linux.go +++ /dev/null @@ -1,36 +0,0 @@ -package nl - -import "encoding/binary" - -const ( - MPLS_LS_LABEL_SHIFT = 12 - MPLS_LS_S_SHIFT = 8 -) - -func EncodeMPLSStack(labels ...int) []byte { - b := make([]byte, 4*len(labels)) - for idx, label := range labels { - l := label << MPLS_LS_LABEL_SHIFT - if idx == len(labels)-1 { - l |= 1 << MPLS_LS_S_SHIFT - } - binary.BigEndian.PutUint32(b[idx*4:], uint32(l)) - } - return b -} - -func DecodeMPLSStack(buf []byte) []int { - if len(buf)%4 != 0 { - return nil - } - stack := make([]int, 0, len(buf)/4) - for len(buf) > 0 { - l := binary.BigEndian.Uint32(buf[:4]) - buf = buf[4:] - stack = append(stack, int(l)>>MPLS_LS_LABEL_SHIFT) - if (l>>MPLS_LS_S_SHIFT)&1 > 0 { - break - } - } - return stack -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/nl_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/nl_linux.go deleted file mode 100644 index cef64b8..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/nl_linux.go +++ /dev/null @@ -1,780 +0,0 @@ -// Package nl has low level primitives for making Netlink calls. -package nl - -import ( - "bytes" - "encoding/binary" - "fmt" - "net" - "runtime" - "sync" - "sync/atomic" - "syscall" - "unsafe" - - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -const ( - // Family type definitions - FAMILY_ALL = unix.AF_UNSPEC - FAMILY_V4 = unix.AF_INET - FAMILY_V6 = unix.AF_INET6 - FAMILY_MPLS = unix.AF_MPLS - // Arbitrary set value (greater than default 4k) to allow receiving - // from kernel more verbose messages e.g. for statistics, - // tc rules or filters, or other more memory requiring data. - RECEIVE_BUFFER_SIZE = 65536 - // Kernel netlink pid - PidKernel uint32 = 0 -) - -// SupportedNlFamilies contains the list of netlink families this netlink package supports -var SupportedNlFamilies = []int{unix.NETLINK_ROUTE, unix.NETLINK_XFRM, unix.NETLINK_NETFILTER} - -var nextSeqNr uint32 - -// GetIPFamily returns the family type of a net.IP. -func GetIPFamily(ip net.IP) int { - if len(ip) <= net.IPv4len { - return FAMILY_V4 - } - if ip.To4() != nil { - return FAMILY_V4 - } - return FAMILY_V6 -} - -var nativeEndian binary.ByteOrder - -// NativeEndian gets native endianness for the system -func NativeEndian() binary.ByteOrder { - if nativeEndian == nil { - var x uint32 = 0x01020304 - if *(*byte)(unsafe.Pointer(&x)) == 0x01 { - nativeEndian = binary.BigEndian - } else { - nativeEndian = binary.LittleEndian - } - } - return nativeEndian -} - -// Byte swap a 16 bit value if we aren't big endian -func Swap16(i uint16) uint16 { - if NativeEndian() == binary.BigEndian { - return i - } - return (i&0xff00)>>8 | (i&0xff)<<8 -} - -// Byte swap a 32 bit value if aren't big endian -func Swap32(i uint32) uint32 { - if NativeEndian() == binary.BigEndian { - return i - } - return (i&0xff000000)>>24 | (i&0xff0000)>>8 | (i&0xff00)<<8 | (i&0xff)<<24 -} - -type NetlinkRequestData interface { - Len() int - Serialize() []byte -} - -// IfInfomsg is related to links, but it is used for list requests as well -type IfInfomsg struct { - unix.IfInfomsg -} - -// Create an IfInfomsg with family specified -func NewIfInfomsg(family int) *IfInfomsg { - return &IfInfomsg{ - IfInfomsg: unix.IfInfomsg{ - Family: uint8(family), - }, - } -} - -func DeserializeIfInfomsg(b []byte) *IfInfomsg { - return (*IfInfomsg)(unsafe.Pointer(&b[0:unix.SizeofIfInfomsg][0])) -} - -func (msg *IfInfomsg) Serialize() []byte { - return (*(*[unix.SizeofIfInfomsg]byte)(unsafe.Pointer(msg)))[:] -} - -func (msg *IfInfomsg) Len() int { - return unix.SizeofIfInfomsg -} - -func (msg *IfInfomsg) EncapType() string { - switch msg.Type { - case 0: - return "generic" - case unix.ARPHRD_ETHER: - return "ether" - case unix.ARPHRD_EETHER: - return "eether" - case unix.ARPHRD_AX25: - return "ax25" - case unix.ARPHRD_PRONET: - return "pronet" - case unix.ARPHRD_CHAOS: - return "chaos" - case unix.ARPHRD_IEEE802: - return "ieee802" - case unix.ARPHRD_ARCNET: - return "arcnet" - case unix.ARPHRD_APPLETLK: - return "atalk" - case unix.ARPHRD_DLCI: - return "dlci" - case unix.ARPHRD_ATM: - return "atm" - case unix.ARPHRD_METRICOM: - return "metricom" - case unix.ARPHRD_IEEE1394: - return "ieee1394" - case unix.ARPHRD_INFINIBAND: - return "infiniband" - case unix.ARPHRD_SLIP: - return "slip" - case unix.ARPHRD_CSLIP: - return "cslip" - case unix.ARPHRD_SLIP6: - return "slip6" - case unix.ARPHRD_CSLIP6: - return "cslip6" - case unix.ARPHRD_RSRVD: - return "rsrvd" - case unix.ARPHRD_ADAPT: - return "adapt" - case unix.ARPHRD_ROSE: - return "rose" - case unix.ARPHRD_X25: - return "x25" - case unix.ARPHRD_HWX25: - return "hwx25" - case unix.ARPHRD_PPP: - return "ppp" - case unix.ARPHRD_HDLC: - return "hdlc" - case unix.ARPHRD_LAPB: - return "lapb" - case unix.ARPHRD_DDCMP: - return "ddcmp" - case unix.ARPHRD_RAWHDLC: - return "rawhdlc" - case unix.ARPHRD_TUNNEL: - return "ipip" - case unix.ARPHRD_TUNNEL6: - return "tunnel6" - case unix.ARPHRD_FRAD: - return "frad" - case unix.ARPHRD_SKIP: - return "skip" - case unix.ARPHRD_LOOPBACK: - return "loopback" - case unix.ARPHRD_LOCALTLK: - return "ltalk" - case unix.ARPHRD_FDDI: - return "fddi" - case unix.ARPHRD_BIF: - return "bif" - case unix.ARPHRD_SIT: - return "sit" - case unix.ARPHRD_IPDDP: - return "ip/ddp" - case unix.ARPHRD_IPGRE: - return "gre" - case unix.ARPHRD_PIMREG: - return "pimreg" - case unix.ARPHRD_HIPPI: - return "hippi" - case unix.ARPHRD_ASH: - return "ash" - case unix.ARPHRD_ECONET: - return "econet" - case unix.ARPHRD_IRDA: - return "irda" - case unix.ARPHRD_FCPP: - return "fcpp" - case unix.ARPHRD_FCAL: - return "fcal" - case unix.ARPHRD_FCPL: - return "fcpl" - case unix.ARPHRD_FCFABRIC: - return "fcfb0" - case unix.ARPHRD_FCFABRIC + 1: - return "fcfb1" - case unix.ARPHRD_FCFABRIC + 2: - return "fcfb2" - case unix.ARPHRD_FCFABRIC + 3: - return "fcfb3" - case unix.ARPHRD_FCFABRIC + 4: - return "fcfb4" - case unix.ARPHRD_FCFABRIC + 5: - return "fcfb5" - case unix.ARPHRD_FCFABRIC + 6: - return "fcfb6" - case unix.ARPHRD_FCFABRIC + 7: - return "fcfb7" - case unix.ARPHRD_FCFABRIC + 8: - return "fcfb8" - case unix.ARPHRD_FCFABRIC + 9: - return "fcfb9" - case unix.ARPHRD_FCFABRIC + 10: - return "fcfb10" - case unix.ARPHRD_FCFABRIC + 11: - return "fcfb11" - case unix.ARPHRD_FCFABRIC + 12: - return "fcfb12" - case unix.ARPHRD_IEEE802_TR: - return "tr" - case unix.ARPHRD_IEEE80211: - return "ieee802.11" - case unix.ARPHRD_IEEE80211_PRISM: - return "ieee802.11/prism" - case unix.ARPHRD_IEEE80211_RADIOTAP: - return "ieee802.11/radiotap" - case unix.ARPHRD_IEEE802154: - return "ieee802.15.4" - - case 65534: - return "none" - case 65535: - return "void" - } - return fmt.Sprintf("unknown%d", msg.Type) -} - -func rtaAlignOf(attrlen int) int { - return (attrlen + unix.RTA_ALIGNTO - 1) & ^(unix.RTA_ALIGNTO - 1) -} - -func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg { - msg := NewIfInfomsg(family) - parent.children = append(parent.children, msg) - return msg -} - -type Uint32Attribute struct { - Type uint16 - Value uint32 -} - -func (a *Uint32Attribute) Serialize() []byte { - native := NativeEndian() - buf := make([]byte, rtaAlignOf(8)) - native.PutUint16(buf[0:2], 8) - native.PutUint16(buf[2:4], a.Type) - - if a.Type&NLA_F_NET_BYTEORDER != 0 { - binary.BigEndian.PutUint32(buf[4:], a.Value) - } else { - native.PutUint32(buf[4:], a.Value) - } - return buf -} - -func (a *Uint32Attribute) Len() int { - return 8 -} - -// Extend RtAttr to handle data and children -type RtAttr struct { - unix.RtAttr - Data []byte - children []NetlinkRequestData -} - -// Create a new Extended RtAttr object -func NewRtAttr(attrType int, data []byte) *RtAttr { - return &RtAttr{ - RtAttr: unix.RtAttr{ - Type: uint16(attrType), - }, - children: []NetlinkRequestData{}, - Data: data, - } -} - -// NewRtAttrChild adds an RtAttr as a child to the parent and returns the new attribute -// -// Deprecated: Use AddRtAttr() on the parent object -func NewRtAttrChild(parent *RtAttr, attrType int, data []byte) *RtAttr { - return parent.AddRtAttr(attrType, data) -} - -// AddRtAttr adds an RtAttr as a child and returns the new attribute -func (a *RtAttr) AddRtAttr(attrType int, data []byte) *RtAttr { - attr := NewRtAttr(attrType, data) - a.children = append(a.children, attr) - return attr -} - -// AddChild adds an existing NetlinkRequestData as a child. -func (a *RtAttr) AddChild(attr NetlinkRequestData) { - a.children = append(a.children, attr) -} - -func (a *RtAttr) Len() int { - if len(a.children) == 0 { - return (unix.SizeofRtAttr + len(a.Data)) - } - - l := 0 - for _, child := range a.children { - l += rtaAlignOf(child.Len()) - } - l += unix.SizeofRtAttr - return rtaAlignOf(l + len(a.Data)) -} - -// Serialize the RtAttr into a byte array -// This can't just unsafe.cast because it must iterate through children. -func (a *RtAttr) Serialize() []byte { - native := NativeEndian() - - length := a.Len() - buf := make([]byte, rtaAlignOf(length)) - - next := 4 - if a.Data != nil { - copy(buf[next:], a.Data) - next += rtaAlignOf(len(a.Data)) - } - if len(a.children) > 0 { - for _, child := range a.children { - childBuf := child.Serialize() - copy(buf[next:], childBuf) - next += rtaAlignOf(len(childBuf)) - } - } - - if l := uint16(length); l != 0 { - native.PutUint16(buf[0:2], l) - } - native.PutUint16(buf[2:4], a.Type) - return buf -} - -type NetlinkRequest struct { - unix.NlMsghdr - Data []NetlinkRequestData - RawData []byte - Sockets map[int]*SocketHandle -} - -// Serialize the Netlink Request into a byte array -func (req *NetlinkRequest) Serialize() []byte { - length := unix.SizeofNlMsghdr - dataBytes := make([][]byte, len(req.Data)) - for i, data := range req.Data { - dataBytes[i] = data.Serialize() - length = length + len(dataBytes[i]) - } - length += len(req.RawData) - - req.Len = uint32(length) - b := make([]byte, length) - hdr := (*(*[unix.SizeofNlMsghdr]byte)(unsafe.Pointer(req)))[:] - next := unix.SizeofNlMsghdr - copy(b[0:next], hdr) - for _, data := range dataBytes { - for _, dataByte := range data { - b[next] = dataByte - next = next + 1 - } - } - // Add the raw data if any - if len(req.RawData) > 0 { - copy(b[next:length], req.RawData) - } - return b -} - -func (req *NetlinkRequest) AddData(data NetlinkRequestData) { - req.Data = append(req.Data, data) -} - -// AddRawData adds raw bytes to the end of the NetlinkRequest object during serialization -func (req *NetlinkRequest) AddRawData(data []byte) { - req.RawData = append(req.RawData, data...) -} - -// Execute the request against a the given sockType. -// Returns a list of netlink messages in serialized format, optionally filtered -// by resType. -func (req *NetlinkRequest) Execute(sockType int, resType uint16) ([][]byte, error) { - var ( - s *NetlinkSocket - err error - ) - - if req.Sockets != nil { - if sh, ok := req.Sockets[sockType]; ok { - s = sh.Socket - req.Seq = atomic.AddUint32(&sh.Seq, 1) - } - } - sharedSocket := s != nil - - if s == nil { - s, err = getNetlinkSocket(sockType) - if err != nil { - return nil, err - } - defer s.Close() - } else { - s.Lock() - defer s.Unlock() - } - - if err := s.Send(req); err != nil { - return nil, err - } - - pid, err := s.GetPid() - if err != nil { - return nil, err - } - - var res [][]byte - -done: - for { - msgs, from, err := s.Receive() - if err != nil { - return nil, err - } - if from.Pid != PidKernel { - return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, PidKernel) - } - for _, m := range msgs { - if m.Header.Seq != req.Seq { - if sharedSocket { - continue - } - return nil, fmt.Errorf("Wrong Seq nr %d, expected %d", m.Header.Seq, req.Seq) - } - if m.Header.Pid != pid { - continue - } - if m.Header.Type == unix.NLMSG_DONE || m.Header.Type == unix.NLMSG_ERROR { - native := NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - if error == 0 { - break done - } - return nil, syscall.Errno(-error) - } - if resType != 0 && m.Header.Type != resType { - continue - } - res = append(res, m.Data) - if m.Header.Flags&unix.NLM_F_MULTI == 0 { - break done - } - } - } - return res, nil -} - -// Create a new netlink request from proto and flags -// Note the Len value will be inaccurate once data is added until -// the message is serialized -func NewNetlinkRequest(proto, flags int) *NetlinkRequest { - return &NetlinkRequest{ - NlMsghdr: unix.NlMsghdr{ - Len: uint32(unix.SizeofNlMsghdr), - Type: uint16(proto), - Flags: unix.NLM_F_REQUEST | uint16(flags), - Seq: atomic.AddUint32(&nextSeqNr, 1), - }, - } -} - -type NetlinkSocket struct { - fd int32 - lsa unix.SockaddrNetlink - sync.Mutex -} - -func getNetlinkSocket(protocol int) (*NetlinkSocket, error) { - fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW|unix.SOCK_CLOEXEC, protocol) - if err != nil { - return nil, err - } - s := &NetlinkSocket{ - fd: int32(fd), - } - s.lsa.Family = unix.AF_NETLINK - if err := unix.Bind(fd, &s.lsa); err != nil { - unix.Close(fd) - return nil, err - } - - return s, nil -} - -// GetNetlinkSocketAt opens a netlink socket in the network namespace newNs -// and positions the thread back into the network namespace specified by curNs, -// when done. If curNs is close, the function derives the current namespace and -// moves back into it when done. If newNs is close, the socket will be opened -// in the current network namespace. -func GetNetlinkSocketAt(newNs, curNs netns.NsHandle, protocol int) (*NetlinkSocket, error) { - c, err := executeInNetns(newNs, curNs) - if err != nil { - return nil, err - } - defer c() - return getNetlinkSocket(protocol) -} - -// executeInNetns sets execution of the code following this call to the -// network namespace newNs, then moves the thread back to curNs if open, -// otherwise to the current netns at the time the function was invoked -// In case of success, the caller is expected to execute the returned function -// at the end of the code that needs to be executed in the network namespace. -// Example: -// func jobAt(...) error { -// d, err := executeInNetns(...) -// if err != nil { return err} -// defer d() -// < code which needs to be executed in specific netns> -// } -// TODO: his function probably belongs to netns pkg. -func executeInNetns(newNs, curNs netns.NsHandle) (func(), error) { - var ( - err error - moveBack func(netns.NsHandle) error - closeNs func() error - unlockThd func() - ) - restore := func() { - // order matters - if moveBack != nil { - moveBack(curNs) - } - if closeNs != nil { - closeNs() - } - if unlockThd != nil { - unlockThd() - } - } - if newNs.IsOpen() { - runtime.LockOSThread() - unlockThd = runtime.UnlockOSThread - if !curNs.IsOpen() { - if curNs, err = netns.Get(); err != nil { - restore() - return nil, fmt.Errorf("could not get current namespace while creating netlink socket: %v", err) - } - closeNs = curNs.Close - } - if err := netns.Set(newNs); err != nil { - restore() - return nil, fmt.Errorf("failed to set into network namespace %d while creating netlink socket: %v", newNs, err) - } - moveBack = netns.Set - } - return restore, nil -} - -// Create a netlink socket with a given protocol (e.g. NETLINK_ROUTE) -// and subscribe it to multicast groups passed in variable argument list. -// Returns the netlink socket on which Receive() method can be called -// to retrieve the messages from the kernel. -func Subscribe(protocol int, groups ...uint) (*NetlinkSocket, error) { - fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW, protocol) - if err != nil { - return nil, err - } - s := &NetlinkSocket{ - fd: int32(fd), - } - s.lsa.Family = unix.AF_NETLINK - - for _, g := range groups { - s.lsa.Groups |= (1 << (g - 1)) - } - - if err := unix.Bind(fd, &s.lsa); err != nil { - unix.Close(fd) - return nil, err - } - - return s, nil -} - -// SubscribeAt works like Subscribe plus let's the caller choose the network -// namespace in which the socket would be opened (newNs). Then control goes back -// to curNs if open, otherwise to the netns at the time this function was called. -func SubscribeAt(newNs, curNs netns.NsHandle, protocol int, groups ...uint) (*NetlinkSocket, error) { - c, err := executeInNetns(newNs, curNs) - if err != nil { - return nil, err - } - defer c() - return Subscribe(protocol, groups...) -} - -func (s *NetlinkSocket) Close() { - fd := int(atomic.SwapInt32(&s.fd, -1)) - unix.Close(fd) -} - -func (s *NetlinkSocket) GetFd() int { - return int(atomic.LoadInt32(&s.fd)) -} - -func (s *NetlinkSocket) Send(request *NetlinkRequest) error { - fd := int(atomic.LoadInt32(&s.fd)) - if fd < 0 { - return fmt.Errorf("Send called on a closed socket") - } - if err := unix.Sendto(fd, request.Serialize(), 0, &s.lsa); err != nil { - return err - } - return nil -} - -func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, *unix.SockaddrNetlink, error) { - fd := int(atomic.LoadInt32(&s.fd)) - if fd < 0 { - return nil, nil, fmt.Errorf("Receive called on a closed socket") - } - var fromAddr *unix.SockaddrNetlink - var rb [RECEIVE_BUFFER_SIZE]byte - nr, from, err := unix.Recvfrom(fd, rb[:], 0) - if err != nil { - return nil, nil, err - } - fromAddr, ok := from.(*unix.SockaddrNetlink) - if !ok { - return nil, nil, fmt.Errorf("Error converting to netlink sockaddr") - } - if nr < unix.NLMSG_HDRLEN { - return nil, nil, fmt.Errorf("Got short response from netlink") - } - rb2 := make([]byte, nr) - copy(rb2, rb[:nr]) - nl, err := syscall.ParseNetlinkMessage(rb2) - if err != nil { - return nil, nil, err - } - return nl, fromAddr, nil -} - -// SetSendTimeout allows to set a send timeout on the socket -func (s *NetlinkSocket) SetSendTimeout(timeout *unix.Timeval) error { - // Set a send timeout of SOCKET_SEND_TIMEOUT, this will allow the Send to periodically unblock and avoid that a routine - // remains stuck on a send on a closed fd - return unix.SetsockoptTimeval(int(s.fd), unix.SOL_SOCKET, unix.SO_SNDTIMEO, timeout) -} - -// SetReceiveTimeout allows to set a receive timeout on the socket -func (s *NetlinkSocket) SetReceiveTimeout(timeout *unix.Timeval) error { - // Set a read timeout of SOCKET_READ_TIMEOUT, this will allow the Read to periodically unblock and avoid that a routine - // remains stuck on a recvmsg on a closed fd - return unix.SetsockoptTimeval(int(s.fd), unix.SOL_SOCKET, unix.SO_RCVTIMEO, timeout) -} - -func (s *NetlinkSocket) GetPid() (uint32, error) { - fd := int(atomic.LoadInt32(&s.fd)) - lsa, err := unix.Getsockname(fd) - if err != nil { - return 0, err - } - switch v := lsa.(type) { - case *unix.SockaddrNetlink: - return v.Pid, nil - } - return 0, fmt.Errorf("Wrong socket type") -} - -func ZeroTerminated(s string) []byte { - bytes := make([]byte, len(s)+1) - for i := 0; i < len(s); i++ { - bytes[i] = s[i] - } - bytes[len(s)] = 0 - return bytes -} - -func NonZeroTerminated(s string) []byte { - bytes := make([]byte, len(s)) - for i := 0; i < len(s); i++ { - bytes[i] = s[i] - } - return bytes -} - -func BytesToString(b []byte) string { - n := bytes.Index(b, []byte{0}) - return string(b[:n]) -} - -func Uint8Attr(v uint8) []byte { - return []byte{byte(v)} -} - -func Uint16Attr(v uint16) []byte { - native := NativeEndian() - bytes := make([]byte, 2) - native.PutUint16(bytes, v) - return bytes -} - -func Uint32Attr(v uint32) []byte { - native := NativeEndian() - bytes := make([]byte, 4) - native.PutUint32(bytes, v) - return bytes -} - -func Uint64Attr(v uint64) []byte { - native := NativeEndian() - bytes := make([]byte, 8) - native.PutUint64(bytes, v) - return bytes -} - -func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) { - var attrs []syscall.NetlinkRouteAttr - for len(b) >= unix.SizeofRtAttr { - a, vbuf, alen, err := netlinkRouteAttrAndValue(b) - if err != nil { - return nil, err - } - ra := syscall.NetlinkRouteAttr{Attr: syscall.RtAttr(*a), Value: vbuf[:int(a.Len)-unix.SizeofRtAttr]} - attrs = append(attrs, ra) - b = b[alen:] - } - return attrs, nil -} - -func netlinkRouteAttrAndValue(b []byte) (*unix.RtAttr, []byte, int, error) { - a := (*unix.RtAttr)(unsafe.Pointer(&b[0])) - if int(a.Len) < unix.SizeofRtAttr || int(a.Len) > len(b) { - return nil, nil, 0, unix.EINVAL - } - return a, b[unix.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil -} - -// SocketHandle contains the netlink socket and the associated -// sequence counter for a specific netlink family -type SocketHandle struct { - Seq uint32 - Socket *NetlinkSocket -} - -// Close closes the netlink socket -func (sh *SocketHandle) Close() { - if sh.Socket != nil { - sh.Socket.Close() - } -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go b/examples/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go deleted file mode 100644 index dfc0be6..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/nl_unspecified.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !linux - -package nl - -import "encoding/binary" - -var SupportedNlFamilies = []int{} - -func NativeEndian() binary.ByteOrder { - return nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/parse_attr.go b/examples/vendor/github.com/vishvananda/netlink/nl/parse_attr.go deleted file mode 100644 index 19eb8f2..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/parse_attr.go +++ /dev/null @@ -1,67 +0,0 @@ -package nl - -import ( - "encoding/binary" - "fmt" -) - -type Attribute struct { - Type uint16 - Value []byte -} - -func ParseAttributes(data []byte) <-chan Attribute { - native := NativeEndian() - result := make(chan Attribute) - - go func() { - i := 0 - for i+4 < len(data) { - length := int(native.Uint16(data[i : i+2])) - - result <- Attribute{ - Type: native.Uint16(data[i+2 : i+4]), - Value: data[i+4 : i+length], - } - i += rtaAlignOf(length) - } - close(result) - }() - - return result -} - -func PrintAttributes(data []byte) { - printAttributes(data, 0) -} - -func printAttributes(data []byte, level int) { - for attr := range ParseAttributes(data) { - for i := 0; i < level; i++ { - print("> ") - } - nested := attr.Type&NLA_F_NESTED != 0 - fmt.Printf("type=%d nested=%v len=%v %v\n", attr.Type&NLA_TYPE_MASK, nested, len(attr.Value), attr.Value) - if nested { - printAttributes(attr.Value, level+1) - } - } -} - -// Uint32 returns the uint32 value respecting the NET_BYTEORDER flag -func (attr *Attribute) Uint32() uint32 { - if attr.Type&NLA_F_NET_BYTEORDER != 0 { - return binary.BigEndian.Uint32(attr.Value) - } else { - return NativeEndian().Uint32(attr.Value) - } -} - -// Uint64 returns the uint64 value respecting the NET_BYTEORDER flag -func (attr *Attribute) Uint64() uint64 { - if attr.Type&NLA_F_NET_BYTEORDER != 0 { - return binary.BigEndian.Uint64(attr.Value) - } else { - return NativeEndian().Uint64(attr.Value) - } -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/rdma_link_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/rdma_link_linux.go deleted file mode 100644 index 1224b74..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/rdma_link_linux.go +++ /dev/null @@ -1,35 +0,0 @@ -package nl - -const ( - RDMA_NL_GET_CLIENT_SHIFT = 10 -) - -const ( - RDMA_NL_NLDEV = 5 -) - -const ( - RDMA_NLDEV_CMD_GET = 1 - RDMA_NLDEV_CMD_SET = 2 - RDMA_NLDEV_CMD_SYS_GET = 6 - RDMA_NLDEV_CMD_SYS_SET = 7 -) - -const ( - RDMA_NLDEV_ATTR_DEV_INDEX = 1 - RDMA_NLDEV_ATTR_DEV_NAME = 2 - RDMA_NLDEV_ATTR_PORT_INDEX = 3 - RDMA_NLDEV_ATTR_CAP_FLAGS = 4 - RDMA_NLDEV_ATTR_FW_VERSION = 5 - RDMA_NLDEV_ATTR_NODE_GUID = 6 - RDMA_NLDEV_ATTR_SYS_IMAGE_GUID = 7 - RDMA_NLDEV_ATTR_SUBNET_PREFIX = 8 - RDMA_NLDEV_ATTR_LID = 9 - RDMA_NLDEV_ATTR_SM_LID = 10 - RDMA_NLDEV_ATTR_LMC = 11 - RDMA_NLDEV_ATTR_PORT_STATE = 12 - RDMA_NLDEV_ATTR_PORT_PHYS_STATE = 13 - RDMA_NLDEV_ATTR_DEV_NODE_TYPE = 14 - RDMA_NLDEV_SYS_ATTR_NETNS_MODE = 66 - RDMA_NLDEV_NET_NS_FD = 68 -) diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/route_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/route_linux.go deleted file mode 100644 index 03c1900..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/route_linux.go +++ /dev/null @@ -1,107 +0,0 @@ -package nl - -import ( - "unsafe" - - "golang.org/x/sys/unix" -) - -type RtMsg struct { - unix.RtMsg -} - -func NewRtMsg() *RtMsg { - return &RtMsg{ - RtMsg: unix.RtMsg{ - Table: unix.RT_TABLE_MAIN, - Scope: unix.RT_SCOPE_UNIVERSE, - Protocol: unix.RTPROT_BOOT, - Type: unix.RTN_UNICAST, - }, - } -} - -func NewRtDelMsg() *RtMsg { - return &RtMsg{ - RtMsg: unix.RtMsg{ - Table: unix.RT_TABLE_MAIN, - Scope: unix.RT_SCOPE_NOWHERE, - }, - } -} - -func (msg *RtMsg) Len() int { - return unix.SizeofRtMsg -} - -func DeserializeRtMsg(b []byte) *RtMsg { - return (*RtMsg)(unsafe.Pointer(&b[0:unix.SizeofRtMsg][0])) -} - -func (msg *RtMsg) Serialize() []byte { - return (*(*[unix.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:] -} - -type RtNexthop struct { - unix.RtNexthop - Children []NetlinkRequestData -} - -func DeserializeRtNexthop(b []byte) *RtNexthop { - return (*RtNexthop)(unsafe.Pointer(&b[0:unix.SizeofRtNexthop][0])) -} - -func (msg *RtNexthop) Len() int { - if len(msg.Children) == 0 { - return unix.SizeofRtNexthop - } - - l := 0 - for _, child := range msg.Children { - l += rtaAlignOf(child.Len()) - } - l += unix.SizeofRtNexthop - return rtaAlignOf(l) -} - -func (msg *RtNexthop) Serialize() []byte { - length := msg.Len() - msg.RtNexthop.Len = uint16(length) - buf := make([]byte, length) - copy(buf, (*(*[unix.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:]) - next := rtaAlignOf(unix.SizeofRtNexthop) - if len(msg.Children) > 0 { - for _, child := range msg.Children { - childBuf := child.Serialize() - copy(buf[next:], childBuf) - next += rtaAlignOf(len(childBuf)) - } - } - return buf -} - -type RtGenMsg struct { - unix.RtGenmsg -} - -func NewRtGenMsg() *RtGenMsg { - return &RtGenMsg{ - RtGenmsg: unix.RtGenmsg{ - Family: unix.AF_UNSPEC, - }, - } -} - -func (msg *RtGenMsg) Len() int { - return rtaAlignOf(unix.SizeofRtGenmsg) -} - -func DeserializeRtGenMsg(b []byte) *RtGenMsg { - return &RtGenMsg{RtGenmsg: unix.RtGenmsg{Family: b[0]}} -} - -func (msg *RtGenMsg) Serialize() []byte { - out := make([]byte, msg.Len()) - out[0] = msg.Family - return out -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/seg6_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/seg6_linux.go deleted file mode 100644 index 5774cbb..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/seg6_linux.go +++ /dev/null @@ -1,154 +0,0 @@ -package nl - -import ( - "errors" - "fmt" - "net" -) - -type IPv6SrHdr struct { - nextHdr uint8 - hdrLen uint8 - routingType uint8 - segmentsLeft uint8 - firstSegment uint8 - flags uint8 - reserved uint16 - - Segments []net.IP -} - -func (s1 *IPv6SrHdr) Equal(s2 IPv6SrHdr) bool { - if len(s1.Segments) != len(s2.Segments) { - return false - } - for i := range s1.Segments { - if s1.Segments[i].Equal(s2.Segments[i]) != true { - return false - } - } - return s1.nextHdr == s2.nextHdr && - s1.hdrLen == s2.hdrLen && - s1.routingType == s2.routingType && - s1.segmentsLeft == s2.segmentsLeft && - s1.firstSegment == s2.firstSegment && - s1.flags == s2.flags - // reserved doesn't need to be identical. -} - -// seg6 encap mode -const ( - SEG6_IPTUN_MODE_INLINE = iota - SEG6_IPTUN_MODE_ENCAP -) - -// number of nested RTATTR -// from include/uapi/linux/seg6_iptunnel.h -const ( - SEG6_IPTUNNEL_UNSPEC = iota - SEG6_IPTUNNEL_SRH - __SEG6_IPTUNNEL_MAX -) -const ( - SEG6_IPTUNNEL_MAX = __SEG6_IPTUNNEL_MAX - 1 -) - -func EncodeSEG6Encap(mode int, segments []net.IP) ([]byte, error) { - nsegs := len(segments) // nsegs: number of segments - if nsegs == 0 { - return nil, errors.New("EncodeSEG6Encap: No Segment in srh") - } - b := make([]byte, 12, 12+len(segments)*16) - native := NativeEndian() - native.PutUint32(b, uint32(mode)) - b[4] = 0 // srh.nextHdr (0 when calling netlink) - b[5] = uint8(16 * nsegs >> 3) // srh.hdrLen (in 8-octets unit) - b[6] = IPV6_SRCRT_TYPE_4 // srh.routingType (assigned by IANA) - b[7] = uint8(nsegs - 1) // srh.segmentsLeft - b[8] = uint8(nsegs - 1) // srh.firstSegment - b[9] = 0 // srh.flags (SR6_FLAG1_HMAC for srh_hmac) - // srh.reserved: Defined as "Tag" in draft-ietf-6man-segment-routing-header-07 - native.PutUint16(b[10:], 0) // srh.reserved - for _, netIP := range segments { - b = append(b, netIP...) // srh.Segments - } - return b, nil -} - -func DecodeSEG6Encap(buf []byte) (int, []net.IP, error) { - native := NativeEndian() - mode := int(native.Uint32(buf)) - srh := IPv6SrHdr{ - nextHdr: buf[4], - hdrLen: buf[5], - routingType: buf[6], - segmentsLeft: buf[7], - firstSegment: buf[8], - flags: buf[9], - reserved: native.Uint16(buf[10:12]), - } - buf = buf[12:] - if len(buf)%16 != 0 { - err := fmt.Errorf("DecodeSEG6Encap: error parsing Segment List (buf len: %d)\n", len(buf)) - return mode, nil, err - } - for len(buf) > 0 { - srh.Segments = append(srh.Segments, net.IP(buf[:16])) - buf = buf[16:] - } - return mode, srh.Segments, nil -} - -func DecodeSEG6Srh(buf []byte) ([]net.IP, error) { - native := NativeEndian() - srh := IPv6SrHdr{ - nextHdr: buf[0], - hdrLen: buf[1], - routingType: buf[2], - segmentsLeft: buf[3], - firstSegment: buf[4], - flags: buf[5], - reserved: native.Uint16(buf[6:8]), - } - buf = buf[8:] - if len(buf)%16 != 0 { - err := fmt.Errorf("DecodeSEG6Srh: error parsing Segment List (buf len: %d)", len(buf)) - return nil, err - } - for len(buf) > 0 { - srh.Segments = append(srh.Segments, net.IP(buf[:16])) - buf = buf[16:] - } - return srh.Segments, nil -} -func EncodeSEG6Srh(segments []net.IP) ([]byte, error) { - nsegs := len(segments) // nsegs: number of segments - if nsegs == 0 { - return nil, errors.New("EncodeSEG6Srh: No Segments") - } - b := make([]byte, 8, 8+len(segments)*16) - native := NativeEndian() - b[0] = 0 // srh.nextHdr (0 when calling netlink) - b[1] = uint8(16 * nsegs >> 3) // srh.hdrLen (in 8-octets unit) - b[2] = IPV6_SRCRT_TYPE_4 // srh.routingType (assigned by IANA) - b[3] = uint8(nsegs - 1) // srh.segmentsLeft - b[4] = uint8(nsegs - 1) // srh.firstSegment - b[5] = 0 // srh.flags (SR6_FLAG1_HMAC for srh_hmac) - // srh.reserved: Defined as "Tag" in draft-ietf-6man-segment-routing-header-07 - native.PutUint16(b[6:], 0) // srh.reserved - for _, netIP := range segments { - b = append(b, netIP...) // srh.Segments - } - return b, nil -} - -// Helper functions -func SEG6EncapModeString(mode int) string { - switch mode { - case SEG6_IPTUN_MODE_INLINE: - return "inline" - case SEG6_IPTUN_MODE_ENCAP: - return "encap" - } - return "unknown" -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/seg6local_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/seg6local_linux.go deleted file mode 100644 index 1500177..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/seg6local_linux.go +++ /dev/null @@ -1,76 +0,0 @@ -package nl - -import () - -// seg6local parameters -const ( - SEG6_LOCAL_UNSPEC = iota - SEG6_LOCAL_ACTION - SEG6_LOCAL_SRH - SEG6_LOCAL_TABLE - SEG6_LOCAL_NH4 - SEG6_LOCAL_NH6 - SEG6_LOCAL_IIF - SEG6_LOCAL_OIF - __SEG6_LOCAL_MAX -) -const ( - SEG6_LOCAL_MAX = __SEG6_LOCAL_MAX -) - -// seg6local actions -const ( - SEG6_LOCAL_ACTION_END = iota + 1 // 1 - SEG6_LOCAL_ACTION_END_X // 2 - SEG6_LOCAL_ACTION_END_T // 3 - SEG6_LOCAL_ACTION_END_DX2 // 4 - SEG6_LOCAL_ACTION_END_DX6 // 5 - SEG6_LOCAL_ACTION_END_DX4 // 6 - SEG6_LOCAL_ACTION_END_DT6 // 7 - SEG6_LOCAL_ACTION_END_DT4 // 8 - SEG6_LOCAL_ACTION_END_B6 // 9 - SEG6_LOCAL_ACTION_END_B6_ENCAPS // 10 - SEG6_LOCAL_ACTION_END_BM // 11 - SEG6_LOCAL_ACTION_END_S // 12 - SEG6_LOCAL_ACTION_END_AS // 13 - SEG6_LOCAL_ACTION_END_AM // 14 - __SEG6_LOCAL_ACTION_MAX -) -const ( - SEG6_LOCAL_ACTION_MAX = __SEG6_LOCAL_ACTION_MAX - 1 -) - -// Helper functions -func SEG6LocalActionString(action int) string { - switch action { - case SEG6_LOCAL_ACTION_END: - return "End" - case SEG6_LOCAL_ACTION_END_X: - return "End.X" - case SEG6_LOCAL_ACTION_END_T: - return "End.T" - case SEG6_LOCAL_ACTION_END_DX2: - return "End.DX2" - case SEG6_LOCAL_ACTION_END_DX6: - return "End.DX6" - case SEG6_LOCAL_ACTION_END_DX4: - return "End.DX4" - case SEG6_LOCAL_ACTION_END_DT6: - return "End.DT6" - case SEG6_LOCAL_ACTION_END_DT4: - return "End.DT4" - case SEG6_LOCAL_ACTION_END_B6: - return "End.B6" - case SEG6_LOCAL_ACTION_END_B6_ENCAPS: - return "End.B6.Encaps" - case SEG6_LOCAL_ACTION_END_BM: - return "End.BM" - case SEG6_LOCAL_ACTION_END_S: - return "End.S" - case SEG6_LOCAL_ACTION_END_AS: - return "End.AS" - case SEG6_LOCAL_ACTION_END_AM: - return "End.AM" - } - return "unknown" -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/syscall.go b/examples/vendor/github.com/vishvananda/netlink/nl/syscall.go deleted file mode 100644 index 4a01e6e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/syscall.go +++ /dev/null @@ -1,76 +0,0 @@ -package nl - -// syscall package lack of rule atributes type. -// Thus there are defined below -const ( - FRA_UNSPEC = iota - FRA_DST /* destination address */ - FRA_SRC /* source address */ - FRA_IIFNAME /* interface name */ - FRA_GOTO /* target to jump to (FR_ACT_GOTO) */ - FRA_UNUSED2 - FRA_PRIORITY /* priority/preference */ - FRA_UNUSED3 - FRA_UNUSED4 - FRA_UNUSED5 - FRA_FWMARK /* mark */ - FRA_FLOW /* flow/class id */ - FRA_TUN_ID - FRA_SUPPRESS_IFGROUP - FRA_SUPPRESS_PREFIXLEN - FRA_TABLE /* Extended table id */ - FRA_FWMASK /* mask for netfilter mark */ - FRA_OIFNAME - FRA_PAD - FRA_L3MDEV /* iif or oif is l3mdev goto its table */ - FRA_UID_RANGE /* UID range */ - FRA_PROTOCOL /* Originator of the rule */ - FRA_IP_PROTO /* ip proto */ - FRA_SPORT_RANGE /* sport */ - FRA_DPORT_RANGE /* dport */ -) - -// ip rule netlink request types -const ( - FR_ACT_UNSPEC = iota - FR_ACT_TO_TBL /* Pass to fixed table */ - FR_ACT_GOTO /* Jump to another rule */ - FR_ACT_NOP /* No operation */ - FR_ACT_RES3 - FR_ACT_RES4 - FR_ACT_BLACKHOLE /* Drop without notification */ - FR_ACT_UNREACHABLE /* Drop with ENETUNREACH */ - FR_ACT_PROHIBIT /* Drop with EACCES */ -) - -// socket diags related -const ( - SOCK_DIAG_BY_FAMILY = 20 /* linux.sock_diag.h */ - TCPDIAG_NOCOOKIE = 0xFFFFFFFF /* TCPDIAG_NOCOOKIE in net/ipv4/tcp_diag.h*/ -) - -// RTA_ENCAP subtype -const ( - MPLS_IPTUNNEL_UNSPEC = iota - MPLS_IPTUNNEL_DST -) - -// light weight tunnel encap types -const ( - LWTUNNEL_ENCAP_NONE = iota - LWTUNNEL_ENCAP_MPLS - LWTUNNEL_ENCAP_IP - LWTUNNEL_ENCAP_ILA - LWTUNNEL_ENCAP_IP6 - LWTUNNEL_ENCAP_SEG6 - LWTUNNEL_ENCAP_BPF - LWTUNNEL_ENCAP_SEG6_LOCAL -) - -// routing header types -const ( - IPV6_SRCRT_STRICT = 0x01 // Deprecated; will be removed - IPV6_SRCRT_TYPE_0 = 0 // Deprecated; will be removed - IPV6_SRCRT_TYPE_2 = 2 // IPv6 type 2 Routing Header - IPV6_SRCRT_TYPE_4 = 4 // Segment Routing with IPv6 -) diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/tc_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/tc_linux.go deleted file mode 100644 index c24d53e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/tc_linux.go +++ /dev/null @@ -1,983 +0,0 @@ -package nl - -import ( - "encoding/binary" - "unsafe" -) - -// LinkLayer -const ( - LINKLAYER_UNSPEC = iota - LINKLAYER_ETHERNET - LINKLAYER_ATM -) - -// ATM -const ( - ATM_CELL_PAYLOAD = 48 - ATM_CELL_SIZE = 53 -) - -const TC_LINKLAYER_MASK = 0x0F - -// Police -const ( - TCA_POLICE_UNSPEC = iota - TCA_POLICE_TBF - TCA_POLICE_RATE - TCA_POLICE_PEAKRATE - TCA_POLICE_AVRATE - TCA_POLICE_RESULT - TCA_POLICE_MAX = TCA_POLICE_RESULT -) - -// Message types -const ( - TCA_UNSPEC = iota - TCA_KIND - TCA_OPTIONS - TCA_STATS - TCA_XSTATS - TCA_RATE - TCA_FCNT - TCA_STATS2 - TCA_STAB - TCA_MAX = TCA_STAB -) - -const ( - TCA_ACT_TAB = 1 - TCAA_MAX = 1 -) - -const ( - TCA_ACT_UNSPEC = iota - TCA_ACT_KIND - TCA_ACT_OPTIONS - TCA_ACT_INDEX - TCA_ACT_STATS - TCA_ACT_MAX -) - -const ( - TCA_PRIO_UNSPEC = iota - TCA_PRIO_MQ - TCA_PRIO_MAX = TCA_PRIO_MQ -) - -const ( - TCA_STATS_UNSPEC = iota - TCA_STATS_BASIC - TCA_STATS_RATE_EST - TCA_STATS_QUEUE - TCA_STATS_APP - TCA_STATS_MAX = TCA_STATS_APP -) - -const ( - SizeofTcMsg = 0x14 - SizeofTcActionMsg = 0x04 - SizeofTcPrioMap = 0x14 - SizeofTcRateSpec = 0x0c - SizeofTcNetemQopt = 0x18 - SizeofTcNetemCorr = 0x0c - SizeofTcNetemReorder = 0x08 - SizeofTcNetemCorrupt = 0x08 - SizeofTcTbfQopt = 2*SizeofTcRateSpec + 0x0c - SizeofTcHtbCopt = 2*SizeofTcRateSpec + 0x14 - SizeofTcHtbGlob = 0x14 - SizeofTcU32Key = 0x10 - SizeofTcU32Sel = 0x10 // without keys - SizeofTcGen = 0x14 - SizeofTcConnmark = SizeofTcGen + 0x04 - SizeofTcMirred = SizeofTcGen + 0x08 - SizeofTcTunnelKey = SizeofTcGen + 0x04 - SizeofTcSkbEdit = SizeofTcGen - SizeofTcPolice = 2*SizeofTcRateSpec + 0x20 - SizeofTcSfqQopt = 0x0b - SizeofTcSfqRedStats = 0x18 - SizeofTcSfqQoptV1 = SizeofTcSfqQopt + SizeofTcSfqRedStats + 0x1c -) - -// struct tcmsg { -// unsigned char tcm_family; -// unsigned char tcm__pad1; -// unsigned short tcm__pad2; -// int tcm_ifindex; -// __u32 tcm_handle; -// __u32 tcm_parent; -// __u32 tcm_info; -// }; - -type TcMsg struct { - Family uint8 - Pad [3]byte - Ifindex int32 - Handle uint32 - Parent uint32 - Info uint32 -} - -func (msg *TcMsg) Len() int { - return SizeofTcMsg -} - -func DeserializeTcMsg(b []byte) *TcMsg { - return (*TcMsg)(unsafe.Pointer(&b[0:SizeofTcMsg][0])) -} - -func (x *TcMsg) Serialize() []byte { - return (*(*[SizeofTcMsg]byte)(unsafe.Pointer(x)))[:] -} - -// struct tcamsg { -// unsigned char tca_family; -// unsigned char tca__pad1; -// unsigned short tca__pad2; -// }; - -type TcActionMsg struct { - Family uint8 - Pad [3]byte -} - -func (msg *TcActionMsg) Len() int { - return SizeofTcActionMsg -} - -func DeserializeTcActionMsg(b []byte) *TcActionMsg { - return (*TcActionMsg)(unsafe.Pointer(&b[0:SizeofTcActionMsg][0])) -} - -func (x *TcActionMsg) Serialize() []byte { - return (*(*[SizeofTcActionMsg]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TC_PRIO_MAX = 15 -) - -// struct tc_prio_qopt { -// int bands; /* Number of bands */ -// __u8 priomap[TC_PRIO_MAX+1]; /* Map: logical priority -> PRIO band */ -// }; - -type TcPrioMap struct { - Bands int32 - Priomap [TC_PRIO_MAX + 1]uint8 -} - -func (msg *TcPrioMap) Len() int { - return SizeofTcPrioMap -} - -func DeserializeTcPrioMap(b []byte) *TcPrioMap { - return (*TcPrioMap)(unsafe.Pointer(&b[0:SizeofTcPrioMap][0])) -} - -func (x *TcPrioMap) Serialize() []byte { - return (*(*[SizeofTcPrioMap]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_TBF_UNSPEC = iota - TCA_TBF_PARMS - TCA_TBF_RTAB - TCA_TBF_PTAB - TCA_TBF_RATE64 - TCA_TBF_PRATE64 - TCA_TBF_BURST - TCA_TBF_PBURST - TCA_TBF_MAX = TCA_TBF_PBURST -) - -// struct tc_ratespec { -// unsigned char cell_log; -// __u8 linklayer; /* lower 4 bits */ -// unsigned short overhead; -// short cell_align; -// unsigned short mpu; -// __u32 rate; -// }; - -type TcRateSpec struct { - CellLog uint8 - Linklayer uint8 - Overhead uint16 - CellAlign int16 - Mpu uint16 - Rate uint32 -} - -func (msg *TcRateSpec) Len() int { - return SizeofTcRateSpec -} - -func DeserializeTcRateSpec(b []byte) *TcRateSpec { - return (*TcRateSpec)(unsafe.Pointer(&b[0:SizeofTcRateSpec][0])) -} - -func (x *TcRateSpec) Serialize() []byte { - return (*(*[SizeofTcRateSpec]byte)(unsafe.Pointer(x)))[:] -} - -/** -* NETEM - */ - -const ( - TCA_NETEM_UNSPEC = iota - TCA_NETEM_CORR - TCA_NETEM_DELAY_DIST - TCA_NETEM_REORDER - TCA_NETEM_CORRUPT - TCA_NETEM_LOSS - TCA_NETEM_RATE - TCA_NETEM_ECN - TCA_NETEM_RATE64 - TCA_NETEM_MAX = TCA_NETEM_RATE64 -) - -// struct tc_netem_qopt { -// __u32 latency; /* added delay (us) */ -// __u32 limit; /* fifo limit (packets) */ -// __u32 loss; /* random packet loss (0=none ~0=100%) */ -// __u32 gap; /* re-ordering gap (0 for none) */ -// __u32 duplicate; /* random packet dup (0=none ~0=100%) */ -// __u32 jitter; /* random jitter in latency (us) */ -// }; - -type TcNetemQopt struct { - Latency uint32 - Limit uint32 - Loss uint32 - Gap uint32 - Duplicate uint32 - Jitter uint32 -} - -func (msg *TcNetemQopt) Len() int { - return SizeofTcNetemQopt -} - -func DeserializeTcNetemQopt(b []byte) *TcNetemQopt { - return (*TcNetemQopt)(unsafe.Pointer(&b[0:SizeofTcNetemQopt][0])) -} - -func (x *TcNetemQopt) Serialize() []byte { - return (*(*[SizeofTcNetemQopt]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_netem_corr { -// __u32 delay_corr; /* delay correlation */ -// __u32 loss_corr; /* packet loss correlation */ -// __u32 dup_corr; /* duplicate correlation */ -// }; - -type TcNetemCorr struct { - DelayCorr uint32 - LossCorr uint32 - DupCorr uint32 -} - -func (msg *TcNetemCorr) Len() int { - return SizeofTcNetemCorr -} - -func DeserializeTcNetemCorr(b []byte) *TcNetemCorr { - return (*TcNetemCorr)(unsafe.Pointer(&b[0:SizeofTcNetemCorr][0])) -} - -func (x *TcNetemCorr) Serialize() []byte { - return (*(*[SizeofTcNetemCorr]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_netem_reorder { -// __u32 probability; -// __u32 correlation; -// }; - -type TcNetemReorder struct { - Probability uint32 - Correlation uint32 -} - -func (msg *TcNetemReorder) Len() int { - return SizeofTcNetemReorder -} - -func DeserializeTcNetemReorder(b []byte) *TcNetemReorder { - return (*TcNetemReorder)(unsafe.Pointer(&b[0:SizeofTcNetemReorder][0])) -} - -func (x *TcNetemReorder) Serialize() []byte { - return (*(*[SizeofTcNetemReorder]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_netem_corrupt { -// __u32 probability; -// __u32 correlation; -// }; - -type TcNetemCorrupt struct { - Probability uint32 - Correlation uint32 -} - -func (msg *TcNetemCorrupt) Len() int { - return SizeofTcNetemCorrupt -} - -func DeserializeTcNetemCorrupt(b []byte) *TcNetemCorrupt { - return (*TcNetemCorrupt)(unsafe.Pointer(&b[0:SizeofTcNetemCorrupt][0])) -} - -func (x *TcNetemCorrupt) Serialize() []byte { - return (*(*[SizeofTcNetemCorrupt]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_tbf_qopt { -// struct tc_ratespec rate; -// struct tc_ratespec peakrate; -// __u32 limit; -// __u32 buffer; -// __u32 mtu; -// }; - -type TcTbfQopt struct { - Rate TcRateSpec - Peakrate TcRateSpec - Limit uint32 - Buffer uint32 - Mtu uint32 -} - -func (msg *TcTbfQopt) Len() int { - return SizeofTcTbfQopt -} - -func DeserializeTcTbfQopt(b []byte) *TcTbfQopt { - return (*TcTbfQopt)(unsafe.Pointer(&b[0:SizeofTcTbfQopt][0])) -} - -func (x *TcTbfQopt) Serialize() []byte { - return (*(*[SizeofTcTbfQopt]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_HTB_UNSPEC = iota - TCA_HTB_PARMS - TCA_HTB_INIT - TCA_HTB_CTAB - TCA_HTB_RTAB - TCA_HTB_DIRECT_QLEN - TCA_HTB_RATE64 - TCA_HTB_CEIL64 - TCA_HTB_MAX = TCA_HTB_CEIL64 -) - -//struct tc_htb_opt { -// struct tc_ratespec rate; -// struct tc_ratespec ceil; -// __u32 buffer; -// __u32 cbuffer; -// __u32 quantum; -// __u32 level; /* out only */ -// __u32 prio; -//}; - -type TcHtbCopt struct { - Rate TcRateSpec - Ceil TcRateSpec - Buffer uint32 - Cbuffer uint32 - Quantum uint32 - Level uint32 - Prio uint32 -} - -func (msg *TcHtbCopt) Len() int { - return SizeofTcHtbCopt -} - -func DeserializeTcHtbCopt(b []byte) *TcHtbCopt { - return (*TcHtbCopt)(unsafe.Pointer(&b[0:SizeofTcHtbCopt][0])) -} - -func (x *TcHtbCopt) Serialize() []byte { - return (*(*[SizeofTcHtbCopt]byte)(unsafe.Pointer(x)))[:] -} - -type TcHtbGlob struct { - Version uint32 - Rate2Quantum uint32 - Defcls uint32 - Debug uint32 - DirectPkts uint32 -} - -func (msg *TcHtbGlob) Len() int { - return SizeofTcHtbGlob -} - -func DeserializeTcHtbGlob(b []byte) *TcHtbGlob { - return (*TcHtbGlob)(unsafe.Pointer(&b[0:SizeofTcHtbGlob][0])) -} - -func (x *TcHtbGlob) Serialize() []byte { - return (*(*[SizeofTcHtbGlob]byte)(unsafe.Pointer(x)))[:] -} - -// HFSC - -type Curve struct { - m1 uint32 - d uint32 - m2 uint32 -} - -type HfscCopt struct { - Rsc Curve - Fsc Curve - Usc Curve -} - -func (c *Curve) Attrs() (uint32, uint32, uint32) { - return c.m1, c.d, c.m2 -} - -func (c *Curve) Set(m1 uint32, d uint32, m2 uint32) { - c.m1 = m1 - c.d = d - c.m2 = m2 -} - -func DeserializeHfscCurve(b []byte) *Curve { - return &Curve{ - m1: binary.LittleEndian.Uint32(b[0:4]), - d: binary.LittleEndian.Uint32(b[4:8]), - m2: binary.LittleEndian.Uint32(b[8:12]), - } -} - -func SerializeHfscCurve(c *Curve) (b []byte) { - t := make([]byte, binary.MaxVarintLen32) - binary.LittleEndian.PutUint32(t, c.m1) - b = append(b, t[:4]...) - binary.LittleEndian.PutUint32(t, c.d) - b = append(b, t[:4]...) - binary.LittleEndian.PutUint32(t, c.m2) - b = append(b, t[:4]...) - return b -} - -type TcHfscOpt struct { - Defcls uint16 -} - -func (x *TcHfscOpt) Serialize() []byte { - return (*(*[2]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_U32_UNSPEC = iota - TCA_U32_CLASSID - TCA_U32_HASH - TCA_U32_LINK - TCA_U32_DIVISOR - TCA_U32_SEL - TCA_U32_POLICE - TCA_U32_ACT - TCA_U32_INDEV - TCA_U32_PCNT - TCA_U32_MARK - TCA_U32_MAX = TCA_U32_MARK -) - -// struct tc_u32_key { -// __be32 mask; -// __be32 val; -// int off; -// int offmask; -// }; - -type TcU32Key struct { - Mask uint32 // big endian - Val uint32 // big endian - Off int32 - OffMask int32 -} - -func (msg *TcU32Key) Len() int { - return SizeofTcU32Key -} - -func DeserializeTcU32Key(b []byte) *TcU32Key { - return (*TcU32Key)(unsafe.Pointer(&b[0:SizeofTcU32Key][0])) -} - -func (x *TcU32Key) Serialize() []byte { - return (*(*[SizeofTcU32Key]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_u32_sel { -// unsigned char flags; -// unsigned char offshift; -// unsigned char nkeys; -// -// __be16 offmask; -// __u16 off; -// short offoff; -// -// short hoff; -// __be32 hmask; -// struct tc_u32_key keys[0]; -// }; - -const ( - TC_U32_TERMINAL = 1 << iota - TC_U32_OFFSET = 1 << iota - TC_U32_VAROFFSET = 1 << iota - TC_U32_EAT = 1 << iota -) - -type TcU32Sel struct { - Flags uint8 - Offshift uint8 - Nkeys uint8 - Pad uint8 - Offmask uint16 // big endian - Off uint16 - Offoff int16 - Hoff int16 - Hmask uint32 // big endian - Keys []TcU32Key -} - -func (msg *TcU32Sel) Len() int { - return SizeofTcU32Sel + int(msg.Nkeys)*SizeofTcU32Key -} - -func DeserializeTcU32Sel(b []byte) *TcU32Sel { - x := &TcU32Sel{} - copy((*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:], b) - next := SizeofTcU32Sel - var i uint8 - for i = 0; i < x.Nkeys; i++ { - x.Keys = append(x.Keys, *DeserializeTcU32Key(b[next:])) - next += SizeofTcU32Key - } - return x -} - -func (x *TcU32Sel) Serialize() []byte { - // This can't just unsafe.cast because it must iterate through keys. - buf := make([]byte, x.Len()) - copy(buf, (*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:]) - next := SizeofTcU32Sel - for _, key := range x.Keys { - keyBuf := key.Serialize() - copy(buf[next:], keyBuf) - next += SizeofTcU32Key - } - return buf -} - -type TcGen struct { - Index uint32 - Capab uint32 - Action int32 - Refcnt int32 - Bindcnt int32 -} - -func (msg *TcGen) Len() int { - return SizeofTcGen -} - -func DeserializeTcGen(b []byte) *TcGen { - return (*TcGen)(unsafe.Pointer(&b[0:SizeofTcGen][0])) -} - -func (x *TcGen) Serialize() []byte { - return (*(*[SizeofTcGen]byte)(unsafe.Pointer(x)))[:] -} - -// #define tc_gen \ -// __u32 index; \ -// __u32 capab; \ -// int action; \ -// int refcnt; \ -// int bindcnt - -const ( - TCA_ACT_GACT = 5 -) - -const ( - TCA_GACT_UNSPEC = iota - TCA_GACT_TM - TCA_GACT_PARMS - TCA_GACT_PROB - TCA_GACT_MAX = TCA_GACT_PROB -) - -type TcGact TcGen - -const ( - TCA_ACT_BPF = 13 -) - -const ( - TCA_ACT_BPF_UNSPEC = iota - TCA_ACT_BPF_TM - TCA_ACT_BPF_PARMS - TCA_ACT_BPF_OPS_LEN - TCA_ACT_BPF_OPS - TCA_ACT_BPF_FD - TCA_ACT_BPF_NAME - TCA_ACT_BPF_MAX = TCA_ACT_BPF_NAME -) - -const ( - TCA_BPF_FLAG_ACT_DIRECT uint32 = 1 << iota -) - -const ( - TCA_BPF_UNSPEC = iota - TCA_BPF_ACT - TCA_BPF_POLICE - TCA_BPF_CLASSID - TCA_BPF_OPS_LEN - TCA_BPF_OPS - TCA_BPF_FD - TCA_BPF_NAME - TCA_BPF_FLAGS - TCA_BPF_FLAGS_GEN - TCA_BPF_TAG - TCA_BPF_ID - TCA_BPF_MAX = TCA_BPF_ID -) - -type TcBpf TcGen - -const ( - TCA_ACT_CONNMARK = 14 -) - -const ( - TCA_CONNMARK_UNSPEC = iota - TCA_CONNMARK_PARMS - TCA_CONNMARK_TM - TCA_CONNMARK_MAX = TCA_CONNMARK_TM -) - -// struct tc_connmark { -// tc_gen; -// __u16 zone; -// }; - -type TcConnmark struct { - TcGen - Zone uint16 -} - -func (msg *TcConnmark) Len() int { - return SizeofTcConnmark -} - -func DeserializeTcConnmark(b []byte) *TcConnmark { - return (*TcConnmark)(unsafe.Pointer(&b[0:SizeofTcConnmark][0])) -} - -func (x *TcConnmark) Serialize() []byte { - return (*(*[SizeofTcConnmark]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_ACT_MIRRED = 8 -) - -const ( - TCA_MIRRED_UNSPEC = iota - TCA_MIRRED_TM - TCA_MIRRED_PARMS - TCA_MIRRED_MAX = TCA_MIRRED_PARMS -) - -// struct tc_mirred { -// tc_gen; -// int eaction; /* one of IN/EGRESS_MIRROR/REDIR */ -// __u32 ifindex; /* ifindex of egress port */ -// }; - -type TcMirred struct { - TcGen - Eaction int32 - Ifindex uint32 -} - -func (msg *TcMirred) Len() int { - return SizeofTcMirred -} - -func DeserializeTcMirred(b []byte) *TcMirred { - return (*TcMirred)(unsafe.Pointer(&b[0:SizeofTcMirred][0])) -} - -func (x *TcMirred) Serialize() []byte { - return (*(*[SizeofTcMirred]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_TUNNEL_KEY_UNSPEC = iota - TCA_TUNNEL_KEY_TM - TCA_TUNNEL_KEY_PARMS - TCA_TUNNEL_KEY_ENC_IPV4_SRC - TCA_TUNNEL_KEY_ENC_IPV4_DST - TCA_TUNNEL_KEY_ENC_IPV6_SRC - TCA_TUNNEL_KEY_ENC_IPV6_DST - TCA_TUNNEL_KEY_ENC_KEY_ID - TCA_TUNNEL_KEY_PAD - TCA_TUNNEL_KEY_ENC_DST_PORT - TCA_TUNNEL_KEY_NO_CSUM - TCA_TUNNEL_KEY_ENC_OPTS - TCA_TUNNEL_KEY_ENC_TOS - TCA_TUNNEL_KEY_ENC_TTL - TCA_TUNNEL_KEY_MAX -) - -type TcTunnelKey struct { - TcGen - Action int32 -} - -func (x *TcTunnelKey) Len() int { - return SizeofTcTunnelKey -} - -func DeserializeTunnelKey(b []byte) *TcTunnelKey { - return (*TcTunnelKey)(unsafe.Pointer(&b[0:SizeofTcTunnelKey][0])) -} - -func (x *TcTunnelKey) Serialize() []byte { - return (*(*[SizeofTcTunnelKey]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_SKBEDIT_UNSPEC = iota - TCA_SKBEDIT_TM - TCA_SKBEDIT_PARMS - TCA_SKBEDIT_PRIORITY - TCA_SKBEDIT_QUEUE_MAPPING - TCA_SKBEDIT_MARK - TCA_SKBEDIT_PAD - TCA_SKBEDIT_PTYPE - TCA_SKBEDIT_MAX = TCA_SKBEDIT_MARK -) - -type TcSkbEdit struct { - TcGen -} - -func (x *TcSkbEdit) Len() int { - return SizeofTcSkbEdit -} - -func DeserializeSkbEdit(b []byte) *TcSkbEdit { - return (*TcSkbEdit)(unsafe.Pointer(&b[0:SizeofTcSkbEdit][0])) -} - -func (x *TcSkbEdit) Serialize() []byte { - return (*(*[SizeofTcSkbEdit]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_police { -// __u32 index; -// int action; -// __u32 limit; -// __u32 burst; -// __u32 mtu; -// struct tc_ratespec rate; -// struct tc_ratespec peakrate; -// int refcnt; -// int bindcnt; -// __u32 capab; -// }; - -type TcPolice struct { - Index uint32 - Action int32 - Limit uint32 - Burst uint32 - Mtu uint32 - Rate TcRateSpec - PeakRate TcRateSpec - Refcnt int32 - Bindcnt int32 - Capab uint32 -} - -func (msg *TcPolice) Len() int { - return SizeofTcPolice -} - -func DeserializeTcPolice(b []byte) *TcPolice { - return (*TcPolice)(unsafe.Pointer(&b[0:SizeofTcPolice][0])) -} - -func (x *TcPolice) Serialize() []byte { - return (*(*[SizeofTcPolice]byte)(unsafe.Pointer(x)))[:] -} - -const ( - TCA_FW_UNSPEC = iota - TCA_FW_CLASSID - TCA_FW_POLICE - TCA_FW_INDEV - TCA_FW_ACT - TCA_FW_MASK - TCA_FW_MAX = TCA_FW_MASK -) - -const ( - TCA_MATCHALL_UNSPEC = iota - TCA_MATCHALL_CLASSID - TCA_MATCHALL_ACT - TCA_MATCHALL_FLAGS -) - -const ( - TCA_FQ_UNSPEC = iota - TCA_FQ_PLIMIT // limit of total number of packets in queue - TCA_FQ_FLOW_PLIMIT // limit of packets per flow - TCA_FQ_QUANTUM // RR quantum - TCA_FQ_INITIAL_QUANTUM // RR quantum for new flow - TCA_FQ_RATE_ENABLE // enable/disable rate limiting - TCA_FQ_FLOW_DEFAULT_RATE // obsolete do not use - TCA_FQ_FLOW_MAX_RATE // per flow max rate - TCA_FQ_BUCKETS_LOG // log2(number of buckets) - TCA_FQ_FLOW_REFILL_DELAY // flow credit refill delay in usec - TCA_FQ_ORPHAN_MASK // mask applied to orphaned skb hashes - TCA_FQ_LOW_RATE_THRESHOLD // per packet delay under this rate -) - -const ( - TCA_FQ_CODEL_UNSPEC = iota - TCA_FQ_CODEL_TARGET - TCA_FQ_CODEL_LIMIT - TCA_FQ_CODEL_INTERVAL - TCA_FQ_CODEL_ECN - TCA_FQ_CODEL_FLOWS - TCA_FQ_CODEL_QUANTUM - TCA_FQ_CODEL_CE_THRESHOLD - TCA_FQ_CODEL_DROP_BATCH_SIZE - TCA_FQ_CODEL_MEMORY_LIMIT -) - -const ( - TCA_HFSC_UNSPEC = iota - TCA_HFSC_RSC - TCA_HFSC_FSC - TCA_HFSC_USC -) - -// struct tc_sfq_qopt { -// unsigned quantum; /* Bytes per round allocated to flow */ -// int perturb_period; /* Period of hash perturbation */ -// __u32 limit; /* Maximal packets in queue */ -// unsigned divisor; /* Hash divisor */ -// unsigned flows; /* Maximal number of flows */ -// }; - -type TcSfqQopt struct { - Quantum uint8 - Perturb int32 - Limit uint32 - Divisor uint8 - Flows uint8 -} - -func (x *TcSfqQopt) Len() int { - return SizeofTcSfqQopt -} - -func DeserializeTcSfqQopt(b []byte) *TcSfqQopt { - return (*TcSfqQopt)(unsafe.Pointer(&b[0:SizeofTcSfqQopt][0])) -} - -func (x *TcSfqQopt) Serialize() []byte { - return (*(*[SizeofTcSfqQopt]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_sfqred_stats { -// __u32 prob_drop; /* Early drops, below max threshold */ -// __u32 forced_drop; /* Early drops, after max threshold */ -// __u32 prob_mark; /* Marked packets, below max threshold */ -// __u32 forced_mark; /* Marked packets, after max threshold */ -// __u32 prob_mark_head; /* Marked packets, below max threshold */ -// __u32 forced_mark_head;/* Marked packets, after max threshold */ -// }; -type TcSfqRedStats struct { - ProbDrop uint32 - ForcedDrop uint32 - ProbMark uint32 - ForcedMark uint32 - ProbMarkHead uint32 - ForcedMarkHead uint32 -} - -func (x *TcSfqRedStats) Len() int { - return SizeofTcSfqRedStats -} - -func DeserializeTcSfqRedStats(b []byte) *TcSfqRedStats { - return (*TcSfqRedStats)(unsafe.Pointer(&b[0:SizeofTcSfqRedStats][0])) -} - -func (x *TcSfqRedStats) Serialize() []byte { - return (*(*[SizeofTcSfqRedStats]byte)(unsafe.Pointer(x)))[:] -} - -// struct tc_sfq_qopt_v1 { -// struct tc_sfq_qopt v0; -// unsigned int depth; /* max number of packets per flow */ -// unsigned int headdrop; -// /* SFQRED parameters */ -// __u32 limit; /* HARD maximal flow queue length (bytes) */ -// __u32 qth_min; /* Min average length threshold (bytes) */ -// __u32 qth_max; /* Max average length threshold (bytes) */ -// unsigned char Wlog; /* log(W) */ -// unsigned char Plog; /* log(P_max/(qth_max-qth_min)) */ -// unsigned char Scell_log; /* cell size for idle damping */ -// unsigned char flags; -// __u32 max_P; /* probability, high resolution */ -// /* SFQRED stats */ -// struct tc_sfqred_stats stats; -// }; -type TcSfqQoptV1 struct { - TcSfqQopt - Depth uint32 - HeadDrop uint32 - Limit uint32 - QthMin uint32 - QthMax uint32 - Wlog byte - Plog byte - ScellLog byte - Flags byte - MaxP uint32 - TcSfqRedStats -} - -func (x *TcSfqQoptV1) Len() int { - return SizeofTcSfqQoptV1 -} - -func DeserializeTcSfqQoptV1(b []byte) *TcSfqQoptV1 { - return (*TcSfqQoptV1)(unsafe.Pointer(&b[0:SizeofTcSfqQoptV1][0])) -} - -func (x *TcSfqQoptV1) Serialize() []byte { - return (*(*[SizeofTcSfqQoptV1]byte)(unsafe.Pointer(x)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go deleted file mode 100644 index dce9073..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go +++ /dev/null @@ -1,306 +0,0 @@ -package nl - -import ( - "bytes" - "net" - "unsafe" -) - -// Infinity for packet and byte counts -const ( - XFRM_INF = ^uint64(0) -) - -type XfrmMsgType uint8 - -type XfrmMsg interface { - Type() XfrmMsgType -} - -// Message Types -const ( - XFRM_MSG_BASE XfrmMsgType = 0x10 - XFRM_MSG_NEWSA = 0x10 - XFRM_MSG_DELSA = 0x11 - XFRM_MSG_GETSA = 0x12 - XFRM_MSG_NEWPOLICY = 0x13 - XFRM_MSG_DELPOLICY = 0x14 - XFRM_MSG_GETPOLICY = 0x15 - XFRM_MSG_ALLOCSPI = 0x16 - XFRM_MSG_ACQUIRE = 0x17 - XFRM_MSG_EXPIRE = 0x18 - XFRM_MSG_UPDPOLICY = 0x19 - XFRM_MSG_UPDSA = 0x1a - XFRM_MSG_POLEXPIRE = 0x1b - XFRM_MSG_FLUSHSA = 0x1c - XFRM_MSG_FLUSHPOLICY = 0x1d - XFRM_MSG_NEWAE = 0x1e - XFRM_MSG_GETAE = 0x1f - XFRM_MSG_REPORT = 0x20 - XFRM_MSG_MIGRATE = 0x21 - XFRM_MSG_NEWSADINFO = 0x22 - XFRM_MSG_GETSADINFO = 0x23 - XFRM_MSG_NEWSPDINFO = 0x24 - XFRM_MSG_GETSPDINFO = 0x25 - XFRM_MSG_MAPPING = 0x26 - XFRM_MSG_MAX = 0x26 - XFRM_NR_MSGTYPES = 0x17 -) - -// Attribute types -const ( - /* Netlink message attributes. */ - XFRMA_UNSPEC = iota - XFRMA_ALG_AUTH /* struct xfrm_algo */ - XFRMA_ALG_CRYPT /* struct xfrm_algo */ - XFRMA_ALG_COMP /* struct xfrm_algo */ - XFRMA_ENCAP /* struct xfrm_algo + struct xfrm_encap_tmpl */ - XFRMA_TMPL /* 1 or more struct xfrm_user_tmpl */ - XFRMA_SA /* struct xfrm_usersa_info */ - XFRMA_POLICY /* struct xfrm_userpolicy_info */ - XFRMA_SEC_CTX /* struct xfrm_sec_ctx */ - XFRMA_LTIME_VAL - XFRMA_REPLAY_VAL - XFRMA_REPLAY_THRESH - XFRMA_ETIMER_THRESH - XFRMA_SRCADDR /* xfrm_address_t */ - XFRMA_COADDR /* xfrm_address_t */ - XFRMA_LASTUSED /* unsigned long */ - XFRMA_POLICY_TYPE /* struct xfrm_userpolicy_type */ - XFRMA_MIGRATE - XFRMA_ALG_AEAD /* struct xfrm_algo_aead */ - XFRMA_KMADDRESS /* struct xfrm_user_kmaddress */ - XFRMA_ALG_AUTH_TRUNC /* struct xfrm_algo_auth */ - XFRMA_MARK /* struct xfrm_mark */ - XFRMA_TFCPAD /* __u32 */ - XFRMA_REPLAY_ESN_VAL /* struct xfrm_replay_esn */ - XFRMA_SA_EXTRA_FLAGS /* __u32 */ - XFRMA_PROTO /* __u8 */ - XFRMA_ADDRESS_FILTER /* struct xfrm_address_filter */ - XFRMA_PAD - XFRMA_OFFLOAD_DEV /* struct xfrm_state_offload */ - XFRMA_SET_MARK /* __u32 */ - XFRMA_SET_MARK_MASK /* __u32 */ - XFRMA_IF_ID /* __u32 */ - - XFRMA_MAX = iota - 1 -) - -const XFRMA_OUTPUT_MARK = XFRMA_SET_MARK - -const ( - SizeofXfrmAddress = 0x10 - SizeofXfrmSelector = 0x38 - SizeofXfrmLifetimeCfg = 0x40 - SizeofXfrmLifetimeCur = 0x20 - SizeofXfrmId = 0x18 - SizeofXfrmMark = 0x08 -) - -// Netlink groups -const ( - XFRMNLGRP_NONE = 0x0 - XFRMNLGRP_ACQUIRE = 0x1 - XFRMNLGRP_EXPIRE = 0x2 - XFRMNLGRP_SA = 0x3 - XFRMNLGRP_POLICY = 0x4 - XFRMNLGRP_AEVENTS = 0x5 - XFRMNLGRP_REPORT = 0x6 - XFRMNLGRP_MIGRATE = 0x7 - XFRMNLGRP_MAPPING = 0x8 - __XFRMNLGRP_MAX = 0x9 -) - -// typedef union { -// __be32 a4; -// __be32 a6[4]; -// } xfrm_address_t; - -type XfrmAddress [SizeofXfrmAddress]byte - -func (x *XfrmAddress) ToIP() net.IP { - var empty = [12]byte{} - ip := make(net.IP, net.IPv6len) - if bytes.Equal(x[4:16], empty[:]) { - ip[10] = 0xff - ip[11] = 0xff - copy(ip[12:16], x[0:4]) - } else { - copy(ip[:], x[:]) - } - return ip -} - -func (x *XfrmAddress) ToIPNet(prefixlen uint8) *net.IPNet { - ip := x.ToIP() - if GetIPFamily(ip) == FAMILY_V4 { - return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 32)} - } - return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 128)} -} - -func (x *XfrmAddress) FromIP(ip net.IP) { - var empty = [16]byte{} - if len(ip) < net.IPv4len { - copy(x[4:16], empty[:]) - } else if GetIPFamily(ip) == FAMILY_V4 { - copy(x[0:4], ip.To4()[0:4]) - copy(x[4:16], empty[:12]) - } else { - copy(x[0:16], ip.To16()[0:16]) - } -} - -func DeserializeXfrmAddress(b []byte) *XfrmAddress { - return (*XfrmAddress)(unsafe.Pointer(&b[0:SizeofXfrmAddress][0])) -} - -func (x *XfrmAddress) Serialize() []byte { - return (*(*[SizeofXfrmAddress]byte)(unsafe.Pointer(x)))[:] -} - -// struct xfrm_selector { -// xfrm_address_t daddr; -// xfrm_address_t saddr; -// __be16 dport; -// __be16 dport_mask; -// __be16 sport; -// __be16 sport_mask; -// __u16 family; -// __u8 prefixlen_d; -// __u8 prefixlen_s; -// __u8 proto; -// int ifindex; -// __kernel_uid32_t user; -// }; - -type XfrmSelector struct { - Daddr XfrmAddress - Saddr XfrmAddress - Dport uint16 // big endian - DportMask uint16 // big endian - Sport uint16 // big endian - SportMask uint16 // big endian - Family uint16 - PrefixlenD uint8 - PrefixlenS uint8 - Proto uint8 - Pad [3]byte - Ifindex int32 - User uint32 -} - -func (msg *XfrmSelector) Len() int { - return SizeofXfrmSelector -} - -func DeserializeXfrmSelector(b []byte) *XfrmSelector { - return (*XfrmSelector)(unsafe.Pointer(&b[0:SizeofXfrmSelector][0])) -} - -func (msg *XfrmSelector) Serialize() []byte { - return (*(*[SizeofXfrmSelector]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_lifetime_cfg { -// __u64 soft_byte_limit; -// __u64 hard_byte_limit; -// __u64 soft_packet_limit; -// __u64 hard_packet_limit; -// __u64 soft_add_expires_seconds; -// __u64 hard_add_expires_seconds; -// __u64 soft_use_expires_seconds; -// __u64 hard_use_expires_seconds; -// }; -// - -type XfrmLifetimeCfg struct { - SoftByteLimit uint64 - HardByteLimit uint64 - SoftPacketLimit uint64 - HardPacketLimit uint64 - SoftAddExpiresSeconds uint64 - HardAddExpiresSeconds uint64 - SoftUseExpiresSeconds uint64 - HardUseExpiresSeconds uint64 -} - -func (msg *XfrmLifetimeCfg) Len() int { - return SizeofXfrmLifetimeCfg -} - -func DeserializeXfrmLifetimeCfg(b []byte) *XfrmLifetimeCfg { - return (*XfrmLifetimeCfg)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCfg][0])) -} - -func (msg *XfrmLifetimeCfg) Serialize() []byte { - return (*(*[SizeofXfrmLifetimeCfg]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_lifetime_cur { -// __u64 bytes; -// __u64 packets; -// __u64 add_time; -// __u64 use_time; -// }; - -type XfrmLifetimeCur struct { - Bytes uint64 - Packets uint64 - AddTime uint64 - UseTime uint64 -} - -func (msg *XfrmLifetimeCur) Len() int { - return SizeofXfrmLifetimeCur -} - -func DeserializeXfrmLifetimeCur(b []byte) *XfrmLifetimeCur { - return (*XfrmLifetimeCur)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCur][0])) -} - -func (msg *XfrmLifetimeCur) Serialize() []byte { - return (*(*[SizeofXfrmLifetimeCur]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_id { -// xfrm_address_t daddr; -// __be32 spi; -// __u8 proto; -// }; - -type XfrmId struct { - Daddr XfrmAddress - Spi uint32 // big endian - Proto uint8 - Pad [3]byte -} - -func (msg *XfrmId) Len() int { - return SizeofXfrmId -} - -func DeserializeXfrmId(b []byte) *XfrmId { - return (*XfrmId)(unsafe.Pointer(&b[0:SizeofXfrmId][0])) -} - -func (msg *XfrmId) Serialize() []byte { - return (*(*[SizeofXfrmId]byte)(unsafe.Pointer(msg)))[:] -} - -type XfrmMark struct { - Value uint32 - Mask uint32 -} - -func (msg *XfrmMark) Len() int { - return SizeofXfrmMark -} - -func DeserializeXfrmMark(b []byte) *XfrmMark { - return (*XfrmMark)(unsafe.Pointer(&b[0:SizeofXfrmMark][0])) -} - -func (msg *XfrmMark) Serialize() []byte { - return (*(*[SizeofXfrmMark]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go deleted file mode 100644 index 715df4c..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_monitor_linux.go +++ /dev/null @@ -1,32 +0,0 @@ -package nl - -import ( - "unsafe" -) - -const ( - SizeofXfrmUserExpire = 0xe8 -) - -// struct xfrm_user_expire { -// struct xfrm_usersa_info state; -// __u8 hard; -// }; - -type XfrmUserExpire struct { - XfrmUsersaInfo XfrmUsersaInfo - Hard uint8 - Pad [7]byte -} - -func (msg *XfrmUserExpire) Len() int { - return SizeofXfrmUserExpire -} - -func DeserializeXfrmUserExpire(b []byte) *XfrmUserExpire { - return (*XfrmUserExpire)(unsafe.Pointer(&b[0:SizeofXfrmUserExpire][0])) -} - -func (msg *XfrmUserExpire) Serialize() []byte { - return (*(*[SizeofXfrmUserExpire]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go deleted file mode 100644 index 66f7e03..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go +++ /dev/null @@ -1,119 +0,0 @@ -package nl - -import ( - "unsafe" -) - -const ( - SizeofXfrmUserpolicyId = 0x40 - SizeofXfrmUserpolicyInfo = 0xa8 - SizeofXfrmUserTmpl = 0x40 -) - -// struct xfrm_userpolicy_id { -// struct xfrm_selector sel; -// __u32 index; -// __u8 dir; -// }; -// - -type XfrmUserpolicyId struct { - Sel XfrmSelector - Index uint32 - Dir uint8 - Pad [3]byte -} - -func (msg *XfrmUserpolicyId) Len() int { - return SizeofXfrmUserpolicyId -} - -func DeserializeXfrmUserpolicyId(b []byte) *XfrmUserpolicyId { - return (*XfrmUserpolicyId)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyId][0])) -} - -func (msg *XfrmUserpolicyId) Serialize() []byte { - return (*(*[SizeofXfrmUserpolicyId]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_userpolicy_info { -// struct xfrm_selector sel; -// struct xfrm_lifetime_cfg lft; -// struct xfrm_lifetime_cur curlft; -// __u32 priority; -// __u32 index; -// __u8 dir; -// __u8 action; -// #define XFRM_POLICY_ALLOW 0 -// #define XFRM_POLICY_BLOCK 1 -// __u8 flags; -// #define XFRM_POLICY_LOCALOK 1 /* Allow user to override global policy */ -// /* Automatically expand selector to include matching ICMP payloads. */ -// #define XFRM_POLICY_ICMP 2 -// __u8 share; -// }; - -type XfrmUserpolicyInfo struct { - Sel XfrmSelector - Lft XfrmLifetimeCfg - Curlft XfrmLifetimeCur - Priority uint32 - Index uint32 - Dir uint8 - Action uint8 - Flags uint8 - Share uint8 - Pad [4]byte -} - -func (msg *XfrmUserpolicyInfo) Len() int { - return SizeofXfrmUserpolicyInfo -} - -func DeserializeXfrmUserpolicyInfo(b []byte) *XfrmUserpolicyInfo { - return (*XfrmUserpolicyInfo)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyInfo][0])) -} - -func (msg *XfrmUserpolicyInfo) Serialize() []byte { - return (*(*[SizeofXfrmUserpolicyInfo]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_user_tmpl { -// struct xfrm_id id; -// __u16 family; -// xfrm_address_t saddr; -// __u32 reqid; -// __u8 mode; -// __u8 share; -// __u8 optional; -// __u32 aalgos; -// __u32 ealgos; -// __u32 calgos; -// } - -type XfrmUserTmpl struct { - XfrmId XfrmId - Family uint16 - Pad1 [2]byte - Saddr XfrmAddress - Reqid uint32 - Mode uint8 - Share uint8 - Optional uint8 - Pad2 byte - Aalgos uint32 - Ealgos uint32 - Calgos uint32 -} - -func (msg *XfrmUserTmpl) Len() int { - return SizeofXfrmUserTmpl -} - -func DeserializeXfrmUserTmpl(b []byte) *XfrmUserTmpl { - return (*XfrmUserTmpl)(unsafe.Pointer(&b[0:SizeofXfrmUserTmpl][0])) -} - -func (msg *XfrmUserTmpl) Serialize() []byte { - return (*(*[SizeofXfrmUserTmpl]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go b/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go deleted file mode 100644 index 43a947f..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go +++ /dev/null @@ -1,334 +0,0 @@ -package nl - -import ( - "unsafe" -) - -const ( - SizeofXfrmUsersaId = 0x18 - SizeofXfrmStats = 0x0c - SizeofXfrmUsersaInfo = 0xe0 - SizeofXfrmUserSpiInfo = 0xe8 - SizeofXfrmAlgo = 0x44 - SizeofXfrmAlgoAuth = 0x48 - SizeofXfrmAlgoAEAD = 0x48 - SizeofXfrmEncapTmpl = 0x18 - SizeofXfrmUsersaFlush = 0x1 - SizeofXfrmReplayStateEsn = 0x18 -) - -const ( - XFRM_STATE_NOECN = 1 - XFRM_STATE_DECAP_DSCP = 2 - XFRM_STATE_NOPMTUDISC = 4 - XFRM_STATE_WILDRECV = 8 - XFRM_STATE_ICMP = 16 - XFRM_STATE_AF_UNSPEC = 32 - XFRM_STATE_ALIGN4 = 64 - XFRM_STATE_ESN = 128 -) - -// struct xfrm_usersa_id { -// xfrm_address_t daddr; -// __be32 spi; -// __u16 family; -// __u8 proto; -// }; - -type XfrmUsersaId struct { - Daddr XfrmAddress - Spi uint32 // big endian - Family uint16 - Proto uint8 - Pad byte -} - -func (msg *XfrmUsersaId) Len() int { - return SizeofXfrmUsersaId -} - -func DeserializeXfrmUsersaId(b []byte) *XfrmUsersaId { - return (*XfrmUsersaId)(unsafe.Pointer(&b[0:SizeofXfrmUsersaId][0])) -} - -func (msg *XfrmUsersaId) Serialize() []byte { - return (*(*[SizeofXfrmUsersaId]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_stats { -// __u32 replay_window; -// __u32 replay; -// __u32 integrity_failed; -// }; - -type XfrmStats struct { - ReplayWindow uint32 - Replay uint32 - IntegrityFailed uint32 -} - -func (msg *XfrmStats) Len() int { - return SizeofXfrmStats -} - -func DeserializeXfrmStats(b []byte) *XfrmStats { - return (*XfrmStats)(unsafe.Pointer(&b[0:SizeofXfrmStats][0])) -} - -func (msg *XfrmStats) Serialize() []byte { - return (*(*[SizeofXfrmStats]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_usersa_info { -// struct xfrm_selector sel; -// struct xfrm_id id; -// xfrm_address_t saddr; -// struct xfrm_lifetime_cfg lft; -// struct xfrm_lifetime_cur curlft; -// struct xfrm_stats stats; -// __u32 seq; -// __u32 reqid; -// __u16 family; -// __u8 mode; /* XFRM_MODE_xxx */ -// __u8 replay_window; -// __u8 flags; -// #define XFRM_STATE_NOECN 1 -// #define XFRM_STATE_DECAP_DSCP 2 -// #define XFRM_STATE_NOPMTUDISC 4 -// #define XFRM_STATE_WILDRECV 8 -// #define XFRM_STATE_ICMP 16 -// #define XFRM_STATE_AF_UNSPEC 32 -// #define XFRM_STATE_ALIGN4 64 -// #define XFRM_STATE_ESN 128 -// }; -// -// #define XFRM_SA_XFLAG_DONT_ENCAP_DSCP 1 -// - -type XfrmUsersaInfo struct { - Sel XfrmSelector - Id XfrmId - Saddr XfrmAddress - Lft XfrmLifetimeCfg - Curlft XfrmLifetimeCur - Stats XfrmStats - Seq uint32 - Reqid uint32 - Family uint16 - Mode uint8 - ReplayWindow uint8 - Flags uint8 - Pad [7]byte -} - -func (msg *XfrmUsersaInfo) Len() int { - return SizeofXfrmUsersaInfo -} - -func DeserializeXfrmUsersaInfo(b []byte) *XfrmUsersaInfo { - return (*XfrmUsersaInfo)(unsafe.Pointer(&b[0:SizeofXfrmUsersaInfo][0])) -} - -func (msg *XfrmUsersaInfo) Serialize() []byte { - return (*(*[SizeofXfrmUsersaInfo]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_userspi_info { -// struct xfrm_usersa_info info; -// __u32 min; -// __u32 max; -// }; - -type XfrmUserSpiInfo struct { - XfrmUsersaInfo XfrmUsersaInfo - Min uint32 - Max uint32 -} - -func (msg *XfrmUserSpiInfo) Len() int { - return SizeofXfrmUserSpiInfo -} - -func DeserializeXfrmUserSpiInfo(b []byte) *XfrmUserSpiInfo { - return (*XfrmUserSpiInfo)(unsafe.Pointer(&b[0:SizeofXfrmUserSpiInfo][0])) -} - -func (msg *XfrmUserSpiInfo) Serialize() []byte { - return (*(*[SizeofXfrmUserSpiInfo]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_algo { -// char alg_name[64]; -// unsigned int alg_key_len; /* in bits */ -// char alg_key[0]; -// }; - -type XfrmAlgo struct { - AlgName [64]byte - AlgKeyLen uint32 - AlgKey []byte -} - -func (msg *XfrmAlgo) Len() int { - return SizeofXfrmAlgo + int(msg.AlgKeyLen/8) -} - -func DeserializeXfrmAlgo(b []byte) *XfrmAlgo { - ret := XfrmAlgo{} - copy(ret.AlgName[:], b[0:64]) - ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64])) - ret.AlgKey = b[68:ret.Len()] - return &ret -} - -func (msg *XfrmAlgo) Serialize() []byte { - b := make([]byte, msg.Len()) - copy(b[0:64], msg.AlgName[:]) - copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:]) - copy(b[68:msg.Len()], msg.AlgKey[:]) - return b -} - -// struct xfrm_algo_auth { -// char alg_name[64]; -// unsigned int alg_key_len; /* in bits */ -// unsigned int alg_trunc_len; /* in bits */ -// char alg_key[0]; -// }; - -type XfrmAlgoAuth struct { - AlgName [64]byte - AlgKeyLen uint32 - AlgTruncLen uint32 - AlgKey []byte -} - -func (msg *XfrmAlgoAuth) Len() int { - return SizeofXfrmAlgoAuth + int(msg.AlgKeyLen/8) -} - -func DeserializeXfrmAlgoAuth(b []byte) *XfrmAlgoAuth { - ret := XfrmAlgoAuth{} - copy(ret.AlgName[:], b[0:64]) - ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64])) - ret.AlgTruncLen = *(*uint32)(unsafe.Pointer(&b[68])) - ret.AlgKey = b[72:ret.Len()] - return &ret -} - -func (msg *XfrmAlgoAuth) Serialize() []byte { - b := make([]byte, msg.Len()) - copy(b[0:64], msg.AlgName[:]) - copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:]) - copy(b[68:72], (*(*[4]byte)(unsafe.Pointer(&msg.AlgTruncLen)))[:]) - copy(b[72:msg.Len()], msg.AlgKey[:]) - return b -} - -// struct xfrm_algo_aead { -// char alg_name[64]; -// unsigned int alg_key_len; /* in bits */ -// unsigned int alg_icv_len; /* in bits */ -// char alg_key[0]; -// } - -type XfrmAlgoAEAD struct { - AlgName [64]byte - AlgKeyLen uint32 - AlgICVLen uint32 - AlgKey []byte -} - -func (msg *XfrmAlgoAEAD) Len() int { - return SizeofXfrmAlgoAEAD + int(msg.AlgKeyLen/8) -} - -func DeserializeXfrmAlgoAEAD(b []byte) *XfrmAlgoAEAD { - ret := XfrmAlgoAEAD{} - copy(ret.AlgName[:], b[0:64]) - ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64])) - ret.AlgICVLen = *(*uint32)(unsafe.Pointer(&b[68])) - ret.AlgKey = b[72:ret.Len()] - return &ret -} - -func (msg *XfrmAlgoAEAD) Serialize() []byte { - b := make([]byte, msg.Len()) - copy(b[0:64], msg.AlgName[:]) - copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:]) - copy(b[68:72], (*(*[4]byte)(unsafe.Pointer(&msg.AlgICVLen)))[:]) - copy(b[72:msg.Len()], msg.AlgKey[:]) - return b -} - -// struct xfrm_encap_tmpl { -// __u16 encap_type; -// __be16 encap_sport; -// __be16 encap_dport; -// xfrm_address_t encap_oa; -// }; - -type XfrmEncapTmpl struct { - EncapType uint16 - EncapSport uint16 // big endian - EncapDport uint16 // big endian - Pad [2]byte - EncapOa XfrmAddress -} - -func (msg *XfrmEncapTmpl) Len() int { - return SizeofXfrmEncapTmpl -} - -func DeserializeXfrmEncapTmpl(b []byte) *XfrmEncapTmpl { - return (*XfrmEncapTmpl)(unsafe.Pointer(&b[0:SizeofXfrmEncapTmpl][0])) -} - -func (msg *XfrmEncapTmpl) Serialize() []byte { - return (*(*[SizeofXfrmEncapTmpl]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_usersa_flush { -// __u8 proto; -// }; - -type XfrmUsersaFlush struct { - Proto uint8 -} - -func (msg *XfrmUsersaFlush) Len() int { - return SizeofXfrmUsersaFlush -} - -func DeserializeXfrmUsersaFlush(b []byte) *XfrmUsersaFlush { - return (*XfrmUsersaFlush)(unsafe.Pointer(&b[0:SizeofXfrmUsersaFlush][0])) -} - -func (msg *XfrmUsersaFlush) Serialize() []byte { - return (*(*[SizeofXfrmUsersaFlush]byte)(unsafe.Pointer(msg)))[:] -} - -// struct xfrm_replay_state_esn { -// unsigned int bmp_len; -// __u32 oseq; -// __u32 seq; -// __u32 oseq_hi; -// __u32 seq_hi; -// __u32 replay_window; -// __u32 bmp[0]; -// }; - -type XfrmReplayStateEsn struct { - BmpLen uint32 - OSeq uint32 - Seq uint32 - OSeqHi uint32 - SeqHi uint32 - ReplayWindow uint32 - Bmp []uint32 -} - -func (msg *XfrmReplayStateEsn) Serialize() []byte { - // We deliberately do not pass Bmp, as it gets set by the kernel. - return (*(*[SizeofXfrmReplayStateEsn]byte)(unsafe.Pointer(msg)))[:] -} diff --git a/examples/vendor/github.com/vishvananda/netlink/order.go b/examples/vendor/github.com/vishvananda/netlink/order.go deleted file mode 100644 index e28e153..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/order.go +++ /dev/null @@ -1,32 +0,0 @@ -package netlink - -import ( - "encoding/binary" - - "github.com/vishvananda/netlink/nl" -) - -var ( - native = nl.NativeEndian() - networkOrder = binary.BigEndian -) - -func htonl(val uint32) []byte { - bytes := make([]byte, 4) - binary.BigEndian.PutUint32(bytes, val) - return bytes -} - -func htons(val uint16) []byte { - bytes := make([]byte, 2) - binary.BigEndian.PutUint16(bytes, val) - return bytes -} - -func ntohl(buf []byte) uint32 { - return binary.BigEndian.Uint32(buf) -} - -func ntohs(buf []byte) uint16 { - return binary.BigEndian.Uint16(buf) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/protinfo.go b/examples/vendor/github.com/vishvananda/netlink/protinfo.go deleted file mode 100644 index 60b23b3..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/protinfo.go +++ /dev/null @@ -1,62 +0,0 @@ -package netlink - -import ( - "strings" -) - -// Protinfo represents bridge flags from netlink. -type Protinfo struct { - Hairpin bool - Guard bool - FastLeave bool - RootBlock bool - Learning bool - Flood bool - ProxyArp bool - ProxyArpWiFi bool -} - -// String returns a list of enabled flags -func (prot *Protinfo) String() string { - if prot == nil { - return "" - } - - var boolStrings []string - if prot.Hairpin { - boolStrings = append(boolStrings, "Hairpin") - } - if prot.Guard { - boolStrings = append(boolStrings, "Guard") - } - if prot.FastLeave { - boolStrings = append(boolStrings, "FastLeave") - } - if prot.RootBlock { - boolStrings = append(boolStrings, "RootBlock") - } - if prot.Learning { - boolStrings = append(boolStrings, "Learning") - } - if prot.Flood { - boolStrings = append(boolStrings, "Flood") - } - if prot.ProxyArp { - boolStrings = append(boolStrings, "ProxyArp") - } - if prot.ProxyArpWiFi { - boolStrings = append(boolStrings, "ProxyArpWiFi") - } - return strings.Join(boolStrings, " ") -} - -func boolToByte(x bool) []byte { - if x { - return []byte{1} - } - return []byte{0} -} - -func byteToBool(x byte) bool { - return uint8(x) != 0 -} diff --git a/examples/vendor/github.com/vishvananda/netlink/protinfo_linux.go b/examples/vendor/github.com/vishvananda/netlink/protinfo_linux.go deleted file mode 100644 index 15b6512..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/protinfo_linux.go +++ /dev/null @@ -1,74 +0,0 @@ -package netlink - -import ( - "fmt" - "syscall" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -func LinkGetProtinfo(link Link) (Protinfo, error) { - return pkgHandle.LinkGetProtinfo(link) -} - -func (h *Handle) LinkGetProtinfo(link Link) (Protinfo, error) { - base := link.Attrs() - h.ensureIndex(base) - var pi Protinfo - req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP) - msg := nl.NewIfInfomsg(unix.AF_BRIDGE) - req.AddData(msg) - msgs, err := req.Execute(unix.NETLINK_ROUTE, 0) - if err != nil { - return pi, err - } - - for _, m := range msgs { - ans := nl.DeserializeIfInfomsg(m) - if int(ans.Index) != base.Index { - continue - } - attrs, err := nl.ParseRouteAttr(m[ans.Len():]) - if err != nil { - return pi, err - } - for _, attr := range attrs { - if attr.Attr.Type != unix.IFLA_PROTINFO|unix.NLA_F_NESTED { - continue - } - infos, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return pi, err - } - pi = parseProtinfo(infos) - - return pi, nil - } - } - return pi, fmt.Errorf("Device with index %d not found", base.Index) -} - -func parseProtinfo(infos []syscall.NetlinkRouteAttr) (pi Protinfo) { - for _, info := range infos { - switch info.Attr.Type { - case nl.IFLA_BRPORT_MODE: - pi.Hairpin = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_GUARD: - pi.Guard = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_FAST_LEAVE: - pi.FastLeave = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_PROTECT: - pi.RootBlock = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_LEARNING: - pi.Learning = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_UNICAST_FLOOD: - pi.Flood = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_PROXYARP: - pi.ProxyArp = byteToBool(info.Value[0]) - case nl.IFLA_BRPORT_PROXYARP_WIFI: - pi.ProxyArpWiFi = byteToBool(info.Value[0]) - } - } - return -} diff --git a/examples/vendor/github.com/vishvananda/netlink/qdisc.go b/examples/vendor/github.com/vishvananda/netlink/qdisc.go deleted file mode 100644 index 8418569..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/qdisc.go +++ /dev/null @@ -1,364 +0,0 @@ -package netlink - -import ( - "fmt" - "math" -) - -const ( - HANDLE_NONE = 0 - HANDLE_INGRESS = 0xFFFFFFF1 - HANDLE_CLSACT = HANDLE_INGRESS - HANDLE_ROOT = 0xFFFFFFFF - PRIORITY_MAP_LEN = 16 -) -const ( - HANDLE_MIN_INGRESS = 0xFFFFFFF2 - HANDLE_MIN_EGRESS = 0xFFFFFFF3 -) - -type Qdisc interface { - Attrs() *QdiscAttrs - Type() string -} - -// QdiscAttrs represents a netlink qdisc. A qdisc is associated with a link, -// has a handle, a parent and a refcnt. The root qdisc of a device should -// have parent == HANDLE_ROOT. -type QdiscAttrs struct { - LinkIndex int - Handle uint32 - Parent uint32 - Refcnt uint32 // read only -} - -func (q QdiscAttrs) String() string { - return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Refcnt: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Refcnt) -} - -func MakeHandle(major, minor uint16) uint32 { - return (uint32(major) << 16) | uint32(minor) -} - -func MajorMinor(handle uint32) (uint16, uint16) { - return uint16((handle & 0xFFFF0000) >> 16), uint16(handle & 0x0000FFFFF) -} - -func HandleStr(handle uint32) string { - switch handle { - case HANDLE_NONE: - return "none" - case HANDLE_INGRESS: - return "ingress" - case HANDLE_ROOT: - return "root" - default: - major, minor := MajorMinor(handle) - return fmt.Sprintf("%x:%x", major, minor) - } -} - -func Percentage2u32(percentage float32) uint32 { - // FIXME this is most likely not the best way to convert from % to uint32 - if percentage == 100 { - return math.MaxUint32 - } - return uint32(math.MaxUint32 * (percentage / 100)) -} - -// PfifoFast is the default qdisc created by the kernel if one has not -// been defined for the interface -type PfifoFast struct { - QdiscAttrs - Bands uint8 - PriorityMap [PRIORITY_MAP_LEN]uint8 -} - -func (qdisc *PfifoFast) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *PfifoFast) Type() string { - return "pfifo_fast" -} - -// Prio is a basic qdisc that works just like PfifoFast -type Prio struct { - QdiscAttrs - Bands uint8 - PriorityMap [PRIORITY_MAP_LEN]uint8 -} - -func NewPrio(attrs QdiscAttrs) *Prio { - return &Prio{ - QdiscAttrs: attrs, - Bands: 3, - PriorityMap: [PRIORITY_MAP_LEN]uint8{1, 2, 2, 2, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - } -} - -func (qdisc *Prio) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Prio) Type() string { - return "prio" -} - -// Htb is a classful qdisc that rate limits based on tokens -type Htb struct { - QdiscAttrs - Version uint32 - Rate2Quantum uint32 - Defcls uint32 - Debug uint32 - DirectPkts uint32 -} - -func NewHtb(attrs QdiscAttrs) *Htb { - return &Htb{ - QdiscAttrs: attrs, - Version: 3, - Defcls: 0, - Rate2Quantum: 10, - Debug: 0, - DirectPkts: 0, - } -} - -func (qdisc *Htb) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Htb) Type() string { - return "htb" -} - -// Netem is a classless qdisc that rate limits based on tokens - -type NetemQdiscAttrs struct { - Latency uint32 // in us - DelayCorr float32 // in % - Limit uint32 - Loss float32 // in % - LossCorr float32 // in % - Gap uint32 - Duplicate float32 // in % - DuplicateCorr float32 // in % - Jitter uint32 // in us - ReorderProb float32 // in % - ReorderCorr float32 // in % - CorruptProb float32 // in % - CorruptCorr float32 // in % -} - -func (q NetemQdiscAttrs) String() string { - return fmt.Sprintf( - "{Latency: %d, Limit: %d, Loss: %f, Gap: %d, Duplicate: %f, Jitter: %d}", - q.Latency, q.Limit, q.Loss, q.Gap, q.Duplicate, q.Jitter, - ) -} - -type Netem struct { - QdiscAttrs - Latency uint32 - DelayCorr uint32 - Limit uint32 - Loss uint32 - LossCorr uint32 - Gap uint32 - Duplicate uint32 - DuplicateCorr uint32 - Jitter uint32 - ReorderProb uint32 - ReorderCorr uint32 - CorruptProb uint32 - CorruptCorr uint32 -} - -func (netem *Netem) String() string { - return fmt.Sprintf( - "{Latency: %v, Limit: %v, Loss: %v, Gap: %v, Duplicate: %v, Jitter: %v}", - netem.Latency, netem.Limit, netem.Loss, netem.Gap, netem.Duplicate, netem.Jitter, - ) -} - -func (qdisc *Netem) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Netem) Type() string { - return "netem" -} - -// Tbf is a classless qdisc that rate limits based on tokens -type Tbf struct { - QdiscAttrs - Rate uint64 - Limit uint32 - Buffer uint32 - Peakrate uint64 - Minburst uint32 - // TODO: handle other settings -} - -func (qdisc *Tbf) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Tbf) Type() string { - return "tbf" -} - -// Ingress is a qdisc for adding ingress filters -type Ingress struct { - QdiscAttrs -} - -func (qdisc *Ingress) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Ingress) Type() string { - return "ingress" -} - -// GenericQdisc qdiscs represent types that are not currently understood -// by this netlink library. -type GenericQdisc struct { - QdiscAttrs - QdiscType string -} - -func (qdisc *GenericQdisc) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *GenericQdisc) Type() string { - return qdisc.QdiscType -} - -type Hfsc struct { - QdiscAttrs - Defcls uint16 -} - -func NewHfsc(attrs QdiscAttrs) *Hfsc { - return &Hfsc{ - QdiscAttrs: attrs, - Defcls: 1, - } -} - -func (hfsc *Hfsc) Attrs() *QdiscAttrs { - return &hfsc.QdiscAttrs -} - -func (hfsc *Hfsc) Type() string { - return "hfsc" -} - -func (hfsc *Hfsc) String() string { - return fmt.Sprintf( - "{%v -- default: %d}", - hfsc.Attrs(), hfsc.Defcls, - ) -} - -// Fq is a classless packet scheduler meant to be mostly used for locally generated traffic. -type Fq struct { - QdiscAttrs - PacketLimit uint32 - FlowPacketLimit uint32 - // In bytes - Quantum uint32 - InitialQuantum uint32 - // called RateEnable under the hood - Pacing uint32 - FlowDefaultRate uint32 - FlowMaxRate uint32 - // called BucketsLog under the hood - Buckets uint32 - FlowRefillDelay uint32 - LowRateThreshold uint32 -} - -func (fq *Fq) String() string { - return fmt.Sprintf( - "{PacketLimit: %v, FlowPacketLimit: %v, Quantum: %v, InitialQuantum: %v, Pacing: %v, FlowDefaultRate: %v, FlowMaxRate: %v, Buckets: %v, FlowRefillDelay: %v, LowRateThreshold: %v}", - fq.PacketLimit, fq.FlowPacketLimit, fq.Quantum, fq.InitialQuantum, fq.Pacing, fq.FlowDefaultRate, fq.FlowMaxRate, fq.Buckets, fq.FlowRefillDelay, fq.LowRateThreshold, - ) -} - -func NewFq(attrs QdiscAttrs) *Fq { - return &Fq{ - QdiscAttrs: attrs, - Pacing: 1, - } -} - -func (qdisc *Fq) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Fq) Type() string { - return "fq" -} - -// FQ_Codel (Fair Queuing Controlled Delay) is queuing discipline that combines Fair Queuing with the CoDel AQM scheme. -type FqCodel struct { - QdiscAttrs - Target uint32 - Limit uint32 - Interval uint32 - ECN uint32 - Flows uint32 - Quantum uint32 - // There are some more attributes here, but support for them seems not ubiquitous -} - -func (fqcodel *FqCodel) String() string { - return fmt.Sprintf( - "{%v -- Target: %v, Limit: %v, Interval: %v, ECM: %v, Flows: %v, Quantum: %v}", - fqcodel.Attrs(), fqcodel.Target, fqcodel.Limit, fqcodel.Interval, fqcodel.ECN, fqcodel.Flows, fqcodel.Quantum, - ) -} - -func NewFqCodel(attrs QdiscAttrs) *FqCodel { - return &FqCodel{ - QdiscAttrs: attrs, - ECN: 1, - } -} - -func (qdisc *FqCodel) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *FqCodel) Type() string { - return "fq_codel" -} - -type Sfq struct { - QdiscAttrs - // TODO: Only the simplified options for SFQ are handled here. Support for the extended one can be added later. - Quantum uint8 - Perturb uint8 - Limit uint32 - Divisor uint8 -} - -func (sfq *Sfq) String() string { - return fmt.Sprintf( - "{%v -- Quantum: %v, Perturb: %v, Limit: %v, Divisor: %v}", - sfq.Attrs(), sfq.Quantum, sfq.Perturb, sfq.Limit, sfq.Divisor, - ) -} - -func (qdisc *Sfq) Attrs() *QdiscAttrs { - return &qdisc.QdiscAttrs -} - -func (qdisc *Sfq) Type() string { - return "sfq" -} diff --git a/examples/vendor/github.com/vishvananda/netlink/qdisc_linux.go b/examples/vendor/github.com/vishvananda/netlink/qdisc_linux.go deleted file mode 100644 index d0e1ca1..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/qdisc_linux.go +++ /dev/null @@ -1,699 +0,0 @@ -package netlink - -import ( - "fmt" - "io/ioutil" - "strconv" - "strings" - "syscall" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// NOTE function is here because it uses other linux functions -func NewNetem(attrs QdiscAttrs, nattrs NetemQdiscAttrs) *Netem { - var limit uint32 = 1000 - var lossCorr, delayCorr, duplicateCorr uint32 - var reorderProb, reorderCorr uint32 - var corruptProb, corruptCorr uint32 - - latency := nattrs.Latency - loss := Percentage2u32(nattrs.Loss) - gap := nattrs.Gap - duplicate := Percentage2u32(nattrs.Duplicate) - jitter := nattrs.Jitter - - // Correlation - if latency > 0 && jitter > 0 { - delayCorr = Percentage2u32(nattrs.DelayCorr) - } - if loss > 0 { - lossCorr = Percentage2u32(nattrs.LossCorr) - } - if duplicate > 0 { - duplicateCorr = Percentage2u32(nattrs.DuplicateCorr) - } - // FIXME should validate values(like loss/duplicate are percentages...) - latency = time2Tick(latency) - - if nattrs.Limit != 0 { - limit = nattrs.Limit - } - // Jitter is only value if latency is > 0 - if latency > 0 { - jitter = time2Tick(jitter) - } - - reorderProb = Percentage2u32(nattrs.ReorderProb) - reorderCorr = Percentage2u32(nattrs.ReorderCorr) - - if reorderProb > 0 { - // ERROR if lantency == 0 - if gap == 0 { - gap = 1 - } - } - - corruptProb = Percentage2u32(nattrs.CorruptProb) - corruptCorr = Percentage2u32(nattrs.CorruptCorr) - - return &Netem{ - QdiscAttrs: attrs, - Latency: latency, - DelayCorr: delayCorr, - Limit: limit, - Loss: loss, - LossCorr: lossCorr, - Gap: gap, - Duplicate: duplicate, - DuplicateCorr: duplicateCorr, - Jitter: jitter, - ReorderProb: reorderProb, - ReorderCorr: reorderCorr, - CorruptProb: corruptProb, - CorruptCorr: corruptCorr, - } -} - -// QdiscDel will delete a qdisc from the system. -// Equivalent to: `tc qdisc del $qdisc` -func QdiscDel(qdisc Qdisc) error { - return pkgHandle.QdiscDel(qdisc) -} - -// QdiscDel will delete a qdisc from the system. -// Equivalent to: `tc qdisc del $qdisc` -func (h *Handle) QdiscDel(qdisc Qdisc) error { - return h.qdiscModify(unix.RTM_DELQDISC, 0, qdisc) -} - -// QdiscChange will change a qdisc in place -// Equivalent to: `tc qdisc change $qdisc` -// The parent and handle MUST NOT be changed. -func QdiscChange(qdisc Qdisc) error { - return pkgHandle.QdiscChange(qdisc) -} - -// QdiscChange will change a qdisc in place -// Equivalent to: `tc qdisc change $qdisc` -// The parent and handle MUST NOT be changed. -func (h *Handle) QdiscChange(qdisc Qdisc) error { - return h.qdiscModify(unix.RTM_NEWQDISC, 0, qdisc) -} - -// QdiscReplace will replace a qdisc to the system. -// Equivalent to: `tc qdisc replace $qdisc` -// The handle MUST change. -func QdiscReplace(qdisc Qdisc) error { - return pkgHandle.QdiscReplace(qdisc) -} - -// QdiscReplace will replace a qdisc to the system. -// Equivalent to: `tc qdisc replace $qdisc` -// The handle MUST change. -func (h *Handle) QdiscReplace(qdisc Qdisc) error { - return h.qdiscModify( - unix.RTM_NEWQDISC, - unix.NLM_F_CREATE|unix.NLM_F_REPLACE, - qdisc) -} - -// QdiscAdd will add a qdisc to the system. -// Equivalent to: `tc qdisc add $qdisc` -func QdiscAdd(qdisc Qdisc) error { - return pkgHandle.QdiscAdd(qdisc) -} - -// QdiscAdd will add a qdisc to the system. -// Equivalent to: `tc qdisc add $qdisc` -func (h *Handle) QdiscAdd(qdisc Qdisc) error { - return h.qdiscModify( - unix.RTM_NEWQDISC, - unix.NLM_F_CREATE|unix.NLM_F_EXCL, - qdisc) -} - -func (h *Handle) qdiscModify(cmd, flags int, qdisc Qdisc) error { - req := h.newNetlinkRequest(cmd, flags|unix.NLM_F_ACK) - base := qdisc.Attrs() - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Ifindex: int32(base.LinkIndex), - Handle: base.Handle, - Parent: base.Parent, - } - req.AddData(msg) - - // When deleting don't bother building the rest of the netlink payload - if cmd != unix.RTM_DELQDISC { - if err := qdiscPayload(req, qdisc); err != nil { - return err - } - } - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -func qdiscPayload(req *nl.NetlinkRequest, qdisc Qdisc) error { - - req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(qdisc.Type()))) - - options := nl.NewRtAttr(nl.TCA_OPTIONS, nil) - - switch qdisc := qdisc.(type) { - case *Prio: - tcmap := nl.TcPrioMap{ - Bands: int32(qdisc.Bands), - Priomap: qdisc.PriorityMap, - } - options = nl.NewRtAttr(nl.TCA_OPTIONS, tcmap.Serialize()) - case *Tbf: - opt := nl.TcTbfQopt{} - opt.Rate.Rate = uint32(qdisc.Rate) - opt.Peakrate.Rate = uint32(qdisc.Peakrate) - opt.Limit = qdisc.Limit - opt.Buffer = qdisc.Buffer - options.AddRtAttr(nl.TCA_TBF_PARMS, opt.Serialize()) - if qdisc.Rate >= uint64(1<<32) { - options.AddRtAttr(nl.TCA_TBF_RATE64, nl.Uint64Attr(qdisc.Rate)) - } - if qdisc.Peakrate >= uint64(1<<32) { - options.AddRtAttr(nl.TCA_TBF_PRATE64, nl.Uint64Attr(qdisc.Peakrate)) - } - if qdisc.Peakrate > 0 { - options.AddRtAttr(nl.TCA_TBF_PBURST, nl.Uint32Attr(qdisc.Minburst)) - } - case *Htb: - opt := nl.TcHtbGlob{} - opt.Version = qdisc.Version - opt.Rate2Quantum = qdisc.Rate2Quantum - opt.Defcls = qdisc.Defcls - // TODO: Handle Debug properly. For now default to 0 - opt.Debug = qdisc.Debug - opt.DirectPkts = qdisc.DirectPkts - options.AddRtAttr(nl.TCA_HTB_INIT, opt.Serialize()) - // options.AddRtAttr(nl.TCA_HTB_DIRECT_QLEN, opt.Serialize()) - case *Hfsc: - opt := nl.TcHfscOpt{} - opt.Defcls = qdisc.Defcls - options = nl.NewRtAttr(nl.TCA_OPTIONS, opt.Serialize()) - case *Netem: - opt := nl.TcNetemQopt{} - opt.Latency = qdisc.Latency - opt.Limit = qdisc.Limit - opt.Loss = qdisc.Loss - opt.Gap = qdisc.Gap - opt.Duplicate = qdisc.Duplicate - opt.Jitter = qdisc.Jitter - options = nl.NewRtAttr(nl.TCA_OPTIONS, opt.Serialize()) - // Correlation - corr := nl.TcNetemCorr{} - corr.DelayCorr = qdisc.DelayCorr - corr.LossCorr = qdisc.LossCorr - corr.DupCorr = qdisc.DuplicateCorr - - if corr.DelayCorr > 0 || corr.LossCorr > 0 || corr.DupCorr > 0 { - options.AddRtAttr(nl.TCA_NETEM_CORR, corr.Serialize()) - } - // Corruption - corruption := nl.TcNetemCorrupt{} - corruption.Probability = qdisc.CorruptProb - corruption.Correlation = qdisc.CorruptCorr - if corruption.Probability > 0 { - options.AddRtAttr(nl.TCA_NETEM_CORRUPT, corruption.Serialize()) - } - // Reorder - reorder := nl.TcNetemReorder{} - reorder.Probability = qdisc.ReorderProb - reorder.Correlation = qdisc.ReorderCorr - if reorder.Probability > 0 { - options.AddRtAttr(nl.TCA_NETEM_REORDER, reorder.Serialize()) - } - case *Ingress: - // ingress filters must use the proper handle - if qdisc.Attrs().Parent != HANDLE_INGRESS { - return fmt.Errorf("Ingress filters must set Parent to HANDLE_INGRESS") - } - case *FqCodel: - options.AddRtAttr(nl.TCA_FQ_CODEL_ECN, nl.Uint32Attr((uint32(qdisc.ECN)))) - if qdisc.Limit > 0 { - options.AddRtAttr(nl.TCA_FQ_CODEL_LIMIT, nl.Uint32Attr((uint32(qdisc.Limit)))) - } - if qdisc.Interval > 0 { - options.AddRtAttr(nl.TCA_FQ_CODEL_INTERVAL, nl.Uint32Attr((uint32(qdisc.Interval)))) - } - if qdisc.Flows > 0 { - options.AddRtAttr(nl.TCA_FQ_CODEL_FLOWS, nl.Uint32Attr((uint32(qdisc.Flows)))) - } - if qdisc.Quantum > 0 { - options.AddRtAttr(nl.TCA_FQ_CODEL_QUANTUM, nl.Uint32Attr((uint32(qdisc.Quantum)))) - } - - case *Fq: - options.AddRtAttr(nl.TCA_FQ_RATE_ENABLE, nl.Uint32Attr((uint32(qdisc.Pacing)))) - - if qdisc.Buckets > 0 { - options.AddRtAttr(nl.TCA_FQ_BUCKETS_LOG, nl.Uint32Attr((uint32(qdisc.Buckets)))) - } - if qdisc.LowRateThreshold > 0 { - options.AddRtAttr(nl.TCA_FQ_LOW_RATE_THRESHOLD, nl.Uint32Attr((uint32(qdisc.LowRateThreshold)))) - } - if qdisc.Quantum > 0 { - options.AddRtAttr(nl.TCA_FQ_QUANTUM, nl.Uint32Attr((uint32(qdisc.Quantum)))) - } - if qdisc.InitialQuantum > 0 { - options.AddRtAttr(nl.TCA_FQ_INITIAL_QUANTUM, nl.Uint32Attr((uint32(qdisc.InitialQuantum)))) - } - if qdisc.FlowRefillDelay > 0 { - options.AddRtAttr(nl.TCA_FQ_FLOW_REFILL_DELAY, nl.Uint32Attr((uint32(qdisc.FlowRefillDelay)))) - } - if qdisc.FlowPacketLimit > 0 { - options.AddRtAttr(nl.TCA_FQ_FLOW_PLIMIT, nl.Uint32Attr((uint32(qdisc.FlowPacketLimit)))) - } - if qdisc.FlowMaxRate > 0 { - options.AddRtAttr(nl.TCA_FQ_FLOW_MAX_RATE, nl.Uint32Attr((uint32(qdisc.FlowMaxRate)))) - } - if qdisc.FlowDefaultRate > 0 { - options.AddRtAttr(nl.TCA_FQ_FLOW_DEFAULT_RATE, nl.Uint32Attr((uint32(qdisc.FlowDefaultRate)))) - } - case *Sfq: - opt := nl.TcSfqQoptV1{} - opt.TcSfqQopt.Quantum = qdisc.Quantum - opt.TcSfqQopt.Perturb = int32(qdisc.Perturb) - opt.TcSfqQopt.Limit = qdisc.Limit - opt.TcSfqQopt.Divisor = qdisc.Divisor - - options = nl.NewRtAttr(nl.TCA_OPTIONS, opt.Serialize()) - default: - options = nil - } - - if options != nil { - req.AddData(options) - } - return nil -} - -// QdiscList gets a list of qdiscs in the system. -// Equivalent to: `tc qdisc show`. -// The list can be filtered by link. -func QdiscList(link Link) ([]Qdisc, error) { - return pkgHandle.QdiscList(link) -} - -// QdiscList gets a list of qdiscs in the system. -// Equivalent to: `tc qdisc show`. -// The list can be filtered by link. -func (h *Handle) QdiscList(link Link) ([]Qdisc, error) { - req := h.newNetlinkRequest(unix.RTM_GETQDISC, unix.NLM_F_DUMP) - index := int32(0) - if link != nil { - base := link.Attrs() - h.ensureIndex(base) - index = int32(base.Index) - } - msg := &nl.TcMsg{ - Family: nl.FAMILY_ALL, - Ifindex: index, - } - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWQDISC) - if err != nil { - return nil, err - } - - var res []Qdisc - for _, m := range msgs { - msg := nl.DeserializeTcMsg(m) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - // skip qdiscs from other interfaces - if link != nil && msg.Ifindex != index { - continue - } - - base := QdiscAttrs{ - LinkIndex: int(msg.Ifindex), - Handle: msg.Handle, - Parent: msg.Parent, - Refcnt: msg.Info, - } - var qdisc Qdisc - qdiscType := "" - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.TCA_KIND: - qdiscType = string(attr.Value[:len(attr.Value)-1]) - switch qdiscType { - case "pfifo_fast": - qdisc = &PfifoFast{} - case "prio": - qdisc = &Prio{} - case "tbf": - qdisc = &Tbf{} - case "ingress": - qdisc = &Ingress{} - case "htb": - qdisc = &Htb{} - case "fq": - qdisc = &Fq{} - case "hfsc": - qdisc = &Hfsc{} - case "fq_codel": - qdisc = &FqCodel{} - case "netem": - qdisc = &Netem{} - case "sfq": - qdisc = &Sfq{} - default: - qdisc = &GenericQdisc{QdiscType: qdiscType} - } - case nl.TCA_OPTIONS: - switch qdiscType { - case "pfifo_fast": - // pfifo returns TcPrioMap directly without wrapping it in rtattr - if err := parsePfifoFastData(qdisc, attr.Value); err != nil { - return nil, err - } - case "prio": - // prio returns TcPrioMap directly without wrapping it in rtattr - if err := parsePrioData(qdisc, attr.Value); err != nil { - return nil, err - } - case "tbf": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - if err := parseTbfData(qdisc, data); err != nil { - return nil, err - } - case "hfsc": - if err := parseHfscData(qdisc, attr.Value); err != nil { - return nil, err - } - case "htb": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - if err := parseHtbData(qdisc, data); err != nil { - return nil, err - } - case "fq": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - if err := parseFqData(qdisc, data); err != nil { - return nil, err - } - case "fq_codel": - data, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return nil, err - } - if err := parseFqCodelData(qdisc, data); err != nil { - return nil, err - } - case "netem": - if err := parseNetemData(qdisc, attr.Value); err != nil { - return nil, err - } - case "sfq": - if err := parseSfqData(qdisc, attr.Value); err != nil { - return nil, err - } - - // no options for ingress - } - } - } - *qdisc.Attrs() = base - res = append(res, qdisc) - } - - return res, nil -} - -func parsePfifoFastData(qdisc Qdisc, value []byte) error { - pfifo := qdisc.(*PfifoFast) - tcmap := nl.DeserializeTcPrioMap(value) - pfifo.PriorityMap = tcmap.Priomap - pfifo.Bands = uint8(tcmap.Bands) - return nil -} - -func parsePrioData(qdisc Qdisc, value []byte) error { - prio := qdisc.(*Prio) - tcmap := nl.DeserializeTcPrioMap(value) - prio.PriorityMap = tcmap.Priomap - prio.Bands = uint8(tcmap.Bands) - return nil -} - -func parseHtbData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error { - native = nl.NativeEndian() - htb := qdisc.(*Htb) - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_HTB_INIT: - opt := nl.DeserializeTcHtbGlob(datum.Value) - htb.Version = opt.Version - htb.Rate2Quantum = opt.Rate2Quantum - htb.Defcls = opt.Defcls - htb.Debug = opt.Debug - htb.DirectPkts = opt.DirectPkts - case nl.TCA_HTB_DIRECT_QLEN: - // TODO - //htb.DirectQlen = native.uint32(datum.Value) - } - } - return nil -} - -func parseFqCodelData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error { - native = nl.NativeEndian() - fqCodel := qdisc.(*FqCodel) - for _, datum := range data { - - switch datum.Attr.Type { - case nl.TCA_FQ_CODEL_TARGET: - fqCodel.Target = native.Uint32(datum.Value) - case nl.TCA_FQ_CODEL_LIMIT: - fqCodel.Limit = native.Uint32(datum.Value) - case nl.TCA_FQ_CODEL_INTERVAL: - fqCodel.Interval = native.Uint32(datum.Value) - case nl.TCA_FQ_CODEL_ECN: - fqCodel.ECN = native.Uint32(datum.Value) - case nl.TCA_FQ_CODEL_FLOWS: - fqCodel.Flows = native.Uint32(datum.Value) - case nl.TCA_FQ_CODEL_QUANTUM: - fqCodel.Quantum = native.Uint32(datum.Value) - } - } - return nil -} - -func parseHfscData(qdisc Qdisc, data []byte) error { - Hfsc := qdisc.(*Hfsc) - native = nl.NativeEndian() - Hfsc.Defcls = native.Uint16(data) - return nil -} - -func parseFqData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error { - native = nl.NativeEndian() - fq := qdisc.(*Fq) - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_FQ_BUCKETS_LOG: - fq.Buckets = native.Uint32(datum.Value) - case nl.TCA_FQ_LOW_RATE_THRESHOLD: - fq.LowRateThreshold = native.Uint32(datum.Value) - case nl.TCA_FQ_QUANTUM: - fq.Quantum = native.Uint32(datum.Value) - case nl.TCA_FQ_RATE_ENABLE: - fq.Pacing = native.Uint32(datum.Value) - case nl.TCA_FQ_INITIAL_QUANTUM: - fq.InitialQuantum = native.Uint32(datum.Value) - case nl.TCA_FQ_ORPHAN_MASK: - // TODO - case nl.TCA_FQ_FLOW_REFILL_DELAY: - fq.FlowRefillDelay = native.Uint32(datum.Value) - case nl.TCA_FQ_FLOW_PLIMIT: - fq.FlowPacketLimit = native.Uint32(datum.Value) - case nl.TCA_FQ_PLIMIT: - fq.PacketLimit = native.Uint32(datum.Value) - case nl.TCA_FQ_FLOW_MAX_RATE: - fq.FlowMaxRate = native.Uint32(datum.Value) - case nl.TCA_FQ_FLOW_DEFAULT_RATE: - fq.FlowDefaultRate = native.Uint32(datum.Value) - } - } - return nil -} - -func parseNetemData(qdisc Qdisc, value []byte) error { - netem := qdisc.(*Netem) - opt := nl.DeserializeTcNetemQopt(value) - netem.Latency = opt.Latency - netem.Limit = opt.Limit - netem.Loss = opt.Loss - netem.Gap = opt.Gap - netem.Duplicate = opt.Duplicate - netem.Jitter = opt.Jitter - data, err := nl.ParseRouteAttr(value[nl.SizeofTcNetemQopt:]) - if err != nil { - return err - } - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_NETEM_CORR: - opt := nl.DeserializeTcNetemCorr(datum.Value) - netem.DelayCorr = opt.DelayCorr - netem.LossCorr = opt.LossCorr - netem.DuplicateCorr = opt.DupCorr - case nl.TCA_NETEM_CORRUPT: - opt := nl.DeserializeTcNetemCorrupt(datum.Value) - netem.CorruptProb = opt.Probability - netem.CorruptCorr = opt.Correlation - case nl.TCA_NETEM_REORDER: - opt := nl.DeserializeTcNetemReorder(datum.Value) - netem.ReorderProb = opt.Probability - netem.ReorderCorr = opt.Correlation - } - } - return nil -} - -func parseTbfData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error { - native = nl.NativeEndian() - tbf := qdisc.(*Tbf) - for _, datum := range data { - switch datum.Attr.Type { - case nl.TCA_TBF_PARMS: - opt := nl.DeserializeTcTbfQopt(datum.Value) - tbf.Rate = uint64(opt.Rate.Rate) - tbf.Peakrate = uint64(opt.Peakrate.Rate) - tbf.Limit = opt.Limit - tbf.Buffer = opt.Buffer - case nl.TCA_TBF_RATE64: - tbf.Rate = native.Uint64(datum.Value[0:8]) - case nl.TCA_TBF_PRATE64: - tbf.Peakrate = native.Uint64(datum.Value[0:8]) - case nl.TCA_TBF_PBURST: - tbf.Minburst = native.Uint32(datum.Value[0:4]) - } - } - return nil -} - -func parseSfqData(qdisc Qdisc, value []byte) error { - sfq := qdisc.(*Sfq) - opt := nl.DeserializeTcSfqQoptV1(value) - sfq.Quantum = opt.TcSfqQopt.Quantum - sfq.Perturb = uint8(opt.TcSfqQopt.Perturb) - sfq.Limit = opt.TcSfqQopt.Limit - sfq.Divisor = opt.TcSfqQopt.Divisor - - return nil -} - -const ( - TIME_UNITS_PER_SEC = 1000000 -) - -var ( - tickInUsec float64 - clockFactor float64 - hz float64 -) - -func initClock() { - data, err := ioutil.ReadFile("/proc/net/psched") - if err != nil { - return - } - parts := strings.Split(strings.TrimSpace(string(data)), " ") - if len(parts) < 4 { - return - } - var vals [4]uint64 - for i := range vals { - val, err := strconv.ParseUint(parts[i], 16, 32) - if err != nil { - return - } - vals[i] = val - } - // compatibility - if vals[2] == 1000000000 { - vals[0] = vals[1] - } - clockFactor = float64(vals[2]) / TIME_UNITS_PER_SEC - tickInUsec = float64(vals[0]) / float64(vals[1]) * clockFactor - if vals[2] == 1000000 { - // ref https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/lib/utils.c#n963 - hz = float64(vals[3]) - } else { - hz = 100 - } -} - -func TickInUsec() float64 { - if tickInUsec == 0.0 { - initClock() - } - return tickInUsec -} - -func ClockFactor() float64 { - if clockFactor == 0.0 { - initClock() - } - return clockFactor -} - -func Hz() float64 { - if hz == 0.0 { - initClock() - } - return hz -} - -func time2Tick(time uint32) uint32 { - return uint32(float64(time) * TickInUsec()) -} - -func tick2Time(tick uint32) uint32 { - return uint32(float64(tick) / TickInUsec()) -} - -func time2Ktime(time uint32) uint32 { - return uint32(float64(time) * ClockFactor()) -} - -func ktime2Time(ktime uint32) uint32 { - return uint32(float64(ktime) / ClockFactor()) -} - -func burst(rate uint64, buffer uint32) uint32 { - return uint32(float64(rate) * float64(tick2Time(buffer)) / TIME_UNITS_PER_SEC) -} - -func latency(rate uint64, limit, buffer uint32) float64 { - return TIME_UNITS_PER_SEC*(float64(limit)/float64(rate)) - float64(tick2Time(buffer)) -} - -func Xmittime(rate uint64, size uint32) uint32 { - // https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/tc/tc_core.c#n62 - return time2Tick(uint32(TIME_UNITS_PER_SEC * (float64(size) / float64(rate)))) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/rdma_link_linux.go b/examples/vendor/github.com/vishvananda/netlink/rdma_link_linux.go deleted file mode 100644 index ff014ca..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/rdma_link_linux.go +++ /dev/null @@ -1,280 +0,0 @@ -package netlink - -import ( - "bytes" - "encoding/binary" - "fmt" - "net" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -// LinkAttrs represents data shared by most link types -type RdmaLinkAttrs struct { - Index uint32 - Name string - FirmwareVersion string - NodeGuid string - SysImageGuid string -} - -// Link represents a rdma device from netlink. -type RdmaLink struct { - Attrs RdmaLinkAttrs -} - -func getProtoField(clientType int, op int) int { - return ((clientType << nl.RDMA_NL_GET_CLIENT_SHIFT) | op) -} - -func uint64ToGuidString(guid uint64) string { - //Convert to byte array - sysGuidBytes := new(bytes.Buffer) - binary.Write(sysGuidBytes, binary.LittleEndian, guid) - - //Convert to HardwareAddr - sysGuidNet := net.HardwareAddr(sysGuidBytes.Bytes()) - - //Get the String - return sysGuidNet.String() -} - -func executeOneGetRdmaLink(data []byte) (*RdmaLink, error) { - - link := RdmaLink{} - - reader := bytes.NewReader(data) - for reader.Len() >= 4 { - _, attrType, len, value := parseNfAttrTLV(reader) - - switch attrType { - case nl.RDMA_NLDEV_ATTR_DEV_INDEX: - var Index uint32 - r := bytes.NewReader(value) - binary.Read(r, nl.NativeEndian(), &Index) - link.Attrs.Index = Index - case nl.RDMA_NLDEV_ATTR_DEV_NAME: - link.Attrs.Name = string(value[0 : len-1]) - case nl.RDMA_NLDEV_ATTR_FW_VERSION: - link.Attrs.FirmwareVersion = string(value[0 : len-1]) - case nl.RDMA_NLDEV_ATTR_NODE_GUID: - var guid uint64 - r := bytes.NewReader(value) - binary.Read(r, nl.NativeEndian(), &guid) - link.Attrs.NodeGuid = uint64ToGuidString(guid) - case nl.RDMA_NLDEV_ATTR_SYS_IMAGE_GUID: - var sysGuid uint64 - r := bytes.NewReader(value) - binary.Read(r, nl.NativeEndian(), &sysGuid) - link.Attrs.SysImageGuid = uint64ToGuidString(sysGuid) - } - if (len % 4) != 0 { - // Skip pad bytes - reader.Seek(int64(4-(len%4)), seekCurrent) - } - } - return &link, nil -} - -func execRdmaSetLink(req *nl.NetlinkRequest) error { - - _, err := req.Execute(unix.NETLINK_RDMA, 0) - return err -} - -// RdmaLinkList gets a list of RDMA link devices. -// Equivalent to: `rdma dev show` -func RdmaLinkList() ([]*RdmaLink, error) { - return pkgHandle.RdmaLinkList() -} - -// RdmaLinkList gets a list of RDMA link devices. -// Equivalent to: `rdma dev show` -func (h *Handle) RdmaLinkList() ([]*RdmaLink, error) { - proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_GET) - req := h.newNetlinkRequest(proto, unix.NLM_F_ACK|unix.NLM_F_DUMP) - - msgs, err := req.Execute(unix.NETLINK_RDMA, 0) - if err != nil { - return nil, err - } - - var res []*RdmaLink - for _, m := range msgs { - link, err := executeOneGetRdmaLink(m) - if err != nil { - return nil, err - } - res = append(res, link) - } - - return res, nil -} - -// RdmaLinkByName finds a link by name and returns a pointer to the object if -// found and nil error, otherwise returns error code. -func RdmaLinkByName(name string) (*RdmaLink, error) { - return pkgHandle.RdmaLinkByName(name) -} - -// RdmaLinkByName finds a link by name and returns a pointer to the object if -// found and nil error, otherwise returns error code. -func (h *Handle) RdmaLinkByName(name string) (*RdmaLink, error) { - links, err := h.RdmaLinkList() - if err != nil { - return nil, err - } - for _, link := range links { - if link.Attrs.Name == name { - return link, nil - } - } - return nil, fmt.Errorf("Rdma device %v not found", name) -} - -// RdmaLinkSetName sets the name of the rdma link device. Return nil on success -// or error otherwise. -// Equivalent to: `rdma dev set $old_devname name $name` -func RdmaLinkSetName(link *RdmaLink, name string) error { - return pkgHandle.RdmaLinkSetName(link, name) -} - -// RdmaLinkSetName sets the name of the rdma link device. Return nil on success -// or error otherwise. -// Equivalent to: `rdma dev set $old_devname name $name` -func (h *Handle) RdmaLinkSetName(link *RdmaLink, name string) error { - proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SET) - req := h.newNetlinkRequest(proto, unix.NLM_F_ACK) - - b := make([]byte, 4) - native.PutUint32(b, uint32(link.Attrs.Index)) - data := nl.NewRtAttr(nl.RDMA_NLDEV_ATTR_DEV_INDEX, b) - req.AddData(data) - - b = make([]byte, len(name)+1) - copy(b, name) - data = nl.NewRtAttr(nl.RDMA_NLDEV_ATTR_DEV_NAME, b) - req.AddData(data) - - return execRdmaSetLink(req) -} - -func netnsModeToString(mode uint8) string { - switch mode { - case 0: - return "exclusive" - case 1: - return "shared" - default: - return "unknown" - } -} - -func executeOneGetRdmaNetnsMode(data []byte) (string, error) { - reader := bytes.NewReader(data) - for reader.Len() >= 4 { - _, attrType, len, value := parseNfAttrTLV(reader) - - switch attrType { - case nl.RDMA_NLDEV_SYS_ATTR_NETNS_MODE: - var mode uint8 - r := bytes.NewReader(value) - binary.Read(r, nl.NativeEndian(), &mode) - return netnsModeToString(mode), nil - } - if (len % 4) != 0 { - // Skip pad bytes - reader.Seek(int64(4-(len%4)), seekCurrent) - } - } - return "", fmt.Errorf("Invalid netns mode") -} - -// RdmaSystemGetNetnsMode gets the net namespace mode for RDMA subsystem -// Returns mode string and error status as nil on success or returns error -// otherwise. -// Equivalent to: `rdma system show netns' -func RdmaSystemGetNetnsMode() (string, error) { - return pkgHandle.RdmaSystemGetNetnsMode() -} - -// RdmaSystemGetNetnsMode gets the net namespace mode for RDMA subsystem -// Returns mode string and error status as nil on success or returns error -// otherwise. -// Equivalent to: `rdma system show netns' -func (h *Handle) RdmaSystemGetNetnsMode() (string, error) { - - proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SYS_GET) - req := h.newNetlinkRequest(proto, unix.NLM_F_ACK) - - msgs, err := req.Execute(unix.NETLINK_RDMA, 0) - if err != nil { - return "", err - } - if len(msgs) == 0 { - return "", fmt.Errorf("No valid response from kernel") - } - return executeOneGetRdmaNetnsMode(msgs[0]) -} - -func netnsModeStringToUint8(mode string) (uint8, error) { - switch mode { - case "exclusive": - return 0, nil - case "shared": - return 1, nil - default: - return 0, fmt.Errorf("Invalid mode; %q", mode) - } -} - -// RdmaSystemSetNetnsMode sets the net namespace mode for RDMA subsystem -// Returns nil on success or appropriate error code. -// Equivalent to: `rdma system set netns { shared | exclusive }' -func RdmaSystemSetNetnsMode(NewMode string) error { - return pkgHandle.RdmaSystemSetNetnsMode(NewMode) -} - -// RdmaSystemSetNetnsMode sets the net namespace mode for RDMA subsystem -// Returns nil on success or appropriate error code. -// Equivalent to: `rdma system set netns { shared | exclusive }' -func (h *Handle) RdmaSystemSetNetnsMode(NewMode string) error { - value, err := netnsModeStringToUint8(NewMode) - if err != nil { - return err - } - - proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SYS_SET) - req := h.newNetlinkRequest(proto, unix.NLM_F_ACK) - - data := nl.NewRtAttr(nl.RDMA_NLDEV_SYS_ATTR_NETNS_MODE, []byte{value}) - req.AddData(data) - - _, err = req.Execute(unix.NETLINK_RDMA, 0) - return err -} - -// RdmaLinkSetNsFd puts the RDMA device into a new network namespace. The -// fd must be an open file descriptor to a network namespace. -// Similar to: `rdma dev set $dev netns $ns` -func RdmaLinkSetNsFd(link *RdmaLink, fd uint32) error { - return pkgHandle.RdmaLinkSetNsFd(link, fd) -} - -// RdmaLinkSetNsFd puts the RDMA device into a new network namespace. The -// fd must be an open file descriptor to a network namespace. -// Similar to: `rdma dev set $dev netns $ns` -func (h *Handle) RdmaLinkSetNsFd(link *RdmaLink, fd uint32) error { - proto := getProtoField(nl.RDMA_NL_NLDEV, nl.RDMA_NLDEV_CMD_SET) - req := h.newNetlinkRequest(proto, unix.NLM_F_ACK) - - data := nl.NewRtAttr(nl.RDMA_NLDEV_ATTR_DEV_INDEX, - nl.Uint32Attr(link.Attrs.Index)) - req.AddData(data) - - data = nl.NewRtAttr(nl.RDMA_NLDEV_NET_NS_FD, nl.Uint32Attr(fd)) - req.AddData(data) - - return execRdmaSetLink(req) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/route.go b/examples/vendor/github.com/vishvananda/netlink/route.go deleted file mode 100644 index b162541..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/route.go +++ /dev/null @@ -1,193 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "strings" -) - -// Scope is an enum representing a route scope. -type Scope uint8 - -type NextHopFlag int - -type Destination interface { - Family() int - Decode([]byte) error - Encode() ([]byte, error) - String() string - Equal(Destination) bool -} - -type Encap interface { - Type() int - Decode([]byte) error - Encode() ([]byte, error) - String() string - Equal(Encap) bool -} - -// Route represents a netlink route. -type Route struct { - LinkIndex int - ILinkIndex int - Scope Scope - Dst *net.IPNet - Src net.IP - Gw net.IP - MultiPath []*NexthopInfo - Protocol int - Priority int - Table int - Type int - Tos int - Flags int - MPLSDst *int - NewDst Destination - Encap Encap - MTU int - Window int - Rtt int - RttVar int - Ssthresh int - Cwnd int - AdvMSS int - Reordering int - Hoplimit int - InitCwnd int - Features int - RtoMin int - InitRwnd int - QuickACK int - Congctl string - FastOpenNoCookie int -} - -func (r Route) String() string { - elems := []string{} - if len(r.MultiPath) == 0 { - elems = append(elems, fmt.Sprintf("Ifindex: %d", r.LinkIndex)) - } - if r.MPLSDst != nil { - elems = append(elems, fmt.Sprintf("Dst: %d", r.MPLSDst)) - } else { - elems = append(elems, fmt.Sprintf("Dst: %s", r.Dst)) - } - if r.NewDst != nil { - elems = append(elems, fmt.Sprintf("NewDst: %s", r.NewDst)) - } - if r.Encap != nil { - elems = append(elems, fmt.Sprintf("Encap: %s", r.Encap)) - } - elems = append(elems, fmt.Sprintf("Src: %s", r.Src)) - if len(r.MultiPath) > 0 { - elems = append(elems, fmt.Sprintf("Gw: %s", r.MultiPath)) - } else { - elems = append(elems, fmt.Sprintf("Gw: %s", r.Gw)) - } - elems = append(elems, fmt.Sprintf("Flags: %s", r.ListFlags())) - elems = append(elems, fmt.Sprintf("Table: %d", r.Table)) - return fmt.Sprintf("{%s}", strings.Join(elems, " ")) -} - -func (r Route) Equal(x Route) bool { - return r.LinkIndex == x.LinkIndex && - r.ILinkIndex == x.ILinkIndex && - r.Scope == x.Scope && - ipNetEqual(r.Dst, x.Dst) && - r.Src.Equal(x.Src) && - r.Gw.Equal(x.Gw) && - nexthopInfoSlice(r.MultiPath).Equal(x.MultiPath) && - r.Protocol == x.Protocol && - r.Priority == x.Priority && - r.Table == x.Table && - r.Type == x.Type && - r.Tos == x.Tos && - r.Hoplimit == x.Hoplimit && - r.Flags == x.Flags && - (r.MPLSDst == x.MPLSDst || (r.MPLSDst != nil && x.MPLSDst != nil && *r.MPLSDst == *x.MPLSDst)) && - (r.NewDst == x.NewDst || (r.NewDst != nil && r.NewDst.Equal(x.NewDst))) && - (r.Encap == x.Encap || (r.Encap != nil && r.Encap.Equal(x.Encap))) -} - -func (r *Route) SetFlag(flag NextHopFlag) { - r.Flags |= int(flag) -} - -func (r *Route) ClearFlag(flag NextHopFlag) { - r.Flags &^= int(flag) -} - -type flagString struct { - f NextHopFlag - s string -} - -// RouteUpdate is sent when a route changes - type is RTM_NEWROUTE or RTM_DELROUTE -type RouteUpdate struct { - Type uint16 - Route -} - -type NexthopInfo struct { - LinkIndex int - Hops int - Gw net.IP - Flags int - NewDst Destination - Encap Encap -} - -func (n *NexthopInfo) String() string { - elems := []string{} - elems = append(elems, fmt.Sprintf("Ifindex: %d", n.LinkIndex)) - if n.NewDst != nil { - elems = append(elems, fmt.Sprintf("NewDst: %s", n.NewDst)) - } - if n.Encap != nil { - elems = append(elems, fmt.Sprintf("Encap: %s", n.Encap)) - } - elems = append(elems, fmt.Sprintf("Weight: %d", n.Hops+1)) - elems = append(elems, fmt.Sprintf("Gw: %s", n.Gw)) - elems = append(elems, fmt.Sprintf("Flags: %s", n.ListFlags())) - return fmt.Sprintf("{%s}", strings.Join(elems, " ")) -} - -func (n NexthopInfo) Equal(x NexthopInfo) bool { - return n.LinkIndex == x.LinkIndex && - n.Hops == x.Hops && - n.Gw.Equal(x.Gw) && - n.Flags == x.Flags && - (n.NewDst == x.NewDst || (n.NewDst != nil && n.NewDst.Equal(x.NewDst))) && - (n.Encap == x.Encap || (n.Encap != nil && n.Encap.Equal(x.Encap))) -} - -type nexthopInfoSlice []*NexthopInfo - -func (n nexthopInfoSlice) Equal(x []*NexthopInfo) bool { - if len(n) != len(x) { - return false - } - for i := range n { - if n[i] == nil || x[i] == nil { - return false - } - if !n[i].Equal(*x[i]) { - return false - } - } - return true -} - -// ipNetEqual returns true iff both IPNet are equal -func ipNetEqual(ipn1 *net.IPNet, ipn2 *net.IPNet) bool { - if ipn1 == ipn2 { - return true - } - if ipn1 == nil || ipn2 == nil { - return false - } - m1, _ := ipn1.Mask.Size() - m2, _ := ipn2.Mask.Size() - return m1 == m2 && ipn1.IP.Equal(ipn2.IP) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/route_linux.go b/examples/vendor/github.com/vishvananda/netlink/route_linux.go deleted file mode 100644 index 4e778a4..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/route_linux.go +++ /dev/null @@ -1,1192 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "strings" - "syscall" - - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -// RtAttr is shared so it is in netlink_linux.go - -const ( - SCOPE_UNIVERSE Scope = unix.RT_SCOPE_UNIVERSE - SCOPE_SITE Scope = unix.RT_SCOPE_SITE - SCOPE_LINK Scope = unix.RT_SCOPE_LINK - SCOPE_HOST Scope = unix.RT_SCOPE_HOST - SCOPE_NOWHERE Scope = unix.RT_SCOPE_NOWHERE -) - -const ( - RT_FILTER_PROTOCOL uint64 = 1 << (1 + iota) - RT_FILTER_SCOPE - RT_FILTER_TYPE - RT_FILTER_TOS - RT_FILTER_IIF - RT_FILTER_OIF - RT_FILTER_DST - RT_FILTER_SRC - RT_FILTER_GW - RT_FILTER_TABLE - RT_FILTER_HOPLIMIT - RT_FILTER_PRIORITY - RT_FILTER_MARK - RT_FILTER_MASK -) - -const ( - FLAG_ONLINK NextHopFlag = unix.RTNH_F_ONLINK - FLAG_PERVASIVE NextHopFlag = unix.RTNH_F_PERVASIVE -) - -var testFlags = []flagString{ - {f: FLAG_ONLINK, s: "onlink"}, - {f: FLAG_PERVASIVE, s: "pervasive"}, -} - -func listFlags(flag int) []string { - var flags []string - for _, tf := range testFlags { - if flag&int(tf.f) != 0 { - flags = append(flags, tf.s) - } - } - return flags -} - -func (r *Route) ListFlags() []string { - return listFlags(r.Flags) -} - -func (n *NexthopInfo) ListFlags() []string { - return listFlags(n.Flags) -} - -type MPLSDestination struct { - Labels []int -} - -func (d *MPLSDestination) Family() int { - return nl.FAMILY_MPLS -} - -func (d *MPLSDestination) Decode(buf []byte) error { - d.Labels = nl.DecodeMPLSStack(buf) - return nil -} - -func (d *MPLSDestination) Encode() ([]byte, error) { - return nl.EncodeMPLSStack(d.Labels...), nil -} - -func (d *MPLSDestination) String() string { - s := make([]string, 0, len(d.Labels)) - for _, l := range d.Labels { - s = append(s, fmt.Sprintf("%d", l)) - } - return strings.Join(s, "/") -} - -func (d *MPLSDestination) Equal(x Destination) bool { - o, ok := x.(*MPLSDestination) - if !ok { - return false - } - if d == nil && o == nil { - return true - } - if d == nil || o == nil { - return false - } - if d.Labels == nil && o.Labels == nil { - return true - } - if d.Labels == nil || o.Labels == nil { - return false - } - if len(d.Labels) != len(o.Labels) { - return false - } - for i := range d.Labels { - if d.Labels[i] != o.Labels[i] { - return false - } - } - return true -} - -type MPLSEncap struct { - Labels []int -} - -func (e *MPLSEncap) Type() int { - return nl.LWTUNNEL_ENCAP_MPLS -} - -func (e *MPLSEncap) Decode(buf []byte) error { - if len(buf) < 4 { - return fmt.Errorf("lack of bytes") - } - native := nl.NativeEndian() - l := native.Uint16(buf) - if len(buf) < int(l) { - return fmt.Errorf("lack of bytes") - } - buf = buf[:l] - typ := native.Uint16(buf[2:]) - if typ != nl.MPLS_IPTUNNEL_DST { - return fmt.Errorf("unknown MPLS Encap Type: %d", typ) - } - e.Labels = nl.DecodeMPLSStack(buf[4:]) - return nil -} - -func (e *MPLSEncap) Encode() ([]byte, error) { - s := nl.EncodeMPLSStack(e.Labels...) - native := nl.NativeEndian() - hdr := make([]byte, 4) - native.PutUint16(hdr, uint16(len(s)+4)) - native.PutUint16(hdr[2:], nl.MPLS_IPTUNNEL_DST) - return append(hdr, s...), nil -} - -func (e *MPLSEncap) String() string { - s := make([]string, 0, len(e.Labels)) - for _, l := range e.Labels { - s = append(s, fmt.Sprintf("%d", l)) - } - return strings.Join(s, "/") -} - -func (e *MPLSEncap) Equal(x Encap) bool { - o, ok := x.(*MPLSEncap) - if !ok { - return false - } - if e == nil && o == nil { - return true - } - if e == nil || o == nil { - return false - } - if e.Labels == nil && o.Labels == nil { - return true - } - if e.Labels == nil || o.Labels == nil { - return false - } - if len(e.Labels) != len(o.Labels) { - return false - } - for i := range e.Labels { - if e.Labels[i] != o.Labels[i] { - return false - } - } - return true -} - -// SEG6 definitions -type SEG6Encap struct { - Mode int - Segments []net.IP -} - -func (e *SEG6Encap) Type() int { - return nl.LWTUNNEL_ENCAP_SEG6 -} -func (e *SEG6Encap) Decode(buf []byte) error { - if len(buf) < 4 { - return fmt.Errorf("lack of bytes") - } - native := nl.NativeEndian() - // Get Length(l) & Type(typ) : 2 + 2 bytes - l := native.Uint16(buf) - if len(buf) < int(l) { - return fmt.Errorf("lack of bytes") - } - buf = buf[:l] // make sure buf size upper limit is Length - typ := native.Uint16(buf[2:]) - // LWTUNNEL_ENCAP_SEG6 has only one attr type SEG6_IPTUNNEL_SRH - if typ != nl.SEG6_IPTUNNEL_SRH { - return fmt.Errorf("unknown SEG6 Type: %d", typ) - } - - var err error - e.Mode, e.Segments, err = nl.DecodeSEG6Encap(buf[4:]) - - return err -} -func (e *SEG6Encap) Encode() ([]byte, error) { - s, err := nl.EncodeSEG6Encap(e.Mode, e.Segments) - native := nl.NativeEndian() - hdr := make([]byte, 4) - native.PutUint16(hdr, uint16(len(s)+4)) - native.PutUint16(hdr[2:], nl.SEG6_IPTUNNEL_SRH) - return append(hdr, s...), err -} -func (e *SEG6Encap) String() string { - segs := make([]string, 0, len(e.Segments)) - // append segment backwards (from n to 0) since seg#0 is the last segment. - for i := len(e.Segments); i > 0; i-- { - segs = append(segs, fmt.Sprintf("%s", e.Segments[i-1])) - } - str := fmt.Sprintf("mode %s segs %d [ %s ]", nl.SEG6EncapModeString(e.Mode), - len(e.Segments), strings.Join(segs, " ")) - return str -} -func (e *SEG6Encap) Equal(x Encap) bool { - o, ok := x.(*SEG6Encap) - if !ok { - return false - } - if e == o { - return true - } - if e == nil || o == nil { - return false - } - if e.Mode != o.Mode { - return false - } - if len(e.Segments) != len(o.Segments) { - return false - } - for i := range e.Segments { - if !e.Segments[i].Equal(o.Segments[i]) { - return false - } - } - return true -} - -// SEG6LocalEncap definitions -type SEG6LocalEncap struct { - Flags [nl.SEG6_LOCAL_MAX]bool - Action int - Segments []net.IP // from SRH in seg6_local_lwt - Table int // table id for End.T and End.DT6 - InAddr net.IP - In6Addr net.IP - Iif int - Oif int -} - -func (e *SEG6LocalEncap) Type() int { - return nl.LWTUNNEL_ENCAP_SEG6_LOCAL -} -func (e *SEG6LocalEncap) Decode(buf []byte) error { - attrs, err := nl.ParseRouteAttr(buf) - if err != nil { - return err - } - native := nl.NativeEndian() - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.SEG6_LOCAL_ACTION: - e.Action = int(native.Uint32(attr.Value[0:4])) - e.Flags[nl.SEG6_LOCAL_ACTION] = true - case nl.SEG6_LOCAL_SRH: - e.Segments, err = nl.DecodeSEG6Srh(attr.Value[:]) - e.Flags[nl.SEG6_LOCAL_SRH] = true - case nl.SEG6_LOCAL_TABLE: - e.Table = int(native.Uint32(attr.Value[0:4])) - e.Flags[nl.SEG6_LOCAL_TABLE] = true - case nl.SEG6_LOCAL_NH4: - e.InAddr = net.IP(attr.Value[0:4]) - e.Flags[nl.SEG6_LOCAL_NH4] = true - case nl.SEG6_LOCAL_NH6: - e.In6Addr = net.IP(attr.Value[0:16]) - e.Flags[nl.SEG6_LOCAL_NH6] = true - case nl.SEG6_LOCAL_IIF: - e.Iif = int(native.Uint32(attr.Value[0:4])) - e.Flags[nl.SEG6_LOCAL_IIF] = true - case nl.SEG6_LOCAL_OIF: - e.Oif = int(native.Uint32(attr.Value[0:4])) - e.Flags[nl.SEG6_LOCAL_OIF] = true - } - } - return err -} -func (e *SEG6LocalEncap) Encode() ([]byte, error) { - var err error - native := nl.NativeEndian() - res := make([]byte, 8) - native.PutUint16(res, 8) // length - native.PutUint16(res[2:], nl.SEG6_LOCAL_ACTION) - native.PutUint32(res[4:], uint32(e.Action)) - if e.Flags[nl.SEG6_LOCAL_SRH] { - srh, err := nl.EncodeSEG6Srh(e.Segments) - if err != nil { - return nil, err - } - attr := make([]byte, 4) - native.PutUint16(attr, uint16(len(srh)+4)) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_SRH) - attr = append(attr, srh...) - res = append(res, attr...) - } - if e.Flags[nl.SEG6_LOCAL_TABLE] { - attr := make([]byte, 8) - native.PutUint16(attr, 8) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_TABLE) - native.PutUint32(attr[4:], uint32(e.Table)) - res = append(res, attr...) - } - if e.Flags[nl.SEG6_LOCAL_NH4] { - attr := make([]byte, 4) - native.PutUint16(attr, 8) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_NH4) - ipv4 := e.InAddr.To4() - if ipv4 == nil { - err = fmt.Errorf("SEG6_LOCAL_NH4 has invalid IPv4 address") - return nil, err - } - attr = append(attr, ipv4...) - res = append(res, attr...) - } - if e.Flags[nl.SEG6_LOCAL_NH6] { - attr := make([]byte, 4) - native.PutUint16(attr, 20) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_NH6) - attr = append(attr, e.In6Addr...) - res = append(res, attr...) - } - if e.Flags[nl.SEG6_LOCAL_IIF] { - attr := make([]byte, 8) - native.PutUint16(attr, 8) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_IIF) - native.PutUint32(attr[4:], uint32(e.Iif)) - res = append(res, attr...) - } - if e.Flags[nl.SEG6_LOCAL_OIF] { - attr := make([]byte, 8) - native.PutUint16(attr, 8) - native.PutUint16(attr[2:], nl.SEG6_LOCAL_OIF) - native.PutUint32(attr[4:], uint32(e.Oif)) - res = append(res, attr...) - } - return res, err -} -func (e *SEG6LocalEncap) String() string { - strs := make([]string, 0, nl.SEG6_LOCAL_MAX) - strs = append(strs, fmt.Sprintf("action %s", nl.SEG6LocalActionString(e.Action))) - - if e.Flags[nl.SEG6_LOCAL_TABLE] { - strs = append(strs, fmt.Sprintf("table %d", e.Table)) - } - if e.Flags[nl.SEG6_LOCAL_NH4] { - strs = append(strs, fmt.Sprintf("nh4 %s", e.InAddr)) - } - if e.Flags[nl.SEG6_LOCAL_NH6] { - strs = append(strs, fmt.Sprintf("nh6 %s", e.In6Addr)) - } - if e.Flags[nl.SEG6_LOCAL_IIF] { - link, err := LinkByIndex(e.Iif) - if err != nil { - strs = append(strs, fmt.Sprintf("iif %d", e.Iif)) - } else { - strs = append(strs, fmt.Sprintf("iif %s", link.Attrs().Name)) - } - } - if e.Flags[nl.SEG6_LOCAL_OIF] { - link, err := LinkByIndex(e.Oif) - if err != nil { - strs = append(strs, fmt.Sprintf("oif %d", e.Oif)) - } else { - strs = append(strs, fmt.Sprintf("oif %s", link.Attrs().Name)) - } - } - if e.Flags[nl.SEG6_LOCAL_SRH] { - segs := make([]string, 0, len(e.Segments)) - //append segment backwards (from n to 0) since seg#0 is the last segment. - for i := len(e.Segments); i > 0; i-- { - segs = append(segs, fmt.Sprintf("%s", e.Segments[i-1])) - } - strs = append(strs, fmt.Sprintf("segs %d [ %s ]", len(e.Segments), strings.Join(segs, " "))) - } - return strings.Join(strs, " ") -} -func (e *SEG6LocalEncap) Equal(x Encap) bool { - o, ok := x.(*SEG6LocalEncap) - if !ok { - return false - } - if e == o { - return true - } - if e == nil || o == nil { - return false - } - // compare all arrays first - for i := range e.Flags { - if e.Flags[i] != o.Flags[i] { - return false - } - } - if len(e.Segments) != len(o.Segments) { - return false - } - for i := range e.Segments { - if !e.Segments[i].Equal(o.Segments[i]) { - return false - } - } - // compare values - if !e.InAddr.Equal(o.InAddr) || !e.In6Addr.Equal(o.In6Addr) { - return false - } - if e.Action != o.Action || e.Table != o.Table || e.Iif != o.Iif || e.Oif != o.Oif { - return false - } - return true -} - -// RouteAdd will add a route to the system. -// Equivalent to: `ip route add $route` -func RouteAdd(route *Route) error { - return pkgHandle.RouteAdd(route) -} - -// RouteAdd will add a route to the system. -// Equivalent to: `ip route add $route` -func (h *Handle) RouteAdd(route *Route) error { - flags := unix.NLM_F_CREATE | unix.NLM_F_EXCL | unix.NLM_F_ACK - req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags) - return h.routeHandle(route, req, nl.NewRtMsg()) -} - -// RouteReplace will add a route to the system. -// Equivalent to: `ip route replace $route` -func RouteReplace(route *Route) error { - return pkgHandle.RouteReplace(route) -} - -// RouteReplace will add a route to the system. -// Equivalent to: `ip route replace $route` -func (h *Handle) RouteReplace(route *Route) error { - flags := unix.NLM_F_CREATE | unix.NLM_F_REPLACE | unix.NLM_F_ACK - req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags) - return h.routeHandle(route, req, nl.NewRtMsg()) -} - -// RouteDel will delete a route from the system. -// Equivalent to: `ip route del $route` -func RouteDel(route *Route) error { - return pkgHandle.RouteDel(route) -} - -// RouteDel will delete a route from the system. -// Equivalent to: `ip route del $route` -func (h *Handle) RouteDel(route *Route) error { - req := h.newNetlinkRequest(unix.RTM_DELROUTE, unix.NLM_F_ACK) - return h.routeHandle(route, req, nl.NewRtDelMsg()) -} - -func (h *Handle) routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error { - if (route.Dst == nil || route.Dst.IP == nil) && route.Src == nil && route.Gw == nil && route.MPLSDst == nil { - return fmt.Errorf("one of Dst.IP, Src, or Gw must not be nil") - } - - family := -1 - var rtAttrs []*nl.RtAttr - - if route.Dst != nil && route.Dst.IP != nil { - dstLen, _ := route.Dst.Mask.Size() - msg.Dst_len = uint8(dstLen) - dstFamily := nl.GetIPFamily(route.Dst.IP) - family = dstFamily - var dstData []byte - if dstFamily == FAMILY_V4 { - dstData = route.Dst.IP.To4() - } else { - dstData = route.Dst.IP.To16() - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, dstData)) - } else if route.MPLSDst != nil { - family = nl.FAMILY_MPLS - msg.Dst_len = uint8(20) - msg.Type = unix.RTN_UNICAST - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, nl.EncodeMPLSStack(*route.MPLSDst))) - } - - if route.NewDst != nil { - if family != -1 && family != route.NewDst.Family() { - return fmt.Errorf("new destination and destination are not the same address family") - } - buf, err := route.NewDst.Encode() - if err != nil { - return err - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_NEWDST, buf)) - } - - if route.Encap != nil { - buf := make([]byte, 2) - native.PutUint16(buf, uint16(route.Encap.Type())) - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_ENCAP_TYPE, buf)) - buf, err := route.Encap.Encode() - if err != nil { - return err - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_ENCAP, buf)) - } - - if route.Src != nil { - srcFamily := nl.GetIPFamily(route.Src) - if family != -1 && family != srcFamily { - return fmt.Errorf("source and destination ip are not the same IP family") - } - family = srcFamily - var srcData []byte - if srcFamily == FAMILY_V4 { - srcData = route.Src.To4() - } else { - srcData = route.Src.To16() - } - // The commonly used src ip for routes is actually PREFSRC - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_PREFSRC, srcData)) - } - - if route.Gw != nil { - gwFamily := nl.GetIPFamily(route.Gw) - if family != -1 && family != gwFamily { - return fmt.Errorf("gateway, source, and destination ip are not the same IP family") - } - family = gwFamily - var gwData []byte - if gwFamily == FAMILY_V4 { - gwData = route.Gw.To4() - } else { - gwData = route.Gw.To16() - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_GATEWAY, gwData)) - } - - if len(route.MultiPath) > 0 { - buf := []byte{} - for _, nh := range route.MultiPath { - rtnh := &nl.RtNexthop{ - RtNexthop: unix.RtNexthop{ - Hops: uint8(nh.Hops), - Ifindex: int32(nh.LinkIndex), - Flags: uint8(nh.Flags), - }, - } - children := []nl.NetlinkRequestData{} - if nh.Gw != nil { - gwFamily := nl.GetIPFamily(nh.Gw) - if family != -1 && family != gwFamily { - return fmt.Errorf("gateway, source, and destination ip are not the same IP family") - } - if gwFamily == FAMILY_V4 { - children = append(children, nl.NewRtAttr(unix.RTA_GATEWAY, []byte(nh.Gw.To4()))) - } else { - children = append(children, nl.NewRtAttr(unix.RTA_GATEWAY, []byte(nh.Gw.To16()))) - } - } - if nh.NewDst != nil { - if family != -1 && family != nh.NewDst.Family() { - return fmt.Errorf("new destination and destination are not the same address family") - } - buf, err := nh.NewDst.Encode() - if err != nil { - return err - } - children = append(children, nl.NewRtAttr(unix.RTA_NEWDST, buf)) - } - if nh.Encap != nil { - buf := make([]byte, 2) - native.PutUint16(buf, uint16(nh.Encap.Type())) - children = append(children, nl.NewRtAttr(unix.RTA_ENCAP_TYPE, buf)) - buf, err := nh.Encap.Encode() - if err != nil { - return err - } - children = append(children, nl.NewRtAttr(unix.RTA_ENCAP, buf)) - } - rtnh.Children = children - buf = append(buf, rtnh.Serialize()...) - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_MULTIPATH, buf)) - } - - if route.Table > 0 { - if route.Table >= 256 { - msg.Table = unix.RT_TABLE_UNSPEC - b := make([]byte, 4) - native.PutUint32(b, uint32(route.Table)) - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_TABLE, b)) - } else { - msg.Table = uint8(route.Table) - } - } - - if route.Priority > 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(route.Priority)) - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_PRIORITY, b)) - } - if route.Tos > 0 { - msg.Tos = uint8(route.Tos) - } - if route.Protocol > 0 { - msg.Protocol = uint8(route.Protocol) - } - if route.Type > 0 { - msg.Type = uint8(route.Type) - } - - var metrics []*nl.RtAttr - if route.MTU > 0 { - b := nl.Uint32Attr(uint32(route.MTU)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_MTU, b)) - } - if route.Window > 0 { - b := nl.Uint32Attr(uint32(route.Window)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_WINDOW, b)) - } - if route.Rtt > 0 { - b := nl.Uint32Attr(uint32(route.Rtt)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_RTT, b)) - } - if route.RttVar > 0 { - b := nl.Uint32Attr(uint32(route.RttVar)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_RTTVAR, b)) - } - if route.Ssthresh > 0 { - b := nl.Uint32Attr(uint32(route.Ssthresh)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_SSTHRESH, b)) - } - if route.Cwnd > 0 { - b := nl.Uint32Attr(uint32(route.Cwnd)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_CWND, b)) - } - if route.AdvMSS > 0 { - b := nl.Uint32Attr(uint32(route.AdvMSS)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_ADVMSS, b)) - } - if route.Reordering > 0 { - b := nl.Uint32Attr(uint32(route.Reordering)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_REORDERING, b)) - } - if route.Hoplimit > 0 { - b := nl.Uint32Attr(uint32(route.Hoplimit)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_HOPLIMIT, b)) - } - if route.InitCwnd > 0 { - b := nl.Uint32Attr(uint32(route.InitCwnd)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_INITCWND, b)) - } - if route.Features > 0 { - b := nl.Uint32Attr(uint32(route.Features)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_FEATURES, b)) - } - if route.RtoMin > 0 { - b := nl.Uint32Attr(uint32(route.RtoMin)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_RTO_MIN, b)) - } - if route.InitRwnd > 0 { - b := nl.Uint32Attr(uint32(route.InitRwnd)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_INITRWND, b)) - } - if route.QuickACK > 0 { - b := nl.Uint32Attr(uint32(route.QuickACK)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_QUICKACK, b)) - } - if route.Congctl != "" { - b := nl.ZeroTerminated(route.Congctl) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_CC_ALGO, b)) - } - if route.FastOpenNoCookie > 0 { - b := nl.Uint32Attr(uint32(route.FastOpenNoCookie)) - metrics = append(metrics, nl.NewRtAttr(unix.RTAX_FASTOPEN_NO_COOKIE, b)) - } - - if metrics != nil { - attr := nl.NewRtAttr(unix.RTA_METRICS, nil) - for _, metric := range metrics { - attr.AddChild(metric) - } - rtAttrs = append(rtAttrs, attr) - } - - msg.Flags = uint32(route.Flags) - msg.Scope = uint8(route.Scope) - msg.Family = uint8(family) - req.AddData(msg) - for _, attr := range rtAttrs { - req.AddData(attr) - } - - var ( - b = make([]byte, 4) - native = nl.NativeEndian() - ) - native.PutUint32(b, uint32(route.LinkIndex)) - - req.AddData(nl.NewRtAttr(unix.RTA_OIF, b)) - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// RouteList gets a list of routes in the system. -// Equivalent to: `ip route show`. -// The list can be filtered by link and ip family. -func RouteList(link Link, family int) ([]Route, error) { - return pkgHandle.RouteList(link, family) -} - -// RouteList gets a list of routes in the system. -// Equivalent to: `ip route show`. -// The list can be filtered by link and ip family. -func (h *Handle) RouteList(link Link, family int) ([]Route, error) { - var routeFilter *Route - if link != nil { - routeFilter = &Route{ - LinkIndex: link.Attrs().Index, - } - } - return h.RouteListFiltered(family, routeFilter, RT_FILTER_OIF) -} - -// RouteListFiltered gets a list of routes in the system filtered with specified rules. -// All rules must be defined in RouteFilter struct -func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) { - return pkgHandle.RouteListFiltered(family, filter, filterMask) -} - -// RouteListFiltered gets a list of routes in the system filtered with specified rules. -// All rules must be defined in RouteFilter struct -func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) { - req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_DUMP) - infmsg := nl.NewIfInfomsg(family) - req.AddData(infmsg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE) - if err != nil { - return nil, err - } - - var res []Route - for _, m := range msgs { - msg := nl.DeserializeRtMsg(m) - if msg.Flags&unix.RTM_F_CLONED != 0 { - // Ignore cloned routes - continue - } - if msg.Table != unix.RT_TABLE_MAIN { - if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 { - // Ignore non-main tables - continue - } - } - route, err := deserializeRoute(m) - if err != nil { - return nil, err - } - if filter != nil { - switch { - case filterMask&RT_FILTER_TABLE != 0 && filter.Table != unix.RT_TABLE_UNSPEC && route.Table != filter.Table: - continue - case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol: - continue - case filterMask&RT_FILTER_SCOPE != 0 && route.Scope != filter.Scope: - continue - case filterMask&RT_FILTER_TYPE != 0 && route.Type != filter.Type: - continue - case filterMask&RT_FILTER_TOS != 0 && route.Tos != filter.Tos: - continue - case filterMask&RT_FILTER_OIF != 0 && route.LinkIndex != filter.LinkIndex: - continue - case filterMask&RT_FILTER_IIF != 0 && route.ILinkIndex != filter.ILinkIndex: - continue - case filterMask&RT_FILTER_GW != 0 && !route.Gw.Equal(filter.Gw): - continue - case filterMask&RT_FILTER_SRC != 0 && !route.Src.Equal(filter.Src): - continue - case filterMask&RT_FILTER_DST != 0: - if filter.MPLSDst == nil || route.MPLSDst == nil || (*filter.MPLSDst) != (*route.MPLSDst) { - if !ipNetEqual(route.Dst, filter.Dst) { - continue - } - } - case filterMask&RT_FILTER_HOPLIMIT != 0 && route.Hoplimit != filter.Hoplimit: - continue - } - } - res = append(res, route) - } - return res, nil -} - -// deserializeRoute decodes a binary netlink message into a Route struct -func deserializeRoute(m []byte) (Route, error) { - msg := nl.DeserializeRtMsg(m) - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return Route{}, err - } - route := Route{ - Scope: Scope(msg.Scope), - Protocol: int(msg.Protocol), - Table: int(msg.Table), - Type: int(msg.Type), - Tos: int(msg.Tos), - Flags: int(msg.Flags), - } - - native := nl.NativeEndian() - var encap, encapType syscall.NetlinkRouteAttr - for _, attr := range attrs { - switch attr.Attr.Type { - case unix.RTA_GATEWAY: - route.Gw = net.IP(attr.Value) - case unix.RTA_PREFSRC: - route.Src = net.IP(attr.Value) - case unix.RTA_DST: - if msg.Family == nl.FAMILY_MPLS { - stack := nl.DecodeMPLSStack(attr.Value) - if len(stack) == 0 || len(stack) > 1 { - return route, fmt.Errorf("invalid MPLS RTA_DST") - } - route.MPLSDst = &stack[0] - } else { - route.Dst = &net.IPNet{ - IP: attr.Value, - Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)), - } - } - case unix.RTA_OIF: - route.LinkIndex = int(native.Uint32(attr.Value[0:4])) - case unix.RTA_IIF: - route.ILinkIndex = int(native.Uint32(attr.Value[0:4])) - case unix.RTA_PRIORITY: - route.Priority = int(native.Uint32(attr.Value[0:4])) - case unix.RTA_TABLE: - route.Table = int(native.Uint32(attr.Value[0:4])) - case unix.RTA_MULTIPATH: - parseRtNexthop := func(value []byte) (*NexthopInfo, []byte, error) { - if len(value) < unix.SizeofRtNexthop { - return nil, nil, fmt.Errorf("lack of bytes") - } - nh := nl.DeserializeRtNexthop(value) - if len(value) < int(nh.RtNexthop.Len) { - return nil, nil, fmt.Errorf("lack of bytes") - } - info := &NexthopInfo{ - LinkIndex: int(nh.RtNexthop.Ifindex), - Hops: int(nh.RtNexthop.Hops), - Flags: int(nh.RtNexthop.Flags), - } - attrs, err := nl.ParseRouteAttr(value[unix.SizeofRtNexthop:int(nh.RtNexthop.Len)]) - if err != nil { - return nil, nil, err - } - var encap, encapType syscall.NetlinkRouteAttr - for _, attr := range attrs { - switch attr.Attr.Type { - case unix.RTA_GATEWAY: - info.Gw = net.IP(attr.Value) - case unix.RTA_NEWDST: - var d Destination - switch msg.Family { - case nl.FAMILY_MPLS: - d = &MPLSDestination{} - } - if err := d.Decode(attr.Value); err != nil { - return nil, nil, err - } - info.NewDst = d - case unix.RTA_ENCAP_TYPE: - encapType = attr - case unix.RTA_ENCAP: - encap = attr - } - } - - if len(encap.Value) != 0 && len(encapType.Value) != 0 { - typ := int(native.Uint16(encapType.Value[0:2])) - var e Encap - switch typ { - case nl.LWTUNNEL_ENCAP_MPLS: - e = &MPLSEncap{} - if err := e.Decode(encap.Value); err != nil { - return nil, nil, err - } - } - info.Encap = e - } - - return info, value[int(nh.RtNexthop.Len):], nil - } - rest := attr.Value - for len(rest) > 0 { - info, buf, err := parseRtNexthop(rest) - if err != nil { - return route, err - } - route.MultiPath = append(route.MultiPath, info) - rest = buf - } - case unix.RTA_NEWDST: - var d Destination - switch msg.Family { - case nl.FAMILY_MPLS: - d = &MPLSDestination{} - } - if err := d.Decode(attr.Value); err != nil { - return route, err - } - route.NewDst = d - case unix.RTA_ENCAP_TYPE: - encapType = attr - case unix.RTA_ENCAP: - encap = attr - case unix.RTA_METRICS: - metrics, err := nl.ParseRouteAttr(attr.Value) - if err != nil { - return route, err - } - for _, metric := range metrics { - switch metric.Attr.Type { - case unix.RTAX_MTU: - route.MTU = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_WINDOW: - route.Window = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_RTT: - route.Rtt = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_RTTVAR: - route.RttVar = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_SSTHRESH: - route.Ssthresh = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_CWND: - route.Cwnd = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_ADVMSS: - route.AdvMSS = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_REORDERING: - route.Reordering = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_HOPLIMIT: - route.Hoplimit = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_INITCWND: - route.InitCwnd = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_FEATURES: - route.Features = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_RTO_MIN: - route.RtoMin = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_INITRWND: - route.InitRwnd = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_QUICKACK: - route.QuickACK = int(native.Uint32(metric.Value[0:4])) - case unix.RTAX_CC_ALGO: - route.Congctl = nl.BytesToString(metric.Value) - case unix.RTAX_FASTOPEN_NO_COOKIE: - route.FastOpenNoCookie = int(native.Uint32(metric.Value[0:4])) - } - } - } - } - - if len(encap.Value) != 0 && len(encapType.Value) != 0 { - typ := int(native.Uint16(encapType.Value[0:2])) - var e Encap - switch typ { - case nl.LWTUNNEL_ENCAP_MPLS: - e = &MPLSEncap{} - if err := e.Decode(encap.Value); err != nil { - return route, err - } - case nl.LWTUNNEL_ENCAP_SEG6: - e = &SEG6Encap{} - if err := e.Decode(encap.Value); err != nil { - return route, err - } - case nl.LWTUNNEL_ENCAP_SEG6_LOCAL: - e = &SEG6LocalEncap{} - if err := e.Decode(encap.Value); err != nil { - return route, err - } - } - route.Encap = e - } - - return route, nil -} - -// RouteGetOptions contains a set of options to use with -// RouteGetWithOptions -type RouteGetOptions struct { - VrfName string -} - -// RouteGetWithOptions gets a route to a specific destination from the host system. -// Equivalent to: 'ip route get <> vrf '. -func RouteGetWithOptions(destination net.IP, options *RouteGetOptions) ([]Route, error) { - return pkgHandle.RouteGetWithOptions(destination, options) -} - -// RouteGet gets a route to a specific destination from the host system. -// Equivalent to: 'ip route get'. -func RouteGet(destination net.IP) ([]Route, error) { - return pkgHandle.RouteGet(destination) -} - -// RouteGetWithOptions gets a route to a specific destination from the host system. -// Equivalent to: 'ip route get <> vrf '. -func (h *Handle) RouteGetWithOptions(destination net.IP, options *RouteGetOptions) ([]Route, error) { - req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_REQUEST) - family := nl.GetIPFamily(destination) - var destinationData []byte - var bitlen uint8 - if family == FAMILY_V4 { - destinationData = destination.To4() - bitlen = 32 - } else { - destinationData = destination.To16() - bitlen = 128 - } - msg := &nl.RtMsg{} - msg.Family = uint8(family) - msg.Dst_len = bitlen - req.AddData(msg) - - rtaDst := nl.NewRtAttr(unix.RTA_DST, destinationData) - req.AddData(rtaDst) - - if options != nil { - link, err := LinkByName(options.VrfName) - if err != nil { - return nil, err - } - var ( - b = make([]byte, 4) - native = nl.NativeEndian() - ) - native.PutUint32(b, uint32(link.Attrs().Index)) - - req.AddData(nl.NewRtAttr(unix.RTA_OIF, b)) - } - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE) - if err != nil { - return nil, err - } - - var res []Route - for _, m := range msgs { - route, err := deserializeRoute(m) - if err != nil { - return nil, err - } - res = append(res, route) - } - return res, nil -} - -// RouteGet gets a route to a specific destination from the host system. -// Equivalent to: 'ip route get'. -func (h *Handle) RouteGet(destination net.IP) ([]Route, error) { - return h.RouteGetWithOptions(destination, nil) -} - -// RouteSubscribe takes a chan down which notifications will be sent -// when routes are added or deleted. Close the 'done' chan to stop subscription. -func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error { - return routeSubscribeAt(netns.None(), netns.None(), ch, done, nil, false) -} - -// RouteSubscribeAt works like RouteSubscribe plus it allows the caller -// to choose the network namespace in which to subscribe (ns). -func RouteSubscribeAt(ns netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}) error { - return routeSubscribeAt(ns, netns.None(), ch, done, nil, false) -} - -// RouteSubscribeOptions contains a set of options to use with -// RouteSubscribeWithOptions. -type RouteSubscribeOptions struct { - Namespace *netns.NsHandle - ErrorCallback func(error) - ListExisting bool -} - -// RouteSubscribeWithOptions work like RouteSubscribe but enable to -// provide additional options to modify the behavior. Currently, the -// namespace can be provided as well as an error callback. -func RouteSubscribeWithOptions(ch chan<- RouteUpdate, done <-chan struct{}, options RouteSubscribeOptions) error { - if options.Namespace == nil { - none := netns.None() - options.Namespace = &none - } - return routeSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting) -} - -func routeSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}, cberr func(error), listExisting bool) error { - s, err := nl.SubscribeAt(newNs, curNs, unix.NETLINK_ROUTE, unix.RTNLGRP_IPV4_ROUTE, unix.RTNLGRP_IPV6_ROUTE) - if err != nil { - return err - } - if done != nil { - go func() { - <-done - s.Close() - }() - } - if listExisting { - req := pkgHandle.newNetlinkRequest(unix.RTM_GETROUTE, - unix.NLM_F_DUMP) - infmsg := nl.NewIfInfomsg(unix.AF_UNSPEC) - req.AddData(infmsg) - if err := s.Send(req); err != nil { - return err - } - } - go func() { - defer close(ch) - for { - msgs, from, err := s.Receive() - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - if from.Pid != nl.PidKernel { - if cberr != nil { - cberr(fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel)) - } - continue - } - for _, m := range msgs { - if m.Header.Type == unix.NLMSG_DONE { - continue - } - if m.Header.Type == unix.NLMSG_ERROR { - native := nl.NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - if error == 0 { - continue - } - if cberr != nil { - cberr(syscall.Errno(-error)) - } - return - } - route, err := deserializeRoute(m.Data) - if err != nil { - if cberr != nil { - cberr(err) - } - return - } - ch <- RouteUpdate{Type: m.Header.Type, Route: route} - } - } - }() - - return nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/route_unspecified.go b/examples/vendor/github.com/vishvananda/netlink/route_unspecified.go deleted file mode 100644 index 2701862..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/route_unspecified.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !linux - -package netlink - -func (r *Route) ListFlags() []string { - return []string{} -} - -func (n *NexthopInfo) ListFlags() []string { - return []string{} -} diff --git a/examples/vendor/github.com/vishvananda/netlink/rule.go b/examples/vendor/github.com/vishvananda/netlink/rule.go deleted file mode 100644 index 95f2fac..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/rule.go +++ /dev/null @@ -1,56 +0,0 @@ -package netlink - -import ( - "fmt" - "net" -) - -// Rule represents a netlink rule. -type Rule struct { - Priority int - Family int - Table int - Mark int - Mask int - Tos uint - TunID uint - Goto int - Src *net.IPNet - Dst *net.IPNet - Flow int - IifName string - OifName string - SuppressIfgroup int - SuppressPrefixlen int - Invert bool - Dport *RulePortRange - Sport *RulePortRange -} - -func (r Rule) String() string { - return fmt.Sprintf("ip rule %d: from %s table %d", r.Priority, r.Src, r.Table) -} - -// NewRule return empty rules. -func NewRule() *Rule { - return &Rule{ - SuppressIfgroup: -1, - SuppressPrefixlen: -1, - Priority: -1, - Mark: -1, - Mask: -1, - Goto: -1, - Flow: -1, - } -} - -// NewRulePortRange creates rule sport/dport range. -func NewRulePortRange(start, end uint16) *RulePortRange { - return &RulePortRange{Start: start, End: end} -} - -// RulePortRange represents rule sport/dport range. -type RulePortRange struct { - Start uint16 - End uint16 -} diff --git a/examples/vendor/github.com/vishvananda/netlink/rule_linux.go b/examples/vendor/github.com/vishvananda/netlink/rule_linux.go deleted file mode 100644 index 40474f3..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/rule_linux.go +++ /dev/null @@ -1,296 +0,0 @@ -package netlink - -import ( - "bytes" - "fmt" - "net" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -const FibRuleInvert = 0x2 - -// RuleAdd adds a rule to the system. -// Equivalent to: ip rule add -func RuleAdd(rule *Rule) error { - return pkgHandle.RuleAdd(rule) -} - -// RuleAdd adds a rule to the system. -// Equivalent to: ip rule add -func (h *Handle) RuleAdd(rule *Rule) error { - req := h.newNetlinkRequest(unix.RTM_NEWRULE, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) - return ruleHandle(rule, req) -} - -// RuleDel deletes a rule from the system. -// Equivalent to: ip rule del -func RuleDel(rule *Rule) error { - return pkgHandle.RuleDel(rule) -} - -// RuleDel deletes a rule from the system. -// Equivalent to: ip rule del -func (h *Handle) RuleDel(rule *Rule) error { - req := h.newNetlinkRequest(unix.RTM_DELRULE, unix.NLM_F_ACK) - return ruleHandle(rule, req) -} - -func ruleHandle(rule *Rule, req *nl.NetlinkRequest) error { - msg := nl.NewRtMsg() - msg.Family = unix.AF_INET - msg.Protocol = unix.RTPROT_BOOT - msg.Scope = unix.RT_SCOPE_UNIVERSE - msg.Table = unix.RT_TABLE_UNSPEC - msg.Type = unix.RTN_UNSPEC - if req.NlMsghdr.Flags&unix.NLM_F_CREATE > 0 { - msg.Type = unix.RTN_UNICAST - } - if rule.Invert { - msg.Flags |= FibRuleInvert - } - if rule.Family != 0 { - msg.Family = uint8(rule.Family) - } - if rule.Table >= 0 && rule.Table < 256 { - msg.Table = uint8(rule.Table) - } - if rule.Tos != 0 { - msg.Tos = uint8(rule.Tos) - } - - var dstFamily uint8 - var rtAttrs []*nl.RtAttr - if rule.Dst != nil && rule.Dst.IP != nil { - dstLen, _ := rule.Dst.Mask.Size() - msg.Dst_len = uint8(dstLen) - msg.Family = uint8(nl.GetIPFamily(rule.Dst.IP)) - dstFamily = msg.Family - var dstData []byte - if msg.Family == unix.AF_INET { - dstData = rule.Dst.IP.To4() - } else { - dstData = rule.Dst.IP.To16() - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_DST, dstData)) - } - - if rule.Src != nil && rule.Src.IP != nil { - msg.Family = uint8(nl.GetIPFamily(rule.Src.IP)) - if dstFamily != 0 && dstFamily != msg.Family { - return fmt.Errorf("source and destination ip are not the same IP family") - } - srcLen, _ := rule.Src.Mask.Size() - msg.Src_len = uint8(srcLen) - var srcData []byte - if msg.Family == unix.AF_INET { - srcData = rule.Src.IP.To4() - } else { - srcData = rule.Src.IP.To16() - } - rtAttrs = append(rtAttrs, nl.NewRtAttr(unix.RTA_SRC, srcData)) - } - - req.AddData(msg) - for i := range rtAttrs { - req.AddData(rtAttrs[i]) - } - - native := nl.NativeEndian() - - if rule.Priority >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Priority)) - req.AddData(nl.NewRtAttr(nl.FRA_PRIORITY, b)) - } - if rule.Mark >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Mark)) - req.AddData(nl.NewRtAttr(nl.FRA_FWMARK, b)) - } - if rule.Mask >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Mask)) - req.AddData(nl.NewRtAttr(nl.FRA_FWMASK, b)) - } - if rule.Flow >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Flow)) - req.AddData(nl.NewRtAttr(nl.FRA_FLOW, b)) - } - if rule.TunID > 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.TunID)) - req.AddData(nl.NewRtAttr(nl.FRA_TUN_ID, b)) - } - if rule.Table >= 256 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Table)) - req.AddData(nl.NewRtAttr(nl.FRA_TABLE, b)) - } - if msg.Table > 0 { - if rule.SuppressPrefixlen >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.SuppressPrefixlen)) - req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_PREFIXLEN, b)) - } - if rule.SuppressIfgroup >= 0 { - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.SuppressIfgroup)) - req.AddData(nl.NewRtAttr(nl.FRA_SUPPRESS_IFGROUP, b)) - } - } - if rule.IifName != "" { - req.AddData(nl.NewRtAttr(nl.FRA_IIFNAME, []byte(rule.IifName+"\x00"))) - } - if rule.OifName != "" { - req.AddData(nl.NewRtAttr(nl.FRA_OIFNAME, []byte(rule.OifName+"\x00"))) - } - if rule.Goto >= 0 { - msg.Type = nl.FR_ACT_GOTO - b := make([]byte, 4) - native.PutUint32(b, uint32(rule.Goto)) - req.AddData(nl.NewRtAttr(nl.FRA_GOTO, b)) - } - - if rule.Dport != nil { - b := rule.Dport.toRtAttrData() - req.AddData(nl.NewRtAttr(nl.FRA_DPORT_RANGE, b)) - } - - if rule.Sport != nil { - b := rule.Sport.toRtAttrData() - req.AddData(nl.NewRtAttr(nl.FRA_SPORT_RANGE, b)) - } - - _, err := req.Execute(unix.NETLINK_ROUTE, 0) - return err -} - -// RuleList lists rules in the system. -// Equivalent to: ip rule list -func RuleList(family int) ([]Rule, error) { - return pkgHandle.RuleList(family) -} - -// RuleList lists rules in the system. -// Equivalent to: ip rule list -func (h *Handle) RuleList(family int) ([]Rule, error) { - return h.RuleListFiltered(family, nil, 0) -} - -// RuleListFiltered gets a list of rules in the system filtered by the -// specified rule template `filter`. -// Equivalent to: ip rule list -func RuleListFiltered(family int, filter *Rule, filterMask uint64) ([]Rule, error) { - return pkgHandle.RuleListFiltered(family, filter, filterMask) -} - -// RuleListFiltered lists rules in the system. -// Equivalent to: ip rule list -func (h *Handle) RuleListFiltered(family int, filter *Rule, filterMask uint64) ([]Rule, error) { - req := h.newNetlinkRequest(unix.RTM_GETRULE, unix.NLM_F_DUMP|unix.NLM_F_REQUEST) - msg := nl.NewIfInfomsg(family) - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWRULE) - if err != nil { - return nil, err - } - - native := nl.NativeEndian() - var res = make([]Rule, 0) - for i := range msgs { - msg := nl.DeserializeRtMsg(msgs[i]) - attrs, err := nl.ParseRouteAttr(msgs[i][msg.Len():]) - if err != nil { - return nil, err - } - - rule := NewRule() - - rule.Invert = msg.Flags&FibRuleInvert > 0 - rule.Tos = uint(msg.Tos) - - for j := range attrs { - switch attrs[j].Attr.Type { - case unix.RTA_TABLE: - rule.Table = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_SRC: - rule.Src = &net.IPNet{ - IP: attrs[j].Value, - Mask: net.CIDRMask(int(msg.Src_len), 8*len(attrs[j].Value)), - } - case nl.FRA_DST: - rule.Dst = &net.IPNet{ - IP: attrs[j].Value, - Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attrs[j].Value)), - } - case nl.FRA_FWMARK: - rule.Mark = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_FWMASK: - rule.Mask = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_TUN_ID: - rule.TunID = uint(native.Uint64(attrs[j].Value[0:4])) - case nl.FRA_IIFNAME: - rule.IifName = string(attrs[j].Value[:len(attrs[j].Value)-1]) - case nl.FRA_OIFNAME: - rule.OifName = string(attrs[j].Value[:len(attrs[j].Value)-1]) - case nl.FRA_SUPPRESS_PREFIXLEN: - i := native.Uint32(attrs[j].Value[0:4]) - if i != 0xffffffff { - rule.SuppressPrefixlen = int(i) - } - case nl.FRA_SUPPRESS_IFGROUP: - i := native.Uint32(attrs[j].Value[0:4]) - if i != 0xffffffff { - rule.SuppressIfgroup = int(i) - } - case nl.FRA_FLOW: - rule.Flow = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_GOTO: - rule.Goto = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_PRIORITY: - rule.Priority = int(native.Uint32(attrs[j].Value[0:4])) - case nl.FRA_DPORT_RANGE: - rule.Dport = NewRulePortRange(native.Uint16(attrs[j].Value[0:2]), native.Uint16(attrs[j].Value[2:4])) - case nl.FRA_SPORT_RANGE: - rule.Sport = NewRulePortRange(native.Uint16(attrs[j].Value[0:2]), native.Uint16(attrs[j].Value[2:4])) - } - } - - if filter != nil { - switch { - case filterMask&RT_FILTER_SRC != 0 && - (rule.Src == nil || rule.Src.String() != filter.Src.String()): - continue - case filterMask&RT_FILTER_DST != 0 && - (rule.Dst == nil || rule.Dst.String() != filter.Dst.String()): - continue - case filterMask&RT_FILTER_TABLE != 0 && - filter.Table != unix.RT_TABLE_UNSPEC && rule.Table != filter.Table: - continue - case filterMask&RT_FILTER_TOS != 0 && rule.Tos != filter.Tos: - continue - case filterMask&RT_FILTER_PRIORITY != 0 && rule.Priority != filter.Priority: - continue - case filterMask&RT_FILTER_MARK != 0 && rule.Mark != filter.Mark: - continue - case filterMask&RT_FILTER_MASK != 0 && rule.Mask != filter.Mask: - continue - } - } - - res = append(res, *rule) - } - - return res, nil -} - -func (pr *RulePortRange) toRtAttrData() []byte { - b := [][]byte{make([]byte, 2), make([]byte, 2)} - native.PutUint16(b[0], pr.Start) - native.PutUint16(b[1], pr.End) - return bytes.Join(b, []byte{}) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/socket.go b/examples/vendor/github.com/vishvananda/netlink/socket.go deleted file mode 100644 index 41aa726..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/socket.go +++ /dev/null @@ -1,27 +0,0 @@ -package netlink - -import "net" - -// SocketID identifies a single socket. -type SocketID struct { - SourcePort uint16 - DestinationPort uint16 - Source net.IP - Destination net.IP - Interface uint32 - Cookie [2]uint32 -} - -// Socket represents a netlink socket. -type Socket struct { - Family uint8 - State uint8 - Timer uint8 - Retrans uint8 - ID SocketID - Expires uint32 - RQueue uint32 - WQueue uint32 - UID uint32 - INode uint32 -} diff --git a/examples/vendor/github.com/vishvananda/netlink/socket_linux.go b/examples/vendor/github.com/vishvananda/netlink/socket_linux.go deleted file mode 100644 index e4e7f7a..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/socket_linux.go +++ /dev/null @@ -1,238 +0,0 @@ -package netlink - -import ( - "errors" - "fmt" - "net" - "syscall" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -const ( - sizeofSocketID = 0x30 - sizeofSocketRequest = sizeofSocketID + 0x8 - sizeofSocket = sizeofSocketID + 0x18 -) - -type socketRequest struct { - Family uint8 - Protocol uint8 - Ext uint8 - pad uint8 - States uint32 - ID SocketID -} - -type writeBuffer struct { - Bytes []byte - pos int -} - -func (b *writeBuffer) Write(c byte) { - b.Bytes[b.pos] = c - b.pos++ -} - -func (b *writeBuffer) Next(n int) []byte { - s := b.Bytes[b.pos : b.pos+n] - b.pos += n - return s -} - -func (r *socketRequest) Serialize() []byte { - b := writeBuffer{Bytes: make([]byte, sizeofSocketRequest)} - b.Write(r.Family) - b.Write(r.Protocol) - b.Write(r.Ext) - b.Write(r.pad) - native.PutUint32(b.Next(4), r.States) - networkOrder.PutUint16(b.Next(2), r.ID.SourcePort) - networkOrder.PutUint16(b.Next(2), r.ID.DestinationPort) - if r.Family == unix.AF_INET6 { - copy(b.Next(16), r.ID.Source) - copy(b.Next(16), r.ID.Destination) - } else { - copy(b.Next(4), r.ID.Source.To4()) - b.Next(12) - copy(b.Next(4), r.ID.Destination.To4()) - b.Next(12) - } - native.PutUint32(b.Next(4), r.ID.Interface) - native.PutUint32(b.Next(4), r.ID.Cookie[0]) - native.PutUint32(b.Next(4), r.ID.Cookie[1]) - return b.Bytes -} - -func (r *socketRequest) Len() int { return sizeofSocketRequest } - -type readBuffer struct { - Bytes []byte - pos int -} - -func (b *readBuffer) Read() byte { - c := b.Bytes[b.pos] - b.pos++ - return c -} - -func (b *readBuffer) Next(n int) []byte { - s := b.Bytes[b.pos : b.pos+n] - b.pos += n - return s -} - -func (s *Socket) deserialize(b []byte) error { - if len(b) < sizeofSocket { - return fmt.Errorf("socket data short read (%d); want %d", len(b), sizeofSocket) - } - rb := readBuffer{Bytes: b} - s.Family = rb.Read() - s.State = rb.Read() - s.Timer = rb.Read() - s.Retrans = rb.Read() - s.ID.SourcePort = networkOrder.Uint16(rb.Next(2)) - s.ID.DestinationPort = networkOrder.Uint16(rb.Next(2)) - if s.Family == unix.AF_INET6 { - s.ID.Source = net.IP(rb.Next(16)) - s.ID.Destination = net.IP(rb.Next(16)) - } else { - s.ID.Source = net.IPv4(rb.Read(), rb.Read(), rb.Read(), rb.Read()) - rb.Next(12) - s.ID.Destination = net.IPv4(rb.Read(), rb.Read(), rb.Read(), rb.Read()) - rb.Next(12) - } - s.ID.Interface = native.Uint32(rb.Next(4)) - s.ID.Cookie[0] = native.Uint32(rb.Next(4)) - s.ID.Cookie[1] = native.Uint32(rb.Next(4)) - s.Expires = native.Uint32(rb.Next(4)) - s.RQueue = native.Uint32(rb.Next(4)) - s.WQueue = native.Uint32(rb.Next(4)) - s.UID = native.Uint32(rb.Next(4)) - s.INode = native.Uint32(rb.Next(4)) - return nil -} - -// SocketGet returns the Socket identified by its local and remote addresses. -func SocketGet(local, remote net.Addr) (*Socket, error) { - localTCP, ok := local.(*net.TCPAddr) - if !ok { - return nil, ErrNotImplemented - } - remoteTCP, ok := remote.(*net.TCPAddr) - if !ok { - return nil, ErrNotImplemented - } - localIP := localTCP.IP.To4() - if localIP == nil { - return nil, ErrNotImplemented - } - remoteIP := remoteTCP.IP.To4() - if remoteIP == nil { - return nil, ErrNotImplemented - } - - s, err := nl.Subscribe(unix.NETLINK_INET_DIAG) - if err != nil { - return nil, err - } - defer s.Close() - req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, 0) - req.AddData(&socketRequest{ - Family: unix.AF_INET, - Protocol: unix.IPPROTO_TCP, - ID: SocketID{ - SourcePort: uint16(localTCP.Port), - DestinationPort: uint16(remoteTCP.Port), - Source: localIP, - Destination: remoteIP, - Cookie: [2]uint32{nl.TCPDIAG_NOCOOKIE, nl.TCPDIAG_NOCOOKIE}, - }, - }) - s.Send(req) - msgs, from, err := s.Receive() - if err != nil { - return nil, err - } - if from.Pid != nl.PidKernel { - return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel) - } - if len(msgs) == 0 { - return nil, errors.New("no message nor error from netlink") - } - if len(msgs) > 2 { - return nil, fmt.Errorf("multiple (%d) matching sockets", len(msgs)) - } - sock := &Socket{} - if err := sock.deserialize(msgs[0].Data); err != nil { - return nil, err - } - return sock, nil -} - -// SocketDiagTCPInfo requests INET_DIAG_INFO for TCP protocol for specified family type. -func SocketDiagTCPInfo(family uint8) ([]*InetDiagTCPInfoResp, error) { - s, err := nl.Subscribe(unix.NETLINK_INET_DIAG) - if err != nil { - return nil, err - } - defer s.Close() - - req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP) - req.AddData(&socketRequest{ - Family: family, - Protocol: unix.IPPROTO_TCP, - Ext: INET_DIAG_INFO, - States: uint32(0xfff), // All TCP states - }) - s.Send(req) - - var result []*InetDiagTCPInfoResp -loop: - for { - msgs, from, err := s.Receive() - if err != nil { - return nil, err - } - if from.Pid != nl.PidKernel { - return nil, fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel) - } - if len(msgs) == 0 { - return nil, errors.New("no message nor error from netlink") - } - - for _, m := range msgs { - switch m.Header.Type { - case unix.NLMSG_DONE: - break loop - case unix.NLMSG_ERROR: - native := nl.NativeEndian() - error := int32(native.Uint32(m.Data[0:4])) - return nil, syscall.Errno(-error) - } - sockInfo := &Socket{} - if err := sockInfo.deserialize(m.Data); err != nil { - return nil, err - } - attrs, err := nl.ParseRouteAttr(m.Data[sizeofSocket:]) - if err != nil { - return nil, err - } - var tcpInfo *TCPInfo - for _, a := range attrs { - if a.Attr.Type == INET_DIAG_INFO { - tcpInfo = &TCPInfo{} - if err := tcpInfo.deserialize(a.Value); err != nil { - return nil, err - } - break - } - } - r := &InetDiagTCPInfoResp{InetDiagMsg: sockInfo, TCPInfo: tcpInfo} - result = append(result, r) - } - } - return result, nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/tcp.go b/examples/vendor/github.com/vishvananda/netlink/tcp.go deleted file mode 100644 index 4a42ee5..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/tcp.go +++ /dev/null @@ -1,18 +0,0 @@ -package netlink - -// TCP States -const ( - TCP_ESTABLISHED = iota + 0x01 - TCP_SYN_SENT - TCP_SYN_RECV - TCP_FIN_WAIT1 - TCP_FIN_WAIT2 - TCP_TIME_WAIT - TCP_CLOSE - TCP_CLOSE_WAIT - TCP_LAST_ACK - TCP_LISTEN - TCP_CLOSING - TCP_NEW_SYN_REC - TCP_MAX_STATES -) diff --git a/examples/vendor/github.com/vishvananda/netlink/tcp_linux.go b/examples/vendor/github.com/vishvananda/netlink/tcp_linux.go deleted file mode 100644 index 741ea16..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/tcp_linux.go +++ /dev/null @@ -1,393 +0,0 @@ -package netlink - -import ( - "bytes" - "io" -) - -type TCPInfo struct { - State uint8 - Ca_state uint8 - Retransmits uint8 - Probes uint8 - Backoff uint8 - Options uint8 - Snd_wscale uint8 // no uint4 - Rcv_wscale uint8 - Delivery_rate_app_limited uint8 - Fastopen_client_fail uint8 - Rto uint32 - Ato uint32 - Snd_mss uint32 - Rcv_mss uint32 - Unacked uint32 - Sacked uint32 - Lost uint32 - Retrans uint32 - Fackets uint32 - Last_data_sent uint32 - Last_ack_sent uint32 - Last_data_recv uint32 - Last_ack_recv uint32 - Pmtu uint32 - Rcv_ssthresh uint32 - Rtt uint32 - Rttvar uint32 - Snd_ssthresh uint32 - Snd_cwnd uint32 - Advmss uint32 - Reordering uint32 - Rcv_rtt uint32 - Rcv_space uint32 - Total_retrans uint32 - Pacing_rate uint64 - Max_pacing_rate uint64 - Bytes_acked uint64 /* RFC4898 tcpEStatsAppHCThruOctetsAcked */ - Bytes_received uint64 /* RFC4898 tcpEStatsAppHCThruOctetsReceived */ - Segs_out uint32 /* RFC4898 tcpEStatsPerfSegsOut */ - Segs_in uint32 /* RFC4898 tcpEStatsPerfSegsIn */ - Notsent_bytes uint32 - Min_rtt uint32 - Data_segs_in uint32 /* RFC4898 tcpEStatsDataSegsIn */ - Data_segs_out uint32 /* RFC4898 tcpEStatsDataSegsOut */ - Delivery_rate uint64 - Busy_time uint64 /* Time (usec) busy sending data */ - Rwnd_limited uint64 /* Time (usec) limited by receive window */ - Sndbuf_limited uint64 /* Time (usec) limited by send buffer */ - Delivered uint32 - Delivered_ce uint32 - Bytes_sent uint64 /* RFC4898 tcpEStatsPerfHCDataOctetsOut */ - Bytes_retrans uint64 /* RFC4898 tcpEStatsPerfOctetsRetrans */ - Dsack_dups uint32 /* RFC4898 tcpEStatsStackDSACKDups */ - Reord_seen uint32 /* reordering events seen */ - Rcv_ooopack uint32 /* Out-of-order packets received */ - Snd_wnd uint32 /* peer's advertised receive window after * scaling (bytes) */ -} - -func checkDeserErr(err error) error { - if err == io.EOF { - return nil - } - return err -} - -func (t *TCPInfo) deserialize(b []byte) error { - var err error - rb := bytes.NewBuffer(b) - - t.State, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - - t.Ca_state, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - - t.Retransmits, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - - t.Probes, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - - t.Backoff, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - t.Options, err = rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - - scales, err := rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - t.Snd_wscale = scales >> 4 // first 4 bits - t.Rcv_wscale = scales & 0xf // last 4 bits - - rateLimAndFastOpen, err := rb.ReadByte() - if err != nil { - return checkDeserErr(err) - } - t.Delivery_rate_app_limited = rateLimAndFastOpen >> 7 // get first bit - t.Fastopen_client_fail = rateLimAndFastOpen >> 5 & 3 // get next two bits - - next := rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rto = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Ato = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Snd_mss = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rcv_mss = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Unacked = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Sacked = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Lost = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Retrans = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Fackets = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Last_data_sent = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Last_ack_sent = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Last_data_recv = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Last_ack_recv = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Pmtu = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rcv_ssthresh = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rtt = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rttvar = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Snd_ssthresh = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Snd_cwnd = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Advmss = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Reordering = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rcv_rtt = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rcv_space = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Total_retrans = native.Uint32(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Pacing_rate = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Max_pacing_rate = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Bytes_acked = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Bytes_received = native.Uint64(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Segs_out = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Segs_in = native.Uint32(next) - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Notsent_bytes = native.Uint32(next) - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Min_rtt = native.Uint32(next) - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Data_segs_in = native.Uint32(next) - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Data_segs_out = native.Uint32(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Delivery_rate = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Busy_time = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Rwnd_limited = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Sndbuf_limited = native.Uint64(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Delivered = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Delivered_ce = native.Uint32(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Bytes_sent = native.Uint64(next) - - next = rb.Next(8) - if len(next) == 0 { - return nil - } - t.Bytes_retrans = native.Uint64(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Dsack_dups = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Reord_seen = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Rcv_ooopack = native.Uint32(next) - - next = rb.Next(4) - if len(next) == 0 { - return nil - } - t.Snd_wnd = native.Uint32(next) - return nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm.go b/examples/vendor/github.com/vishvananda/netlink/xfrm.go deleted file mode 100644 index 02b4184..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm.go +++ /dev/null @@ -1,75 +0,0 @@ -package netlink - -import ( - "fmt" - - "golang.org/x/sys/unix" -) - -// Proto is an enum representing an ipsec protocol. -type Proto uint8 - -const ( - XFRM_PROTO_ROUTE2 Proto = unix.IPPROTO_ROUTING - XFRM_PROTO_ESP Proto = unix.IPPROTO_ESP - XFRM_PROTO_AH Proto = unix.IPPROTO_AH - XFRM_PROTO_HAO Proto = unix.IPPROTO_DSTOPTS - XFRM_PROTO_COMP Proto = 0x6c // NOTE not defined on darwin - XFRM_PROTO_IPSEC_ANY Proto = unix.IPPROTO_RAW -) - -func (p Proto) String() string { - switch p { - case XFRM_PROTO_ROUTE2: - return "route2" - case XFRM_PROTO_ESP: - return "esp" - case XFRM_PROTO_AH: - return "ah" - case XFRM_PROTO_HAO: - return "hao" - case XFRM_PROTO_COMP: - return "comp" - case XFRM_PROTO_IPSEC_ANY: - return "ipsec-any" - } - return fmt.Sprintf("%d", p) -} - -// Mode is an enum representing an ipsec transport. -type Mode uint8 - -const ( - XFRM_MODE_TRANSPORT Mode = iota - XFRM_MODE_TUNNEL - XFRM_MODE_ROUTEOPTIMIZATION - XFRM_MODE_IN_TRIGGER - XFRM_MODE_BEET - XFRM_MODE_MAX -) - -func (m Mode) String() string { - switch m { - case XFRM_MODE_TRANSPORT: - return "transport" - case XFRM_MODE_TUNNEL: - return "tunnel" - case XFRM_MODE_ROUTEOPTIMIZATION: - return "ro" - case XFRM_MODE_IN_TRIGGER: - return "in_trigger" - case XFRM_MODE_BEET: - return "beet" - } - return fmt.Sprintf("%d", m) -} - -// XfrmMark represents the mark associated to the state or policy -type XfrmMark struct { - Value uint32 - Mask uint32 -} - -func (m *XfrmMark) String() string { - return fmt.Sprintf("(0x%x,0x%x)", m.Value, m.Mask) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go b/examples/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go deleted file mode 100644 index 985d3a9..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm_monitor_linux.go +++ /dev/null @@ -1,101 +0,0 @@ -package netlink - -import ( - "fmt" - - "github.com/vishvananda/netlink/nl" - "github.com/vishvananda/netns" - "golang.org/x/sys/unix" -) - -type XfrmMsg interface { - Type() nl.XfrmMsgType -} - -type XfrmMsgExpire struct { - XfrmState *XfrmState - Hard bool -} - -func (ue *XfrmMsgExpire) Type() nl.XfrmMsgType { - return nl.XFRM_MSG_EXPIRE -} - -func parseXfrmMsgExpire(b []byte) *XfrmMsgExpire { - var e XfrmMsgExpire - - msg := nl.DeserializeXfrmUserExpire(b) - e.XfrmState = xfrmStateFromXfrmUsersaInfo(&msg.XfrmUsersaInfo) - e.Hard = msg.Hard == 1 - - return &e -} - -func XfrmMonitor(ch chan<- XfrmMsg, done <-chan struct{}, errorChan chan<- error, - types ...nl.XfrmMsgType) error { - - groups, err := xfrmMcastGroups(types) - if err != nil { - return nil - } - s, err := nl.SubscribeAt(netns.None(), netns.None(), unix.NETLINK_XFRM, groups...) - if err != nil { - return err - } - - if done != nil { - go func() { - <-done - s.Close() - }() - - } - - go func() { - defer close(ch) - for { - msgs, from, err := s.Receive() - if err != nil { - errorChan <- err - return - } - if from.Pid != nl.PidKernel { - errorChan <- fmt.Errorf("Wrong sender portid %d, expected %d", from.Pid, nl.PidKernel) - return - } - for _, m := range msgs { - switch m.Header.Type { - case nl.XFRM_MSG_EXPIRE: - ch <- parseXfrmMsgExpire(m.Data) - default: - errorChan <- fmt.Errorf("unsupported msg type: %x", m.Header.Type) - } - } - } - }() - - return nil -} - -func xfrmMcastGroups(types []nl.XfrmMsgType) ([]uint, error) { - groups := make([]uint, 0) - - if len(types) == 0 { - return nil, fmt.Errorf("no xfrm msg type specified") - } - - for _, t := range types { - var group uint - - switch t { - case nl.XFRM_MSG_EXPIRE: - group = nl.XFRMNLGRP_EXPIRE - default: - return nil, fmt.Errorf("unsupported group: %x", t) - } - - groups = append(groups, group) - } - - return groups, nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm_policy.go b/examples/vendor/github.com/vishvananda/netlink/xfrm_policy.go deleted file mode 100644 index 6219d27..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm_policy.go +++ /dev/null @@ -1,96 +0,0 @@ -package netlink - -import ( - "fmt" - "net" -) - -// Dir is an enum representing an ipsec template direction. -type Dir uint8 - -const ( - XFRM_DIR_IN Dir = iota - XFRM_DIR_OUT - XFRM_DIR_FWD - XFRM_SOCKET_IN - XFRM_SOCKET_OUT - XFRM_SOCKET_FWD -) - -func (d Dir) String() string { - switch d { - case XFRM_DIR_IN: - return "dir in" - case XFRM_DIR_OUT: - return "dir out" - case XFRM_DIR_FWD: - return "dir fwd" - case XFRM_SOCKET_IN: - return "socket in" - case XFRM_SOCKET_OUT: - return "socket out" - case XFRM_SOCKET_FWD: - return "socket fwd" - } - return fmt.Sprintf("socket %d", d-XFRM_SOCKET_IN) -} - -// PolicyAction is an enum representing an ipsec policy action. -type PolicyAction uint8 - -const ( - XFRM_POLICY_ALLOW PolicyAction = 0 - XFRM_POLICY_BLOCK PolicyAction = 1 -) - -func (a PolicyAction) String() string { - switch a { - case XFRM_POLICY_ALLOW: - return "allow" - case XFRM_POLICY_BLOCK: - return "block" - default: - return fmt.Sprintf("action %d", a) - } -} - -// XfrmPolicyTmpl encapsulates a rule for the base addresses of an ipsec -// policy. These rules are matched with XfrmState to determine encryption -// and authentication algorithms. -type XfrmPolicyTmpl struct { - Dst net.IP - Src net.IP - Proto Proto - Mode Mode - Spi int - Reqid int -} - -func (t XfrmPolicyTmpl) String() string { - return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, Mode: %s, Spi: 0x%x, Reqid: 0x%x}", - t.Dst, t.Src, t.Proto, t.Mode, t.Spi, t.Reqid) -} - -// XfrmPolicy represents an ipsec policy. It represents the overlay network -// and has a list of XfrmPolicyTmpls representing the base addresses of -// the policy. -type XfrmPolicy struct { - Dst *net.IPNet - Src *net.IPNet - Proto Proto - DstPort int - SrcPort int - Dir Dir - Priority int - Index int - Action PolicyAction - Ifindex int - Ifid int - Mark *XfrmMark - Tmpls []XfrmPolicyTmpl -} - -func (p XfrmPolicy) String() string { - return fmt.Sprintf("{Dst: %v, Src: %v, Proto: %s, DstPort: %d, SrcPort: %d, Dir: %s, Priority: %d, Index: %d, Action: %s, Ifindex: %d, Ifid: %d, Mark: %s, Tmpls: %s}", - p.Dst, p.Src, p.Proto, p.DstPort, p.SrcPort, p.Dir, p.Priority, p.Index, p.Action, p.Ifindex, p.Ifid, p.Mark, p.Tmpls) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go b/examples/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go deleted file mode 100644 index a4e132e..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go +++ /dev/null @@ -1,263 +0,0 @@ -package netlink - -import ( - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) { - sel.Family = uint16(nl.FAMILY_V4) - if policy.Dst != nil { - sel.Family = uint16(nl.GetIPFamily(policy.Dst.IP)) - sel.Daddr.FromIP(policy.Dst.IP) - prefixlenD, _ := policy.Dst.Mask.Size() - sel.PrefixlenD = uint8(prefixlenD) - } - if policy.Src != nil { - sel.Saddr.FromIP(policy.Src.IP) - prefixlenS, _ := policy.Src.Mask.Size() - sel.PrefixlenS = uint8(prefixlenS) - } - sel.Proto = uint8(policy.Proto) - sel.Dport = nl.Swap16(uint16(policy.DstPort)) - sel.Sport = nl.Swap16(uint16(policy.SrcPort)) - if sel.Dport != 0 { - sel.DportMask = ^uint16(0) - } - if sel.Sport != 0 { - sel.SportMask = ^uint16(0) - } - sel.Ifindex = int32(policy.Ifindex) -} - -// XfrmPolicyAdd will add an xfrm policy to the system. -// Equivalent to: `ip xfrm policy add $policy` -func XfrmPolicyAdd(policy *XfrmPolicy) error { - return pkgHandle.XfrmPolicyAdd(policy) -} - -// XfrmPolicyAdd will add an xfrm policy to the system. -// Equivalent to: `ip xfrm policy add $policy` -func (h *Handle) XfrmPolicyAdd(policy *XfrmPolicy) error { - return h.xfrmPolicyAddOrUpdate(policy, nl.XFRM_MSG_NEWPOLICY) -} - -// XfrmPolicyUpdate will update an xfrm policy to the system. -// Equivalent to: `ip xfrm policy update $policy` -func XfrmPolicyUpdate(policy *XfrmPolicy) error { - return pkgHandle.XfrmPolicyUpdate(policy) -} - -// XfrmPolicyUpdate will update an xfrm policy to the system. -// Equivalent to: `ip xfrm policy update $policy` -func (h *Handle) XfrmPolicyUpdate(policy *XfrmPolicy) error { - return h.xfrmPolicyAddOrUpdate(policy, nl.XFRM_MSG_UPDPOLICY) -} - -func (h *Handle) xfrmPolicyAddOrUpdate(policy *XfrmPolicy, nlProto int) error { - req := h.newNetlinkRequest(nlProto, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) - - msg := &nl.XfrmUserpolicyInfo{} - selFromPolicy(&msg.Sel, policy) - msg.Priority = uint32(policy.Priority) - msg.Index = uint32(policy.Index) - msg.Dir = uint8(policy.Dir) - msg.Action = uint8(policy.Action) - msg.Lft.SoftByteLimit = nl.XFRM_INF - msg.Lft.HardByteLimit = nl.XFRM_INF - msg.Lft.SoftPacketLimit = nl.XFRM_INF - msg.Lft.HardPacketLimit = nl.XFRM_INF - req.AddData(msg) - - tmplData := make([]byte, nl.SizeofXfrmUserTmpl*len(policy.Tmpls)) - for i, tmpl := range policy.Tmpls { - start := i * nl.SizeofXfrmUserTmpl - userTmpl := nl.DeserializeXfrmUserTmpl(tmplData[start : start+nl.SizeofXfrmUserTmpl]) - userTmpl.XfrmId.Daddr.FromIP(tmpl.Dst) - userTmpl.Saddr.FromIP(tmpl.Src) - userTmpl.XfrmId.Proto = uint8(tmpl.Proto) - userTmpl.XfrmId.Spi = nl.Swap32(uint32(tmpl.Spi)) - userTmpl.Mode = uint8(tmpl.Mode) - userTmpl.Reqid = uint32(tmpl.Reqid) - userTmpl.Aalgos = ^uint32(0) - userTmpl.Ealgos = ^uint32(0) - userTmpl.Calgos = ^uint32(0) - } - if len(tmplData) > 0 { - tmpls := nl.NewRtAttr(nl.XFRMA_TMPL, tmplData) - req.AddData(tmpls) - } - if policy.Mark != nil { - out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(policy.Mark)) - req.AddData(out) - } - - ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(policy.Ifid))) - req.AddData(ifId) - - _, err := req.Execute(unix.NETLINK_XFRM, 0) - return err -} - -// XfrmPolicyDel will delete an xfrm policy from the system. Note that -// the Tmpls are ignored when matching the policy to delete. -// Equivalent to: `ip xfrm policy del $policy` -func XfrmPolicyDel(policy *XfrmPolicy) error { - return pkgHandle.XfrmPolicyDel(policy) -} - -// XfrmPolicyDel will delete an xfrm policy from the system. Note that -// the Tmpls are ignored when matching the policy to delete. -// Equivalent to: `ip xfrm policy del $policy` -func (h *Handle) XfrmPolicyDel(policy *XfrmPolicy) error { - _, err := h.xfrmPolicyGetOrDelete(policy, nl.XFRM_MSG_DELPOLICY) - return err -} - -// XfrmPolicyList gets a list of xfrm policies in the system. -// Equivalent to: `ip xfrm policy show`. -// The list can be filtered by ip family. -func XfrmPolicyList(family int) ([]XfrmPolicy, error) { - return pkgHandle.XfrmPolicyList(family) -} - -// XfrmPolicyList gets a list of xfrm policies in the system. -// Equivalent to: `ip xfrm policy show`. -// The list can be filtered by ip family. -func (h *Handle) XfrmPolicyList(family int) ([]XfrmPolicy, error) { - req := h.newNetlinkRequest(nl.XFRM_MSG_GETPOLICY, unix.NLM_F_DUMP) - - msg := nl.NewIfInfomsg(family) - req.AddData(msg) - - msgs, err := req.Execute(unix.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY) - if err != nil { - return nil, err - } - - var res []XfrmPolicy - for _, m := range msgs { - if policy, err := parseXfrmPolicy(m, family); err == nil { - res = append(res, *policy) - } else if err == familyError { - continue - } else { - return nil, err - } - } - return res, nil -} - -// XfrmPolicyGet gets a the policy described by the index or selector, if found. -// Equivalent to: `ip xfrm policy get { SELECTOR | index INDEX } dir DIR [ctx CTX ] [ mark MARK [ mask MASK ] ] [ ptype PTYPE ]`. -func XfrmPolicyGet(policy *XfrmPolicy) (*XfrmPolicy, error) { - return pkgHandle.XfrmPolicyGet(policy) -} - -// XfrmPolicyGet gets a the policy described by the index or selector, if found. -// Equivalent to: `ip xfrm policy get { SELECTOR | index INDEX } dir DIR [ctx CTX ] [ mark MARK [ mask MASK ] ] [ ptype PTYPE ]`. -func (h *Handle) XfrmPolicyGet(policy *XfrmPolicy) (*XfrmPolicy, error) { - return h.xfrmPolicyGetOrDelete(policy, nl.XFRM_MSG_GETPOLICY) -} - -// XfrmPolicyFlush will flush the policies on the system. -// Equivalent to: `ip xfrm policy flush` -func XfrmPolicyFlush() error { - return pkgHandle.XfrmPolicyFlush() -} - -// XfrmPolicyFlush will flush the policies on the system. -// Equivalent to: `ip xfrm policy flush` -func (h *Handle) XfrmPolicyFlush() error { - req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHPOLICY, unix.NLM_F_ACK) - _, err := req.Execute(unix.NETLINK_XFRM, 0) - return err -} - -func (h *Handle) xfrmPolicyGetOrDelete(policy *XfrmPolicy, nlProto int) (*XfrmPolicy, error) { - req := h.newNetlinkRequest(nlProto, unix.NLM_F_ACK) - - msg := &nl.XfrmUserpolicyId{} - selFromPolicy(&msg.Sel, policy) - msg.Index = uint32(policy.Index) - msg.Dir = uint8(policy.Dir) - req.AddData(msg) - - if policy.Mark != nil { - out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(policy.Mark)) - req.AddData(out) - } - - ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(policy.Ifid))) - req.AddData(ifId) - - resType := nl.XFRM_MSG_NEWPOLICY - if nlProto == nl.XFRM_MSG_DELPOLICY { - resType = 0 - } - - msgs, err := req.Execute(unix.NETLINK_XFRM, uint16(resType)) - if err != nil { - return nil, err - } - - if nlProto == nl.XFRM_MSG_DELPOLICY { - return nil, err - } - - return parseXfrmPolicy(msgs[0], FAMILY_ALL) -} - -func parseXfrmPolicy(m []byte, family int) (*XfrmPolicy, error) { - msg := nl.DeserializeXfrmUserpolicyInfo(m) - - // This is mainly for the policy dump - if family != FAMILY_ALL && family != int(msg.Sel.Family) { - return nil, familyError - } - - var policy XfrmPolicy - - policy.Dst = msg.Sel.Daddr.ToIPNet(msg.Sel.PrefixlenD) - policy.Src = msg.Sel.Saddr.ToIPNet(msg.Sel.PrefixlenS) - policy.Proto = Proto(msg.Sel.Proto) - policy.DstPort = int(nl.Swap16(msg.Sel.Dport)) - policy.SrcPort = int(nl.Swap16(msg.Sel.Sport)) - policy.Ifindex = int(msg.Sel.Ifindex) - policy.Priority = int(msg.Priority) - policy.Index = int(msg.Index) - policy.Dir = Dir(msg.Dir) - policy.Action = PolicyAction(msg.Action) - - attrs, err := nl.ParseRouteAttr(m[msg.Len():]) - if err != nil { - return nil, err - } - - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.XFRMA_TMPL: - max := len(attr.Value) - for i := 0; i < max; i += nl.SizeofXfrmUserTmpl { - var resTmpl XfrmPolicyTmpl - tmpl := nl.DeserializeXfrmUserTmpl(attr.Value[i : i+nl.SizeofXfrmUserTmpl]) - resTmpl.Dst = tmpl.XfrmId.Daddr.ToIP() - resTmpl.Src = tmpl.Saddr.ToIP() - resTmpl.Proto = Proto(tmpl.XfrmId.Proto) - resTmpl.Mode = Mode(tmpl.Mode) - resTmpl.Spi = int(nl.Swap32(tmpl.XfrmId.Spi)) - resTmpl.Reqid = int(tmpl.Reqid) - policy.Tmpls = append(policy.Tmpls, resTmpl) - } - case nl.XFRMA_MARK: - mark := nl.DeserializeXfrmMark(attr.Value[:]) - policy.Mark = new(XfrmMark) - policy.Mark.Value = mark.Value - policy.Mark.Mask = mark.Mask - case nl.XFRMA_IF_ID: - policy.Ifid = int(native.Uint32(attr.Value)) - } - } - - return &policy, nil -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm_state.go b/examples/vendor/github.com/vishvananda/netlink/xfrm_state.go deleted file mode 100644 index 483d893..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm_state.go +++ /dev/null @@ -1,131 +0,0 @@ -package netlink - -import ( - "fmt" - "net" - "time" -) - -// XfrmStateAlgo represents the algorithm to use for the ipsec encryption. -type XfrmStateAlgo struct { - Name string - Key []byte - TruncateLen int // Auth only - ICVLen int // AEAD only -} - -func (a XfrmStateAlgo) String() string { - base := fmt.Sprintf("{Name: %s, Key: 0x%x", a.Name, a.Key) - if a.TruncateLen != 0 { - base = fmt.Sprintf("%s, Truncate length: %d", base, a.TruncateLen) - } - if a.ICVLen != 0 { - base = fmt.Sprintf("%s, ICV length: %d", base, a.ICVLen) - } - return fmt.Sprintf("%s}", base) -} - -// EncapType is an enum representing the optional packet encapsulation. -type EncapType uint8 - -const ( - XFRM_ENCAP_ESPINUDP_NONIKE EncapType = iota + 1 - XFRM_ENCAP_ESPINUDP -) - -func (e EncapType) String() string { - switch e { - case XFRM_ENCAP_ESPINUDP_NONIKE: - return "espinudp-non-ike" - case XFRM_ENCAP_ESPINUDP: - return "espinudp" - } - return "unknown" -} - -// XfrmStateEncap represents the encapsulation to use for the ipsec encryption. -type XfrmStateEncap struct { - Type EncapType - SrcPort int - DstPort int - OriginalAddress net.IP -} - -func (e XfrmStateEncap) String() string { - return fmt.Sprintf("{Type: %s, Srcport: %d, DstPort: %d, OriginalAddress: %v}", - e.Type, e.SrcPort, e.DstPort, e.OriginalAddress) -} - -// XfrmStateLimits represents the configured limits for the state. -type XfrmStateLimits struct { - ByteSoft uint64 - ByteHard uint64 - PacketSoft uint64 - PacketHard uint64 - TimeSoft uint64 - TimeHard uint64 - TimeUseSoft uint64 - TimeUseHard uint64 -} - -// XfrmStateStats represents the current number of bytes/packets -// processed by this State, the State's installation and first use -// time and the replay window counters. -type XfrmStateStats struct { - ReplayWindow uint32 - Replay uint32 - Failed uint32 - Bytes uint64 - Packets uint64 - AddTime uint64 - UseTime uint64 -} - -// XfrmState represents the state of an ipsec policy. It optionally -// contains an XfrmStateAlgo for encryption and one for authentication. -type XfrmState struct { - Dst net.IP - Src net.IP - Proto Proto - Mode Mode - Spi int - Reqid int - ReplayWindow int - Limits XfrmStateLimits - Statistics XfrmStateStats - Mark *XfrmMark - OutputMark int - Ifid int - Auth *XfrmStateAlgo - Crypt *XfrmStateAlgo - Aead *XfrmStateAlgo - Encap *XfrmStateEncap - ESN bool -} - -func (sa XfrmState) String() string { - return fmt.Sprintf("Dst: %v, Src: %v, Proto: %s, Mode: %s, SPI: 0x%x, ReqID: 0x%x, ReplayWindow: %d, Mark: %v, OutputMark: %d, Ifid: %d, Auth: %v, Crypt: %v, Aead: %v, Encap: %v, ESN: %t", - sa.Dst, sa.Src, sa.Proto, sa.Mode, sa.Spi, sa.Reqid, sa.ReplayWindow, sa.Mark, sa.OutputMark, sa.Ifid, sa.Auth, sa.Crypt, sa.Aead, sa.Encap, sa.ESN) -} -func (sa XfrmState) Print(stats bool) string { - if !stats { - return sa.String() - } - at := time.Unix(int64(sa.Statistics.AddTime), 0).Format(time.UnixDate) - ut := "-" - if sa.Statistics.UseTime > 0 { - ut = time.Unix(int64(sa.Statistics.UseTime), 0).Format(time.UnixDate) - } - return fmt.Sprintf("%s, ByteSoft: %s, ByteHard: %s, PacketSoft: %s, PacketHard: %s, TimeSoft: %d, TimeHard: %d, TimeUseSoft: %d, TimeUseHard: %d, Bytes: %d, Packets: %d, "+ - "AddTime: %s, UseTime: %s, ReplayWindow: %d, Replay: %d, Failed: %d", - sa.String(), printLimit(sa.Limits.ByteSoft), printLimit(sa.Limits.ByteHard), printLimit(sa.Limits.PacketSoft), printLimit(sa.Limits.PacketHard), - sa.Limits.TimeSoft, sa.Limits.TimeHard, sa.Limits.TimeUseSoft, sa.Limits.TimeUseHard, sa.Statistics.Bytes, sa.Statistics.Packets, at, ut, - sa.Statistics.ReplayWindow, sa.Statistics.Replay, sa.Statistics.Failed) -} - -func printLimit(lmt uint64) string { - if lmt == ^uint64(0) { - return "(INF)" - } - return fmt.Sprintf("%d", lmt) -} diff --git a/examples/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go b/examples/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go deleted file mode 100644 index 66c9942..0000000 --- a/examples/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go +++ /dev/null @@ -1,462 +0,0 @@ -package netlink - -import ( - "fmt" - "unsafe" - - "github.com/vishvananda/netlink/nl" - "golang.org/x/sys/unix" -) - -func writeStateAlgo(a *XfrmStateAlgo) []byte { - algo := nl.XfrmAlgo{ - AlgKeyLen: uint32(len(a.Key) * 8), - AlgKey: a.Key, - } - end := len(a.Name) - if end > 64 { - end = 64 - } - copy(algo.AlgName[:end], a.Name) - return algo.Serialize() -} - -func writeStateAlgoAuth(a *XfrmStateAlgo) []byte { - algo := nl.XfrmAlgoAuth{ - AlgKeyLen: uint32(len(a.Key) * 8), - AlgTruncLen: uint32(a.TruncateLen), - AlgKey: a.Key, - } - end := len(a.Name) - if end > 64 { - end = 64 - } - copy(algo.AlgName[:end], a.Name) - return algo.Serialize() -} - -func writeStateAlgoAead(a *XfrmStateAlgo) []byte { - algo := nl.XfrmAlgoAEAD{ - AlgKeyLen: uint32(len(a.Key) * 8), - AlgICVLen: uint32(a.ICVLen), - AlgKey: a.Key, - } - end := len(a.Name) - if end > 64 { - end = 64 - } - copy(algo.AlgName[:end], a.Name) - return algo.Serialize() -} - -func writeMark(m *XfrmMark) []byte { - mark := &nl.XfrmMark{ - Value: m.Value, - Mask: m.Mask, - } - if mark.Mask == 0 { - mark.Mask = ^uint32(0) - } - return mark.Serialize() -} - -func writeReplayEsn(replayWindow int) []byte { - replayEsn := &nl.XfrmReplayStateEsn{ - OSeq: 0, - Seq: 0, - OSeqHi: 0, - SeqHi: 0, - ReplayWindow: uint32(replayWindow), - } - - // Linux stores the bitmap to identify the already received sequence packets in blocks of uint32 elements. - // Therefore bitmap length is the minimum number of uint32 elements needed. The following is a ceiling operation. - bytesPerElem := int(unsafe.Sizeof(replayEsn.BmpLen)) // Any uint32 variable is good for this - replayEsn.BmpLen = uint32((replayWindow + (bytesPerElem * 8) - 1) / (bytesPerElem * 8)) - - return replayEsn.Serialize() -} - -// XfrmStateAdd will add an xfrm state to the system. -// Equivalent to: `ip xfrm state add $state` -func XfrmStateAdd(state *XfrmState) error { - return pkgHandle.XfrmStateAdd(state) -} - -// XfrmStateAdd will add an xfrm state to the system. -// Equivalent to: `ip xfrm state add $state` -func (h *Handle) XfrmStateAdd(state *XfrmState) error { - return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_NEWSA) -} - -// XfrmStateAllocSpi will allocate an xfrm state in the system. -// Equivalent to: `ip xfrm state allocspi` -func XfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) { - return pkgHandle.xfrmStateAllocSpi(state) -} - -// XfrmStateUpdate will update an xfrm state to the system. -// Equivalent to: `ip xfrm state update $state` -func XfrmStateUpdate(state *XfrmState) error { - return pkgHandle.XfrmStateUpdate(state) -} - -// XfrmStateUpdate will update an xfrm state to the system. -// Equivalent to: `ip xfrm state update $state` -func (h *Handle) XfrmStateUpdate(state *XfrmState) error { - return h.xfrmStateAddOrUpdate(state, nl.XFRM_MSG_UPDSA) -} - -func (h *Handle) xfrmStateAddOrUpdate(state *XfrmState, nlProto int) error { - - // A state with spi 0 can't be deleted so don't allow it to be set - if state.Spi == 0 { - return fmt.Errorf("Spi must be set when adding xfrm state.") - } - req := h.newNetlinkRequest(nlProto, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) - - msg := xfrmUsersaInfoFromXfrmState(state) - - if state.ESN { - if state.ReplayWindow == 0 { - return fmt.Errorf("ESN flag set without ReplayWindow") - } - msg.Flags |= nl.XFRM_STATE_ESN - msg.ReplayWindow = 0 - } - - limitsToLft(state.Limits, &msg.Lft) - req.AddData(msg) - - if state.Auth != nil { - out := nl.NewRtAttr(nl.XFRMA_ALG_AUTH_TRUNC, writeStateAlgoAuth(state.Auth)) - req.AddData(out) - } - if state.Crypt != nil { - out := nl.NewRtAttr(nl.XFRMA_ALG_CRYPT, writeStateAlgo(state.Crypt)) - req.AddData(out) - } - if state.Aead != nil { - out := nl.NewRtAttr(nl.XFRMA_ALG_AEAD, writeStateAlgoAead(state.Aead)) - req.AddData(out) - } - if state.Encap != nil { - encapData := make([]byte, nl.SizeofXfrmEncapTmpl) - encap := nl.DeserializeXfrmEncapTmpl(encapData) - encap.EncapType = uint16(state.Encap.Type) - encap.EncapSport = nl.Swap16(uint16(state.Encap.SrcPort)) - encap.EncapDport = nl.Swap16(uint16(state.Encap.DstPort)) - encap.EncapOa.FromIP(state.Encap.OriginalAddress) - out := nl.NewRtAttr(nl.XFRMA_ENCAP, encapData) - req.AddData(out) - } - if state.Mark != nil { - out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark)) - req.AddData(out) - } - if state.ESN { - out := nl.NewRtAttr(nl.XFRMA_REPLAY_ESN_VAL, writeReplayEsn(state.ReplayWindow)) - req.AddData(out) - } - if state.OutputMark != 0 { - out := nl.NewRtAttr(nl.XFRMA_OUTPUT_MARK, nl.Uint32Attr(uint32(state.OutputMark))) - req.AddData(out) - } - - ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid))) - req.AddData(ifId) - - _, err := req.Execute(unix.NETLINK_XFRM, 0) - return err -} - -func (h *Handle) xfrmStateAllocSpi(state *XfrmState) (*XfrmState, error) { - req := h.newNetlinkRequest(nl.XFRM_MSG_ALLOCSPI, - unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK) - - msg := &nl.XfrmUserSpiInfo{} - msg.XfrmUsersaInfo = *(xfrmUsersaInfoFromXfrmState(state)) - // 1-255 is reserved by IANA for future use - msg.Min = 0x100 - msg.Max = 0xffffffff - req.AddData(msg) - - if state.Mark != nil { - out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark)) - req.AddData(out) - } - - msgs, err := req.Execute(unix.NETLINK_XFRM, 0) - if err != nil { - return nil, err - } - - return parseXfrmState(msgs[0], FAMILY_ALL) -} - -// XfrmStateDel will delete an xfrm state from the system. Note that -// the Algos are ignored when matching the state to delete. -// Equivalent to: `ip xfrm state del $state` -func XfrmStateDel(state *XfrmState) error { - return pkgHandle.XfrmStateDel(state) -} - -// XfrmStateDel will delete an xfrm state from the system. Note that -// the Algos are ignored when matching the state to delete. -// Equivalent to: `ip xfrm state del $state` -func (h *Handle) XfrmStateDel(state *XfrmState) error { - _, err := h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_DELSA) - return err -} - -// XfrmStateList gets a list of xfrm states in the system. -// Equivalent to: `ip [-4|-6] xfrm state show`. -// The list can be filtered by ip family. -func XfrmStateList(family int) ([]XfrmState, error) { - return pkgHandle.XfrmStateList(family) -} - -// XfrmStateList gets a list of xfrm states in the system. -// Equivalent to: `ip xfrm state show`. -// The list can be filtered by ip family. -func (h *Handle) XfrmStateList(family int) ([]XfrmState, error) { - req := h.newNetlinkRequest(nl.XFRM_MSG_GETSA, unix.NLM_F_DUMP) - - msgs, err := req.Execute(unix.NETLINK_XFRM, nl.XFRM_MSG_NEWSA) - if err != nil { - return nil, err - } - - var res []XfrmState - for _, m := range msgs { - if state, err := parseXfrmState(m, family); err == nil { - res = append(res, *state) - } else if err == familyError { - continue - } else { - return nil, err - } - } - return res, nil -} - -// XfrmStateGet gets the xfrm state described by the ID, if found. -// Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`. -// Only the fields which constitue the SA ID must be filled in: -// ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ] -// mark is optional -func XfrmStateGet(state *XfrmState) (*XfrmState, error) { - return pkgHandle.XfrmStateGet(state) -} - -// XfrmStateGet gets the xfrm state described by the ID, if found. -// Equivalent to: `ip xfrm state get ID [ mark MARK [ mask MASK ] ]`. -// Only the fields which constitue the SA ID must be filled in: -// ID := [ src ADDR ] [ dst ADDR ] [ proto XFRM-PROTO ] [ spi SPI ] -// mark is optional -func (h *Handle) XfrmStateGet(state *XfrmState) (*XfrmState, error) { - return h.xfrmStateGetOrDelete(state, nl.XFRM_MSG_GETSA) -} - -func (h *Handle) xfrmStateGetOrDelete(state *XfrmState, nlProto int) (*XfrmState, error) { - req := h.newNetlinkRequest(nlProto, unix.NLM_F_ACK) - - msg := &nl.XfrmUsersaId{} - msg.Family = uint16(nl.GetIPFamily(state.Dst)) - msg.Daddr.FromIP(state.Dst) - msg.Proto = uint8(state.Proto) - msg.Spi = nl.Swap32(uint32(state.Spi)) - req.AddData(msg) - - if state.Mark != nil { - out := nl.NewRtAttr(nl.XFRMA_MARK, writeMark(state.Mark)) - req.AddData(out) - } - if state.Src != nil { - out := nl.NewRtAttr(nl.XFRMA_SRCADDR, state.Src.To16()) - req.AddData(out) - } - - ifId := nl.NewRtAttr(nl.XFRMA_IF_ID, nl.Uint32Attr(uint32(state.Ifid))) - req.AddData(ifId) - - resType := nl.XFRM_MSG_NEWSA - if nlProto == nl.XFRM_MSG_DELSA { - resType = 0 - } - - msgs, err := req.Execute(unix.NETLINK_XFRM, uint16(resType)) - if err != nil { - return nil, err - } - - if nlProto == nl.XFRM_MSG_DELSA { - return nil, nil - } - - s, err := parseXfrmState(msgs[0], FAMILY_ALL) - if err != nil { - return nil, err - } - - return s, nil -} - -var familyError = fmt.Errorf("family error") - -func xfrmStateFromXfrmUsersaInfo(msg *nl.XfrmUsersaInfo) *XfrmState { - var state XfrmState - - state.Dst = msg.Id.Daddr.ToIP() - state.Src = msg.Saddr.ToIP() - state.Proto = Proto(msg.Id.Proto) - state.Mode = Mode(msg.Mode) - state.Spi = int(nl.Swap32(msg.Id.Spi)) - state.Reqid = int(msg.Reqid) - state.ReplayWindow = int(msg.ReplayWindow) - lftToLimits(&msg.Lft, &state.Limits) - curToStats(&msg.Curlft, &msg.Stats, &state.Statistics) - - return &state -} - -func parseXfrmState(m []byte, family int) (*XfrmState, error) { - msg := nl.DeserializeXfrmUsersaInfo(m) - - // This is mainly for the state dump - if family != FAMILY_ALL && family != int(msg.Family) { - return nil, familyError - } - - state := xfrmStateFromXfrmUsersaInfo(msg) - - attrs, err := nl.ParseRouteAttr(m[nl.SizeofXfrmUsersaInfo:]) - if err != nil { - return nil, err - } - - for _, attr := range attrs { - switch attr.Attr.Type { - case nl.XFRMA_ALG_AUTH, nl.XFRMA_ALG_CRYPT: - var resAlgo *XfrmStateAlgo - if attr.Attr.Type == nl.XFRMA_ALG_AUTH { - if state.Auth == nil { - state.Auth = new(XfrmStateAlgo) - } - resAlgo = state.Auth - } else { - state.Crypt = new(XfrmStateAlgo) - resAlgo = state.Crypt - } - algo := nl.DeserializeXfrmAlgo(attr.Value[:]) - (*resAlgo).Name = nl.BytesToString(algo.AlgName[:]) - (*resAlgo).Key = algo.AlgKey - case nl.XFRMA_ALG_AUTH_TRUNC: - if state.Auth == nil { - state.Auth = new(XfrmStateAlgo) - } - algo := nl.DeserializeXfrmAlgoAuth(attr.Value[:]) - state.Auth.Name = nl.BytesToString(algo.AlgName[:]) - state.Auth.Key = algo.AlgKey - state.Auth.TruncateLen = int(algo.AlgTruncLen) - case nl.XFRMA_ALG_AEAD: - state.Aead = new(XfrmStateAlgo) - algo := nl.DeserializeXfrmAlgoAEAD(attr.Value[:]) - state.Aead.Name = nl.BytesToString(algo.AlgName[:]) - state.Aead.Key = algo.AlgKey - state.Aead.ICVLen = int(algo.AlgICVLen) - case nl.XFRMA_ENCAP: - encap := nl.DeserializeXfrmEncapTmpl(attr.Value[:]) - state.Encap = new(XfrmStateEncap) - state.Encap.Type = EncapType(encap.EncapType) - state.Encap.SrcPort = int(nl.Swap16(encap.EncapSport)) - state.Encap.DstPort = int(nl.Swap16(encap.EncapDport)) - state.Encap.OriginalAddress = encap.EncapOa.ToIP() - case nl.XFRMA_MARK: - mark := nl.DeserializeXfrmMark(attr.Value[:]) - state.Mark = new(XfrmMark) - state.Mark.Value = mark.Value - state.Mark.Mask = mark.Mask - case nl.XFRMA_OUTPUT_MARK: - state.OutputMark = int(native.Uint32(attr.Value)) - case nl.XFRMA_IF_ID: - state.Ifid = int(native.Uint32(attr.Value)) - } - } - - return state, nil -} - -// XfrmStateFlush will flush the xfrm state on the system. -// proto = 0 means any transformation protocols -// Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]` -func XfrmStateFlush(proto Proto) error { - return pkgHandle.XfrmStateFlush(proto) -} - -// XfrmStateFlush will flush the xfrm state on the system. -// proto = 0 means any transformation protocols -// Equivalent to: `ip xfrm state flush [ proto XFRM-PROTO ]` -func (h *Handle) XfrmStateFlush(proto Proto) error { - req := h.newNetlinkRequest(nl.XFRM_MSG_FLUSHSA, unix.NLM_F_ACK) - - req.AddData(&nl.XfrmUsersaFlush{Proto: uint8(proto)}) - - _, err := req.Execute(unix.NETLINK_XFRM, 0) - return err -} - -func limitsToLft(lmts XfrmStateLimits, lft *nl.XfrmLifetimeCfg) { - if lmts.ByteSoft != 0 { - lft.SoftByteLimit = lmts.ByteSoft - } else { - lft.SoftByteLimit = nl.XFRM_INF - } - if lmts.ByteHard != 0 { - lft.HardByteLimit = lmts.ByteHard - } else { - lft.HardByteLimit = nl.XFRM_INF - } - if lmts.PacketSoft != 0 { - lft.SoftPacketLimit = lmts.PacketSoft - } else { - lft.SoftPacketLimit = nl.XFRM_INF - } - if lmts.PacketHard != 0 { - lft.HardPacketLimit = lmts.PacketHard - } else { - lft.HardPacketLimit = nl.XFRM_INF - } - lft.SoftAddExpiresSeconds = lmts.TimeSoft - lft.HardAddExpiresSeconds = lmts.TimeHard - lft.SoftUseExpiresSeconds = lmts.TimeUseSoft - lft.HardUseExpiresSeconds = lmts.TimeUseHard -} - -func lftToLimits(lft *nl.XfrmLifetimeCfg, lmts *XfrmStateLimits) { - *lmts = *(*XfrmStateLimits)(unsafe.Pointer(lft)) -} - -func curToStats(cur *nl.XfrmLifetimeCur, wstats *nl.XfrmStats, stats *XfrmStateStats) { - stats.Bytes = cur.Bytes - stats.Packets = cur.Packets - stats.AddTime = cur.AddTime - stats.UseTime = cur.UseTime - stats.ReplayWindow = wstats.ReplayWindow - stats.Replay = wstats.Replay - stats.Failed = wstats.IntegrityFailed -} - -func xfrmUsersaInfoFromXfrmState(state *XfrmState) *nl.XfrmUsersaInfo { - msg := &nl.XfrmUsersaInfo{} - msg.Family = uint16(nl.GetIPFamily(state.Dst)) - msg.Id.Daddr.FromIP(state.Dst) - msg.Saddr.FromIP(state.Src) - msg.Id.Proto = uint8(state.Proto) - msg.Mode = uint8(state.Mode) - msg.Id.Spi = nl.Swap32(uint32(state.Spi)) - msg.Reqid = uint32(state.Reqid) - msg.ReplayWindow = uint8(state.ReplayWindow) - - return msg -} diff --git a/examples/vendor/github.com/vishvananda/netns/LICENSE b/examples/vendor/github.com/vishvananda/netns/LICENSE deleted file mode 100644 index 9f64db8..0000000 --- a/examples/vendor/github.com/vishvananda/netns/LICENSE +++ /dev/null @@ -1,192 +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 - - Copyright 2014 Vishvananda Ishaya. - Copyright 2014 Docker, 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. diff --git a/examples/vendor/github.com/vishvananda/netns/README.md b/examples/vendor/github.com/vishvananda/netns/README.md deleted file mode 100644 index 6b45cfb..0000000 --- a/examples/vendor/github.com/vishvananda/netns/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# netns - network namespaces in go # - -The netns package provides an ultra-simple interface for handling -network namespaces in go. Changing namespaces requires elevated -privileges, so in most cases this code needs to be run as root. - -## Local Build and Test ## - -You can use go get command: - - go get github.com/vishvananda/netns - -Testing (requires root): - - sudo -E go test github.com/vishvananda/netns - -## Example ## - -```go -package main - -import ( - "fmt" - "net" - "runtime" - "github.com/vishvananda/netns" -) - -func main() { - // Lock the OS Thread so we don't accidentally switch namespaces - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - // Save the current network namespace - origns, _ := netns.Get() - defer origns.Close() - - // Create a new network namespace - newns, _ := netns.New() - defer newns.Close() - - // Do something with the network namespace - ifaces, _ := net.Interfaces() - fmt.Printf("Interfaces: %v\n", ifaces) - - // Switch back to the original namespace - netns.Set(origns) -} - -``` diff --git a/examples/vendor/github.com/vishvananda/netns/netns.go b/examples/vendor/github.com/vishvananda/netns/netns.go deleted file mode 100644 index 116befd..0000000 --- a/examples/vendor/github.com/vishvananda/netns/netns.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package netns allows ultra-simple network namespace handling. NsHandles -// can be retrieved and set. Note that the current namespace is thread -// local so actions that set and reset namespaces should use LockOSThread -// to make sure the namespace doesn't change due to a goroutine switch. -// It is best to close NsHandles when you are done with them. This can be -// accomplished via a `defer ns.Close()` on the handle. Changing namespaces -// requires elevated privileges, so in most cases this code needs to be run -// as root. -package netns - -import ( - "fmt" - - "golang.org/x/sys/unix" -) - -// NsHandle is a handle to a network namespace. It can be cast directly -// to an int and used as a file descriptor. -type NsHandle int - -// Equal determines if two network handles refer to the same network -// namespace. This is done by comparing the device and inode that the -// file descriptors point to. -func (ns NsHandle) Equal(other NsHandle) bool { - if ns == other { - return true - } - var s1, s2 unix.Stat_t - if err := unix.Fstat(int(ns), &s1); err != nil { - return false - } - if err := unix.Fstat(int(other), &s2); err != nil { - return false - } - return (s1.Dev == s2.Dev) && (s1.Ino == s2.Ino) -} - -// String shows the file descriptor number and its dev and inode. -func (ns NsHandle) String() string { - if ns == -1 { - return "NS(None)" - } - var s unix.Stat_t - if err := unix.Fstat(int(ns), &s); err != nil { - return fmt.Sprintf("NS(%d: unknown)", ns) - } - return fmt.Sprintf("NS(%d: %d, %d)", ns, s.Dev, s.Ino) -} - -// UniqueId returns a string which uniquely identifies the namespace -// associated with the network handle. -func (ns NsHandle) UniqueId() string { - if ns == -1 { - return "NS(none)" - } - var s unix.Stat_t - if err := unix.Fstat(int(ns), &s); err != nil { - return "NS(unknown)" - } - return fmt.Sprintf("NS(%d:%d)", s.Dev, s.Ino) -} - -// IsOpen returns true if Close() has not been called. -func (ns NsHandle) IsOpen() bool { - return ns != -1 -} - -// Close closes the NsHandle and resets its file descriptor to -1. -// It is not safe to use an NsHandle after Close() is called. -func (ns *NsHandle) Close() error { - if err := unix.Close(int(*ns)); err != nil { - return err - } - (*ns) = -1 - return nil -} - -// None gets an empty (closed) NsHandle. -func None() NsHandle { - return NsHandle(-1) -} diff --git a/examples/vendor/github.com/vishvananda/netns/netns_linux.go b/examples/vendor/github.com/vishvananda/netns/netns_linux.go deleted file mode 100644 index c76acd0..0000000 --- a/examples/vendor/github.com/vishvananda/netns/netns_linux.go +++ /dev/null @@ -1,260 +0,0 @@ -// +build linux - -package netns - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strconv" - "strings" - "syscall" - - "golang.org/x/sys/unix" -) - -// Deprecated: use syscall pkg instead (go >= 1.5 needed). -const ( - CLONE_NEWUTS = 0x04000000 /* New utsname group? */ - CLONE_NEWIPC = 0x08000000 /* New ipcs */ - CLONE_NEWUSER = 0x10000000 /* New user namespace */ - CLONE_NEWPID = 0x20000000 /* New pid namespace */ - CLONE_NEWNET = 0x40000000 /* New network namespace */ - CLONE_IO = 0x80000000 /* Get io context */ - bindMountPath = "/run/netns" /* Bind mount path for named netns */ -) - -// Setns sets namespace using syscall. Note that this should be a method -// in syscall but it has not been added. -func Setns(ns NsHandle, nstype int) (err error) { - return unix.Setns(int(ns), nstype) -} - -// Set sets the current network namespace to the namespace represented -// by NsHandle. -func Set(ns NsHandle) (err error) { - return Setns(ns, CLONE_NEWNET) -} - -// New creates a new network namespace, sets it as current and returns -// a handle to it. -func New() (ns NsHandle, err error) { - if err := unix.Unshare(CLONE_NEWNET); err != nil { - return -1, err - } - return Get() -} - -// NewNamed creates a new named network namespace and returns a handle to it -func NewNamed(name string) (NsHandle, error) { - if _, err := os.Stat(bindMountPath); os.IsNotExist(err) { - err = os.MkdirAll(bindMountPath, 0755) - if err != nil { - return None(), err - } - } - - newNs, err := New() - if err != nil { - return None(), err - } - - namedPath := path.Join(bindMountPath, name) - - f, err := os.OpenFile(namedPath, os.O_CREATE|os.O_EXCL, 0444) - if err != nil { - return None(), err - } - f.Close() - - nsPath := fmt.Sprintf("/proc/%d/task/%d/ns/net", os.Getpid(), syscall.Gettid()) - err = syscall.Mount(nsPath, namedPath, "bind", syscall.MS_BIND, "") - if err != nil { - return None(), err - } - - return newNs, nil -} - -// DeleteNamed deletes a named network namespace -func DeleteNamed(name string) error { - namedPath := path.Join(bindMountPath, name) - - err := syscall.Unmount(namedPath, syscall.MNT_DETACH) - if err != nil { - return err - } - - return os.Remove(namedPath) -} - -// Get gets a handle to the current threads network namespace. -func Get() (NsHandle, error) { - return GetFromThread(os.Getpid(), unix.Gettid()) -} - -// GetFromPath gets a handle to a network namespace -// identified by the path -func GetFromPath(path string) (NsHandle, error) { - fd, err := unix.Open(path, unix.O_RDONLY|unix.O_CLOEXEC, 0) - if err != nil { - return -1, err - } - return NsHandle(fd), nil -} - -// GetFromName gets a handle to a named network namespace such as one -// created by `ip netns add`. -func GetFromName(name string) (NsHandle, error) { - return GetFromPath(fmt.Sprintf("/var/run/netns/%s", name)) -} - -// GetFromPid gets a handle to the network namespace of a given pid. -func GetFromPid(pid int) (NsHandle, error) { - return GetFromPath(fmt.Sprintf("/proc/%d/ns/net", pid)) -} - -// GetFromThread gets a handle to the network namespace of a given pid and tid. -func GetFromThread(pid, tid int) (NsHandle, error) { - return GetFromPath(fmt.Sprintf("/proc/%d/task/%d/ns/net", pid, tid)) -} - -// GetFromDocker gets a handle to the network namespace of a docker container. -// Id is prefixed matched against the running docker containers, so a short -// identifier can be used as long as it isn't ambiguous. -func GetFromDocker(id string) (NsHandle, error) { - pid, err := getPidForContainer(id) - if err != nil { - return -1, err - } - return GetFromPid(pid) -} - -// borrowed from docker/utils/utils.go -func findCgroupMountpoint(cgroupType string) (string, error) { - output, err := ioutil.ReadFile("/proc/mounts") - if err != nil { - return "", err - } - - // /proc/mounts has 6 fields per line, one mount per line, e.g. - // cgroup /sys/fs/cgroup/devices cgroup rw,relatime,devices 0 0 - for _, line := range strings.Split(string(output), "\n") { - parts := strings.Split(line, " ") - if len(parts) == 6 && parts[2] == "cgroup" { - for _, opt := range strings.Split(parts[3], ",") { - if opt == cgroupType { - return parts[1], nil - } - } - } - } - - return "", fmt.Errorf("cgroup mountpoint not found for %s", cgroupType) -} - -// Returns the relative path to the cgroup docker is running in. -// borrowed from docker/utils/utils.go -// modified to get the docker pid instead of using /proc/self -func getThisCgroup(cgroupType string) (string, error) { - dockerpid, err := ioutil.ReadFile("/var/run/docker.pid") - if err != nil { - return "", err - } - result := strings.Split(string(dockerpid), "\n") - if len(result) == 0 || len(result[0]) == 0 { - return "", fmt.Errorf("docker pid not found in /var/run/docker.pid") - } - pid, err := strconv.Atoi(result[0]) - if err != nil { - return "", err - } - output, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid)) - if err != nil { - return "", err - } - for _, line := range strings.Split(string(output), "\n") { - parts := strings.Split(line, ":") - // any type used by docker should work - if parts[1] == cgroupType { - return parts[2], nil - } - } - return "", fmt.Errorf("cgroup '%s' not found in /proc/%d/cgroup", cgroupType, pid) -} - -// Returns the first pid in a container. -// borrowed from docker/utils/utils.go -// modified to only return the first pid -// modified to glob with id -// modified to search for newer docker containers -func getPidForContainer(id string) (int, error) { - pid := 0 - - // memory is chosen randomly, any cgroup used by docker works - cgroupType := "memory" - - cgroupRoot, err := findCgroupMountpoint(cgroupType) - if err != nil { - return pid, err - } - - cgroupThis, err := getThisCgroup(cgroupType) - if err != nil { - return pid, err - } - - id += "*" - - attempts := []string{ - filepath.Join(cgroupRoot, cgroupThis, id, "tasks"), - // With more recent lxc versions use, cgroup will be in lxc/ - filepath.Join(cgroupRoot, cgroupThis, "lxc", id, "tasks"), - // With more recent docker, cgroup will be in docker/ - filepath.Join(cgroupRoot, cgroupThis, "docker", id, "tasks"), - // Even more recent docker versions under systemd use docker-.scope/ - filepath.Join(cgroupRoot, "system.slice", "docker-"+id+".scope", "tasks"), - // Even more recent docker versions under cgroup/systemd/docker// - filepath.Join(cgroupRoot, "..", "systemd", "docker", id, "tasks"), - // Kubernetes with docker and CNI is even more different - filepath.Join(cgroupRoot, "..", "systemd", "kubepods", "*", "pod*", id, "tasks"), - // Another flavor of containers location in recent kubernetes 1.11+ - filepath.Join(cgroupRoot, cgroupThis, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"), - // When runs inside of a container with recent kubernetes 1.11+ - filepath.Join(cgroupRoot, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"), - } - - var filename string - for _, attempt := range attempts { - filenames, _ := filepath.Glob(attempt) - if len(filenames) > 1 { - return pid, fmt.Errorf("Ambiguous id supplied: %v", filenames) - } else if len(filenames) == 1 { - filename = filenames[0] - break - } - } - - if filename == "" { - return pid, fmt.Errorf("Unable to find container: %v", id[:len(id)-1]) - } - - output, err := ioutil.ReadFile(filename) - if err != nil { - return pid, err - } - - result := strings.Split(string(output), "\n") - if len(result) == 0 || len(result[0]) == 0 { - return pid, fmt.Errorf("No pid found for container") - } - - pid, err = strconv.Atoi(result[0]) - if err != nil { - return pid, fmt.Errorf("Invalid pid '%s': %s", result[0], err) - } - - return pid, nil -} diff --git a/examples/vendor/github.com/vishvananda/netns/netns_unspecified.go b/examples/vendor/github.com/vishvananda/netns/netns_unspecified.go deleted file mode 100644 index d06af62..0000000 --- a/examples/vendor/github.com/vishvananda/netns/netns_unspecified.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build !linux - -package netns - -import ( - "errors" -) - -var ( - ErrNotImplemented = errors.New("not implemented") -) - -func Set(ns NsHandle) (err error) { - return ErrNotImplemented -} - -func New() (ns NsHandle, err error) { - return -1, ErrNotImplemented -} - -func Get() (NsHandle, error) { - return -1, ErrNotImplemented -} - -func GetFromPath(path string) (NsHandle, error) { - return -1, ErrNotImplemented -} - -func GetFromName(name string) (NsHandle, error) { - return -1, ErrNotImplemented -} - -func GetFromPid(pid int) (NsHandle, error) { - return -1, ErrNotImplemented -} - -func GetFromThread(pid, tid int) (NsHandle, error) { - return -1, ErrNotImplemented -} - -func GetFromDocker(id string) (NsHandle, error) { - return -1, ErrNotImplemented -} diff --git a/examples/vendor/golang.org/x/crypto/ssh/terminal/terminal.go b/examples/vendor/golang.org/x/crypto/ssh/terminal/terminal.go deleted file mode 100644 index a4d1919..0000000 --- a/examples/vendor/golang.org/x/crypto/ssh/terminal/terminal.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2011 The Go 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 terminal provides support functions for dealing with terminals, as -// commonly found on UNIX systems. -// -// Deprecated: this package moved to golang.org/x/term. -package terminal - -import ( - "io" - - "golang.org/x/term" -) - -// EscapeCodes contains escape sequences that can be written to the terminal in -// order to achieve different styles of text. -type EscapeCodes = term.EscapeCodes - -// Terminal contains the state for running a VT100 terminal that is capable of -// reading lines of input. -type Terminal = term.Terminal - -// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is -// a local terminal, that terminal must first have been put into raw mode. -// prompt is a string that is written at the start of each input line (i.e. -// "> "). -func NewTerminal(c io.ReadWriter, prompt string) *Terminal { - return term.NewTerminal(c, prompt) -} - -// ErrPasteIndicator may be returned from ReadLine as the error, in addition -// to valid line data. It indicates that bracketed paste mode is enabled and -// that the returned line consists only of pasted data. Programs may wish to -// interpret pasted data more literally than typed data. -var ErrPasteIndicator = term.ErrPasteIndicator - -// State contains the state of a terminal. -type State = term.State - -// IsTerminal returns whether the given file descriptor is a terminal. -func IsTerminal(fd int) bool { - return term.IsTerminal(fd) -} - -// ReadPassword reads a line of input from a terminal without local echo. This -// is commonly used for inputting passwords and other sensitive data. The slice -// returned does not include the \n. -func ReadPassword(fd int) ([]byte, error) { - return term.ReadPassword(fd) -} - -// MakeRaw puts the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd int) (*State, error) { - return term.MakeRaw(fd) -} - -// Restore restores the terminal connected to the given file descriptor to a -// previous state. -func Restore(fd int, oldState *State) error { - return term.Restore(fd, oldState) -} - -// GetState returns the current state of a terminal which may be useful to -// restore the terminal after a signal. -func GetState(fd int) (*State, error) { - return term.GetState(fd) -} - -// GetSize returns the dimensions of the given terminal. -func GetSize(fd int) (width, height int, err error) { - return term.GetSize(fd) -} diff --git a/examples/vendor/golang.org/x/net/internal/socks/client.go b/examples/vendor/golang.org/x/net/internal/socks/client.go deleted file mode 100644 index 3d6f516..0000000 --- a/examples/vendor/golang.org/x/net/internal/socks/client.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2018 The Go 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 socks - -import ( - "context" - "errors" - "io" - "net" - "strconv" - "time" -) - -var ( - noDeadline = time.Time{} - aLongTimeAgo = time.Unix(1, 0) -) - -func (d *Dialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error) { - host, port, err := splitHostPort(address) - if err != nil { - return nil, err - } - if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() { - c.SetDeadline(deadline) - defer c.SetDeadline(noDeadline) - } - if ctx != context.Background() { - errCh := make(chan error, 1) - done := make(chan struct{}) - defer func() { - close(done) - if ctxErr == nil { - ctxErr = <-errCh - } - }() - go func() { - select { - case <-ctx.Done(): - c.SetDeadline(aLongTimeAgo) - errCh <- ctx.Err() - case <-done: - errCh <- nil - } - }() - } - - b := make([]byte, 0, 6+len(host)) // the size here is just an estimate - b = append(b, Version5) - if len(d.AuthMethods) == 0 || d.Authenticate == nil { - b = append(b, 1, byte(AuthMethodNotRequired)) - } else { - ams := d.AuthMethods - if len(ams) > 255 { - return nil, errors.New("too many authentication methods") - } - b = append(b, byte(len(ams))) - for _, am := range ams { - b = append(b, byte(am)) - } - } - if _, ctxErr = c.Write(b); ctxErr != nil { - return - } - - if _, ctxErr = io.ReadFull(c, b[:2]); ctxErr != nil { - return - } - if b[0] != Version5 { - return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0]))) - } - am := AuthMethod(b[1]) - if am == AuthMethodNoAcceptableMethods { - return nil, errors.New("no acceptable authentication methods") - } - if d.Authenticate != nil { - if ctxErr = d.Authenticate(ctx, c, am); ctxErr != nil { - return - } - } - - b = b[:0] - b = append(b, Version5, byte(d.cmd), 0) - if ip := net.ParseIP(host); ip != nil { - if ip4 := ip.To4(); ip4 != nil { - b = append(b, AddrTypeIPv4) - b = append(b, ip4...) - } else if ip6 := ip.To16(); ip6 != nil { - b = append(b, AddrTypeIPv6) - b = append(b, ip6...) - } else { - return nil, errors.New("unknown address type") - } - } else { - if len(host) > 255 { - return nil, errors.New("FQDN too long") - } - b = append(b, AddrTypeFQDN) - b = append(b, byte(len(host))) - b = append(b, host...) - } - b = append(b, byte(port>>8), byte(port)) - if _, ctxErr = c.Write(b); ctxErr != nil { - return - } - - if _, ctxErr = io.ReadFull(c, b[:4]); ctxErr != nil { - return - } - if b[0] != Version5 { - return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0]))) - } - if cmdErr := Reply(b[1]); cmdErr != StatusSucceeded { - return nil, errors.New("unknown error " + cmdErr.String()) - } - if b[2] != 0 { - return nil, errors.New("non-zero reserved field") - } - l := 2 - var a Addr - switch b[3] { - case AddrTypeIPv4: - l += net.IPv4len - a.IP = make(net.IP, net.IPv4len) - case AddrTypeIPv6: - l += net.IPv6len - a.IP = make(net.IP, net.IPv6len) - case AddrTypeFQDN: - if _, err := io.ReadFull(c, b[:1]); err != nil { - return nil, err - } - l += int(b[0]) - default: - return nil, errors.New("unknown address type " + strconv.Itoa(int(b[3]))) - } - if cap(b) < l { - b = make([]byte, l) - } else { - b = b[:l] - } - if _, ctxErr = io.ReadFull(c, b); ctxErr != nil { - return - } - if a.IP != nil { - copy(a.IP, b) - } else { - a.Name = string(b[:len(b)-2]) - } - a.Port = int(b[len(b)-2])<<8 | int(b[len(b)-1]) - return &a, nil -} - -func splitHostPort(address string) (string, int, error) { - host, port, err := net.SplitHostPort(address) - if err != nil { - return "", 0, err - } - portnum, err := strconv.Atoi(port) - if err != nil { - return "", 0, err - } - if 1 > portnum || portnum > 0xffff { - return "", 0, errors.New("port number out of range " + port) - } - return host, portnum, nil -} diff --git a/examples/vendor/golang.org/x/net/internal/socks/socks.go b/examples/vendor/golang.org/x/net/internal/socks/socks.go deleted file mode 100644 index 97db234..0000000 --- a/examples/vendor/golang.org/x/net/internal/socks/socks.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2018 The Go 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 socks provides a SOCKS version 5 client implementation. -// -// SOCKS protocol version 5 is defined in RFC 1928. -// Username/Password authentication for SOCKS version 5 is defined in -// RFC 1929. -package socks - -import ( - "context" - "errors" - "io" - "net" - "strconv" -) - -// A Command represents a SOCKS command. -type Command int - -func (cmd Command) String() string { - switch cmd { - case CmdConnect: - return "socks connect" - case cmdBind: - return "socks bind" - default: - return "socks " + strconv.Itoa(int(cmd)) - } -} - -// An AuthMethod represents a SOCKS authentication method. -type AuthMethod int - -// A Reply represents a SOCKS command reply code. -type Reply int - -func (code Reply) String() string { - switch code { - case StatusSucceeded: - return "succeeded" - case 0x01: - return "general SOCKS server failure" - case 0x02: - return "connection not allowed by ruleset" - case 0x03: - return "network unreachable" - case 0x04: - return "host unreachable" - case 0x05: - return "connection refused" - case 0x06: - return "TTL expired" - case 0x07: - return "command not supported" - case 0x08: - return "address type not supported" - default: - return "unknown code: " + strconv.Itoa(int(code)) - } -} - -// Wire protocol constants. -const ( - Version5 = 0x05 - - AddrTypeIPv4 = 0x01 - AddrTypeFQDN = 0x03 - AddrTypeIPv6 = 0x04 - - CmdConnect Command = 0x01 // establishes an active-open forward proxy connection - cmdBind Command = 0x02 // establishes a passive-open forward proxy connection - - AuthMethodNotRequired AuthMethod = 0x00 // no authentication required - AuthMethodUsernamePassword AuthMethod = 0x02 // use username/password - AuthMethodNoAcceptableMethods AuthMethod = 0xff // no acceptable authentication methods - - StatusSucceeded Reply = 0x00 -) - -// An Addr represents a SOCKS-specific address. -// Either Name or IP is used exclusively. -type Addr struct { - Name string // fully-qualified domain name - IP net.IP - Port int -} - -func (a *Addr) Network() string { return "socks" } - -func (a *Addr) String() string { - if a == nil { - return "" - } - port := strconv.Itoa(a.Port) - if a.IP == nil { - return net.JoinHostPort(a.Name, port) - } - return net.JoinHostPort(a.IP.String(), port) -} - -// A Conn represents a forward proxy connection. -type Conn struct { - net.Conn - - boundAddr net.Addr -} - -// BoundAddr returns the address assigned by the proxy server for -// connecting to the command target address from the proxy server. -func (c *Conn) BoundAddr() net.Addr { - if c == nil { - return nil - } - return c.boundAddr -} - -// A Dialer holds SOCKS-specific options. -type Dialer struct { - cmd Command // either CmdConnect or cmdBind - proxyNetwork string // network between a proxy server and a client - proxyAddress string // proxy server address - - // ProxyDial specifies the optional dial function for - // establishing the transport connection. - ProxyDial func(context.Context, string, string) (net.Conn, error) - - // AuthMethods specifies the list of request authentication - // methods. - // If empty, SOCKS client requests only AuthMethodNotRequired. - AuthMethods []AuthMethod - - // Authenticate specifies the optional authentication - // function. It must be non-nil when AuthMethods is not empty. - // It must return an error when the authentication is failed. - Authenticate func(context.Context, io.ReadWriter, AuthMethod) error -} - -// DialContext connects to the provided address on the provided -// network. -// -// The returned error value may be a net.OpError. When the Op field of -// net.OpError contains "socks", the Source field contains a proxy -// server address and the Addr field contains a command target -// address. -// -// See func Dial of the net package of standard library for a -// description of the network and address parameters. -func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if ctx == nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")} - } - var err error - var c net.Conn - if d.ProxyDial != nil { - c, err = d.ProxyDial(ctx, d.proxyNetwork, d.proxyAddress) - } else { - var dd net.Dialer - c, err = dd.DialContext(ctx, d.proxyNetwork, d.proxyAddress) - } - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - a, err := d.connect(ctx, c, address) - if err != nil { - c.Close() - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - return &Conn{Conn: c, boundAddr: a}, nil -} - -// DialWithConn initiates a connection from SOCKS server to the target -// network and address using the connection c that is already -// connected to the SOCKS server. -// -// It returns the connection's local address assigned by the SOCKS -// server. -func (d *Dialer) DialWithConn(ctx context.Context, c net.Conn, network, address string) (net.Addr, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if ctx == nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: errors.New("nil context")} - } - a, err := d.connect(ctx, c, address) - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - return a, nil -} - -// Dial connects to the provided address on the provided network. -// -// Unlike DialContext, it returns a raw transport connection instead -// of a forward proxy connection. -// -// Deprecated: Use DialContext or DialWithConn instead. -func (d *Dialer) Dial(network, address string) (net.Conn, error) { - if err := d.validateTarget(network, address); err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - var err error - var c net.Conn - if d.ProxyDial != nil { - c, err = d.ProxyDial(context.Background(), d.proxyNetwork, d.proxyAddress) - } else { - c, err = net.Dial(d.proxyNetwork, d.proxyAddress) - } - if err != nil { - proxy, dst, _ := d.pathAddrs(address) - return nil, &net.OpError{Op: d.cmd.String(), Net: network, Source: proxy, Addr: dst, Err: err} - } - if _, err := d.DialWithConn(context.Background(), c, network, address); err != nil { - c.Close() - return nil, err - } - return c, nil -} - -func (d *Dialer) validateTarget(network, address string) error { - switch network { - case "tcp", "tcp6", "tcp4": - default: - return errors.New("network not implemented") - } - switch d.cmd { - case CmdConnect, cmdBind: - default: - return errors.New("command not implemented") - } - return nil -} - -func (d *Dialer) pathAddrs(address string) (proxy, dst net.Addr, err error) { - for i, s := range []string{d.proxyAddress, address} { - host, port, err := splitHostPort(s) - if err != nil { - return nil, nil, err - } - a := &Addr{Port: port} - a.IP = net.ParseIP(host) - if a.IP == nil { - a.Name = host - } - if i == 0 { - proxy = a - } else { - dst = a - } - } - return -} - -// NewDialer returns a new Dialer that dials through the provided -// proxy server's network and address. -func NewDialer(network, address string) *Dialer { - return &Dialer{proxyNetwork: network, proxyAddress: address, cmd: CmdConnect} -} - -const ( - authUsernamePasswordVersion = 0x01 - authStatusSucceeded = 0x00 -) - -// UsernamePassword are the credentials for the username/password -// authentication method. -type UsernamePassword struct { - Username string - Password string -} - -// Authenticate authenticates a pair of username and password with the -// proxy server. -func (up *UsernamePassword) Authenticate(ctx context.Context, rw io.ReadWriter, auth AuthMethod) error { - switch auth { - case AuthMethodNotRequired: - return nil - case AuthMethodUsernamePassword: - if len(up.Username) == 0 || len(up.Username) > 255 || len(up.Password) == 0 || len(up.Password) > 255 { - return errors.New("invalid username/password") - } - b := []byte{authUsernamePasswordVersion} - b = append(b, byte(len(up.Username))) - b = append(b, up.Username...) - b = append(b, byte(len(up.Password))) - b = append(b, up.Password...) - // TODO(mikio): handle IO deadlines and cancelation if - // necessary - if _, err := rw.Write(b); err != nil { - return err - } - if _, err := io.ReadFull(rw, b[:2]); err != nil { - return err - } - if b[0] != authUsernamePasswordVersion { - return errors.New("invalid username/password version") - } - if b[1] != authStatusSucceeded { - return errors.New("username/password authentication failed") - } - return nil - } - return errors.New("unsupported authentication method " + strconv.Itoa(int(auth))) -} diff --git a/examples/vendor/golang.org/x/net/proxy/dial.go b/examples/vendor/golang.org/x/net/proxy/dial.go deleted file mode 100644 index 811c2e4..0000000 --- a/examples/vendor/golang.org/x/net/proxy/dial.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2019 The Go 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 proxy - -import ( - "context" - "net" -) - -// A ContextDialer dials using a context. -type ContextDialer interface { - DialContext(ctx context.Context, network, address string) (net.Conn, error) -} - -// Dial works like DialContext on net.Dialer but using a dialer returned by FromEnvironment. -// -// The passed ctx is only used for returning the Conn, not the lifetime of the Conn. -// -// Custom dialers (registered via RegisterDialerType) that do not implement ContextDialer -// can leak a goroutine for as long as it takes the underlying Dialer implementation to timeout. -// -// A Conn returned from a successful Dial after the context has been cancelled will be immediately closed. -func Dial(ctx context.Context, network, address string) (net.Conn, error) { - d := FromEnvironment() - if xd, ok := d.(ContextDialer); ok { - return xd.DialContext(ctx, network, address) - } - return dialContext(ctx, d, network, address) -} - -// WARNING: this can leak a goroutine for as long as the underlying Dialer implementation takes to timeout -// A Conn returned from a successful Dial after the context has been cancelled will be immediately closed. -func dialContext(ctx context.Context, d Dialer, network, address string) (net.Conn, error) { - var ( - conn net.Conn - done = make(chan struct{}, 1) - err error - ) - go func() { - conn, err = d.Dial(network, address) - close(done) - if conn != nil && ctx.Err() != nil { - conn.Close() - } - }() - select { - case <-ctx.Done(): - err = ctx.Err() - case <-done: - } - return conn, err -} diff --git a/examples/vendor/golang.org/x/net/proxy/direct.go b/examples/vendor/golang.org/x/net/proxy/direct.go deleted file mode 100644 index 3d66bde..0000000 --- a/examples/vendor/golang.org/x/net/proxy/direct.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2011 The Go 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 proxy - -import ( - "context" - "net" -) - -type direct struct{} - -// Direct implements Dialer by making network connections directly using net.Dial or net.DialContext. -var Direct = direct{} - -var ( - _ Dialer = Direct - _ ContextDialer = Direct -) - -// Dial directly invokes net.Dial with the supplied parameters. -func (direct) Dial(network, addr string) (net.Conn, error) { - return net.Dial(network, addr) -} - -// DialContext instantiates a net.Dialer and invokes its DialContext receiver with the supplied parameters. -func (direct) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { - var d net.Dialer - return d.DialContext(ctx, network, addr) -} diff --git a/examples/vendor/golang.org/x/net/proxy/per_host.go b/examples/vendor/golang.org/x/net/proxy/per_host.go deleted file mode 100644 index 573fe79..0000000 --- a/examples/vendor/golang.org/x/net/proxy/per_host.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2011 The Go 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 proxy - -import ( - "context" - "net" - "strings" -) - -// A PerHost directs connections to a default Dialer unless the host name -// requested matches one of a number of exceptions. -type PerHost struct { - def, bypass 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 NewPerHost(defaultDialer, bypass Dialer) *PerHost { - return &PerHost{ - def: defaultDialer, - bypass: bypass, - } -} - -// Dial connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *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) -} - -// DialContext connects to the address addr on the given network through either -// defaultDialer or bypass. -func (p *PerHost) DialContext(ctx context.Context, network, addr string) (c net.Conn, err error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - d := p.dialerForRequest(host) - if x, ok := d.(ContextDialer); ok { - return x.DialContext(ctx, network, addr) - } - return dialContext(ctx, d, network, addr) -} - -func (p *PerHost) dialerForRequest(host string) 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 *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 *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 *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 *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 *PerHost) AddHost(host string) { - if strings.HasSuffix(host, ".") { - host = host[:len(host)-1] - } - p.bypassHosts = append(p.bypassHosts, host) -} diff --git a/examples/vendor/golang.org/x/net/proxy/proxy.go b/examples/vendor/golang.org/x/net/proxy/proxy.go deleted file mode 100644 index 9ff4b9a..0000000 --- a/examples/vendor/golang.org/x/net/proxy/proxy.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2011 The Go 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 proxy provides support for a variety of protocols to proxy network -// data. -package proxy // import "golang.org/x/net/proxy" - -import ( - "errors" - "net" - "net/url" - "os" - "sync" -) - -// A Dialer is a means to establish a connection. -// Custom dialers should also implement ContextDialer. -type 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 Auth struct { - User, Password string -} - -// FromEnvironment returns the dialer specified by the proxy-related -// variables in the environment and makes underlying connections -// directly. -func FromEnvironment() Dialer { - return FromEnvironmentUsing(Direct) -} - -// FromEnvironmentUsing returns the dialer specify by the proxy-related -// variables in the environment and makes underlying connections -// using the provided forwarding Dialer (for instance, a *net.Dialer -// with desired configuration). -func FromEnvironmentUsing(forward Dialer) Dialer { - allProxy := allProxyEnv.Get() - if len(allProxy) == 0 { - return forward - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return forward - } - proxy, err := FromURL(proxyURL, forward) - if err != nil { - return forward - } - - noProxy := noProxyEnv.Get() - if len(noProxy) == 0 { - return proxy - } - - perHost := NewPerHost(proxy, forward) - 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 proxySchemes map[string]func(*url.URL, Dialer) (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 RegisterDialerType(scheme string, f func(*url.URL, Dialer) (Dialer, error)) { - if proxySchemes == nil { - proxySchemes = make(map[string]func(*url.URL, Dialer) (Dialer, error)) - } - proxySchemes[scheme] = f -} - -// FromURL returns a Dialer given a URL specification and an underlying -// Dialer for it to make network requests. -func FromURL(u *url.URL, forward Dialer) (Dialer, error) { - var auth *Auth - if u.User != nil { - auth = new(Auth) - auth.User = u.User.Username() - if p, ok := u.User.Password(); ok { - auth.Password = p - } - } - - switch u.Scheme { - case "socks5", "socks5h": - addr := u.Hostname() - port := u.Port() - if port == "" { - port = "1080" - } - return SOCKS5("tcp", net.JoinHostPort(addr, port), auth, forward) - } - - // If the scheme doesn't match any of the built-in schemes, see if it - // was registered by another package. - if proxySchemes != nil { - if f, ok := proxySchemes[u.Scheme]; ok { - return f(u, forward) - } - } - - return nil, errors.New("proxy: unknown scheme: " + u.Scheme) -} - -var ( - allProxyEnv = &envOnce{ - names: []string{"ALL_PROXY", "all_proxy"}, - } - noProxyEnv = &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 envOnce struct { - names []string - once sync.Once - val string -} - -func (e *envOnce) Get() string { - e.once.Do(e.init) - return e.val -} - -func (e *envOnce) init() { - for _, n := range e.names { - e.val = os.Getenv(n) - if e.val != "" { - return - } - } -} - -// reset is used by tests -func (e *envOnce) reset() { - e.once = sync.Once{} - e.val = "" -} diff --git a/examples/vendor/golang.org/x/net/proxy/socks5.go b/examples/vendor/golang.org/x/net/proxy/socks5.go deleted file mode 100644 index c91651f..0000000 --- a/examples/vendor/golang.org/x/net/proxy/socks5.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2011 The Go 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 proxy - -import ( - "context" - "net" - - "golang.org/x/net/internal/socks" -) - -// 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 SOCKS5(network, address string, auth *Auth, forward Dialer) (Dialer, error) { - d := socks.NewDialer(network, address) - if forward != nil { - if f, ok := forward.(ContextDialer); ok { - d.ProxyDial = func(ctx context.Context, network string, address string) (net.Conn, error) { - return f.DialContext(ctx, network, address) - } - } else { - d.ProxyDial = func(ctx context.Context, network string, address string) (net.Conn, error) { - return dialContext(ctx, forward, network, address) - } - } - } - if auth != nil { - up := socks.UsernamePassword{ - Username: auth.User, - Password: auth.Password, - } - d.AuthMethods = []socks.AuthMethod{ - socks.AuthMethodNotRequired, - socks.AuthMethodUsernamePassword, - } - d.Authenticate = up.Authenticate - } - return d, nil -} diff --git a/examples/vendor/golang.org/x/sys/cpu/cpu_x86.s b/examples/vendor/golang.org/x/sys/cpu/cpu_x86.s deleted file mode 100644 index b748ba5..0000000 --- a/examples/vendor/golang.org/x/sys/cpu/cpu_x86.s +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build (386 || amd64 || amd64p32) && gc -// +build 386 amd64 amd64p32 -// +build gc - -#include "textflag.h" - -// func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) -TEXT ·cpuid(SB), NOSPLIT, $0-24 - MOVL eaxArg+0(FP), AX - MOVL ecxArg+4(FP), CX - CPUID - MOVL AX, eax+8(FP) - MOVL BX, ebx+12(FP) - MOVL CX, ecx+16(FP) - MOVL DX, edx+20(FP) - RET - -// func xgetbv() (eax, edx uint32) -TEXT ·xgetbv(SB),NOSPLIT,$0-8 - MOVL $0, CX - XGETBV - MOVL AX, eax+0(FP) - MOVL DX, edx+4(FP) - RET - -// func darwinSupportsAVX512() bool -TEXT ·darwinSupportsAVX512(SB), NOSPLIT, $0-1 - MOVB $0, ret+0(FP) // default to false -#ifdef GOOS_darwin // return if not darwin -#ifdef GOARCH_amd64 // return if not amd64 -// These values from: -// https://github.com/apple/darwin-xnu/blob/xnu-4570.1.46/osfmk/i386/cpu_capabilities.h -#define commpage64_base_address 0x00007fffffe00000 -#define commpage64_cpu_capabilities64 (commpage64_base_address+0x010) -#define commpage64_version (commpage64_base_address+0x01E) -#define hasAVX512F 0x0000004000000000 - MOVQ $commpage64_version, BX - CMPW (BX), $13 // cpu_capabilities64 undefined in versions < 13 - JL no_avx512 - MOVQ $commpage64_cpu_capabilities64, BX - MOVQ $hasAVX512F, CX - TESTQ (BX), CX - JZ no_avx512 - MOVB $1, ret+0(FP) -no_avx512: -#endif -#endif - RET diff --git a/examples/vendor/golang.org/x/sys/windows/setupapierrors_windows.go b/examples/vendor/golang.org/x/sys/windows/setupapierrors_windows.go deleted file mode 100644 index 1681810..0000000 --- a/examples/vendor/golang.org/x/sys/windows/setupapierrors_windows.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2020 The Go 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 windows - -import "syscall" - -const ( - ERROR_EXPECTED_SECTION_NAME syscall.Errno = 0x20000000 | 0xC0000000 | 0 - ERROR_BAD_SECTION_NAME_LINE syscall.Errno = 0x20000000 | 0xC0000000 | 1 - ERROR_SECTION_NAME_TOO_LONG syscall.Errno = 0x20000000 | 0xC0000000 | 2 - ERROR_GENERAL_SYNTAX syscall.Errno = 0x20000000 | 0xC0000000 | 3 - ERROR_WRONG_INF_STYLE syscall.Errno = 0x20000000 | 0xC0000000 | 0x100 - ERROR_SECTION_NOT_FOUND syscall.Errno = 0x20000000 | 0xC0000000 | 0x101 - ERROR_LINE_NOT_FOUND syscall.Errno = 0x20000000 | 0xC0000000 | 0x102 - ERROR_NO_BACKUP syscall.Errno = 0x20000000 | 0xC0000000 | 0x103 - ERROR_NO_ASSOCIATED_CLASS syscall.Errno = 0x20000000 | 0xC0000000 | 0x200 - ERROR_CLASS_MISMATCH syscall.Errno = 0x20000000 | 0xC0000000 | 0x201 - ERROR_DUPLICATE_FOUND syscall.Errno = 0x20000000 | 0xC0000000 | 0x202 - ERROR_NO_DRIVER_SELECTED syscall.Errno = 0x20000000 | 0xC0000000 | 0x203 - ERROR_KEY_DOES_NOT_EXIST syscall.Errno = 0x20000000 | 0xC0000000 | 0x204 - ERROR_INVALID_DEVINST_NAME syscall.Errno = 0x20000000 | 0xC0000000 | 0x205 - ERROR_INVALID_CLASS syscall.Errno = 0x20000000 | 0xC0000000 | 0x206 - ERROR_DEVINST_ALREADY_EXISTS syscall.Errno = 0x20000000 | 0xC0000000 | 0x207 - ERROR_DEVINFO_NOT_REGISTERED syscall.Errno = 0x20000000 | 0xC0000000 | 0x208 - ERROR_INVALID_REG_PROPERTY syscall.Errno = 0x20000000 | 0xC0000000 | 0x209 - ERROR_NO_INF syscall.Errno = 0x20000000 | 0xC0000000 | 0x20A - ERROR_NO_SUCH_DEVINST syscall.Errno = 0x20000000 | 0xC0000000 | 0x20B - ERROR_CANT_LOAD_CLASS_ICON syscall.Errno = 0x20000000 | 0xC0000000 | 0x20C - ERROR_INVALID_CLASS_INSTALLER syscall.Errno = 0x20000000 | 0xC0000000 | 0x20D - ERROR_DI_DO_DEFAULT syscall.Errno = 0x20000000 | 0xC0000000 | 0x20E - ERROR_DI_NOFILECOPY syscall.Errno = 0x20000000 | 0xC0000000 | 0x20F - ERROR_INVALID_HWPROFILE syscall.Errno = 0x20000000 | 0xC0000000 | 0x210 - ERROR_NO_DEVICE_SELECTED syscall.Errno = 0x20000000 | 0xC0000000 | 0x211 - ERROR_DEVINFO_LIST_LOCKED syscall.Errno = 0x20000000 | 0xC0000000 | 0x212 - ERROR_DEVINFO_DATA_LOCKED syscall.Errno = 0x20000000 | 0xC0000000 | 0x213 - ERROR_DI_BAD_PATH syscall.Errno = 0x20000000 | 0xC0000000 | 0x214 - ERROR_NO_CLASSINSTALL_PARAMS syscall.Errno = 0x20000000 | 0xC0000000 | 0x215 - ERROR_FILEQUEUE_LOCKED syscall.Errno = 0x20000000 | 0xC0000000 | 0x216 - ERROR_BAD_SERVICE_INSTALLSECT syscall.Errno = 0x20000000 | 0xC0000000 | 0x217 - ERROR_NO_CLASS_DRIVER_LIST syscall.Errno = 0x20000000 | 0xC0000000 | 0x218 - ERROR_NO_ASSOCIATED_SERVICE syscall.Errno = 0x20000000 | 0xC0000000 | 0x219 - ERROR_NO_DEFAULT_DEVICE_INTERFACE syscall.Errno = 0x20000000 | 0xC0000000 | 0x21A - ERROR_DEVICE_INTERFACE_ACTIVE syscall.Errno = 0x20000000 | 0xC0000000 | 0x21B - ERROR_DEVICE_INTERFACE_REMOVED syscall.Errno = 0x20000000 | 0xC0000000 | 0x21C - ERROR_BAD_INTERFACE_INSTALLSECT syscall.Errno = 0x20000000 | 0xC0000000 | 0x21D - ERROR_NO_SUCH_INTERFACE_CLASS syscall.Errno = 0x20000000 | 0xC0000000 | 0x21E - ERROR_INVALID_REFERENCE_STRING syscall.Errno = 0x20000000 | 0xC0000000 | 0x21F - ERROR_INVALID_MACHINENAME syscall.Errno = 0x20000000 | 0xC0000000 | 0x220 - ERROR_REMOTE_COMM_FAILURE syscall.Errno = 0x20000000 | 0xC0000000 | 0x221 - ERROR_MACHINE_UNAVAILABLE syscall.Errno = 0x20000000 | 0xC0000000 | 0x222 - ERROR_NO_CONFIGMGR_SERVICES syscall.Errno = 0x20000000 | 0xC0000000 | 0x223 - ERROR_INVALID_PROPPAGE_PROVIDER syscall.Errno = 0x20000000 | 0xC0000000 | 0x224 - ERROR_NO_SUCH_DEVICE_INTERFACE syscall.Errno = 0x20000000 | 0xC0000000 | 0x225 - ERROR_DI_POSTPROCESSING_REQUIRED syscall.Errno = 0x20000000 | 0xC0000000 | 0x226 - ERROR_INVALID_COINSTALLER syscall.Errno = 0x20000000 | 0xC0000000 | 0x227 - ERROR_NO_COMPAT_DRIVERS syscall.Errno = 0x20000000 | 0xC0000000 | 0x228 - ERROR_NO_DEVICE_ICON syscall.Errno = 0x20000000 | 0xC0000000 | 0x229 - ERROR_INVALID_INF_LOGCONFIG syscall.Errno = 0x20000000 | 0xC0000000 | 0x22A - ERROR_DI_DONT_INSTALL syscall.Errno = 0x20000000 | 0xC0000000 | 0x22B - ERROR_INVALID_FILTER_DRIVER syscall.Errno = 0x20000000 | 0xC0000000 | 0x22C - ERROR_NON_WINDOWS_NT_DRIVER syscall.Errno = 0x20000000 | 0xC0000000 | 0x22D - ERROR_NON_WINDOWS_DRIVER syscall.Errno = 0x20000000 | 0xC0000000 | 0x22E - ERROR_NO_CATALOG_FOR_OEM_INF syscall.Errno = 0x20000000 | 0xC0000000 | 0x22F - ERROR_DEVINSTALL_QUEUE_NONNATIVE syscall.Errno = 0x20000000 | 0xC0000000 | 0x230 - ERROR_NOT_DISABLEABLE syscall.Errno = 0x20000000 | 0xC0000000 | 0x231 - ERROR_CANT_REMOVE_DEVINST syscall.Errno = 0x20000000 | 0xC0000000 | 0x232 - ERROR_INVALID_TARGET syscall.Errno = 0x20000000 | 0xC0000000 | 0x233 - ERROR_DRIVER_NONNATIVE syscall.Errno = 0x20000000 | 0xC0000000 | 0x234 - ERROR_IN_WOW64 syscall.Errno = 0x20000000 | 0xC0000000 | 0x235 - ERROR_SET_SYSTEM_RESTORE_POINT syscall.Errno = 0x20000000 | 0xC0000000 | 0x236 - ERROR_SCE_DISABLED syscall.Errno = 0x20000000 | 0xC0000000 | 0x238 - ERROR_UNKNOWN_EXCEPTION syscall.Errno = 0x20000000 | 0xC0000000 | 0x239 - ERROR_PNP_REGISTRY_ERROR syscall.Errno = 0x20000000 | 0xC0000000 | 0x23A - ERROR_REMOTE_REQUEST_UNSUPPORTED syscall.Errno = 0x20000000 | 0xC0000000 | 0x23B - ERROR_NOT_AN_INSTALLED_OEM_INF syscall.Errno = 0x20000000 | 0xC0000000 | 0x23C - ERROR_INF_IN_USE_BY_DEVICES syscall.Errno = 0x20000000 | 0xC0000000 | 0x23D - ERROR_DI_FUNCTION_OBSOLETE syscall.Errno = 0x20000000 | 0xC0000000 | 0x23E - ERROR_NO_AUTHENTICODE_CATALOG syscall.Errno = 0x20000000 | 0xC0000000 | 0x23F - ERROR_AUTHENTICODE_DISALLOWED syscall.Errno = 0x20000000 | 0xC0000000 | 0x240 - ERROR_AUTHENTICODE_TRUSTED_PUBLISHER syscall.Errno = 0x20000000 | 0xC0000000 | 0x241 - ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED syscall.Errno = 0x20000000 | 0xC0000000 | 0x242 - ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED syscall.Errno = 0x20000000 | 0xC0000000 | 0x243 - ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH syscall.Errno = 0x20000000 | 0xC0000000 | 0x244 - ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE syscall.Errno = 0x20000000 | 0xC0000000 | 0x245 - ERROR_DEVICE_INSTALLER_NOT_READY syscall.Errno = 0x20000000 | 0xC0000000 | 0x246 - ERROR_DRIVER_STORE_ADD_FAILED syscall.Errno = 0x20000000 | 0xC0000000 | 0x247 - ERROR_DEVICE_INSTALL_BLOCKED syscall.Errno = 0x20000000 | 0xC0000000 | 0x248 - ERROR_DRIVER_INSTALL_BLOCKED syscall.Errno = 0x20000000 | 0xC0000000 | 0x249 - ERROR_WRONG_INF_TYPE syscall.Errno = 0x20000000 | 0xC0000000 | 0x24A - ERROR_FILE_HASH_NOT_IN_CATALOG syscall.Errno = 0x20000000 | 0xC0000000 | 0x24B - ERROR_DRIVER_STORE_DELETE_FAILED syscall.Errno = 0x20000000 | 0xC0000000 | 0x24C - ERROR_UNRECOVERABLE_STACK_OVERFLOW syscall.Errno = 0x20000000 | 0xC0000000 | 0x300 - EXCEPTION_SPAPI_UNRECOVERABLE_STACK_OVERFLOW syscall.Errno = ERROR_UNRECOVERABLE_STACK_OVERFLOW - ERROR_NO_DEFAULT_INTERFACE_DEVICE syscall.Errno = ERROR_NO_DEFAULT_DEVICE_INTERFACE - ERROR_INTERFACE_DEVICE_ACTIVE syscall.Errno = ERROR_DEVICE_INTERFACE_ACTIVE - ERROR_INTERFACE_DEVICE_REMOVED syscall.Errno = ERROR_DEVICE_INTERFACE_REMOVED - ERROR_NO_SUCH_INTERFACE_DEVICE syscall.Errno = ERROR_NO_SUCH_DEVICE_INTERFACE -) diff --git a/examples/vendor/google.golang.org/grpc/attributes/attributes.go b/examples/vendor/google.golang.org/grpc/attributes/attributes.go deleted file mode 100644 index 3220d87..0000000 --- a/examples/vendor/google.golang.org/grpc/attributes/attributes.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * - * Copyright 2019 gRPC 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 attributes defines a generic key/value store used in various gRPC -// components. -// -// Experimental -// -// Notice: This package is EXPERIMENTAL and may be changed or removed in a -// later release. -package attributes - -import "fmt" - -// Attributes is an immutable struct for storing and retrieving generic -// key/value pairs. Keys must be hashable, and users should define their own -// types for keys. -type Attributes struct { - m map[interface{}]interface{} -} - -// New returns a new Attributes containing all key/value pairs in kvs. If the -// same key appears multiple times, the last value overwrites all previous -// values for that key. Panics if len(kvs) is not even. -func New(kvs ...interface{}) *Attributes { - if len(kvs)%2 != 0 { - panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) - } - a := &Attributes{m: make(map[interface{}]interface{}, len(kvs)/2)} - for i := 0; i < len(kvs)/2; i++ { - a.m[kvs[i*2]] = kvs[i*2+1] - } - return a -} - -// WithValues returns a new Attributes containing all key/value pairs in a and -// kvs. Panics if len(kvs) is not even. If the same key appears multiple -// times, the last value overwrites all previous values for that key. To -// remove an existing key, use a nil value. -func (a *Attributes) WithValues(kvs ...interface{}) *Attributes { - if a == nil { - return New(kvs...) - } - if len(kvs)%2 != 0 { - panic(fmt.Sprintf("attributes.New called with unexpected input: len(kvs) = %v", len(kvs))) - } - n := &Attributes{m: make(map[interface{}]interface{}, len(a.m)+len(kvs)/2)} - for k, v := range a.m { - n.m[k] = v - } - for i := 0; i < len(kvs)/2; i++ { - n.m[kvs[i*2]] = kvs[i*2+1] - } - return n -} - -// Value returns the value associated with these attributes for key, or nil if -// no value is associated with key. -func (a *Attributes) Value(key interface{}) interface{} { - if a == nil { - return nil - } - return a.m[key] -} diff --git a/examples/vendor/google.golang.org/grpc/internal/grpcutil/target.go b/examples/vendor/google.golang.org/grpc/internal/grpcutil/target.go deleted file mode 100644 index 8833021..0000000 --- a/examples/vendor/google.golang.org/grpc/internal/grpcutil/target.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - * - * Copyright 2020 gRPC 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 grpcutil provides a bunch of utility functions to be used across the -// gRPC codebase. -package grpcutil - -import ( - "strings" - - "google.golang.org/grpc/resolver" -) - -// split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns ("", "", false) instead. -func split2(s, sep string) (string, string, bool) { - spl := strings.SplitN(s, sep, 2) - if len(spl) < 2 { - return "", "", false - } - return spl[0], spl[1], true -} - -// ParseTarget splits target into a resolver.Target struct containing scheme, -// authority and endpoint. skipUnixColonParsing indicates that the parse should -// not parse "unix:[path]" cases. This should be true in cases where a custom -// dialer is present, to prevent a behavior change. -// -// If target is not a valid scheme://authority/endpoint as specified in -// https://github.com/grpc/grpc/blob/master/doc/naming.md, -// it returns {Endpoint: target}. -func ParseTarget(target string, skipUnixColonParsing bool) (ret resolver.Target) { - var ok bool - if strings.HasPrefix(target, "unix-abstract:") { - if strings.HasPrefix(target, "unix-abstract://") { - // Maybe, with Authority specified, try to parse it - var remain string - ret.Scheme, remain, _ = split2(target, "://") - ret.Authority, ret.Endpoint, ok = split2(remain, "/") - if !ok { - // No Authority, add the "//" back - ret.Endpoint = "//" + remain - } else { - // Found Authority, add the "/" back - ret.Endpoint = "/" + ret.Endpoint - } - } else { - // Without Authority specified, split target on ":" - ret.Scheme, ret.Endpoint, _ = split2(target, ":") - } - return ret - } - ret.Scheme, ret.Endpoint, ok = split2(target, "://") - if !ok { - if strings.HasPrefix(target, "unix:") && !skipUnixColonParsing { - // Handle the "unix:[local/path]" and "unix:[/absolute/path]" cases, - // because splitting on :// only handles the - // "unix://[/absolute/path]" case. Only handle if the dialer is nil, - // to avoid a behavior change with custom dialers. - return resolver.Target{Scheme: "unix", Endpoint: target[len("unix:"):]} - } - return resolver.Target{Endpoint: target} - } - ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") - if !ok { - return resolver.Target{Endpoint: target} - } - if ret.Scheme == "unix" { - // Add the "/" back in the unix case, so the unix resolver receives the - // actual endpoint in the "unix://[/absolute/path]" case. - ret.Endpoint = "/" + ret.Endpoint - } - return ret -} diff --git a/examples/vendor/google.golang.org/grpc/internal/xds/env/env.go b/examples/vendor/google.golang.org/grpc/internal/xds/env/env.go deleted file mode 100644 index b171ac9..0000000 --- a/examples/vendor/google.golang.org/grpc/internal/xds/env/env.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - * - * Copyright 2020 gRPC 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 env acts a single source of definition for all environment variables -// related to the xDS implementation in gRPC. -package env - -import ( - "os" - "strings" -) - -const ( - // BootstrapFileNameEnv is the env variable to set bootstrap file name. - // Do not use this and read from env directly. Its value is read and kept in - // variable BootstrapFileName. - // - // When both bootstrap FileName and FileContent are set, FileName is used. - BootstrapFileNameEnv = "GRPC_XDS_BOOTSTRAP" - // BootstrapFileContentEnv is the env variable to set bootstrapp file - // content. Do not use this and read from env directly. Its value is read - // and kept in variable BootstrapFileName. - // - // When both bootstrap FileName and FileContent are set, FileName is used. - BootstrapFileContentEnv = "GRPC_XDS_BOOTSTRAP_CONFIG" - - ringHashSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" - clientSideSecuritySupportEnv = "GRPC_XDS_EXPERIMENTAL_SECURITY_SUPPORT" - aggregateAndDNSSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" - retrySupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_RETRY" - rbacSupportEnv = "GRPC_XDS_EXPERIMENTAL_ENABLE_RBAC" - - c2pResolverSupportEnv = "GRPC_EXPERIMENTAL_GOOGLE_C2P_RESOLVER" - c2pResolverTestOnlyTrafficDirectorURIEnv = "GRPC_TEST_ONLY_GOOGLE_C2P_RESOLVER_TRAFFIC_DIRECTOR_URI" -) - -var ( - // BootstrapFileName holds the name of the file which contains xDS bootstrap - // configuration. Users can specify the location of the bootstrap file by - // setting the environment variable "GRPC_XDS_BOOTSTRAP". - // - // When both bootstrap FileName and FileContent are set, FileName is used. - BootstrapFileName = os.Getenv(BootstrapFileNameEnv) - // BootstrapFileContent holds the content of the xDS bootstrap - // configuration. Users can specify the bootstrap config by - // setting the environment variable "GRPC_XDS_BOOTSTRAP_CONFIG". - // - // When both bootstrap FileName and FileContent are set, FileName is used. - BootstrapFileContent = os.Getenv(BootstrapFileContentEnv) - // RingHashSupport indicates whether ring hash support is enabled, which can - // be disabled by setting the environment variable - // "GRPC_XDS_EXPERIMENTAL_ENABLE_RING_HASH" to "false". - RingHashSupport = !strings.EqualFold(os.Getenv(ringHashSupportEnv), "false") - // ClientSideSecuritySupport is used to control processing of security - // configuration on the client-side. - // - // Note that there is no env var protection for the server-side because we - // have a brand new API on the server-side and users explicitly need to use - // the new API to get security integration on the server. - ClientSideSecuritySupport = !strings.EqualFold(os.Getenv(clientSideSecuritySupportEnv), "false") - // AggregateAndDNSSupportEnv indicates whether processing of aggregated - // cluster and DNS cluster is enabled, which can be enabled by setting the - // environment variable - // "GRPC_XDS_EXPERIMENTAL_ENABLE_AGGREGATE_AND_LOGICAL_DNS_CLUSTER" to - // "true". - AggregateAndDNSSupportEnv = strings.EqualFold(os.Getenv(aggregateAndDNSSupportEnv), "true") - - // RetrySupport indicates whether xDS retry is enabled. - RetrySupport = !strings.EqualFold(os.Getenv(retrySupportEnv), "false") - - // RBACSupport indicates whether xDS configured RBAC HTTP Filter is enabled. - RBACSupport = strings.EqualFold(os.Getenv(rbacSupportEnv), "true") - - // C2PResolverSupport indicates whether support for C2P resolver is enabled. - // This can be enabled by setting the environment variable - // "GRPC_EXPERIMENTAL_GOOGLE_C2P_RESOLVER" to "true". - C2PResolverSupport = strings.EqualFold(os.Getenv(c2pResolverSupportEnv), "true") - // C2PResolverTestOnlyTrafficDirectorURI is the TD URI for testing. - C2PResolverTestOnlyTrafficDirectorURI = os.Getenv(c2pResolverTestOnlyTrafficDirectorURIEnv) -) diff --git a/examples/vendor/gopkg.in/fsnotify.v1/.editorconfig b/examples/vendor/gopkg.in/fsnotify.v1/.editorconfig deleted file mode 100644 index ba49e3c..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/.editorconfig +++ /dev/null @@ -1,5 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 diff --git a/examples/vendor/gopkg.in/fsnotify.v1/.gitignore b/examples/vendor/gopkg.in/fsnotify.v1/.gitignore deleted file mode 100644 index 4cd0cba..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Setup a Global .gitignore for OS and editor generated files: -# https://help.github.com/articles/ignoring-files -# git config --global core.excludesfile ~/.gitignore_global - -.vagrant -*.sublime-project diff --git a/examples/vendor/gopkg.in/fsnotify.v1/.travis.yml b/examples/vendor/gopkg.in/fsnotify.v1/.travis.yml deleted file mode 100644 index 981d1bb..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -sudo: false -language: go - -go: - - 1.8.x - - 1.9.x - - tip - -matrix: - allow_failures: - - go: tip - fast_finish: true - -before_script: - - go get -u github.com/golang/lint/golint - -script: - - go test -v --race ./... - -after_script: - - test -z "$(gofmt -s -l -w . | tee /dev/stderr)" - - test -z "$(golint ./... | tee /dev/stderr)" - - go vet ./... - -os: - - linux - - osx - -notifications: - email: false diff --git a/examples/vendor/gopkg.in/fsnotify.v1/AUTHORS b/examples/vendor/gopkg.in/fsnotify.v1/AUTHORS deleted file mode 100644 index 5ab5d41..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/AUTHORS +++ /dev/null @@ -1,52 +0,0 @@ -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# You can update this list using the following command: -# -# $ git shortlog -se | awk '{print $2 " " $3 " " $4}' - -# Please keep the list sorted. - -Aaron L -Adrien Bustany -Amit Krishnan -Anmol Sethi -Bjørn Erik Pedersen -Bruno Bigras -Caleb Spare -Case Nelson -Chris Howey -Christoffer Buchholz -Daniel Wagner-Hall -Dave Cheney -Evan Phoenix -Francisco Souza -Hari haran -John C Barstow -Kelvin Fo -Ken-ichirou MATSUZAWA -Matt Layher -Nathan Youngman -Nickolai Zeldovich -Patrick -Paul Hammond -Pawel Knap -Pieter Droogendijk -Pursuit92 -Riku Voipio -Rob Figueiredo -Rodrigo Chiossi -Slawek Ligus -Soge Zhang -Tiffany Jernigan -Tilak Sharma -Tom Payne -Travis Cline -Tudor Golubenco -Vahe Khachikyan -Yukang -bronze1man -debrando -henrikedwards -铁哥 diff --git a/examples/vendor/gopkg.in/fsnotify.v1/CHANGELOG.md b/examples/vendor/gopkg.in/fsnotify.v1/CHANGELOG.md deleted file mode 100644 index be4d7ea..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/CHANGELOG.md +++ /dev/null @@ -1,317 +0,0 @@ -# Changelog - -## v1.4.7 / 2018-01-09 - -* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) -* Tests: Fix missing verb on format string (thanks @rchiossi) -* Linux: Fix deadlock in Remove (thanks @aarondl) -* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) -* Docs: Moved FAQ into the README (thanks @vahe) -* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) -* Docs: replace references to OS X with macOS - -## v1.4.2 / 2016-10-10 - -* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) - -## v1.4.1 / 2016-10-04 - -* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) - -## v1.4.0 / 2016-10-01 - -* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) - -## v1.3.1 / 2016-06-28 - -* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) - -## v1.3.0 / 2016-04-19 - -* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) - -## v1.2.10 / 2016-03-02 - -* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) - -## v1.2.9 / 2016-01-13 - -kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) - -## v1.2.8 / 2015-12-17 - -* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) -* inotify: fix race in test -* enable race detection for continuous integration (Linux, Mac, Windows) - -## v1.2.5 / 2015-10-17 - -* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) -* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) -* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) -* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) - -## v1.2.1 / 2015-10-14 - -* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) - -## v1.2.0 / 2015-02-08 - -* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) -* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) -* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) - -## v1.1.1 / 2015-02-05 - -* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) - -## v1.1.0 / 2014-12-12 - -* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) - * add low-level functions - * only need to store flags on directories - * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13) - * done can be an unbuffered channel - * remove calls to os.NewSyscallError -* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher) -* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## v1.0.4 / 2014-09-07 - -* kqueue: add dragonfly to the build tags. -* Rename source code files, rearrange code so exported APIs are at the top. -* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) - -## v1.0.3 / 2014-08-19 - -* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) - -## v1.0.2 / 2014-08-17 - -* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) -* [Fix] Make ./path and path equivalent. (thanks @zhsso) - -## v1.0.0 / 2014-08-15 - -* [API] Remove AddWatch on Windows, use Add. -* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) -* Minor updates based on feedback from golint. - -## dev / 2014-07-09 - -* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify). -* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) - -## dev / 2014-07-04 - -* kqueue: fix incorrect mutex used in Close() -* Update example to demonstrate usage of Op. - -## dev / 2014-06-28 - -* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4) -* Fix for String() method on Event (thanks Alex Brainman) -* Don't build on Plan 9 or Solaris (thanks @4ad) - -## dev / 2014-06-21 - -* Events channel of type Event rather than *Event. -* [internal] use syscall constants directly for inotify and kqueue. -* [internal] kqueue: rename events to kevents and fileEvent to event. - -## dev / 2014-06-19 - -* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). -* [internal] remove cookie from Event struct (unused). -* [internal] Event struct has the same definition across every OS. -* [internal] remove internal watch and removeWatch methods. - -## dev / 2014-06-12 - -* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). -* [API] Pluralized channel names: Events and Errors. -* [API] Renamed FileEvent struct to Event. -* [API] Op constants replace methods like IsCreate(). - -## dev / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## dev / 2014-05-23 - -* [API] Remove current implementation of WatchFlags. - * current implementation doesn't take advantage of OS for efficiency - * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes - * no tests for the current implementation - * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) - -## v0.9.3 / 2014-12-31 - -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## v0.9.2 / 2014-08-17 - -* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) - -## v0.9.1 / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## v0.9.0 / 2014-01-17 - -* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) -* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) -* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. - -## v0.8.12 / 2013-11-13 - -* [API] Remove FD_SET and friends from Linux adapter - -## v0.8.11 / 2013-11-02 - -* [Doc] Add Changelog [#72][] (thanks @nathany) -* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) - -## v0.8.10 / 2013-10-19 - -* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) -* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) -* [Doc] specify OS-specific limits in README (thanks @debrando) - -## v0.8.9 / 2013-09-08 - -* [Doc] Contributing (thanks @nathany) -* [Doc] update package path in example code [#63][] (thanks @paulhammond) -* [Doc] GoCI badge in README (Linux only) [#60][] -* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) - -## v0.8.8 / 2013-06-17 - -* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) - -## v0.8.7 / 2013-06-03 - -* [API] Make syscall flags internal -* [Fix] inotify: ignore event changes -* [Fix] race in symlink test [#45][] (reported by @srid) -* [Fix] tests on Windows -* lower case error messages - -## v0.8.6 / 2013-05-23 - -* kqueue: Use EVT_ONLY flag on Darwin -* [Doc] Update README with full example - -## v0.8.5 / 2013-05-09 - -* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) - -## v0.8.4 / 2013-04-07 - -* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) - -## v0.8.3 / 2013-03-13 - -* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) -* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) - -## v0.8.2 / 2013-02-07 - -* [Doc] add Authors -* [Fix] fix data races for map access [#29][] (thanks @fsouza) - -## v0.8.1 / 2013-01-09 - -* [Fix] Windows path separators -* [Doc] BSD License - -## v0.8.0 / 2012-11-09 - -* kqueue: directory watching improvements (thanks @vmirage) -* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) -* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) - -## v0.7.4 / 2012-10-09 - -* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) -* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) -* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) -* [Fix] kqueue: modify after recreation of file - -## v0.7.3 / 2012-09-27 - -* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) -* [Fix] kqueue: no longer get duplicate CREATE events - -## v0.7.2 / 2012-09-01 - -* kqueue: events for created directories - -## v0.7.1 / 2012-07-14 - -* [Fix] for renaming files - -## v0.7.0 / 2012-07-02 - -* [Feature] FSNotify flags -* [Fix] inotify: Added file name back to event path - -## v0.6.0 / 2012-06-06 - -* kqueue: watch files after directory created (thanks @tmc) - -## v0.5.1 / 2012-05-22 - -* [Fix] inotify: remove all watches before Close() - -## v0.5.0 / 2012-05-03 - -* [API] kqueue: return errors during watch instead of sending over channel -* kqueue: match symlink behavior on Linux -* inotify: add `DELETE_SELF` (requested by @taralx) -* [Fix] kqueue: handle EINTR (reported by @robfig) -* [Doc] Godoc example [#1][] (thanks @davecheney) - -## v0.4.0 / 2012-03-30 - -* Go 1 released: build with go tool -* [Feature] Windows support using winfsnotify -* Windows does not have attribute change notifications -* Roll attribute notifications into IsModify - -## v0.3.0 / 2012-02-19 - -* kqueue: add files when watch directory - -## v0.2.0 / 2011-12-30 - -* update to latest Go weekly code - -## v0.1.0 / 2011-10-19 - -* kqueue: add watch on file creation to match inotify -* kqueue: create file event -* inotify: ignore `IN_IGNORED` events -* event String() -* linux: common FileEvent functions -* initial commit - -[#79]: https://github.com/howeyc/fsnotify/pull/79 -[#77]: https://github.com/howeyc/fsnotify/pull/77 -[#72]: https://github.com/howeyc/fsnotify/issues/72 -[#71]: https://github.com/howeyc/fsnotify/issues/71 -[#70]: https://github.com/howeyc/fsnotify/issues/70 -[#63]: https://github.com/howeyc/fsnotify/issues/63 -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#60]: https://github.com/howeyc/fsnotify/issues/60 -[#59]: https://github.com/howeyc/fsnotify/issues/59 -[#49]: https://github.com/howeyc/fsnotify/issues/49 -[#45]: https://github.com/howeyc/fsnotify/issues/45 -[#40]: https://github.com/howeyc/fsnotify/issues/40 -[#36]: https://github.com/howeyc/fsnotify/issues/36 -[#33]: https://github.com/howeyc/fsnotify/issues/33 -[#29]: https://github.com/howeyc/fsnotify/issues/29 -[#25]: https://github.com/howeyc/fsnotify/issues/25 -[#24]: https://github.com/howeyc/fsnotify/issues/24 -[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/examples/vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md b/examples/vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md deleted file mode 100644 index 828a60b..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/CONTRIBUTING.md +++ /dev/null @@ -1,77 +0,0 @@ -# Contributing - -## Issues - -* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/fsnotify/fsnotify/issues). -* Please indicate the platform you are using fsnotify on. -* A code example to reproduce the problem is appreciated. - -## Pull Requests - -### Contributor License Agreement - -fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual). - -Please indicate that you have signed the CLA in your pull request. - -### How fsnotify is Developed - -* Development is done on feature branches. -* Tests are run on BSD, Linux, macOS and Windows. -* Pull requests are reviewed and [applied to master][am] using [hub][]. - * Maintainers may modify or squash commits rather than asking contributors to. -* To issue a new release, the maintainers will: - * Update the CHANGELOG - * Tag a version, which will become available through gopkg.in. - -### How to Fork - -For smooth sailing, always use the original import path. Installing with `go get` makes this easy. - -1. Install from GitHub (`go get -u github.com/fsnotify/fsnotify`) -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Ensure everything works and the tests pass (see below) -4. Commit your changes (`git commit -am 'Add some feature'`) - -Contribute upstream: - -1. Fork fsnotify on GitHub -2. Add your remote (`git remote add fork git@github.com:mycompany/repo.git`) -3. Push to the branch (`git push fork my-new-feature`) -4. Create a new Pull Request on GitHub - -This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/contributing-open-source-git-repositories-go/). - -### Testing - -fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Windows. - -Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on. - -To aid in cross-platform testing there is a Vagrantfile for Linux and BSD. - -* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/) -* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder. -* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password) -* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`. -* When you're done, you will want to halt or destroy the Vagrant boxes. - -Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory. - -Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads). - -### Maintainers - -Help maintaining fsnotify is welcome. To be a maintainer: - -* Submit a pull request and sign the CLA as above. -* You must be able to run the test suite on Mac, Windows, Linux and BSD. - -To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][]. - -All code changes should be internal pull requests. - -Releases are tagged using [Semantic Versioning](http://semver.org/). - -[hub]: https://github.com/github/hub -[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs diff --git a/examples/vendor/gopkg.in/fsnotify.v1/LICENSE b/examples/vendor/gopkg.in/fsnotify.v1/LICENSE deleted file mode 100644 index f21e540..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2012 fsnotify Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/examples/vendor/gopkg.in/fsnotify.v1/README.md b/examples/vendor/gopkg.in/fsnotify.v1/README.md deleted file mode 100644 index 3993207..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# File system notifications for Go - -[![GoDoc](https://godoc.org/github.com/fsnotify/fsnotify?status.svg)](https://godoc.org/github.com/fsnotify/fsnotify) [![Go Report Card](https://goreportcard.com/badge/github.com/fsnotify/fsnotify)](https://goreportcard.com/report/github.com/fsnotify/fsnotify) - -fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather than `syscall` from the standard library. Ensure you have the latest version installed by running: - -```console -go get -u golang.org/x/sys/... -``` - -Cross platform: Windows, Linux, BSD and macOS. - -|Adapter |OS |Status | -|----------|----------|----------| -|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| -|kqueue |BSD, macOS, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| -|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)| -|FSEvents |macOS |[Planned](https://github.com/fsnotify/fsnotify/issues/11)| -|FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)| -|fanotify |Linux 2.6.37+ | | -|USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)| -|Polling |*All* |[Maybe](https://github.com/fsnotify/fsnotify/issues/9)| - -\* Android and iOS are untested. - -Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) and consult the [FAQ](#faq) for usage information. - -## API stability - -fsnotify is a fork of [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify) with a new API as of v1.0. The API is based on [this design document](http://goo.gl/MrYxyA). - -All [releases](https://github.com/fsnotify/fsnotify/releases) are tagged based on [Semantic Versioning](http://semver.org/). Further API changes are [planned](https://github.com/fsnotify/fsnotify/milestones), and will be tagged with a new major revision number. - -Go 1.6 supports dependencies located in the `vendor/` folder. Unless you are creating a library, it is recommended that you copy fsnotify into `vendor/github.com/fsnotify/fsnotify` within your project, and likewise for `golang.org/x/sys`. - -## Contributing - -Please refer to [CONTRIBUTING][] before opening an issue or pull request. - -## Example - -See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go). - -## FAQ - -**When a file is moved to another directory is it still being watched?** - -No (it shouldn't be, unless you are watching where it was moved to). - -**When I watch a directory, are all subdirectories watched as well?** - -No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap [#18][]). - -**Do I have to watch the Error and Event channels in a separate goroutine?** - -As of now, yes. Looking into making this single-thread friendly (see [howeyc #7][#7]) - -**Why am I receiving multiple events for the same file on OS X?** - -Spotlight indexing on OS X can result in multiple events (see [howeyc #62][#62]). A temporary workaround is to add your folder(s) to the *Spotlight Privacy settings* until we have a native FSEvents implementation (see [#11][]). - -**How many files can be watched at once?** - -There are OS-specific limits as to how many watches can be created: -* Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error. -* BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error. - -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#18]: https://github.com/fsnotify/fsnotify/issues/18 -[#11]: https://github.com/fsnotify/fsnotify/issues/11 -[#7]: https://github.com/howeyc/fsnotify/issues/7 - -[contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md - -## Related Projects - -* [notify](https://github.com/rjeczalik/notify) -* [fsevents](https://github.com/fsnotify/fsevents) - diff --git a/examples/vendor/gopkg.in/fsnotify.v1/fsnotify.go b/examples/vendor/gopkg.in/fsnotify.v1/fsnotify.go deleted file mode 100644 index 190bf0d..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/fsnotify.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2012 The Go 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 !plan9 - -// Package fsnotify provides a platform-independent interface for file system notifications. -package fsnotify - -import ( - "bytes" - "errors" - "fmt" -) - -// Event represents a single file system notification. -type Event struct { - Name string // Relative path to the file or directory. - Op Op // File operation that triggered the event. -} - -// Op describes a set of file operations. -type Op uint32 - -// These are the generalized file operations that can trigger a notification. -const ( - Create Op = 1 << iota - Write - Remove - Rename - Chmod -) - -func (op Op) String() string { - // Use a buffer for efficient string concatenation - var buffer bytes.Buffer - - if op&Create == Create { - buffer.WriteString("|CREATE") - } - if op&Remove == Remove { - buffer.WriteString("|REMOVE") - } - if op&Write == Write { - buffer.WriteString("|WRITE") - } - if op&Rename == Rename { - buffer.WriteString("|RENAME") - } - if op&Chmod == Chmod { - buffer.WriteString("|CHMOD") - } - if buffer.Len() == 0 { - return "" - } - return buffer.String()[1:] // Strip leading pipe -} - -// String returns a string representation of the event in the form -// "file: REMOVE|WRITE|..." -func (e Event) String() string { - return fmt.Sprintf("%q: %s", e.Name, e.Op.String()) -} - -// Common errors that can be reported by a watcher -var ErrEventOverflow = errors.New("fsnotify queue overflow") diff --git a/examples/vendor/gopkg.in/fsnotify.v1/inotify.go b/examples/vendor/gopkg.in/fsnotify.v1/inotify.go deleted file mode 100644 index d9fd1b8..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/inotify.go +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2010 The Go 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 linux - -package fsnotify - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - "unsafe" - - "golang.org/x/sys/unix" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - mu sync.Mutex // Map access - fd int - poller *fdPoller - watches map[string]*watch // Map of inotify watches (key: path) - paths map[int]string // Map of watched paths (key: watch descriptor) - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - doneResp chan struct{} // Channel to respond to Close -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - // Create inotify fd - fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC) - if fd == -1 { - return nil, errno - } - // Create epoll - poller, err := newFdPoller(fd) - if err != nil { - unix.Close(fd) - return nil, err - } - w := &Watcher{ - fd: fd, - poller: poller, - watches: make(map[string]*watch), - paths: make(map[int]string), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan struct{}), - doneResp: make(chan struct{}), - } - - go w.readEvents() - return w, nil -} - -func (w *Watcher) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed() { - return nil - } - - // Send 'close' signal to goroutine, and set the Watcher to closed. - close(w.done) - - // Wake up goroutine - w.poller.wake() - - // Wait for goroutine to close - <-w.doneResp - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - name = filepath.Clean(name) - if w.isClosed() { - return errors.New("inotify instance already closed") - } - - const agnosticEvents = unix.IN_MOVED_TO | unix.IN_MOVED_FROM | - unix.IN_CREATE | unix.IN_ATTRIB | unix.IN_MODIFY | - unix.IN_MOVE_SELF | unix.IN_DELETE | unix.IN_DELETE_SELF - - var flags uint32 = agnosticEvents - - w.mu.Lock() - defer w.mu.Unlock() - watchEntry := w.watches[name] - if watchEntry != nil { - flags |= watchEntry.flags | unix.IN_MASK_ADD - } - wd, errno := unix.InotifyAddWatch(w.fd, name, flags) - if wd == -1 { - return errno - } - - if watchEntry == nil { - w.watches[name] = &watch{wd: uint32(wd), flags: flags} - w.paths[wd] = name - } else { - watchEntry.wd = uint32(wd) - watchEntry.flags = flags - } - - return nil -} - -// Remove stops watching the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - - // Fetch the watch. - w.mu.Lock() - defer w.mu.Unlock() - watch, ok := w.watches[name] - - // Remove it from inotify. - if !ok { - return fmt.Errorf("can't remove non-existent inotify watch for: %s", name) - } - - // We successfully removed the watch if InotifyRmWatch doesn't return an - // error, we need to clean up our internal state to ensure it matches - // inotify's kernel state. - delete(w.paths, int(watch.wd)) - delete(w.watches, name) - - // inotify_rm_watch will return EINVAL if the file has been deleted; - // the inotify will already have been removed. - // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously - // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE - // so that EINVAL means that the wd is being rm_watch()ed or its file removed - // by another thread and we have not received IN_IGNORE event. - success, errno := unix.InotifyRmWatch(w.fd, watch.wd) - if success == -1 { - // TODO: Perhaps it's not helpful to return an error here in every case. - // the only two possible errors are: - // EBADF, which happens when w.fd is not a valid file descriptor of any kind. - // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor. - // Watch descriptors are invalidated when they are removed explicitly or implicitly; - // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted. - return errno - } - - return nil -} - -type watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) - flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) -} - -// readEvents reads from the inotify file descriptor, converts the -// received events into Event objects and sends them via the Events channel -func (w *Watcher) readEvents() { - var ( - buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events - n int // Number of bytes read with read() - errno error // Syscall errno - ok bool // For poller.wait - ) - - defer close(w.doneResp) - defer close(w.Errors) - defer close(w.Events) - defer unix.Close(w.fd) - defer w.poller.close() - - for { - // See if we have been closed. - if w.isClosed() { - return - } - - ok, errno = w.poller.wait() - if errno != nil { - select { - case w.Errors <- errno: - case <-w.done: - return - } - continue - } - - if !ok { - continue - } - - n, errno = unix.Read(w.fd, buf[:]) - // If a signal interrupted execution, see if we've been asked to close, and try again. - // http://man7.org/linux/man-pages/man7/signal.7.html : - // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable" - if errno == unix.EINTR { - continue - } - - // unix.Read might have been woken up by Close. If so, we're done. - if w.isClosed() { - return - } - - if n < unix.SizeofInotifyEvent { - var err error - if n == 0 { - // If EOF is received. This should really never happen. - err = io.EOF - } else if n < 0 { - // If an error occurred while reading. - err = errno - } else { - // Read was too short. - err = errors.New("notify: short read in readEvents()") - } - select { - case w.Errors <- err: - case <-w.done: - return - } - continue - } - - var offset uint32 - // We don't know how many events we just read into the buffer - // While the offset points to at least one whole event... - for offset <= uint32(n-unix.SizeofInotifyEvent) { - // Point "raw" to the event in the buffer - raw := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) - - mask := uint32(raw.Mask) - nameLen := uint32(raw.Len) - - if mask&unix.IN_Q_OVERFLOW != 0 { - select { - case w.Errors <- ErrEventOverflow: - case <-w.done: - return - } - } - - // If the event happened to the watched directory or the watched file, the kernel - // doesn't append the filename to the event, but we would like to always fill the - // the "Name" field with a valid filename. We retrieve the path of the watch from - // the "paths" map. - w.mu.Lock() - name, ok := w.paths[int(raw.Wd)] - // IN_DELETE_SELF occurs when the file/directory being watched is removed. - // This is a sign to clean up the maps, otherwise we are no longer in sync - // with the inotify kernel state which has already deleted the watch - // automatically. - if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { - delete(w.paths, int(raw.Wd)) - delete(w.watches, name) - } - w.mu.Unlock() - - if nameLen > 0 { - // Point "bytes" at the first byte of the filename - bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) - // The filename is padded with NULL bytes. TrimRight() gets rid of those. - name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") - } - - event := newEvent(name, mask) - - // Send the events that are not ignored on the events channel - if !event.ignoreLinux(mask) { - select { - case w.Events <- event: - case <-w.done: - return - } - } - - // Move to the next event in the buffer - offset += unix.SizeofInotifyEvent + nameLen - } - } -} - -// Certain types of events can be "ignored" and not sent over the Events -// channel. Such as events marked ignore by the kernel, or MODIFY events -// against files that do not exist. -func (e *Event) ignoreLinux(mask uint32) bool { - // Ignore anything the inotify API says to ignore - if mask&unix.IN_IGNORED == unix.IN_IGNORED { - return true - } - - // If the event is not a DELETE or RENAME, the file must exist. - // Otherwise the event is ignored. - // *Note*: this was put in place because it was seen that a MODIFY - // event was sent after the DELETE. This ignores that MODIFY and - // assumes a DELETE will come or has come if the file doesn't exist. - if !(e.Op&Remove == Remove || e.Op&Rename == Rename) { - _, statErr := os.Lstat(e.Name) - return os.IsNotExist(statErr) - } - return false -} - -// newEvent returns an platform-independent Event based on an inotify mask. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { - e.Op |= Create - } - if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { - e.Op |= Remove - } - if mask&unix.IN_MODIFY == unix.IN_MODIFY { - e.Op |= Write - } - if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { - e.Op |= Rename - } - if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { - e.Op |= Chmod - } - return e -} diff --git a/examples/vendor/gopkg.in/fsnotify.v1/inotify_poller.go b/examples/vendor/gopkg.in/fsnotify.v1/inotify_poller.go deleted file mode 100644 index cc7db4b..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/inotify_poller.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2015 The Go 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 linux - -package fsnotify - -import ( - "errors" - - "golang.org/x/sys/unix" -) - -type fdPoller struct { - fd int // File descriptor (as returned by the inotify_init() syscall) - epfd int // Epoll file descriptor - pipe [2]int // Pipe for waking up -} - -func emptyPoller(fd int) *fdPoller { - poller := new(fdPoller) - poller.fd = fd - poller.epfd = -1 - poller.pipe[0] = -1 - poller.pipe[1] = -1 - return poller -} - -// Create a new inotify poller. -// This creates an inotify handler, and an epoll handler. -func newFdPoller(fd int) (*fdPoller, error) { - var errno error - poller := emptyPoller(fd) - defer func() { - if errno != nil { - poller.close() - } - }() - poller.fd = fd - - // Create epoll fd - poller.epfd, errno = unix.EpollCreate1(0) - if poller.epfd == -1 { - return nil, errno - } - // Create pipe; pipe[0] is the read end, pipe[1] the write end. - errno = unix.Pipe2(poller.pipe[:], unix.O_NONBLOCK) - if errno != nil { - return nil, errno - } - - // Register inotify fd with epoll - event := unix.EpollEvent{ - Fd: int32(poller.fd), - Events: unix.EPOLLIN, - } - errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.fd, &event) - if errno != nil { - return nil, errno - } - - // Register pipe fd with epoll - event = unix.EpollEvent{ - Fd: int32(poller.pipe[0]), - Events: unix.EPOLLIN, - } - errno = unix.EpollCtl(poller.epfd, unix.EPOLL_CTL_ADD, poller.pipe[0], &event) - if errno != nil { - return nil, errno - } - - return poller, nil -} - -// Wait using epoll. -// Returns true if something is ready to be read, -// false if there is not. -func (poller *fdPoller) wait() (bool, error) { - // 3 possible events per fd, and 2 fds, makes a maximum of 6 events. - // I don't know whether epoll_wait returns the number of events returned, - // or the total number of events ready. - // I decided to catch both by making the buffer one larger than the maximum. - events := make([]unix.EpollEvent, 7) - for { - n, errno := unix.EpollWait(poller.epfd, events, -1) - if n == -1 { - if errno == unix.EINTR { - continue - } - return false, errno - } - if n == 0 { - // If there are no events, try again. - continue - } - if n > 6 { - // This should never happen. More events were returned than should be possible. - return false, errors.New("epoll_wait returned more events than I know what to do with") - } - ready := events[:n] - epollhup := false - epollerr := false - epollin := false - for _, event := range ready { - if event.Fd == int32(poller.fd) { - if event.Events&unix.EPOLLHUP != 0 { - // This should not happen, but if it does, treat it as a wakeup. - epollhup = true - } - if event.Events&unix.EPOLLERR != 0 { - // If an error is waiting on the file descriptor, we should pretend - // something is ready to read, and let unix.Read pick up the error. - epollerr = true - } - if event.Events&unix.EPOLLIN != 0 { - // There is data to read. - epollin = true - } - } - if event.Fd == int32(poller.pipe[0]) { - if event.Events&unix.EPOLLHUP != 0 { - // Write pipe descriptor was closed, by us. This means we're closing down the - // watcher, and we should wake up. - } - if event.Events&unix.EPOLLERR != 0 { - // If an error is waiting on the pipe file descriptor. - // This is an absolute mystery, and should never ever happen. - return false, errors.New("Error on the pipe descriptor.") - } - if event.Events&unix.EPOLLIN != 0 { - // This is a regular wakeup, so we have to clear the buffer. - err := poller.clearWake() - if err != nil { - return false, err - } - } - } - } - - if epollhup || epollerr || epollin { - return true, nil - } - return false, nil - } -} - -// Close the write end of the poller. -func (poller *fdPoller) wake() error { - buf := make([]byte, 1) - n, errno := unix.Write(poller.pipe[1], buf) - if n == -1 { - if errno == unix.EAGAIN { - // Buffer is full, poller will wake. - return nil - } - return errno - } - return nil -} - -func (poller *fdPoller) clearWake() error { - // You have to be woken up a LOT in order to get to 100! - buf := make([]byte, 100) - n, errno := unix.Read(poller.pipe[0], buf) - if n == -1 { - if errno == unix.EAGAIN { - // Buffer is empty, someone else cleared our wake. - return nil - } - return errno - } - return nil -} - -// Close all poller file descriptors, but not the one passed to it. -func (poller *fdPoller) close() { - if poller.pipe[1] != -1 { - unix.Close(poller.pipe[1]) - } - if poller.pipe[0] != -1 { - unix.Close(poller.pipe[0]) - } - if poller.epfd != -1 { - unix.Close(poller.epfd) - } -} diff --git a/examples/vendor/gopkg.in/fsnotify.v1/kqueue.go b/examples/vendor/gopkg.in/fsnotify.v1/kqueue.go deleted file mode 100644 index 86e76a3..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/kqueue.go +++ /dev/null @@ -1,521 +0,0 @@ -// Copyright 2010 The Go 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 freebsd openbsd netbsd dragonfly darwin - -package fsnotify - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sync" - "time" - - "golang.org/x/sys/unix" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - - kq int // File descriptor (as returned by the kqueue() syscall). - - mu sync.Mutex // Protects access to watcher data - watches map[string]int // Map of watched file descriptors (key: path). - externalWatches map[string]bool // Map of watches added by user of the library. - dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue. - paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events. - fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events). - isClosed bool // Set to true when Close() is first called -} - -type pathInfo struct { - name string - isDir bool -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - kq, err := kqueue() - if err != nil { - return nil, err - } - - w := &Watcher{ - kq: kq, - watches: make(map[string]int), - dirFlags: make(map[string]uint32), - paths: make(map[int]pathInfo), - fileExists: make(map[string]bool), - externalWatches: make(map[string]bool), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan struct{}), - } - - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return nil - } - w.isClosed = true - - // copy paths to remove while locked - var pathsToRemove = make([]string, 0, len(w.watches)) - for name := range w.watches { - pathsToRemove = append(pathsToRemove, name) - } - w.mu.Unlock() - // unlock before calling Remove, which also locks - - for _, name := range pathsToRemove { - w.Remove(name) - } - - // send a "quit" message to the reader goroutine - close(w.done) - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - w.mu.Lock() - w.externalWatches[name] = true - w.mu.Unlock() - _, err := w.addWatch(name, noteAllEvents) - return err -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - w.mu.Lock() - watchfd, ok := w.watches[name] - w.mu.Unlock() - if !ok { - return fmt.Errorf("can't remove non-existent kevent watch for: %s", name) - } - - const registerRemove = unix.EV_DELETE - if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil { - return err - } - - unix.Close(watchfd) - - w.mu.Lock() - isDir := w.paths[watchfd].isDir - delete(w.watches, name) - delete(w.paths, watchfd) - delete(w.dirFlags, name) - w.mu.Unlock() - - // Find all watched paths that are in this directory that are not external. - if isDir { - var pathsToRemove []string - w.mu.Lock() - for _, path := range w.paths { - wdir, _ := filepath.Split(path.name) - if filepath.Clean(wdir) == name { - if !w.externalWatches[path.name] { - pathsToRemove = append(pathsToRemove, path.name) - } - } - } - w.mu.Unlock() - for _, name := range pathsToRemove { - // Since these are internal, not much sense in propagating error - // to the user, as that will just confuse them with an error about - // a path they did not explicitly watch themselves. - w.Remove(name) - } - } - - return nil -} - -// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) -const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME - -// keventWaitTime to block on each read from kevent -var keventWaitTime = durationToTimespec(100 * time.Millisecond) - -// addWatch adds name to the watched file set. -// The flags are interpreted as described in kevent(2). -// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks. -func (w *Watcher) addWatch(name string, flags uint32) (string, error) { - var isDir bool - // Make ./name and name equivalent - name = filepath.Clean(name) - - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return "", errors.New("kevent instance already closed") - } - watchfd, alreadyWatching := w.watches[name] - // We already have a watch, but we can still override flags. - if alreadyWatching { - isDir = w.paths[watchfd].isDir - } - w.mu.Unlock() - - if !alreadyWatching { - fi, err := os.Lstat(name) - if err != nil { - return "", err - } - - // Don't watch sockets. - if fi.Mode()&os.ModeSocket == os.ModeSocket { - return "", nil - } - - // Don't watch named pipes. - if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe { - return "", nil - } - - // Follow Symlinks - // Unfortunately, Linux can add bogus symlinks to watch list without - // issue, and Windows can't do symlinks period (AFAIK). To maintain - // consistency, we will act like everything is fine. There will simply - // be no file events for broken symlinks. - // Hence the returns of nil on errors. - if fi.Mode()&os.ModeSymlink == os.ModeSymlink { - name, err = filepath.EvalSymlinks(name) - if err != nil { - return "", nil - } - - w.mu.Lock() - _, alreadyWatching = w.watches[name] - w.mu.Unlock() - - if alreadyWatching { - return name, nil - } - - fi, err = os.Lstat(name) - if err != nil { - return "", nil - } - } - - watchfd, err = unix.Open(name, openMode, 0700) - if watchfd == -1 { - return "", err - } - - isDir = fi.IsDir() - } - - const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE - if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil { - unix.Close(watchfd) - return "", err - } - - if !alreadyWatching { - w.mu.Lock() - w.watches[name] = watchfd - w.paths[watchfd] = pathInfo{name: name, isDir: isDir} - w.mu.Unlock() - } - - if isDir { - // Watch the directory if it has not been watched before, - // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) - w.mu.Lock() - - watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && - (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE) - // Store flags so this watch can be updated later - w.dirFlags[name] = flags - w.mu.Unlock() - - if watchDir { - if err := w.watchDirectoryFiles(name); err != nil { - return "", err - } - } - } - return name, nil -} - -// readEvents reads from kqueue and converts the received kevents into -// Event values that it sends down the Events channel. -func (w *Watcher) readEvents() { - eventBuffer := make([]unix.Kevent_t, 10) - -loop: - for { - // See if there is a message on the "done" channel - select { - case <-w.done: - break loop - default: - } - - // Get new events - kevents, err := read(w.kq, eventBuffer, &keventWaitTime) - // EINTR is okay, the syscall was interrupted before timeout expired. - if err != nil && err != unix.EINTR { - select { - case w.Errors <- err: - case <-w.done: - break loop - } - continue - } - - // Flush the events we received to the Events channel - for len(kevents) > 0 { - kevent := &kevents[0] - watchfd := int(kevent.Ident) - mask := uint32(kevent.Fflags) - w.mu.Lock() - path := w.paths[watchfd] - w.mu.Unlock() - event := newEvent(path.name, mask) - - if path.isDir && !(event.Op&Remove == Remove) { - // Double check to make sure the directory exists. This can happen when - // we do a rm -fr on a recursively watched folders and we receive a - // modification event first but the folder has been deleted and later - // receive the delete event - if _, err := os.Lstat(event.Name); os.IsNotExist(err) { - // mark is as delete event - event.Op |= Remove - } - } - - if event.Op&Rename == Rename || event.Op&Remove == Remove { - w.Remove(event.Name) - w.mu.Lock() - delete(w.fileExists, event.Name) - w.mu.Unlock() - } - - if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { - w.sendDirectoryChangeEvents(event.Name) - } else { - // Send the event on the Events channel. - select { - case w.Events <- event: - case <-w.done: - break loop - } - } - - if event.Op&Remove == Remove { - // Look for a file that may have overwritten this. - // For example, mv f1 f2 will delete f2, then create f2. - if path.isDir { - fileDir := filepath.Clean(event.Name) - w.mu.Lock() - _, found := w.watches[fileDir] - w.mu.Unlock() - if found { - // make sure the directory exists before we watch for changes. When we - // do a recursive watch and perform rm -fr, the parent directory might - // have gone missing, ignore the missing directory and let the - // upcoming delete event remove the watch from the parent directory. - if _, err := os.Lstat(fileDir); err == nil { - w.sendDirectoryChangeEvents(fileDir) - } - } - } else { - filePath := filepath.Clean(event.Name) - if fileInfo, err := os.Lstat(filePath); err == nil { - w.sendFileCreatedEventIfNew(filePath, fileInfo) - } - } - } - - // Move to next event - kevents = kevents[1:] - } - } - - // cleanup - err := unix.Close(w.kq) - if err != nil { - // only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors. - select { - case w.Errors <- err: - default: - } - } - close(w.Events) - close(w.Errors) -} - -// newEvent returns an platform-independent Event based on kqueue Fflags. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { - e.Op |= Remove - } - if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { - e.Op |= Write - } - if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { - e.Op |= Rename - } - if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { - e.Op |= Chmod - } - return e -} - -func newCreateEvent(name string) Event { - return Event{Name: name, Op: Create} -} - -// watchDirectoryFiles to mimic inotify when adding a watch on a directory -func (w *Watcher) watchDirectoryFiles(dirPath string) error { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - return err - } - - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - } - - return nil -} - -// sendDirectoryEvents searches the directory for newly created files -// and sends them over the event channel. This functionality is to have -// the BSD version of fsnotify match Linux inotify which provides a -// create event for files created in a watched directory. -func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - select { - case w.Errors <- err: - case <-w.done: - return - } - } - - // Search for new files - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - err := w.sendFileCreatedEventIfNew(filePath, fileInfo) - - if err != nil { - return - } - } -} - -// sendFileCreatedEvent sends a create event if the file isn't already being tracked. -func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { - w.mu.Lock() - _, doesExist := w.fileExists[filePath] - w.mu.Unlock() - if !doesExist { - // Send create event - select { - case w.Events <- newCreateEvent(filePath): - case <-w.done: - return - } - } - - // like watchDirectoryFiles (but without doing another ReadDir) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - - return nil -} - -func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) { - if fileInfo.IsDir() { - // mimic Linux providing delete events for subdirectories - // but preserve the flags used if currently watching subdirectory - w.mu.Lock() - flags := w.dirFlags[name] - w.mu.Unlock() - - flags |= unix.NOTE_DELETE | unix.NOTE_RENAME - return w.addWatch(name, flags) - } - - // watch file to mimic Linux inotify - return w.addWatch(name, noteAllEvents) -} - -// kqueue creates a new kernel event queue and returns a descriptor. -func kqueue() (kq int, err error) { - kq, err = unix.Kqueue() - if kq == -1 { - return kq, err - } - return kq, nil -} - -// register events with the queue -func register(kq int, fds []int, flags int, fflags uint32) error { - changes := make([]unix.Kevent_t, len(fds)) - - for i, fd := range fds { - // SetKevent converts int to the platform-specific types: - unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) - changes[i].Fflags = fflags - } - - // register the events - success, err := unix.Kevent(kq, changes, nil, nil) - if success == -1 { - return err - } - return nil -} - -// read retrieves pending events, or waits until an event occurs. -// A timeout of nil blocks indefinitely, while 0 polls the queue. -func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) { - n, err := unix.Kevent(kq, nil, events, timeout) - if err != nil { - return nil, err - } - return events[0:n], nil -} - -// durationToTimespec prepares a timeout value -func durationToTimespec(d time.Duration) unix.Timespec { - return unix.NsecToTimespec(d.Nanoseconds()) -} diff --git a/examples/vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go b/examples/vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go deleted file mode 100644 index 7d8de14..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go 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 freebsd openbsd netbsd dragonfly - -package fsnotify - -import "golang.org/x/sys/unix" - -const openMode = unix.O_NONBLOCK | unix.O_RDONLY diff --git a/examples/vendor/gopkg.in/fsnotify.v1/open_mode_darwin.go b/examples/vendor/gopkg.in/fsnotify.v1/open_mode_darwin.go deleted file mode 100644 index 9139e17..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/open_mode_darwin.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 The Go 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 darwin - -package fsnotify - -import "golang.org/x/sys/unix" - -// note: this constant is not defined on BSD -const openMode = unix.O_EVTONLY diff --git a/examples/vendor/gopkg.in/fsnotify.v1/windows.go b/examples/vendor/gopkg.in/fsnotify.v1/windows.go deleted file mode 100644 index 09436f3..0000000 --- a/examples/vendor/gopkg.in/fsnotify.v1/windows.go +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright 2011 The Go 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 windows - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "syscall" - "unsafe" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - isClosed bool // Set to true when Close() is first called - mu sync.Mutex // Map access - port syscall.Handle // Handle to completion port - watches watchMap // Map of watches (key: i-number) - input chan *input // Inputs to the reader are sent on this channel - quit chan chan<- error -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) - if e != nil { - return nil, os.NewSyscallError("CreateIoCompletionPort", e) - } - w := &Watcher{ - port: port, - watches: make(watchMap), - input: make(chan *input, 1), - Events: make(chan Event, 50), - Errors: make(chan error), - quit: make(chan chan<- error, 1), - } - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed { - return nil - } - w.isClosed = true - - // Send "quit" message to the reader goroutine - ch := make(chan error) - w.quit <- ch - if err := w.wakeupReader(); err != nil { - return err - } - return <-ch -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - if w.isClosed { - return errors.New("watcher already closed") - } - in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sysFSALLEVENTS, - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - in := &input{ - op: opRemoveWatch, - path: filepath.Clean(name), - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -const ( - // Options for AddWatch - sysFSONESHOT = 0x80000000 - sysFSONLYDIR = 0x1000000 - - // Events - sysFSACCESS = 0x1 - sysFSALLEVENTS = 0xfff - sysFSATTRIB = 0x4 - sysFSCLOSE = 0x18 - sysFSCREATE = 0x100 - sysFSDELETE = 0x200 - sysFSDELETESELF = 0x400 - sysFSMODIFY = 0x2 - sysFSMOVE = 0xc0 - sysFSMOVEDFROM = 0x40 - sysFSMOVEDTO = 0x80 - sysFSMOVESELF = 0x800 - - // Special events - sysFSIGNORED = 0x8000 - sysFSQOVERFLOW = 0x4000 -) - -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { - e.Op |= Create - } - if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { - e.Op |= Remove - } - if mask&sysFSMODIFY == sysFSMODIFY { - e.Op |= Write - } - if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { - e.Op |= Rename - } - if mask&sysFSATTRIB == sysFSATTRIB { - e.Op |= Chmod - } - return e -} - -const ( - opAddWatch = iota - opRemoveWatch -) - -const ( - provisional uint64 = 1 << (32 + iota) -) - -type input struct { - op int - path string - flags uint32 - reply chan error -} - -type inode struct { - handle syscall.Handle - volume uint32 - index uint64 -} - -type watch struct { - ov syscall.Overlapped - ino *inode // i-number - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf [4096]byte -} - -type indexMap map[uint64]*watch -type watchMap map[uint32]indexMap - -func (w *Watcher) wakeupReader() error { - e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil) - if e != nil { - return os.NewSyscallError("PostQueuedCompletionStatus", e) - } - return nil -} - -func getDir(pathname string) (dir string, err error) { - attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname)) - if e != nil { - return "", os.NewSyscallError("GetFileAttributes", e) - } - if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { - dir = pathname - } else { - dir, _ = filepath.Split(pathname) - dir = filepath.Clean(dir) - } - return -} - -func getIno(path string) (ino *inode, err error) { - h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path), - syscall.FILE_LIST_DIRECTORY, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - nil, syscall.OPEN_EXISTING, - syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0) - if e != nil { - return nil, os.NewSyscallError("CreateFile", e) - } - var fi syscall.ByHandleFileInformation - if e = syscall.GetFileInformationByHandle(h, &fi); e != nil { - syscall.CloseHandle(h) - return nil, os.NewSyscallError("GetFileInformationByHandle", e) - } - ino = &inode{ - handle: h, - volume: fi.VolumeSerialNumber, - index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), - } - return ino, nil -} - -// Must run within the I/O thread. -func (m watchMap) get(ino *inode) *watch { - if i := m[ino.volume]; i != nil { - return i[ino.index] - } - return nil -} - -// Must run within the I/O thread. -func (m watchMap) set(ino *inode, watch *watch) { - i := m[ino.volume] - if i == nil { - i = make(indexMap) - m[ino.volume] = i - } - i[ino.index] = watch -} - -// Must run within the I/O thread. -func (w *Watcher) addWatch(pathname string, flags uint64) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - if flags&sysFSONLYDIR != 0 && pathname != dir { - return nil - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watchEntry := w.watches.get(ino) - w.mu.Unlock() - if watchEntry == nil { - if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil { - syscall.CloseHandle(ino.handle) - return os.NewSyscallError("CreateIoCompletionPort", e) - } - watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), - } - w.mu.Lock() - w.watches.set(ino, watchEntry) - w.mu.Unlock() - flags |= provisional - } else { - syscall.CloseHandle(ino.handle) - } - if pathname == dir { - watchEntry.mask |= flags - } else { - watchEntry.names[filepath.Base(pathname)] |= flags - } - if err = w.startRead(watchEntry); err != nil { - return err - } - if pathname == dir { - watchEntry.mask &= ^provisional - } else { - watchEntry.names[filepath.Base(pathname)] &= ^provisional - } - return nil -} - -// Must run within the I/O thread. -func (w *Watcher) remWatch(pathname string) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watch := w.watches.get(ino) - w.mu.Unlock() - if watch == nil { - return fmt.Errorf("can't remove non-existent watch for: %s", pathname) - } - if pathname == dir { - w.sendEvent(watch.path, watch.mask&sysFSIGNORED) - watch.mask = 0 - } else { - name := filepath.Base(pathname) - w.sendEvent(filepath.Join(watch.path, name), watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - return w.startRead(watch) -} - -// Must run within the I/O thread. -func (w *Watcher) deleteWatch(watch *watch) { - for name, mask := range watch.names { - if mask&provisional == 0 { - w.sendEvent(filepath.Join(watch.path, name), mask&sysFSIGNORED) - } - delete(watch.names, name) - } - if watch.mask != 0 { - if watch.mask&provisional == 0 { - w.sendEvent(watch.path, watch.mask&sysFSIGNORED) - } - watch.mask = 0 - } -} - -// Must run within the I/O thread. -func (w *Watcher) startRead(watch *watch) error { - if e := syscall.CancelIo(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CancelIo", e) - w.deleteWatch(watch) - } - mask := toWindowsFlags(watch.mask) - for _, m := range watch.names { - mask |= toWindowsFlags(m) - } - if mask == 0 { - if e := syscall.CloseHandle(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CloseHandle", e) - } - w.mu.Lock() - delete(w.watches[watch.ino.volume], watch.ino.index) - w.mu.Unlock() - return nil - } - e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0], - uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0) - if e != nil { - err := os.NewSyscallError("ReadDirectoryChanges", e) - if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { - // Watched directory was probably removed - if w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) { - if watch.mask&sysFSONESHOT != 0 { - watch.mask = 0 - } - } - err = nil - } - w.deleteWatch(watch) - w.startRead(watch) - return err - } - return nil -} - -// readEvents reads from the I/O completion port, converts the -// received events into Event objects and sends them via the Events channel. -// Entry point to the I/O thread. -func (w *Watcher) readEvents() { - var ( - n, key uint32 - ov *syscall.Overlapped - ) - runtime.LockOSThread() - - for { - e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE) - watch := (*watch)(unsafe.Pointer(ov)) - - if watch == nil { - select { - case ch := <-w.quit: - w.mu.Lock() - var indexes []indexMap - for _, index := range w.watches { - indexes = append(indexes, index) - } - w.mu.Unlock() - for _, index := range indexes { - for _, watch := range index { - w.deleteWatch(watch) - w.startRead(watch) - } - } - var err error - if e := syscall.CloseHandle(w.port); e != nil { - err = os.NewSyscallError("CloseHandle", e) - } - close(w.Events) - close(w.Errors) - ch <- err - return - case in := <-w.input: - switch in.op { - case opAddWatch: - in.reply <- w.addWatch(in.path, uint64(in.flags)) - case opRemoveWatch: - in.reply <- w.remWatch(in.path) - } - default: - } - continue - } - - switch e { - case syscall.ERROR_MORE_DATA: - if watch == nil { - w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer") - } else { - // The i/o succeeded but the buffer is full. - // In theory we should be building up a full packet. - // In practice we can get away with just carrying on. - n = uint32(unsafe.Sizeof(watch.buf)) - } - case syscall.ERROR_ACCESS_DENIED: - // Watched directory was probably removed - w.sendEvent(watch.path, watch.mask&sysFSDELETESELF) - w.deleteWatch(watch) - w.startRead(watch) - continue - case syscall.ERROR_OPERATION_ABORTED: - // CancelIo was called on this handle - continue - default: - w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e) - continue - case nil: - } - - var offset uint32 - for { - if n == 0 { - w.Events <- newEvent("", sysFSQOVERFLOW) - w.Errors <- errors.New("short read in readEvents()") - break - } - - // Point "raw" to the event in the buffer - raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) - buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName)) - name := syscall.UTF16ToString(buf[:raw.FileNameLength/2]) - fullname := filepath.Join(watch.path, name) - - var mask uint64 - switch raw.Action { - case syscall.FILE_ACTION_REMOVED: - mask = sysFSDELETESELF - case syscall.FILE_ACTION_MODIFIED: - mask = sysFSMODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - watch.rename = name - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - if watch.names[watch.rename] != 0 { - watch.names[name] |= watch.names[watch.rename] - delete(watch.names, watch.rename) - mask = sysFSMOVESELF - } - } - - sendNameEvent := func() { - if w.sendEvent(fullname, watch.names[name]&mask) { - if watch.names[name]&sysFSONESHOT != 0 { - delete(watch.names, name) - } - } - } - if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME { - sendNameEvent() - } - if raw.Action == syscall.FILE_ACTION_REMOVED { - w.sendEvent(fullname, watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) { - if watch.mask&sysFSONESHOT != 0 { - watch.mask = 0 - } - } - if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME { - fullname = filepath.Join(watch.path, watch.rename) - sendNameEvent() - } - - // Move to the next event in the buffer - if raw.NextEntryOffset == 0 { - break - } - offset += raw.NextEntryOffset - - // Error! - if offset >= n { - w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.") - break - } - } - - if err := w.startRead(watch); err != nil { - w.Errors <- err - } - } -} - -func (w *Watcher) sendEvent(name string, mask uint64) bool { - if mask == 0 { - return false - } - event := newEvent(name, uint32(mask)) - select { - case ch := <-w.quit: - w.quit <- ch - case w.Events <- event: - } - return true -} - -func toWindowsFlags(mask uint64) uint32 { - var m uint32 - if mask&sysFSACCESS != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS - } - if mask&sysFSMODIFY != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE - } - if mask&sysFSATTRIB != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES - } - if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME - } - return m -} - -func toFSnotifyFlags(action uint32) uint64 { - switch action { - case syscall.FILE_ACTION_ADDED: - return sysFSCREATE - case syscall.FILE_ACTION_REMOVED: - return sysFSDELETE - case syscall.FILE_ACTION_MODIFIED: - return sysFSMODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - return sysFSMOVEDFROM - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - return sysFSMOVEDTO - } - return 0 -} diff --git a/examples/vendor/gopkg.in/yaml.v2/LICENSE b/examples/vendor/gopkg.in/yaml.v2/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/examples/vendor/gopkg.in/yaml.v2/LICENSE +++ /dev/null @@ -1,201 +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/go.mod b/go.mod index dcce03a..8d0ad19 100644 --- a/go.mod +++ b/go.mod @@ -2,44 +2,43 @@ module github.com/seoyhaein/podman-document go 1.18 -require github.com/containers/podman/v3 v3.4.7 +require ( + github.com/containers/common v0.48.0 + github.com/containers/podman/v4 v4.1.0 +) require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect - github.com/BurntSushi/toml v0.4.1 // indirect - github.com/Microsoft/go-winio v0.5.0 // indirect - github.com/Microsoft/hcsshim v0.8.22 // indirect + github.com/BurntSushi/toml v1.1.0 // indirect + github.com/Microsoft/go-winio v0.5.2 // indirect + github.com/Microsoft/hcsshim v0.9.2 // indirect github.com/VividCortex/ewma v1.2.0 // indirect github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver v3.5.1+incompatible // indirect - github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect - github.com/containerd/cgroups v1.0.1 // indirect - github.com/containerd/containerd v1.5.7 // indirect - github.com/containerd/stargz-snapshotter/estargz v0.9.0 // indirect - github.com/containernetworking/cni v0.8.1 // indirect - github.com/containernetworking/plugins v0.9.1 // indirect - github.com/containers/buildah v1.23.1 // indirect - github.com/containers/common v0.44.5 // indirect - github.com/containers/image/v5 v5.17.0 // indirect - github.com/containers/libtrust v0.0.0-20190913040956-14b96171aa3b // indirect - github.com/containers/ocicrypt v1.1.2 // indirect - github.com/containers/psgo v1.7.2-0.20220414132323-3ae304491648 // indirect - github.com/containers/storage v1.37.2 // indirect + github.com/containerd/cgroups v1.0.3 // indirect + github.com/containerd/containerd v1.6.4 // indirect + github.com/containerd/stargz-snapshotter/estargz v0.11.4 // indirect + github.com/containers/buildah v1.26.1 // indirect + github.com/containers/image/v5 v5.21.1 // indirect + github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a // indirect + github.com/containers/ocicrypt v1.1.4 // indirect + github.com/containers/psgo v1.7.2 // indirect + github.com/containers/storage v1.40.2 // indirect github.com/coreos/go-systemd/v22 v22.3.2 // indirect - github.com/cri-o/ocicni v0.2.1-0.20210621164014-d0acc7862283 // indirect github.com/cyphar/filepath-securejoin v0.2.3 // indirect github.com/disiqueira/gotree/v3 v3.0.2 // indirect - github.com/docker/distribution v2.7.1+incompatible // indirect - github.com/docker/docker v20.10.11+incompatible // indirect + github.com/docker/distribution v2.8.1+incompatible // indirect + github.com/docker/docker v20.10.14+incompatible // indirect github.com/docker/docker-credential-helpers v0.6.4 // indirect - github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-connections v0.4.1-0.20210727194412-58542c764a11 // indirect github.com/docker/go-metrics v0.0.1 // indirect github.com/docker/go-units v0.4.0 // indirect - github.com/fsnotify/fsnotify v1.5.1 // indirect + github.com/fsnotify/fsnotify v1.5.4 // indirect github.com/ghodss/yaml v1.0.0 // indirect - github.com/godbus/dbus/v5 v5.0.6 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect @@ -47,66 +46,62 @@ require ( github.com/google/uuid v1.3.0 // indirect github.com/gorilla/mux v1.8.0 // indirect github.com/gorilla/schema v1.2.0 // indirect - github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hpcloud/tail v1.0.0 // indirect github.com/imdario/mergo v0.3.12 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jinzhu/copier v0.3.2 // indirect + github.com/jinzhu/copier v0.3.5 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.13.6 // indirect + github.com/klauspost/compress v1.15.2 // indirect github.com/klauspost/pgzip v1.2.5 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/mattn/go-shellwords v1.0.12 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect - github.com/miekg/pkcs11 v1.0.3 // indirect + github.com/miekg/pkcs11 v1.1.1 // indirect github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible // indirect - github.com/moby/sys/mountinfo v0.4.1 // indirect + github.com/moby/sys/mountinfo v0.6.1 // indirect github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/mtrmac/gpgme v0.1.2 // indirect + github.com/nxadm/tail v1.4.8 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.0.2-0.20210819154149-5ad6f50d6283 // indirect - github.com/opencontainers/runc v1.0.2 // indirect - github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 // indirect - github.com/opencontainers/runtime-tools v0.9.0 // indirect - github.com/opencontainers/selinux v1.9.1 // indirect - github.com/ostreedev/ostree-go v0.0.0-20190702140239-759a8c1ac913 // indirect + github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 // indirect + github.com/opencontainers/runc v1.1.1 // indirect + github.com/opencontainers/runtime-spec v1.0.3-0.20211214071223-8958f93039ab // indirect + github.com/opencontainers/runtime-tools v0.9.1-0.20220110225228-7e2d60f1e41f // indirect + github.com/opencontainers/selinux v1.10.1 // indirect + github.com/ostreedev/ostree-go v0.0.0-20210805093236-719684c64e4f // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/proglottis/gpgme v0.1.1 // indirect github.com/prometheus/client_golang v1.11.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect - github.com/prometheus/common v0.26.0 // indirect - github.com/prometheus/procfs v0.6.0 // indirect + github.com/prometheus/common v0.30.0 // indirect + github.com/prometheus/procfs v0.7.3 // indirect github.com/rivo/uniseg v0.2.0 // indirect github.com/sirupsen/logrus v1.8.1 // indirect - github.com/spf13/cobra v1.2.1 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980 // indirect + github.com/sylabs/sif/v2 v2.7.0 // indirect github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 // indirect github.com/tchap/go-patricia v2.3.0+incompatible // indirect github.com/ulikunitz/xz v0.5.10 // indirect github.com/vbatts/tar-split v0.11.2 // indirect - github.com/vbauerster/mpb/v7 v7.1.5 // indirect - github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852 // indirect - github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae // indirect - github.com/xeipuuv/gojsonpointer v0.0.0-20190809123943-df4f5c81cb3b // indirect + github.com/vbauerster/mpb/v7 v7.4.1 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1 // indirect go.opencensus.io v0.23.0 // indirect golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect - golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect + golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect - golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 // indirect - golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect + golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect + golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect golang.org/x/text v0.3.7 // indirect - google.golang.org/genproto v0.0.0-20211005153810-c76a74d43a8e // indirect - google.golang.org/grpc v1.41.0 // indirect - google.golang.org/protobuf v1.27.1 // indirect - gopkg.in/fsnotify.v1 v1.4.7 // indirect + google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8 // indirect + google.golang.org/grpc v1.44.0 // indirect + google.golang.org/protobuf v1.28.0 // indirect gopkg.in/square/go-jose.v2 v2.5.1 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index 16d4cd4..9487119 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,7 @@ +4d63.com/gochecknoglobals v0.1.0/go.mod h1:wfdC5ZjKSPr7CybKEcgJhUOgeAQW1+7WcyK8OvUilfo= bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= +bazil.org/fuse v0.0.0-20200407214033-5883e5a4b512/go.mod h1:FbcW6z/2VytnFDhZfumh8Ss8zxHE6qpMP5sHTRe0EaM= +bitbucket.org/creachadair/shell v0.0.6/go.mod h1:8Qqi/cYk7vPnsOePHroKXDJYmb5x7ENhtiFtfZq8K+M= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= @@ -12,6 +15,7 @@ cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6 cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.60.0/go.mod h1:yw2G51M9IfRboUH61Us8GqCeF1PzPblB823Mn2q2eAU= cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= @@ -19,6 +23,11 @@ cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmW cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= @@ -28,36 +37,55 @@ cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM7 cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/firestore v1.6.0/go.mod h1:afJwI0vaXwAG54kI7A//lP/lSPDkQORQuMkv56TxEPU= cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/pubsub v1.5.0/go.mod h1:ZEwJccE3z93Z2HWvstpri00jOg7oO4UZDtKhwDwqF0w= +cloud.google.com/go/spanner v1.7.0/go.mod h1:sd3K2gZ9Fd0vMPLXzeCrF6fq4i63Q7aTLW/lBIfBkIk= cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +contrib.go.opencensus.io/exporter/stackdriver v0.13.4/go.mod h1:aXENhDJ1Y4lIg4EUaVTwzvYETVNZk10Pu26tevFKLUc= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/14rcole/gopopulate v0.0.0-20180821133914-b175b219e774 h1:SCbEWT58NSt7d2mcFdvxC9uyrdcTfvBbPLThhkDmXzg= github.com/14rcole/gopopulate v0.0.0-20180821133914-b175b219e774/go.mod h1:6/0dYRLLXyJjbkIPeeGyoJ/eKOSI0eU6eTlCBYibgd0= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20210715213245-6c3934b029d8/go.mod h1:CzsSbkDixRphAF5hS6wbMKq0eI6ccJRb7/A0M6JBnwg= +github.com/Antonboom/errname v0.1.5/go.mod h1:DugbBstvPFQbv/5uLcRRzfrNqKE9tVdVCqWCLp6Cifo= +github.com/Antonboom/nilnil v0.1.0/go.mod h1:PhHLvRPSghY5Y7mX4TW+BHZQYo1A8flE5H20D3IPZBo= github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= +github.com/Azure/go-ansiterm v0.0.0-20210608223527-2377c96fe795/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-autorest v10.8.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest/autorest v0.11.1/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= +github.com/Azure/go-autorest/autorest v0.11.18/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= +github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v0.4.1 h1:GaI7EiDXDRfa8VshkTj7Fym7ha+y8/XxIgD2okUIjLw= github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= +github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24/go.mod h1:4UJr5HIiMZrwgkSPdsjy2uOQExX/WEILpIrO9UPGuXs= +github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= @@ -66,8 +94,10 @@ github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugX github.com/Microsoft/go-winio v0.4.17-0.20210211115548-6eac466e5fa3/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= github.com/Microsoft/go-winio v0.4.17-0.20210324224401-5516f17a5958/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= github.com/Microsoft/go-winio v0.4.17/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= -github.com/Microsoft/go-winio v0.5.0 h1:Elr9Wn+sGKPlkaBvwu4mTrxtmOp3F3yV9qhaHbXGjwU= github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.5.1/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA= +github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= github.com/Microsoft/hcsshim v0.8.7-0.20190325164909-8abdbb8205e4/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= github.com/Microsoft/hcsshim v0.8.7/go.mod h1:OHd7sQqRFrYd3RmSgbgji+ctCwkbq2wbEYNSzOYtcBQ= @@ -75,18 +105,25 @@ github.com/Microsoft/hcsshim v0.8.9/go.mod h1:5692vkUqntj1idxauYlpoINNKeqCiG6Sg3 github.com/Microsoft/hcsshim v0.8.14/go.mod h1:NtVKoYxQuTLx6gEq0L96c9Ju4JbRJ4nY2ow3VK6a9Lg= github.com/Microsoft/hcsshim v0.8.15/go.mod h1:x38A4YbHbdxJtc0sF6oIz+RG0npwSCAvn69iY6URG00= github.com/Microsoft/hcsshim v0.8.16/go.mod h1:o5/SZqmR7x9JNKsW3pu+nqHm0MF8vbA+VxGOoXdC600= -github.com/Microsoft/hcsshim v0.8.18/go.mod h1:+w2gRZ5ReXQhFOrvSQeNfhrYB/dg3oDwTOcER2fw4I4= github.com/Microsoft/hcsshim v0.8.20/go.mod h1:+w2gRZ5ReXQhFOrvSQeNfhrYB/dg3oDwTOcER2fw4I4= github.com/Microsoft/hcsshim v0.8.21/go.mod h1:+w2gRZ5ReXQhFOrvSQeNfhrYB/dg3oDwTOcER2fw4I4= -github.com/Microsoft/hcsshim v0.8.22 h1:CulZ3GW8sNJExknToo+RWD+U+6ZM5kkNfuxywSDPd08= github.com/Microsoft/hcsshim v0.8.22/go.mod h1:91uVCVzvX2QD16sMCenoxxXo6L1wJnLMX2PSufFMtF0= +github.com/Microsoft/hcsshim v0.8.23/go.mod h1:4zegtUJth7lAvFyc6cH2gGQ5B3OFQim01nnU2M8jKDg= +github.com/Microsoft/hcsshim v0.9.2 h1:wB06W5aYFfUB3IvootYAY2WnOmIdgPGfqSI6tufQNnY= +github.com/Microsoft/hcsshim v0.9.2/go.mod h1:7pLA8lDk46WKDWlVsENo92gC0XFa8rbKfyFRBqxEbCc= github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU= github.com/Microsoft/hcsshim/test v0.0.0-20210227013316-43a75bb4edd3/go.mod h1:mw7qgWloBUl75W/gVH3cQszUg1+gUITj7D6NY7ywVnY= github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/OpenPeeDeeP/depguard v1.0.1/go.mod h1:xsIw86fROiiwelg+jB2uM9PiKihMMmUx/1V+TNhjQvM= +github.com/ProtonMail/go-crypto v0.0.0-20220407094043-a94812496cf5/go.mod h1:z4/9nQmJSSwwds7ejkxaJwO37dru3geImFUdJlaLzQo= +github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20160726150825-5bd2802263f2/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ= +github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= github.com/VividCortex/ewma v1.2.0 h1:f58SaIzcDXrSy3kWaHNvuJgJ3Nmz59Zji6XoJR/q1ow= github.com/VividCortex/ewma v1.2.0/go.mod h1:nz4BbCtbLyFDeC9SUHbtcT5644juEuWfUAUnGx7j5l4= github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8= @@ -97,13 +134,26 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= +github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= +github.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE= +github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y= +github.com/andybalholm/brotli v1.0.3/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= +github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/ashanbrown/forbidigo v1.2.0/go.mod h1:vVW7PEdqEFqapJe95xHkTfB1+XvZXBFg8t0sG2FIxmI= +github.com/ashanbrown/makezero v0.0.0-20210520155254-b6261585ddde/go.mod h1:oG9Dnez7/ESBqc4EdrdNlryeo7d0KcW1ftXHm7nU/UU= github.com/aws/aws-sdk-go v1.15.11/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= +github.com/aws/aws-sdk-go v1.23.20/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.25.37/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.36.30/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= +github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM= github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= @@ -114,25 +164,39 @@ github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngE github.com/bits-and-blooms/bitset v1.2.0/go.mod h1:gIdJ4wp64HaoK2YrL1Q5/N7Y16edYb8uY+O0FJTyyDA= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= +github.com/bkielbasa/cyclop v1.2.0/go.mod h1:qOI0yy6A7dYC4Zgsa72Ppm9kONl0RoIlPbzot9mhmeI= github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/blang/semver v3.5.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= +github.com/blizzy78/varnamelen v0.3.0/go.mod h1:hbwRdBvoBqxk34XyQ6HA0UH3G0/1TKuv5AC4eaBT0Ec= github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= +github.com/bombsimon/wsl/v3 v3.3.0/go.mod h1:st10JtZYLE4D5sC7b8xV4zTKZwAQjCH/Hy2Pm1FNZIc= +github.com/breml/bidichk v0.1.1/go.mod h1:zbfeitpevDUGI7V91Uzzuwrn4Vls8MoBMrwtt78jmso= github.com/bshuster-repo/logrus-logstash-hook v0.4.1/go.mod h1:zsTqEiSzDgAa/8GZR7E1qaXrhYNDKBYy5/dWPTIflbk= -github.com/buger/goterm v0.0.0-20181115115552-c206103e1f37/go.mod h1:u9UyCz2eTrSGy6fbupqJ54eY5c4IC8gREQ1053dK12U= +github.com/buger/goterm v1.0.4/go.mod h1:HiFWV3xnkolgrBV3mY8m0X0Pumt4zg4QhbdOzQtB8tE= github.com/buger/jsonparser v0.0.0-20180808090653-f4dd9f5a6b44/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= +github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd/go.mod h1:2oa8nejYd4cQ/b0hMIopN0lCRxU0bueqREvZLWFrtK8= github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0BsqsP2LwDJ9aOkm/6J86V6lyAXCoQWGw3K50= github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= +github.com/butuzov/ireturn v0.1.1/go.mod h1:Wh6Zl3IMtTpaIKbmwzqi6olnM9ptYQxxVacMsOEFPoc= +github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/cenkalti/backoff/v4 v4.1.2/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/certifi/gocertifi v0.0.0-20191021191039-0944d244cd40/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA= +github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= -github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/checkpoint-restore/checkpointctl v0.0.0-20210301084134-a2024f5584e7/go.mod h1:Kp3ezoDVdhfYxZUtgs4OL8sVvgOLz3txk0sbQD0opvw= -github.com/checkpoint-restore/go-criu/v4 v4.0.2/go.mod h1:xUQBLp4RLc5zJtWY++yjOoMoB5lihDt7fai+75m+rGw= +github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= +github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charithe/durationcheck v0.0.9/go.mod h1:SSbRIBVfMjCi/kEB6K65XEA83D6prSM8ap1UCpNKtgg= +github.com/chavacava/garif v0.0.0-20210405164556-e8a0a408d6af/go.mod h1:Qjyv4H3//PWVzTeCezG2b9IRn6myJxJSr4TD/xo6ojU= +github.com/checkpoint-restore/checkpointctl v0.0.0-20220321135231-33f4a66335f0/go.mod h1:67kWC1PXQLR3lM/mmNnu3Kzn7K4TSWZAGUuQP1JSngk= github.com/checkpoint-restore/go-criu/v4 v4.1.0/go.mod h1:xUQBLp4RLc5zJtWY++yjOoMoB5lihDt7fai+75m+rGw= github.com/checkpoint-restore/go-criu/v5 v5.0.0/go.mod h1:cfwC0EG7HMUenopBsUf9d89JlCLQIfgVcNsNN0t6T2M= -github.com/checkpoint-restore/go-criu/v5 v5.1.0/go.mod h1:iaS8bb7p6zKJanp1Qe8mpl7+bnkYBR500psJR6mwma0= +github.com/checkpoint-restore/go-criu/v5 v5.2.0/go.mod h1:E/eQpaFtUKGOOSEBZgmKAcn+zUUwWxqcaKZlF54wK8E= +github.com/checkpoint-restore/go-criu/v5 v5.3.0/go.mod h1:E/eQpaFtUKGOOSEBZgmKAcn+zUUwWxqcaKZlF54wK8E= github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e h1:fY5BOSpyZCqRo5OhCuC+XN+r/bBCmeuuJtjz+bCNIf8= @@ -140,19 +204,25 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3/go.mod h1:MA5e5Lr8slmEg9bt0VpxxWqJlO4iwu3FBdHUzV7wQVg= -github.com/cilium/ebpf v0.0.0-20200507155900-a9f01edf17e3/go.mod h1:XT+cAw5wfvsodedcijoh1l9cf7v1x9FlFB/3VmF/O8s= github.com/cilium/ebpf v0.0.0-20200702112145-1c8d4c9ef775/go.mod h1:7cR51M8ViRLIdUjrmSXlK9pkrsDlLHbO8jiB8X8JnOc= github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX2Qs= github.com/cilium/ebpf v0.4.0/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= github.com/cilium/ebpf v0.6.2/go.mod h1:4tRaxcgiL706VnOzHOdBlY8IEAIdxINsQBcU4xJJXRs= +github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/container-orchestrated-devices/container-device-interface v0.0.0-20210325223243-f99e8b6c10b9/go.mod h1:eQt66kIaJpUhCrjCtBFQGQxGLbAUl0OuuwjTH16ON4s= +github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5/go.mod h1:h6jFvWxBdQXxjopDMZyH2UVceIRfR84bdzbkoKrsWNo= +github.com/cockroachdb/errors v1.2.4/go.mod h1:rQD95gz6FARkaKkQXUksEje/d9a6wBJoCr5oaCLELYA= +github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= +github.com/container-orchestrated-devices/container-device-interface v0.4.0/go.mod h1:E1zcucIkq9P3eyNmY+68dBQsTcsXJh9cgRo2IVNScKQ= github.com/containerd/aufs v0.0.0-20200908144142-dab0cbea06f4/go.mod h1:nukgQABAEopAHvB6j7cnP5zJ+/3aVcE7hCYqvIwAHyE= github.com/containerd/aufs v0.0.0-20201003224125-76a6863f2989/go.mod h1:AkGGQs9NM2vtYHaUen+NljV0/baGCAPELGm2q9ZXpWU= github.com/containerd/aufs v0.0.0-20210316121734-20793ff83c97/go.mod h1:kL5kd6KM5TzQjR79jljyi4olc1Vrx6XBlcyj3gNv2PU= @@ -166,14 +236,15 @@ github.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1 github.com/containerd/cgroups v0.0.0-20200710171044-318312a37340/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= github.com/containerd/cgroups v0.0.0-20210114181951-8a68de567b68/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE= -github.com/containerd/cgroups v1.0.1 h1:iJnMvco9XGvKUvNQkv88bE4uJXxRQH18efbKo9w5vHQ= github.com/containerd/cgroups v1.0.1/go.mod h1:0SJrPIenamHDcZhEcJMNBB85rHcUsw4f25ZfBiPYRkU= +github.com/containerd/cgroups v1.0.3 h1:ADZftAkglvCiD44c77s5YmMqaP2pzVCFZvBmAlBdAP4= +github.com/containerd/cgroups v1.0.3/go.mod h1:/ofk34relqNjSGyqPrmEULrO4Sc8LJhvJmWbUCUKqj8= github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= github.com/containerd/console v0.0.0-20181022165439-0650fd9eeb50/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= github.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE= -github.com/containerd/console v1.0.0/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE= github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw= github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ= +github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/containerd/containerd v1.2.10/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= github.com/containerd/containerd v1.3.0/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= @@ -188,9 +259,13 @@ github.com/containerd/containerd v1.5.0-beta.3/go.mod h1:/wr9AVtEM7x9c+n0+stptlo github.com/containerd/containerd v1.5.0-beta.4/go.mod h1:GmdgZd2zA2GYIBZ0w09ZvgqEq8EfBp/m3lcVZIvPHhI= github.com/containerd/containerd v1.5.0-rc.0/go.mod h1:V/IXoMqNGgBlabz3tHD2TWDoTJseu1FGOKuoA4nNb2s= github.com/containerd/containerd v1.5.1/go.mod h1:0DOxVqwDy2iZvrZp2JUx/E+hS0UNTVn7dJnIOwtYR4g= -github.com/containerd/containerd v1.5.5/go.mod h1:oSTh0QpT1w6jYcGmbiSbxv9OSQYaa88mPyWIuU79zyo= -github.com/containerd/containerd v1.5.7 h1:rQyoYtj4KddB3bxG6SAqd4+08gePNyJjRqvOIfV3rkM= github.com/containerd/containerd v1.5.7/go.mod h1:gyvv6+ugqY25TiXxcZC3L5yOeYgEw0QMhscqVp1AR9c= +github.com/containerd/containerd v1.5.8/go.mod h1:YdFSv5bTFLpG2HIYmfqDpSYYTDX+mc5qtSuYx1YUb/s= +github.com/containerd/containerd v1.5.9/go.mod h1:fvQqCfadDGga5HZyn3j4+dx56qj2I9YwBrlSdalvJYQ= +github.com/containerd/containerd v1.6.1/go.mod h1:1nJz5xCZPusx6jJU8Frfct988y0NpumIq9ODB0kLtoE= +github.com/containerd/containerd v1.6.3/go.mod h1:gCVGrYRYFm2E8GmuUIbj/NGD7DLZQLzSJQazjVKDOig= +github.com/containerd/containerd v1.6.4 h1:SEDZBp10mhCp+hkO3Njz/YhGrI7ah3edNcUlRdUPOgg= +github.com/containerd/containerd v1.6.4/go.mod h1:oWOqbuJUZmOVafhA0lj2NAXbiO1u7F0K5l1bUgdyo94= github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= github.com/containerd/continuity v0.0.0-20190815185530-f2a389ac0a02/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= github.com/containerd/continuity v0.0.0-20191127005431-f65d91d395eb/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= @@ -198,6 +273,7 @@ github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe/go.mod h1:cE github.com/containerd/continuity v0.0.0-20201208142359-180525291bb7/go.mod h1:kR3BEg7bDFaEddKm54WSmrol1fKWDU1nKYkgrcgZT7Y= github.com/containerd/continuity v0.0.0-20210208174643-50096c924a4e/go.mod h1:EXlVlkqNba9rJe3j7w3Xa924itAMLgZH4UD/Q4PExuQ= github.com/containerd/continuity v0.1.0/go.mod h1:ICJu0PwR54nI0yPEnJ6jcS+J7CZAUXrLh8lPo2knzsM= +github.com/containerd/continuity v0.2.2/go.mod h1:pWygW9u7LtS1o4N/Tn0FoCFDIXZ7rxcMX7HX1Dmibvk= github.com/containerd/fifo v0.0.0-20180307165137-3d5202aec260/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= github.com/containerd/fifo v0.0.0-20200410184934-f15a3290365b/go.mod h1:jPQ2IAeZRCYxpS/Cm1495vGFww6ecHmMk1YJH2Q5ln0= @@ -206,6 +282,10 @@ github.com/containerd/fifo v0.0.0-20210316144830-115abcc95a1d/go.mod h1:ocF/ME1S github.com/containerd/fifo v1.0.0/go.mod h1:ocF/ME1SX5b1AOlWi9r677YJmCPSwwWnQ9O123vzpE4= github.com/containerd/go-cni v1.0.1/go.mod h1:+vUpYxKvAF72G9i1WoDOiPGRtQpqsNW/ZHtSlv++smU= github.com/containerd/go-cni v1.0.2/go.mod h1:nrNABBHzu0ZwCug9Ije8hL2xBCYh/pjfMb1aZGrrohk= +github.com/containerd/go-cni v1.1.0/go.mod h1:Rflh2EJ/++BA2/vY5ao3K6WJRR/bZKsX123aPk+kUtA= +github.com/containerd/go-cni v1.1.3/go.mod h1:Rflh2EJ/++BA2/vY5ao3K6WJRR/bZKsX123aPk+kUtA= +github.com/containerd/go-cni v1.1.4/go.mod h1:Rflh2EJ/++BA2/vY5ao3K6WJRR/bZKsX123aPk+kUtA= +github.com/containerd/go-cni v1.1.5/go.mod h1:Rf2ZrMycr1El589IyuRzn7RkfdRZVKaFGaxSDHVAjj0= github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= github.com/containerd/go-runc v0.0.0-20190911050354-e029b79d8cda/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= github.com/containerd/go-runc v0.0.0-20200220073739-7016d3ce2328/go.mod h1:PpyHrqVs8FTi9vpyHwPwiNEGaACDxT/N/pLcvMSRA9g= @@ -215,17 +295,22 @@ github.com/containerd/imgcrypt v1.0.1/go.mod h1:mdd8cEPW7TPgNG4FpuP3sGBiQ7Yi/zak github.com/containerd/imgcrypt v1.0.4-0.20210301171431-0ae5c75f59ba/go.mod h1:6TNsg0ctmizkrOgXRNQjAPFWpMYRWuiB6dSF4Pfa5SA= github.com/containerd/imgcrypt v1.1.1-0.20210312161619-7ed62a527887/go.mod h1:5AZJNI6sLHJljKuI9IHnw1pWqo/F0nGDOuR9zgTs7ow= github.com/containerd/imgcrypt v1.1.1/go.mod h1:xpLnwiQmEUJPvQoAapeb2SNCxz7Xr6PJrXQb0Dpc4ms= +github.com/containerd/imgcrypt v1.1.3/go.mod h1:/TPA1GIDXMzbj01yd8pIbQiLdQxed5ue1wb8bP7PQu4= +github.com/containerd/imgcrypt v1.1.4/go.mod h1:LorQnPtzL/T0IyCeftcsMEO7AqxUDbdO8j/tSUpgxvo= github.com/containerd/nri v0.0.0-20201007170849-eb1350a75164/go.mod h1:+2wGSDGFYfE5+So4M5syatU0N0f0LbWpuqyMi4/BE8c= github.com/containerd/nri v0.0.0-20210316161719-dbaa18c31c14/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= github.com/containerd/nri v0.1.0/go.mod h1:lmxnXF6oMkbqs39FiCt1s0R2HSMhcLel9vNL3m4AaeY= -github.com/containerd/stargz-snapshotter/estargz v0.8.0/go.mod h1:mwIwuwb+D8FX2t45Trwi0hmWmZm5VW7zPP/rekwhWQU= -github.com/containerd/stargz-snapshotter/estargz v0.9.0 h1:PkB6BSTfOKX23erT2GkoUKkJEcXfNcyKskIViK770v8= +github.com/containerd/stargz-snapshotter/estargz v0.4.1/go.mod h1:x7Q9dg9QYb4+ELgxmo4gBUeJB0tl5dqH1Sdz0nJU1QM= github.com/containerd/stargz-snapshotter/estargz v0.9.0/go.mod h1:aE5PCyhFMwR8sbrErO5eM2GcvkyXTTJremG883D4qF0= +github.com/containerd/stargz-snapshotter/estargz v0.10.1/go.mod h1:aE5PCyhFMwR8sbrErO5eM2GcvkyXTTJremG883D4qF0= +github.com/containerd/stargz-snapshotter/estargz v0.11.4 h1:LjrYUZpyOhiSaU7hHrdR82/RBoxfGWSaC0VeSSMXqnk= +github.com/containerd/stargz-snapshotter/estargz v0.11.4/go.mod h1:7vRJIcImfY8bpifnMjt+HTJoQxASq7T28MYbP15/Nf0= github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= github.com/containerd/ttrpc v0.0.0-20190828172938-92c8520ef9f8/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= github.com/containerd/ttrpc v0.0.0-20191028202541-4f1b8fe65a5c/go.mod h1:LPm1u0xBw8r8NOKoOdNMeVHSawSsltak+Ihv+etqsE8= github.com/containerd/ttrpc v1.0.1/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= github.com/containerd/ttrpc v1.0.2/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= +github.com/containerd/ttrpc v1.1.0/go.mod h1:XX4ZTnoOId4HklF4edwc4DcqskFZuvXB1Evzy5KFQpQ= github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= github.com/containerd/typeurl v0.0.0-20190911142611-5eb25027c9fd/go.mod h1:GeKYzf2pQcqv7tJ0AoCuuhtnqhva5LNU3U+OyKxxJpk= github.com/containerd/typeurl v1.0.1/go.mod h1:TB1hUtrpaiO88KEK56ijojHS1+NeF0izUACaJW2mdXg= @@ -237,49 +322,53 @@ github.com/containerd/zfs v0.0.0-20210324211415-d5c4544f0433/go.mod h1:m+m51S1Dv github.com/containerd/zfs v1.0.0/go.mod h1:m+m51S1DvAP6r3FcmYCp54bQ34pyOwTieQDNRIRHsFY= github.com/containernetworking/cni v0.7.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= github.com/containernetworking/cni v0.8.0/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= -github.com/containernetworking/cni v0.8.1 h1:7zpDnQ3T3s4ucOuJ/ZCLrYBxzkg0AELFfII3Epo9TmI= github.com/containernetworking/cni v0.8.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= +github.com/containernetworking/cni v1.0.1/go.mod h1:AKuhXbN5EzmD4yTNtfSsX3tPcmtrBI6QcRV0NiNt15Y= +github.com/containernetworking/cni v1.1.0/go.mod h1:sDpYKmGVENF3s6uvMvGgldDWeG8dMxakj/u+i9ht9vw= github.com/containernetworking/plugins v0.8.6/go.mod h1:qnw5mN19D8fIwkqW7oHHYDHVlzhJpcY6TQxn/fUyDDM= -github.com/containernetworking/plugins v0.8.7/go.mod h1:R7lXeZaBzpfqapcAbHRW8/CYwm0dHzbz0XEjofx0uB0= -github.com/containernetworking/plugins v0.9.1 h1:FD1tADPls2EEi3flPc2OegIY1M9pUa9r2Quag7HMLV8= github.com/containernetworking/plugins v0.9.1/go.mod h1:xP/idU2ldlzN6m4p5LmGiwRDjeJr6FLK6vuiUwoH7P8= -github.com/containers/buildah v1.23.1 h1:Tpc9DsRuU+0Oofewpxb6OJVNQjCu7yloN/obUqzfDTY= -github.com/containers/buildah v1.23.1/go.mod h1:4WnrN0yrA7ab0ppgunixu2WM1rlD2rG8QLJAKbEkZlQ= -github.com/containers/common v0.44.2/go.mod h1:7sdP4vmI5Bm6FPFxb3lvAh1Iktb6tiO1MzjUzhxdoGo= -github.com/containers/common v0.44.5 h1:YqCqDLN4wPW5ZDnzWhmCBX2PoCnuzEUU8fzS+lI8lLo= -github.com/containers/common v0.44.5/go.mod h1:7sdP4vmI5Bm6FPFxb3lvAh1Iktb6tiO1MzjUzhxdoGo= +github.com/containernetworking/plugins v1.0.1/go.mod h1:QHCfGpaTwYTbbH+nZXKVTxNBDZcxSOplJT5ico8/FLE= +github.com/containernetworking/plugins v1.1.1/go.mod h1:Sr5TH/eBsGLXK/h71HeLfX19sZPp3ry5uHSkI4LPxV8= +github.com/containers/buildah v1.26.1 h1:D65Vuo+orsI14WWtJhSX6KrpgBBa7+hveVWevzG8p8E= +github.com/containers/buildah v1.26.1/go.mod h1:CsWSG8OpJd8v3mlLREJzVAOBgC93DjRNALUVHoi8QsY= +github.com/containers/common v0.48.0 h1:997nnXBZ+eNpfSM7L4SxhhZubQrfEyw3jRyNMTSsNlw= +github.com/containers/common v0.48.0/go.mod h1:zPLZCfLXfnd1jI0QRsD4By54fP4k1+ifQs+tulIe3o0= github.com/containers/conmon v2.0.20+incompatible/go.mod h1:hgwZ2mtuDrppv78a/cOBNiCm6O0UMWGx1mu7P00nu5I= -github.com/containers/image/v5 v5.16.0/go.mod h1:XgTpfAPLRGOd1XYyCU5cISFr777bLmOerCSpt/v7+Q4= -github.com/containers/image/v5 v5.17.0 h1:KS5pro80CCsSp5qDBTMmSAWQo+xcBX19zUPExmYX2OQ= -github.com/containers/image/v5 v5.17.0/go.mod h1:GnYVusVRFPMMTAAUkrcS8NNSpBp8oyrjOUe04AAmRr4= -github.com/containers/libtrust v0.0.0-20190913040956-14b96171aa3b h1:Q8ePgVfHDplZ7U33NwHZkrVELsZP5fYj9pM5WBZB2GE= -github.com/containers/libtrust v0.0.0-20190913040956-14b96171aa3b/go.mod h1:9rfv8iPl1ZP7aqh9YA68wnZv2NUDbXdcdPHVz0pFbPY= +github.com/containers/image/v5 v5.21.1 h1:Cr3zw2f0FZs4SCkdGlc8SN/mpcmg2AKG4OUuDbeGS/Q= +github.com/containers/image/v5 v5.21.1/go.mod h1:zl35egpcDQa79IEXIuoUe1bW+D1pdxRxYjNlyb3YiXw= +github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a h1:spAGlqziZjCJL25C6F1zsQY05tfCKE9F5YwtEWWe6hU= +github.com/containers/libtrust v0.0.0-20200511145503-9c3a6c22cd9a/go.mod h1:9rfv8iPl1ZP7aqh9YA68wnZv2NUDbXdcdPHVz0pFbPY= github.com/containers/ocicrypt v1.0.1/go.mod h1:MeJDzk1RJHv89LjsH0Sp5KTY3ZYkjXO/C+bKAeWFIrc= github.com/containers/ocicrypt v1.1.0/go.mod h1:b8AOe0YR67uU8OqfVNcznfFpAzu3rdgUV4GP9qXPfu4= github.com/containers/ocicrypt v1.1.1/go.mod h1:Dm55fwWm1YZAjYRaJ94z2mfZikIyIN4B0oB3dj3jFxY= -github.com/containers/ocicrypt v1.1.2 h1:Ez+GAMP/4GLix5Ywo/fL7O0nY771gsBIigiqUm1aXz0= github.com/containers/ocicrypt v1.1.2/go.mod h1:Dm55fwWm1YZAjYRaJ94z2mfZikIyIN4B0oB3dj3jFxY= -github.com/containers/podman/v3 v3.4.7 h1:yFEoPcVkCLfWKmKN0AQoRDXMq5hf4TfwNLamKd6a53M= -github.com/containers/podman/v3 v3.4.7/go.mod h1:W5bxaoM0UkYC31zd/R895iqOmHYg48jQsplnH6puqcg= -github.com/containers/psgo v1.7.2-0.20220414132323-3ae304491648 h1:nncdLuajRBSN9Yo5BaHU6NTFJR+Zq5CNVCpU6rH/FPs= -github.com/containers/psgo v1.7.2-0.20220414132323-3ae304491648/go.mod h1:5BZZWHXOqzLm/It+0DhfJcU7uZmepVRsO7uAs/lCxdo= -github.com/containers/storage v1.23.5/go.mod h1:ha26Q6ngehFNhf3AWoXldvAvwI4jFe3ETQAf/CeZPyM= -github.com/containers/storage v1.35.0/go.mod h1:qzYhasQP2/V9D9XdO+vRwkHBhsBO0oznMLzzRDQ8s20= -github.com/containers/storage v1.36.0/go.mod h1:vbd3SKVQNHdmU5qQI6hTEcKPxnZkGqydG4f6uwrI5a8= +github.com/containers/ocicrypt v1.1.3/go.mod h1:xpdkbVAuaH3WzbEabUd5yDsl9SwJA5pABH85425Es2g= +github.com/containers/ocicrypt v1.1.4-0.20220428134531-566b808bdf6f/go.mod h1:xpdkbVAuaH3WzbEabUd5yDsl9SwJA5pABH85425Es2g= +github.com/containers/ocicrypt v1.1.4 h1:V0ktirShnF1iJ2ithuoYE4eNAOSL3af1PlTiykv3PLQ= +github.com/containers/ocicrypt v1.1.4/go.mod h1:xpdkbVAuaH3WzbEabUd5yDsl9SwJA5pABH85425Es2g= +github.com/containers/podman/v4 v4.1.0 h1:3fo/4U2fjdeKB86RpyJDqyglg5G6TkDuAU9jECv8Z9A= +github.com/containers/podman/v4 v4.1.0/go.mod h1:ZgZCaL1EAnRXPbCUVQ3P24UZ+uGAGUTXLysvEBwpmkY= +github.com/containers/psgo v1.7.2 h1:WbCvsY9w+nCv3j4der0mbD3PSRUv/W8l+G0YrZrdSDc= +github.com/containers/psgo v1.7.2/go.mod h1:SLpqxsPOHtTqRygjutCPXmeU2PoEFzV3gzJplN4BMx0= github.com/containers/storage v1.37.0/go.mod h1:kqeJeS0b7DO2ZT1nVWs0XufrmPFbgV3c+Q/45RlH6r4= -github.com/containers/storage v1.37.2 h1:sHLL9LEZA/PvFAeCQ9lOxJohL5t5PqYCa5eTZMpZVO4= -github.com/containers/storage v1.37.2/go.mod h1:kqeJeS0b7DO2ZT1nVWs0XufrmPFbgV3c+Q/45RlH6r4= +github.com/containers/storage v1.38.0/go.mod h1:lBzt28gAk5ADZuRtwdndRJyqX22vnRaXmlF+7ktfMYc= +github.com/containers/storage v1.40.0/go.mod h1:zUyPC3CFIGR1OhY1CKkffxgw9+LuH76PGvVcFj38dgs= +github.com/containers/storage v1.40.2 h1:GUlHaGnrs1JOEwv6YEvkQdgYXOXZdU1Angy4wgWNgF8= +github.com/containers/storage v1.40.2/go.mod h1:zUyPC3CFIGR1OhY1CKkffxgw9+LuH76PGvVcFj38dgs= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-iptables v0.4.5/go.mod h1:/mVI274lEDI2ns62jHCDnCyBF9Iwsmekav8Dbxlm1MU= github.com/coreos/go-iptables v0.5.0/go.mod h1:/mVI274lEDI2ns62jHCDnCyBF9Iwsmekav8Dbxlm1MU= +github.com/coreos/go-iptables v0.6.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q= github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20161114122254-48702e0da86b/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190620071333-e64a0ec8b42a/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.0.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= github.com/coreos/go-systemd/v22 v22.1.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI= @@ -287,14 +376,14 @@ github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/coreos/stream-metadata-go v0.0.0-20210225230131-70edb9eb47b3/go.mod h1:RTjQyHgO/G37oJ3qnqYK6Z4TPZ5EsaabOtfMjVXmgko= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= +github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cri-o/ocicni v0.2.1-0.20210621164014-d0acc7862283 h1:7FyIYKksGvRF8XjMkG5T6uIxg8PcgZoPyO+f6kHT5+s= -github.com/cri-o/ocicni v0.2.1-0.20210621164014-d0acc7862283/go.mod h1:vingr1ztOAzP2WyTgGbpMov9dFhbjNxdLtDv0+PhAvY= github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= github.com/cyphar/filepath-securejoin v0.2.3 h1:YX6ebbZCZP7VkM3scTTokDgBL2TY741X51MTk3ycuNI= github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= @@ -302,36 +391,45 @@ github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c/go.mod h1:Ct2BUK8SB0YC1S github.com/d2g/dhcp4client v1.0.0/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW34z5W5s= github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/IX2hfWJfwxMzLyuSZyxSoAug2nGa1G2QAi8= github.com/d2g/hardwareaddr v0.0.0-20190221164911-e7d9fbe030e4/go.mod h1:bMl4RjIciD2oAxI7DmWRx6gbeqrkoLqv3MV0vzNad+I= +github.com/daixiang0/gci v0.2.9/go.mod h1:+4dZ7TISfSmqfAGv59ePaHfNzgGtIkHAhhdKggP1JAc= github.com/danieljoos/wincred v1.1.0/go.mod h1:XYlo+eRTsVA9aHGp7NGjFkPla4m+DCL7hqDjlFjiygg= +github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denis-tingajkin/go-header v0.4.2/go.mod h1:eLRHAVXzE5atsKAnNRDB90WHCFFnBUn4RN0nRcs1LJA= github.com/denverdino/aliyungo v0.0.0-20190125010748-a747050bb1ba/go.mod h1:dV8lFg6daOBZbT6/BDGIz6Y3WFGn8juu6G+CQ6LHtl0= github.com/dgrijalva/jwt-go v0.0.0-20170104182250-a601269ab70c/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/digitalocean/go-libvirt v0.0.0-20201209184759-e2a69bcd5bd1/go.mod h1:QS1XzqZLcDniNYrN7EZefq3wIyb/M2WmJbql4ZKoc1Q= -github.com/digitalocean/go-qemu v0.0.0-20210209191958-152a1535e49f/go.mod h1:IetBE52JfFxK46p2n2Rqm+p5Gx1gpu2hRHsrbnPOWZQ= +github.com/digitalocean/go-qemu v0.0.0-20210326154740-ac9e0b687001/go.mod h1:IetBE52JfFxK46p2n2Rqm+p5Gx1gpu2hRHsrbnPOWZQ= github.com/disiqueira/gotree/v3 v3.0.2 h1:ik5iuLQQoufZBNPY518dXhiO5056hyNBIK9lWhkNRq8= github.com/disiqueira/gotree/v3 v3.0.2/go.mod h1:ZuyjE4+mUQZlbpkI24AmruZKhg3VHEgPLDY8Qk+uUu8= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/docker/cli v0.0.0-20191017083524-a8ff7f821017/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug= github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v20.10.8+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/docker v20.10.11+incompatible h1:OqzI/g/W54LczvhnccGqniFoQghHx3pklbLuhfXpqGo= -github.com/docker/docker v20.10.11+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= +github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v1.4.2-0.20190924003213-a8608b5b67c7/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v20.10.3-0.20220208084023-a5c757555091+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v20.10.12+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker v20.10.14+incompatible h1:+T9/PRYWNDo5SZl5qS1r9Mo/0Q8AwxKKPtu9S1yxM0w= +github.com/docker/docker v20.10.14+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker-credential-helpers v0.6.3/go.mod h1:WRaJzqw3CTB9bk10avuGsjVBZsD05qeibJ1/TYlvc0Y= github.com/docker/docker-credential-helpers v0.6.4 h1:axCks+yV+2MR3/kZhAmy07yC56WZ2Pwu/fKWtKuZB0o= github.com/docker/docker-credential-helpers v0.6.4/go.mod h1:ofX3UI0Gz1TteYBjtgs07O36Pyasyp66D2uKT7H8W1c= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-connections v0.4.1-0.20210727194412-58542c764a11 h1:IPrmumsT9t5BS7XcPhgsCTlkWbYg80SEXUzDpReaU6Y= +github.com/docker/go-connections v0.4.1-0.20210727194412-58542c764a11/go.mod h1:a6bNUGTbQBsY6VRHTr4h/rkOXjl244DyRD0tx3fgq4Q= github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= github.com/docker/go-metrics v0.0.0-20180209012529-399ea8c73916/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI= github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= -github.com/docker/go-plugins-helpers v0.0.0-20200102110956-c9a8a2d92ccc/go.mod h1:LFyLie6XcDbyKGeVK6bHe+9aJTYCxWLBg5IrJZOaXKA= +github.com/docker/go-plugins-helpers v0.0.0-20211224144127-6eecb7beb651/go.mod h1:LFyLie6XcDbyKGeVK6bHe+9aJTYCxWLBg5IrJZOaXKA= github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/libnetwork v0.8.0-dev.2.0.20190625141545-5a177b73e316/go.mod h1:93m0aTqz6z+g32wla4l4WxTrdtvBRmVzYRkYvasA5Z8= @@ -354,24 +452,39 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/protoc-gen-validate v0.0.14/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/esimonov/ifshort v1.0.3/go.mod h1:yZqNJUrNn20K8Q9n2CrjTKYyVEmX209Hgu+M1LBpeZE= +github.com/ettle/strcase v0.1.1/go.mod h1:hzDLsPC7/lwKyBOywSHEP89nt2pDgdy+No1NBA9o9VY= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.11.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/fanliao/go-promise v0.0.0-20141029170127-1890db352a72/go.mod h1:PjfxuH4FZdUyfMdtBio2lsRr1AKEaVPwelzuHuh8Lqc= github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= +github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= +github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= -github.com/fsouza/go-dockerclient v1.7.4/go.mod h1:het+LPt7NaTEVGgwXJAKxPn77RZrQKb2EXJb4e+BHv0= +github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= +github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/fsouza/go-dockerclient v1.7.7/go.mod h1:njNCXvoZj3sLPjf3yO0DPHf1mdLdCPDYPc14GskKA4Y= +github.com/fsouza/go-dockerclient v1.7.11/go.mod h1:zvYxutUNOK853i1s7VywZxQgxSHbm7A6en/q9MHBN6k= github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= +github.com/fullstorydev/grpcurl v1.6.0/go.mod h1:ZQ+ayqbKMJNhzLmbpCiurTVlaK2M/3nqZCxaQ2Ze/sM= +github.com/fzipp/gocyclo v0.3.1/go.mod h1:DJHO6AUmbdqj2ET4Z9iArSuwWgYDRryYt2wASxc7x3E= github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= +github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-critic/go-critic v0.6.1/go.mod h1:SdNCfU0yF3UBjtaZGw6586/WocupMOJuiqgom5DsQxM= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= @@ -385,22 +498,53 @@ github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.4.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= +github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.1/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/stdr v1.2.0/go.mod h1:YkVgnZu1ZjjL7xTxrfm/LLZBfkhTqSR1ydtm6jTKKwI= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0= github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg= github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= +github.com/go-openapi/jsonreference v0.19.5/go.mod h1:RdybgQwPxbL4UEjuAruzK1x3nE69AqPYEJeo/TWfEeg= +github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc= github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= +github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dpr1UfpPtxFw+EFuQ41HhCWZfha5jSVRG7C7I= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-redis/redis v6.15.8+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/go-toolsmith/astcast v1.0.0/go.mod h1:mt2OdQTeAQcY4DQgPSArJjHCcOwlX+Wl/kwN+LbLGQ4= +github.com/go-toolsmith/astcopy v1.0.0/go.mod h1:vrgyG+5Bxrnz4MZWPF+pI4R8h3qKRjjyvV/DSez4WVQ= +github.com/go-toolsmith/astequal v1.0.0/go.mod h1:H+xSiq0+LtiDC11+h1G32h7Of5O3CYFJ99GVbS5lDKY= +github.com/go-toolsmith/astequal v1.0.1/go.mod h1:4oGA3EZXTVItV/ipGiOx7NWkY5veFfcsOJVS2YxltLw= +github.com/go-toolsmith/astfmt v1.0.0/go.mod h1:cnWmsOAuq4jJY6Ct5YWlVLmcmLMn1JUPuQIHCY7CJDw= +github.com/go-toolsmith/astinfo v0.0.0-20180906194353-9809ff7efb21/go.mod h1:dDStQCHtmZpYOmjRP/8gHHnCCch3Zz3oEgCdZVdtweU= +github.com/go-toolsmith/astp v1.0.0/go.mod h1:RSyrtpVlfTFGDYRbrjyWP1pYu//tSFcvdYrA8meBmLI= +github.com/go-toolsmith/pkgload v1.0.0/go.mod h1:5eFArkbO80v7Z0kdngIxsRXRMTaX4Ilcwuh3clNrQJc= +github.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8= +github.com/go-toolsmith/typep v1.0.0/go.mod h1:JSQCQMUPdRlMZFswiq3TGpNp1GMktqkR2Ns5AIQkATU= +github.com/go-toolsmith/typep v1.0.2/go.mod h1:JSQCQMUPdRlMZFswiq3TGpNp1GMktqkR2Ns5AIQkATU= +github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM= +github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= github.com/godbus/dbus v0.0.0-20151105175453-c7fdd8b5cd55/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/godbus/dbus/v5 v5.0.6 h1:mkgN1ofwASrYnJ5W6U/BxG15eXXXjirgZc7CLqkcaro= github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= github.com/gogo/googleapis v1.4.0/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c= @@ -427,6 +571,8 @@ github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -446,8 +592,21 @@ github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2/go.mod h1:k9Qvh+8juN+UKMCS/3jFtGICgW8O96FVaZsaxdzDkR4= +github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a/go.mod h1:ryS0uhF+x9jgbj/N71xsEqODy9BN81/GonCZiOzirOk= +github.com/golangci/go-misc v0.0.0-20180628070357-927a3d87b613/go.mod h1:SyvUF2NxV+sN8upjjeVYr5W7tyxaT1JVtvhKhOn2ii8= +github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= +github.com/golangci/golangci-lint v1.43.0/go.mod h1:VIFlUqidx5ggxDfQagdvd9E67UjMXtTHBkBQ7sHoC5Q= +github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0/go.mod h1:66R6K6P6VWk9I95jvqGxkqJxVWGFy9XlDwLwVz1RCFg= +github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca/go.mod h1:tvlJhZqDe4LMs4ZHD0oMUlt9G2LWuDGoisJTBzLMV9o= +github.com/golangci/misspell v0.3.5/go.mod h1:dEbvlSfYbMQDtrpRMQU675gSDLDNa8sCPPChZ7PhiVA= +github.com/golangci/revgrep v0.0.0-20210930125155-c22e5001d4f2/go.mod h1:LK+zW4MpyytAWQRz0M4xnzEk50lSvqDQKfx304apFkY= +github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4/go.mod h1:Izgrg8RkN3rCIMLGE9CyYmU9pY2Jer6DgANEnZ/L/cQ= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA= +github.com/google/certificate-transparency-go v1.0.21/go.mod h1:QeJfpSbVSfYc7RgB3gJFj9cbuQMMchQxrWXz8Ruopmg= +github.com/google/certificate-transparency-go v1.1.1/go.mod h1:FDKqPvSXawb2ecErVRrD+nfy23RCzyl7eqVCEmlT1Zs= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -459,28 +618,39 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-containerregistry v0.5.1/go.mod h1:Ct15B4yir3PLOP5jsy0GNeYVaIZs/MK/Jz5any1wFW0= github.com/google/go-intervals v0.0.2 h1:FGrVEiUnTRKR8yE04qzXYaJMtnIYqobR5QbblK3ixcM= github.com/google/go-intervals v0.0.2/go.mod h1:MkaR3LNRfeKLPmqgJYs4E66z5InYjmCjbbr4TQlcT6Y= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200507031123-427632fa3b1c/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/trillian v1.3.11/go.mod h1:0tPraVHrSDkA3BO6vKX67zgLXs6SsOAbHEivX+9mPgw= +github.com/google/uuid v0.0.0-20161128191214-064e2069ce9c/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -489,12 +659,19 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= github.com/googleapis/gnostic v0.5.1/go.mod h1:6U4PtQXGIEt/Z3h5MAT7FNofLnw9vXk2cUuW7uA/OeU= github.com/googleapis/gnostic v0.5.5/go.mod h1:7+EbHbldMins07ALC74bsA81Ovc97DwqyJO1AENw9kA= +github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gordonklaus/ineffassign v0.0.0-20200309095847-7953dde2c7bf/go.mod h1:cuNKsD1zp2v6XfE/orVX2QE1LC+i254ceGcVeDT3pTU= +github.com/gordonklaus/ineffassign v0.0.0-20210225214923-2e10b2664254/go.mod h1:M9mZEtGIsR1oDaZagNPNG9iq9n2HrhZ17dsXk73V3Lw= +github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75/go.mod h1:g2644b03hfBX9Ov0ZBDgXXens4rxSxmqFBbhvKv2yVA= github.com/gorilla/handlers v0.0.0-20150720190736-60c7bfde3e33/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= @@ -502,20 +679,41 @@ github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc= github.com/gorilla/schema v1.2.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gostaticanalysis/analysisutil v0.0.0-20190318220348-4088753ea4d3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= +github.com/gostaticanalysis/analysisutil v0.0.3/go.mod h1:eEOZF4jCKGi+aprrirO9e7WKB3beBRtWgqGunKl6pKE= +github.com/gostaticanalysis/analysisutil v0.1.0/go.mod h1:dMhHRU9KTiDcuLGdy87/2gTR8WruwYZrKdRq9m1O6uw= +github.com/gostaticanalysis/analysisutil v0.4.1/go.mod h1:18U/DLpRgIUd459wGxVHE0fRgmo1UgHDcbw7F5idXu0= +github.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc= +github.com/gostaticanalysis/comment v1.3.0/go.mod h1:xMicKDx7XRXYdVwY9f9wQpDJVnqWxw9wCauCMKp+IBI= +github.com/gostaticanalysis/comment v1.4.1/go.mod h1:ih6ZxzTHLdadaiSnF5WY3dxUoXfXAlTaRzuaNDlSado= +github.com/gostaticanalysis/comment v1.4.2/go.mod h1:KLUTGDv6HOCotCH8h2erHKmpci2ZoR8VPu34YA2uzdM= +github.com/gostaticanalysis/forcetypeassert v0.0.0-20200621232751-01d4955beaa5/go.mod h1:qZEedyP/sY1lTGV1uJ3VhWZ2mqag3IkWsDHVbplHXak= +github.com/gostaticanalysis/nilerr v0.1.1/go.mod h1:wZYb6YI5YAxxq0i1+VJbY0s2YONW0HU0GPE3+5PWN4A= +github.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M= +github.com/gostaticanalysis/testutil v0.4.0/go.mod h1:bLIoPefWXrRi/ssLFWX1dx7Repi5x3CuviD3dgAZaBU= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/go-grpc-middleware v1.3.0/go.mod h1:z0ButlSOZa5vEBq9m2m2hlwIgKw+rp3sdCBRoJY+30Y= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.12.1/go.mod h1:8XEsbTttt/W+VvjtQhLACqCisSPWTxCZ7sBRjU6iH9c= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= +github.com/hashicorp/consul/api v1.10.1/go.mod h1:XjsvQN+RJGWI2TWy1/kqaE16HrR2J/FWgkYjdZQsX9M= github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= +github.com/hashicorp/consul/sdk v0.8.0/go.mod h1:GBvyrGALthsZObzUGsfgHZQDXjg4lOjagTIwIR1vPms= github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= @@ -524,23 +722,31 @@ github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+ github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= +github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= +github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= +github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= github.com/hugelgupf/socketpair v0.0.0-20190730060125-05d35a94e714/go.mod h1:2Goc3h8EklBH5mspfHFxBnEoURQCGzQQH1ga9Myjvis= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= @@ -549,14 +755,29 @@ github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/insomniacslk/dhcp v0.0.0-20210120172423-cc9239ac6294/go.mod h1:TKl4jN3Voofo4UJIicyNhWGp/nlQqQkFxmwIFTvBkKI= +github.com/insomniacslk/dhcp v0.0.0-20220119180841-3c283ff8b7dd/go.mod h1:h+MxyHxRg9NH3terB1nfRIUaQEcI0XOVkdR9LNBlp8E= +github.com/intel/goresctrl v0.2.0/go.mod h1:+CZdzouYFn5EsxgqAQTEzMfwKwuc0fVdMrT9FCCAVRQ= github.com/ishidawataru/sctp v0.0.0-20210226210310-f2269e66cdee/go.mod h1:co9pwDoBCm1kGxawmb4sPq0cSIOOWNPT4KnHotMP1Zg= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= -github.com/jinzhu/copier v0.3.2 h1:QdBOCbaouLDYaIPFfi1bKv5F5tPpeTwXe4sD0jqtz5w= -github.com/jinzhu/copier v0.3.2/go.mod h1:24xnZezI2Yqac9J61UC6/dG/k76ttpq0DdJI3QmUvro= +github.com/j-keck/arping v1.0.2/go.mod h1:aJbELhR92bSk7tp79AWM/ftfc90EfEi2bQJrbBFOsPw= +github.com/jgautheron/goconst v1.5.1/go.mod h1:aAosetZ5zaeC/2EfMeRswtxUFBpe2Hr7HzkgX4fanO4= +github.com/jhump/protoreflect v1.6.1/go.mod h1:RZQ/lnuN+zqeRVpQigTwO6o0AJUkxbnSnpuG7toUTG4= +github.com/jingyugao/rowserrcheck v1.1.1/go.mod h1:4yvlZSDb3IyDTUZJUmpZfm2Hwok+Dtp+nu2qOq+er9c= +github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= +github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= +github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af/go.mod h1:HEWGJkRDzjJY2sqdDwxccsGicWEf9BQOZsq2tV+xzM0= github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= +github.com/joefitzgerald/rainbow-reporter v0.1.0/go.mod h1:481CNgqmVHQZzdIbN52CupLJyoVwB10FQ/IQlF1pdL8= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/jonboulle/clockwork v0.2.0/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/jonboulle/clockwork v0.2.2/go.mod h1:Pkfl5aHPm1nk2H9h0bjmnJD/BcgbGXUBGnn1kMkgxc8= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/josharian/txtarfs v0.0.0-20210218200122-0702f000015a/go.mod h1:izVPOvVRsHiKkeGCT6tYBNWyDVuzj9wAaBb5R9qamfw= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/jsimonetti/rtnetlink v0.0.0-20190606172950-9527aa82566a/go.mod h1:Oz+70psSo5OFh8DBl0Zv2ACw7Esh6pPUphlvZG9x7uw= github.com/jsimonetti/rtnetlink v0.0.0-20200117123717-f846d4f6c1f4/go.mod h1:WGuG/smIU4J/54PblvSbh+xvCZmpJnFgr3ds6Z55XMQ= @@ -571,20 +792,25 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/juju/ansiterm v0.0.0-20180109212912-720a0952cc2a/go.mod h1:UJSiEoRfvx3hP73CvoARgeLjaIOjybY9vj8PUPPFGeU= +github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/julz/importas v0.0.0-20210419104244-841f0c0fe66d/go.mod h1:oSFU2R4XK/P7kNBrnL/FEQlDGN1/6WoxXEjSSXO0DV0= +github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/errcheck v1.6.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.14.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.2 h1:3WH+AG7s2+T8o3nrM/8u2rdqUEcQhmga7smjrT41nAw= +github.com/klauspost/compress v1.15.2/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -594,38 +820,71 @@ github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lunixbochs/vtclean v0.0.0-20180621232353-2d01aacdc34a/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI= +github.com/kulti/thelper v0.4.0/go.mod h1:vMu2Cizjy/grP+jmsvOFDx1kYP6+PD1lqg4Yu5exl2U= +github.com/kunwardeep/paralleltest v1.0.3/go.mod h1:vLydzomDFpk7yu5UX02RmP0H8QfRPOV/oFhWN85Mjb4= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/kyoh86/exportloopref v0.1.8/go.mod h1:1tUcJeiioIs7VWe5gcOObrux3lb66+sBqGZrRkMwPgg= +github.com/ldez/gomoddirectives v0.2.2/go.mod h1:cpgBogWITnCfRq2qGoDkKMEVSaarhdBr6g8G04uz6d0= +github.com/ldez/tagliatelle v0.2.0/go.mod h1:8s6WJQwEYHbKZDsp/LjArytKOG8qaMrKQQ3mFukHs88= +github.com/letsencrypt/pkcs11key/v4 v4.0.0/go.mod h1:EFUvBDay26dErnNb70Nd0/VW3tJiIbETBPTl9ATXQag= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.8.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.9.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.10.3/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/linuxkit/virtsock v0.0.0-20201010232012-f8cee7dfc7a3/go.mod h1:3r6x7q95whyfWQpmGZTu3gk3v2YkMi05HEzl7Tf7YEo= +github.com/logrusorgru/aurora v0.0.0-20181002194514-a7b3b318ed4e/go.mod h1:7rIyQOR62GCctdiQpZ/zOJlFyk6y+94wXzv6RNZgaR4= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= -github.com/manifoldco/promptui v0.8.0/go.mod h1:n4zTdgP0vr0S3w7/O/g98U+e0gwLScEXGwov2nIKuGQ= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA= github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg= +github.com/maratori/testpackage v1.0.1/go.mod h1:ddKdw+XG0Phzhx8BFDTKgpWP4i7MpApTE5fXSKAqwDU= github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= +github.com/matoous/godox v0.0.0-20210227103229-6504466cf951/go.mod h1:1BELzlh859Sh1c6+90blK8lbYy0kwQf1bYlBhBysy1s= +github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= +github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= -github.com/mattn/go-shellwords v1.0.10/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= +github.com/mattn/go-shellwords v1.0.6/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk= github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= +github.com/mattn/go-sqlite3 v1.9.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/maxbrunsfeld/counterfeiter/v6 v6.2.2/go.mod h1:eD9eIE7cdwcMi9rYluz88Jz2VyhSmden33/aXg4oVIY= +github.com/mbilski/exhaustivestruct v1.2.0/go.mod h1:OeTBVxQWoEmB2J2JCHmXWPJ0aksxSUOUy+nvtVEfzXc= github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7/go.mod h1:U6ZQobyTjI/tJyq2HG+i/dfSoFUt8/aZCM+GKtmFk/Y= github.com/mdlayher/netlink v0.0.0-20190409211403-11939a169225/go.mod h1:eQB3mZE4aiYnlUsyGGCOpPETfdQq4Jhsgf1fk3cwQaA= github.com/mdlayher/netlink v1.0.0/go.mod h1:KxeJAFOFLG6AjpyDkQ/iIhxygIUKD+vcwqcnu43w/+M= @@ -633,32 +892,47 @@ github.com/mdlayher/netlink v1.1.0/go.mod h1:H4WCitaheIsdF9yOYu8CFmCgQthAPIWZmcK github.com/mdlayher/netlink v1.1.1/go.mod h1:WTYpFb/WTvlRJAyKhZL5/uy69TDDpHHu2VZmb2XgV7o= github.com/mdlayher/raw v0.0.0-20190606142536-fef19f00fc18/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065/go.mod h1:7EpbotpCmVZcu+KCX4g9WaRNuu11uyhiW7+Le1dKawg= +github.com/mgechev/dots v0.0.0-20210922191527-e955255bf517/go.mod h1:KQ7+USdGKfpPjXk4Ga+5XxQM4Lm4e3gAogrreFAYpOg= +github.com/mgechev/revive v1.1.2/go.mod h1:bnXsMr+ZTH09V5rssEI+jHAZ4z+ZdyhgO/zsy3EhK+0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/miekg/pkcs11 v1.0.3 h1:iMwmD7I5225wv84WxIG/bmxz9AXjWvTWIbM/TYHvWtw= +github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= +github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= +github.com/miekg/pkcs11 v1.0.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= -github.com/mistifyio/go-zfs v2.1.1+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= +github.com/miekg/pkcs11 v1.1.1 h1:Ugu9pdy6vAYku5DEpVWVFPYnzV+bxB+iRdbuFSu7TvU= +github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible h1:aKW/4cBs+yK6gpqU3K/oIwk9Q/XICqd3zOX/UFuvqmk= github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.2/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f/go.mod h1:OkQIRizQZAeMln+1tSwduZz7+Af5oFlKirV/MSYes2A= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/mndrix/tap-go v0.0.0-20171203230836-629fa407e90b/go.mod h1:pzzDgJWZ34fGzaAZGFW22KVZDfyrYW+QABMrWnJBnSs= github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= github.com/moby/spdystream v0.2.0/go.mod h1:f7i0iNDQJ059oMTcWxx8MA/zKFIuD/lY+0GqbN2Wy8c= github.com/moby/sys/mount v0.2.0/go.mod h1:aAivFE2LB3W4bACsUXChRHQ0qKWsetY4Y9V7sxOougM= -github.com/moby/sys/mountinfo v0.1.3/go.mod h1:w2t2Avltqx8vE7gX5l+QiBKxODu2TX0+Syr3h52Tw4o= github.com/moby/sys/mountinfo v0.4.0/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= -github.com/moby/sys/mountinfo v0.4.1 h1:1O+1cHA1aujwEwwVMa2Xm2l+gIpUHyd3+D+d7LZh1kM= github.com/moby/sys/mountinfo v0.4.1/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= +github.com/moby/sys/mountinfo v0.5.0/go.mod h1:3bMD3Rg+zkqx8MRYPi7Pyb0Ie97QEBmdxbhnCLlSvSU= +github.com/moby/sys/mountinfo v0.6.1 h1:+H/KnGEAGRpTrEAqNVQ2AM3SiwMgJUt/TXj+Z8cmCIc= +github.com/moby/sys/mountinfo v0.6.1/go.mod h1:3bMD3Rg+zkqx8MRYPi7Pyb0Ie97QEBmdxbhnCLlSvSU= +github.com/moby/sys/signal v0.6.0/go.mod h1:GQ6ObYZfqacOwTtlXvcmh9A26dVRul/hbOZn88Kg8Tg= github.com/moby/sys/symlink v0.1.0/go.mod h1:GGDODQmbFOjFsXvfLVn3+ZRxkch54RkSiGqsZeMYowQ= +github.com/moby/sys/symlink v0.2.0/go.mod h1:7uZVF2dqJjG/NsClqul95CqKOBRQyYSNnJ6BMgR/gFs= github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= -github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= +github.com/moby/term v0.0.0-20210610120745-9d4ed1856297/go.mod h1:vgPCkQMyxTZ7IDy8SXRufE172gr8+K/JE/7hHFxHW3A= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 h1:dcztxKSvZ4Id8iPpHERQBbIJfabdt4wUm5qy3wOL2Zc= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= github.com/moby/vpnkit v0.5.0/go.mod h1:KyjUrL9cb6ZSNNAUwZfqRjhwwgJ3BJN+kXh0t43WTUQ= @@ -669,26 +943,36 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lN github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8= +github.com/moricho/tparallel v0.2.1/go.mod h1:fXEIZxG2vdfl0ZF8b42f5a78EhjjD5mX8qUplsoSU4k= github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= -github.com/mrunalp/fileutils v0.0.0-20171103030105-7d4729fb3618/go.mod h1:x8F1gnqOkIEiO4rqoeEEEqQbo7HjGMTvyoq3gej4iT0= +github.com/mozilla/scribe v0.0.0-20180711195314-fb71baf557c1/go.mod h1:FIczTrinKo8VaLxe6PWTPEXRXDIHz2QAwiaBaP5/4a8= +github.com/mozilla/tls-observatory v0.0.0-20210609171429-7bc42856d2e5/go.mod h1:FUqVoUPHSEdDR0MnFM3Dh8AU0pZHLXUD127SAJGER/s= github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= -github.com/mtrmac/gpgme v0.1.2 h1:dNOmvYmsrakgW7LcgiprD0yfRuQQe8/C8F6Z+zogO3s= -github.com/mtrmac/gpgme v0.1.2/go.mod h1:GYYHnGSuS7HK3zVS2n3y73y0okK/BeKzwnn5jgiVFNI= github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-proto-validators v0.0.0-20180403085117-0950a7990007/go.mod h1:m2XC9Qq0AlmmVksL6FktJCdTYyLk7V3fKyp0sl1yWQo= +github.com/mwitkow/go-proto-validators v0.2.0/go.mod h1:ZfA1hW+UH/2ZHOWvQ3HnQaU0DtnpXu850MZiy+YUgcc= github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE= +github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354/go.mod h1:KSVJerMDfblTH7p5MZaTt+8zaT2iEk3AkVb9PQdZuE8= github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/networkplumbing/go-nft v0.2.0/go.mod h1:HnnM+tYvlGAsMU7yoYwXEVLLiDW9gdMmb5HoGcwpuQs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nishanths/exhaustive v0.2.3/go.mod h1:bhIX678Nx8inLM9PbpvK1yv6oGtoP8BfaIeMzgBNKvc= +github.com/nishanths/predeclared v0.0.0-20190419143655-18a43bb90ffc/go.mod h1:62PewwiQTlm/7Rj+cxVYqZvDIUc+JjZq6GHAC1fsObQ= +github.com/nishanths/predeclared v0.2.1/go.mod h1:HvkGJcA3naj4lOwnFXFDkFxVtSqQMB9sbB1usJ+xjQE= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.4/go.mod h1:zq6QwlOf5SlnkVbMSr5EoBv3636FWnp+qbPhuoO21uA= +github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/olekukonko/tablewriter v0.0.2/go.mod h1:rSAaSIOAGT9odnlyGlUfAJaoc5w2fSBUmeGDbRWPxyQ= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= @@ -696,21 +980,29 @@ github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+W github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= -github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= -github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc= github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= +github.com/onsi/ginkgo/v2 v2.1.4 h1:GNapqRSid3zijZ9H77KrgVG4/8KqiyRsxcSxe+7ApXY= +github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU= github.com/onsi/gomega v0.0.0-20151007035656-2152b45fa28a/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= -github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= -github.com/onsi/gomega v1.16.0 h1:6gjqkI8iiRHMvdccRJM8rVKjCWk6ZIm6FTm3ddIe4/c= +github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= +github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw= +github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= @@ -719,61 +1011,83 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.0/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= -github.com/opencontainers/image-spec v1.0.2-0.20210819154149-5ad6f50d6283 h1:TVzvdjOalkJBNkbpPVMAr4KV9QRf2IjfxdyxwAK78Gs= -github.com/opencontainers/image-spec v1.0.2-0.20210819154149-5ad6f50d6283/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.2-0.20211117181255-693428a734f5/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/image-spec v1.0.3-0.20211202193544-a5463b7f9c84/go.mod h1:Qnt1q4cjDNQI9bT832ziho5Iw2BhK8o1KwLOwW56VP4= +github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198 h1:+czc/J8SlhPKLOtVLMQc+xDCFBT73ZStMsRhSsUhsSg= +github.com/opencontainers/image-spec v1.0.3-0.20220114050600-8b9d41f48198/go.mod h1:j4h1pJW6ZcJTgMZWP3+7RlG3zTaP02aDZ/Qw0sppK7Q= github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= github.com/opencontainers/runc v1.0.0-rc8.0.20190926000215-3e425f80a8c9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= github.com/opencontainers/runc v1.0.0-rc9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= -github.com/opencontainers/runc v1.0.0-rc91/go.mod h1:3Sm6Dt7OT8z88EbdQqqcRN2oCT54jbi72tT/HqgflT8= github.com/opencontainers/runc v1.0.0-rc93/go.mod h1:3NOsor4w32B2tC0Zbl8Knk4Wg84SM2ImC1fxBuqJ/H0= -github.com/opencontainers/runc v1.0.1/go.mod h1:aTaHFFwQXuA71CiyxOdFFIorAoemI04suvGRQFzWTD0= -github.com/opencontainers/runc v1.0.2 h1:opHZMaswlyxz1OuGpBE53Dwe4/xF7EZTY0A2L/FpCOg= github.com/opencontainers/runc v1.0.2/go.mod h1:aTaHFFwQXuA71CiyxOdFFIorAoemI04suvGRQFzWTD0= +github.com/opencontainers/runc v1.0.3/go.mod h1:aTaHFFwQXuA71CiyxOdFFIorAoemI04suvGRQFzWTD0= +github.com/opencontainers/runc v1.1.0/go.mod h1:Tj1hFw6eFWp/o33uxGf5yF2BX5yz2Z6iptFpuvbbKqc= +github.com/opencontainers/runc v1.1.1 h1:PJ9DSs2sVwE0iVr++pAHE6QkS9tzcVWozlPifdwMgrU= +github.com/opencontainers/runc v1.1.1/go.mod h1:Tj1hFw6eFWp/o33uxGf5yF2BX5yz2Z6iptFpuvbbKqc= github.com/opencontainers/runtime-spec v0.1.2-0.20190507144316-5b71a03e2700/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.2-0.20190207185410-29686dbc5559/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.3-0.20200520003142-237cc4f519e2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.3-0.20200929063507-e6143ca7d51d/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 h1:3snG66yBm59tKhhSPQrQ/0bCrv1LQbKt40LnUPiUxdc= +github.com/opencontainers/runtime-spec v1.0.3-0.20201121164853-7413a7f753e1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.3-0.20211214071223-8958f93039ab h1:YQZXa3elcHgKXAa2GjVFC9M3JeP7ZPyFD1YByDx/dgQ= +github.com/opencontainers/runtime-spec v1.0.3-0.20211214071223-8958f93039ab/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= -github.com/opencontainers/runtime-tools v0.9.0 h1:FYgwVsKRI/H9hU32MJ/4MLOzXWodKK5zsQavY8NPMkU= +github.com/opencontainers/runtime-tools v0.0.0-20190417131837-cd1349b7c47e/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= github.com/opencontainers/runtime-tools v0.9.0/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= -github.com/opencontainers/selinux v1.5.1/go.mod h1:yTcKuYAh6R95iDpefGLQaPaRwJFwyzAJufJyiTt7s0g= +github.com/opencontainers/runtime-tools v0.9.1-0.20220110225228-7e2d60f1e41f h1:MMcsVl0FAVEahmXTy+uXoDTw3yJq7nGrK8ITs/kkreo= +github.com/opencontainers/runtime-tools v0.9.1-0.20220110225228-7e2d60f1e41f/go.mod h1:/tgP02fPXGHkU3/qKK1Y0Db4yqNyGm03vLq/mzHzcS4= github.com/opencontainers/selinux v1.6.0/go.mod h1:VVGKuOLlE7v4PJyT6h7mNWvq1rzqiriPsEqVhc+svHE= github.com/opencontainers/selinux v1.8.0/go.mod h1:RScLhm78qiWa2gbVCcGkC7tCGdgk3ogry1nUQF8Evvo= github.com/opencontainers/selinux v1.8.2/go.mod h1:MUIHuUEvKB1wtJjQdOyYRgOnLD2xAPP8dBsCoU0KuF8= -github.com/opencontainers/selinux v1.8.4/go.mod h1:HTvjPFoGMbpQsG886e3lQwnsRWtE4TC1OF3OUvG9FAo= github.com/opencontainers/selinux v1.8.5/go.mod h1:HTvjPFoGMbpQsG886e3lQwnsRWtE4TC1OF3OUvG9FAo= -github.com/opencontainers/selinux v1.9.1 h1:b4VPEF3O5JLZgdTDBmGepaaIbAo0GqoF6EBRq5f/g3Y= github.com/opencontainers/selinux v1.9.1/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= -github.com/openshift/imagebuilder v1.2.2-0.20210415181909-87f3e48c2656/go.mod h1:9aJRczxCH0mvT6XQ+5STAQaPWz7OsWcU5/mRkt8IWeo= -github.com/ostreedev/ostree-go v0.0.0-20190702140239-759a8c1ac913 h1:TnbXhKzrTOyuvWrjI8W6pcoI9XPbLHFXCdN2dtUw7Rw= -github.com/ostreedev/ostree-go v0.0.0-20190702140239-759a8c1ac913/go.mod h1:J6OG6YJVEWopen4avK3VNQSnALmmjvniMmni/YFYAwc= +github.com/opencontainers/selinux v1.10.0/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= +github.com/opencontainers/selinux v1.10.1 h1:09LIPVRP3uuZGQvgR+SgMSNBd1Eb3vlRbGqQpoHsF8w= +github.com/opencontainers/selinux v1.10.1/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= +github.com/openshift/imagebuilder v1.2.4-0.20220502172744-009dbc6cb805/go.mod h1:TRYHe4CH9U6nkDjxjBNM5klrLbJBrRbpJE5SaRwUBsQ= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/ostreedev/ostree-go v0.0.0-20210805093236-719684c64e4f h1:/UDgs8FGMqwnHagNDPGOlts35QkhAZ8by3DR7nMih7M= +github.com/ostreedev/ostree-go v0.0.0-20210805093236-719684c64e4f/go.mod h1:J6OG6YJVEWopen4avK3VNQSnALmmjvniMmni/YFYAwc= +github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= +github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= +github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d/go.mod h1:3OzsM7FXDQlpCiw2j81fOmAwQLnZnLGXVKUzeKQXIAw= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= +github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/polyfloyd/go-errorlint v0.0.0-20210722154253-910bb7978349/go.mod h1:wi9BfjxjF/bwiZ701TzmfKu6UKC357IOAtNr0Td0Lvw= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= +github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= -github.com/pquerna/ffjson v0.0.0-20181028064349-e517b90714f7/go.mod h1:YARuvh7BUWHNhzDq2OM5tzR2RiCcN2D7sapiKyCel/M= +github.com/proglottis/gpgme v0.1.1 h1:72xI0pt/hy7pqsRxk32KExITkXp+RZErRizsA+up/lQ= +github.com/proglottis/gpgme v0.1.1/go.mod h1:fPbW/EZ0LvwQtH8Hy7eixhp1eF3G39dtx7GUN+0Gmy0= github.com/prometheus/client_golang v0.0.0-20180209125602-c332b6f63c06/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_golang v1.11.1 h1:+4eQaD7vAZ6DsfsxB15hbE0odUjGI5ARs9yskGu1v4s= github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_model v0.0.0-20171117100541-99fa1f4be8e5/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= @@ -788,8 +1102,9 @@ github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8 github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/common v0.26.0 h1:iMAkS2TDoNWnKM+Kopnx/8tnEStIfpYA0ur0xQzzhMQ= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= +github.com/prometheus/common v0.30.0 h1:JEkYlQnpzrzQFxi6gnukFPdQ+ac82oRhzMcIduJu/Ug= +github.com/prometheus/common v0.30.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= github.com/prometheus/procfs v0.0.0-20180125133057-cb4147076ac7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= @@ -800,24 +1115,56 @@ github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDa github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= +github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= +github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/pseudomuto/protoc-gen-doc v1.3.2/go.mod h1:y5+P6n3iGrbKG+9O04V5ld71in3v/bX88wUwgt+U8EA= +github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= +github.com/quasilyte/go-consistent v0.0.0-20190521200055-c6f3937de18c/go.mod h1:5STLWrekHfjyYwxBRVRXNOSewLJ3PWfDJd1VyTS21fI= +github.com/quasilyte/go-ruleguard v0.3.1-0.20210203134552-1b5a410e1cc8/go.mod h1:KsAh3x0e7Fkpgs+Q9pNLS5XpFSvYCEVl5gP9Pp1xp30= +github.com/quasilyte/go-ruleguard v0.3.13/go.mod h1:Ul8wwdqR6kBVOCt2dipDBkE+T6vAV/iixkrKuRTN1oQ= +github.com/quasilyte/go-ruleguard/dsl v0.3.0/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= +github.com/quasilyte/go-ruleguard/dsl v0.3.10/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU= +github.com/quasilyte/go-ruleguard/rules v0.0.0-20201231183845-9e62ed36efe1/go.mod h1:7JTjp89EGyU1d6XfBiXihJNG37wB2VRkd125Q1u7Plc= +github.com/quasilyte/go-ruleguard/rules v0.0.0-20210428214800-545e0d2e0bf7/go.mod h1:4cgAphtvu7Ftv7vOT2ZOYhC6CvBxZixcasr8qIOTA50= +github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rootless-containers/rootlesskit v0.14.5/go.mod h1:Ai3detLzryb/4EkzXmNfh8aByUcBXp/qqkQusJs1SO8= +github.com/rogpeppe/go-internal v1.6.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rootless-containers/rootlesskit v1.0.1/go.mod h1:t2UAiYagxrJ+wmpFAUIZPcqsm4k2B7ve6g7lILKbloc= +github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/ryancurrah/gomodguard v1.2.3/go.mod h1:rYbA/4Tg5c54mV1sv4sQTP5WOPBcoLtnBZ7/TEhXAbg= +github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= +github.com/safchain/ethtool v0.0.0-20210803160452-9aa261dae9b1/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= +github.com/sagikazarmark/crypt v0.1.0/go.mod h1:B/mN0msZuINBtQ1zZLEQcegFJJf9vnYIR88KRMEuODE= +github.com/sanposhiho/wastedassign/v2 v2.0.6/go.mod h1:KyZ0MWTwxxBmfwn33zh3k1dmsbF2ud9pAAGfoLfjhtI= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= +github.com/sclevine/spec v1.2.0/go.mod h1:W4J29eT/Kzv7/b9IWLB055Z+qvVC9vt0Arko24q7p+U= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= +github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y= +github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= -github.com/seccomp/libseccomp-golang v0.9.2-0.20200616122406-847368b35ebf/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= +github.com/seccomp/libseccomp-golang v0.9.2-0.20210429002308-3879420cc921/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= +github.com/securego/gosec/v2 v2.9.1/go.mod h1:oDcDLcatOJxkCGaCaq8lua1jTnYf6Sou4wdiJ1n4iHc= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= +github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= +github.com/shirou/gopsutil/v3 v3.21.10/go.mod h1:t75NhzCZ/dYyPQjyQmrAYP6c8+LCdFANeBMdLPCNnew= +github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= +github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= @@ -828,23 +1175,30 @@ github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrf github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sivchari/tenv v1.4.7/go.mod h1:5nF+bITvkebQVanjU6IuMbvIot/7ReNsUV7I5NbprB0= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= +github.com/sonatard/noctx v0.0.1/go.mod h1:9D2D/EoULe8Yy2joDHJj7bv3sZoq9AaSb8B4lqBjiZI= github.com/songgao/water v0.0.0-20200317203138-2b4b6d7c09d8/go.mod h1:P5HUIBuIWKbyjl083/loAegFkfbFNx5i2qEP4CNbm7E= +github.com/sourcegraph/go-diff v0.6.1/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= -github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= -github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= +github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= +github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q= +github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= @@ -853,9 +1207,12 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= +github.com/spf13/viper v1.9.0/go.mod h1:+i6ajR7OX2XaiBkrcZJFK21htRk7eDeLg7+O6bhUPP4= +github.com/ssgreg/nlreturn/v2 v2.2.1/go.mod h1:E/iiPB78hV7Szg2YfRgyIrk1AD6JVMTRkkxBiELzh2I= github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980 h1:lIOOHPEbXzO3vnmx2gok1Tfs31Q8GQqKLc8vVqyQq/I= github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h1:AO3tvPzVZ/ayst6UlUKUv6rcPQInYe3IknH3jYhAKu8= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= @@ -863,15 +1220,21 @@ github.com/stretchr/objx v0.0.0-20180129172003-8a3f7159479f/go.mod h1:HFkY916IF+ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/testify v0.0.0-20170130113145-4d4bfba8f1d1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v0.0.0-20180303142811-b89eecf5ca5d/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.1.4/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= +github.com/sylabs/sif/v2 v2.7.0 h1:VFzN8alnJ/3n1JA0K9DyUtfSzezWgWrzLDcYGhgBskk= +github.com/sylabs/sif/v2 v2.7.0/go.mod h1:TiyBWsgWeh5yBeQFNuQnvROwswqK7YJT8JA1L53bsXQ= +github.com/sylvia7788/contextcheck v1.0.4/go.mod h1:vuPKJMQ7MQ91ZTqfdyreNKwZjyUg6KO+IebVyQDedZQ= github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtseVEc4yCz2qF8ZrQvIDBJLl4S1c3GCXmoI= @@ -879,63 +1242,98 @@ github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= github.com/tchap/go-patricia v2.3.0+incompatible h1:GkY4dP3cEfEASBPPkWd+AmjYxhmDkqO9/zg7R0lSQRs= github.com/tchap/go-patricia v2.3.0+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= +github.com/tdakkota/asciicheck v0.0.0-20200416200610-e657995f937b/go.mod h1:yHp0ai0Z9gUljN3o0xMhYJnH/IcvkdTBOX2fmJ93JEM= +github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= +github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= +github.com/tetafro/godot v1.4.11/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= +github.com/timakin/bodyclose v0.0.0-20200424151742-cb6215831a94/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= +github.com/tklauser/go-sysconf v0.3.9/go.mod h1:11DU/5sG7UexIrp/O6g35hrWzu0JxlwQ3LSFUzyeuhs= +github.com/tklauser/numcpus v0.3.0/go.mod h1:yFGUr7TUHQRAhyqBcEg0Ge34zDBAsIvJJcyE6boqnA8= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/u-root/u-root v7.0.0+incompatible/go.mod h1:RYkpo8pTHrNjW08opNd/U6p/RJE7K0D8fXO0d47+3YY= -github.com/uber/jaeger-client-go v2.29.1+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= +github.com/tmc/grpc-websocket-proxy v0.0.0-20200427203606-3cfed13b9966/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/tomarrell/wrapcheck/v2 v2.4.0/go.mod h1:68bQ/eJg55BROaRTbMjC7vuhL2OgfoG8bLp9ZyoBfyY= +github.com/tomasen/realip v0.0.0-20180522021738-f0c99a92ddce/go.mod h1:o8v6yHRoik09Xen7gje4m9ERNah1d1PPsVq1VEx9vE4= +github.com/tommy-muehle/go-mnd/v2 v2.4.0/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= +github.com/tv42/httpunix v0.0.0-20191220191345-2ba4b9c3382c/go.mod h1:hzIxponao9Kjc7aWznkXaL4U4TWaDSs8zcsY4Ka08nM= +github.com/u-root/uio v0.0.0-20210528114334-82958018845c/go.mod h1:LpEX5FO/cB+WF4TYGY1V5qktpaZLkKkSegbr0V4eYXA= +github.com/uber/jaeger-client-go v2.30.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/ulikunitz/xz v0.5.10 h1:t92gobL9l3HE202wg3rlk19F6X+JOxl9BBrCCMYEYd8= github.com/ulikunitz/xz v0.5.10/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +github.com/ultraware/funlen v0.0.3/go.mod h1:Dp4UiAus7Wdb9KUZsYWZEWiRzGuM2kXM1lPbfaF6xhA= +github.com/ultraware/whitespace v0.0.4/go.mod h1:aVMh/gQve5Maj9hQ/hg+F75lr/X5A89uZnzAmWSineA= github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli v1.19.1/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/vbatts/tar-split v0.11.1/go.mod h1:LEuURwDEiWjRjwu46yU3KVGuUdVv/dcnpcEPSzR8z6g= +github.com/urfave/cli/v2 v2.5.1/go.mod h1:oDzoM7pVwz6wHn5ogWgFUU1s4VJayeQS+aEZDqXIEJs= +github.com/uudashr/gocognit v1.0.5/go.mod h1:wgYz0mitoKOTysqxTDMOUXg+Jb5SvtihkfmugIZYpEA= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.30.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus= +github.com/valyala/quicktemplate v1.7.0/go.mod h1:sqKJnoaOF88V07vkO+9FL8fb9uZg/VPSJnLYn+LmLk8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= github.com/vbatts/tar-split v0.11.2 h1:Via6XqJr0hceW4wff3QRzD5gAk/tatMw/4ZA7cTlIME= github.com/vbatts/tar-split v0.11.2/go.mod h1:vV3ZuO2yWSVsz+pfFzDG/upWH1JhjOiEaWq6kXyQ3VI= -github.com/vbauerster/mpb/v6 v6.0.4/go.mod h1:a/+JT57gqh6Du0Ay5jSR+uBMfXGdlR7VQlGP52fJxLM= -github.com/vbauerster/mpb/v7 v7.1.3/go.mod h1:X5GlohZw2fIpypMXWaKart+HGSAjpz49skxkDk+ZL7c= -github.com/vbauerster/mpb/v7 v7.1.5 h1:vtUEUfQHmNeJETyF4AcRCOV6RC4wqFwNORy52UMXPbQ= -github.com/vbauerster/mpb/v7 v7.1.5/go.mod h1:4M8+qAoQqV60WDNktBM5k05i1iTrXE7rjKOHEVkVlec= +github.com/vbauerster/mpb/v7 v7.4.1 h1:NhLMWQ3gNg2KJR8oeA9lO8Xvq+eNPmixDmB6JEQOUdA= +github.com/vbauerster/mpb/v7 v7.4.1/go.mod h1:Ygg2mV9Vj9sQBWqsK2m2pidcf9H3s6bNKtqd3/M4gBo= +github.com/viki-org/dnscache v0.0.0-20130720023526-c70c1f23c5d8/go.mod h1:dniwbG03GafCjFohMDmz6Zc6oCuiqgH6tGNyXTkHzXE= github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= -github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852 h1:cPXZWzzG0NllBLdjWoD1nDfaqu98YMv+OneaKc8sPOA= github.com/vishvananda/netlink v1.1.1-0.20201029203352-d40f9887b852/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= +github.com/vishvananda/netlink v1.1.1-0.20210330154013-f5de75959ad5/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= +github.com/vishvananda/netlink v1.1.1-0.20220115184804-dd687eb2f2d4/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI= github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= -github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae h1:4hwBBUfQCFe3Cym0ZtKyq7L16eZUtYKs+BaHDN6mAns= github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= +github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/willf/bitset v1.1.11-0.20200630133818-d5bec3311243/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190809123943-df4f5c81cb3b h1:6cLsL+2FW6dRAdl5iMtHgRogVCff0QpRi9653YmdcJA= -github.com/xeipuuv/gojsonpointer v0.0.0-20190809123943-df4f5c81cb3b/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yeya24/promlinter v0.1.0/go.mod h1:rs5vtZzeBHqqMwXqFScncpCF6u06lezhZepno9AB1Oc= +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= +github.com/yudai/pp v2.0.1+incompatible/go.mod h1:PuxR/8QJ7cyCkFp/aUDS+JY727OFEZkTdatxwunjIkc= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= +go.etcd.io/etcd v0.0.0-20200513171258-e048e166ab9c/go.mod h1:xCI7ZzBfRuGgBXyXO6yfWfDmlWd35khcWpUa4L0xI/k= go.etcd.io/etcd v0.5.0-alpha.5.0.20200910180754-dd1b699fc489/go.mod h1:yVHk9ub3CSBatqGNg7GRmsnfLWtoW60w4eDYfh7vHDg= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= +go.etcd.io/etcd/client/v3 v3.5.0/go.mod h1:AIKXXVX/DQXtfTEqBryiLTUXwON+GuvO6Z7lLS/oTh0= +go.etcd.io/etcd/pkg/v3 v3.5.0/go.mod h1:UzJGatBQ1lXChBkQF0AuAtkRQMYnHubxAEYIrC3MSsE= +go.etcd.io/etcd/raft/v3 v3.5.0/go.mod h1:UFOHSIvO/nKwd4lhkwabrTD3cqW5yVyYYf/KlD00Szc= +go.etcd.io/etcd/server/v3 v3.5.0/go.mod h1:3Ah5ruV+M+7RZr0+Y/5mNLwC+eQlni+mQmOVdCRJoS4= +go.mozilla.org/mozlog v0.0.0-20170222151521-4bb13139d403/go.mod h1:jHoPAGnDrCy6kaI2tAze5Prf0Nr0w/oNkROt2lw3n3o= go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1 h1:A/5uWzF44DlIgdm/PQFwfMkW0JX+cIcQi/SwLAmZP5M= go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -946,30 +1344,65 @@ go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/contrib v0.20.0/go.mod h1:G/EtFaa6qaN7+LxqfIAT3GiZa7Wv5DTBUzl5H4LY0Kc= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.20.0/go.mod h1:oVGt1LRbBOBq1A5BQLlUg9UaU/54aiHw8cgjV3aWZ/E= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.28.0/go.mod h1:vEhqr0m4eTc+DWxfsXoXue2GBgV2uUwVznkGIHW/e5w= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.20.0/go.mod h1:2AboqHi0CiIZU0qwhtUfCYD1GeUzvvIXWNkhDt7ZMG4= +go.opentelemetry.io/otel v0.20.0/go.mod h1:Y3ugLH2oa81t5QO+Lty+zXf8zC9L26ax4Nzoxm/dooo= +go.opentelemetry.io/otel v1.3.0/go.mod h1:PWIKzi6JCp7sM0k9yZ43VX+T345uNbAkDKwHVjb2PTs= +go.opentelemetry.io/otel/exporters/otlp v0.20.0/go.mod h1:YIieizyaN77rtLJra0buKiNBOm9XQfkPEKBeuhoMwAM= +go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.3.0/go.mod h1:VpP4/RMn8bv8gNo9uK7/IMY4mtWLELsS+JIP0inH0h4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.3.0/go.mod h1:hO1KLR7jcKaDDKDkvI9dP/FIhpmna5lkqPUQdEjFAM8= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.3.0/go.mod h1:keUU7UfnwWTWpJ+FWnyqmogPa82nuU5VUANFq49hlMY= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.3.0/go.mod h1:QNX1aly8ehqqX1LEa6YniTU7VY9I6R3X/oPxhGdTceE= +go.opentelemetry.io/otel/metric v0.20.0/go.mod h1:598I5tYlH1vzBjn+BTuhzTCSb/9debfNp6R3s7Pr1eU= +go.opentelemetry.io/otel/oteltest v0.20.0/go.mod h1:L7bgKf9ZB7qCwT9Up7i9/pn0PWIa9FqQ2IQ8LoxiGnw= +go.opentelemetry.io/otel/sdk v0.20.0/go.mod h1:g/IcepuwNsoiX5Byy2nNV0ySUF1em498m7hBWC279Yc= +go.opentelemetry.io/otel/sdk v1.3.0/go.mod h1:rIo4suHNhQwBIPg9axF8V9CA72Wz2mKF1teNrup8yzs= +go.opentelemetry.io/otel/sdk/export/metric v0.20.0/go.mod h1:h7RBNMsDJ5pmI1zExLi+bJK+Dr8NQCh0qGhm1KDnNlE= +go.opentelemetry.io/otel/sdk/metric v0.20.0/go.mod h1:knxiS8Xd4E/N+ZqKmUPf3gTTZ4/0TjTXukfxjzSTpHE= +go.opentelemetry.io/otel/trace v0.20.0/go.mod h1:6GjCW8zgDjwGHGa6GkyeB8+/5vjT16gUEi0Nf1iBdgw= +go.opentelemetry.io/otel/trace v1.3.0/go.mod h1:c/VDhno8888bvQYmbYLqe41/Ldmr/KKunbvWM4/fEjk= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.opentelemetry.io/proto/otlp v0.11.0/go.mod h1:QpEjXPrNQzrFDZgoTo49dgHR9RYRSrg3NAKnUGl9YpQ= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.4.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180501155221-613d6eafa307/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 h1:kUhD7nTDoI3fVd9G4ORWrbV5NY0liEs/Jg2pv5f+bBA= golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -982,6 +1415,7 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= @@ -1007,6 +1441,8 @@ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -1031,6 +1467,8 @@ golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191007182048-72f939374954/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -1040,6 +1478,7 @@ golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLL golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= @@ -1061,10 +1500,19 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211005001312-d4b1ae081e3b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= +golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210825183410-e898025ed96a/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1077,10 +1525,15 @@ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1097,7 +1550,9 @@ golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1113,12 +1568,15 @@ golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190812073006-9eafafc0a87e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1131,6 +1589,7 @@ golang.org/x/sys v0.0.0-20191210023423-ac6580df4449/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1140,8 +1599,8 @@ golang.org/x/sys v0.0.0-20200217220822-9197077df867/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200327173247-9dae0f8f5775/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1177,24 +1636,47 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210331175145-43e1dd70ce54/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210426230700-d19ff857e887/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210820121016-41cdb8703e55/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210910150752-751e447fb3d0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211004093028-2c5d950f24ef/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 h1:2B5p2L5IfGiD7+b9BOoRMC6DgObAVZV+Fsp050NqXik= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210903071746-97244b99971b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210906170528-6f6e22806c34/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210915083310-ed5796bab164/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 h1:xHms4gcpe1YE7A3yIllJXP16CMAGuqwO2lX1mTyyRRc= +golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= +golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1209,16 +1691,26 @@ golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxb golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e h1:EHBhcS0mlXEAVwNyO2dLfjToGsyY4j24pTs2ScHnX7s= +golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac h1:7zkz7BUtwNFFqcowJ+RIgu2MaV/MapERkDIy+mwPyjs= +golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181011042414-1f849cf54d09/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190110163146-51295c7ec13a/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190307163923-6a08e3108db3/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190311215038-5c2858a9cfe5/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190321232350-e250d351ecad/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190322203728-c1a832b0ad89/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= @@ -1228,18 +1720,28 @@ golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190706070813-72ffa07ba3db/go.mod h1:jcCCGcm9btYwXyDqrUWc6MKQKKGJCWEQ3AfLSRIbEuI= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190910044552-dd2b5c81c578/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190916130336-e45ffcd953cc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117220505-0cba7a3a9ee9/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= @@ -1249,35 +1751,71 @@ golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200324003944-a576cf524670/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200414032229-332987a829c3/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200426102838-f3a5411a4c3b/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200505023115-26f46d2f7ef8/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200616133436-c1934b75d054/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200622203043-20e05c1c8ffa/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200624225443-88f3c62a19ff/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200625211823-6506e20df31f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200626171337-aa94e735be7f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200630154851-b2d8b0336632/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200706234117-b22de6825cf7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200711155855-7342f9734a7d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200812195022-5ae4c3c160a0/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200820010801-b793a1359eac/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200831203904-5a2aa26beb65/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20200916195026-c9a70fc28ce3/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201001104356-43ebab892c4c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201002184944-ecd9fd270d5d/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201023174141-c8cfbd0f21e6/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201028025901-8cd080b735b3/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201114224030-61ea331ec02b/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201118003311-bd56c0adb394/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201230224404-63754364767c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210101214203-2dba1e4ea05c/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210104081019-d8d6ddbec6ee/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1-0.20210205202024-ef80cdb6ec6d/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= +golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.6/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.0.0-20160322025152-9bf6e6e569ff/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.10.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= @@ -1296,15 +1834,24 @@ google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjR google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= google.golang.org/api v0.44.0/go.mod h1:EBOGZqzyhtvMDoxwS97ctnh0zUmYY6CxqXsc1AvkYD8= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.2/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/cloud v0.0.0-20151119220103-975617b05ea8/go.mod h1:0H1ncTHf11KCFhTc/+EFRbzSCOZx+VUbRMk55Yv5MYk= +google.golang.org/genproto v0.0.0-20170818010345-ee236bd376b0/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20181107211654-5fc9ac540362/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= @@ -1313,6 +1860,7 @@ google.golang.org/genproto v0.0.0-20190522204451-c2c4e71fbf69/go.mod h1:z3L6/3dT google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= @@ -1327,12 +1875,16 @@ google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfG google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200527145253-8367513e4ece/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200626011028-ee7919e894b5/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200707001353-8e8330bf89df/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= @@ -1348,10 +1900,24 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= -google.golang.org/genproto v0.0.0-20211005153810-c76a74d43a8e h1:Im71rbA1N3CbIag/PumYhQcNR8bLNmuOtRIyOnnLsT8= -google.golang.org/genproto v0.0.0-20211005153810-c76a74d43a8e/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8 h1:U9V52f6rAgINH7kT+musA1qF8kWyVOxzF8eYuOVuFwQ= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= +google.golang.org/grpc v1.8.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -1364,6 +1930,7 @@ google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8 google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.0/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= @@ -1374,10 +1941,17 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= -google.golang.org/grpc v1.41.0 h1:f+PlOh7QV4iIJkPrx5NQ7qaNGFQ3OTse67yaDHfju4E= -google.golang.org/grpc v1.41.0/go.mod h1:U3l9uK9J0sini8mHphKoXyaqDA/8VyGnDee1zzIUK6k= +google.golang.org/grpc v1.42.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.43.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.44.0 h1:weqSxi/TMs1SqFRMHCtBgXRs8k3X39QIDEZ0pRcttUg= +google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -1390,24 +1964,28 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20141024133853-64131543e789/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= +gopkg.in/cheggaaa/pb.v1 v1.0.28/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.63.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= @@ -1416,12 +1994,14 @@ gopkg.in/square/go-jose.v2 v2.5.1 h1:7odma5RETjNHWJnR32wx8t+Io4djHE1PqxCFx3iiZ2w gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.6/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= @@ -1442,43 +2022,65 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.2.1/go.mod h1:lPVVZ2BS5TfnjLyizF7o7hv7j9/L+8cZY2hLyjP9cGY= k8s.io/api v0.20.1/go.mod h1:KqwcCVogGxQY3nBlRpwt+wpAMF/KjaCc7RpywacvqUo= k8s.io/api v0.20.4/go.mod h1:++lNL1AJMkDymriNniQsWRkMDzRaX2Y/POTUi8yvqYQ= k8s.io/api v0.20.6/go.mod h1:X9e8Qag6JV/bL5G6bU8sdVRltWKmdHsFUGS3eVndqE8= -k8s.io/api v0.22.1/go.mod h1:bh13rkTp3F1XEaLGykbyRD2QaTTzPm0e/BMd8ptFONY= +k8s.io/api v0.22.5/go.mod h1:mEhXyLaSD1qTOf40rRiKXkc+2iCem09rWLlFwhCEiAs= k8s.io/apimachinery v0.20.1/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= k8s.io/apimachinery v0.20.4/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= k8s.io/apimachinery v0.20.6/go.mod h1:ejZXtW1Ra6V1O5H8xPBGz+T3+4gfkTCeExAHKU57MAc= k8s.io/apimachinery v0.22.1/go.mod h1:O3oNtNadZdeOMxHFVxOreoznohCpy0z6mocxbZr7oJ0= +k8s.io/apimachinery v0.22.5/go.mod h1:xziclGKwuuJ2RM5/rSFQSYAj0zdbci3DH8kj+WvyN0U= k8s.io/apiserver v0.20.1/go.mod h1:ro5QHeQkgMS7ZGpvf4tSMx6bBOgPfE+f52KwvXfScaU= k8s.io/apiserver v0.20.4/go.mod h1:Mc80thBKOyy7tbvFtB4kJv1kbdD0eIH8k8vianJcbFM= k8s.io/apiserver v0.20.6/go.mod h1:QIJXNt6i6JB+0YQRNcS0hdRHJlMhflFmsBDeSgT1r8Q= +k8s.io/apiserver v0.22.5/go.mod h1:s2WbtgZAkTKt679sYtSudEQrTGWUSQAPe6MupLnlmaQ= k8s.io/client-go v0.20.1/go.mod h1:/zcHdt1TeWSd5HoUe6elJmHSQ6uLLgp4bIJHVEuy+/Y= k8s.io/client-go v0.20.4/go.mod h1:LiMv25ND1gLUdBeYxBIwKpkSC5IsozMMmOOeSJboP+k= k8s.io/client-go v0.20.6/go.mod h1:nNQMnOvEUEsOzRRFIIkdmYOjAZrC8bgq0ExboWSU1I0= +k8s.io/client-go v0.22.5/go.mod h1:cs6yf/61q2T1SdQL5Rdcjg9J1ElXSwbjSrW2vFImM4Y= +k8s.io/code-generator v0.19.7/go.mod h1:lwEq3YnLYb/7uVXLorOJfxg+cUu2oihFhHZ0n9NIla0= k8s.io/component-base v0.20.1/go.mod h1:guxkoJnNoh8LNrbtiQOlyp2Y2XFCZQmrcg2n/DeYNLk= k8s.io/component-base v0.20.4/go.mod h1:t4p9EdiagbVCJKrQ1RsA5/V4rFQNDfRlevJajlGwgjI= k8s.io/component-base v0.20.6/go.mod h1:6f1MPBAeI+mvuts3sIdtpjljHWBQ2cIy38oBIWMYnrM= +k8s.io/component-base v0.22.5/go.mod h1:VK3I+TjuF9eaa+Ln67dKxhGar5ynVbwnGrUiNF4MqCI= k8s.io/cri-api v0.17.3/go.mod h1:X1sbHmuXhwaHs9xxYffLqJogVsnI+f6cPRcgPel7ywM= k8s.io/cri-api v0.20.1/go.mod h1:2JRbKt+BFLTjtrILYVqQK5jqhI+XNdF6UiGMgczeBCI= k8s.io/cri-api v0.20.4/go.mod h1:2JRbKt+BFLTjtrILYVqQK5jqhI+XNdF6UiGMgczeBCI= k8s.io/cri-api v0.20.6/go.mod h1:ew44AjNXwyn1s0U4xCKGodU7J1HzBeZ1MpGrpa5r8Yc= +k8s.io/cri-api v0.23.1/go.mod h1:REJE3PSU0h/LOV1APBrupxrEJqnoxZC8KWzkBUHwrK4= k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/gengo v0.0.0-20200428234225-8167cfdcfc14/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/gengo v0.0.0-20201113003025-83324d819ded/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= +k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.9.0/go.mod h1:hy9LJ/NvuK+iVyP4Ehqva4HxZG/oXyIS3n3Jmire4Ec= +k8s.io/klog/v2 v2.30.0/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= +k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o= k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAGcJo0Tvi+dK12EcqSLqcWsryKMpfM= k8s.io/kube-openapi v0.0.0-20210421082810-95288971da7e/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw= +k8s.io/kube-openapi v0.0.0-20211109043538-20434351676c/go.mod h1:vHXdDvt9+2spS2Rx9ql3I8tycm3H9FDfdUoIuKCefvw= k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= k8s.io/utils v0.0.0-20201110183641-67b214c5f920/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20210819203725-bdf08cb9a70a/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +mvdan.cc/gofumpt v0.1.1/go.mod h1:yXG1r1WqZVKWbVRtBWKWX9+CxGYfA51nSomhM0woR48= +mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed/go.mod h1:Xkxe497xwlCKkIaQYRfC7CSLworTXY9RMqwhhCm+8Nc= +mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b/go.mod h1:2odslEg/xrtNQqCYg2/jCoyKnw3vv5biOc3JnIcYfL4= +mvdan.cc/unparam v0.0.0-20210104141923-aac4ce9116a7/go.mod h1:hBpJkZE8H/sb+VRFvw2+rBpHNsTBcvSpk61hr8mzXZE= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.15/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.22/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= +sigs.k8s.io/structured-merge-diff/v4 v4.0.1/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.0.3/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= sigs.k8s.io/structured-merge-diff/v4 v4.1.2/go.mod h1:j/nl6xW8vLS49O8YvXW1ocPhZawJtm+Yrr7PPRQ0Vg4= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= +sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8= diff --git a/main.go b/main.go index a9f7382..1e23e50 100644 --- a/main.go +++ b/main.go @@ -5,10 +5,10 @@ import ( "fmt" "os" - "github.com/containers/podman/v3/pkg/bindings" - "github.com/containers/podman/v3/pkg/bindings/containers" - "github.com/containers/podman/v3/pkg/bindings/images" - "github.com/containers/podman/v3/pkg/specgen" + "github.com/containers/podman/v4/pkg/bindings" + "github.com/containers/podman/v4/pkg/bindings/containers" + "github.com/containers/podman/v4/pkg/bindings/images" + "github.com/containers/podman/v4/pkg/specgen" ) func main() { @@ -64,5 +64,4 @@ func main() { } else { fmt.Println(path) }*/ - } diff --git a/main.go_ b/main.go_ new file mode 100644 index 0000000..873079f --- /dev/null +++ b/main.go_ @@ -0,0 +1,68 @@ +package main + +import ( + "context" + "fmt" + "os" + + "github.com/containers/podman/v4/pkg/bindings" + "github.com/containers/podman/v4/pkg/bindings/containers" + "github.com/containers/podman/v4/pkg/bindings/images" + "github.com/containers/podman/v4/pkg/specgen" +) + +func main() { + fmt.Println("podman test 시작") + + // Get Podman socket location + sock_dir := os.Getenv("XDG_RUNTIME_DIR") + if sock_dir == "" { + sock_dir = "/var/run" + } + socket := "unix:" + sock_dir + "/podman/podman.sock" + + // Connect to Podman socket + ctx, err := bindings.NewConnection(context.Background(), socket) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + centos := "cent" + // container 를 생성해주는데 여기서 bind mount 관련 설정이 있는 듯하다. + // https://sourcegraph.com/github.com/containers/podman/-/blob/pkg/specgenutil/specgenutil_test.go?L16 참고해서 일단 test 를 해보자. + // https://sourcegraph.com/search?q=context:global+specgen.NewSpecGenerator&patternType=literal + s := specgen.NewSpecGenerator(centos, false) + s.Terminal = true + r, err := containers.CreateWithSpec(ctx, s, &containers.CreateOptions{}) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + // Pull Busybox image (Sample 1) + fmt.Println("Pulling Busybox image...") + _, err = images.Pull(ctx, "docker.io/busybox", &images.PullOptions{}) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + // Container start + fmt.Println("centos latest start") + + err = containers.Start(ctx, r.ID, &containers.StartOptions{}) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + /* path, err1 := containers.Mount(ctx, centos, &containers.MountOptions{}) + + if err1 != nil { + fmt.Println(err) + os.Exit(1) + } else { + fmt.Println(path) + }*/ + +} diff --git a/types/service.go b/types/service.go index bcfb9b3..443fd5b 100644 --- a/types/service.go +++ b/types/service.go @@ -6,10 +6,11 @@ import ( "log" "strconv" - nettypes "github.com/containers/podman/v3/libpod/network/types" - "github.com/containers/podman/v3/pkg/bindings/containers" - "github.com/containers/podman/v3/pkg/bindings/images" - "github.com/containers/podman/v3/pkg/specgen" + nettypes "github.com/containers/common/libnetwork/types" + + "github.com/containers/podman/v4/pkg/bindings/containers" + "github.com/containers/podman/v4/pkg/bindings/images" + "github.com/containers/podman/v4/pkg/specgen" ) var ( @@ -32,7 +33,7 @@ type Service struct { } // CreateContainer method creates a new container with using a given image pulled by PullImage method. -// main.go 와 비교해보자. +// main.go_ 와 비교해보자. // containerExistsOptions return 값인 거 같은데 어떻게 사용되는지 디버깅 해보자. func (service *Service) CreateContainer(connText *context.Context) (containerID string) { // types.go 참고.