| 1 |
/* |
| 2 |
Copyright The containerd Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package kubeconfig |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"context" |
| 22 |
"fmt" |
| 23 |
"os" |
| 24 |
"sync" |
| 25 |
"time" |
| 26 |
|
| 27 |
"github.com/containerd/containerd/log" |
| 28 |
"github.com/containerd/containerd/reference" |
| 29 |
"github.com/containerd/stargz-snapshotter/service/resolver" |
| 30 |
dcfile "github.com/docker/cli/cli/config/configfile" |
| 31 |
corev1 "k8s.io/api/core/v1" |
| 32 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 33 |
"k8s.io/apimachinery/pkg/runtime" |
| 34 |
utilruntime "k8s.io/apimachinery/pkg/util/runtime" |
| 35 |
"k8s.io/apimachinery/pkg/util/wait" |
| 36 |
"k8s.io/apimachinery/pkg/watch" |
| 37 |
"k8s.io/client-go/kubernetes" |
| 38 |
"k8s.io/client-go/tools/cache" |
| 39 |
"k8s.io/client-go/tools/clientcmd" |
| 40 |
"k8s.io/client-go/util/workqueue" |
| 41 |
) |
| 42 |
|
| 43 |
const dockerconfigSelector = "type=" + string(corev1.SecretTypeDockerConfigJson) |
| 44 |
|
| 45 |
type options struct { |
| 46 |
kubeconfigPath string |
| 47 |
} |
| 48 |
|
| 49 |
type Option func(*options) |
| 50 |
|
| 51 |
func WithKubeconfigPath(path string) Option { |
| 52 |
return func(opts *options) { |
| 53 |
opts.kubeconfigPath = path |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// NewKubeconfigKeychain provides a keychain which can sync its contents with |
| 58 |
// kubernetes API server by fetching all `kubernetes.io/dockerconfigjson` |
| 59 |
// secrets in the cluster with provided kubeconfig. It's OK that config provides |
| 60 |
// kubeconfig path but the file doesn't exist at that moment. In this case, this |
| 61 |
// keychain keeps on trying to read the specified path periodically and when the |
| 62 |
// file is actually provided, this keychain tries to access API server using the |
| 63 |
// file. This is useful for some environments (e.g. single node cluster with |
| 64 |
// containerized apiserver) where stargz snapshotter needs to start before |
| 65 |
// everything, including booting containerd/kubelet/apiserver and configuring |
| 66 |
// users/roles. |
| 67 |
// TODO: support update of kubeconfig file |
| 68 |
func NewKubeconfigKeychain(ctx context.Context, opts ...Option) resolver.Credential { |
| 69 |
var kcOpts options |
| 70 |
for _, o := range opts { |
| 71 |
o(&kcOpts) |
| 72 |
} |
| 73 |
kc := newKeychain(ctx, kcOpts.kubeconfigPath) |
| 74 |
return kc.credentials |
| 75 |
} |
| 76 |
|
| 77 |
func newKeychain(ctx context.Context, kubeconfigPath string) *keychain { |
| 78 |
kc := &keychain{ |
| 79 |
config: make(map[string]*dcfile.ConfigFile), |
| 80 |
} |
| 81 |
ctx = log.WithLogger(ctx, log.G(ctx).WithField("kubeconfig", kubeconfigPath)) |
| 82 |
go func() { |
| 83 |
if kubeconfigPath != "" { |
| 84 |
log.G(ctx).Debugf("Waiting for kubeconfig being installed...") |
| 85 |
for { |
| 86 |
if _, err := os.Stat(kubeconfigPath); err == nil { |
| 87 |
break |
| 88 |
} else if !os.IsNotExist(err) { |
| 89 |
log.G(ctx).WithError(err). |
| 90 |
Warnf("failed to read; Disabling syncing") |
| 91 |
return |
| 92 |
} |
| 93 |
time.Sleep(10 * time.Second) |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
// default loader for KUBECONFIG or `~/.kube/config` |
| 98 |
// if no explicit path provided, KUBECONFIG will be used. |
| 99 |
// if KUBECONFIG doesn't contain paths, `~/.kube/config` will be used. |
| 100 |
loadingRule := clientcmd.NewDefaultClientConfigLoadingRules() |
| 101 |
|
| 102 |
// explicitly provide path for kubeconfig. |
| 103 |
// if path isn't "", this path will be respected. |
| 104 |
loadingRule.ExplicitPath = kubeconfigPath |
| 105 |
|
| 106 |
// load and merge config files |
| 107 |
clientcfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( |
| 108 |
loadingRule, // loader for config files |
| 109 |
&clientcmd.ConfigOverrides{}, // no overrides for config |
| 110 |
).ClientConfig() |
| 111 |
if err != nil { |
| 112 |
log.G(ctx).WithError(err).Warnf("failed to load config; Disabling syncing") |
| 113 |
return |
| 114 |
} |
| 115 |
|
| 116 |
client, err := kubernetes.NewForConfig(clientcfg) |
| 117 |
if err != nil { |
| 118 |
log.G(ctx).WithError(err).Warnf("failed to prepare client; Disabling syncing") |
| 119 |
return |
| 120 |
} |
| 121 |
if err := kc.startSyncSecrets(ctx, client); err != nil { |
| 122 |
log.G(ctx).WithError(err).Warnf("failed to sync secrets") |
| 123 |
} |
| 124 |
}() |
| 125 |
return kc |
| 126 |
} |
| 127 |
|
| 128 |
type keychain struct { |
| 129 |
config map[string]*dcfile.ConfigFile |
| 130 |
configMu sync.Mutex |
| 131 |
|
| 132 |
// the following entries are used for syncing secrets with API server. |
| 133 |
// these fields are lazily filled after kubeconfig file is provided. |
| 134 |
queue *workqueue.Type |
| 135 |
informer cache.SharedIndexInformer |
| 136 |
} |
| 137 |
|
| 138 |
func (kc *keychain) credentials(host string, refspec reference.Spec) (string, string, error) { |
| 139 |
if host == "docker.io" || host == "registry-1.docker.io" { |
| 140 |
// Creds of "docker.io" is stored keyed by "https://index.docker.io/v1/". |
| 141 |
host = "https://index.docker.io/v1/" |
| 142 |
} |
| 143 |
kc.configMu.Lock() |
| 144 |
defer kc.configMu.Unlock() |
| 145 |
for _, cfg := range kc.config { |
| 146 |
if acfg, err := cfg.GetAuthConfig(host); err == nil { |
| 147 |
if acfg.IdentityToken != "" { |
| 148 |
return "", acfg.IdentityToken, nil |
| 149 |
} else if !(acfg.Username == "" && acfg.Password == "") { |
| 150 |
return acfg.Username, acfg.Password, nil |
| 151 |
} |
| 152 |
} |
| 153 |
} |
| 154 |
return "", "", nil |
| 155 |
} |
| 156 |
|
| 157 |
func (kc *keychain) startSyncSecrets(ctx context.Context, client kubernetes.Interface) error { |
| 158 |
|
| 159 |
// don't let panics crash the process |
| 160 |
defer utilruntime.HandleCrash() |
| 161 |
|
| 162 |
// get informed on `kubernetes.io/dockerconfigjson` secrets in all namespaces |
| 163 |
informer := cache.NewSharedIndexInformer( |
| 164 |
&cache.ListWatch{ |
| 165 |
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { |
| 166 |
// TODO: support legacy image secret `kubernetes.io/dockercfg` |
| 167 |
options.FieldSelector = dockerconfigSelector |
| 168 |
return client.CoreV1().Secrets(metav1.NamespaceAll).List(ctx, options) |
| 169 |
}, |
| 170 |
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { |
| 171 |
// TODO: support legacy image secret `kubernetes.io/dockercfg` |
| 172 |
options.FieldSelector = dockerconfigSelector |
| 173 |
return client.CoreV1().Secrets(metav1.NamespaceAll).Watch(ctx, options) |
| 174 |
}, |
| 175 |
}, |
| 176 |
&corev1.Secret{}, |
| 177 |
0, |
| 178 |
cache.Indexers{}, |
| 179 |
) |
| 180 |
|
| 181 |
// use workqueue because each task possibly takes long for parsing config, |
| 182 |
// wating for lock, etc... |
| 183 |
queue := workqueue.New() |
| 184 |
defer queue.ShutDown() |
| 185 |
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ |
| 186 |
AddFunc: func(obj interface{}) { |
| 187 |
key, err := cache.MetaNamespaceKeyFunc(obj) |
| 188 |
if err == nil { |
| 189 |
queue.Add(key) |
| 190 |
} |
| 191 |
}, |
| 192 |
UpdateFunc: func(old, new interface{}) { |
| 193 |
key, err := cache.MetaNamespaceKeyFunc(new) |
| 194 |
if err == nil { |
| 195 |
queue.Add(key) |
| 196 |
} |
| 197 |
}, |
| 198 |
DeleteFunc: func(obj interface{}) { |
| 199 |
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) |
| 200 |
if err == nil { |
| 201 |
queue.Add(key) |
| 202 |
} |
| 203 |
}, |
| 204 |
}) |
| 205 |
go informer.Run(ctx.Done()) |
| 206 |
if !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) { |
| 207 |
return fmt.Errorf("Timed out for syncing cache") |
| 208 |
} |
| 209 |
|
| 210 |
// get informer and queue |
| 211 |
kc.informer = informer |
| 212 |
kc.queue = queue |
| 213 |
|
| 214 |
// keep on syncing secrets |
| 215 |
wait.Until(kc.runWorker, time.Second, ctx.Done()) |
| 216 |
|
| 217 |
return nil |
| 218 |
} |
| 219 |
|
| 220 |
func (kc *keychain) runWorker() { |
| 221 |
for kc.processNextItem() { |
| 222 |
// continue looping |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
// TODO: consider retrying? |
| 227 |
func (kc *keychain) processNextItem() bool { |
| 228 |
key, quit := kc.queue.Get() |
| 229 |
if quit { |
| 230 |
return false |
| 231 |
} |
| 232 |
defer kc.queue.Done(key) |
| 233 |
|
| 234 |
obj, exists, err := kc.informer.GetIndexer().GetByKey(key.(string)) |
| 235 |
if err != nil { |
| 236 |
utilruntime.HandleError(fmt.Errorf("failed to get object; don't sync %q: %v", key, err)) |
| 237 |
return true |
| 238 |
} |
| 239 |
if !exists { |
| 240 |
kc.configMu.Lock() |
| 241 |
delete(kc.config, key.(string)) |
| 242 |
kc.configMu.Unlock() |
| 243 |
return true |
| 244 |
} |
| 245 |
|
| 246 |
// TODO: support legacy image secret `kubernetes.io/dockercfg` |
| 247 |
data, ok := obj.(*corev1.Secret).Data[corev1.DockerConfigJsonKey] |
| 248 |
if !ok { |
| 249 |
utilruntime.HandleError(fmt.Errorf("no secret is provided; don't sync %q", key)) |
| 250 |
return true |
| 251 |
} |
| 252 |
configFile := dcfile.New("") |
| 253 |
if err := configFile.LoadFromReader(bytes.NewReader(data)); err != nil { |
| 254 |
utilruntime.HandleError(fmt.Errorf("broken data; don't sync %q: %v", key, err)) |
| 255 |
return true |
| 256 |
} |
| 257 |
kc.configMu.Lock() |
| 258 |
kc.config[key.(string)] = configFile |
| 259 |
kc.configMu.Unlock() |
| 260 |
|
| 261 |
return true |
| 262 |
} |