mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-13 10:33:35 +00:00
build: move e2e dependencies into e2e/go.mod
Several packages are only used while running the e2e suite. These packages are less important to update, as the they can not influence the final executable that is part of the Ceph-CSI container-image. By moving these dependencies out of the main Ceph-CSI go.mod, it is easier to identify if a reported CVE affects Ceph-CSI, or only the testing (like most of the Kubernetes CVEs). Signed-off-by: Niels de Vos <ndevos@ibm.com>
This commit is contained in:
committed by
mergify[bot]
parent
15da101b1b
commit
bec6090996
202
e2e/vendor/k8s.io/utils/LICENSE
generated
vendored
Normal file
202
e2e/vendor/k8s.io/utils/LICENSE
generated
vendored
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
72
e2e/vendor/k8s.io/utils/buffer/ring_growing.go
generated
vendored
Normal file
72
e2e/vendor/k8s.io/utils/buffer/ring_growing.go
generated
vendored
Normal file
@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package buffer
|
||||
|
||||
// RingGrowing is a growing ring buffer.
|
||||
// Not thread safe.
|
||||
type RingGrowing struct {
|
||||
data []interface{}
|
||||
n int // Size of Data
|
||||
beg int // First available element
|
||||
readable int // Number of data items available
|
||||
}
|
||||
|
||||
// NewRingGrowing constructs a new RingGrowing instance with provided parameters.
|
||||
func NewRingGrowing(initialSize int) *RingGrowing {
|
||||
return &RingGrowing{
|
||||
data: make([]interface{}, initialSize),
|
||||
n: initialSize,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOne reads (consumes) first item from the buffer if it is available, otherwise returns false.
|
||||
func (r *RingGrowing) ReadOne() (data interface{}, ok bool) {
|
||||
if r.readable == 0 {
|
||||
return nil, false
|
||||
}
|
||||
r.readable--
|
||||
element := r.data[r.beg]
|
||||
r.data[r.beg] = nil // Remove reference to the object to help GC
|
||||
if r.beg == r.n-1 {
|
||||
// Was the last element
|
||||
r.beg = 0
|
||||
} else {
|
||||
r.beg++
|
||||
}
|
||||
return element, true
|
||||
}
|
||||
|
||||
// WriteOne adds an item to the end of the buffer, growing it if it is full.
|
||||
func (r *RingGrowing) WriteOne(data interface{}) {
|
||||
if r.readable == r.n {
|
||||
// Time to grow
|
||||
newN := r.n * 2
|
||||
newData := make([]interface{}, newN)
|
||||
to := r.beg + r.readable
|
||||
if to <= r.n {
|
||||
copy(newData, r.data[r.beg:to])
|
||||
} else {
|
||||
copied := copy(newData, r.data[r.beg:])
|
||||
copy(newData[copied:], r.data[:(to%r.n)])
|
||||
}
|
||||
r.beg = 0
|
||||
r.data = newData
|
||||
r.n = newN
|
||||
}
|
||||
r.data[(r.readable+r.beg)%r.n] = data
|
||||
r.readable++
|
||||
}
|
4
e2e/vendor/k8s.io/utils/clock/README.md
generated
vendored
Normal file
4
e2e/vendor/k8s.io/utils/clock/README.md
generated
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# Clock
|
||||
|
||||
This package provides an interface for time-based operations. It allows
|
||||
mocking time for testing.
|
178
e2e/vendor/k8s.io/utils/clock/clock.go
generated
vendored
Normal file
178
e2e/vendor/k8s.io/utils/clock/clock.go
generated
vendored
Normal file
@ -0,0 +1,178 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package clock
|
||||
|
||||
import "time"
|
||||
|
||||
// PassiveClock allows for injecting fake or real clocks into code
|
||||
// that needs to read the current time but does not support scheduling
|
||||
// activity in the future.
|
||||
type PassiveClock interface {
|
||||
Now() time.Time
|
||||
Since(time.Time) time.Duration
|
||||
}
|
||||
|
||||
// Clock allows for injecting fake or real clocks into code that
|
||||
// needs to do arbitrary things based on time.
|
||||
type Clock interface {
|
||||
PassiveClock
|
||||
// After returns the channel of a new Timer.
|
||||
// This method does not allow to free/GC the backing timer before it fires. Use
|
||||
// NewTimer instead.
|
||||
After(d time.Duration) <-chan time.Time
|
||||
// NewTimer returns a new Timer.
|
||||
NewTimer(d time.Duration) Timer
|
||||
// Sleep sleeps for the provided duration d.
|
||||
// Consider making the sleep interruptible by using 'select' on a context channel and a timer channel.
|
||||
Sleep(d time.Duration)
|
||||
// Tick returns the channel of a new Ticker.
|
||||
// This method does not allow to free/GC the backing ticker. Use
|
||||
// NewTicker from WithTicker instead.
|
||||
Tick(d time.Duration) <-chan time.Time
|
||||
}
|
||||
|
||||
// WithTicker allows for injecting fake or real clocks into code that
|
||||
// needs to do arbitrary things based on time.
|
||||
type WithTicker interface {
|
||||
Clock
|
||||
// NewTicker returns a new Ticker.
|
||||
NewTicker(time.Duration) Ticker
|
||||
}
|
||||
|
||||
// WithDelayedExecution allows for injecting fake or real clocks into
|
||||
// code that needs to make use of AfterFunc functionality.
|
||||
type WithDelayedExecution interface {
|
||||
Clock
|
||||
// AfterFunc executes f in its own goroutine after waiting
|
||||
// for d duration and returns a Timer whose channel can be
|
||||
// closed by calling Stop() on the Timer.
|
||||
AfterFunc(d time.Duration, f func()) Timer
|
||||
}
|
||||
|
||||
// WithTickerAndDelayedExecution allows for injecting fake or real clocks
|
||||
// into code that needs Ticker and AfterFunc functionality
|
||||
type WithTickerAndDelayedExecution interface {
|
||||
WithTicker
|
||||
// AfterFunc executes f in its own goroutine after waiting
|
||||
// for d duration and returns a Timer whose channel can be
|
||||
// closed by calling Stop() on the Timer.
|
||||
AfterFunc(d time.Duration, f func()) Timer
|
||||
}
|
||||
|
||||
// Ticker defines the Ticker interface.
|
||||
type Ticker interface {
|
||||
C() <-chan time.Time
|
||||
Stop()
|
||||
}
|
||||
|
||||
var _ = WithTicker(RealClock{})
|
||||
|
||||
// RealClock really calls time.Now()
|
||||
type RealClock struct{}
|
||||
|
||||
// Now returns the current time.
|
||||
func (RealClock) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// Since returns time since the specified timestamp.
|
||||
func (RealClock) Since(ts time.Time) time.Duration {
|
||||
return time.Since(ts)
|
||||
}
|
||||
|
||||
// After is the same as time.After(d).
|
||||
// This method does not allow to free/GC the backing timer before it fires. Use
|
||||
// NewTimer instead.
|
||||
func (RealClock) After(d time.Duration) <-chan time.Time {
|
||||
return time.After(d)
|
||||
}
|
||||
|
||||
// NewTimer is the same as time.NewTimer(d)
|
||||
func (RealClock) NewTimer(d time.Duration) Timer {
|
||||
return &realTimer{
|
||||
timer: time.NewTimer(d),
|
||||
}
|
||||
}
|
||||
|
||||
// AfterFunc is the same as time.AfterFunc(d, f).
|
||||
func (RealClock) AfterFunc(d time.Duration, f func()) Timer {
|
||||
return &realTimer{
|
||||
timer: time.AfterFunc(d, f),
|
||||
}
|
||||
}
|
||||
|
||||
// Tick is the same as time.Tick(d)
|
||||
// This method does not allow to free/GC the backing ticker. Use
|
||||
// NewTicker instead.
|
||||
func (RealClock) Tick(d time.Duration) <-chan time.Time {
|
||||
return time.Tick(d)
|
||||
}
|
||||
|
||||
// NewTicker returns a new Ticker.
|
||||
func (RealClock) NewTicker(d time.Duration) Ticker {
|
||||
return &realTicker{
|
||||
ticker: time.NewTicker(d),
|
||||
}
|
||||
}
|
||||
|
||||
// Sleep is the same as time.Sleep(d)
|
||||
// Consider making the sleep interruptible by using 'select' on a context channel and a timer channel.
|
||||
func (RealClock) Sleep(d time.Duration) {
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
||||
// Timer allows for injecting fake or real timers into code that
|
||||
// needs to do arbitrary things based on time.
|
||||
type Timer interface {
|
||||
C() <-chan time.Time
|
||||
Stop() bool
|
||||
Reset(d time.Duration) bool
|
||||
}
|
||||
|
||||
var _ = Timer(&realTimer{})
|
||||
|
||||
// realTimer is backed by an actual time.Timer.
|
||||
type realTimer struct {
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
// C returns the underlying timer's channel.
|
||||
func (r *realTimer) C() <-chan time.Time {
|
||||
return r.timer.C
|
||||
}
|
||||
|
||||
// Stop calls Stop() on the underlying timer.
|
||||
func (r *realTimer) Stop() bool {
|
||||
return r.timer.Stop()
|
||||
}
|
||||
|
||||
// Reset calls Reset() on the underlying timer.
|
||||
func (r *realTimer) Reset(d time.Duration) bool {
|
||||
return r.timer.Reset(d)
|
||||
}
|
||||
|
||||
type realTicker struct {
|
||||
ticker *time.Ticker
|
||||
}
|
||||
|
||||
func (r *realTicker) C() <-chan time.Time {
|
||||
return r.ticker.C
|
||||
}
|
||||
|
||||
func (r *realTicker) Stop() {
|
||||
r.ticker.Stop()
|
||||
}
|
362
e2e/vendor/k8s.io/utils/clock/testing/fake_clock.go
generated
vendored
Normal file
362
e2e/vendor/k8s.io/utils/clock/testing/fake_clock.go
generated
vendored
Normal file
@ -0,0 +1,362 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package testing
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"k8s.io/utils/clock"
|
||||
)
|
||||
|
||||
var (
|
||||
_ = clock.PassiveClock(&FakePassiveClock{})
|
||||
_ = clock.WithTicker(&FakeClock{})
|
||||
_ = clock.Clock(&IntervalClock{})
|
||||
)
|
||||
|
||||
// FakePassiveClock implements PassiveClock, but returns an arbitrary time.
|
||||
type FakePassiveClock struct {
|
||||
lock sync.RWMutex
|
||||
time time.Time
|
||||
}
|
||||
|
||||
// FakeClock implements clock.Clock, but returns an arbitrary time.
|
||||
type FakeClock struct {
|
||||
FakePassiveClock
|
||||
|
||||
// waiters are waiting for the fake time to pass their specified time
|
||||
waiters []*fakeClockWaiter
|
||||
}
|
||||
|
||||
type fakeClockWaiter struct {
|
||||
targetTime time.Time
|
||||
stepInterval time.Duration
|
||||
skipIfBlocked bool
|
||||
destChan chan time.Time
|
||||
afterFunc func()
|
||||
}
|
||||
|
||||
// NewFakePassiveClock returns a new FakePassiveClock.
|
||||
func NewFakePassiveClock(t time.Time) *FakePassiveClock {
|
||||
return &FakePassiveClock{
|
||||
time: t,
|
||||
}
|
||||
}
|
||||
|
||||
// NewFakeClock constructs a fake clock set to the provided time.
|
||||
func NewFakeClock(t time.Time) *FakeClock {
|
||||
return &FakeClock{
|
||||
FakePassiveClock: *NewFakePassiveClock(t),
|
||||
}
|
||||
}
|
||||
|
||||
// Now returns f's time.
|
||||
func (f *FakePassiveClock) Now() time.Time {
|
||||
f.lock.RLock()
|
||||
defer f.lock.RUnlock()
|
||||
return f.time
|
||||
}
|
||||
|
||||
// Since returns time since the time in f.
|
||||
func (f *FakePassiveClock) Since(ts time.Time) time.Duration {
|
||||
f.lock.RLock()
|
||||
defer f.lock.RUnlock()
|
||||
return f.time.Sub(ts)
|
||||
}
|
||||
|
||||
// SetTime sets the time on the FakePassiveClock.
|
||||
func (f *FakePassiveClock) SetTime(t time.Time) {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
f.time = t
|
||||
}
|
||||
|
||||
// After is the fake version of time.After(d).
|
||||
func (f *FakeClock) After(d time.Duration) <-chan time.Time {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
stopTime := f.time.Add(d)
|
||||
ch := make(chan time.Time, 1) // Don't block!
|
||||
f.waiters = append(f.waiters, &fakeClockWaiter{
|
||||
targetTime: stopTime,
|
||||
destChan: ch,
|
||||
})
|
||||
return ch
|
||||
}
|
||||
|
||||
// NewTimer constructs a fake timer, akin to time.NewTimer(d).
|
||||
func (f *FakeClock) NewTimer(d time.Duration) clock.Timer {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
stopTime := f.time.Add(d)
|
||||
ch := make(chan time.Time, 1) // Don't block!
|
||||
timer := &fakeTimer{
|
||||
fakeClock: f,
|
||||
waiter: fakeClockWaiter{
|
||||
targetTime: stopTime,
|
||||
destChan: ch,
|
||||
},
|
||||
}
|
||||
f.waiters = append(f.waiters, &timer.waiter)
|
||||
return timer
|
||||
}
|
||||
|
||||
// AfterFunc is the Fake version of time.AfterFunc(d, cb).
|
||||
func (f *FakeClock) AfterFunc(d time.Duration, cb func()) clock.Timer {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
stopTime := f.time.Add(d)
|
||||
ch := make(chan time.Time, 1) // Don't block!
|
||||
|
||||
timer := &fakeTimer{
|
||||
fakeClock: f,
|
||||
waiter: fakeClockWaiter{
|
||||
targetTime: stopTime,
|
||||
destChan: ch,
|
||||
afterFunc: cb,
|
||||
},
|
||||
}
|
||||
f.waiters = append(f.waiters, &timer.waiter)
|
||||
return timer
|
||||
}
|
||||
|
||||
// Tick constructs a fake ticker, akin to time.Tick
|
||||
func (f *FakeClock) Tick(d time.Duration) <-chan time.Time {
|
||||
if d <= 0 {
|
||||
return nil
|
||||
}
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
tickTime := f.time.Add(d)
|
||||
ch := make(chan time.Time, 1) // hold one tick
|
||||
f.waiters = append(f.waiters, &fakeClockWaiter{
|
||||
targetTime: tickTime,
|
||||
stepInterval: d,
|
||||
skipIfBlocked: true,
|
||||
destChan: ch,
|
||||
})
|
||||
|
||||
return ch
|
||||
}
|
||||
|
||||
// NewTicker returns a new Ticker.
|
||||
func (f *FakeClock) NewTicker(d time.Duration) clock.Ticker {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
tickTime := f.time.Add(d)
|
||||
ch := make(chan time.Time, 1) // hold one tick
|
||||
f.waiters = append(f.waiters, &fakeClockWaiter{
|
||||
targetTime: tickTime,
|
||||
stepInterval: d,
|
||||
skipIfBlocked: true,
|
||||
destChan: ch,
|
||||
})
|
||||
|
||||
return &fakeTicker{
|
||||
c: ch,
|
||||
}
|
||||
}
|
||||
|
||||
// Step moves the clock by Duration and notifies anyone that's called After,
|
||||
// Tick, or NewTimer.
|
||||
func (f *FakeClock) Step(d time.Duration) {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
f.setTimeLocked(f.time.Add(d))
|
||||
}
|
||||
|
||||
// SetTime sets the time.
|
||||
func (f *FakeClock) SetTime(t time.Time) {
|
||||
f.lock.Lock()
|
||||
defer f.lock.Unlock()
|
||||
f.setTimeLocked(t)
|
||||
}
|
||||
|
||||
// Actually changes the time and checks any waiters. f must be write-locked.
|
||||
func (f *FakeClock) setTimeLocked(t time.Time) {
|
||||
f.time = t
|
||||
newWaiters := make([]*fakeClockWaiter, 0, len(f.waiters))
|
||||
for i := range f.waiters {
|
||||
w := f.waiters[i]
|
||||
if !w.targetTime.After(t) {
|
||||
if w.skipIfBlocked {
|
||||
select {
|
||||
case w.destChan <- t:
|
||||
default:
|
||||
}
|
||||
} else {
|
||||
w.destChan <- t
|
||||
}
|
||||
|
||||
if w.afterFunc != nil {
|
||||
w.afterFunc()
|
||||
}
|
||||
|
||||
if w.stepInterval > 0 {
|
||||
for !w.targetTime.After(t) {
|
||||
w.targetTime = w.targetTime.Add(w.stepInterval)
|
||||
}
|
||||
newWaiters = append(newWaiters, w)
|
||||
}
|
||||
|
||||
} else {
|
||||
newWaiters = append(newWaiters, f.waiters[i])
|
||||
}
|
||||
}
|
||||
f.waiters = newWaiters
|
||||
}
|
||||
|
||||
// HasWaiters returns true if After or AfterFunc has been called on f but not yet satisfied (so you can
|
||||
// write race-free tests).
|
||||
func (f *FakeClock) HasWaiters() bool {
|
||||
f.lock.RLock()
|
||||
defer f.lock.RUnlock()
|
||||
return len(f.waiters) > 0
|
||||
}
|
||||
|
||||
// Sleep is akin to time.Sleep
|
||||
func (f *FakeClock) Sleep(d time.Duration) {
|
||||
f.Step(d)
|
||||
}
|
||||
|
||||
// IntervalClock implements clock.PassiveClock, but each invocation of Now steps the clock forward the specified duration.
|
||||
// IntervalClock technically implements the other methods of clock.Clock, but each implementation is just a panic.
|
||||
//
|
||||
// Deprecated: See SimpleIntervalClock for an alternative that only has the methods of PassiveClock.
|
||||
type IntervalClock struct {
|
||||
Time time.Time
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// Now returns i's time.
|
||||
func (i *IntervalClock) Now() time.Time {
|
||||
i.Time = i.Time.Add(i.Duration)
|
||||
return i.Time
|
||||
}
|
||||
|
||||
// Since returns time since the time in i.
|
||||
func (i *IntervalClock) Since(ts time.Time) time.Duration {
|
||||
return i.Time.Sub(ts)
|
||||
}
|
||||
|
||||
// After is unimplemented, will panic.
|
||||
// TODO: make interval clock use FakeClock so this can be implemented.
|
||||
func (*IntervalClock) After(d time.Duration) <-chan time.Time {
|
||||
panic("IntervalClock doesn't implement After")
|
||||
}
|
||||
|
||||
// NewTimer is unimplemented, will panic.
|
||||
// TODO: make interval clock use FakeClock so this can be implemented.
|
||||
func (*IntervalClock) NewTimer(d time.Duration) clock.Timer {
|
||||
panic("IntervalClock doesn't implement NewTimer")
|
||||
}
|
||||
|
||||
// AfterFunc is unimplemented, will panic.
|
||||
// TODO: make interval clock use FakeClock so this can be implemented.
|
||||
func (*IntervalClock) AfterFunc(d time.Duration, f func()) clock.Timer {
|
||||
panic("IntervalClock doesn't implement AfterFunc")
|
||||
}
|
||||
|
||||
// Tick is unimplemented, will panic.
|
||||
// TODO: make interval clock use FakeClock so this can be implemented.
|
||||
func (*IntervalClock) Tick(d time.Duration) <-chan time.Time {
|
||||
panic("IntervalClock doesn't implement Tick")
|
||||
}
|
||||
|
||||
// NewTicker has no implementation yet and is omitted.
|
||||
// TODO: make interval clock use FakeClock so this can be implemented.
|
||||
func (*IntervalClock) NewTicker(d time.Duration) clock.Ticker {
|
||||
panic("IntervalClock doesn't implement NewTicker")
|
||||
}
|
||||
|
||||
// Sleep is unimplemented, will panic.
|
||||
func (*IntervalClock) Sleep(d time.Duration) {
|
||||
panic("IntervalClock doesn't implement Sleep")
|
||||
}
|
||||
|
||||
var _ = clock.Timer(&fakeTimer{})
|
||||
|
||||
// fakeTimer implements clock.Timer based on a FakeClock.
|
||||
type fakeTimer struct {
|
||||
fakeClock *FakeClock
|
||||
waiter fakeClockWaiter
|
||||
}
|
||||
|
||||
// C returns the channel that notifies when this timer has fired.
|
||||
func (f *fakeTimer) C() <-chan time.Time {
|
||||
return f.waiter.destChan
|
||||
}
|
||||
|
||||
// Stop prevents the Timer from firing. It returns true if the call stops the
|
||||
// timer, false if the timer has already expired or been stopped.
|
||||
func (f *fakeTimer) Stop() bool {
|
||||
f.fakeClock.lock.Lock()
|
||||
defer f.fakeClock.lock.Unlock()
|
||||
|
||||
active := false
|
||||
newWaiters := make([]*fakeClockWaiter, 0, len(f.fakeClock.waiters))
|
||||
for i := range f.fakeClock.waiters {
|
||||
w := f.fakeClock.waiters[i]
|
||||
if w != &f.waiter {
|
||||
newWaiters = append(newWaiters, w)
|
||||
continue
|
||||
}
|
||||
// If timer is found, it has not been fired yet.
|
||||
active = true
|
||||
}
|
||||
|
||||
f.fakeClock.waiters = newWaiters
|
||||
|
||||
return active
|
||||
}
|
||||
|
||||
// Reset changes the timer to expire after duration d. It returns true if the
|
||||
// timer had been active, false if the timer had expired or been stopped.
|
||||
func (f *fakeTimer) Reset(d time.Duration) bool {
|
||||
f.fakeClock.lock.Lock()
|
||||
defer f.fakeClock.lock.Unlock()
|
||||
|
||||
active := false
|
||||
|
||||
f.waiter.targetTime = f.fakeClock.time.Add(d)
|
||||
|
||||
for i := range f.fakeClock.waiters {
|
||||
w := f.fakeClock.waiters[i]
|
||||
if w == &f.waiter {
|
||||
// If timer is found, it has not been fired yet.
|
||||
active = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !active {
|
||||
f.fakeClock.waiters = append(f.fakeClock.waiters, &f.waiter)
|
||||
}
|
||||
|
||||
return active
|
||||
}
|
||||
|
||||
type fakeTicker struct {
|
||||
c <-chan time.Time
|
||||
}
|
||||
|
||||
func (t *fakeTicker) C() <-chan time.Time {
|
||||
return t.c
|
||||
}
|
||||
|
||||
func (t *fakeTicker) Stop() {
|
||||
}
|
44
e2e/vendor/k8s.io/utils/clock/testing/simple_interval_clock.go
generated
vendored
Normal file
44
e2e/vendor/k8s.io/utils/clock/testing/simple_interval_clock.go
generated
vendored
Normal file
@ -0,0 +1,44 @@
|
||||
/*
|
||||
Copyright 2021 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package testing
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"k8s.io/utils/clock"
|
||||
)
|
||||
|
||||
var (
|
||||
_ = clock.PassiveClock(&SimpleIntervalClock{})
|
||||
)
|
||||
|
||||
// SimpleIntervalClock implements clock.PassiveClock, but each invocation of Now steps the clock forward the specified duration
|
||||
type SimpleIntervalClock struct {
|
||||
Time time.Time
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
// Now returns i's time.
|
||||
func (i *SimpleIntervalClock) Now() time.Time {
|
||||
i.Time = i.Time.Add(i.Duration)
|
||||
return i.Time
|
||||
}
|
||||
|
||||
// Since returns time since the time in i.
|
||||
func (i *SimpleIntervalClock) Since(ts time.Time) time.Duration {
|
||||
return i.Time.Sub(ts)
|
||||
}
|
8
e2e/vendor/k8s.io/utils/cpuset/OWNERS
generated
vendored
Normal file
8
e2e/vendor/k8s.io/utils/cpuset/OWNERS
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
approvers:
|
||||
- dchen1107
|
||||
- derekwaynecarr
|
||||
- ffromani
|
||||
- klueska
|
||||
- SergeyKanzhelev
|
256
e2e/vendor/k8s.io/utils/cpuset/cpuset.go
generated
vendored
Normal file
256
e2e/vendor/k8s.io/utils/cpuset/cpuset.go
generated
vendored
Normal file
@ -0,0 +1,256 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package cpuset represents a collection of CPUs in a 'set' data structure.
|
||||
//
|
||||
// It can be used to represent core IDs, hyper thread siblings, CPU nodes, or processor IDs.
|
||||
//
|
||||
// The only special thing about this package is that
|
||||
// methods are provided to convert back and forth from Linux 'list' syntax.
|
||||
// See http://man7.org/linux/man-pages/man7/cpuset.7.html#FORMATS for details.
|
||||
//
|
||||
// Future work can migrate this to use a 'set' library, and relax the dubious 'immutable' property.
|
||||
//
|
||||
// This package was originally developed in the 'kubernetes' repository.
|
||||
package cpuset
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CPUSet is a thread-safe, immutable set-like data structure for CPU IDs.
|
||||
type CPUSet struct {
|
||||
elems map[int]struct{}
|
||||
}
|
||||
|
||||
// New returns a new CPUSet containing the supplied elements.
|
||||
func New(cpus ...int) CPUSet {
|
||||
s := CPUSet{
|
||||
elems: map[int]struct{}{},
|
||||
}
|
||||
for _, c := range cpus {
|
||||
s.add(c)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// add adds the supplied elements to the CPUSet.
|
||||
// It is intended for internal use only, since it mutates the CPUSet.
|
||||
func (s CPUSet) add(elems ...int) {
|
||||
for _, elem := range elems {
|
||||
s.elems[elem] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// Size returns the number of elements in this set.
|
||||
func (s CPUSet) Size() int {
|
||||
return len(s.elems)
|
||||
}
|
||||
|
||||
// IsEmpty returns true if there are zero elements in this set.
|
||||
func (s CPUSet) IsEmpty() bool {
|
||||
return s.Size() == 0
|
||||
}
|
||||
|
||||
// Contains returns true if the supplied element is present in this set.
|
||||
func (s CPUSet) Contains(cpu int) bool {
|
||||
_, found := s.elems[cpu]
|
||||
return found
|
||||
}
|
||||
|
||||
// Equals returns true if the supplied set contains exactly the same elements
|
||||
// as this set (s IsSubsetOf s2 and s2 IsSubsetOf s).
|
||||
func (s CPUSet) Equals(s2 CPUSet) bool {
|
||||
return reflect.DeepEqual(s.elems, s2.elems)
|
||||
}
|
||||
|
||||
// filter returns a new CPU set that contains all of the elements from this
|
||||
// set that match the supplied predicate, without mutating the source set.
|
||||
func (s CPUSet) filter(predicate func(int) bool) CPUSet {
|
||||
r := New()
|
||||
for cpu := range s.elems {
|
||||
if predicate(cpu) {
|
||||
r.add(cpu)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// IsSubsetOf returns true if the supplied set contains all the elements
|
||||
func (s CPUSet) IsSubsetOf(s2 CPUSet) bool {
|
||||
result := true
|
||||
for cpu := range s.elems {
|
||||
if !s2.Contains(cpu) {
|
||||
result = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Union returns a new CPU set that contains all of the elements from this
|
||||
// set and all of the elements from the supplied sets, without mutating
|
||||
// either source set.
|
||||
func (s CPUSet) Union(s2 ...CPUSet) CPUSet {
|
||||
r := New()
|
||||
for cpu := range s.elems {
|
||||
r.add(cpu)
|
||||
}
|
||||
for _, cs := range s2 {
|
||||
for cpu := range cs.elems {
|
||||
r.add(cpu)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// Intersection returns a new CPU set that contains all of the elements
|
||||
// that are present in both this set and the supplied set, without mutating
|
||||
// either source set.
|
||||
func (s CPUSet) Intersection(s2 CPUSet) CPUSet {
|
||||
return s.filter(func(cpu int) bool { return s2.Contains(cpu) })
|
||||
}
|
||||
|
||||
// Difference returns a new CPU set that contains all of the elements that
|
||||
// are present in this set and not the supplied set, without mutating either
|
||||
// source set.
|
||||
func (s CPUSet) Difference(s2 CPUSet) CPUSet {
|
||||
return s.filter(func(cpu int) bool { return !s2.Contains(cpu) })
|
||||
}
|
||||
|
||||
// List returns a slice of integers that contains all elements from
|
||||
// this set. The list is sorted.
|
||||
func (s CPUSet) List() []int {
|
||||
result := s.UnsortedList()
|
||||
sort.Ints(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// UnsortedList returns a slice of integers that contains all elements from
|
||||
// this set.
|
||||
func (s CPUSet) UnsortedList() []int {
|
||||
result := make([]int, 0, len(s.elems))
|
||||
for cpu := range s.elems {
|
||||
result = append(result, cpu)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// String returns a new string representation of the elements in this CPU set
|
||||
// in canonical linux CPU list format.
|
||||
//
|
||||
// See: http://man7.org/linux/man-pages/man7/cpuset.7.html#FORMATS
|
||||
func (s CPUSet) String() string {
|
||||
if s.IsEmpty() {
|
||||
return ""
|
||||
}
|
||||
|
||||
elems := s.List()
|
||||
|
||||
type rng struct {
|
||||
start int
|
||||
end int
|
||||
}
|
||||
|
||||
ranges := []rng{{elems[0], elems[0]}}
|
||||
|
||||
for i := 1; i < len(elems); i++ {
|
||||
lastRange := &ranges[len(ranges)-1]
|
||||
// if this element is adjacent to the high end of the last range
|
||||
if elems[i] == lastRange.end+1 {
|
||||
// then extend the last range to include this element
|
||||
lastRange.end = elems[i]
|
||||
continue
|
||||
}
|
||||
// otherwise, start a new range beginning with this element
|
||||
ranges = append(ranges, rng{elems[i], elems[i]})
|
||||
}
|
||||
|
||||
// construct string from ranges
|
||||
var result bytes.Buffer
|
||||
for _, r := range ranges {
|
||||
if r.start == r.end {
|
||||
result.WriteString(strconv.Itoa(r.start))
|
||||
} else {
|
||||
result.WriteString(fmt.Sprintf("%d-%d", r.start, r.end))
|
||||
}
|
||||
result.WriteString(",")
|
||||
}
|
||||
return strings.TrimRight(result.String(), ",")
|
||||
}
|
||||
|
||||
// Parse CPUSet constructs a new CPU set from a Linux CPU list formatted string.
|
||||
//
|
||||
// See: http://man7.org/linux/man-pages/man7/cpuset.7.html#FORMATS
|
||||
func Parse(s string) (CPUSet, error) {
|
||||
// Handle empty string.
|
||||
if s == "" {
|
||||
return New(), nil
|
||||
}
|
||||
|
||||
result := New()
|
||||
|
||||
// Split CPU list string:
|
||||
// "0-5,34,46-48" => ["0-5", "34", "46-48"]
|
||||
ranges := strings.Split(s, ",")
|
||||
|
||||
for _, r := range ranges {
|
||||
boundaries := strings.SplitN(r, "-", 2)
|
||||
if len(boundaries) == 1 {
|
||||
// Handle ranges that consist of only one element like "34".
|
||||
elem, err := strconv.Atoi(boundaries[0])
|
||||
if err != nil {
|
||||
return New(), err
|
||||
}
|
||||
result.add(elem)
|
||||
} else if len(boundaries) == 2 {
|
||||
// Handle multi-element ranges like "0-5".
|
||||
start, err := strconv.Atoi(boundaries[0])
|
||||
if err != nil {
|
||||
return New(), err
|
||||
}
|
||||
end, err := strconv.Atoi(boundaries[1])
|
||||
if err != nil {
|
||||
return New(), err
|
||||
}
|
||||
if start > end {
|
||||
return New(), fmt.Errorf("invalid range %q (%d > %d)", r, start, end)
|
||||
}
|
||||
// start == end is acceptable (1-1 -> 1)
|
||||
|
||||
// Add all elements to the result.
|
||||
// e.g. "0-5", "46-48" => [0, 1, 2, 3, 4, 5, 46, 47, 48].
|
||||
for e := start; e <= end; e++ {
|
||||
result.add(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Clone returns a copy of this CPU set.
|
||||
func (s CPUSet) Clone() CPUSet {
|
||||
r := New()
|
||||
for elem := range s.elems {
|
||||
r.add(elem)
|
||||
}
|
||||
return r
|
||||
}
|
5
e2e/vendor/k8s.io/utils/exec/README.md
generated
vendored
Normal file
5
e2e/vendor/k8s.io/utils/exec/README.md
generated
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
# Exec
|
||||
|
||||
This package provides an interface for `os/exec`. It makes it easier to mock
|
||||
and replace in tests, especially with the [FakeExec](testing/fake_exec.go)
|
||||
struct.
|
18
e2e/vendor/k8s.io/utils/exec/doc.go
generated
vendored
Normal file
18
e2e/vendor/k8s.io/utils/exec/doc.go
generated
vendored
Normal file
@ -0,0 +1,18 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package exec provides an injectable interface and implementations for running commands.
|
||||
package exec // import "k8s.io/utils/exec"
|
256
e2e/vendor/k8s.io/utils/exec/exec.go
generated
vendored
Normal file
256
e2e/vendor/k8s.io/utils/exec/exec.go
generated
vendored
Normal file
@ -0,0 +1,256 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package exec
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
osexec "os/exec"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrExecutableNotFound is returned if the executable is not found.
|
||||
var ErrExecutableNotFound = osexec.ErrNotFound
|
||||
|
||||
// Interface is an interface that presents a subset of the os/exec API. Use this
|
||||
// when you want to inject fakeable/mockable exec behavior.
|
||||
type Interface interface {
|
||||
// Command returns a Cmd instance which can be used to run a single command.
|
||||
// This follows the pattern of package os/exec.
|
||||
Command(cmd string, args ...string) Cmd
|
||||
|
||||
// CommandContext returns a Cmd instance which can be used to run a single command.
|
||||
//
|
||||
// The provided context is used to kill the process if the context becomes done
|
||||
// before the command completes on its own. For example, a timeout can be set in
|
||||
// the context.
|
||||
CommandContext(ctx context.Context, cmd string, args ...string) Cmd
|
||||
|
||||
// LookPath wraps os/exec.LookPath
|
||||
LookPath(file string) (string, error)
|
||||
}
|
||||
|
||||
// Cmd is an interface that presents an API that is very similar to Cmd from os/exec.
|
||||
// As more functionality is needed, this can grow. Since Cmd is a struct, we will have
|
||||
// to replace fields with get/set method pairs.
|
||||
type Cmd interface {
|
||||
// Run runs the command to the completion.
|
||||
Run() error
|
||||
// CombinedOutput runs the command and returns its combined standard output
|
||||
// and standard error. This follows the pattern of package os/exec.
|
||||
CombinedOutput() ([]byte, error)
|
||||
// Output runs the command and returns standard output, but not standard err
|
||||
Output() ([]byte, error)
|
||||
SetDir(dir string)
|
||||
SetStdin(in io.Reader)
|
||||
SetStdout(out io.Writer)
|
||||
SetStderr(out io.Writer)
|
||||
SetEnv(env []string)
|
||||
|
||||
// StdoutPipe and StderrPipe for getting the process' Stdout and Stderr as
|
||||
// Readers
|
||||
StdoutPipe() (io.ReadCloser, error)
|
||||
StderrPipe() (io.ReadCloser, error)
|
||||
|
||||
// Start and Wait are for running a process non-blocking
|
||||
Start() error
|
||||
Wait() error
|
||||
|
||||
// Stops the command by sending SIGTERM. It is not guaranteed the
|
||||
// process will stop before this function returns. If the process is not
|
||||
// responding, an internal timer function will send a SIGKILL to force
|
||||
// terminate after 10 seconds.
|
||||
Stop()
|
||||
}
|
||||
|
||||
// ExitError is an interface that presents an API similar to os.ProcessState, which is
|
||||
// what ExitError from os/exec is. This is designed to make testing a bit easier and
|
||||
// probably loses some of the cross-platform properties of the underlying library.
|
||||
type ExitError interface {
|
||||
String() string
|
||||
Error() string
|
||||
Exited() bool
|
||||
ExitStatus() int
|
||||
}
|
||||
|
||||
// Implements Interface in terms of really exec()ing.
|
||||
type executor struct{}
|
||||
|
||||
// New returns a new Interface which will os/exec to run commands.
|
||||
func New() Interface {
|
||||
return &executor{}
|
||||
}
|
||||
|
||||
// Command is part of the Interface interface.
|
||||
func (executor *executor) Command(cmd string, args ...string) Cmd {
|
||||
return (*cmdWrapper)(maskErrDotCmd(osexec.Command(cmd, args...)))
|
||||
}
|
||||
|
||||
// CommandContext is part of the Interface interface.
|
||||
func (executor *executor) CommandContext(ctx context.Context, cmd string, args ...string) Cmd {
|
||||
return (*cmdWrapper)(maskErrDotCmd(osexec.CommandContext(ctx, cmd, args...)))
|
||||
}
|
||||
|
||||
// LookPath is part of the Interface interface
|
||||
func (executor *executor) LookPath(file string) (string, error) {
|
||||
path, err := osexec.LookPath(file)
|
||||
return path, handleError(maskErrDot(err))
|
||||
}
|
||||
|
||||
// Wraps exec.Cmd so we can capture errors.
|
||||
type cmdWrapper osexec.Cmd
|
||||
|
||||
var _ Cmd = &cmdWrapper{}
|
||||
|
||||
func (cmd *cmdWrapper) SetDir(dir string) {
|
||||
cmd.Dir = dir
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) SetStdin(in io.Reader) {
|
||||
cmd.Stdin = in
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) SetStdout(out io.Writer) {
|
||||
cmd.Stdout = out
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) SetStderr(out io.Writer) {
|
||||
cmd.Stderr = out
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) SetEnv(env []string) {
|
||||
cmd.Env = env
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) StdoutPipe() (io.ReadCloser, error) {
|
||||
r, err := (*osexec.Cmd)(cmd).StdoutPipe()
|
||||
return r, handleError(err)
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) StderrPipe() (io.ReadCloser, error) {
|
||||
r, err := (*osexec.Cmd)(cmd).StderrPipe()
|
||||
return r, handleError(err)
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) Start() error {
|
||||
err := (*osexec.Cmd)(cmd).Start()
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) Wait() error {
|
||||
err := (*osexec.Cmd)(cmd).Wait()
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
// Run is part of the Cmd interface.
|
||||
func (cmd *cmdWrapper) Run() error {
|
||||
err := (*osexec.Cmd)(cmd).Run()
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
// CombinedOutput is part of the Cmd interface.
|
||||
func (cmd *cmdWrapper) CombinedOutput() ([]byte, error) {
|
||||
out, err := (*osexec.Cmd)(cmd).CombinedOutput()
|
||||
return out, handleError(err)
|
||||
}
|
||||
|
||||
func (cmd *cmdWrapper) Output() ([]byte, error) {
|
||||
out, err := (*osexec.Cmd)(cmd).Output()
|
||||
return out, handleError(err)
|
||||
}
|
||||
|
||||
// Stop is part of the Cmd interface.
|
||||
func (cmd *cmdWrapper) Stop() {
|
||||
c := (*osexec.Cmd)(cmd)
|
||||
|
||||
if c.Process == nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.Process.Signal(syscall.SIGTERM)
|
||||
|
||||
time.AfterFunc(10*time.Second, func() {
|
||||
if !c.ProcessState.Exited() {
|
||||
c.Process.Signal(syscall.SIGKILL)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func handleError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch e := err.(type) {
|
||||
case *osexec.ExitError:
|
||||
return &ExitErrorWrapper{e}
|
||||
case *fs.PathError:
|
||||
return ErrExecutableNotFound
|
||||
case *osexec.Error:
|
||||
if e.Err == osexec.ErrNotFound {
|
||||
return ErrExecutableNotFound
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ExitErrorWrapper is an implementation of ExitError in terms of os/exec ExitError.
|
||||
// Note: standard exec.ExitError is type *os.ProcessState, which already implements Exited().
|
||||
type ExitErrorWrapper struct {
|
||||
*osexec.ExitError
|
||||
}
|
||||
|
||||
var _ ExitError = &ExitErrorWrapper{}
|
||||
|
||||
// ExitStatus is part of the ExitError interface.
|
||||
func (eew ExitErrorWrapper) ExitStatus() int {
|
||||
ws, ok := eew.Sys().(syscall.WaitStatus)
|
||||
if !ok {
|
||||
panic("can't call ExitStatus() on a non-WaitStatus exitErrorWrapper")
|
||||
}
|
||||
return ws.ExitStatus()
|
||||
}
|
||||
|
||||
// CodeExitError is an implementation of ExitError consisting of an error object
|
||||
// and an exit code (the upper bits of os.exec.ExitStatus).
|
||||
type CodeExitError struct {
|
||||
Err error
|
||||
Code int
|
||||
}
|
||||
|
||||
var _ ExitError = CodeExitError{}
|
||||
|
||||
func (e CodeExitError) Error() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e CodeExitError) String() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
// Exited is to check if the process has finished
|
||||
func (e CodeExitError) Exited() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// ExitStatus is for checking the error code
|
||||
func (e CodeExitError) ExitStatus() int {
|
||||
return e.Code
|
||||
}
|
32
e2e/vendor/k8s.io/utils/exec/fixup_go118.go
generated
vendored
Normal file
32
e2e/vendor/k8s.io/utils/exec/fixup_go118.go
generated
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
//go:build !go1.19
|
||||
// +build !go1.19
|
||||
|
||||
/*
|
||||
Copyright 2022 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package exec
|
||||
|
||||
import (
|
||||
osexec "os/exec"
|
||||
)
|
||||
|
||||
func maskErrDotCmd(cmd *osexec.Cmd) *osexec.Cmd {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func maskErrDot(err error) error {
|
||||
return err
|
||||
}
|
40
e2e/vendor/k8s.io/utils/exec/fixup_go119.go
generated
vendored
Normal file
40
e2e/vendor/k8s.io/utils/exec/fixup_go119.go
generated
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
//go:build go1.19
|
||||
// +build go1.19
|
||||
|
||||
/*
|
||||
Copyright 2022 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package exec
|
||||
|
||||
import (
|
||||
"errors"
|
||||
osexec "os/exec"
|
||||
)
|
||||
|
||||
// maskErrDotCmd reverts the behavior of osexec.Cmd to what it was before go1.19
|
||||
// specifically set the Err field to nil (LookPath returns a new error when the file
|
||||
// is resolved to the current directory.
|
||||
func maskErrDotCmd(cmd *osexec.Cmd) *osexec.Cmd {
|
||||
cmd.Err = maskErrDot(cmd.Err)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func maskErrDot(err error) error {
|
||||
if err != nil && errors.Is(err, osexec.ErrDot) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
27
e2e/vendor/k8s.io/utils/inotify/LICENSE
generated
vendored
Normal file
27
e2e/vendor/k8s.io/utils/inotify/LICENSE
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
22
e2e/vendor/k8s.io/utils/inotify/PATENTS
generated
vendored
Normal file
22
e2e/vendor/k8s.io/utils/inotify/PATENTS
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
Additional IP Rights Grant (Patents)
|
||||
|
||||
"This implementation" means the copyrightable works distributed by
|
||||
Google as part of the Go project.
|
||||
|
||||
Google 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,
|
||||
transfer and otherwise run, modify and propagate the contents of this
|
||||
implementation of Go, where such license applies only to those patent
|
||||
claims, both currently owned or controlled by Google and acquired in
|
||||
the future, licensable by Google that are necessarily infringed by this
|
||||
implementation of Go. This grant does not include claims that would be
|
||||
infringed only as a consequence of further modification of this
|
||||
implementation. If you or your agent or exclusive licensee institute or
|
||||
order or agree to the institution of patent litigation against any
|
||||
entity (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that this implementation of Go or any code incorporated within this
|
||||
implementation of Go constitutes direct or contributory patent
|
||||
infringement, or inducement of patent infringement, then any patent
|
||||
rights granted to you under this License for this implementation of Go
|
||||
shall terminate as of the date such litigation is filed.
|
5
e2e/vendor/k8s.io/utils/inotify/README.md
generated
vendored
Normal file
5
e2e/vendor/k8s.io/utils/inotify/README.md
generated
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
This is a fork of golang.org/x/exp/inotify before it was deleted.
|
||||
|
||||
Please use gopkg.in/fsnotify.v1 instead.
|
||||
|
||||
For updates, see: https://github.com/fsnotify/fsnotify
|
45
e2e/vendor/k8s.io/utils/inotify/inotify.go
generated
vendored
Normal file
45
e2e/vendor/k8s.io/utils/inotify/inotify.go
generated
vendored
Normal file
@ -0,0 +1,45 @@
|
||||
/*
|
||||
Copyright 2020 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package inotify // import "k8s.io/utils/inotify"
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Event represents a notification
|
||||
type Event struct {
|
||||
Mask uint32 // Mask of events
|
||||
Cookie uint32 // Unique cookie associating related events (for rename(2))
|
||||
Name string // File name (optional)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// Watcher represents an inotify instance
|
||||
type Watcher struct {
|
||||
mu sync.Mutex
|
||||
fd int // File descriptor (as returned by the inotify_init() syscall)
|
||||
watches map[string]*watch // Map of inotify watches (key: path)
|
||||
paths map[int]string // Map of watched paths (key: watch descriptor)
|
||||
Error chan error // Errors are sent on this channel
|
||||
Event chan *Event // Events are returned on this channel
|
||||
done chan bool // Channel for sending a "quit message" to the reader goroutine
|
||||
isClosed bool // Set to true when Close() is first called
|
||||
}
|
315
e2e/vendor/k8s.io/utils/inotify/inotify_linux.go
generated
vendored
Normal file
315
e2e/vendor/k8s.io/utils/inotify/inotify_linux.go
generated
vendored
Normal file
@ -0,0 +1,315 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
// 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.
|
||||
|
||||
/*
|
||||
Package inotify implements a wrapper for the Linux inotify system.
|
||||
|
||||
Example:
|
||||
|
||||
watcher, err := inotify.NewWatcher()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err = watcher.Watch("/tmp")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case ev := <-watcher.Event:
|
||||
log.Println("event:", ev)
|
||||
case err := <-watcher.Error:
|
||||
log.Println("error:", err)
|
||||
}
|
||||
}
|
||||
*/
|
||||
package inotify // import "k8s.io/utils/inotify"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// NewWatcher creates and returns a new inotify instance using inotify_init(2)
|
||||
func NewWatcher() (*Watcher, error) {
|
||||
fd, errno := syscall.InotifyInit1(syscall.IN_CLOEXEC)
|
||||
if fd == -1 {
|
||||
return nil, os.NewSyscallError("inotify_init", errno)
|
||||
}
|
||||
w := &Watcher{
|
||||
fd: fd,
|
||||
watches: make(map[string]*watch),
|
||||
paths: make(map[int]string),
|
||||
Event: make(chan *Event),
|
||||
Error: make(chan error),
|
||||
done: make(chan bool, 1),
|
||||
}
|
||||
|
||||
go w.readEvents()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// Close closes an inotify watcher instance
|
||||
// It sends a message to the reader goroutine to quit and removes all watches
|
||||
// associated with the inotify instance
|
||||
func (w *Watcher) Close() error {
|
||||
if w.isClosed {
|
||||
return nil
|
||||
}
|
||||
w.isClosed = true
|
||||
|
||||
// Send "quit" message to the reader goroutine
|
||||
w.done <- true
|
||||
for path := range w.watches {
|
||||
w.RemoveWatch(path)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddWatch adds path to the watched file set.
|
||||
// The flags are interpreted as described in inotify_add_watch(2).
|
||||
func (w *Watcher) AddWatch(path string, flags uint32) error {
|
||||
if w.isClosed {
|
||||
return errors.New("inotify instance already closed")
|
||||
}
|
||||
|
||||
watchEntry, found := w.watches[path]
|
||||
if found {
|
||||
watchEntry.flags |= flags
|
||||
flags |= syscall.IN_MASK_ADD
|
||||
}
|
||||
|
||||
w.mu.Lock() // synchronize with readEvents goroutine
|
||||
|
||||
wd, err := syscall.InotifyAddWatch(w.fd, path, flags)
|
||||
if err != nil {
|
||||
w.mu.Unlock()
|
||||
return &os.PathError{
|
||||
Op: "inotify_add_watch",
|
||||
Path: path,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
w.watches[path] = &watch{wd: uint32(wd), flags: flags}
|
||||
w.paths[wd] = path
|
||||
}
|
||||
w.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Watch adds path to the watched file set, watching all events.
|
||||
func (w *Watcher) Watch(path string) error {
|
||||
return w.AddWatch(path, InAllEvents)
|
||||
}
|
||||
|
||||
// RemoveWatch removes path from the watched file set.
|
||||
func (w *Watcher) RemoveWatch(path string) error {
|
||||
watch, ok := w.watches[path]
|
||||
if !ok {
|
||||
return fmt.Errorf("can't remove non-existent inotify watch for: %s", path)
|
||||
}
|
||||
success, errno := syscall.InotifyRmWatch(w.fd, watch.wd)
|
||||
if success == -1 {
|
||||
// when file descriptor or watch descriptor not found, InotifyRmWatch syscall return EINVAL error
|
||||
// if return error, it may lead this path remain in watches and paths map, and no other event can trigger remove action.
|
||||
if errno != syscall.EINVAL {
|
||||
return os.NewSyscallError("inotify_rm_watch", errno)
|
||||
}
|
||||
}
|
||||
delete(w.watches, path)
|
||||
// Locking here to protect the read from paths in readEvents.
|
||||
w.mu.Lock()
|
||||
delete(w.paths, int(watch.wd))
|
||||
w.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// readEvents reads from the inotify file descriptor, converts the
|
||||
// received events into Event objects and sends them via the Event channel
|
||||
func (w *Watcher) readEvents() {
|
||||
var buf [syscall.SizeofInotifyEvent * 4096]byte
|
||||
|
||||
for {
|
||||
n, err := syscall.Read(w.fd, buf[:])
|
||||
// See if there is a message on the "done" channel
|
||||
var done bool
|
||||
select {
|
||||
case done = <-w.done:
|
||||
default:
|
||||
}
|
||||
|
||||
// If EOF or a "done" message is received
|
||||
if n == 0 || done {
|
||||
// The syscall.Close can be slow. Close
|
||||
// w.Event first.
|
||||
close(w.Event)
|
||||
err := syscall.Close(w.fd)
|
||||
if err != nil {
|
||||
w.Error <- os.NewSyscallError("close", err)
|
||||
}
|
||||
close(w.Error)
|
||||
return
|
||||
}
|
||||
if n < 0 {
|
||||
w.Error <- os.NewSyscallError("read", err)
|
||||
continue
|
||||
}
|
||||
if n < syscall.SizeofInotifyEvent {
|
||||
w.Error <- errors.New("inotify: short read in readEvents()")
|
||||
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-syscall.SizeofInotifyEvent) {
|
||||
// Point "raw" to the event in the buffer
|
||||
raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
|
||||
event := new(Event)
|
||||
event.Mask = uint32(raw.Mask)
|
||||
event.Cookie = uint32(raw.Cookie)
|
||||
nameLen := uint32(raw.Len)
|
||||
// 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)]
|
||||
w.mu.Unlock()
|
||||
if ok {
|
||||
event.Name = name
|
||||
if nameLen > 0 {
|
||||
// Point "bytes" at the first byte of the filename
|
||||
bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
|
||||
// The filename is padded with NUL bytes. TrimRight() gets rid of those.
|
||||
event.Name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
|
||||
}
|
||||
// Send the event on the events channel
|
||||
w.Event <- event
|
||||
}
|
||||
// Move to the next event in the buffer
|
||||
offset += syscall.SizeofInotifyEvent + nameLen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// String formats the event e in the form
|
||||
// "filename: 0xEventMask = IN_ACCESS|IN_ATTRIB_|..."
|
||||
func (e *Event) String() string {
|
||||
var events string
|
||||
|
||||
m := e.Mask
|
||||
for _, b := range eventBits {
|
||||
if m&b.Value == b.Value {
|
||||
m &^= b.Value
|
||||
events += "|" + b.Name
|
||||
}
|
||||
}
|
||||
|
||||
if m != 0 {
|
||||
events += fmt.Sprintf("|%#x", m)
|
||||
}
|
||||
if len(events) > 0 {
|
||||
events = " == " + events[1:]
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%q: %#x%s", e.Name, e.Mask, events)
|
||||
}
|
||||
|
||||
const (
|
||||
// Options for inotify_init() are not exported
|
||||
// IN_CLOEXEC uint32 = syscall.IN_CLOEXEC
|
||||
// IN_NONBLOCK uint32 = syscall.IN_NONBLOCK
|
||||
|
||||
// Options for AddWatch
|
||||
|
||||
// InDontFollow : Don't dereference pathname if it is a symbolic link
|
||||
InDontFollow uint32 = syscall.IN_DONT_FOLLOW
|
||||
// InOneshot : Monitor the filesystem object corresponding to pathname for one event, then remove from watch list
|
||||
InOneshot uint32 = syscall.IN_ONESHOT
|
||||
// InOnlydir : Watch pathname only if it is a directory
|
||||
InOnlydir uint32 = syscall.IN_ONLYDIR
|
||||
|
||||
// The "IN_MASK_ADD" option is not exported, as AddWatch
|
||||
// adds it automatically, if there is already a watch for the given path
|
||||
// IN_MASK_ADD uint32 = syscall.IN_MASK_ADD
|
||||
|
||||
// Events
|
||||
|
||||
// InAccess : File was accessed
|
||||
InAccess uint32 = syscall.IN_ACCESS
|
||||
// InAllEvents : Bit mask for all notify events
|
||||
InAllEvents uint32 = syscall.IN_ALL_EVENTS
|
||||
// InAttrib : Metadata changed
|
||||
InAttrib uint32 = syscall.IN_ATTRIB
|
||||
// InClose : Equates to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
|
||||
InClose uint32 = syscall.IN_CLOSE
|
||||
// InCloseNowrite : File or directory not opened for writing was closed
|
||||
InCloseNowrite uint32 = syscall.IN_CLOSE_NOWRITE
|
||||
// InCloseWrite : File opened for writing was closed
|
||||
InCloseWrite uint32 = syscall.IN_CLOSE_WRITE
|
||||
// InCreate : File/directory created in watched directory
|
||||
InCreate uint32 = syscall.IN_CREATE
|
||||
// InDelete : File/directory deleted from watched directory
|
||||
InDelete uint32 = syscall.IN_DELETE
|
||||
// InDeleteSelf : Watched file/directory was itself deleted
|
||||
InDeleteSelf uint32 = syscall.IN_DELETE_SELF
|
||||
// InModify : File was modified
|
||||
InModify uint32 = syscall.IN_MODIFY
|
||||
// InMove : Equates to IN_MOVED_FROM | IN_MOVED_TO
|
||||
InMove uint32 = syscall.IN_MOVE
|
||||
// InMovedFrom : Generated for the directory containing the old filename when a file is renamed
|
||||
InMovedFrom uint32 = syscall.IN_MOVED_FROM
|
||||
// InMovedTo : Generated for the directory containing the new filename when a file is renamed
|
||||
InMovedTo uint32 = syscall.IN_MOVED_TO
|
||||
// InMoveSelf : Watched file/directory was itself moved
|
||||
InMoveSelf uint32 = syscall.IN_MOVE_SELF
|
||||
// InOpen : File or directory was opened
|
||||
InOpen uint32 = syscall.IN_OPEN
|
||||
|
||||
// Special events
|
||||
|
||||
// InIsdir : Subject of this event is a directory
|
||||
InIsdir uint32 = syscall.IN_ISDIR
|
||||
// InIgnored : Watch was removed explicitly or automatically
|
||||
InIgnored uint32 = syscall.IN_IGNORED
|
||||
// InQOverflow : Event queue overflowed
|
||||
InQOverflow uint32 = syscall.IN_Q_OVERFLOW
|
||||
// InUnmount : Filesystem containing watched object was unmounted
|
||||
InUnmount uint32 = syscall.IN_UNMOUNT
|
||||
)
|
||||
|
||||
var eventBits = []struct {
|
||||
Value uint32
|
||||
Name string
|
||||
}{
|
||||
{InAccess, "IN_ACCESS"},
|
||||
{InAttrib, "IN_ATTRIB"},
|
||||
{InClose, "IN_CLOSE"},
|
||||
{InCloseNowrite, "IN_CLOSE_NOWRITE"},
|
||||
{InCloseWrite, "IN_CLOSE_WRITE"},
|
||||
{InCreate, "IN_CREATE"},
|
||||
{InDelete, "IN_DELETE"},
|
||||
{InDeleteSelf, "IN_DELETE_SELF"},
|
||||
{InModify, "IN_MODIFY"},
|
||||
{InMove, "IN_MOVE"},
|
||||
{InMovedFrom, "IN_MOVED_FROM"},
|
||||
{InMovedTo, "IN_MOVED_TO"},
|
||||
{InMoveSelf, "IN_MOVE_SELF"},
|
||||
{InOpen, "IN_OPEN"},
|
||||
{InIsdir, "IN_ISDIR"},
|
||||
{InIgnored, "IN_IGNORED"},
|
||||
{InQOverflow, "IN_Q_OVERFLOW"},
|
||||
{InUnmount, "IN_UNMOUNT"},
|
||||
}
|
54
e2e/vendor/k8s.io/utils/inotify/inotify_others.go
generated
vendored
Normal file
54
e2e/vendor/k8s.io/utils/inotify/inotify_others.go
generated
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
// +build !linux
|
||||
|
||||
/*
|
||||
Copyright 2020 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package inotify // import "k8s.io/utils/inotify"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var errNotSupported = fmt.Errorf("watch not supported on %s", runtime.GOOS)
|
||||
|
||||
// NewWatcher creates and returns a new inotify instance using inotify_init(2)
|
||||
func NewWatcher() (*Watcher, error) {
|
||||
return nil, errNotSupported
|
||||
}
|
||||
|
||||
// Close closes an inotify watcher instance
|
||||
// It sends a message to the reader goroutine to quit and removes all watches
|
||||
// associated with the inotify instance
|
||||
func (w *Watcher) Close() error {
|
||||
return errNotSupported
|
||||
}
|
||||
|
||||
// AddWatch adds path to the watched file set.
|
||||
// The flags are interpreted as described in inotify_add_watch(2).
|
||||
func (w *Watcher) AddWatch(path string, flags uint32) error {
|
||||
return errNotSupported
|
||||
}
|
||||
|
||||
// Watch adds path to the watched file set, watching all events.
|
||||
func (w *Watcher) Watch(path string) error {
|
||||
return errNotSupported
|
||||
}
|
||||
|
||||
// RemoveWatch removes path from the watched file set.
|
||||
func (w *Watcher) RemoveWatch(path string) error {
|
||||
return errNotSupported
|
||||
}
|
79
e2e/vendor/k8s.io/utils/integer/integer.go
generated
vendored
Normal file
79
e2e/vendor/k8s.io/utils/integer/integer.go
generated
vendored
Normal file
@ -0,0 +1,79 @@
|
||||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package integer
|
||||
|
||||
import "math"
|
||||
|
||||
// IntMax returns the maximum of the params.
|
||||
// Deprecated: for new code, use the max() builtin instead.
|
||||
func IntMax(a, b int) int {
|
||||
if b > a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// IntMin returns the minimum of the params.
|
||||
// Deprecated: for new code, use the min() builtin instead.
|
||||
func IntMin(a, b int) int {
|
||||
if b < a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Int32Max returns the maximum of the params.
|
||||
// Deprecated: for new code, use the max() builtin instead.
|
||||
func Int32Max(a, b int32) int32 {
|
||||
if b > a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Int32Min returns the minimum of the params.
|
||||
// Deprecated: for new code, use the min() builtin instead.
|
||||
func Int32Min(a, b int32) int32 {
|
||||
if b < a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Int64Max returns the maximum of the params.
|
||||
// Deprecated: for new code, use the max() builtin instead.
|
||||
func Int64Max(a, b int64) int64 {
|
||||
if b > a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// Int64Min returns the minimum of the params.
|
||||
// Deprecated: for new code, use the min() builtin instead.
|
||||
func Int64Min(a, b int64) int64 {
|
||||
if b < a {
|
||||
return b
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// RoundToInt32 rounds floats into integer numbers.
|
||||
// Deprecated: use math.Round() and a cast directly.
|
||||
func RoundToInt32(a float64) int32 {
|
||||
return int32(math.Round(a))
|
||||
}
|
27
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/LICENSE
generated
vendored
Normal file
27
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/LICENSE
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
22
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/PATENTS
generated
vendored
Normal file
22
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/PATENTS
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
||||
Additional IP Rights Grant (Patents)
|
||||
|
||||
"This implementation" means the copyrightable works distributed by
|
||||
Google as part of the Go project.
|
||||
|
||||
Google 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,
|
||||
transfer and otherwise run, modify and propagate the contents of this
|
||||
implementation of Go, where such license applies only to those patent
|
||||
claims, both currently owned or controlled by Google and acquired in
|
||||
the future, licensable by Google that are necessarily infringed by this
|
||||
implementation of Go. This grant does not include claims that would be
|
||||
infringed only as a consequence of further modification of this
|
||||
implementation. If you or your agent or exclusive licensee institute or
|
||||
order or agree to the institution of patent litigation against any
|
||||
entity (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||
that this implementation of Go or any code incorporated within this
|
||||
implementation of Go constitutes direct or contributory patent
|
||||
infringement, or inducement of patent infringement, then any patent
|
||||
rights granted to you under this License for this implementation of Go
|
||||
shall terminate as of the date such litigation is filed.
|
133
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go
generated
vendored
Normal file
133
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go
generated
vendored
Normal file
@ -0,0 +1,133 @@
|
||||
/*
|
||||
Copyright 2013 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package lru implements an LRU cache.
|
||||
package golang_lru
|
||||
|
||||
import "container/list"
|
||||
|
||||
// Cache is an LRU cache. It is not safe for concurrent access.
|
||||
type Cache struct {
|
||||
// MaxEntries is the maximum number of cache entries before
|
||||
// an item is evicted. Zero means no limit.
|
||||
MaxEntries int
|
||||
|
||||
// OnEvicted optionally specifies a callback function to be
|
||||
// executed when an entry is purged from the cache.
|
||||
OnEvicted func(key Key, value interface{})
|
||||
|
||||
ll *list.List
|
||||
cache map[interface{}]*list.Element
|
||||
}
|
||||
|
||||
// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
|
||||
type Key interface{}
|
||||
|
||||
type entry struct {
|
||||
key Key
|
||||
value interface{}
|
||||
}
|
||||
|
||||
// New creates a new Cache.
|
||||
// If maxEntries is zero, the cache has no limit and it's assumed
|
||||
// that eviction is done by the caller.
|
||||
func New(maxEntries int) *Cache {
|
||||
return &Cache{
|
||||
MaxEntries: maxEntries,
|
||||
ll: list.New(),
|
||||
cache: make(map[interface{}]*list.Element),
|
||||
}
|
||||
}
|
||||
|
||||
// Add adds a value to the cache.
|
||||
func (c *Cache) Add(key Key, value interface{}) {
|
||||
if c.cache == nil {
|
||||
c.cache = make(map[interface{}]*list.Element)
|
||||
c.ll = list.New()
|
||||
}
|
||||
if ee, ok := c.cache[key]; ok {
|
||||
c.ll.MoveToFront(ee)
|
||||
ee.Value.(*entry).value = value
|
||||
return
|
||||
}
|
||||
ele := c.ll.PushFront(&entry{key, value})
|
||||
c.cache[key] = ele
|
||||
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries {
|
||||
c.RemoveOldest()
|
||||
}
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *Cache) Get(key Key) (value interface{}, ok bool) {
|
||||
if c.cache == nil {
|
||||
return
|
||||
}
|
||||
if ele, hit := c.cache[key]; hit {
|
||||
c.ll.MoveToFront(ele)
|
||||
return ele.Value.(*entry).value, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *Cache) Remove(key Key) {
|
||||
if c.cache == nil {
|
||||
return
|
||||
}
|
||||
if ele, hit := c.cache[key]; hit {
|
||||
c.removeElement(ele)
|
||||
}
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *Cache) RemoveOldest() {
|
||||
if c.cache == nil {
|
||||
return
|
||||
}
|
||||
ele := c.ll.Back()
|
||||
if ele != nil {
|
||||
c.removeElement(ele)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) removeElement(e *list.Element) {
|
||||
c.ll.Remove(e)
|
||||
kv := e.Value.(*entry)
|
||||
delete(c.cache, kv.key)
|
||||
if c.OnEvicted != nil {
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *Cache) Len() int {
|
||||
if c.cache == nil {
|
||||
return 0
|
||||
}
|
||||
return c.ll.Len()
|
||||
}
|
||||
|
||||
// Clear purges all stored items from the cache.
|
||||
func (c *Cache) Clear() {
|
||||
if c.OnEvicted != nil {
|
||||
for _, e := range c.cache {
|
||||
kv := e.Value.(*entry)
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
}
|
||||
}
|
||||
c.ll = nil
|
||||
c.cache = nil
|
||||
}
|
236
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/net/ip.go
generated
vendored
Normal file
236
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/net/ip.go
generated
vendored
Normal file
@ -0,0 +1,236 @@
|
||||
// Copyright 2009 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.
|
||||
|
||||
// IP address manipulations
|
||||
//
|
||||
// IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes.
|
||||
// An IPv4 address can be converted to an IPv6 address by
|
||||
// adding a canonical prefix (10 zeros, 2 0xFFs).
|
||||
// This library accepts either size of byte slice but always
|
||||
// returns 16-byte addresses.
|
||||
|
||||
package net
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// NOTE: This file was forked because we need to maintain backwards-compatible
|
||||
// IP parsing logic, which was changed in a correct but incompatible way in
|
||||
// go-1.17.
|
||||
//
|
||||
// See https://issue.k8s.io/100895
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import (
|
||||
stdnet "net"
|
||||
)
|
||||
|
||||
//
|
||||
// Lean on the standard net lib as much as possible.
|
||||
//
|
||||
|
||||
type IP = stdnet.IP
|
||||
type IPNet = stdnet.IPNet
|
||||
type ParseError = stdnet.ParseError
|
||||
|
||||
const IPv4len = stdnet.IPv4len
|
||||
const IPv6len = stdnet.IPv6len
|
||||
|
||||
var CIDRMask = stdnet.CIDRMask
|
||||
var IPv4 = stdnet.IPv4
|
||||
|
||||
// Parse IPv4 address (d.d.d.d).
|
||||
func parseIPv4(s string) IP {
|
||||
var p [IPv4len]byte
|
||||
for i := 0; i < IPv4len; i++ {
|
||||
if len(s) == 0 {
|
||||
// Missing octets.
|
||||
return nil
|
||||
}
|
||||
if i > 0 {
|
||||
if s[0] != '.' {
|
||||
return nil
|
||||
}
|
||||
s = s[1:]
|
||||
}
|
||||
n, c, ok := dtoi(s)
|
||||
if !ok || n > 0xFF {
|
||||
return nil
|
||||
}
|
||||
//
|
||||
// NOTE: This correct check was added for go-1.17, but is a
|
||||
// backwards-incompatible change for kubernetes users, who might have
|
||||
// stored data which uses these leading zeroes already.
|
||||
//
|
||||
// See https://issue.k8s.io/100895
|
||||
//
|
||||
//if c > 1 && s[0] == '0' {
|
||||
// // Reject non-zero components with leading zeroes.
|
||||
// return nil
|
||||
//}
|
||||
s = s[c:]
|
||||
p[i] = byte(n)
|
||||
}
|
||||
if len(s) != 0 {
|
||||
return nil
|
||||
}
|
||||
return IPv4(p[0], p[1], p[2], p[3])
|
||||
}
|
||||
|
||||
// parseIPv6 parses s as a literal IPv6 address described in RFC 4291
|
||||
// and RFC 5952.
|
||||
func parseIPv6(s string) (ip IP) {
|
||||
ip = make(IP, IPv6len)
|
||||
ellipsis := -1 // position of ellipsis in ip
|
||||
|
||||
// Might have leading ellipsis
|
||||
if len(s) >= 2 && s[0] == ':' && s[1] == ':' {
|
||||
ellipsis = 0
|
||||
s = s[2:]
|
||||
// Might be only ellipsis
|
||||
if len(s) == 0 {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
|
||||
// Loop, parsing hex numbers followed by colon.
|
||||
i := 0
|
||||
for i < IPv6len {
|
||||
// Hex number.
|
||||
n, c, ok := xtoi(s)
|
||||
if !ok || n > 0xFFFF {
|
||||
return nil
|
||||
}
|
||||
|
||||
// If followed by dot, might be in trailing IPv4.
|
||||
if c < len(s) && s[c] == '.' {
|
||||
if ellipsis < 0 && i != IPv6len-IPv4len {
|
||||
// Not the right place.
|
||||
return nil
|
||||
}
|
||||
if i+IPv4len > IPv6len {
|
||||
// Not enough room.
|
||||
return nil
|
||||
}
|
||||
ip4 := parseIPv4(s)
|
||||
if ip4 == nil {
|
||||
return nil
|
||||
}
|
||||
ip[i] = ip4[12]
|
||||
ip[i+1] = ip4[13]
|
||||
ip[i+2] = ip4[14]
|
||||
ip[i+3] = ip4[15]
|
||||
s = ""
|
||||
i += IPv4len
|
||||
break
|
||||
}
|
||||
|
||||
// Save this 16-bit chunk.
|
||||
ip[i] = byte(n >> 8)
|
||||
ip[i+1] = byte(n)
|
||||
i += 2
|
||||
|
||||
// Stop at end of string.
|
||||
s = s[c:]
|
||||
if len(s) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
// Otherwise must be followed by colon and more.
|
||||
if s[0] != ':' || len(s) == 1 {
|
||||
return nil
|
||||
}
|
||||
s = s[1:]
|
||||
|
||||
// Look for ellipsis.
|
||||
if s[0] == ':' {
|
||||
if ellipsis >= 0 { // already have one
|
||||
return nil
|
||||
}
|
||||
ellipsis = i
|
||||
s = s[1:]
|
||||
if len(s) == 0 { // can be at end
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Must have used entire string.
|
||||
if len(s) != 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// If didn't parse enough, expand ellipsis.
|
||||
if i < IPv6len {
|
||||
if ellipsis < 0 {
|
||||
return nil
|
||||
}
|
||||
n := IPv6len - i
|
||||
for j := i - 1; j >= ellipsis; j-- {
|
||||
ip[j+n] = ip[j]
|
||||
}
|
||||
for j := ellipsis + n - 1; j >= ellipsis; j-- {
|
||||
ip[j] = 0
|
||||
}
|
||||
} else if ellipsis >= 0 {
|
||||
// Ellipsis must represent at least one 0 group.
|
||||
return nil
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
// ParseIP parses s as an IP address, returning the result.
|
||||
// The string s can be in IPv4 dotted decimal ("192.0.2.1"), IPv6
|
||||
// ("2001:db8::68"), or IPv4-mapped IPv6 ("::ffff:192.0.2.1") form.
|
||||
// If s is not a valid textual representation of an IP address,
|
||||
// ParseIP returns nil.
|
||||
func ParseIP(s string) IP {
|
||||
for i := 0; i < len(s); i++ {
|
||||
switch s[i] {
|
||||
case '.':
|
||||
return parseIPv4(s)
|
||||
case ':':
|
||||
return parseIPv6(s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseCIDR parses s as a CIDR notation IP address and prefix length,
|
||||
// like "192.0.2.0/24" or "2001:db8::/32", as defined in
|
||||
// RFC 4632 and RFC 4291.
|
||||
//
|
||||
// It returns the IP address and the network implied by the IP and
|
||||
// prefix length.
|
||||
// For example, ParseCIDR("192.0.2.1/24") returns the IP address
|
||||
// 192.0.2.1 and the network 192.0.2.0/24.
|
||||
func ParseCIDR(s string) (IP, *IPNet, error) {
|
||||
i := indexByteString(s, '/')
|
||||
if i < 0 {
|
||||
return nil, nil, &ParseError{Type: "CIDR address", Text: s}
|
||||
}
|
||||
addr, mask := s[:i], s[i+1:]
|
||||
iplen := IPv4len
|
||||
ip := parseIPv4(addr)
|
||||
if ip == nil {
|
||||
iplen = IPv6len
|
||||
ip = parseIPv6(addr)
|
||||
}
|
||||
n, i, ok := dtoi(mask)
|
||||
if ip == nil || !ok || i != len(mask) || n < 0 || n > 8*iplen {
|
||||
return nil, nil, &ParseError{Type: "CIDR address", Text: s}
|
||||
}
|
||||
m := CIDRMask(n, 8*iplen)
|
||||
return ip, &IPNet{IP: ip.Mask(m), Mask: m}, nil
|
||||
}
|
||||
|
||||
// This is copied from go/src/internal/bytealg, which includes versions
|
||||
// optimized for various platforms. Those optimizations are elided here so we
|
||||
// don't have to maintain them.
|
||||
func indexByteString(s string, c byte) int {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == c {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
59
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/net/parse.go
generated
vendored
Normal file
59
e2e/vendor/k8s.io/utils/internal/third_party/forked/golang/net/parse.go
generated
vendored
Normal file
@ -0,0 +1,59 @@
|
||||
// Copyright 2009 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.
|
||||
|
||||
// Simple file i/o and string manipulation, to avoid
|
||||
// depending on strconv and bufio and strings.
|
||||
|
||||
package net
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// NOTE: This file was forked because it is used by other code that needed to
|
||||
// be forked, not because it is used on its own.
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// Bigger than we need, not too big to worry about overflow
|
||||
const big = 0xFFFFFF
|
||||
|
||||
// Decimal to integer.
|
||||
// Returns number, characters consumed, success.
|
||||
func dtoi(s string) (n int, i int, ok bool) {
|
||||
n = 0
|
||||
for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
|
||||
n = n*10 + int(s[i]-'0')
|
||||
if n >= big {
|
||||
return big, i, false
|
||||
}
|
||||
}
|
||||
if i == 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
return n, i, true
|
||||
}
|
||||
|
||||
// Hexadecimal to integer.
|
||||
// Returns number, characters consumed, success.
|
||||
func xtoi(s string) (n int, i int, ok bool) {
|
||||
n = 0
|
||||
for i = 0; i < len(s); i++ {
|
||||
if '0' <= s[i] && s[i] <= '9' {
|
||||
n *= 16
|
||||
n += int(s[i] - '0')
|
||||
} else if 'a' <= s[i] && s[i] <= 'f' {
|
||||
n *= 16
|
||||
n += int(s[i]-'a') + 10
|
||||
} else if 'A' <= s[i] && s[i] <= 'F' {
|
||||
n *= 16
|
||||
n += int(s[i]-'A') + 10
|
||||
} else {
|
||||
break
|
||||
}
|
||||
if n >= big {
|
||||
return 0, i, false
|
||||
}
|
||||
}
|
||||
if i == 0 {
|
||||
return 0, i, false
|
||||
}
|
||||
return n, i, true
|
||||
}
|
4
e2e/vendor/k8s.io/utils/io/README.md
generated
vendored
Normal file
4
e2e/vendor/k8s.io/utils/io/README.md
generated
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# IO
|
||||
|
||||
This package provides interfaces for working with file IO. Currently it
|
||||
provides functionality for consistently reading a file.
|
98
e2e/vendor/k8s.io/utils/io/read.go
generated
vendored
Normal file
98
e2e/vendor/k8s.io/utils/io/read.go
generated
vendored
Normal file
@ -0,0 +1,98 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package io
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
// ErrLimitReached means that the read limit is reached.
|
||||
var ErrLimitReached = errors.New("the read limit is reached")
|
||||
|
||||
// ConsistentRead repeatedly reads a file until it gets the same content twice.
|
||||
// This is useful when reading files in /proc that are larger than page size
|
||||
// and kernel may modify them between individual read() syscalls.
|
||||
// It returns InconsistentReadError when it cannot get a consistent read in
|
||||
// given nr. of attempts. Caller should retry, kernel is probably under heavy
|
||||
// mount/unmount load.
|
||||
func ConsistentRead(filename string, attempts int) ([]byte, error) {
|
||||
return consistentReadSync(filename, attempts, nil)
|
||||
}
|
||||
|
||||
// consistentReadSync is the main functionality of ConsistentRead but
|
||||
// introduces a sync callback that can be used by the tests to mutate the file
|
||||
// from which the test data is being read
|
||||
func consistentReadSync(filename string, attempts int, sync func(int)) ([]byte, error) {
|
||||
oldContent, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < attempts; i++ {
|
||||
if sync != nil {
|
||||
sync(i)
|
||||
}
|
||||
newContent, err := ioutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bytes.Compare(oldContent, newContent) == 0 {
|
||||
return newContent, nil
|
||||
}
|
||||
// Files are different, continue reading
|
||||
oldContent = newContent
|
||||
}
|
||||
return nil, InconsistentReadError{filename, attempts}
|
||||
}
|
||||
|
||||
// InconsistentReadError is returned from ConsistentRead when it cannot get
|
||||
// a consistent read in given nr. of attempts. Caller should retry, kernel is
|
||||
// probably under heavy mount/unmount load.
|
||||
type InconsistentReadError struct {
|
||||
filename string
|
||||
attempts int
|
||||
}
|
||||
|
||||
func (i InconsistentReadError) Error() string {
|
||||
return fmt.Sprintf("could not get consistent content of %s after %d attempts", i.filename, i.attempts)
|
||||
}
|
||||
|
||||
var _ error = InconsistentReadError{}
|
||||
|
||||
func IsInconsistentReadError(err error) bool {
|
||||
if _, ok := err.(InconsistentReadError); ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ReadAtMost reads up to `limit` bytes from `r`, and reports an error
|
||||
// when `limit` bytes are read.
|
||||
func ReadAtMost(r io.Reader, limit int64) ([]byte, error) {
|
||||
limitedReader := &io.LimitedReader{R: r, N: limit}
|
||||
data, err := ioutil.ReadAll(limitedReader)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
if limitedReader.N <= 0 {
|
||||
return data, ErrLimitReached
|
||||
}
|
||||
return data, nil
|
||||
}
|
58
e2e/vendor/k8s.io/utils/keymutex/hashed.go
generated
vendored
Normal file
58
e2e/vendor/k8s.io/utils/keymutex/hashed.go
generated
vendored
Normal file
@ -0,0 +1,58 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package keymutex
|
||||
|
||||
import (
|
||||
"hash/fnv"
|
||||
"runtime"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// NewHashed returns a new instance of KeyMutex which hashes arbitrary keys to
|
||||
// a fixed set of locks. `n` specifies number of locks, if n <= 0, we use
|
||||
// number of cpus.
|
||||
// Note that because it uses fixed set of locks, different keys may share same
|
||||
// lock, so it's possible to wait on same lock.
|
||||
func NewHashed(n int) KeyMutex {
|
||||
if n <= 0 {
|
||||
n = runtime.NumCPU()
|
||||
}
|
||||
return &hashedKeyMutex{
|
||||
mutexes: make([]sync.Mutex, n),
|
||||
}
|
||||
}
|
||||
|
||||
type hashedKeyMutex struct {
|
||||
mutexes []sync.Mutex
|
||||
}
|
||||
|
||||
// Acquires a lock associated with the specified ID.
|
||||
func (km *hashedKeyMutex) LockKey(id string) {
|
||||
km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Lock()
|
||||
}
|
||||
|
||||
// Releases the lock associated with the specified ID.
|
||||
func (km *hashedKeyMutex) UnlockKey(id string) error {
|
||||
km.mutexes[km.hash(id)%uint32(len(km.mutexes))].Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (km *hashedKeyMutex) hash(id string) uint32 {
|
||||
h := fnv.New32a()
|
||||
h.Write([]byte(id))
|
||||
return h.Sum32()
|
||||
}
|
27
e2e/vendor/k8s.io/utils/keymutex/keymutex.go
generated
vendored
Normal file
27
e2e/vendor/k8s.io/utils/keymutex/keymutex.go
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package keymutex
|
||||
|
||||
// KeyMutex is a thread-safe interface for acquiring locks on arbitrary strings.
|
||||
type KeyMutex interface {
|
||||
// Acquires a lock associated with the specified ID, creates the lock if one doesn't already exist.
|
||||
LockKey(id string)
|
||||
|
||||
// Releases the lock associated with the specified ID.
|
||||
// Returns an error if the specified ID doesn't exist.
|
||||
UnlockKey(id string) error
|
||||
}
|
99
e2e/vendor/k8s.io/utils/lru/lru.go
generated
vendored
Normal file
99
e2e/vendor/k8s.io/utils/lru/lru.go
generated
vendored
Normal file
@ -0,0 +1,99 @@
|
||||
/*
|
||||
Copyright 2021 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
package lru
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
groupcache "k8s.io/utils/internal/third_party/forked/golang/golang-lru"
|
||||
)
|
||||
|
||||
type Key = groupcache.Key
|
||||
type EvictionFunc = func(key Key, value interface{})
|
||||
|
||||
// Cache is a thread-safe fixed size LRU cache.
|
||||
type Cache struct {
|
||||
cache *groupcache.Cache
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// New creates an LRU of the given size.
|
||||
func New(size int) *Cache {
|
||||
return &Cache{
|
||||
cache: groupcache.New(size),
|
||||
}
|
||||
}
|
||||
|
||||
// NewWithEvictionFunc creates an LRU of the given size with the given eviction func.
|
||||
func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
|
||||
c := New(size)
|
||||
c.cache.OnEvicted = f
|
||||
return c
|
||||
}
|
||||
|
||||
// SetEvictionFunc updates the eviction func
|
||||
func (c *Cache) SetEvictionFunc(f EvictionFunc) error {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
if c.cache.OnEvicted != nil {
|
||||
return fmt.Errorf("lru cache eviction function is already set")
|
||||
}
|
||||
c.cache.OnEvicted = f
|
||||
return nil
|
||||
}
|
||||
|
||||
// Add adds a value to the cache.
|
||||
func (c *Cache) Add(key Key, value interface{}) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.cache.Add(key, value)
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *Cache) Get(key Key) (value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
return c.cache.Get(key)
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *Cache) Remove(key Key) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.cache.Remove(key)
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *Cache) RemoveOldest() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.cache.RemoveOldest()
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *Cache) Len() int {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
return c.cache.Len()
|
||||
}
|
||||
|
||||
// Clear purges all stored items from the cache.
|
||||
func (c *Cache) Clear() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.cache.Clear()
|
||||
}
|
181
e2e/vendor/k8s.io/utils/net/ipfamily.go
generated
vendored
Normal file
181
e2e/vendor/k8s.io/utils/net/ipfamily.go
generated
vendored
Normal file
@ -0,0 +1,181 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// IPFamily refers to a specific family if not empty, i.e. "4" or "6".
|
||||
type IPFamily string
|
||||
|
||||
// Constants for valid IPFamilys:
|
||||
const (
|
||||
IPFamilyUnknown IPFamily = ""
|
||||
|
||||
IPv4 IPFamily = "4"
|
||||
IPv6 IPFamily = "6"
|
||||
)
|
||||
|
||||
// IsDualStackIPs returns true if:
|
||||
// - all elements of ips are valid
|
||||
// - at least one IP from each family (v4 and v6) is present
|
||||
func IsDualStackIPs(ips []net.IP) (bool, error) {
|
||||
v4Found := false
|
||||
v6Found := false
|
||||
for i, ip := range ips {
|
||||
switch IPFamilyOf(ip) {
|
||||
case IPv4:
|
||||
v4Found = true
|
||||
case IPv6:
|
||||
v6Found = true
|
||||
default:
|
||||
return false, fmt.Errorf("invalid IP[%d]: %v", i, ip)
|
||||
}
|
||||
}
|
||||
|
||||
return (v4Found && v6Found), nil
|
||||
}
|
||||
|
||||
// IsDualStackIPStrings returns true if:
|
||||
// - all elements of ips can be parsed as IPs
|
||||
// - at least one IP from each family (v4 and v6) is present
|
||||
func IsDualStackIPStrings(ips []string) (bool, error) {
|
||||
parsedIPs := make([]net.IP, 0, len(ips))
|
||||
for i, ip := range ips {
|
||||
parsedIP := ParseIPSloppy(ip)
|
||||
if parsedIP == nil {
|
||||
return false, fmt.Errorf("invalid IP[%d]: %v", i, ip)
|
||||
}
|
||||
parsedIPs = append(parsedIPs, parsedIP)
|
||||
}
|
||||
return IsDualStackIPs(parsedIPs)
|
||||
}
|
||||
|
||||
// IsDualStackCIDRs returns true if:
|
||||
// - all elements of cidrs are non-nil
|
||||
// - at least one CIDR from each family (v4 and v6) is present
|
||||
func IsDualStackCIDRs(cidrs []*net.IPNet) (bool, error) {
|
||||
v4Found := false
|
||||
v6Found := false
|
||||
for i, cidr := range cidrs {
|
||||
switch IPFamilyOfCIDR(cidr) {
|
||||
case IPv4:
|
||||
v4Found = true
|
||||
case IPv6:
|
||||
v6Found = true
|
||||
default:
|
||||
return false, fmt.Errorf("invalid CIDR[%d]: %v", i, cidr)
|
||||
}
|
||||
}
|
||||
|
||||
return (v4Found && v6Found), nil
|
||||
}
|
||||
|
||||
// IsDualStackCIDRStrings returns if
|
||||
// - all elements of cidrs can be parsed as CIDRs
|
||||
// - at least one CIDR from each family (v4 and v6) is present
|
||||
func IsDualStackCIDRStrings(cidrs []string) (bool, error) {
|
||||
parsedCIDRs, err := ParseCIDRs(cidrs)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return IsDualStackCIDRs(parsedCIDRs)
|
||||
}
|
||||
|
||||
// IPFamilyOf returns the IP family of ip, or IPFamilyUnknown if it is invalid.
|
||||
func IPFamilyOf(ip net.IP) IPFamily {
|
||||
switch {
|
||||
case ip.To4() != nil:
|
||||
return IPv4
|
||||
case ip.To16() != nil:
|
||||
return IPv6
|
||||
default:
|
||||
return IPFamilyUnknown
|
||||
}
|
||||
}
|
||||
|
||||
// IPFamilyOfString returns the IP family of ip, or IPFamilyUnknown if ip cannot
|
||||
// be parsed as an IP.
|
||||
func IPFamilyOfString(ip string) IPFamily {
|
||||
return IPFamilyOf(ParseIPSloppy(ip))
|
||||
}
|
||||
|
||||
// IPFamilyOfCIDR returns the IP family of cidr.
|
||||
func IPFamilyOfCIDR(cidr *net.IPNet) IPFamily {
|
||||
if cidr == nil {
|
||||
return IPFamilyUnknown
|
||||
}
|
||||
return IPFamilyOf(cidr.IP)
|
||||
}
|
||||
|
||||
// IPFamilyOfCIDRString returns the IP family of cidr.
|
||||
func IPFamilyOfCIDRString(cidr string) IPFamily {
|
||||
ip, _, _ := ParseCIDRSloppy(cidr)
|
||||
return IPFamilyOf(ip)
|
||||
}
|
||||
|
||||
// IsIPv6 returns true if netIP is IPv6 (and false if it is IPv4, nil, or invalid).
|
||||
func IsIPv6(netIP net.IP) bool {
|
||||
return IPFamilyOf(netIP) == IPv6
|
||||
}
|
||||
|
||||
// IsIPv6String returns true if ip contains a single IPv6 address and nothing else. It
|
||||
// returns false if ip is an empty string, an IPv4 address, or anything else that is not a
|
||||
// single IPv6 address.
|
||||
func IsIPv6String(ip string) bool {
|
||||
return IPFamilyOfString(ip) == IPv6
|
||||
}
|
||||
|
||||
// IsIPv6CIDR returns true if a cidr is a valid IPv6 CIDR. It returns false if cidr is
|
||||
// nil or an IPv4 CIDR. Its behavior is not defined if cidr is invalid.
|
||||
func IsIPv6CIDR(cidr *net.IPNet) bool {
|
||||
return IPFamilyOfCIDR(cidr) == IPv6
|
||||
}
|
||||
|
||||
// IsIPv6CIDRString returns true if cidr contains a single IPv6 CIDR and nothing else. It
|
||||
// returns false if cidr is an empty string, an IPv4 CIDR, or anything else that is not a
|
||||
// single valid IPv6 CIDR.
|
||||
func IsIPv6CIDRString(cidr string) bool {
|
||||
return IPFamilyOfCIDRString(cidr) == IPv6
|
||||
}
|
||||
|
||||
// IsIPv4 returns true if netIP is IPv4 (and false if it is IPv6, nil, or invalid).
|
||||
func IsIPv4(netIP net.IP) bool {
|
||||
return IPFamilyOf(netIP) == IPv4
|
||||
}
|
||||
|
||||
// IsIPv4String returns true if ip contains a single IPv4 address and nothing else. It
|
||||
// returns false if ip is an empty string, an IPv6 address, or anything else that is not a
|
||||
// single IPv4 address.
|
||||
func IsIPv4String(ip string) bool {
|
||||
return IPFamilyOfString(ip) == IPv4
|
||||
}
|
||||
|
||||
// IsIPv4CIDR returns true if cidr is a valid IPv4 CIDR. It returns false if cidr is nil
|
||||
// or an IPv6 CIDR. Its behavior is not defined if cidr is invalid.
|
||||
func IsIPv4CIDR(cidr *net.IPNet) bool {
|
||||
return IPFamilyOfCIDR(cidr) == IPv4
|
||||
}
|
||||
|
||||
// IsIPv4CIDRString returns true if cidr contains a single IPv4 CIDR and nothing else. It
|
||||
// returns false if cidr is an empty string, an IPv6 CIDR, or anything else that is not a
|
||||
// single valid IPv4 CIDR.
|
||||
func IsIPv4CIDRString(cidr string) bool {
|
||||
return IPFamilyOfCIDRString(cidr) == IPv4
|
||||
}
|
221
e2e/vendor/k8s.io/utils/net/ipnet.go
generated
vendored
Normal file
221
e2e/vendor/k8s.io/utils/net/ipnet.go
generated
vendored
Normal file
@ -0,0 +1,221 @@
|
||||
/*
|
||||
Copyright 2016 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IPNetSet maps string to net.IPNet.
|
||||
type IPNetSet map[string]*net.IPNet
|
||||
|
||||
// ParseIPNets parses string slice to IPNetSet.
|
||||
func ParseIPNets(specs ...string) (IPNetSet, error) {
|
||||
ipnetset := make(IPNetSet)
|
||||
for _, spec := range specs {
|
||||
spec = strings.TrimSpace(spec)
|
||||
_, ipnet, err := ParseCIDRSloppy(spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
k := ipnet.String() // In case of normalization
|
||||
ipnetset[k] = ipnet
|
||||
}
|
||||
return ipnetset, nil
|
||||
}
|
||||
|
||||
// Insert adds items to the set.
|
||||
func (s IPNetSet) Insert(items ...*net.IPNet) {
|
||||
for _, item := range items {
|
||||
s[item.String()] = item
|
||||
}
|
||||
}
|
||||
|
||||
// Delete removes all items from the set.
|
||||
func (s IPNetSet) Delete(items ...*net.IPNet) {
|
||||
for _, item := range items {
|
||||
delete(s, item.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Has returns true if and only if item is contained in the set.
|
||||
func (s IPNetSet) Has(item *net.IPNet) bool {
|
||||
_, contained := s[item.String()]
|
||||
return contained
|
||||
}
|
||||
|
||||
// HasAll returns true if and only if all items are contained in the set.
|
||||
func (s IPNetSet) HasAll(items ...*net.IPNet) bool {
|
||||
for _, item := range items {
|
||||
if !s.Has(item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Difference returns a set of objects that are not in s2
|
||||
// For example:
|
||||
// s1 = {a1, a2, a3}
|
||||
// s2 = {a1, a2, a4, a5}
|
||||
// s1.Difference(s2) = {a3}
|
||||
// s2.Difference(s1) = {a4, a5}
|
||||
func (s IPNetSet) Difference(s2 IPNetSet) IPNetSet {
|
||||
result := make(IPNetSet)
|
||||
for k, i := range s {
|
||||
_, found := s2[k]
|
||||
if found {
|
||||
continue
|
||||
}
|
||||
result[k] = i
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// StringSlice returns a []string with the String representation of each element in the set.
|
||||
// Order is undefined.
|
||||
func (s IPNetSet) StringSlice() []string {
|
||||
a := make([]string, 0, len(s))
|
||||
for k := range s {
|
||||
a = append(a, k)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// IsSuperset returns true if and only if s1 is a superset of s2.
|
||||
func (s IPNetSet) IsSuperset(s2 IPNetSet) bool {
|
||||
for k := range s2 {
|
||||
_, found := s[k]
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Equal returns true if and only if s1 is equal (as a set) to s2.
|
||||
// Two sets are equal if their membership is identical.
|
||||
// (In practice, this means same elements, order doesn't matter)
|
||||
func (s IPNetSet) Equal(s2 IPNetSet) bool {
|
||||
return len(s) == len(s2) && s.IsSuperset(s2)
|
||||
}
|
||||
|
||||
// Len returns the size of the set.
|
||||
func (s IPNetSet) Len() int {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
// IPSet maps string to net.IP
|
||||
type IPSet map[string]net.IP
|
||||
|
||||
// ParseIPSet parses string slice to IPSet
|
||||
func ParseIPSet(items ...string) (IPSet, error) {
|
||||
ipset := make(IPSet)
|
||||
for _, item := range items {
|
||||
ip := ParseIPSloppy(strings.TrimSpace(item))
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("error parsing IP %q", item)
|
||||
}
|
||||
|
||||
ipset[ip.String()] = ip
|
||||
}
|
||||
|
||||
return ipset, nil
|
||||
}
|
||||
|
||||
// Insert adds items to the set.
|
||||
func (s IPSet) Insert(items ...net.IP) {
|
||||
for _, item := range items {
|
||||
s[item.String()] = item
|
||||
}
|
||||
}
|
||||
|
||||
// Delete removes all items from the set.
|
||||
func (s IPSet) Delete(items ...net.IP) {
|
||||
for _, item := range items {
|
||||
delete(s, item.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Has returns true if and only if item is contained in the set.
|
||||
func (s IPSet) Has(item net.IP) bool {
|
||||
_, contained := s[item.String()]
|
||||
return contained
|
||||
}
|
||||
|
||||
// HasAll returns true if and only if all items are contained in the set.
|
||||
func (s IPSet) HasAll(items ...net.IP) bool {
|
||||
for _, item := range items {
|
||||
if !s.Has(item) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Difference returns a set of objects that are not in s2
|
||||
// For example:
|
||||
// s1 = {a1, a2, a3}
|
||||
// s2 = {a1, a2, a4, a5}
|
||||
// s1.Difference(s2) = {a3}
|
||||
// s2.Difference(s1) = {a4, a5}
|
||||
func (s IPSet) Difference(s2 IPSet) IPSet {
|
||||
result := make(IPSet)
|
||||
for k, i := range s {
|
||||
_, found := s2[k]
|
||||
if found {
|
||||
continue
|
||||
}
|
||||
result[k] = i
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// StringSlice returns a []string with the String representation of each element in the set.
|
||||
// Order is undefined.
|
||||
func (s IPSet) StringSlice() []string {
|
||||
a := make([]string, 0, len(s))
|
||||
for k := range s {
|
||||
a = append(a, k)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// IsSuperset returns true if and only if s1 is a superset of s2.
|
||||
func (s IPSet) IsSuperset(s2 IPSet) bool {
|
||||
for k := range s2 {
|
||||
_, found := s[k]
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Equal returns true if and only if s1 is equal (as a set) to s2.
|
||||
// Two sets are equal if their membership is identical.
|
||||
// (In practice, this means same elements, order doesn't matter)
|
||||
func (s IPSet) Equal(s2 IPSet) bool {
|
||||
return len(s) == len(s2) && s.IsSuperset(s2)
|
||||
}
|
||||
|
||||
// Len returns the size of the set.
|
||||
func (s IPSet) Len() int {
|
||||
return len(s)
|
||||
}
|
195
e2e/vendor/k8s.io/utils/net/multi_listen.go
generated
vendored
Normal file
195
e2e/vendor/k8s.io/utils/net/multi_listen.go
generated
vendored
Normal file
@ -0,0 +1,195 @@
|
||||
/*
|
||||
Copyright 2024 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// connErrPair pairs conn and error which is returned by accept on sub-listeners.
|
||||
type connErrPair struct {
|
||||
conn net.Conn
|
||||
err error
|
||||
}
|
||||
|
||||
// multiListener implements net.Listener
|
||||
type multiListener struct {
|
||||
listeners []net.Listener
|
||||
wg sync.WaitGroup
|
||||
|
||||
// connCh passes accepted connections, from child listeners to parent.
|
||||
connCh chan connErrPair
|
||||
// stopCh communicates from parent to child listeners.
|
||||
stopCh chan struct{}
|
||||
}
|
||||
|
||||
// compile time check to ensure *multiListener implements net.Listener
|
||||
var _ net.Listener = &multiListener{}
|
||||
|
||||
// MultiListen returns net.Listener which can listen on and accept connections for
|
||||
// the given network on multiple addresses. Internally it uses stdlib to create
|
||||
// sub-listener and multiplexes connection requests using go-routines.
|
||||
// The network must be "tcp", "tcp4" or "tcp6".
|
||||
// It follows the semantics of net.Listen that primarily means:
|
||||
// 1. If the host is an unspecified/zero IP address with "tcp" network, MultiListen
|
||||
// listens on all available unicast and anycast IP addresses of the local system.
|
||||
// 2. Use "tcp4" or "tcp6" to exclusively listen on IPv4 or IPv6 family, respectively.
|
||||
// 3. The host can accept names (e.g, localhost) and it will create a listener for at
|
||||
// most one of the host's IP.
|
||||
func MultiListen(ctx context.Context, network string, addrs ...string) (net.Listener, error) {
|
||||
var lc net.ListenConfig
|
||||
return multiListen(
|
||||
ctx,
|
||||
network,
|
||||
addrs,
|
||||
func(ctx context.Context, network, address string) (net.Listener, error) {
|
||||
return lc.Listen(ctx, network, address)
|
||||
})
|
||||
}
|
||||
|
||||
// multiListen implements MultiListen by consuming stdlib functions as dependency allowing
|
||||
// mocking for unit-testing.
|
||||
func multiListen(
|
||||
ctx context.Context,
|
||||
network string,
|
||||
addrs []string,
|
||||
listenFunc func(ctx context.Context, network, address string) (net.Listener, error),
|
||||
) (net.Listener, error) {
|
||||
if !(network == "tcp" || network == "tcp4" || network == "tcp6") {
|
||||
return nil, fmt.Errorf("network %q not supported", network)
|
||||
}
|
||||
if len(addrs) == 0 {
|
||||
return nil, fmt.Errorf("no address provided to listen on")
|
||||
}
|
||||
|
||||
ml := &multiListener{
|
||||
connCh: make(chan connErrPair),
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
for _, addr := range addrs {
|
||||
l, err := listenFunc(ctx, network, addr)
|
||||
if err != nil {
|
||||
// close all the sub-listeners and exit
|
||||
_ = ml.Close()
|
||||
return nil, err
|
||||
}
|
||||
ml.listeners = append(ml.listeners, l)
|
||||
}
|
||||
|
||||
for _, l := range ml.listeners {
|
||||
ml.wg.Add(1)
|
||||
go func(l net.Listener) {
|
||||
defer ml.wg.Done()
|
||||
for {
|
||||
// Accept() is blocking, unless ml.Close() is called, in which
|
||||
// case it will return immediately with an error.
|
||||
conn, err := l.Accept()
|
||||
// This assumes that ANY error from Accept() will terminate the
|
||||
// sub-listener. We could maybe be more precise, but it
|
||||
// doesn't seem necessary.
|
||||
terminate := err != nil
|
||||
|
||||
select {
|
||||
case ml.connCh <- connErrPair{conn: conn, err: err}:
|
||||
case <-ml.stopCh:
|
||||
// In case we accepted a connection AND were stopped, and
|
||||
// this select-case was chosen, just throw away the
|
||||
// connection. This avoids potentially blocking on connCh
|
||||
// or leaking a connection.
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
terminate = true
|
||||
}
|
||||
// Make sure we don't loop on Accept() returning an error and
|
||||
// the select choosing the channel case.
|
||||
if terminate {
|
||||
return
|
||||
}
|
||||
}
|
||||
}(l)
|
||||
}
|
||||
return ml, nil
|
||||
}
|
||||
|
||||
// Accept implements net.Listener. It waits for and returns a connection from
|
||||
// any of the sub-listener.
|
||||
func (ml *multiListener) Accept() (net.Conn, error) {
|
||||
// wait for any sub-listener to enqueue an accepted connection
|
||||
connErr, ok := <-ml.connCh
|
||||
if !ok {
|
||||
// The channel will be closed only when Close() is called on the
|
||||
// multiListener. Closing of this channel implies that all
|
||||
// sub-listeners are also closed, which causes a "use of closed
|
||||
// network connection" error on their Accept() calls. We return the
|
||||
// same error for multiListener.Accept() if multiListener.Close()
|
||||
// has already been called.
|
||||
return nil, fmt.Errorf("use of closed network connection")
|
||||
}
|
||||
return connErr.conn, connErr.err
|
||||
}
|
||||
|
||||
// Close implements net.Listener. It will close all sub-listeners and wait for
|
||||
// the go-routines to exit.
|
||||
func (ml *multiListener) Close() error {
|
||||
// Make sure this can be called repeatedly without explosions.
|
||||
select {
|
||||
case <-ml.stopCh:
|
||||
return fmt.Errorf("use of closed network connection")
|
||||
default:
|
||||
}
|
||||
|
||||
// Tell all sub-listeners to stop.
|
||||
close(ml.stopCh)
|
||||
|
||||
// Closing the listeners causes Accept() to immediately return an error in
|
||||
// the sub-listener go-routines.
|
||||
for _, l := range ml.listeners {
|
||||
_ = l.Close()
|
||||
}
|
||||
|
||||
// Wait for all the sub-listener go-routines to exit.
|
||||
ml.wg.Wait()
|
||||
close(ml.connCh)
|
||||
|
||||
// Drain any already-queued connections.
|
||||
for connErr := range ml.connCh {
|
||||
if connErr.conn != nil {
|
||||
_ = connErr.conn.Close()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Addr is an implementation of the net.Listener interface. It always returns
|
||||
// the address of the first listener. Callers should use conn.LocalAddr() to
|
||||
// obtain the actual local address of the sub-listener.
|
||||
func (ml *multiListener) Addr() net.Addr {
|
||||
return ml.listeners[0].Addr()
|
||||
}
|
||||
|
||||
// Addrs is like Addr, but returns the address for all registered listeners.
|
||||
func (ml *multiListener) Addrs() []net.Addr {
|
||||
var ret []net.Addr
|
||||
for _, l := range ml.listeners {
|
||||
ret = append(ret, l.Addr())
|
||||
}
|
||||
return ret
|
||||
}
|
91
e2e/vendor/k8s.io/utils/net/net.go
generated
vendored
Normal file
91
e2e/vendor/k8s.io/utils/net/net.go
generated
vendored
Normal file
@ -0,0 +1,91 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"net"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ParseCIDRs parses a list of cidrs and return error if any is invalid.
|
||||
// order is maintained
|
||||
func ParseCIDRs(cidrsString []string) ([]*net.IPNet, error) {
|
||||
cidrs := make([]*net.IPNet, 0, len(cidrsString))
|
||||
for i, cidrString := range cidrsString {
|
||||
_, cidr, err := ParseCIDRSloppy(cidrString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid CIDR[%d]: %v (%v)", i, cidr, err)
|
||||
}
|
||||
cidrs = append(cidrs, cidr)
|
||||
}
|
||||
return cidrs, nil
|
||||
}
|
||||
|
||||
// ParsePort parses a string representing an IP port. If the string is not a
|
||||
// valid port number, this returns an error.
|
||||
func ParsePort(port string, allowZero bool) (int, error) {
|
||||
portInt, err := strconv.ParseUint(port, 10, 16)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if portInt == 0 && !allowZero {
|
||||
return 0, errors.New("0 is not a valid port number")
|
||||
}
|
||||
return int(portInt), nil
|
||||
}
|
||||
|
||||
// BigForIP creates a big.Int based on the provided net.IP
|
||||
func BigForIP(ip net.IP) *big.Int {
|
||||
// NOTE: Convert to 16-byte representation so we can
|
||||
// handle v4 and v6 values the same way.
|
||||
return big.NewInt(0).SetBytes(ip.To16())
|
||||
}
|
||||
|
||||
// AddIPOffset adds the provided integer offset to a base big.Int representing a net.IP
|
||||
// NOTE: If you started with a v4 address and overflow it, you get a v6 result.
|
||||
func AddIPOffset(base *big.Int, offset int) net.IP {
|
||||
r := big.NewInt(0).Add(base, big.NewInt(int64(offset))).Bytes()
|
||||
r = append(make([]byte, 16), r...)
|
||||
return net.IP(r[len(r)-16:])
|
||||
}
|
||||
|
||||
// RangeSize returns the size of a range in valid addresses.
|
||||
// returns the size of the subnet (or math.MaxInt64 if the range size would overflow int64)
|
||||
func RangeSize(subnet *net.IPNet) int64 {
|
||||
ones, bits := subnet.Mask.Size()
|
||||
if bits == 32 && (bits-ones) >= 31 || bits == 128 && (bits-ones) >= 127 {
|
||||
return 0
|
||||
}
|
||||
// this checks that we are not overflowing an int64
|
||||
if bits-ones >= 63 {
|
||||
return math.MaxInt64
|
||||
}
|
||||
return int64(1) << uint(bits-ones)
|
||||
}
|
||||
|
||||
// GetIndexedIP returns a net.IP that is subnet.IP + index in the contiguous IP space.
|
||||
func GetIndexedIP(subnet *net.IPNet, index int) (net.IP, error) {
|
||||
ip := AddIPOffset(BigForIP(subnet.IP), index)
|
||||
if !subnet.Contains(ip) {
|
||||
return nil, fmt.Errorf("can't generate IP with index %d from subnet. subnet too small. subnet: %q", index, subnet)
|
||||
}
|
||||
return ip, nil
|
||||
}
|
33
e2e/vendor/k8s.io/utils/net/parse.go
generated
vendored
Normal file
33
e2e/vendor/k8s.io/utils/net/parse.go
generated
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
/*
|
||||
Copyright 2021 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
forkednet "k8s.io/utils/internal/third_party/forked/golang/net"
|
||||
)
|
||||
|
||||
// ParseIPSloppy is identical to Go's standard net.ParseIP, except that it allows
|
||||
// leading '0' characters on numbers. Go used to allow this and then changed
|
||||
// the behavior in 1.17. We're choosing to keep it for compat with potential
|
||||
// stored values.
|
||||
var ParseIPSloppy = forkednet.ParseIP
|
||||
|
||||
// ParseCIDRSloppy is identical to Go's standard net.ParseCIDR, except that it allows
|
||||
// leading '0' characters on numbers. Go used to allow this and then changed
|
||||
// the behavior in 1.17. We're choosing to keep it for compat with potential
|
||||
// stored values.
|
||||
var ParseCIDRSloppy = forkednet.ParseCIDR
|
129
e2e/vendor/k8s.io/utils/net/port.go
generated
vendored
Normal file
129
e2e/vendor/k8s.io/utils/net/port.go
generated
vendored
Normal file
@ -0,0 +1,129 @@
|
||||
/*
|
||||
Copyright 2020 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Protocol is a network protocol support by LocalPort.
|
||||
type Protocol string
|
||||
|
||||
// Constants for valid protocols:
|
||||
const (
|
||||
TCP Protocol = "TCP"
|
||||
UDP Protocol = "UDP"
|
||||
)
|
||||
|
||||
// LocalPort represents an IP address and port pair along with a protocol
|
||||
// and potentially a specific IP family.
|
||||
// A LocalPort can be opened and subsequently closed.
|
||||
type LocalPort struct {
|
||||
// Description is an arbitrary string.
|
||||
Description string
|
||||
// IP is the IP address part of a given local port.
|
||||
// If this string is empty, the port binds to all local IP addresses.
|
||||
IP string
|
||||
// If IPFamily is not empty, the port binds only to addresses of this
|
||||
// family.
|
||||
// IF empty along with IP, bind to local addresses of any family.
|
||||
IPFamily IPFamily
|
||||
// Port is the port number.
|
||||
// A value of 0 causes a port to be automatically chosen.
|
||||
Port int
|
||||
// Protocol is the protocol, e.g. TCP
|
||||
Protocol Protocol
|
||||
}
|
||||
|
||||
// NewLocalPort returns a LocalPort instance and ensures IPFamily and IP are
|
||||
// consistent and that the given protocol is valid.
|
||||
func NewLocalPort(desc, ip string, ipFamily IPFamily, port int, protocol Protocol) (*LocalPort, error) {
|
||||
if protocol != TCP && protocol != UDP {
|
||||
return nil, fmt.Errorf("Unsupported protocol %s", protocol)
|
||||
}
|
||||
if ipFamily != IPFamilyUnknown && ipFamily != IPv4 && ipFamily != IPv6 {
|
||||
return nil, fmt.Errorf("Invalid IP family %s", ipFamily)
|
||||
}
|
||||
if ip != "" {
|
||||
parsedIP := ParseIPSloppy(ip)
|
||||
if parsedIP == nil {
|
||||
return nil, fmt.Errorf("invalid ip address %s", ip)
|
||||
}
|
||||
if ipFamily != IPFamilyUnknown {
|
||||
if IPFamily(parsedIP) != ipFamily {
|
||||
return nil, fmt.Errorf("ip address and family mismatch %s, %s", ip, ipFamily)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &LocalPort{Description: desc, IP: ip, IPFamily: ipFamily, Port: port, Protocol: protocol}, nil
|
||||
}
|
||||
|
||||
func (lp *LocalPort) String() string {
|
||||
ipPort := net.JoinHostPort(lp.IP, strconv.Itoa(lp.Port))
|
||||
return fmt.Sprintf("%q (%s/%s%s)", lp.Description, ipPort, strings.ToLower(string(lp.Protocol)), lp.IPFamily)
|
||||
}
|
||||
|
||||
// Closeable closes an opened LocalPort.
|
||||
type Closeable interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
// PortOpener can open a LocalPort and allows later closing it.
|
||||
type PortOpener interface {
|
||||
OpenLocalPort(lp *LocalPort) (Closeable, error)
|
||||
}
|
||||
|
||||
type listenPortOpener struct{}
|
||||
|
||||
// ListenPortOpener opens ports by calling bind() and listen().
|
||||
var ListenPortOpener listenPortOpener
|
||||
|
||||
// OpenLocalPort holds the given local port open.
|
||||
func (l *listenPortOpener) OpenLocalPort(lp *LocalPort) (Closeable, error) {
|
||||
return openLocalPort(lp)
|
||||
}
|
||||
|
||||
func openLocalPort(lp *LocalPort) (Closeable, error) {
|
||||
var socket Closeable
|
||||
hostPort := net.JoinHostPort(lp.IP, strconv.Itoa(lp.Port))
|
||||
switch lp.Protocol {
|
||||
case TCP:
|
||||
network := "tcp" + string(lp.IPFamily)
|
||||
listener, err := net.Listen(network, hostPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
socket = listener
|
||||
case UDP:
|
||||
network := "udp" + string(lp.IPFamily)
|
||||
addr, err := net.ResolveUDPAddr(network, hostPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := net.ListenUDP(network, addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
socket = conn
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown protocol %q", lp.Protocol)
|
||||
}
|
||||
return socket, nil
|
||||
}
|
10
e2e/vendor/k8s.io/utils/nsenter/OWNERS
generated
vendored
Normal file
10
e2e/vendor/k8s.io/utils/nsenter/OWNERS
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
reviewers:
|
||||
- jsafrane
|
||||
- msau42
|
||||
- cofyc
|
||||
approvers:
|
||||
- jsafrane
|
||||
- msau42
|
||||
- cofyc
|
4
e2e/vendor/k8s.io/utils/nsenter/README.md
generated
vendored
Normal file
4
e2e/vendor/k8s.io/utils/nsenter/README.md
generated
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
# NSEnter
|
||||
|
||||
This package provides interfaces for executing and interacting with processes
|
||||
running within a namespace.
|
264
e2e/vendor/k8s.io/utils/nsenter/nsenter.go
generated
vendored
Normal file
264
e2e/vendor/k8s.io/utils/nsenter/nsenter.go
generated
vendored
Normal file
@ -0,0 +1,264 @@
|
||||
//go:build linux
|
||||
// +build linux
|
||||
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package nsenter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"k8s.io/klog/v2"
|
||||
"k8s.io/utils/exec"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultHostRootFsPath is path to host's filesystem mounted into container
|
||||
// with kubelet.
|
||||
DefaultHostRootFsPath = "/rootfs"
|
||||
// mountNsPath is the default mount namespace of the host
|
||||
mountNsPath = "/proc/1/ns/mnt"
|
||||
// nsenterPath is the default nsenter command
|
||||
nsenterPath = "nsenter"
|
||||
)
|
||||
|
||||
// Nsenter is a type alias for backward compatibility
|
||||
type Nsenter = NSEnter
|
||||
|
||||
// NSEnter is part of experimental support for running the kubelet
|
||||
// in a container.
|
||||
//
|
||||
// NSEnter requires:
|
||||
//
|
||||
// 1. Docker >= 1.6 due to the dependency on the slave propagation mode
|
||||
// of the bind-mount of the kubelet root directory in the container.
|
||||
// Docker 1.5 used a private propagation mode for bind-mounts, so mounts
|
||||
// performed in the host's mount namespace do not propagate out to the
|
||||
// bind-mount in this docker version.
|
||||
// 2. The host's root filesystem must be available at /rootfs
|
||||
// 3. The nsenter binary must be on the Kubelet process' PATH in the container's
|
||||
// filesystem.
|
||||
// 4. The Kubelet process must have CAP_SYS_ADMIN (required by nsenter); at
|
||||
// the present, this effectively means that the kubelet is running in a
|
||||
// privileged container.
|
||||
// 5. The volume path used by the Kubelet must be the same inside and outside
|
||||
// the container and be writable by the container (to initialize volume)
|
||||
// contents. TODO: remove this requirement.
|
||||
// 6. The host image must have "mount", "findmnt", "umount", "stat", "touch",
|
||||
// "mkdir", "ls", "sh" and "chmod" binaries in /bin, /usr/sbin, or /usr/bin
|
||||
// 7. The host image should have systemd-run in /bin, /usr/sbin, or /usr/bin if
|
||||
// systemd is installed/enabled in the operating system.
|
||||
//
|
||||
// For more information about mount propagation modes, see:
|
||||
//
|
||||
// https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
|
||||
type NSEnter struct {
|
||||
// a map of commands to their paths on the host filesystem
|
||||
paths map[string]string
|
||||
|
||||
// Path to the host filesystem, typically "/rootfs". Used only for testing.
|
||||
hostRootFsPath string
|
||||
|
||||
// Exec implementation
|
||||
executor exec.Interface
|
||||
}
|
||||
|
||||
// NewNsenter constructs a new instance of NSEnter
|
||||
func NewNsenter(hostRootFsPath string, executor exec.Interface) (*NSEnter, error) {
|
||||
ne := &NSEnter{
|
||||
hostRootFsPath: hostRootFsPath,
|
||||
executor: executor,
|
||||
}
|
||||
if err := ne.initPaths(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ne, nil
|
||||
}
|
||||
|
||||
func (ne *NSEnter) initPaths() error {
|
||||
ne.paths = map[string]string{}
|
||||
binaries := []string{
|
||||
"mount",
|
||||
"findmnt",
|
||||
"umount",
|
||||
"systemd-run",
|
||||
"stat",
|
||||
"touch",
|
||||
"mkdir",
|
||||
"sh",
|
||||
"chmod",
|
||||
"realpath",
|
||||
}
|
||||
// search for the required commands in other locations besides /usr/bin
|
||||
for _, binary := range binaries {
|
||||
// check for binary under the following directories
|
||||
for _, path := range []string{"/", "/bin", "/usr/sbin", "/usr/bin"} {
|
||||
binPath := filepath.Join(path, binary)
|
||||
if _, err := os.Stat(filepath.Join(ne.hostRootFsPath, binPath)); err != nil {
|
||||
continue
|
||||
}
|
||||
ne.paths[binary] = binPath
|
||||
break
|
||||
}
|
||||
// systemd-run is optional, bailout if we don't find any of the other binaries
|
||||
if ne.paths[binary] == "" && binary != "systemd-run" {
|
||||
return fmt.Errorf("unable to find %v", binary)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Exec executes nsenter commands in hostProcMountNsPath mount namespace
|
||||
func (ne *NSEnter) Exec(cmd string, args []string) exec.Cmd {
|
||||
hostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)
|
||||
fullArgs := append([]string{fmt.Sprintf("--mount=%s", hostProcMountNsPath), "--"},
|
||||
append([]string{ne.AbsHostPath(cmd)}, args...)...)
|
||||
klog.V(5).Infof("Running nsenter command: %v %v", nsenterPath, fullArgs)
|
||||
return ne.executor.Command(nsenterPath, fullArgs...)
|
||||
}
|
||||
|
||||
// Command returns a command wrapped with nsenter
|
||||
func (ne *NSEnter) Command(cmd string, args ...string) exec.Cmd {
|
||||
return ne.Exec(cmd, args)
|
||||
}
|
||||
|
||||
// CommandContext returns a CommandContext wrapped with nsenter
|
||||
func (ne *NSEnter) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
|
||||
hostProcMountNsPath := filepath.Join(ne.hostRootFsPath, mountNsPath)
|
||||
fullArgs := append([]string{fmt.Sprintf("--mount=%s", hostProcMountNsPath), "--"},
|
||||
append([]string{ne.AbsHostPath(cmd)}, args...)...)
|
||||
klog.V(5).Infof("Running nsenter command: %v %v", nsenterPath, fullArgs)
|
||||
return ne.executor.CommandContext(ctx, nsenterPath, fullArgs...)
|
||||
}
|
||||
|
||||
// LookPath returns a LookPath wrapped with nsenter
|
||||
func (ne *NSEnter) LookPath(file string) (string, error) {
|
||||
return "", fmt.Errorf("not implemented, error looking up : %s", file)
|
||||
}
|
||||
|
||||
// AbsHostPath returns the absolute runnable path for a specified command
|
||||
func (ne *NSEnter) AbsHostPath(command string) string {
|
||||
path, ok := ne.paths[command]
|
||||
if !ok {
|
||||
return command
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// SupportsSystemd checks whether command systemd-run exists
|
||||
func (ne *NSEnter) SupportsSystemd() (string, bool) {
|
||||
systemdRunPath, ok := ne.paths["systemd-run"]
|
||||
return systemdRunPath, ok && systemdRunPath != ""
|
||||
}
|
||||
|
||||
// EvalSymlinks returns the path name on the host after evaluating symlinks on the
|
||||
// host.
|
||||
// mustExist makes EvalSymlinks to return error when the path does not
|
||||
// exist. When it's false, it evaluates symlinks of the existing part and
|
||||
// blindly adds the non-existing part:
|
||||
// pathname: /mnt/volume/non/existing/directory
|
||||
//
|
||||
// /mnt/volume exists
|
||||
// non/existing/directory does not exist
|
||||
//
|
||||
// -> It resolves symlinks in /mnt/volume to say /mnt/foo and returns
|
||||
//
|
||||
// /mnt/foo/non/existing/directory.
|
||||
//
|
||||
// BEWARE! EvalSymlinks is not able to detect symlink looks with mustExist=false!
|
||||
// If /tmp/link is symlink to /tmp/link, EvalSymlinks(/tmp/link/foo) returns /tmp/link/foo.
|
||||
func (ne *NSEnter) EvalSymlinks(pathname string, mustExist bool) (string, error) {
|
||||
var args []string
|
||||
if mustExist {
|
||||
// "realpath -e: all components of the path must exist"
|
||||
args = []string{"-e", pathname}
|
||||
} else {
|
||||
// "realpath -m: no path components need exist or be a directory"
|
||||
args = []string{"-m", pathname}
|
||||
}
|
||||
outBytes, err := ne.Exec("realpath", args).CombinedOutput()
|
||||
if err != nil {
|
||||
klog.Infof("failed to resolve symbolic links on %s: %v", pathname, err)
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(outBytes)), nil
|
||||
}
|
||||
|
||||
// KubeletPath returns the path name that can be accessed by containerized
|
||||
// kubelet. It is recommended to resolve symlinks on the host by EvalSymlinks
|
||||
// before calling this function
|
||||
func (ne *NSEnter) KubeletPath(pathname string) string {
|
||||
return filepath.Join(ne.hostRootFsPath, pathname)
|
||||
}
|
||||
|
||||
// NewFakeNsenter returns a NSEnter that does not run "nsenter --mount=... --",
|
||||
// but runs everything in the same mount namespace as the unit test binary.
|
||||
// rootfsPath is supposed to be a symlink, e.g. /tmp/xyz/rootfs -> /.
|
||||
// This fake NSEnter is enough for most operations, e.g. to resolve symlinks,
|
||||
// but it's not enough to call /bin/mount - unit tests don't run as root.
|
||||
func NewFakeNsenter(rootfsPath string) (*NSEnter, error) {
|
||||
executor := &fakeExec{
|
||||
rootfsPath: rootfsPath,
|
||||
}
|
||||
// prepare /rootfs/bin, usr/bin and usr/sbin
|
||||
bin := filepath.Join(rootfsPath, "bin")
|
||||
if err := os.Symlink("/bin", bin); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
usr := filepath.Join(rootfsPath, "usr")
|
||||
if err := os.Mkdir(usr, 0755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
usrbin := filepath.Join(usr, "bin")
|
||||
if err := os.Symlink("/usr/bin", usrbin); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
usrsbin := filepath.Join(usr, "sbin")
|
||||
if err := os.Symlink("/usr/sbin", usrsbin); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return NewNsenter(rootfsPath, executor)
|
||||
}
|
||||
|
||||
type fakeExec struct {
|
||||
rootfsPath string
|
||||
}
|
||||
|
||||
func (f fakeExec) Command(cmd string, args ...string) exec.Cmd {
|
||||
// This will intentionaly panic if NSEnter does not provide enough arguments.
|
||||
realCmd := args[2]
|
||||
realArgs := args[3:]
|
||||
return exec.New().Command(realCmd, realArgs...)
|
||||
}
|
||||
|
||||
func (fakeExec) LookPath(file string) (string, error) {
|
||||
return "", errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (fakeExec) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ exec.Interface = fakeExec{}
|
||||
var _ exec.Interface = &NSEnter{}
|
80
e2e/vendor/k8s.io/utils/nsenter/nsenter_unsupported.go
generated
vendored
Normal file
80
e2e/vendor/k8s.io/utils/nsenter/nsenter_unsupported.go
generated
vendored
Normal file
@ -0,0 +1,80 @@
|
||||
//go:build !linux
|
||||
// +build !linux
|
||||
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package nsenter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"k8s.io/utils/exec"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultHostRootFsPath is path to host's filesystem mounted into container
|
||||
// with kubelet.
|
||||
DefaultHostRootFsPath = "/rootfs"
|
||||
)
|
||||
|
||||
// Nsenter is a type alias for backward compatibility
|
||||
type Nsenter = NSEnter
|
||||
|
||||
// NSEnter is part of experimental support for running the kubelet
|
||||
// in a container.
|
||||
type NSEnter struct {
|
||||
// a map of commands to their paths on the host filesystem
|
||||
Paths map[string]string
|
||||
}
|
||||
|
||||
// NewNsenter constructs a new instance of NSEnter
|
||||
func NewNsenter(hostRootFsPath string, executor exec.Interface) (*Nsenter, error) {
|
||||
return &Nsenter{}, nil
|
||||
}
|
||||
|
||||
// Exec executes nsenter commands in hostProcMountNsPath mount namespace
|
||||
func (ne *NSEnter) Exec(cmd string, args []string) exec.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AbsHostPath returns the absolute runnable path for a specified command
|
||||
func (ne *NSEnter) AbsHostPath(command string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// SupportsSystemd checks whether command systemd-run exists
|
||||
func (ne *NSEnter) SupportsSystemd() (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
// Command returns a command wrapped with nenter
|
||||
func (ne *NSEnter) Command(cmd string, args ...string) exec.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// CommandContext returns a CommandContext wrapped with nsenter
|
||||
func (ne *NSEnter) CommandContext(ctx context.Context, cmd string, args ...string) exec.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// LookPath returns a LookPath wrapped with nsenter
|
||||
func (ne *NSEnter) LookPath(file string) (string, error) {
|
||||
return "", fmt.Errorf("not implemented, error looking up : %s", file)
|
||||
}
|
||||
|
||||
var _ exec.Interface = &NSEnter{}
|
78
e2e/vendor/k8s.io/utils/path/file.go
generated
vendored
Normal file
78
e2e/vendor/k8s.io/utils/path/file.go
generated
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
/*
|
||||
Copyright 2017 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package path
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
// LinkTreatment is the base type for constants used by Exists that indicate
|
||||
// how symlinks are treated for existence checks.
|
||||
type LinkTreatment int
|
||||
|
||||
const (
|
||||
// CheckFollowSymlink follows the symlink and verifies that the target of
|
||||
// the symlink exists.
|
||||
CheckFollowSymlink LinkTreatment = iota
|
||||
|
||||
// CheckSymlinkOnly does not follow the symlink and verifies only that they
|
||||
// symlink itself exists.
|
||||
CheckSymlinkOnly
|
||||
)
|
||||
|
||||
// ErrInvalidLinkTreatment indicates that the link treatment behavior requested
|
||||
// is not a valid behavior.
|
||||
var ErrInvalidLinkTreatment = errors.New("unknown link behavior")
|
||||
|
||||
// Exists checks if specified file, directory, or symlink exists. The behavior
|
||||
// of the test depends on the linkBehaviour argument. See LinkTreatment for
|
||||
// more details.
|
||||
func Exists(linkBehavior LinkTreatment, filename string) (bool, error) {
|
||||
var err error
|
||||
|
||||
if linkBehavior == CheckFollowSymlink {
|
||||
_, err = os.Stat(filename)
|
||||
} else if linkBehavior == CheckSymlinkOnly {
|
||||
_, err = os.Lstat(filename)
|
||||
} else {
|
||||
return false, ErrInvalidLinkTreatment
|
||||
}
|
||||
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
} else if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ReadDirNoStat returns a string of files/directories contained
|
||||
// in dirname without calling lstat on them.
|
||||
func ReadDirNoStat(dirname string) ([]string, error) {
|
||||
if dirname == "" {
|
||||
dirname = "."
|
||||
}
|
||||
|
||||
f, err := os.Open(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return f.Readdirnames(-1)
|
||||
}
|
10
e2e/vendor/k8s.io/utils/pointer/OWNERS
generated
vendored
Normal file
10
e2e/vendor/k8s.io/utils/pointer/OWNERS
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
approvers:
|
||||
- apelisse
|
||||
- stewart-yu
|
||||
- thockin
|
||||
reviewers:
|
||||
- apelisse
|
||||
- stewart-yu
|
||||
- thockin
|
3
e2e/vendor/k8s.io/utils/pointer/README.md
generated
vendored
Normal file
3
e2e/vendor/k8s.io/utils/pointer/README.md
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
# Pointer
|
||||
|
||||
This package provides some functions for pointer-based operations.
|
249
e2e/vendor/k8s.io/utils/pointer/pointer.go
generated
vendored
Normal file
249
e2e/vendor/k8s.io/utils/pointer/pointer.go
generated
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
/*
|
||||
Copyright 2018 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Deprecated: Use functions in k8s.io/utils/ptr instead: ptr.To to obtain
|
||||
// a pointer, ptr.Deref to dereference a pointer, ptr.Equal to compare
|
||||
// dereferenced pointers.
|
||||
package pointer
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"k8s.io/utils/ptr"
|
||||
)
|
||||
|
||||
// AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when,
|
||||
// for example, an API struct is handled by plugins which need to distinguish
|
||||
// "no plugin accepted this spec" from "this spec is empty".
|
||||
//
|
||||
// This function is only valid for structs and pointers to structs. Any other
|
||||
// type will cause a panic. Passing a typed nil pointer will return true.
|
||||
//
|
||||
// Deprecated: Use ptr.AllPtrFieldsNil instead.
|
||||
var AllPtrFieldsNil = ptr.AllPtrFieldsNil
|
||||
|
||||
// Int returns a pointer to an int.
|
||||
var Int = ptr.To[int]
|
||||
|
||||
// IntPtr is a function variable referring to Int.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var IntPtr = Int // for back-compat
|
||||
|
||||
// IntDeref dereferences the int ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var IntDeref = ptr.Deref[int]
|
||||
|
||||
// IntPtrDerefOr is a function variable referring to IntDeref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var IntPtrDerefOr = IntDeref // for back-compat
|
||||
|
||||
// Int32 returns a pointer to an int32.
|
||||
var Int32 = ptr.To[int32]
|
||||
|
||||
// Int32Ptr is a function variable referring to Int32.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Int32Ptr = Int32 // for back-compat
|
||||
|
||||
// Int32Deref dereferences the int32 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Int32Deref = ptr.Deref[int32]
|
||||
|
||||
// Int32PtrDerefOr is a function variable referring to Int32Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Int32PtrDerefOr = Int32Deref // for back-compat
|
||||
|
||||
// Int32Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Int32Equal = ptr.Equal[int32]
|
||||
|
||||
// Uint returns a pointer to an uint
|
||||
var Uint = ptr.To[uint]
|
||||
|
||||
// UintPtr is a function variable referring to Uint.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var UintPtr = Uint // for back-compat
|
||||
|
||||
// UintDeref dereferences the uint ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var UintDeref = ptr.Deref[uint]
|
||||
|
||||
// UintPtrDerefOr is a function variable referring to UintDeref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var UintPtrDerefOr = UintDeref // for back-compat
|
||||
|
||||
// Uint32 returns a pointer to an uint32.
|
||||
var Uint32 = ptr.To[uint32]
|
||||
|
||||
// Uint32Ptr is a function variable referring to Uint32.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Uint32Ptr = Uint32 // for back-compat
|
||||
|
||||
// Uint32Deref dereferences the uint32 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Uint32Deref = ptr.Deref[uint32]
|
||||
|
||||
// Uint32PtrDerefOr is a function variable referring to Uint32Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Uint32PtrDerefOr = Uint32Deref // for back-compat
|
||||
|
||||
// Uint32Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Uint32Equal = ptr.Equal[uint32]
|
||||
|
||||
// Int64 returns a pointer to an int64.
|
||||
var Int64 = ptr.To[int64]
|
||||
|
||||
// Int64Ptr is a function variable referring to Int64.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Int64Ptr = Int64 // for back-compat
|
||||
|
||||
// Int64Deref dereferences the int64 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Int64Deref = ptr.Deref[int64]
|
||||
|
||||
// Int64PtrDerefOr is a function variable referring to Int64Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Int64PtrDerefOr = Int64Deref // for back-compat
|
||||
|
||||
// Int64Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Int64Equal = ptr.Equal[int64]
|
||||
|
||||
// Uint64 returns a pointer to an uint64.
|
||||
var Uint64 = ptr.To[uint64]
|
||||
|
||||
// Uint64Ptr is a function variable referring to Uint64.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Uint64Ptr = Uint64 // for back-compat
|
||||
|
||||
// Uint64Deref dereferences the uint64 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Uint64Deref = ptr.Deref[uint64]
|
||||
|
||||
// Uint64PtrDerefOr is a function variable referring to Uint64Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Uint64PtrDerefOr = Uint64Deref // for back-compat
|
||||
|
||||
// Uint64Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Uint64Equal = ptr.Equal[uint64]
|
||||
|
||||
// Bool returns a pointer to a bool.
|
||||
var Bool = ptr.To[bool]
|
||||
|
||||
// BoolPtr is a function variable referring to Bool.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var BoolPtr = Bool // for back-compat
|
||||
|
||||
// BoolDeref dereferences the bool ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var BoolDeref = ptr.Deref[bool]
|
||||
|
||||
// BoolPtrDerefOr is a function variable referring to BoolDeref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var BoolPtrDerefOr = BoolDeref // for back-compat
|
||||
|
||||
// BoolEqual returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var BoolEqual = ptr.Equal[bool]
|
||||
|
||||
// String returns a pointer to a string.
|
||||
var String = ptr.To[string]
|
||||
|
||||
// StringPtr is a function variable referring to String.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var StringPtr = String // for back-compat
|
||||
|
||||
// StringDeref dereferences the string ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var StringDeref = ptr.Deref[string]
|
||||
|
||||
// StringPtrDerefOr is a function variable referring to StringDeref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var StringPtrDerefOr = StringDeref // for back-compat
|
||||
|
||||
// StringEqual returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var StringEqual = ptr.Equal[string]
|
||||
|
||||
// Float32 returns a pointer to a float32.
|
||||
var Float32 = ptr.To[float32]
|
||||
|
||||
// Float32Ptr is a function variable referring to Float32.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Float32Ptr = Float32
|
||||
|
||||
// Float32Deref dereferences the float32 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Float32Deref = ptr.Deref[float32]
|
||||
|
||||
// Float32PtrDerefOr is a function variable referring to Float32Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Float32PtrDerefOr = Float32Deref // for back-compat
|
||||
|
||||
// Float32Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Float32Equal = ptr.Equal[float32]
|
||||
|
||||
// Float64 returns a pointer to a float64.
|
||||
var Float64 = ptr.To[float64]
|
||||
|
||||
// Float64Ptr is a function variable referring to Float64.
|
||||
//
|
||||
// Deprecated: Use ptr.To instead.
|
||||
var Float64Ptr = Float64
|
||||
|
||||
// Float64Deref dereferences the float64 ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var Float64Deref = ptr.Deref[float64]
|
||||
|
||||
// Float64PtrDerefOr is a function variable referring to Float64Deref.
|
||||
//
|
||||
// Deprecated: Use ptr.Deref instead.
|
||||
var Float64PtrDerefOr = Float64Deref // for back-compat
|
||||
|
||||
// Float64Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var Float64Equal = ptr.Equal[float64]
|
||||
|
||||
// Duration returns a pointer to a time.Duration.
|
||||
var Duration = ptr.To[time.Duration]
|
||||
|
||||
// DurationDeref dereferences the time.Duration ptr and returns it if not nil, or else
|
||||
// returns def.
|
||||
var DurationDeref = ptr.Deref[time.Duration]
|
||||
|
||||
// DurationEqual returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
var DurationEqual = ptr.Equal[time.Duration]
|
10
e2e/vendor/k8s.io/utils/ptr/OWNERS
generated
vendored
Normal file
10
e2e/vendor/k8s.io/utils/ptr/OWNERS
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
approvers:
|
||||
- apelisse
|
||||
- stewart-yu
|
||||
- thockin
|
||||
reviewers:
|
||||
- apelisse
|
||||
- stewart-yu
|
||||
- thockin
|
3
e2e/vendor/k8s.io/utils/ptr/README.md
generated
vendored
Normal file
3
e2e/vendor/k8s.io/utils/ptr/README.md
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
# Pointer
|
||||
|
||||
This package provides some functions for pointer-based operations.
|
73
e2e/vendor/k8s.io/utils/ptr/ptr.go
generated
vendored
Normal file
73
e2e/vendor/k8s.io/utils/ptr/ptr.go
generated
vendored
Normal file
@ -0,0 +1,73 @@
|
||||
/*
|
||||
Copyright 2023 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package ptr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// AllPtrFieldsNil tests whether all pointer fields in a struct are nil. This is useful when,
|
||||
// for example, an API struct is handled by plugins which need to distinguish
|
||||
// "no plugin accepted this spec" from "this spec is empty".
|
||||
//
|
||||
// This function is only valid for structs and pointers to structs. Any other
|
||||
// type will cause a panic. Passing a typed nil pointer will return true.
|
||||
func AllPtrFieldsNil(obj interface{}) bool {
|
||||
v := reflect.ValueOf(obj)
|
||||
if !v.IsValid() {
|
||||
panic(fmt.Sprintf("reflect.ValueOf() produced a non-valid Value for %#v", obj))
|
||||
}
|
||||
if v.Kind() == reflect.Ptr {
|
||||
if v.IsNil() {
|
||||
return true
|
||||
}
|
||||
v = v.Elem()
|
||||
}
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
if v.Field(i).Kind() == reflect.Ptr && !v.Field(i).IsNil() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// To returns a pointer to the given value.
|
||||
func To[T any](v T) *T {
|
||||
return &v
|
||||
}
|
||||
|
||||
// Deref dereferences ptr and returns the value it points to if no nil, or else
|
||||
// returns def.
|
||||
func Deref[T any](ptr *T, def T) T {
|
||||
if ptr != nil {
|
||||
return *ptr
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// Equal returns true if both arguments are nil or both arguments
|
||||
// dereference to the same value.
|
||||
func Equal[T comparable](a, b *T) bool {
|
||||
if (a == nil) != (b == nil) {
|
||||
return false
|
||||
}
|
||||
if a == nil {
|
||||
return true
|
||||
}
|
||||
return *a == *b
|
||||
}
|
36
e2e/vendor/k8s.io/utils/strings/escape.go
generated
vendored
Normal file
36
e2e/vendor/k8s.io/utils/strings/escape.go
generated
vendored
Normal file
@ -0,0 +1,36 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package strings
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// EscapeQualifiedName converts a plugin name, which might contain a / into a
|
||||
// string that is safe to use on-disk. This assumes that the input has already
|
||||
// been validates as a qualified name. we use "~" rather than ":" here in case
|
||||
// we ever use a filesystem that doesn't allow ":".
|
||||
func EscapeQualifiedName(in string) string {
|
||||
return strings.Replace(in, "/", "~", -1)
|
||||
}
|
||||
|
||||
// UnescapeQualifiedName converts an escaped plugin name (as per EscapeQualifiedName)
|
||||
// back to its normal form. This assumes that the input has already been
|
||||
// validates as a qualified name.
|
||||
func UnescapeQualifiedName(in string) string {
|
||||
return strings.Replace(in, "~", "/", -1)
|
||||
}
|
64
e2e/vendor/k8s.io/utils/strings/line_delimiter.go
generated
vendored
Normal file
64
e2e/vendor/k8s.io/utils/strings/line_delimiter.go
generated
vendored
Normal file
@ -0,0 +1,64 @@
|
||||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package strings
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LineDelimiter is a filter that will split input on lines
|
||||
// and bracket each line with the delimiter string.
|
||||
type LineDelimiter struct {
|
||||
output io.Writer
|
||||
delimiter []byte
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
// NewLineDelimiter allocates a new io.Writer that will split input on lines
|
||||
// and bracket each line with the delimiter string. This can be useful in
|
||||
// output tests where it is difficult to see and test trailing whitespace.
|
||||
func NewLineDelimiter(output io.Writer, delimiter string) *LineDelimiter {
|
||||
return &LineDelimiter{output: output, delimiter: []byte(delimiter)}
|
||||
}
|
||||
|
||||
// Write writes buf to the LineDelimiter ld. The only errors returned are ones
|
||||
// encountered while writing to the underlying output stream.
|
||||
func (ld *LineDelimiter) Write(buf []byte) (n int, err error) {
|
||||
return ld.buf.Write(buf)
|
||||
}
|
||||
|
||||
// Flush all lines up until now. This will assume insert a linebreak at the current point of the stream.
|
||||
func (ld *LineDelimiter) Flush() (err error) {
|
||||
lines := strings.Split(ld.buf.String(), "\n")
|
||||
for _, line := range lines {
|
||||
if _, err = ld.output.Write(ld.delimiter); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = ld.output.Write([]byte(line)); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = ld.output.Write(ld.delimiter); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = ld.output.Write([]byte("\n")); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
46
e2e/vendor/k8s.io/utils/strings/strings.go
generated
vendored
Normal file
46
e2e/vendor/k8s.io/utils/strings/strings.go
generated
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package strings
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SplitQualifiedName Splits a fully qualified name and returns its namespace and name.
|
||||
// Assumes that the input 'str' has been validated.
|
||||
func SplitQualifiedName(str string) (string, string) {
|
||||
parts := strings.Split(str, "/")
|
||||
if len(parts) < 2 {
|
||||
return "", str
|
||||
}
|
||||
return parts[0], parts[1]
|
||||
}
|
||||
|
||||
// JoinQualifiedName joins 'namespace' and 'name' and returns a fully qualified name
|
||||
// Assumes that the input is valid.
|
||||
func JoinQualifiedName(namespace, name string) string {
|
||||
return path.Join(namespace, name)
|
||||
}
|
||||
|
||||
// ShortenString returns the first N slice of a string.
|
||||
func ShortenString(str string, n int) string {
|
||||
if len(str) <= n {
|
||||
return str
|
||||
}
|
||||
return str[:n]
|
||||
}
|
67
e2e/vendor/k8s.io/utils/trace/README.md
generated
vendored
Normal file
67
e2e/vendor/k8s.io/utils/trace/README.md
generated
vendored
Normal file
@ -0,0 +1,67 @@
|
||||
# Trace
|
||||
|
||||
This package provides an interface for recording the latency of operations and logging details
|
||||
about all operations where the latency exceeds a limit.
|
||||
|
||||
## Usage
|
||||
|
||||
To create a trace:
|
||||
|
||||
```go
|
||||
func doSomething() {
|
||||
opTrace := trace.New("operation", Field{Key: "fieldKey1", Value: "fieldValue1"})
|
||||
defer opTrace.LogIfLong(100 * time.Millisecond)
|
||||
// do something
|
||||
}
|
||||
```
|
||||
|
||||
To split an trace into multiple steps:
|
||||
|
||||
```go
|
||||
func doSomething() {
|
||||
opTrace := trace.New("operation")
|
||||
defer opTrace.LogIfLong(100 * time.Millisecond)
|
||||
// do step 1
|
||||
opTrace.Step("step1", Field{Key: "stepFieldKey1", Value: "stepFieldValue1"})
|
||||
// do step 2
|
||||
opTrace.Step("step2")
|
||||
}
|
||||
```
|
||||
|
||||
To nest traces:
|
||||
|
||||
```go
|
||||
func doSomething() {
|
||||
rootTrace := trace.New("rootOperation")
|
||||
defer rootTrace.LogIfLong(100 * time.Millisecond)
|
||||
|
||||
func() {
|
||||
nestedTrace := rootTrace.Nest("nested", Field{Key: "nestedFieldKey1", Value: "nestedFieldValue1"})
|
||||
defer nestedTrace.LogIfLong(50 * time.Millisecond)
|
||||
// do nested operation
|
||||
}()
|
||||
}
|
||||
```
|
||||
|
||||
Traces can also be logged unconditionally or introspected:
|
||||
|
||||
```go
|
||||
opTrace.TotalTime() // Duration since the Trace was created
|
||||
opTrace.Log() // unconditionally log the trace
|
||||
```
|
||||
|
||||
### Using context.Context to nest traces
|
||||
|
||||
`context.Context` can be used to manage nested traces. Create traces by calling `trace.GetTraceFromContext(ctx).Nest`.
|
||||
This is safe even if there is no parent trace already in the context because `(*(Trace)nil).Nest()` returns
|
||||
a top level trace.
|
||||
|
||||
```go
|
||||
func doSomething(ctx context.Context) {
|
||||
opTrace := trace.FromContext(ctx).Nest("operation") // create a trace, possibly nested
|
||||
ctx = trace.ContextWithTrace(ctx, opTrace) // make this trace the parent trace of the context
|
||||
defer opTrace.LogIfLong(50 * time.Millisecond)
|
||||
|
||||
doSomethingElse(ctx)
|
||||
}
|
||||
```
|
319
e2e/vendor/k8s.io/utils/trace/trace.go
generated
vendored
Normal file
319
e2e/vendor/k8s.io/utils/trace/trace.go
generated
vendored
Normal file
@ -0,0 +1,319 @@
|
||||
/*
|
||||
Copyright 2015 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package trace
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"k8s.io/klog/v2"
|
||||
)
|
||||
|
||||
var klogV = func(lvl klog.Level) bool {
|
||||
return klog.V(lvl).Enabled()
|
||||
}
|
||||
|
||||
// Field is a key value pair that provides additional details about the trace.
|
||||
type Field struct {
|
||||
Key string
|
||||
Value interface{}
|
||||
}
|
||||
|
||||
func (f Field) format() string {
|
||||
return fmt.Sprintf("%s:%v", f.Key, f.Value)
|
||||
}
|
||||
|
||||
func writeFields(b *bytes.Buffer, l []Field) {
|
||||
for i, f := range l {
|
||||
b.WriteString(f.format())
|
||||
if i < len(l)-1 {
|
||||
b.WriteString(",")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeTraceItemSummary(b *bytes.Buffer, msg string, totalTime time.Duration, startTime time.Time, fields []Field) {
|
||||
b.WriteString(fmt.Sprintf("%q ", msg))
|
||||
if len(fields) > 0 {
|
||||
writeFields(b, fields)
|
||||
b.WriteString(" ")
|
||||
}
|
||||
|
||||
b.WriteString(fmt.Sprintf("%vms (%v)", durationToMilliseconds(totalTime), startTime.Format("15:04:05.000")))
|
||||
}
|
||||
|
||||
func durationToMilliseconds(timeDuration time.Duration) int64 {
|
||||
return timeDuration.Nanoseconds() / 1e6
|
||||
}
|
||||
|
||||
type traceItem interface {
|
||||
// rLock must be called before invoking time or writeItem.
|
||||
rLock()
|
||||
// rUnlock must be called after processing the item is complete.
|
||||
rUnlock()
|
||||
|
||||
// time returns when the trace was recorded as completed.
|
||||
time() time.Time
|
||||
// writeItem outputs the traceItem to the buffer. If stepThreshold is non-nil, only output the
|
||||
// traceItem if its the duration exceeds the stepThreshold.
|
||||
// Each line of output is prefixed by formatter to visually indent nested items.
|
||||
writeItem(b *bytes.Buffer, formatter string, startTime time.Time, stepThreshold *time.Duration)
|
||||
}
|
||||
|
||||
type traceStep struct {
|
||||
stepTime time.Time
|
||||
msg string
|
||||
fields []Field
|
||||
}
|
||||
|
||||
// rLock doesn't need to do anything because traceStep instances are immutable.
|
||||
func (s traceStep) rLock() {}
|
||||
func (s traceStep) rUnlock() {}
|
||||
|
||||
func (s traceStep) time() time.Time {
|
||||
return s.stepTime
|
||||
}
|
||||
|
||||
func (s traceStep) writeItem(b *bytes.Buffer, formatter string, startTime time.Time, stepThreshold *time.Duration) {
|
||||
stepDuration := s.stepTime.Sub(startTime)
|
||||
if stepThreshold == nil || *stepThreshold == 0 || stepDuration >= *stepThreshold || klogV(4) {
|
||||
b.WriteString(fmt.Sprintf("%s---", formatter))
|
||||
writeTraceItemSummary(b, s.msg, stepDuration, s.stepTime, s.fields)
|
||||
}
|
||||
}
|
||||
|
||||
// Trace keeps track of a set of "steps" and allows us to log a specific
|
||||
// step if it took longer than its share of the total allowed time
|
||||
type Trace struct {
|
||||
// constant fields
|
||||
name string
|
||||
fields []Field
|
||||
startTime time.Time
|
||||
parentTrace *Trace
|
||||
// fields guarded by a lock
|
||||
lock sync.RWMutex
|
||||
threshold *time.Duration
|
||||
endTime *time.Time
|
||||
traceItems []traceItem
|
||||
}
|
||||
|
||||
func (t *Trace) rLock() {
|
||||
t.lock.RLock()
|
||||
}
|
||||
|
||||
func (t *Trace) rUnlock() {
|
||||
t.lock.RUnlock()
|
||||
}
|
||||
|
||||
func (t *Trace) time() time.Time {
|
||||
if t.endTime != nil {
|
||||
return *t.endTime
|
||||
}
|
||||
return t.startTime // if the trace is incomplete, don't assume an end time
|
||||
}
|
||||
|
||||
func (t *Trace) writeItem(b *bytes.Buffer, formatter string, startTime time.Time, stepThreshold *time.Duration) {
|
||||
if t.durationIsWithinThreshold() || klogV(4) {
|
||||
b.WriteString(fmt.Sprintf("%v[", formatter))
|
||||
writeTraceItemSummary(b, t.name, t.TotalTime(), t.startTime, t.fields)
|
||||
if st := t.calculateStepThreshold(); st != nil {
|
||||
stepThreshold = st
|
||||
}
|
||||
t.writeTraceSteps(b, formatter+" ", stepThreshold)
|
||||
b.WriteString("]")
|
||||
return
|
||||
}
|
||||
// If the trace should not be written, still check for nested traces that should be written
|
||||
for _, s := range t.traceItems {
|
||||
if nestedTrace, ok := s.(*Trace); ok {
|
||||
nestedTrace.writeItem(b, formatter, startTime, stepThreshold)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a Trace with the specified name. The name identifies the operation to be traced. The
|
||||
// Fields add key value pairs to provide additional details about the trace, such as operation inputs.
|
||||
func New(name string, fields ...Field) *Trace {
|
||||
return &Trace{name: name, startTime: time.Now(), fields: fields}
|
||||
}
|
||||
|
||||
// Step adds a new step with a specific message. Call this at the end of an execution step to record
|
||||
// how long it took. The Fields add key value pairs to provide additional details about the trace
|
||||
// step.
|
||||
func (t *Trace) Step(msg string, fields ...Field) {
|
||||
t.lock.Lock()
|
||||
defer t.lock.Unlock()
|
||||
if t.traceItems == nil {
|
||||
// traces almost always have less than 6 steps, do this to avoid more than a single allocation
|
||||
t.traceItems = make([]traceItem, 0, 6)
|
||||
}
|
||||
t.traceItems = append(t.traceItems, traceStep{stepTime: time.Now(), msg: msg, fields: fields})
|
||||
}
|
||||
|
||||
// Nest adds a nested trace with the given message and fields and returns it.
|
||||
// As a convenience, if the receiver is nil, returns a top level trace. This allows
|
||||
// one to call FromContext(ctx).Nest without having to check if the trace
|
||||
// in the context is nil.
|
||||
func (t *Trace) Nest(msg string, fields ...Field) *Trace {
|
||||
newTrace := New(msg, fields...)
|
||||
if t != nil {
|
||||
newTrace.parentTrace = t
|
||||
t.lock.Lock()
|
||||
t.traceItems = append(t.traceItems, newTrace)
|
||||
t.lock.Unlock()
|
||||
}
|
||||
return newTrace
|
||||
}
|
||||
|
||||
// Log is used to dump all the steps in the Trace. It also logs the nested trace messages using indentation.
|
||||
// If the Trace is nested it is not immediately logged. Instead, it is logged when the trace it is nested within
|
||||
// is logged.
|
||||
func (t *Trace) Log() {
|
||||
endTime := time.Now()
|
||||
t.lock.Lock()
|
||||
t.endTime = &endTime
|
||||
t.lock.Unlock()
|
||||
// an explicit logging request should dump all the steps out at the higher level
|
||||
if t.parentTrace == nil && klogV(2) { // We don't start logging until Log or LogIfLong is called on the root trace
|
||||
t.logTrace()
|
||||
}
|
||||
}
|
||||
|
||||
// LogIfLong only logs the trace if the duration of the trace exceeds the threshold.
|
||||
// Only steps that took longer than their share or the given threshold are logged.
|
||||
// If klog is at verbosity level 4 or higher and the trace took longer than the threshold,
|
||||
// all substeps and subtraces are logged. Otherwise, only those which took longer than
|
||||
// their own threshold.
|
||||
// If the Trace is nested it is not immediately logged. Instead, it is logged when the trace it
|
||||
// is nested within is logged.
|
||||
func (t *Trace) LogIfLong(threshold time.Duration) {
|
||||
t.lock.Lock()
|
||||
t.threshold = &threshold
|
||||
t.lock.Unlock()
|
||||
t.Log()
|
||||
}
|
||||
|
||||
// logTopLevelTraces finds all traces in a hierarchy of nested traces that should be logged but do not have any
|
||||
// parents that will be logged, due to threshold limits, and logs them as top level traces.
|
||||
func (t *Trace) logTrace() {
|
||||
t.lock.RLock()
|
||||
defer t.lock.RUnlock()
|
||||
if t.durationIsWithinThreshold() {
|
||||
var buffer bytes.Buffer
|
||||
traceNum := rand.Int31()
|
||||
|
||||
totalTime := t.endTime.Sub(t.startTime)
|
||||
buffer.WriteString(fmt.Sprintf("Trace[%d]: %q ", traceNum, t.name))
|
||||
if len(t.fields) > 0 {
|
||||
writeFields(&buffer, t.fields)
|
||||
buffer.WriteString(" ")
|
||||
}
|
||||
|
||||
// if any step took more than it's share of the total allowed time, it deserves a higher log level
|
||||
buffer.WriteString(fmt.Sprintf("(%v) (total time: %vms):", t.startTime.Format("02-Jan-2006 15:04:05.000"), totalTime.Milliseconds()))
|
||||
stepThreshold := t.calculateStepThreshold()
|
||||
t.writeTraceSteps(&buffer, fmt.Sprintf("\nTrace[%d]: ", traceNum), stepThreshold)
|
||||
buffer.WriteString(fmt.Sprintf("\nTrace[%d]: [%v] [%v] END\n", traceNum, t.endTime.Sub(t.startTime), totalTime))
|
||||
|
||||
klog.Info(buffer.String())
|
||||
return
|
||||
}
|
||||
|
||||
// If the trace should not be logged, still check if nested traces should be logged
|
||||
for _, s := range t.traceItems {
|
||||
if nestedTrace, ok := s.(*Trace); ok {
|
||||
nestedTrace.logTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Trace) writeTraceSteps(b *bytes.Buffer, formatter string, stepThreshold *time.Duration) {
|
||||
lastStepTime := t.startTime
|
||||
for _, stepOrTrace := range t.traceItems {
|
||||
stepOrTrace.rLock()
|
||||
stepOrTrace.writeItem(b, formatter, lastStepTime, stepThreshold)
|
||||
lastStepTime = stepOrTrace.time()
|
||||
stepOrTrace.rUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Trace) durationIsWithinThreshold() bool {
|
||||
if t.endTime == nil { // we don't assume incomplete traces meet the threshold
|
||||
return false
|
||||
}
|
||||
return t.threshold == nil || *t.threshold == 0 || t.endTime.Sub(t.startTime) >= *t.threshold
|
||||
}
|
||||
|
||||
// TotalTime can be used to figure out how long it took since the Trace was created
|
||||
func (t *Trace) TotalTime() time.Duration {
|
||||
return time.Since(t.startTime)
|
||||
}
|
||||
|
||||
// calculateStepThreshold returns a threshold for the individual steps of a trace, or nil if there is no threshold and
|
||||
// all steps should be written.
|
||||
func (t *Trace) calculateStepThreshold() *time.Duration {
|
||||
if t.threshold == nil {
|
||||
return nil
|
||||
}
|
||||
lenTrace := len(t.traceItems) + 1
|
||||
traceThreshold := *t.threshold
|
||||
for _, s := range t.traceItems {
|
||||
nestedTrace, ok := s.(*Trace)
|
||||
if ok {
|
||||
nestedTrace.lock.RLock()
|
||||
if nestedTrace.threshold != nil {
|
||||
traceThreshold = traceThreshold - *nestedTrace.threshold
|
||||
lenTrace--
|
||||
}
|
||||
nestedTrace.lock.RUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
// the limit threshold is used when the threshold(
|
||||
//remaining after subtracting that of the child trace) is getting very close to zero to prevent unnecessary logging
|
||||
limitThreshold := *t.threshold / 4
|
||||
if traceThreshold < limitThreshold {
|
||||
traceThreshold = limitThreshold
|
||||
lenTrace = len(t.traceItems) + 1
|
||||
}
|
||||
|
||||
stepThreshold := traceThreshold / time.Duration(lenTrace)
|
||||
return &stepThreshold
|
||||
}
|
||||
|
||||
// ContextTraceKey provides a common key for traces in context.Context values.
|
||||
type ContextTraceKey struct{}
|
||||
|
||||
// FromContext returns the trace keyed by ContextTraceKey in the context values, if one
|
||||
// is present, or nil If there is no trace in the Context.
|
||||
// It is safe to call Nest() on the returned value even if it is nil because ((*Trace)nil).Nest returns a top level
|
||||
// trace.
|
||||
func FromContext(ctx context.Context) *Trace {
|
||||
if v, ok := ctx.Value(ContextTraceKey{}).(*Trace); ok {
|
||||
return v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ContextWithTrace returns a context with trace included in the context values, keyed by ContextTraceKey.
|
||||
func ContextWithTrace(ctx context.Context, trace *Trace) context.Context {
|
||||
return context.WithValue(ctx, ContextTraceKey{}, trace)
|
||||
}
|
Reference in New Issue
Block a user