kubectl源码分析之config view

心已赠人 2023-02-21 01:56 29阅读 0赞

欢迎关注我的公众号:

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBAaHhwamF2YTE_size_8_color_FFFFFF_t_70_g_se_x_16

目前刚开始写一个月,一共写了18篇原创文章,文章目录如下:

istio多集群探秘,部署了50次多集群后我得出的结论

istio多集群链路追踪,附实操视频

istio防故障利器,你知道几个,istio新手不要读,太难!

istio业务权限控制,原来可以这么玩

istio实现非侵入压缩,微服务之间如何实现压缩

不懂envoyfilter也敢说精通istio系列-http-rbac-不要只会用AuthorizationPolicy配置权限

不懂envoyfilter也敢说精通istio系列-02-http-corsFilter-不要只会vs

不懂envoyfilter也敢说精通istio系列-03-http-csrf filter-再也不用再代码里写csrf逻辑了

不懂envoyfilter也敢说精通istio系列http-jwt_authn-不要只会RequestAuthorization

不懂envoyfilter也敢说精通istio系列-05-fault-filter-故障注入不止是vs

不懂envoyfilter也敢说精通istio系列-06-http-match-配置路由不只是vs

不懂envoyfilter也敢说精通istio系列-07-负载均衡配置不止是dr

不懂envoyfilter也敢说精通istio系列-08-连接池和断路器

不懂envoyfilter也敢说精通istio系列-09-http-route filter

不懂envoyfilter也敢说精通istio系列-network filter-redis proxy

不懂envoyfilter也敢说精通istio系列-network filter-HttpConnectionManager

不懂envoyfilter也敢说精通istio系列-ratelimit-istio ratelimit完全手册

————————————————

  1. //创建config命令
  2. func NewCmdConfig(f cmdutil.Factory, pathOptions *clientcmd.PathOptions, streams genericclioptions.IOStreams) *cobra.Command {
  3. if len(pathOptions.ExplicitFileFlag) == 0 {//设置kubeconfig选项名称
  4. pathOptions.ExplicitFileFlag = clientcmd.RecommendedConfigPathFlag
  5. }
  6. cmd := &cobra.Command{//创建cobra命令
  7. Use: "config SUBCOMMAND",
  8. DisableFlagsInUseLine: true,
  9. Short: i18n.T("Modify kubeconfig files"),
  10. Long: templates.LongDesc(`
  11. Modify kubeconfig files using subcommands like "kubectl config set current-context my-context"
  12. The loading order follows these rules:
  13. 1. If the --` + pathOptions.ExplicitFileFlag + ` flag is set, then only that file is loaded. The flag may only be set once and no merging takes place.
  14. 2. If $` + pathOptions.EnvVar + ` environment variable is set, then it is used as a list of paths (normal path delimiting rules for your system). These paths are merged. When a value is modified, it is modified in the file that defines the stanza. When a value is created, it is created in the first file that exists. If no files in the chain exist, then it creates the last file in the list.
  15. 3. Otherwise, ` + path.Join("${HOME}", pathOptions.GlobalFileSubpath) + ` is used and no merging takes place.`),
  16. Run: cmdutil.DefaultSubCommandRun(streams.ErrOut),
  17. }
  18. // file paths are common to all sub commands
  19. cmd.PersistentFlags().StringVar(&pathOptions.LoadingRules.ExplicitPath, pathOptions.ExplicitFileFlag, pathOptions.LoadingRules.ExplicitPath, "use a particular kubeconfig file")//kubeconfig选项
  20. // TODO(juanvallejo): update all subcommands to work with genericclioptions.IOStreams
  21. cmd.AddCommand(NewCmdConfigView(f, streams, pathOptions))//添加view子命令
  22. cmd.AddCommand(NewCmdConfigSetCluster(streams.Out, pathOptions))//set-cluster子命令
  23. cmd.AddCommand(NewCmdConfigSetAuthInfo(streams.Out, pathOptions))//setauthinfo子命令
  24. cmd.AddCommand(NewCmdConfigSetContext(streams.Out, pathOptions))//set-context子命令
  25. cmd.AddCommand(NewCmdConfigSet(streams.Out, pathOptions))//set子命令
  26. cmd.AddCommand(NewCmdConfigUnset(streams.Out, pathOptions))//unset子命令
  27. cmd.AddCommand(NewCmdConfigCurrentContext(streams.Out, pathOptions))//current-context子命令
  28. cmd.AddCommand(NewCmdConfigUseContext(streams.Out, pathOptions))//use-context子命令
  29. cmd.AddCommand(NewCmdConfigGetContexts(streams, pathOptions))//get-context子命令
  30. cmd.AddCommand(NewCmdConfigGetClusters(streams.Out, pathOptions))//get-cluster子命令
  31. cmd.AddCommand(NewCmdConfigDeleteCluster(streams.Out, pathOptions))//delete-cluster子命令
  32. cmd.AddCommand(NewCmdConfigDeleteContext(streams.Out, streams.ErrOut, pathOptions))//delete-context子命令
  33. cmd.AddCommand(NewCmdConfigRenameContext(streams.Out, pathOptions))//rename-context子命令
  34. return cmd
  35. }
  36. type ViewOptions struct {//view结构体
  37. PrintFlags *genericclioptions.PrintFlags
  38. PrintObject printers.ResourcePrinterFunc
  39. ConfigAccess clientcmd.ConfigAccess
  40. Merge cliflag.Tristate
  41. Flatten bool
  42. Minify bool
  43. RawByteData bool
  44. Context string
  45. OutputFormat string
  46. genericclioptions.IOStreams
  47. }
  48. //创建config命令
  49. func NewCmdConfigView(f cmdutil.Factory, streams genericclioptions.IOStreams, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {
  50. o := &ViewOptions{//初始化结构体
  51. PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme).WithDefaultOutput("yaml"),
  52. ConfigAccess: ConfigAccess,
  53. IOStreams: streams,
  54. }
  55. cmd := &cobra.Command{//创建cobra命令
  56. Use: "view",
  57. Short: i18n.T("Display merged kubeconfig settings or a specified kubeconfig file"),
  58. Long: viewLong,
  59. Example: viewExample,
  60. Run: func(cmd *cobra.Command, args []string) {
  61. cmdutil.CheckErr(o.Complete(cmd, args))//准备
  62. cmdutil.CheckErr(o.Validate())//校验
  63. cmdutil.CheckErr(o.Run())//运行
  64. },
  65. }
  66. o.PrintFlags.AddFlags(cmd)//打印选项
  67. o.Merge.Default(true)//merge默认值
  68. mergeFlag := cmd.Flags().VarPF(&o.Merge, "merge", "", "Merge the full hierarchy of kubeconfig files")//merge选项
  69. mergeFlag.NoOptDefVal = "true"
  70. cmd.Flags().BoolVar(&o.RawByteData, "raw", o.RawByteData, "Display raw byte data")//raw选项
  71. cmd.Flags().BoolVar(&o.Flatten, "flatten", o.Flatten, "Flatten the resulting kubeconfig file into self-contained output (useful for creating portable kubeconfig files)")//flatten选项
  72. cmd.Flags().BoolVar(&o.Minify, "minify", o.Minify, "Remove all information not used by current-context from the output")//minify选项
  73. return cmd
  74. }
  75. //准备
  76. func (o *ViewOptions) Complete(cmd *cobra.Command, args []string) error {
  77. if len(args) != 0 {//参数必须是0个
  78. return cmdutil.UsageErrorf(cmd, "unexpected arguments: %v", args)
  79. }
  80. if o.ConfigAccess.IsExplicitFile() {//如果指定了kubeconfig选项
  81. if !o.Merge.Provided() {//如果merge没设置,设置为false
  82. o.Merge.Set("false")
  83. }
  84. }
  85. printer, err := o.PrintFlags.ToPrinter()//print flag转printer
  86. if err != nil {
  87. return err
  88. }
  89. o.PrintObject = printer.PrintObj//设置printObject函数
  90. o.Context = cmdutil.GetFlagString(cmd, "context")//设置context
  91. return nil
  92. }
  93. func (o ViewOptions) Validate() error {//校验
  94. if !o.Merge.Value() && !o.ConfigAccess.IsExplicitFile() {//如果merge为false,必须指定kubeconfig选项
  95. return errors.New("if merge==false a precise file must to specified")
  96. }
  97. return nil
  98. }
  99. //运行
  100. func (o ViewOptions) Run() error {
  101. config, err := o.loadConfig()//加载config
  102. if err != nil {
  103. return err
  104. }
  105. if o.Minify {//如果指定了minify
  106. if len(o.Context) > 0 {//如果指定了context
  107. config.CurrentContext = o.Context//设置config context
  108. }
  109. if err := clientcmdapi.MinifyConfig(config); err != nil {//修剪config
  110. return err
  111. }
  112. }
  113. if o.Flatten {// 如果指定了flattern
  114. if err := clientcmdapi.FlattenConfig(config); err != nil {//flatten config
  115. return err
  116. }
  117. } else if !o.RawByteData {//如果没指定raw
  118. clientcmdapi.ShortenConfig(config)//shorten config
  119. }
  120. convertedObj, err := latest.Scheme.ConvertToVersion(config, latest.ExternalVersion)//转换config版本
  121. if err != nil {
  122. return err
  123. }
  124. return o.PrintObject(convertedObj, o.Out)//打印
  125. }
  126. func (o ViewOptions) loadConfig() (*clientcmdapi.Config, error) {//加载config
  127. err := o.Validate()//校验
  128. if err != nil {
  129. return nil, err
  130. }
  131. config, err := o.getStartingConfig()//获取config
  132. return config, err
  133. }
  134. // getStartingConfig returns the Config object built from the sources specified by the options, the filename read (only if it was a single file), and an error if something goes wrong
  135. func (o *ViewOptions) getStartingConfig() (*clientcmdapi.Config, error) {
  136. switch {
  137. case !o.Merge.Value():// 如果merge为false
  138. return clientcmd.LoadFromFile(o.ConfigAccess.GetExplicitFile())//从文件加载
  139. default:
  140. return o.ConfigAccess.GetStartingConfig()//从configAccess加载
  141. }
  142. }
  143. func MinifyConfig(config *Config) error {//修剪config
  144. if len(config.CurrentContext) == 0 {//如果没有currentContext报错
  145. return errors.New("current-context must exist in order to minify")
  146. }
  147. currContext, exists := config.Contexts[config.CurrentContext]//获取currentContext
  148. if !exists {
  149. return fmt.Errorf("cannot locate context %v", config.CurrentContext)
  150. }
  151. newContexts := map[string]*Context{}
  152. newContexts[config.CurrentContext] = currContext//设置新的context
  153. newClusters := map[string]*Cluster{}//clustermap
  154. if len(currContext.Cluster) > 0 {//如果currentContext的cluster有值
  155. if _, exists := config.Clusters[currContext.Cluster]; !exists {//获取当前cluster
  156. return fmt.Errorf("cannot locate cluster %v", currContext.Cluster)
  157. }
  158. newClusters[currContext.Cluster] = config.Clusters[currContext.Cluster]//把cluster设置到newCluster里
  159. }
  160. newAuthInfos := map[string]*AuthInfo{}//newAuthinfos map
  161. if len(currContext.AuthInfo) > 0 {//如果当前contenxt有授权信息
  162. if _, exists := config.AuthInfos[currContext.AuthInfo]; !exists {//判断授权信息是否存在
  163. return fmt.Errorf("cannot locate user %v", currContext.AuthInfo)
  164. }
  165. newAuthInfos[currContext.AuthInfo] = config.AuthInfos[currContext.AuthInfo]//设置newAuthInfos
  166. }
  167. config.AuthInfos = newAuthInfos//设置config当前上下文的信息
  168. config.Clusters = newClusters
  169. config.Contexts = newContexts
  170. return nil
  171. }
  172. func FlattenConfig(config *Config) error {//flatten config
  173. for key, authInfo := range config.AuthInfos {//遍历授权信息
  174. baseDir, err := MakeAbs(path.Dir(authInfo.LocationOfOrigin), "")//获取授权信息秘钥基路径
  175. if err != nil {
  176. return err
  177. }
  178. if err := FlattenContent(&authInfo.ClientCertificate, &authInfo.ClientCertificateData, baseDir); err != nil {//从文件读取ClientCertificate信息,赋值给ClientCertificateData
  179. return err
  180. }
  181. if err := FlattenContent(&authInfo.ClientKey, &authInfo.ClientKeyData, baseDir); err != nil {//从文件读取ClientKey信息赋值给ClientKeyData
  182. return err
  183. }
  184. config.AuthInfos[key] = authInfo//设置授权信息
  185. }
  186. for key, cluster := range config.Clusters {//遍历clusters
  187. baseDir, err := MakeAbs(path.Dir(cluster.LocationOfOrigin), "")//获取cluster秘钥信息基路径
  188. if err != nil {
  189. return err
  190. }
  191. if err := FlattenContent(&cluster.CertificateAuthority, &cluster.CertificateAuthorityData, baseDir); err != nil {//从文件读取CertificateAuthority,赋值给CertificateAuthorityData
  192. return err
  193. }
  194. config.Clusters[key] = cluster//设置cluster
  195. }
  196. return nil
  197. }
  198. func ShortenConfig(config *Config) {//简化config
  199. // trick json encoder into printing a human readable string in the raw data
  200. // by base64 decoding what we want to print. Relies on implementation of
  201. // http://golang.org/pkg/encoding/json/#Marshal using base64 to encode []byte
  202. for key, authInfo := range config.AuthInfos {//遍历授权信息
  203. if len(authInfo.ClientKeyData) > 0 {
  204. authInfo.ClientKeyData = redactedBytes//设置ClientKeyData
  205. }
  206. if len(authInfo.ClientCertificateData) > 0 {
  207. authInfo.ClientCertificateData = redactedBytes//设置ClientCertificateData
  208. }
  209. config.AuthInfos[key] = authInfo//设置授权信息
  210. }
  211. for key, cluster := range config.Clusters {
  212. if len(cluster.CertificateAuthorityData) > 0 {
  213. cluster.CertificateAuthorityData = dataOmittedBytes//设置CertificateAuthorityData
  214. }
  215. config.Clusters[key] = cluster//设置cluster
  216. }
  217. }

发表评论

表情:
评论列表 (有 0 条评论,29人围观)

还没有评论,来说两句吧...

相关阅读