network: support network isolate
Add new crd to convert kubesphere network policy to k8s network policy, and then other network plugin will do the rest work. Use cache.go from calico project's kube-controller, it aim to sync nsnp with k8s np, delete unused np, and relieve the pressure on k8s restful client. If you want higher performance, you can implement interface NsNetworkPolicyProvider in pkg/controller/provider/namespace_np.go. Signed-off-by: Duan Jiong <djduanjiong@gmail.com>
This commit is contained in:
9
vendor/github.com/patrickmn/go-cache/CONTRIBUTORS
generated
vendored
Normal file
9
vendor/github.com/patrickmn/go-cache/CONTRIBUTORS
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
This is a list of people who have contributed code to go-cache. They, or their
|
||||
employers, are the copyright holders of the contributed code. Contributed code
|
||||
is subject to the license restrictions listed in LICENSE (as they were when the
|
||||
code was contributed.)
|
||||
|
||||
Dustin Sallings <dustin@spy.net>
|
||||
Jason Mooberry <jasonmoo@me.com>
|
||||
Sergey Shepelev <temotor@gmail.com>
|
||||
Alex Edwards <ajmedwards@gmail.com>
|
||||
19
vendor/github.com/patrickmn/go-cache/LICENSE
generated
vendored
Normal file
19
vendor/github.com/patrickmn/go-cache/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2012-2017 Patrick Mylund Nielsen and the go-cache contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
83
vendor/github.com/patrickmn/go-cache/README.md
generated
vendored
Normal file
83
vendor/github.com/patrickmn/go-cache/README.md
generated
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
# go-cache
|
||||
|
||||
go-cache is an in-memory key:value store/cache similar to memcached that is
|
||||
suitable for applications running on a single machine. Its major advantage is
|
||||
that, being essentially a thread-safe `map[string]interface{}` with expiration
|
||||
times, it doesn't need to serialize or transmit its contents over the network.
|
||||
|
||||
Any object can be stored, for a given duration or forever, and the cache can be
|
||||
safely used by multiple goroutines.
|
||||
|
||||
Although go-cache isn't meant to be used as a persistent datastore, the entire
|
||||
cache can be saved to and loaded from a file (using `c.Items()` to retrieve the
|
||||
items map to serialize, and `NewFrom()` to create a cache from a deserialized
|
||||
one) to recover from downtime quickly. (See the docs for `NewFrom()` for caveats.)
|
||||
|
||||
### Installation
|
||||
|
||||
`go get github.com/patrickmn/go-cache`
|
||||
|
||||
### Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Create a cache with a default expiration time of 5 minutes, and which
|
||||
// purges expired items every 10 minutes
|
||||
c := cache.New(5*time.Minute, 10*time.Minute)
|
||||
|
||||
// Set the value of the key "foo" to "bar", with the default expiration time
|
||||
c.Set("foo", "bar", cache.DefaultExpiration)
|
||||
|
||||
// Set the value of the key "baz" to 42, with no expiration time
|
||||
// (the item won't be removed until it is re-set, or removed using
|
||||
// c.Delete("baz")
|
||||
c.Set("baz", 42, cache.NoExpiration)
|
||||
|
||||
// Get the string associated with the key "foo" from the cache
|
||||
foo, found := c.Get("foo")
|
||||
if found {
|
||||
fmt.Println(foo)
|
||||
}
|
||||
|
||||
// Since Go is statically typed, and cache values can be anything, type
|
||||
// assertion is needed when values are being passed to functions that don't
|
||||
// take arbitrary types, (i.e. interface{}). The simplest way to do this for
|
||||
// values which will only be used once--e.g. for passing to another
|
||||
// function--is:
|
||||
foo, found := c.Get("foo")
|
||||
if found {
|
||||
MyFunction(foo.(string))
|
||||
}
|
||||
|
||||
// This gets tedious if the value is used several times in the same function.
|
||||
// You might do either of the following instead:
|
||||
if x, found := c.Get("foo"); found {
|
||||
foo := x.(string)
|
||||
// ...
|
||||
}
|
||||
// or
|
||||
var foo string
|
||||
if x, found := c.Get("foo"); found {
|
||||
foo = x.(string)
|
||||
}
|
||||
// ...
|
||||
// foo can then be passed around freely as a string
|
||||
|
||||
// Want performance? Store pointers!
|
||||
c.Set("foo", &MyStruct, cache.DefaultExpiration)
|
||||
if x, found := c.Get("foo"); found {
|
||||
foo := x.(*MyStruct)
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Reference
|
||||
|
||||
`godoc` or [http://godoc.org/github.com/patrickmn/go-cache](http://godoc.org/github.com/patrickmn/go-cache)
|
||||
1161
vendor/github.com/patrickmn/go-cache/cache.go
generated
vendored
Normal file
1161
vendor/github.com/patrickmn/go-cache/cache.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
192
vendor/github.com/patrickmn/go-cache/sharded.go
generated
vendored
Normal file
192
vendor/github.com/patrickmn/go-cache/sharded.go
generated
vendored
Normal file
@@ -0,0 +1,192 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"math"
|
||||
"math/big"
|
||||
insecurerand "math/rand"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This is an experimental and unexported (for now) attempt at making a cache
|
||||
// with better algorithmic complexity than the standard one, namely by
|
||||
// preventing write locks of the entire cache when an item is added. As of the
|
||||
// time of writing, the overhead of selecting buckets results in cache
|
||||
// operations being about twice as slow as for the standard cache with small
|
||||
// total cache sizes, and faster for larger ones.
|
||||
//
|
||||
// See cache_test.go for a few benchmarks.
|
||||
|
||||
type unexportedShardedCache struct {
|
||||
*shardedCache
|
||||
}
|
||||
|
||||
type shardedCache struct {
|
||||
seed uint32
|
||||
m uint32
|
||||
cs []*cache
|
||||
janitor *shardedJanitor
|
||||
}
|
||||
|
||||
// djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead.
|
||||
func djb33(seed uint32, k string) uint32 {
|
||||
var (
|
||||
l = uint32(len(k))
|
||||
d = 5381 + seed + l
|
||||
i = uint32(0)
|
||||
)
|
||||
// Why is all this 5x faster than a for loop?
|
||||
if l >= 4 {
|
||||
for i < l-4 {
|
||||
d = (d * 33) ^ uint32(k[i])
|
||||
d = (d * 33) ^ uint32(k[i+1])
|
||||
d = (d * 33) ^ uint32(k[i+2])
|
||||
d = (d * 33) ^ uint32(k[i+3])
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
switch l - i {
|
||||
case 1:
|
||||
case 2:
|
||||
d = (d * 33) ^ uint32(k[i])
|
||||
case 3:
|
||||
d = (d * 33) ^ uint32(k[i])
|
||||
d = (d * 33) ^ uint32(k[i+1])
|
||||
case 4:
|
||||
d = (d * 33) ^ uint32(k[i])
|
||||
d = (d * 33) ^ uint32(k[i+1])
|
||||
d = (d * 33) ^ uint32(k[i+2])
|
||||
}
|
||||
return d ^ (d >> 16)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) bucket(k string) *cache {
|
||||
return sc.cs[djb33(sc.seed, k)%sc.m]
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) {
|
||||
sc.bucket(k).Set(k, x, d)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error {
|
||||
return sc.bucket(k).Add(k, x, d)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error {
|
||||
return sc.bucket(k).Replace(k, x, d)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Get(k string) (interface{}, bool) {
|
||||
return sc.bucket(k).Get(k)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Increment(k string, n int64) error {
|
||||
return sc.bucket(k).Increment(k, n)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) IncrementFloat(k string, n float64) error {
|
||||
return sc.bucket(k).IncrementFloat(k, n)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Decrement(k string, n int64) error {
|
||||
return sc.bucket(k).Decrement(k, n)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Delete(k string) {
|
||||
sc.bucket(k).Delete(k)
|
||||
}
|
||||
|
||||
func (sc *shardedCache) DeleteExpired() {
|
||||
for _, v := range sc.cs {
|
||||
v.DeleteExpired()
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the items in the cache. This may include items that have expired,
|
||||
// but have not yet been cleaned up. If this is significant, the Expiration
|
||||
// fields of the items should be checked. Note that explicit synchronization
|
||||
// is needed to use a cache and its corresponding Items() return values at
|
||||
// the same time, as the maps are shared.
|
||||
func (sc *shardedCache) Items() []map[string]Item {
|
||||
res := make([]map[string]Item, len(sc.cs))
|
||||
for i, v := range sc.cs {
|
||||
res[i] = v.Items()
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func (sc *shardedCache) Flush() {
|
||||
for _, v := range sc.cs {
|
||||
v.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
type shardedJanitor struct {
|
||||
Interval time.Duration
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func (j *shardedJanitor) Run(sc *shardedCache) {
|
||||
j.stop = make(chan bool)
|
||||
tick := time.Tick(j.Interval)
|
||||
for {
|
||||
select {
|
||||
case <-tick:
|
||||
sc.DeleteExpired()
|
||||
case <-j.stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stopShardedJanitor(sc *unexportedShardedCache) {
|
||||
sc.janitor.stop <- true
|
||||
}
|
||||
|
||||
func runShardedJanitor(sc *shardedCache, ci time.Duration) {
|
||||
j := &shardedJanitor{
|
||||
Interval: ci,
|
||||
}
|
||||
sc.janitor = j
|
||||
go j.Run(sc)
|
||||
}
|
||||
|
||||
func newShardedCache(n int, de time.Duration) *shardedCache {
|
||||
max := big.NewInt(0).SetUint64(uint64(math.MaxUint32))
|
||||
rnd, err := rand.Int(rand.Reader, max)
|
||||
var seed uint32
|
||||
if err != nil {
|
||||
os.Stderr.Write([]byte("WARNING: go-cache's newShardedCache failed to read from the system CSPRNG (/dev/urandom or equivalent.) Your system's security may be compromised. Continuing with an insecure seed.\n"))
|
||||
seed = insecurerand.Uint32()
|
||||
} else {
|
||||
seed = uint32(rnd.Uint64())
|
||||
}
|
||||
sc := &shardedCache{
|
||||
seed: seed,
|
||||
m: uint32(n),
|
||||
cs: make([]*cache, n),
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
c := &cache{
|
||||
defaultExpiration: de,
|
||||
items: map[string]Item{},
|
||||
}
|
||||
sc.cs[i] = c
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache {
|
||||
if defaultExpiration == 0 {
|
||||
defaultExpiration = -1
|
||||
}
|
||||
sc := newShardedCache(shards, defaultExpiration)
|
||||
SC := &unexportedShardedCache{sc}
|
||||
if cleanupInterval > 0 {
|
||||
runShardedJanitor(sc, cleanupInterval)
|
||||
runtime.SetFinalizer(SC, stopShardedJanitor)
|
||||
}
|
||||
return SC
|
||||
}
|
||||
201
vendor/github.com/projectcalico/kube-controllers/LICENSE
generated
vendored
Normal file
201
vendor/github.com/projectcalico/kube-controllers/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
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.
|
||||
296
vendor/github.com/projectcalico/kube-controllers/pkg/cache/cache.go
generated
vendored
Normal file
296
vendor/github.com/projectcalico/kube-controllers/pkg/cache/cache.go
generated
vendored
Normal file
@@ -0,0 +1,296 @@
|
||||
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cache
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/patrickmn/go-cache"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"k8s.io/client-go/util/workqueue"
|
||||
)
|
||||
|
||||
// ResourceCache stores resources and queues updates when those resources
|
||||
// are created, modified, or deleted. It de-duplicates updates by ensuring
|
||||
// updates are only queued when an object has changed.
|
||||
type ResourceCache interface {
|
||||
// Set sets the key to the provided value, and generates an update
|
||||
// on the queue the value has changed.
|
||||
Set(key string, value interface{})
|
||||
|
||||
// Get gets the value associated with the given key. Returns nil
|
||||
// if the key is not present.
|
||||
Get(key string) (interface{}, bool)
|
||||
|
||||
// Prime sets the key to the provided value, but does not generate
|
||||
// and update on the queue ever.
|
||||
Prime(key string, value interface{})
|
||||
|
||||
// Delete deletes the value identified by the given key from the cache, and
|
||||
// generates an update on the queue if a value was deleted.
|
||||
Delete(key string)
|
||||
|
||||
// Clean removes the object identified by the given key from the cache.
|
||||
// It does not generate an update on the queue.
|
||||
Clean(key string)
|
||||
|
||||
// ListKeys lists the keys currently in the cache.
|
||||
ListKeys() []string
|
||||
|
||||
// Run enables the generation of events on the output queue starts
|
||||
// cache reconciliation.
|
||||
Run(reconcilerPeriod string)
|
||||
|
||||
// GetQueue returns the cache's output queue, which emits a stream
|
||||
// of any keys which have been created, modified, or deleted.
|
||||
GetQueue() workqueue.RateLimitingInterface
|
||||
}
|
||||
|
||||
// ResourceCacheArgs struct passed to constructor of ResourceCache.
|
||||
// Groups togather all the arguments to pass in single struct.
|
||||
type ResourceCacheArgs struct {
|
||||
// ListFunc returns a mapping of keys to objects from the Calico datastore.
|
||||
ListFunc func() (map[string]interface{}, error)
|
||||
|
||||
// ObjectType is the type of object which is to be stored in this cache.
|
||||
ObjectType reflect.Type
|
||||
|
||||
// LogTypeDesc (optional) to log the type of object stored in the cache.
|
||||
// If not provided it is derived from the ObjectType.
|
||||
LogTypeDesc string
|
||||
|
||||
ReconcilerConfig ReconcilerConfig
|
||||
}
|
||||
|
||||
// ReconcilerConfig contains configuration for the periodic reconciler.
|
||||
type ReconcilerConfig struct {
|
||||
// DisableUpdateOnChange disables the queuing of updates when the reconciler
|
||||
// detects that a value has changed in the datastore.
|
||||
DisableUpdateOnChange bool
|
||||
|
||||
// DisableMissingInDatastore disables queueing of updates when the reconciler
|
||||
// detects that a value is no longer in the datastore but still exists in the cache.
|
||||
DisableMissingInDatastore bool
|
||||
|
||||
// DisableMissingInCache disables queueing of updates when reconciler detects
|
||||
// that a value that is still in the datastore no longer is in the cache.
|
||||
DisableMissingInCache bool
|
||||
}
|
||||
|
||||
// calicoCache implements the ResourceCache interface
|
||||
type calicoCache struct {
|
||||
threadSafeCache *cache.Cache
|
||||
workqueue workqueue.RateLimitingInterface
|
||||
ListFunc func() (map[string]interface{}, error)
|
||||
ObjectType reflect.Type
|
||||
log *log.Entry
|
||||
running bool
|
||||
mut *sync.Mutex
|
||||
reconcilerConfig ReconcilerConfig
|
||||
}
|
||||
|
||||
// NewResourceCache builds and returns a resource cache using the provided arguments.
|
||||
func NewResourceCache(args ResourceCacheArgs) ResourceCache {
|
||||
// Make sure logging is context aware.
|
||||
return &calicoCache{
|
||||
threadSafeCache: cache.New(cache.NoExpiration, cache.DefaultExpiration),
|
||||
workqueue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()),
|
||||
ListFunc: args.ListFunc,
|
||||
ObjectType: args.ObjectType,
|
||||
log: func() *log.Entry {
|
||||
if args.LogTypeDesc == "" {
|
||||
return log.WithFields(log.Fields{"type": args.ObjectType})
|
||||
}
|
||||
return log.WithFields(log.Fields{"type": args.LogTypeDesc})
|
||||
}(),
|
||||
mut: &sync.Mutex{},
|
||||
reconcilerConfig: args.ReconcilerConfig,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *calicoCache) Set(key string, newObj interface{}) {
|
||||
if reflect.TypeOf(newObj) != c.ObjectType {
|
||||
c.log.Fatalf("Wrong object type recieved to store in cache. Expected: %s, Found: %s", c.ObjectType, reflect.TypeOf(newObj))
|
||||
}
|
||||
|
||||
// Check if the object exists in the cache already. If it does and hasn't changed,
|
||||
// then we don't need to send an update on the queue.
|
||||
if existingObj, found := c.threadSafeCache.Get(key); found {
|
||||
c.log.Debugf("%#v already exists in cache - comparing.", existingObj)
|
||||
if !reflect.DeepEqual(existingObj, newObj) {
|
||||
// The objects do not match - send an update over the queue.
|
||||
c.threadSafeCache.Set(key, newObj, cache.NoExpiration)
|
||||
if c.isRunning() {
|
||||
c.log.Debugf("Queueing update - %#v and %#v do not match.", newObj, existingObj)
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
c.threadSafeCache.Set(key, newObj, cache.NoExpiration)
|
||||
if c.isRunning() {
|
||||
c.log.Debugf("%#v not found in cache, adding it + queuing update.", newObj)
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *calicoCache) Delete(key string) {
|
||||
c.log.Debugf("Deleting %s from cache", key)
|
||||
c.threadSafeCache.Delete(key)
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
|
||||
func (c *calicoCache) Clean(key string) {
|
||||
c.log.Debugf("Cleaning %s from cache, no update required", key)
|
||||
c.threadSafeCache.Delete(key)
|
||||
}
|
||||
|
||||
func (c *calicoCache) Get(key string) (interface{}, bool) {
|
||||
obj, found := c.threadSafeCache.Get(key)
|
||||
if found {
|
||||
return obj, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Prime adds the key and value to the cache but will never generate
|
||||
// an update on the queue.
|
||||
func (c *calicoCache) Prime(key string, value interface{}) {
|
||||
c.threadSafeCache.Set(key, value, cache.NoExpiration)
|
||||
}
|
||||
|
||||
// ListKeys returns a list of all the keys in the cache.
|
||||
func (c *calicoCache) ListKeys() []string {
|
||||
cacheItems := c.threadSafeCache.Items()
|
||||
keys := make([]string, 0, len(cacheItems))
|
||||
for k := range cacheItems {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
// GetQueue returns the output queue from the cache. Whenever a key/value pair
|
||||
// is modified, an event will appear on this queue.
|
||||
func (c *calicoCache) GetQueue() workqueue.RateLimitingInterface {
|
||||
return c.workqueue
|
||||
}
|
||||
|
||||
// Run starts the cache. Any Set() calls prior to calling Run() will
|
||||
// prime the cache, but not trigger any updates on the output queue.
|
||||
func (c *calicoCache) Run(reconcilerPeriod string) {
|
||||
go c.reconcile(reconcilerPeriod)
|
||||
|
||||
// Indicate that the cache is running, and so updates
|
||||
// can be queued.
|
||||
c.mut.Lock()
|
||||
c.running = true
|
||||
c.mut.Unlock()
|
||||
}
|
||||
|
||||
func (c *calicoCache) isRunning() bool {
|
||||
c.mut.Lock()
|
||||
defer c.mut.Unlock()
|
||||
return c.running
|
||||
}
|
||||
|
||||
// reconcile ensures a reconciliation is run every `reconcilerPeriod` in order to bring the datastore
|
||||
// in sync with the cache. This is to correct any manual changes made in the datastore
|
||||
// without the cache being aware.
|
||||
func (c *calicoCache) reconcile(reconcilerPeriod string) {
|
||||
duration, err := time.ParseDuration(reconcilerPeriod)
|
||||
if err != nil {
|
||||
c.log.Fatalf("Invalid time duration format for reconciler: %s. Some valid examples: 5m, 30s, 2m30s etc.", reconcilerPeriod)
|
||||
}
|
||||
|
||||
// If user has set duration to 0 then disable the reconciler job.
|
||||
if duration.Nanoseconds() == 0 {
|
||||
c.log.Infof("Reconciler period set to %d. Disabling reconciler.", duration.Nanoseconds())
|
||||
return
|
||||
}
|
||||
|
||||
// Loop forever, performing a datastore reconciliation periodically.
|
||||
for {
|
||||
c.log.Debugf("Performing reconciliation")
|
||||
err := c.performDatastoreSync()
|
||||
if err != nil {
|
||||
c.log.WithError(err).Error("Reconciliation failed")
|
||||
continue
|
||||
}
|
||||
|
||||
// Reconciliation was successful, sleep the configured duration.
|
||||
c.log.Debugf("Reconciliation complete, %+v until next one.", duration)
|
||||
time.Sleep(duration)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *calicoCache) performDatastoreSync() error {
|
||||
// Get all the objects we care about from the datastore using ListFunc.
|
||||
objMap, err := c.ListFunc()
|
||||
if err != nil {
|
||||
c.log.WithError(err).Errorf("unable to list objects from datastore while reconciling.")
|
||||
return err
|
||||
}
|
||||
|
||||
// Build a map of existing keys in the datastore.
|
||||
allKeys := map[string]bool{}
|
||||
for key := range objMap {
|
||||
allKeys[key] = true
|
||||
}
|
||||
|
||||
// Also add all existing keys in the cache.
|
||||
for _, key := range c.ListKeys() {
|
||||
allKeys[key] = true
|
||||
}
|
||||
|
||||
c.log.Debugf("Reconciling %d keys in total", len(allKeys))
|
||||
for key := range allKeys {
|
||||
cachedObj, existsInCache := c.Get(key)
|
||||
if !existsInCache {
|
||||
// Key does not exist in the cache, queue an update to
|
||||
// remove it from the datastore if configured to do so.
|
||||
if !c.reconcilerConfig.DisableMissingInCache {
|
||||
c.log.WithField("key", key).Warn("Value for key should not exist, queueing update to remove")
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
obj, existsInDatastore := objMap[key]
|
||||
if !existsInDatastore {
|
||||
// Key exists in the cache but not in the datastore - queue an update
|
||||
// to re-add it if configured to do so.
|
||||
if !c.reconcilerConfig.DisableMissingInDatastore {
|
||||
c.log.WithField("key", key).Warn("Value for key is missing in datastore, queueing update to reprogram")
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(obj, cachedObj) {
|
||||
// Objects differ - queue an update to re-program if configured to do so.
|
||||
if !c.reconcilerConfig.DisableUpdateOnChange {
|
||||
c.log.WithField("key", key).Warn("Value for key has changed, queueing update to reprogram")
|
||||
c.log.Debugf("Cached: %#v", cachedObj)
|
||||
c.log.Debugf("Updated: %#v", obj)
|
||||
c.workqueue.Add(key)
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
28
vendor/github.com/projectcalico/kube-controllers/pkg/converter/converter.go
generated
vendored
Normal file
28
vendor/github.com/projectcalico/kube-controllers/pkg/converter/converter.go
generated
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package converter
|
||||
|
||||
// Converter Responsible for conversion of given kubernetes object to equivalent calico object
|
||||
type Converter interface {
|
||||
// Converts kubernetes object to calico representation of it.
|
||||
Convert(k8sObj interface{}) (interface{}, error)
|
||||
|
||||
// Returns apporpriate key for the object
|
||||
GetKey(obj interface{}) string
|
||||
|
||||
// DeleteArgsFromKey returns name and namespace of the object to pass to Delete
|
||||
// for the given key as generated by GetKey.
|
||||
DeleteArgsFromKey(key string) (string, string)
|
||||
}
|
||||
72
vendor/github.com/projectcalico/kube-controllers/pkg/converter/namespace_converter.go
generated
vendored
Normal file
72
vendor/github.com/projectcalico/kube-controllers/pkg/converter/namespace_converter.go
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package converter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
|
||||
"github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
type namespaceConverter struct {
|
||||
}
|
||||
|
||||
// NewNamespaceConverter Constructor for namespaceConverter
|
||||
func NewNamespaceConverter() Converter {
|
||||
return &namespaceConverter{}
|
||||
}
|
||||
func (nc *namespaceConverter) Convert(k8sObj interface{}) (interface{}, error) {
|
||||
var c conversion.Converter
|
||||
namespace, ok := k8sObj.(*v1.Namespace)
|
||||
if !ok {
|
||||
tombstone, ok := k8sObj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("couldn't get object from tombstone %+v", k8sObj)
|
||||
}
|
||||
namespace, ok = tombstone.Obj.(*v1.Namespace)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("tombstone contained object that is not a Namespace %+v", k8sObj)
|
||||
}
|
||||
}
|
||||
kvp, err := c.NamespaceToProfile(namespace)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profile := kvp.Value.(*api.Profile)
|
||||
|
||||
// Isolate the metadata fields that we care about. ResourceVersion, CreationTimeStamp, etc are
|
||||
// not relevant so we ignore them. This prevents uncessary updates.
|
||||
profile.ObjectMeta = metav1.ObjectMeta{Name: profile.Name}
|
||||
|
||||
return *profile, nil
|
||||
}
|
||||
|
||||
// GetKey returns name of the Profile as its key. For Profiles
|
||||
// backed by Kubernetes namespaces and managed by this controller, the name
|
||||
// is of format `kns.name`.
|
||||
func (nc *namespaceConverter) GetKey(obj interface{}) string {
|
||||
profile := obj.(api.Profile)
|
||||
return profile.Name
|
||||
}
|
||||
|
||||
func (p *namespaceConverter) DeleteArgsFromKey(key string) (string, string) {
|
||||
// Not namespaced, so just return the key, which is the profile name.
|
||||
return "", key
|
||||
}
|
||||
75
vendor/github.com/projectcalico/kube-controllers/pkg/converter/networkpolicy_converter.go
generated
vendored
Normal file
75
vendor/github.com/projectcalico/kube-controllers/pkg/converter/networkpolicy_converter.go
generated
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package converter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
|
||||
"github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
|
||||
|
||||
networkingv1 "k8s.io/api/networking/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
type policyConverter struct {
|
||||
}
|
||||
|
||||
// NewPolicyConverter Constructor for policyConverter
|
||||
func NewPolicyConverter() Converter {
|
||||
return &policyConverter{}
|
||||
}
|
||||
|
||||
// Convert takes a Kubernetes NetworkPolicy and returns a Calico api.NetworkPolicy representation.
|
||||
func (p *policyConverter) Convert(k8sObj interface{}) (interface{}, error) {
|
||||
np, ok := k8sObj.(*networkingv1.NetworkPolicy)
|
||||
|
||||
if !ok {
|
||||
tombstone, ok := k8sObj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("couldn't get object from tombstone %+v", k8sObj)
|
||||
}
|
||||
np, ok = tombstone.Obj.(*networkingv1.NetworkPolicy)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("tombstone contained object that is not a NetworkPolicy %+v", k8sObj)
|
||||
}
|
||||
}
|
||||
|
||||
var c conversion.Converter
|
||||
kvp, err := c.K8sNetworkPolicyToCalico(np)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cnp := kvp.Value.(*api.NetworkPolicy)
|
||||
|
||||
// Isolate the metadata fields that we care about. ResourceVersion, CreationTimeStamp, etc are
|
||||
// not relevant so we ignore them. This prevents uncessary updates.
|
||||
cnp.ObjectMeta = metav1.ObjectMeta{Name: cnp.Name, Namespace: cnp.Namespace}
|
||||
|
||||
return *cnp, err
|
||||
}
|
||||
|
||||
// GetKey returns the 'namespace/name' for the given Calico NetworkPolicy as its key.
|
||||
func (p *policyConverter) GetKey(obj interface{}) string {
|
||||
policy := obj.(api.NetworkPolicy)
|
||||
return fmt.Sprintf("%s/%s", policy.Namespace, policy.Name)
|
||||
}
|
||||
|
||||
func (p *policyConverter) DeleteArgsFromKey(key string) (string, string) {
|
||||
splits := strings.SplitN(key, "/", 2)
|
||||
return splits[0], splits[1]
|
||||
}
|
||||
109
vendor/github.com/projectcalico/kube-controllers/pkg/converter/pod_converter.go
generated
vendored
Normal file
109
vendor/github.com/projectcalico/kube-controllers/pkg/converter/pod_converter.go
generated
vendored
Normal file
@@ -0,0 +1,109 @@
|
||||
// Copyright (c) 2017 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package converter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
|
||||
"github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
// WorkloadEndpointData is an internal struct used to store the various bits
|
||||
// of information that the policy controller cares about on a workload endpoint.
|
||||
type WorkloadEndpointData struct {
|
||||
PodName string
|
||||
Namespace string
|
||||
Labels map[string]string
|
||||
}
|
||||
|
||||
type podConverter struct {
|
||||
}
|
||||
|
||||
// BuildWorkloadEndpointData generates the correct WorkloadEndpointData for the given
|
||||
// WorkloadEndpoint, extracting fields that the policy controller is responsible for syncing.
|
||||
func BuildWorkloadEndpointData(wep api.WorkloadEndpoint) WorkloadEndpointData {
|
||||
return WorkloadEndpointData{
|
||||
PodName: wep.Spec.Pod,
|
||||
Namespace: wep.Namespace,
|
||||
Labels: wep.Labels,
|
||||
}
|
||||
}
|
||||
|
||||
// MergeWorkloadEndpointData applies the given WorkloadEndpointData to the provided
|
||||
// WorkloadEndpoint, updating relevant fields with new values.
|
||||
func MergeWorkloadEndpointData(wep *api.WorkloadEndpoint, upd WorkloadEndpointData) {
|
||||
if wep.Spec.Pod != upd.PodName || wep.Namespace != upd.Namespace {
|
||||
log.Fatalf("Bad attempt to merge data for %s/%s into wep %s/%s", upd.PodName, upd.Namespace, wep.Name, wep.Namespace)
|
||||
}
|
||||
wep.Labels = upd.Labels
|
||||
}
|
||||
|
||||
// NewPodConverter Constructor for podConverter
|
||||
func NewPodConverter() Converter {
|
||||
return &podConverter{}
|
||||
}
|
||||
|
||||
func (p *podConverter) Convert(k8sObj interface{}) (interface{}, error) {
|
||||
// Convert Pod into a workload endpoint.
|
||||
var c conversion.Converter
|
||||
pod, ok := k8sObj.(*v1.Pod)
|
||||
if !ok {
|
||||
tombstone, ok := k8sObj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
return nil, errors.New("couldn't get object from tombstone")
|
||||
}
|
||||
pod, ok = tombstone.Obj.(*v1.Pod)
|
||||
if !ok {
|
||||
return nil, errors.New("tombstone contained object that is not a Pod")
|
||||
}
|
||||
}
|
||||
|
||||
// The conversion logic always requires a node, but we don't always have one. We don't actually
|
||||
// care about the value used for the node in this controller, so just dummy it out if it doesn't exist.
|
||||
if pod.Spec.NodeName == "" {
|
||||
pod.Spec.NodeName = "unknown.node"
|
||||
}
|
||||
|
||||
kvp, err := c.PodToWorkloadEndpoint(pod)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
wep := kvp.Value.(*api.WorkloadEndpoint)
|
||||
|
||||
// Build and return a WorkloadEndpointData struct using the data.
|
||||
return BuildWorkloadEndpointData(*wep), nil
|
||||
}
|
||||
|
||||
// GetKey takes a WorkloadEndpointData and returns the key which
|
||||
// identifies it - namespace/name
|
||||
func (p *podConverter) GetKey(obj interface{}) string {
|
||||
e := obj.(WorkloadEndpointData)
|
||||
return fmt.Sprintf("%s/%s", e.Namespace, e.PodName)
|
||||
}
|
||||
|
||||
func (p *podConverter) DeleteArgsFromKey(key string) (string, string) {
|
||||
// We don't have enough information to generate the delete args from the key that's used
|
||||
// for Pods / WorkloadEndpoints, so just panic. This should never be called but is necessary
|
||||
// to satisfy the interface.
|
||||
log.Panicf("DeleteArgsFromKey call for WorkloadEndpoints is not allowed")
|
||||
return "", ""
|
||||
}
|
||||
73
vendor/github.com/projectcalico/kube-controllers/pkg/converter/serviceaccount_converter.go
generated
vendored
Normal file
73
vendor/github.com/projectcalico/kube-controllers/pkg/converter/serviceaccount_converter.go
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) 2018 Tigera, Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package converter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
api "github.com/projectcalico/libcalico-go/lib/apis/v3"
|
||||
"github.com/projectcalico/libcalico-go/lib/backend/k8s/conversion"
|
||||
|
||||
"k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/client-go/tools/cache"
|
||||
)
|
||||
|
||||
type serviceAccountConverter struct {
|
||||
}
|
||||
|
||||
// NewServiceaccountConverter Constructor to convert ServiceAccount to Profile
|
||||
func NewServiceAccountConverter() Converter {
|
||||
return &serviceAccountConverter{}
|
||||
}
|
||||
|
||||
func (nc *serviceAccountConverter) Convert(k8sObj interface{}) (interface{}, error) {
|
||||
var c conversion.Converter
|
||||
serviceAccount, ok := k8sObj.(*v1.ServiceAccount)
|
||||
if !ok {
|
||||
tombstone, ok := k8sObj.(cache.DeletedFinalStateUnknown)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("couldn't get object from tombstone %+v", k8sObj)
|
||||
}
|
||||
serviceAccount, ok = tombstone.Obj.(*v1.ServiceAccount)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("tombstone contained object that is not a Serviceaccount %+v", k8sObj)
|
||||
}
|
||||
}
|
||||
kvp, err := c.ServiceAccountToProfile(serviceAccount)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profile := kvp.Value.(*api.Profile)
|
||||
|
||||
// Isolate the metadata fields that we care about. ResourceVersion, CreationTimeStamp, etc are
|
||||
// not relevant so we ignore them. This prevents uncessary updates.
|
||||
profile.ObjectMeta = metav1.ObjectMeta{Name: profile.Name}
|
||||
|
||||
return *profile, nil
|
||||
}
|
||||
|
||||
// GetKey returns name of the Profile as its key. For Profiles
|
||||
// backed by Kubernetes serviceaccounts and managed by this controller, the name
|
||||
// is of format `ksa.namespace.name`.
|
||||
func (nc *serviceAccountConverter) GetKey(obj interface{}) string {
|
||||
profile := obj.(api.Profile)
|
||||
return profile.Name
|
||||
}
|
||||
|
||||
func (nc *serviceAccountConverter) DeleteArgsFromKey(key string) (string, string) {
|
||||
// Not serviceaccount, so just return the key, which is the profile name.
|
||||
return "", key
|
||||
}
|
||||
Reference in New Issue
Block a user