code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
item, exists = f.items[key]
return item, exists, nil
} | GetByKey returns the requested item, or sets exists=false. | GetByKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) IsClosed() bool {
f.lock.Lock()
defer f.lock.Unlock()
return f.closed
} | IsClosed checks if the queue is closed | IsClosed | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) {
f.lock.Lock()
defer f.lock.Unlock()
for {
for len(f.queue) == 0 {
// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.
// When Close() is called, the f.closed is set and the condition is broadcasted.
// Which causes this loop to continue and return from the Pop().
if f.closed {
return nil, ErrFIFOClosed
}
f.cond.Wait()
}
isInInitialList := !f.hasSynced_locked()
id := f.queue[0]
f.queue = f.queue[1:]
if f.initialPopulationCount > 0 {
f.initialPopulationCount--
}
item, ok := f.items[id]
if !ok {
// Item may have been deleted subsequently.
continue
}
delete(f.items, id)
err := process(item, isInInitialList)
if e, ok := err.(ErrRequeue); ok {
f.addIfNotPresent(id, item)
err = e.Err
}
return item, err
}
} | Pop waits until an item is ready and processes it. If multiple items are
ready, they are returned in the order in which they were added/updated.
The item is removed from the queue (and the store) before it is processed,
so if you don't successfully process it, it should be added back with
AddIfNotPresent(). process function is called under lock, so it is safe
update data structures in it that need to be in sync with the queue. | Pop | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Replace(list []interface{}, resourceVersion string) error {
items := make(map[string]interface{}, len(list))
for _, item := range list {
key, err := f.keyFunc(item)
if err != nil {
return KeyError{item, err}
}
items[key] = item
}
f.lock.Lock()
defer f.lock.Unlock()
if !f.populated {
f.populated = true
f.initialPopulationCount = len(items)
}
f.items = items
f.queue = f.queue[:0]
for id := range items {
f.queue = append(f.queue, id)
}
if len(f.queue) > 0 {
f.cond.Broadcast()
}
return nil
} | Replace will delete the contents of 'f', using instead the given map.
'f' takes ownership of the map, you should not reference the map again
after calling this function. f's queue is reset, too; upon return, it
will contain the items in the map, in no particular order. | Replace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Resync() error {
f.lock.Lock()
defer f.lock.Unlock()
inQueue := sets.NewString()
for _, id := range f.queue {
inQueue.Insert(id)
}
for id := range f.items {
if !inQueue.Has(id) {
f.queue = append(f.queue, id)
}
}
if len(f.queue) > 0 {
f.cond.Broadcast()
}
return nil
} | Resync will ensure that every object in the Store has its key in the queue.
This should be a no-op, because that property is maintained by all operations. | Resync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func NewFIFO(keyFunc KeyFunc) *FIFO {
f := &FIFO{
items: map[string]interface{}{},
queue: []string{},
keyFunc: keyFunc,
}
f.cond.L = &f.lock
return f
} | NewFIFO returns a Store which can be used to queue up items to
process. | NewFIFO | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FakeCustomStore) Add(obj interface{}) error {
if f.AddFunc != nil {
return f.AddFunc(obj)
}
return nil
} | Add calls the custom Add function if defined | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) Update(obj interface{}) error {
if f.UpdateFunc != nil {
return f.UpdateFunc(obj)
}
return nil
} | Update calls the custom Update function if defined | Update | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) Delete(obj interface{}) error {
if f.DeleteFunc != nil {
return f.DeleteFunc(obj)
}
return nil
} | Delete calls the custom Delete function if defined | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) List() []interface{} {
if f.ListFunc != nil {
return f.ListFunc()
}
return nil
} | List calls the custom List function if defined | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) ListKeys() []string {
if f.ListKeysFunc != nil {
return f.ListKeysFunc()
}
return nil
} | ListKeys calls the custom ListKeys function if defined | ListKeys | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) Get(obj interface{}) (item interface{}, exists bool, err error) {
if f.GetFunc != nil {
return f.GetFunc(obj)
}
return nil, false, nil
} | Get calls the custom Get function if defined | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) GetByKey(key string) (item interface{}, exists bool, err error) {
if f.GetByKeyFunc != nil {
return f.GetByKeyFunc(key)
}
return nil, false, nil
} | GetByKey calls the custom GetByKey function if defined | GetByKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) Replace(list []interface{}, resourceVersion string) error {
if f.ReplaceFunc != nil {
return f.ReplaceFunc(list, resourceVersion)
}
return nil
} | Replace calls the custom Replace function if defined | Replace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func (f *FakeCustomStore) Resync() error {
if f.ResyncFunc != nil {
return f.ResyncFunc()
}
return nil
} | Resync calls the custom Resync function if defined | Resync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fake_custom_store.go | Apache-2.0 |
func NewObjectName(namespace, name string) ObjectName {
return ObjectName{Namespace: namespace, Name: name}
} | NewObjectName constructs a new one | NewObjectName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func (objName ObjectName) Parts() (namespace, name string) {
return objName.Namespace, objName.Name
} | Parts is the inverse of the constructor | Parts | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func (objName ObjectName) String() string {
if len(objName.Namespace) > 0 {
return objName.Namespace + "/" + objName.Name
}
return objName.Name
} | String returns the standard string encoding,
which is designed to match the historical behavior of MetaNamespaceKeyFunc.
Note this behavior is different from the String method of types.NamespacedName. | String | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func ParseObjectName(str string) (ObjectName, error) {
var objName ObjectName
var err error
objName.Namespace, objName.Name, err = SplitMetaNamespaceKey(str)
return objName, err
} | ParseObjectName tries to parse the standard encoding | ParseObjectName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func NamespacedNameAsObjectName(nn types.NamespacedName) ObjectName {
return NewObjectName(nn.Namespace, nn.Name)
} | NamespacedNameAsObjectName rebrands the given NamespacedName as an ObjectName | NamespacedNameAsObjectName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func (objName ObjectName) AsNamespacedName() types.NamespacedName {
return types.NamespacedName{Namespace: objName.Namespace, Name: objName.Name}
} | AsNamespacedName rebrands as a NamespacedName | AsNamespacedName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/object-names.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/object-names.go | Apache-2.0 |
func checkWatchListConsistencyIfRequested(stopCh <-chan struct{}, identity string, lastSyncedResourceVersion string, listerWatcher Lister, store Store) {
if !dataConsistencyDetectionEnabled {
return
}
checkWatchListConsistency(stopCh, identity, lastSyncedResourceVersion, listerWatcher, store)
} | checkWatchListConsistencyIfRequested performs a data consistency check only when
the KUBE_WATCHLIST_INCONSISTENCY_DETECTOR environment variable was set during a binary startup.
The consistency check is meant to be enforced only in the CI, not in production.
The check ensures that data retrieved by the watch-list api call
is exactly the same as data received by the standard list api call.
Note that this function will panic when data inconsistency is detected.
This is intentional because we want to catch it in the CI. | checkWatchListConsistencyIfRequested | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go | Apache-2.0 |
func checkWatchListConsistency(stopCh <-chan struct{}, identity string, lastSyncedResourceVersion string, listerWatcher Lister, store Store) {
klog.Warningf("%s: data consistency check for the watch-list feature is enabled, this will result in an additional call to the API server.", identity)
opts := metav1.ListOptions{
ResourceVersion: lastSyncedResourceVersion,
ResourceVersionMatch: metav1.ResourceVersionMatchExact,
}
var list runtime.Object
err := wait.PollUntilContextCancel(wait.ContextForChannel(stopCh), time.Second, true, func(_ context.Context) (done bool, err error) {
list, err = listerWatcher.List(opts)
if err != nil {
// the consistency check will only be enabled in the CI
// and LIST calls in general will be retired by the client-go library
// if we fail simply log and retry
klog.Errorf("failed to list data from the server, retrying until stopCh is closed, err: %v", err)
return false, nil
}
return true, nil
})
if err != nil {
klog.Errorf("failed to list data from the server, the watch-list consistency check won't be performed, stopCh was closed, err: %v", err)
return
}
rawListItems, err := meta.ExtractListWithAlloc(list)
if err != nil {
panic(err) // this should never happen
}
listItems := toMetaObjectSliceOrDie(rawListItems)
storeItems := toMetaObjectSliceOrDie(store.List())
sort.Sort(byUID(listItems))
sort.Sort(byUID(storeItems))
if !cmp.Equal(listItems, storeItems) {
klog.Infof("%s: data received by the new watch-list api call is different than received by the standard list api call, diff: %v", identity, cmp.Diff(listItems, storeItems))
msg := "data inconsistency detected for the watch-list feature, panicking!"
panic(msg)
}
} | checkWatchListConsistency exists solely for testing purposes.
we cannot use checkWatchListConsistencyIfRequested because
it is guarded by an environmental variable.
we cannot manipulate the environmental variable because
it will affect other tests in this package. | checkWatchListConsistency | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector_data_consistency_detector.go | Apache-2.0 |
func (u *UndeltaStore) Add(obj interface{}) error {
if err := u.Store.Add(obj); err != nil {
return err
}
u.PushFunc(u.Store.List())
return nil
} | Add inserts an object into the store and sends complete state by calling PushFunc.
Note about thread safety. The Store implementation (cache.cache) uses a lock for all methods.
In the functions below, the lock gets released and reacquired betweend the {Add,Delete,etc}
and the List. So, the following can happen, resulting in two identical calls to PushFunc.
time thread 1 thread 2
0 UndeltaStore.Add(a)
1 UndeltaStore.Add(b)
2 Store.Add(a)
3 Store.Add(b)
4 Store.List() -> [a,b]
5 Store.List() -> [a,b] | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/undelta_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/undelta_store.go | Apache-2.0 |
func (u *UndeltaStore) Update(obj interface{}) error {
if err := u.Store.Update(obj); err != nil {
return err
}
u.PushFunc(u.Store.List())
return nil
} | Update sets an item in the cache to its updated state and sends complete state by calling PushFunc. | Update | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/undelta_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/undelta_store.go | Apache-2.0 |
func (u *UndeltaStore) Delete(obj interface{}) error {
if err := u.Store.Delete(obj); err != nil {
return err
}
u.PushFunc(u.Store.List())
return nil
} | Delete removes an item from the cache and sends complete state by calling PushFunc. | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/undelta_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/undelta_store.go | Apache-2.0 |
func (u *UndeltaStore) Replace(list []interface{}, resourceVersion string) error {
if err := u.Store.Replace(list, resourceVersion); err != nil {
return err
}
u.PushFunc(u.Store.List())
return nil
} | Replace will delete the contents of current store, using instead the given list.
'u' takes ownership of the list, you should not reference the list again
after calling this function.
The new contents complete state will be sent by calling PushFunc after replacement. | Replace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/undelta_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/undelta_store.go | Apache-2.0 |
func NewUndeltaStore(pushFunc func([]interface{}), keyFunc KeyFunc) *UndeltaStore {
return &UndeltaStore{
Store: NewStore(keyFunc),
PushFunc: pushFunc,
}
} | NewUndeltaStore returns an UndeltaStore implemented with a Store. | NewUndeltaStore | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/undelta_store.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/undelta_store.go | Apache-2.0 |
func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error {
selectAll := selector.Empty()
for _, m := range store.List() {
if selectAll {
// Avoid computing labels of the objects to speed up common flows
// of listing all objects.
appendFn(m)
continue
}
metadata, err := meta.Accessor(m)
if err != nil {
return err
}
if selector.Matches(labels.Set(metadata.GetLabels())) {
appendFn(m)
}
}
return nil
} | ListAll calls appendFn with each value retrieved from store which matches the selector. | ListAll | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listers.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listers.go | Apache-2.0 |
func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error {
if namespace == metav1.NamespaceAll {
return ListAll(indexer, selector, appendFn)
}
items, err := indexer.Index(NamespaceIndex, &metav1.ObjectMeta{Namespace: namespace})
if err != nil {
// Ignore error; do slow search without index.
klog.Warningf("can not retrieve list of objects using index : %v", err)
for _, m := range indexer.List() {
metadata, err := meta.Accessor(m)
if err != nil {
return err
}
if metadata.GetNamespace() == namespace && selector.Matches(labels.Set(metadata.GetLabels())) {
appendFn(m)
}
}
return nil
}
selectAll := selector.Empty()
for _, m := range items {
if selectAll {
// Avoid computing labels of the objects to speed up common flows
// of listing all objects.
appendFn(m)
continue
}
metadata, err := meta.Accessor(m)
if err != nil {
return err
}
if selector.Matches(labels.Set(metadata.GetLabels())) {
appendFn(m)
}
}
return nil
} | ListAllByNamespace used to list items belongs to namespace from Indexer. | ListAllByNamespace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listers.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listers.go | Apache-2.0 |
func NewGenericLister(indexer Indexer, resource schema.GroupResource) GenericLister {
return &genericLister{indexer: indexer, resource: resource}
} | NewGenericLister creates a new instance for the genericLister. | NewGenericLister | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listers.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listers.go | Apache-2.0 |
func SimplePageFunc(fn func(opts metav1.ListOptions) (runtime.Object, error)) ListPageFunc {
return func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) {
return fn(opts)
}
} | SimplePageFunc adapts a context-less list function into one that accepts a context. | SimplePageFunc | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func New(fn ListPageFunc) *ListPager {
return &ListPager{
PageSize: defaultPageSize,
PageFn: fn,
FullListIfExpired: true,
PageBufferSize: defaultPageBufferSize,
}
} | New creates a new pager from the provided pager function using the default
options. It will fall back to a full list if an expiration error is encountered
as a last resort. | New | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) List(ctx context.Context, options metav1.ListOptions) (runtime.Object, bool, error) {
return p.list(ctx, options, false)
} | List returns a single list object, but attempts to retrieve smaller chunks from the
server to reduce the impact on the server. If the chunk attempt fails, it will load
the full list instead. The Limit field on options, if unset, will default to the page size.
If items in the returned list are retained for different durations, and you want to avoid
retaining the whole slice returned by p.PageFn as long as any item is referenced,
use ListWithAlloc instead. | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) ListWithAlloc(ctx context.Context, options metav1.ListOptions) (runtime.Object, bool, error) {
return p.list(ctx, options, true)
} | ListWithAlloc works like List, but avoids retaining references to the items slice returned by p.PageFn.
It does this by making a shallow copy of non-pointer items in the slice returned by p.PageFn.
If the items in the returned list are not retained, or are retained for the same duration, use List instead for memory efficiency. | ListWithAlloc | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) EachListItem(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {
return p.eachListChunkBuffered(ctx, options, func(obj runtime.Object) error {
return meta.EachListItem(obj, fn)
})
} | EachListItem fetches runtime.Object items using this ListPager and invokes fn on each item. If
fn returns an error, processing stops and that error is returned. If fn does not return an error,
any error encountered while retrieving the list from the server is returned. If the context
cancels or times out, the context error is returned. Since the list is retrieved in paginated
chunks, an "Expired" error (metav1.StatusReasonExpired) may be returned if the pagination list
requests exceed the expiration limit of the apiserver being called.
Items are retrieved in chunks from the server to reduce the impact on the server with up to
ListPager.PageBufferSize chunks buffered concurrently in the background.
If items passed to fn are retained for different durations, and you want to avoid
retaining the whole slice returned by p.PageFn as long as any item is referenced,
use EachListItemWithAlloc instead. | EachListItem | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) EachListItemWithAlloc(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {
return p.eachListChunkBuffered(ctx, options, func(obj runtime.Object) error {
return meta.EachListItemWithAlloc(obj, fn)
})
} | EachListItemWithAlloc works like EachListItem, but avoids retaining references to the items slice returned by p.PageFn.
It does this by making a shallow copy of non-pointer items in the slice returned by p.PageFn.
If the items passed to fn are not retained, or are retained for the same duration, use EachListItem instead for memory efficiency. | EachListItemWithAlloc | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) eachListChunkBuffered(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {
if p.PageBufferSize < 0 {
return fmt.Errorf("ListPager.PageBufferSize must be >= 0, got %d", p.PageBufferSize)
}
// Ensure background goroutine is stopped if this call exits before all list items are
// processed. Cancelation error from this deferred cancel call is never returned to caller;
// either the list result has already been sent to bgResultC or the fn error is returned and
// the cancelation error is discarded.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
chunkC := make(chan runtime.Object, p.PageBufferSize)
bgResultC := make(chan error, 1)
go func() {
defer utilruntime.HandleCrash()
var err error
defer func() {
close(chunkC)
bgResultC <- err
}()
err = p.eachListChunk(ctx, options, func(chunk runtime.Object) error {
select {
case chunkC <- chunk: // buffer the chunk, this can block
case <-ctx.Done():
return ctx.Err()
}
return nil
})
}()
for o := range chunkC {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err := fn(o)
if err != nil {
return err // any fn error should be returned immediately
}
}
// promote the results of our background goroutine to the foreground
return <-bgResultC
} | eachListChunkBuffered fetches runtimeObject list chunks using this ListPager and invokes fn on
each list chunk. If fn returns an error, processing stops and that error is returned. If fn does
not return an error, any error encountered while retrieving the list from the server is
returned. If the context cancels or times out, the context error is returned. Since the list is
retrieved in paginated chunks, an "Expired" error (metav1.StatusReasonExpired) may be returned if
the pagination list requests exceed the expiration limit of the apiserver being called.
Up to ListPager.PageBufferSize chunks are buffered concurrently in the background. | eachListChunkBuffered | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func (p *ListPager) eachListChunk(ctx context.Context, options metav1.ListOptions, fn func(obj runtime.Object) error) error {
if options.Limit == 0 {
options.Limit = p.PageSize
}
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
obj, err := p.PageFn(ctx, options)
if err != nil {
return err
}
m, err := meta.ListAccessor(obj)
if err != nil {
return fmt.Errorf("returned object must be a list: %v", err)
}
if err := fn(obj); err != nil {
return err
}
// if we have no more items, return.
if len(m.GetContinue()) == 0 {
return nil
}
// set the next loop up
options.Continue = m.GetContinue()
}
} | eachListChunk fetches runtimeObject list chunks using this ListPager and invokes fn on each list
chunk. If fn returns an error, processing stops and that error is returned. If fn does not return
an error, any error encountered while retrieving the list from the server is returned. If the
context cancels or times out, the context error is returned. Since the list is retrieved in
paginated chunks, an "Expired" error (metav1.StatusReasonExpired) may be returned if the
pagination list requests exceed the expiration limit of the apiserver being called. | eachListChunk | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/pager/pager.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/pager/pager.go | Apache-2.0 |
func getDefaultServer() string {
if server := os.Getenv("KUBERNETES_MASTER"); len(server) > 0 {
return server
}
return "http://localhost:8080"
} | getDefaultServer returns a default setting for DefaultClientConfig
DEPRECATED | getDefaultServer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func NewDefaultClientConfig(config clientcmdapi.Config, overrides *ConfigOverrides) ClientConfig {
return &DirectClientConfig{config, config.CurrentContext, overrides, nil, NewDefaultClientConfigLoadingRules(), promptedCredentials{}}
} | NewDefaultClientConfig creates a DirectClientConfig using the config.CurrentContext as the context name | NewDefaultClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func NewNonInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, configAccess ConfigAccess) ClientConfig {
return &DirectClientConfig{config, contextName, overrides, nil, configAccess, promptedCredentials{}}
} | NewNonInteractiveClientConfig creates a DirectClientConfig using the passed context name and does not have a fallback reader for auth information | NewNonInteractiveClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func NewInteractiveClientConfig(config clientcmdapi.Config, contextName string, overrides *ConfigOverrides, fallbackReader io.Reader, configAccess ConfigAccess) ClientConfig {
return &DirectClientConfig{config, contextName, overrides, fallbackReader, configAccess, promptedCredentials{}}
} | NewInteractiveClientConfig creates a DirectClientConfig using the passed context name and a reader in case auth information is not provided via files or flags | NewInteractiveClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func NewClientConfigFromBytes(configBytes []byte) (ClientConfig, error) {
config, err := Load(configBytes)
if err != nil {
return nil, err
}
return &DirectClientConfig{*config, "", &ConfigOverrides{}, nil, nil, promptedCredentials{}}, nil
} | NewClientConfigFromBytes takes your kubeconfig and gives you back a ClientConfig | NewClientConfigFromBytes | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func RESTConfigFromKubeConfig(configBytes []byte) (*restclient.Config, error) {
clientConfig, err := NewClientConfigFromBytes(configBytes)
if err != nil {
return nil, err
}
return clientConfig.ClientConfig()
} | RESTConfigFromKubeConfig is a convenience method to give back a restconfig from your kubeconfig bytes.
For programmatic access, this is what you want 80% of the time | RESTConfigFromKubeConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) ClientConfig() (*restclient.Config, error) {
// check that getAuthInfo, getContext, and getCluster do not return an error.
// Do this before checking if the current config is usable in the event that an
// AuthInfo, Context, or Cluster config with user-defined names are not found.
// This provides a user with the immediate cause for error if one is found
configAuthInfo, err := config.getAuthInfo()
if err != nil {
return nil, err
}
_, err = config.getContext()
if err != nil {
return nil, err
}
configClusterInfo, err := config.getCluster()
if err != nil {
return nil, err
}
if err := config.ConfirmUsable(); err != nil {
return nil, err
}
clientConfig := &restclient.Config{}
clientConfig.Host = configClusterInfo.Server
if configClusterInfo.ProxyURL != "" {
u, err := parseProxyURL(configClusterInfo.ProxyURL)
if err != nil {
return nil, err
}
clientConfig.Proxy = http.ProxyURL(u)
}
clientConfig.DisableCompression = configClusterInfo.DisableCompression
if config.overrides != nil && len(config.overrides.Timeout) > 0 {
timeout, err := ParseTimeout(config.overrides.Timeout)
if err != nil {
return nil, err
}
clientConfig.Timeout = timeout
}
if u, err := url.ParseRequestURI(clientConfig.Host); err == nil && u.Opaque == "" && len(u.Path) > 1 {
u.RawQuery = ""
u.Fragment = ""
clientConfig.Host = u.String()
}
if len(configAuthInfo.Impersonate) > 0 {
clientConfig.Impersonate = restclient.ImpersonationConfig{
UserName: configAuthInfo.Impersonate,
UID: configAuthInfo.ImpersonateUID,
Groups: configAuthInfo.ImpersonateGroups,
Extra: configAuthInfo.ImpersonateUserExtra,
}
}
// only try to read the auth information if we are secure
if restclient.IsConfigTransportTLS(*clientConfig) {
var err error
var persister restclient.AuthProviderConfigPersister
if config.configAccess != nil {
authInfoName, _ := config.getAuthInfoName()
persister = PersisterForUser(config.configAccess, authInfoName)
}
userAuthPartialConfig, err := config.getUserIdentificationPartialConfig(configAuthInfo, config.fallbackReader, persister, configClusterInfo)
if err != nil {
return nil, err
}
mergo.Merge(clientConfig, userAuthPartialConfig, mergo.WithOverride)
serverAuthPartialConfig, err := getServerIdentificationPartialConfig(configAuthInfo, configClusterInfo)
if err != nil {
return nil, err
}
mergo.Merge(clientConfig, serverAuthPartialConfig, mergo.WithOverride)
}
return clientConfig, nil
} | ClientConfig implements ClientConfig | ClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func getServerIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {
mergedConfig := &restclient.Config{}
// configClusterInfo holds the information identify the server provided by .kubeconfig
configClientConfig := &restclient.Config{}
configClientConfig.CAFile = configClusterInfo.CertificateAuthority
configClientConfig.CAData = configClusterInfo.CertificateAuthorityData
configClientConfig.Insecure = configClusterInfo.InsecureSkipTLSVerify
configClientConfig.ServerName = configClusterInfo.TLSServerName
mergo.Merge(mergedConfig, configClientConfig, mergo.WithOverride)
return mergedConfig, nil
} | clientauth.Info object contain both user identification and server identification. We want different precedence orders for
both, so we have to split the objects and merge them separately
we want this order of precedence for the server identification
1. configClusterInfo (the final result of command line flags and merged .kubeconfig files)
2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority)
3. load the ~/.kubernetes_auth file as a default | getServerIdentificationPartialConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getUserIdentificationPartialConfig(configAuthInfo clientcmdapi.AuthInfo, fallbackReader io.Reader, persistAuthConfig restclient.AuthProviderConfigPersister, configClusterInfo clientcmdapi.Cluster) (*restclient.Config, error) {
mergedConfig := &restclient.Config{}
// blindly overwrite existing values based on precedence
if len(configAuthInfo.Token) > 0 {
mergedConfig.BearerToken = configAuthInfo.Token
mergedConfig.BearerTokenFile = configAuthInfo.TokenFile
} else if len(configAuthInfo.TokenFile) > 0 {
tokenBytes, err := os.ReadFile(configAuthInfo.TokenFile)
if err != nil {
return nil, err
}
mergedConfig.BearerToken = string(tokenBytes)
mergedConfig.BearerTokenFile = configAuthInfo.TokenFile
}
if len(configAuthInfo.Impersonate) > 0 {
mergedConfig.Impersonate = restclient.ImpersonationConfig{
UserName: configAuthInfo.Impersonate,
UID: configAuthInfo.ImpersonateUID,
Groups: configAuthInfo.ImpersonateGroups,
Extra: configAuthInfo.ImpersonateUserExtra,
}
}
if len(configAuthInfo.ClientCertificate) > 0 || len(configAuthInfo.ClientCertificateData) > 0 {
mergedConfig.CertFile = configAuthInfo.ClientCertificate
mergedConfig.CertData = configAuthInfo.ClientCertificateData
mergedConfig.KeyFile = configAuthInfo.ClientKey
mergedConfig.KeyData = configAuthInfo.ClientKeyData
}
if len(configAuthInfo.Username) > 0 || len(configAuthInfo.Password) > 0 {
mergedConfig.Username = configAuthInfo.Username
mergedConfig.Password = configAuthInfo.Password
}
if configAuthInfo.AuthProvider != nil {
mergedConfig.AuthProvider = configAuthInfo.AuthProvider
mergedConfig.AuthConfigPersister = persistAuthConfig
}
if configAuthInfo.Exec != nil {
mergedConfig.ExecProvider = configAuthInfo.Exec
mergedConfig.ExecProvider.InstallHint = cleanANSIEscapeCodes(mergedConfig.ExecProvider.InstallHint)
mergedConfig.ExecProvider.Config = configClusterInfo.Extensions[clusterExtensionKey]
}
// if there still isn't enough information to authenticate the user, try prompting
if !canIdentifyUser(*mergedConfig) && (fallbackReader != nil) {
if len(config.promptedCredentials.username) > 0 && len(config.promptedCredentials.password) > 0 {
mergedConfig.Username = config.promptedCredentials.username
mergedConfig.Password = config.promptedCredentials.password
return mergedConfig, nil
}
prompter := NewPromptingAuthLoader(fallbackReader)
promptedAuthInfo, err := prompter.Prompt()
if err != nil {
return nil, err
}
promptedConfig := makeUserIdentificationConfig(*promptedAuthInfo)
previouslyMergedConfig := mergedConfig
mergedConfig = &restclient.Config{}
mergo.Merge(mergedConfig, promptedConfig, mergo.WithOverride)
mergo.Merge(mergedConfig, previouslyMergedConfig, mergo.WithOverride)
config.promptedCredentials.username = mergedConfig.Username
config.promptedCredentials.password = mergedConfig.Password
}
return mergedConfig, nil
} | clientauth.Info object contain both user identification and server identification. We want different precedence orders for
both, so we have to split the objects and merge them separately
we want this order of precedence for user identification
1. configAuthInfo minus auth-path (the final result of command line flags and merged .kubeconfig files)
2. configAuthInfo.auth-path (this file can contain information that conflicts with #1, and we want #1 to win the priority)
3. if there is not enough information to identify the user, load try the ~/.kubernetes_auth file
4. if there is not enough information to identify the user, prompt if possible | getUserIdentificationPartialConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func makeUserIdentificationConfig(info clientauth.Info) *restclient.Config {
config := &restclient.Config{}
config.Username = info.User
config.Password = info.Password
config.CertFile = info.CertFile
config.KeyFile = info.KeyFile
config.BearerToken = info.BearerToken
return config
} | makeUserIdentificationFieldsConfig returns a client.Config capable of being merged using mergo for only user identification information | makeUserIdentificationConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func cleanANSIEscapeCodes(s string) string {
// spaceControlCharacters includes tab, new line, vertical tab, new page, and
// carriage return. These are in the unicode.Cc category, but that category also
// contains ESC (U+001B) which we don't want.
spaceControlCharacters := unicode.RangeTable{
R16: []unicode.Range16{
{Lo: 0x0009, Hi: 0x000D, Stride: 1},
},
}
// Why not make this deny-only (instead of allow-only)? Because unicode.C
// contains newline and tab characters that we want.
allowedRanges := []*unicode.RangeTable{
unicode.L,
unicode.M,
unicode.N,
unicode.P,
unicode.S,
unicode.Z,
&spaceControlCharacters,
}
builder := strings.Builder{}
for _, roon := range s {
if unicode.IsOneOf(allowedRanges, roon) {
builder.WriteRune(roon) // returns nil error, per go doc
} else {
fmt.Fprintf(&builder, "%U", roon)
}
}
return builder.String()
} | cleanANSIEscapeCodes takes an arbitrary string and ensures that there are no
ANSI escape sequences that could put the terminal in a weird state (e.g.,
"\e[1m" bolds text) | cleanANSIEscapeCodes | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) Namespace() (string, bool, error) {
if config.overrides != nil && config.overrides.Context.Namespace != "" {
// In the event we have an empty config but we do have a namespace override, we should return
// the namespace override instead of having config.ConfirmUsable() return an error. This allows
// things like in-cluster clients to execute `kubectl get pods --namespace=foo` and have the
// --namespace flag honored instead of being ignored.
return config.overrides.Context.Namespace, true, nil
}
if err := config.ConfirmUsable(); err != nil {
return "", false, err
}
configContext, err := config.getContext()
if err != nil {
return "", false, err
}
if len(configContext.Namespace) == 0 {
return "default", false, nil
}
return configContext.Namespace, false, nil
} | Namespace implements ClientConfig | Namespace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) ConfigAccess() ConfigAccess {
return config.configAccess
} | ConfigAccess implements ClientConfig | ConfigAccess | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) ConfirmUsable() error {
validationErrors := make([]error, 0)
var contextName string
if len(config.contextName) != 0 {
contextName = config.contextName
} else {
contextName = config.config.CurrentContext
}
if len(contextName) > 0 {
_, exists := config.config.Contexts[contextName]
if !exists {
validationErrors = append(validationErrors, &errContextNotFound{contextName})
}
}
authInfoName, _ := config.getAuthInfoName()
authInfo, _ := config.getAuthInfo()
validationErrors = append(validationErrors, validateAuthInfo(authInfoName, authInfo)...)
clusterName, _ := config.getClusterName()
cluster, _ := config.getCluster()
validationErrors = append(validationErrors, validateClusterInfo(clusterName, cluster)...)
// when direct client config is specified, and our only error is that no server is defined, we should
// return a standard "no config" error
if len(validationErrors) == 1 && validationErrors[0] == ErrEmptyCluster {
return newErrConfigurationInvalid([]error{ErrEmptyConfig})
}
return newErrConfigurationInvalid(validationErrors)
} | ConfirmUsable looks a particular context and determines if that particular part of the config is useable. There might still be errors in the config,
but no errors in the sections requested or referenced. It does not return early so that it can find as many errors as possible. | ConfirmUsable | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getContextName() (string, bool) {
if config.overrides != nil && len(config.overrides.CurrentContext) != 0 {
return config.overrides.CurrentContext, true
}
if len(config.contextName) != 0 {
return config.contextName, false
}
return config.config.CurrentContext, false
} | getContextName returns the default, or user-set context name, and a boolean that indicates
whether the default context name has been overwritten by a user-set flag, or left as its default value | getContextName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getAuthInfoName() (string, bool) {
if config.overrides != nil && len(config.overrides.Context.AuthInfo) != 0 {
return config.overrides.Context.AuthInfo, true
}
context, _ := config.getContext()
return context.AuthInfo, false
} | getAuthInfoName returns a string containing the current authinfo name for the current context,
and a boolean indicating whether the default authInfo name is overwritten by a user-set flag, or
left as its default value | getAuthInfoName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getClusterName() (string, bool) {
if config.overrides != nil && len(config.overrides.Context.Cluster) != 0 {
return config.overrides.Context.Cluster, true
}
context, _ := config.getContext()
return context.Cluster, false
} | getClusterName returns a string containing the default, or user-set cluster name, and a boolean
indicating whether the default clusterName has been overwritten by a user-set flag, or left as
its default value | getClusterName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getContext() (clientcmdapi.Context, error) {
contexts := config.config.Contexts
contextName, required := config.getContextName()
mergedContext := clientcmdapi.NewContext()
if configContext, exists := contexts[contextName]; exists {
mergo.Merge(mergedContext, configContext, mergo.WithOverride)
} else if required {
return clientcmdapi.Context{}, fmt.Errorf("context %q does not exist", contextName)
}
if config.overrides != nil {
mergo.Merge(mergedContext, config.overrides.Context, mergo.WithOverride)
}
return *mergedContext, nil
} | getContext returns the clientcmdapi.Context, or an error if a required context is not found. | getContext | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getAuthInfo() (clientcmdapi.AuthInfo, error) {
authInfos := config.config.AuthInfos
authInfoName, required := config.getAuthInfoName()
mergedAuthInfo := clientcmdapi.NewAuthInfo()
if configAuthInfo, exists := authInfos[authInfoName]; exists {
mergo.Merge(mergedAuthInfo, configAuthInfo, mergo.WithOverride)
} else if required {
return clientcmdapi.AuthInfo{}, fmt.Errorf("auth info %q does not exist", authInfoName)
}
if config.overrides != nil {
mergo.Merge(mergedAuthInfo, config.overrides.AuthInfo, mergo.WithOverride)
}
return *mergedAuthInfo, nil
} | getAuthInfo returns the clientcmdapi.AuthInfo, or an error if a required auth info is not found. | getAuthInfo | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) {
clusterInfos := config.config.Clusters
clusterInfoName, required := config.getClusterName()
mergedClusterInfo := clientcmdapi.NewCluster()
if config.overrides != nil {
mergo.Merge(mergedClusterInfo, config.overrides.ClusterDefaults, mergo.WithOverride)
}
if configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {
mergo.Merge(mergedClusterInfo, configClusterInfo, mergo.WithOverride)
} else if required {
return clientcmdapi.Cluster{}, fmt.Errorf("cluster %q does not exist", clusterInfoName)
}
if config.overrides != nil {
mergo.Merge(mergedClusterInfo, config.overrides.ClusterInfo, mergo.WithOverride)
}
// * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data
// otherwise, a kubeconfig containing a CA reference would return an error that "CA and insecure-skip-tls-verify couldn't both be set".
// * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence.
if config.overrides != nil {
caLen := len(config.overrides.ClusterInfo.CertificateAuthority)
caDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData)
if config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen > 0 || caDataLen > 0 {
mergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify
mergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority
mergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData
}
// if the --tls-server-name has been set in overrides, use that value.
// if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property
// that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is
// usually correct.
if config.overrides.ClusterInfo.TLSServerName != "" || config.overrides.ClusterInfo.Server != "" {
mergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName
}
}
return *mergedClusterInfo, nil
} | getCluster returns the clientcmdapi.Cluster, or an error if a required cluster is not found. | getCluster | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func (config *inClusterClientConfig) Possible() bool {
fi, err := os.Stat("/var/run/secrets/kubernetes.io/serviceaccount/token")
return os.Getenv("KUBERNETES_SERVICE_HOST") != "" &&
os.Getenv("KUBERNETES_SERVICE_PORT") != "" &&
err == nil && !fi.IsDir()
} | Possible returns true if loading an inside-kubernetes-cluster is possible. | Possible | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) {
if kubeconfigPath == "" && masterUrl == "" {
klog.Warning("Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.")
kubeconfig, err := restclient.InClusterConfig()
if err == nil {
return kubeconfig, nil
}
klog.Warning("error creating inClusterConfig, falling back to default config: ", err)
}
return NewNonInteractiveDeferredLoadingClientConfig(
&ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
&ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig()
} | BuildConfigFromFlags is a helper function that builds configs from a master
url or a kubeconfig filepath. These are passed in as command line flags for cluster
components. Warnings should reflect this usage. If neither masterUrl or kubeconfigPath
are passed in we fallback to inClusterConfig. If inClusterConfig fails, we fallback
to the default config. | BuildConfigFromFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func BuildConfigFromKubeconfigGetter(masterUrl string, kubeconfigGetter KubeconfigGetter) (*restclient.Config, error) {
// TODO: We do not need a DeferredLoader here. Refactor code and see if we can use DirectClientConfig here.
cc := NewNonInteractiveDeferredLoadingClientConfig(
&ClientConfigGetter{kubeconfigGetter: kubeconfigGetter},
&ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}})
return cc.ClientConfig()
} | BuildConfigFromKubeconfigGetter is a helper function that builds configs from a master
url and a kubeconfigGetter. | BuildConfigFromKubeconfigGetter | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/client_config.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/client_config.go | Apache-2.0 |
func NewNonInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides) ClientConfig {
return &DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: &inClusterClientConfig{overrides: overrides}}
} | NewNonInteractiveDeferredLoadingClientConfig creates a ClientConfig using the passed context name | NewNonInteractiveDeferredLoadingClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | Apache-2.0 |
func NewInteractiveDeferredLoadingClientConfig(loader ClientConfigLoader, overrides *ConfigOverrides, fallbackReader io.Reader) ClientConfig {
return &DeferredLoadingClientConfig{loader: loader, overrides: overrides, icc: &inClusterClientConfig{overrides: overrides}, fallbackReader: fallbackReader}
} | NewInteractiveDeferredLoadingClientConfig creates a ClientConfig using the passed context name and the fallback auth reader | NewInteractiveDeferredLoadingClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | Apache-2.0 |
func (config *DeferredLoadingClientConfig) ClientConfig() (*restclient.Config, error) {
mergedClientConfig, err := config.createClientConfig()
if err != nil {
return nil, err
}
// load the configuration and return on non-empty errors and if the
// content differs from the default config
mergedConfig, err := mergedClientConfig.ClientConfig()
switch {
case err != nil:
if !IsEmptyConfig(err) {
// return on any error except empty config
return nil, err
}
case mergedConfig != nil:
// the configuration is valid, but if this is equal to the defaults we should try
// in-cluster configuration
if !config.loader.IsDefaultConfig(mergedConfig) {
return mergedConfig, nil
}
}
// check for in-cluster configuration and use it
if config.icc.Possible() {
klog.V(4).Infof("Using in-cluster configuration")
return config.icc.ClientConfig()
}
// return the result of the merged client config
return mergedConfig, err
} | ClientConfig implements ClientConfig | ClientConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | Apache-2.0 |
func (config *DeferredLoadingClientConfig) Namespace() (string, bool, error) {
mergedKubeConfig, err := config.createClientConfig()
if err != nil {
return "", false, err
}
ns, overridden, err := mergedKubeConfig.Namespace()
// if we get an error and it is not empty config, or if the merged config defined an explicit namespace, or
// if in-cluster config is not possible, return immediately
if (err != nil && !IsEmptyConfig(err)) || overridden || !config.icc.Possible() {
// return on any error except empty config
return ns, overridden, err
}
if len(ns) > 0 {
// if we got a non-default namespace from the kubeconfig, use it
if ns != "default" {
return ns, false, nil
}
// if we got a default namespace, determine whether it was explicit or implicit
if raw, err := mergedKubeConfig.RawConfig(); err == nil {
// determine the current context
currentContext := raw.CurrentContext
if config.overrides != nil && len(config.overrides.CurrentContext) > 0 {
currentContext = config.overrides.CurrentContext
}
if context := raw.Contexts[currentContext]; context != nil && len(context.Namespace) > 0 {
return ns, false, nil
}
}
}
klog.V(4).Infof("Using in-cluster namespace")
// allow the namespace from the service account token directory to be used.
return config.icc.Namespace()
} | Namespace implements KubeConfig | Namespace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | Apache-2.0 |
func (config *DeferredLoadingClientConfig) ConfigAccess() ConfigAccess {
return config.loader
} | ConfigAccess implements ClientConfig | ConfigAccess | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder.go | Apache-2.0 |
func currentMigrationRules() map[string]string {
var oldRecommendedHomeFileName string
if goruntime.GOOS == "windows" {
oldRecommendedHomeFileName = RecommendedFileName
} else {
oldRecommendedHomeFileName = ".kubeconfig"
}
return map[string]string{
RecommendedHomeFile: filepath.Join(os.Getenv("HOME"), RecommendedHomeDir, oldRecommendedHomeFileName),
}
} | currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions.
Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make
sure existing config files are migrated to their new locations properly. | currentMigrationRules | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules {
chain := []string{}
warnIfAllMissing := false
envVarFiles := os.Getenv(RecommendedConfigPathEnvVar)
if len(envVarFiles) != 0 {
fileList := filepath.SplitList(envVarFiles)
// prevent the same path load multiple times
chain = append(chain, deduplicate(fileList)...)
warnIfAllMissing = true
} else {
chain = append(chain, RecommendedHomeFile)
}
return &ClientConfigLoadingRules{
Precedence: chain,
MigrationRules: currentMigrationRules(),
WarnIfAllMissing: warnIfAllMissing,
}
} | NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to
use this constructor | NewDefaultClientConfigLoadingRules | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) {
if err := rules.Migrate(); err != nil {
return nil, err
}
errlist := []error{}
missingList := []string{}
kubeConfigFiles := []string{}
// Make sure a file we were explicitly told to use exists
if len(rules.ExplicitPath) > 0 {
if _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) {
return nil, err
}
kubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath)
} else {
kubeConfigFiles = append(kubeConfigFiles, rules.Precedence...)
}
kubeconfigs := []*clientcmdapi.Config{}
// read and cache the config files so that we only look at them once
for _, filename := range kubeConfigFiles {
if len(filename) == 0 {
// no work to do
continue
}
config, err := LoadFromFile(filename)
if os.IsNotExist(err) {
// skip missing files
// Add to the missing list to produce a warning
missingList = append(missingList, filename)
continue
}
if err != nil {
errlist = append(errlist, fmt.Errorf("error loading config file \"%s\": %v", filename, err))
continue
}
kubeconfigs = append(kubeconfigs, config)
}
if rules.WarnIfAllMissing && len(missingList) > 0 && len(kubeconfigs) == 0 {
rules.Warner.Warn(MissingConfigError{Missing: missingList})
}
// first merge all of our maps
mapConfig := clientcmdapi.NewConfig()
for _, kubeconfig := range kubeconfigs {
mergo.Merge(mapConfig, kubeconfig, mergo.WithOverride)
}
// merge all of the struct values in the reverse order so that priority is given correctly
// errors are not added to the list the second time
nonMapConfig := clientcmdapi.NewConfig()
for i := len(kubeconfigs) - 1; i >= 0; i-- {
kubeconfig := kubeconfigs[i]
mergo.Merge(nonMapConfig, kubeconfig, mergo.WithOverride)
}
// since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and
// get the values we expect.
config := clientcmdapi.NewConfig()
mergo.Merge(config, mapConfig, mergo.WithOverride)
mergo.Merge(config, nonMapConfig, mergo.WithOverride)
if rules.ResolvePaths() {
if err := ResolveLocalPaths(config); err != nil {
errlist = append(errlist, err)
}
}
return config, utilerrors.NewAggregate(errlist)
} | Load starts by running the MigrationRules and then
takes the loading rules and returns a Config object based on following rules.
if the ExplicitPath, return the unmerged explicit file
Otherwise, return a merged config based on the Precedence slice
A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored.
Read errors or files with non-deserializable content produce errors.
The first file to set a particular map key wins and map key's value is never changed.
BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed.
This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two.
It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even
non-conflicting entries from the second file's "red-user" are discarded.
Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder
and only absolute file paths are returned. | Load | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) Migrate() error {
if rules.MigrationRules == nil {
return nil
}
for destination, source := range rules.MigrationRules {
if _, err := os.Stat(destination); err == nil {
// if the destination already exists, do nothing
continue
} else if os.IsPermission(err) {
// if we can't access the file, skip it
continue
} else if !os.IsNotExist(err) {
// if we had an error other than non-existence, fail
return err
}
if sourceInfo, err := os.Stat(source); err != nil {
if os.IsNotExist(err) || os.IsPermission(err) {
// if the source file doesn't exist or we can't access it, there's no work to do.
continue
}
// if we had an error other than non-existence, fail
return err
} else if sourceInfo.IsDir() {
return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination)
}
data, err := os.ReadFile(source)
if err != nil {
return err
}
// destination is created with mode 0666 before umask
err = os.WriteFile(destination, data, 0666)
if err != nil {
return err
}
}
return nil
} | Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked.
If the source file is present, then it is copied to the destination file BEFORE any further loading happens. | Migrate | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string {
if len(rules.ExplicitPath) > 0 {
return []string{rules.ExplicitPath}
}
return rules.Precedence
} | GetLoadingPrecedence implements ConfigAccess | GetLoadingPrecedence | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) {
clientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, &ConfigOverrides{})
rawConfig, err := clientConfig.RawConfig()
if os.IsNotExist(err) {
return clientcmdapi.NewConfig(), nil
}
if err != nil {
return nil, err
}
return &rawConfig, nil
} | GetStartingConfig implements ConfigAccess | GetStartingConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) GetDefaultFilename() string {
// Explicit file if we have one.
if rules.IsExplicitFile() {
return rules.GetExplicitFile()
}
// Otherwise, first existing file from precedence.
for _, filename := range rules.GetLoadingPrecedence() {
if _, err := os.Stat(filename); err == nil {
return filename
}
}
// If none exists, use the first from precedence.
if len(rules.Precedence) > 0 {
return rules.Precedence[0]
}
return ""
} | GetDefaultFilename implements ConfigAccess | GetDefaultFilename | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) IsExplicitFile() bool {
return len(rules.ExplicitPath) > 0
} | IsExplicitFile implements ConfigAccess | IsExplicitFile | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) GetExplicitFile() string {
return rules.ExplicitPath
} | GetExplicitFile implements ConfigAccess | GetExplicitFile | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool {
if rules.DefaultClientConfig == nil {
return false
}
defaultConfig, err := rules.DefaultClientConfig.ClientConfig()
if err != nil {
return false
}
return reflect.DeepEqual(config, defaultConfig)
} | IsDefaultConfig returns true if the provided configuration matches the default | IsDefaultConfig | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func LoadFromFile(filename string) (*clientcmdapi.Config, error) {
kubeconfigBytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
config, err := Load(kubeconfigBytes)
if err != nil {
return nil, err
}
klog.V(6).Infoln("Config loaded from file: ", filename)
// set LocationOfOrigin on every Cluster, User, and Context
for key, obj := range config.AuthInfos {
obj.LocationOfOrigin = filename
config.AuthInfos[key] = obj
}
for key, obj := range config.Clusters {
obj.LocationOfOrigin = filename
config.Clusters[key] = obj
}
for key, obj := range config.Contexts {
obj.LocationOfOrigin = filename
config.Contexts[key] = obj
}
if config.AuthInfos == nil {
config.AuthInfos = map[string]*clientcmdapi.AuthInfo{}
}
if config.Clusters == nil {
config.Clusters = map[string]*clientcmdapi.Cluster{}
}
if config.Contexts == nil {
config.Contexts = map[string]*clientcmdapi.Context{}
}
return config, nil
} | LoadFromFile takes a filename and deserializes the contents into Config object | LoadFromFile | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func Load(data []byte) (*clientcmdapi.Config, error) {
config := clientcmdapi.NewConfig()
// if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)
if len(data) == 0 {
return config, nil
}
decoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config)
if err != nil {
return nil, err
}
return decoded.(*clientcmdapi.Config), nil
} | Load takes a byte slice and deserializes the contents into Config object.
Encapsulates deserialization without assuming the source is a file. | Load | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func WriteToFile(config clientcmdapi.Config, filename string) error {
content, err := Write(config)
if err != nil {
return err
}
dir := filepath.Dir(filename)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err = os.MkdirAll(dir, 0755); err != nil {
return err
}
}
if err := os.WriteFile(filename, content, 0600); err != nil {
return err
}
return nil
} | WriteToFile serializes the config to yaml and writes it out to a file. If not present, it creates the file with the mode 0600. If it is present
it stomps the contents | WriteToFile | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func Write(config clientcmdapi.Config) ([]byte, error) {
return runtime.Encode(clientcmdlatest.Codec, &config)
} | Write serializes the config to yaml.
Encapsulates serialization without assuming the destination is a file. | Write | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func ResolveLocalPaths(config *clientcmdapi.Config) error {
for _, cluster := range config.Clusters {
if len(cluster.LocationOfOrigin) == 0 {
continue
}
base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
if err != nil {
return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
}
if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
return err
}
}
for _, authInfo := range config.AuthInfos {
if len(authInfo.LocationOfOrigin) == 0 {
continue
}
base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
if err != nil {
return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
}
if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
return err
}
}
return nil
} | ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin
this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without
modification of its contents. | ResolveLocalPaths | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error {
if len(cluster.LocationOfOrigin) == 0 {
return fmt.Errorf("no location of origin for %s", cluster.Server)
}
base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
if err != nil {
return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
}
if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
return err
}
if err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil {
return err
}
return nil
} | RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
absolute, but any existing path will be resolved relative to LocationOfOrigin | RelativizeClusterLocalPaths | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error {
if len(authInfo.LocationOfOrigin) == 0 {
return fmt.Errorf("no location of origin for %v", authInfo)
}
base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
if err != nil {
return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
}
if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
return err
}
if err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil {
return err
}
return nil
} | RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
absolute, but any existing path will be resolved relative to LocationOfOrigin | RelativizeAuthInfoLocalPaths | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func ResolvePaths(refs []*string, base string) error {
for _, ref := range refs {
// Don't resolve empty paths
if len(*ref) > 0 {
// Don't resolve absolute paths
if !filepath.IsAbs(*ref) {
*ref = filepath.Join(base, *ref)
}
}
}
return nil
} | ResolvePaths updates the given refs to be absolute paths, relative to the given base directory | ResolvePaths | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func RelativizePathWithNoBacksteps(refs []*string, base string) error {
for _, ref := range refs {
// Don't relativize empty paths
if len(*ref) > 0 {
rel, err := MakeRelative(*ref, base)
if err != nil {
return err
}
// if we have a backstep, don't mess with the path
if strings.HasPrefix(rel, "../") {
if filepath.IsAbs(*ref) {
continue
}
return fmt.Errorf("%v requires backsteps and is not absolute", *ref)
}
*ref = rel
}
}
return nil
} | RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps.
Any path requiring a backstep is left as-is as long it is absolute. Any non-absolute path that can't be relativized produces an error | RelativizePathWithNoBacksteps | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func deduplicate(s []string) []string {
encountered := map[string]bool{}
ret := make([]string, 0)
for i := range s {
if encountered[s[i]] {
continue
}
encountered[s[i]] = true
ret = append(ret, s[i])
}
return ret
} | deduplicate removes any duplicated values and returns a new slice, keeping the order unchanged | deduplicate | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/loader.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/loader.go | Apache-2.0 |
func (f FlagInfo) AddSecretAnnotation(flags *pflag.FlagSet) FlagInfo {
flags.SetAnnotation(f.LongName, "classified", []string{"true"})
return f
} | AddSecretAnnotation add secret flag to Annotation. | AddSecretAnnotation | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func (f FlagInfo) BindStringFlag(flags *pflag.FlagSet, target *string) FlagInfo {
// you can't register a flag without a long name
if len(f.LongName) > 0 {
flags.StringVarP(target, f.LongName, f.ShortName, f.Default, f.Description)
}
return f
} | BindStringFlag binds the flag based on the provided info. If LongName == "", nothing is registered | BindStringFlag | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func (f FlagInfo) BindTransformingStringFlag(flags *pflag.FlagSet, target *string, transformer func(string) (string, error)) FlagInfo {
// you can't register a flag without a long name
if len(f.LongName) > 0 {
flags.VarP(newTransformingStringValue(f.Default, target, transformer), f.LongName, f.ShortName, f.Description)
}
return f
} | BindTransformingStringFlag binds the flag based on the provided info. If LongName == "", nothing is registered | BindTransformingStringFlag | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func (f FlagInfo) BindStringArrayFlag(flags *pflag.FlagSet, target *[]string) FlagInfo {
// you can't register a flag without a long name
if len(f.LongName) > 0 {
sliceVal := []string{}
if len(f.Default) > 0 {
sliceVal = []string{f.Default}
}
flags.StringArrayVarP(target, f.LongName, f.ShortName, sliceVal, f.Description)
}
return f
} | BindStringSliceFlag binds the flag based on the provided info. If LongName == "", nothing is registered | BindStringArrayFlag | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func (f FlagInfo) BindBoolFlag(flags *pflag.FlagSet, target *bool) FlagInfo {
// you can't register a flag without a long name
if len(f.LongName) > 0 {
// try to parse Default as a bool. If it fails, assume false
boolVal, err := strconv.ParseBool(f.Default)
if err != nil {
boolVal = false
}
flags.BoolVarP(target, f.LongName, f.ShortName, boolVal, f.Description)
}
return f
} | BindBoolFlag binds the flag based on the provided info. If LongName == "", nothing is registered | BindBoolFlag | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func RecommendedConfigOverrideFlags(prefix string) ConfigOverrideFlags {
return ConfigOverrideFlags{
AuthOverrideFlags: RecommendedAuthOverrideFlags(prefix),
ClusterOverrideFlags: RecommendedClusterOverrideFlags(prefix),
ContextOverrideFlags: RecommendedContextOverrideFlags(prefix),
CurrentContext: FlagInfo{prefix + FlagContext, "", "", "The name of the kubeconfig context to use"},
Timeout: FlagInfo{prefix + FlagTimeout, "", "0", "The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests."},
}
} | RecommendedConfigOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing | RecommendedConfigOverrideFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func RecommendedAuthOverrideFlags(prefix string) AuthOverrideFlags {
return AuthOverrideFlags{
ClientCertificate: FlagInfo{prefix + FlagCertFile, "", "", "Path to a client certificate file for TLS"},
ClientKey: FlagInfo{prefix + FlagKeyFile, "", "", "Path to a client key file for TLS"},
Token: FlagInfo{prefix + FlagBearerToken, "", "", "Bearer token for authentication to the API server"},
Impersonate: FlagInfo{prefix + FlagImpersonate, "", "", "Username to impersonate for the operation"},
ImpersonateUID: FlagInfo{prefix + FlagImpersonateUID, "", "", "UID to impersonate for the operation"},
ImpersonateGroups: FlagInfo{prefix + FlagImpersonateGroup, "", "", "Group to impersonate for the operation, this flag can be repeated to specify multiple groups."},
Username: FlagInfo{prefix + FlagUsername, "", "", "Username for basic authentication to the API server"},
Password: FlagInfo{prefix + FlagPassword, "", "", "Password for basic authentication to the API server"},
}
} | RecommendedAuthOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing | RecommendedAuthOverrideFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func RecommendedClusterOverrideFlags(prefix string) ClusterOverrideFlags {
return ClusterOverrideFlags{
APIServer: FlagInfo{prefix + FlagAPIServer, "", "", "The address and port of the Kubernetes API server"},
CertificateAuthority: FlagInfo{prefix + FlagCAFile, "", "", "Path to a cert file for the certificate authority"},
InsecureSkipTLSVerify: FlagInfo{prefix + FlagInsecure, "", "false", "If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure"},
TLSServerName: FlagInfo{prefix + FlagTLSServerName, "", "", "If provided, this name will be used to validate server certificate. If this is not provided, hostname used to contact the server is used."},
ProxyURL: FlagInfo{prefix + FlagProxyURL, "", "", "If provided, this URL will be used to connect via proxy"},
DisableCompression: FlagInfo{prefix + FlagDisableCompression, "", "", "If true, opt-out of response compression for all requests to the server"},
}
} | RecommendedClusterOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing | RecommendedClusterOverrideFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags {
return ContextOverrideFlags{
ClusterName: FlagInfo{prefix + FlagClusterName, "", "", "The name of the kubeconfig cluster to use"},
AuthInfoName: FlagInfo{prefix + FlagAuthInfoName, "", "", "The name of the kubeconfig user to use"},
Namespace: FlagInfo{prefix + FlagNamespace, "n", "", "If present, the namespace scope for this CLI request"},
}
} | RecommendedContextOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing | RecommendedContextOverrideFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func BindOverrideFlags(overrides *ConfigOverrides, flags *pflag.FlagSet, flagNames ConfigOverrideFlags) {
BindAuthInfoFlags(&overrides.AuthInfo, flags, flagNames.AuthOverrideFlags)
BindClusterFlags(&overrides.ClusterInfo, flags, flagNames.ClusterOverrideFlags)
BindContextFlags(&overrides.Context, flags, flagNames.ContextOverrideFlags)
flagNames.CurrentContext.BindStringFlag(flags, &overrides.CurrentContext)
flagNames.Timeout.BindStringFlag(flags, &overrides.Timeout)
} | BindOverrideFlags is a convenience method to bind the specified flags to their associated variables | BindOverrideFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func BindAuthInfoFlags(authInfo *clientcmdapi.AuthInfo, flags *pflag.FlagSet, flagNames AuthOverrideFlags) {
flagNames.ClientCertificate.BindStringFlag(flags, &authInfo.ClientCertificate).AddSecretAnnotation(flags)
flagNames.ClientKey.BindStringFlag(flags, &authInfo.ClientKey).AddSecretAnnotation(flags)
flagNames.Token.BindStringFlag(flags, &authInfo.Token).AddSecretAnnotation(flags)
flagNames.Impersonate.BindStringFlag(flags, &authInfo.Impersonate).AddSecretAnnotation(flags)
flagNames.ImpersonateUID.BindStringFlag(flags, &authInfo.ImpersonateUID).AddSecretAnnotation(flags)
flagNames.ImpersonateGroups.BindStringArrayFlag(flags, &authInfo.ImpersonateGroups).AddSecretAnnotation(flags)
flagNames.Username.BindStringFlag(flags, &authInfo.Username).AddSecretAnnotation(flags)
flagNames.Password.BindStringFlag(flags, &authInfo.Password).AddSecretAnnotation(flags)
} | BindAuthInfoFlags is a convenience method to bind the specified flags to their associated variables | BindAuthInfoFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func BindClusterFlags(clusterInfo *clientcmdapi.Cluster, flags *pflag.FlagSet, flagNames ClusterOverrideFlags) {
flagNames.APIServer.BindStringFlag(flags, &clusterInfo.Server)
flagNames.CertificateAuthority.BindStringFlag(flags, &clusterInfo.CertificateAuthority)
flagNames.InsecureSkipTLSVerify.BindBoolFlag(flags, &clusterInfo.InsecureSkipTLSVerify)
flagNames.TLSServerName.BindStringFlag(flags, &clusterInfo.TLSServerName)
flagNames.ProxyURL.BindStringFlag(flags, &clusterInfo.ProxyURL)
flagNames.DisableCompression.BindBoolFlag(flags, &clusterInfo.DisableCompression)
} | BindClusterFlags is a convenience method to bind the specified flags to their associated variables | BindClusterFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
func BindContextFlags(contextInfo *clientcmdapi.Context, flags *pflag.FlagSet, flagNames ContextOverrideFlags) {
flagNames.ClusterName.BindStringFlag(flags, &contextInfo.Cluster)
flagNames.AuthInfoName.BindStringFlag(flags, &contextInfo.AuthInfo)
flagNames.Namespace.BindTransformingStringFlag(flags, &contextInfo.Namespace, RemoveNamespacesPrefix)
} | BindFlags is a convenience method to bind the specified flags to their associated variables | BindContextFlags | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/clientcmd/overrides.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/clientcmd/overrides.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.