loader.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package clientcmd
  14. import (
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "reflect"
  22. goruntime "runtime"
  23. "strings"
  24. "github.com/golang/glog"
  25. "github.com/imdario/mergo"
  26. "k8s.io/apimachinery/pkg/runtime"
  27. "k8s.io/apimachinery/pkg/runtime/schema"
  28. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  29. restclient "k8s.io/client-go/rest"
  30. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  31. clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
  32. "k8s.io/client-go/util/homedir"
  33. )
  34. const (
  35. RecommendedConfigPathFlag = "kubeconfig"
  36. RecommendedConfigPathEnvVar = "KUBECONFIG"
  37. RecommendedHomeDir = ".kube"
  38. RecommendedFileName = "config"
  39. RecommendedSchemaName = "schema"
  40. )
  41. var RecommendedHomeFile = path.Join(homedir.HomeDir(), RecommendedHomeDir, RecommendedFileName)
  42. var RecommendedSchemaFile = path.Join(homedir.HomeDir(), RecommendedHomeDir, RecommendedSchemaName)
  43. // currentMigrationRules returns a map that holds the history of recommended home directories used in previous versions.
  44. // Any future changes to RecommendedHomeFile and related are expected to add a migration rule here, in order to make
  45. // sure existing config files are migrated to their new locations properly.
  46. func currentMigrationRules() map[string]string {
  47. oldRecommendedHomeFile := path.Join(os.Getenv("HOME"), "/.kube/.kubeconfig")
  48. oldRecommendedWindowsHomeFile := path.Join(os.Getenv("HOME"), RecommendedHomeDir, RecommendedFileName)
  49. migrationRules := map[string]string{}
  50. migrationRules[RecommendedHomeFile] = oldRecommendedHomeFile
  51. if goruntime.GOOS == "windows" {
  52. migrationRules[RecommendedHomeFile] = oldRecommendedWindowsHomeFile
  53. }
  54. return migrationRules
  55. }
  56. type ClientConfigLoader interface {
  57. ConfigAccess
  58. // IsDefaultConfig returns true if the returned config matches the defaults.
  59. IsDefaultConfig(*restclient.Config) bool
  60. // Load returns the latest config
  61. Load() (*clientcmdapi.Config, error)
  62. }
  63. type KubeconfigGetter func() (*clientcmdapi.Config, error)
  64. type ClientConfigGetter struct {
  65. kubeconfigGetter KubeconfigGetter
  66. }
  67. // ClientConfigGetter implements the ClientConfigLoader interface.
  68. var _ ClientConfigLoader = &ClientConfigGetter{}
  69. func (g *ClientConfigGetter) Load() (*clientcmdapi.Config, error) {
  70. return g.kubeconfigGetter()
  71. }
  72. func (g *ClientConfigGetter) GetLoadingPrecedence() []string {
  73. return nil
  74. }
  75. func (g *ClientConfigGetter) GetStartingConfig() (*clientcmdapi.Config, error) {
  76. return g.kubeconfigGetter()
  77. }
  78. func (g *ClientConfigGetter) GetDefaultFilename() string {
  79. return ""
  80. }
  81. func (g *ClientConfigGetter) IsExplicitFile() bool {
  82. return false
  83. }
  84. func (g *ClientConfigGetter) GetExplicitFile() string {
  85. return ""
  86. }
  87. func (g *ClientConfigGetter) IsDefaultConfig(config *restclient.Config) bool {
  88. return false
  89. }
  90. // ClientConfigLoadingRules is an ExplicitPath and string slice of specific locations that are used for merging together a Config
  91. // Callers can put the chain together however they want, but we'd recommend:
  92. // EnvVarPathFiles if set (a list of files if set) OR the HomeDirectoryPath
  93. // ExplicitPath is special, because if a user specifically requests a certain file be used and error is reported if thie file is not present
  94. type ClientConfigLoadingRules struct {
  95. ExplicitPath string
  96. Precedence []string
  97. // MigrationRules is a map of destination files to source files. If a destination file is not present, then the source file is checked.
  98. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens.
  99. MigrationRules map[string]string
  100. // DoNotResolvePaths indicates whether or not to resolve paths with respect to the originating files. This is phrased as a negative so
  101. // that a default object that doesn't set this will usually get the behavior it wants.
  102. DoNotResolvePaths bool
  103. // DefaultClientConfig is an optional field indicating what rules to use to calculate a default configuration.
  104. // This should match the overrides passed in to ClientConfig loader.
  105. DefaultClientConfig ClientConfig
  106. }
  107. // ClientConfigLoadingRules implements the ClientConfigLoader interface.
  108. var _ ClientConfigLoader = &ClientConfigLoadingRules{}
  109. // NewDefaultClientConfigLoadingRules returns a ClientConfigLoadingRules object with default fields filled in. You are not required to
  110. // use this constructor
  111. func NewDefaultClientConfigLoadingRules() *ClientConfigLoadingRules {
  112. chain := []string{}
  113. envVarFiles := os.Getenv(RecommendedConfigPathEnvVar)
  114. if len(envVarFiles) != 0 {
  115. chain = append(chain, filepath.SplitList(envVarFiles)...)
  116. } else {
  117. chain = append(chain, RecommendedHomeFile)
  118. }
  119. return &ClientConfigLoadingRules{
  120. Precedence: chain,
  121. MigrationRules: currentMigrationRules(),
  122. }
  123. }
  124. // Load starts by running the MigrationRules and then
  125. // takes the loading rules and returns a Config object based on following rules.
  126. // if the ExplicitPath, return the unmerged explicit file
  127. // Otherwise, return a merged config based on the Precedence slice
  128. // A missing ExplicitPath file produces an error. Empty filenames or other missing files are ignored.
  129. // Read errors or files with non-deserializable content produce errors.
  130. // The first file to set a particular map key wins and map key's value is never changed.
  131. // BUT, if you set a struct value that is NOT contained inside of map, the value WILL be changed.
  132. // This results in some odd looking logic to merge in one direction, merge in the other, and then merge the two.
  133. // It also means that if two files specify a "red-user", only values from the first file's red-user are used. Even
  134. // non-conflicting entries from the second file's "red-user" are discarded.
  135. // Relative paths inside of the .kubeconfig files are resolved against the .kubeconfig file's parent folder
  136. // and only absolute file paths are returned.
  137. func (rules *ClientConfigLoadingRules) Load() (*clientcmdapi.Config, error) {
  138. if err := rules.Migrate(); err != nil {
  139. return nil, err
  140. }
  141. errlist := []error{}
  142. kubeConfigFiles := []string{}
  143. // Make sure a file we were explicitly told to use exists
  144. if len(rules.ExplicitPath) > 0 {
  145. if _, err := os.Stat(rules.ExplicitPath); os.IsNotExist(err) {
  146. return nil, err
  147. }
  148. kubeConfigFiles = append(kubeConfigFiles, rules.ExplicitPath)
  149. } else {
  150. kubeConfigFiles = append(kubeConfigFiles, rules.Precedence...)
  151. }
  152. kubeconfigs := []*clientcmdapi.Config{}
  153. // read and cache the config files so that we only look at them once
  154. for _, filename := range kubeConfigFiles {
  155. if len(filename) == 0 {
  156. // no work to do
  157. continue
  158. }
  159. config, err := LoadFromFile(filename)
  160. if os.IsNotExist(err) {
  161. // skip missing files
  162. continue
  163. }
  164. if err != nil {
  165. errlist = append(errlist, fmt.Errorf("Error loading config file \"%s\": %v", filename, err))
  166. continue
  167. }
  168. kubeconfigs = append(kubeconfigs, config)
  169. }
  170. // first merge all of our maps
  171. mapConfig := clientcmdapi.NewConfig()
  172. for _, kubeconfig := range kubeconfigs {
  173. mergo.Merge(mapConfig, kubeconfig)
  174. }
  175. // merge all of the struct values in the reverse order so that priority is given correctly
  176. // errors are not added to the list the second time
  177. nonMapConfig := clientcmdapi.NewConfig()
  178. for i := len(kubeconfigs) - 1; i >= 0; i-- {
  179. kubeconfig := kubeconfigs[i]
  180. mergo.Merge(nonMapConfig, kubeconfig)
  181. }
  182. // since values are overwritten, but maps values are not, we can merge the non-map config on top of the map config and
  183. // get the values we expect.
  184. config := clientcmdapi.NewConfig()
  185. mergo.Merge(config, mapConfig)
  186. mergo.Merge(config, nonMapConfig)
  187. if rules.ResolvePaths() {
  188. if err := ResolveLocalPaths(config); err != nil {
  189. errlist = append(errlist, err)
  190. }
  191. }
  192. return config, utilerrors.NewAggregate(errlist)
  193. }
  194. // Migrate uses the MigrationRules map. If a destination file is not present, then the source file is checked.
  195. // If the source file is present, then it is copied to the destination file BEFORE any further loading happens.
  196. func (rules *ClientConfigLoadingRules) Migrate() error {
  197. if rules.MigrationRules == nil {
  198. return nil
  199. }
  200. for destination, source := range rules.MigrationRules {
  201. if _, err := os.Stat(destination); err == nil {
  202. // if the destination already exists, do nothing
  203. continue
  204. } else if os.IsPermission(err) {
  205. // if we can't access the file, skip it
  206. continue
  207. } else if !os.IsNotExist(err) {
  208. // if we had an error other than non-existence, fail
  209. return err
  210. }
  211. if sourceInfo, err := os.Stat(source); err != nil {
  212. if os.IsNotExist(err) || os.IsPermission(err) {
  213. // if the source file doesn't exist or we can't access it, there's no work to do.
  214. continue
  215. }
  216. // if we had an error other than non-existence, fail
  217. return err
  218. } else if sourceInfo.IsDir() {
  219. return fmt.Errorf("cannot migrate %v to %v because it is a directory", source, destination)
  220. }
  221. in, err := os.Open(source)
  222. if err != nil {
  223. return err
  224. }
  225. defer in.Close()
  226. out, err := os.Create(destination)
  227. if err != nil {
  228. return err
  229. }
  230. defer out.Close()
  231. if _, err = io.Copy(out, in); err != nil {
  232. return err
  233. }
  234. }
  235. return nil
  236. }
  237. // GetLoadingPrecedence implements ConfigAccess
  238. func (rules *ClientConfigLoadingRules) GetLoadingPrecedence() []string {
  239. return rules.Precedence
  240. }
  241. // GetStartingConfig implements ConfigAccess
  242. func (rules *ClientConfigLoadingRules) GetStartingConfig() (*clientcmdapi.Config, error) {
  243. clientConfig := NewNonInteractiveDeferredLoadingClientConfig(rules, &ConfigOverrides{})
  244. rawConfig, err := clientConfig.RawConfig()
  245. if os.IsNotExist(err) {
  246. return clientcmdapi.NewConfig(), nil
  247. }
  248. if err != nil {
  249. return nil, err
  250. }
  251. return &rawConfig, nil
  252. }
  253. // GetDefaultFilename implements ConfigAccess
  254. func (rules *ClientConfigLoadingRules) GetDefaultFilename() string {
  255. // Explicit file if we have one.
  256. if rules.IsExplicitFile() {
  257. return rules.GetExplicitFile()
  258. }
  259. // Otherwise, first existing file from precedence.
  260. for _, filename := range rules.GetLoadingPrecedence() {
  261. if _, err := os.Stat(filename); err == nil {
  262. return filename
  263. }
  264. }
  265. // If none exists, use the first from precedence.
  266. if len(rules.Precedence) > 0 {
  267. return rules.Precedence[0]
  268. }
  269. return ""
  270. }
  271. // IsExplicitFile implements ConfigAccess
  272. func (rules *ClientConfigLoadingRules) IsExplicitFile() bool {
  273. return len(rules.ExplicitPath) > 0
  274. }
  275. // GetExplicitFile implements ConfigAccess
  276. func (rules *ClientConfigLoadingRules) GetExplicitFile() string {
  277. return rules.ExplicitPath
  278. }
  279. // IsDefaultConfig returns true if the provided configuration matches the default
  280. func (rules *ClientConfigLoadingRules) IsDefaultConfig(config *restclient.Config) bool {
  281. if rules.DefaultClientConfig == nil {
  282. return false
  283. }
  284. defaultConfig, err := rules.DefaultClientConfig.ClientConfig()
  285. if err != nil {
  286. return false
  287. }
  288. return reflect.DeepEqual(config, defaultConfig)
  289. }
  290. // LoadFromFile takes a filename and deserializes the contents into Config object
  291. func LoadFromFile(filename string) (*clientcmdapi.Config, error) {
  292. kubeconfigBytes, err := ioutil.ReadFile(filename)
  293. if err != nil {
  294. return nil, err
  295. }
  296. config, err := Load(kubeconfigBytes)
  297. if err != nil {
  298. return nil, err
  299. }
  300. glog.V(6).Infoln("Config loaded from file", filename)
  301. // set LocationOfOrigin on every Cluster, User, and Context
  302. for key, obj := range config.AuthInfos {
  303. obj.LocationOfOrigin = filename
  304. config.AuthInfos[key] = obj
  305. }
  306. for key, obj := range config.Clusters {
  307. obj.LocationOfOrigin = filename
  308. config.Clusters[key] = obj
  309. }
  310. for key, obj := range config.Contexts {
  311. obj.LocationOfOrigin = filename
  312. config.Contexts[key] = obj
  313. }
  314. if config.AuthInfos == nil {
  315. config.AuthInfos = map[string]*clientcmdapi.AuthInfo{}
  316. }
  317. if config.Clusters == nil {
  318. config.Clusters = map[string]*clientcmdapi.Cluster{}
  319. }
  320. if config.Contexts == nil {
  321. config.Contexts = map[string]*clientcmdapi.Context{}
  322. }
  323. return config, nil
  324. }
  325. // Load takes a byte slice and deserializes the contents into Config object.
  326. // Encapsulates deserialization without assuming the source is a file.
  327. func Load(data []byte) (*clientcmdapi.Config, error) {
  328. config := clientcmdapi.NewConfig()
  329. // if there's no data in a file, return the default object instead of failing (DecodeInto reject empty input)
  330. if len(data) == 0 {
  331. return config, nil
  332. }
  333. decoded, _, err := clientcmdlatest.Codec.Decode(data, &schema.GroupVersionKind{Version: clientcmdlatest.Version, Kind: "Config"}, config)
  334. if err != nil {
  335. return nil, err
  336. }
  337. return decoded.(*clientcmdapi.Config), nil
  338. }
  339. // 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
  340. // it stomps the contents
  341. func WriteToFile(config clientcmdapi.Config, filename string) error {
  342. content, err := Write(config)
  343. if err != nil {
  344. return err
  345. }
  346. dir := filepath.Dir(filename)
  347. if _, err := os.Stat(dir); os.IsNotExist(err) {
  348. if err = os.MkdirAll(dir, 0755); err != nil {
  349. return err
  350. }
  351. }
  352. if err := ioutil.WriteFile(filename, content, 0600); err != nil {
  353. return err
  354. }
  355. return nil
  356. }
  357. func lockFile(filename string) error {
  358. // TODO: find a way to do this with actual file locks. Will
  359. // probably need seperate solution for windows and linux.
  360. // Make sure the dir exists before we try to create a lock file.
  361. dir := filepath.Dir(filename)
  362. if _, err := os.Stat(dir); os.IsNotExist(err) {
  363. if err = os.MkdirAll(dir, 0755); err != nil {
  364. return err
  365. }
  366. }
  367. f, err := os.OpenFile(lockName(filename), os.O_CREATE|os.O_EXCL, 0)
  368. if err != nil {
  369. return err
  370. }
  371. f.Close()
  372. return nil
  373. }
  374. func unlockFile(filename string) error {
  375. return os.Remove(lockName(filename))
  376. }
  377. func lockName(filename string) string {
  378. return filename + ".lock"
  379. }
  380. // Write serializes the config to yaml.
  381. // Encapsulates serialization without assuming the destination is a file.
  382. func Write(config clientcmdapi.Config) ([]byte, error) {
  383. return runtime.Encode(clientcmdlatest.Codec, &config)
  384. }
  385. func (rules ClientConfigLoadingRules) ResolvePaths() bool {
  386. return !rules.DoNotResolvePaths
  387. }
  388. // ResolveLocalPaths resolves all relative paths in the config object with respect to the stanza's LocationOfOrigin
  389. // this cannot be done directly inside of LoadFromFile because doing so there would make it impossible to load a file without
  390. // modification of its contents.
  391. func ResolveLocalPaths(config *clientcmdapi.Config) error {
  392. for _, cluster := range config.Clusters {
  393. if len(cluster.LocationOfOrigin) == 0 {
  394. continue
  395. }
  396. base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
  397. if err != nil {
  398. return fmt.Errorf("Could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
  399. }
  400. if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
  401. return err
  402. }
  403. }
  404. for _, authInfo := range config.AuthInfos {
  405. if len(authInfo.LocationOfOrigin) == 0 {
  406. continue
  407. }
  408. base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
  409. if err != nil {
  410. return fmt.Errorf("Could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
  411. }
  412. if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
  413. return err
  414. }
  415. }
  416. return nil
  417. }
  418. // RelativizeClusterLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
  419. // absolute, but any existing path will be resolved relative to LocationOfOrigin
  420. func RelativizeClusterLocalPaths(cluster *clientcmdapi.Cluster) error {
  421. if len(cluster.LocationOfOrigin) == 0 {
  422. return fmt.Errorf("no location of origin for %s", cluster.Server)
  423. }
  424. base, err := filepath.Abs(filepath.Dir(cluster.LocationOfOrigin))
  425. if err != nil {
  426. return fmt.Errorf("could not determine the absolute path of config file %s: %v", cluster.LocationOfOrigin, err)
  427. }
  428. if err := ResolvePaths(GetClusterFileReferences(cluster), base); err != nil {
  429. return err
  430. }
  431. if err := RelativizePathWithNoBacksteps(GetClusterFileReferences(cluster), base); err != nil {
  432. return err
  433. }
  434. return nil
  435. }
  436. // RelativizeAuthInfoLocalPaths first absolutizes the paths by calling ResolveLocalPaths. This assumes that any NEW path is already
  437. // absolute, but any existing path will be resolved relative to LocationOfOrigin
  438. func RelativizeAuthInfoLocalPaths(authInfo *clientcmdapi.AuthInfo) error {
  439. if len(authInfo.LocationOfOrigin) == 0 {
  440. return fmt.Errorf("no location of origin for %v", authInfo)
  441. }
  442. base, err := filepath.Abs(filepath.Dir(authInfo.LocationOfOrigin))
  443. if err != nil {
  444. return fmt.Errorf("could not determine the absolute path of config file %s: %v", authInfo.LocationOfOrigin, err)
  445. }
  446. if err := ResolvePaths(GetAuthInfoFileReferences(authInfo), base); err != nil {
  447. return err
  448. }
  449. if err := RelativizePathWithNoBacksteps(GetAuthInfoFileReferences(authInfo), base); err != nil {
  450. return err
  451. }
  452. return nil
  453. }
  454. func RelativizeConfigPaths(config *clientcmdapi.Config, base string) error {
  455. return RelativizePathWithNoBacksteps(GetConfigFileReferences(config), base)
  456. }
  457. func ResolveConfigPaths(config *clientcmdapi.Config, base string) error {
  458. return ResolvePaths(GetConfigFileReferences(config), base)
  459. }
  460. func GetConfigFileReferences(config *clientcmdapi.Config) []*string {
  461. refs := []*string{}
  462. for _, cluster := range config.Clusters {
  463. refs = append(refs, GetClusterFileReferences(cluster)...)
  464. }
  465. for _, authInfo := range config.AuthInfos {
  466. refs = append(refs, GetAuthInfoFileReferences(authInfo)...)
  467. }
  468. return refs
  469. }
  470. func GetClusterFileReferences(cluster *clientcmdapi.Cluster) []*string {
  471. return []*string{&cluster.CertificateAuthority}
  472. }
  473. func GetAuthInfoFileReferences(authInfo *clientcmdapi.AuthInfo) []*string {
  474. return []*string{&authInfo.ClientCertificate, &authInfo.ClientKey, &authInfo.TokenFile}
  475. }
  476. // ResolvePaths updates the given refs to be absolute paths, relative to the given base directory
  477. func ResolvePaths(refs []*string, base string) error {
  478. for _, ref := range refs {
  479. // Don't resolve empty paths
  480. if len(*ref) > 0 {
  481. // Don't resolve absolute paths
  482. if !filepath.IsAbs(*ref) {
  483. *ref = filepath.Join(base, *ref)
  484. }
  485. }
  486. }
  487. return nil
  488. }
  489. // RelativizePathWithNoBacksteps updates the given refs to be relative paths, relative to the given base directory as long as they do not require backsteps.
  490. // 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
  491. func RelativizePathWithNoBacksteps(refs []*string, base string) error {
  492. for _, ref := range refs {
  493. // Don't relativize empty paths
  494. if len(*ref) > 0 {
  495. rel, err := MakeRelative(*ref, base)
  496. if err != nil {
  497. return err
  498. }
  499. // if we have a backstep, don't mess with the path
  500. if strings.HasPrefix(rel, "../") {
  501. if filepath.IsAbs(*ref) {
  502. continue
  503. }
  504. return fmt.Errorf("%v requires backsteps and is not absolute", *ref)
  505. }
  506. *ref = rel
  507. }
  508. }
  509. return nil
  510. }
  511. func MakeRelative(path, base string) (string, error) {
  512. if len(path) > 0 {
  513. rel, err := filepath.Rel(base, path)
  514. if err != nil {
  515. return path, err
  516. }
  517. return rel, nil
  518. }
  519. return path, nil
  520. }