0
点赞
收藏
分享

微信扫一扫

kubectl源码分析之cp


 欢迎关注我的公众号:

kubectl源码分析之cp_名称空间

 目前刚开始写一个月,一共写了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完全手册​​

 

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

type CopyOptions struct {//cp结构体
Container string
Namespace string
NoPreserve bool

ClientConfig *restclient.Config
Clientset kubernetes.Interface
ExecParentCmdName string

genericclioptions.IOStreams
}

func NewCopyOptions(ioStreams genericclioptions.IOStreams) *CopyOptions {
return &CopyOptions{//初始化结构体
IOStreams: ioStreams,
}
}

//创建cp命令
func NewCmdCp(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewCopyOptions(ioStreams)//初始化结构体

cmd := &cobra.Command{//创建cobra命令
Use: "cp <file-spec-src> <file-spec-dest>",
DisableFlagsInUseLine: true,
Short: i18n.T("Copy files and directories to and from containers."),
Long: "Copy files and directories to and from containers.",
Example: cpExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd))//准备
cmdutil.CheckErr(o.Run(args))//运行
},
}
cmd.Flags().StringVarP(&o.Container, "container", "c", o.Container, "Container name. If omitted, the first container in the pod will be chosen")//容器选项
cmd.Flags().BoolVarP(&o.NoPreserve, "no-preserve", "", false, "The copied file/directory's ownership and permissions will not be preserved in the container")//no-preserve选项

return cmd
}

type fileSpec struct {//文件结构体
PodNamespace string
PodName string
File string
}

//准备函数
func (o *CopyOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
if cmd.Parent() != nil {//设置父命令名称
o.ExecParentCmdName = cmd.Parent().CommandPath()
}

var err error
o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()//设置名称空间
if err != nil {
return err
}

o.Clientset, err = f.KubernetesClientSet()//设置Clientset
if err != nil {
return err
}

o.ClientConfig, err = f.ToRESTConfig()//设置restconfig
if err != nil {
return err
}
return nil
}

// Validate makes sure provided values for CopyOptions are valid
//校验
func (o *CopyOptions) Validate(cmd *cobra.Command, args []string) error {
if len(args) != 2 {//参数必须是两个
return cmdutil.UsageErrorf(cmd, cpUsageStr)
}
return nil
}

//运行
func (o *CopyOptions) Run(args []string) error {
if len(args) < 2 {//参数小于2个报错
return fmt.Errorf("source and destination are required")
}
srcSpec, err := extractFileSpec(args[0])//从参数抽取源文件规范
if err != nil {
return err
}
destSpec, err := extractFileSpec(args[1])//从arg抽取目标文件规范
if err != nil {
return err
}

if len(srcSpec.PodName) != 0 && len(destSpec.PodName) != 0 {//源pod和目标pod都不为空
if _, err := os.Stat(args[0]); err == nil {//参数0,文件存在
return o.copyToPod(fileSpec{File: args[0]}, destSpec, &exec.ExecOptions{})//拷贝到pod
}
return fmt.Errorf("src doesn't exist in local filesystem")//报错
}

if len(srcSpec.PodName) != 0 {//源pod不额外空
return o.copyFromPod(srcSpec, destSpec)//从pod拷贝到本地
}
if len(destSpec.PodName) != 0 {//目标pod不为空
return o.copyToPod(srcSpec, destSpec, &exec.ExecOptions{})//从本地拷贝到目标
}
return fmt.Errorf("one of src or dest must be a remote file specification")//报错
}

func extractFileSpec(arg string) (fileSpec, error) {//抽取文件规范
if i := strings.Index(arg, ":"); i == -1 {//没有冒号
return fileSpec{File: arg}, nil
} else if i > 0 {
file := arg[i+1:]
pod := arg[:i]
pieces := strings.Split(pod, "/")//用/分割,
if len(pieces) == 1 {//分割后为1个,指定pod名称
return fileSpec{
PodName: pieces[0],
File: file,
}, nil
}
if len(pieces) == 2 {//分割后参数为2个,指定名称空间和pod名称
return fileSpec{
PodNamespace: pieces[0],
PodName: pieces[1],
File: file,
}, nil
}
}

return fileSpec{}, errFileSpecDoesntMatchFormat
}

//拷贝到pod
func (o *CopyOptions) copyToPod(src, dest fileSpec, options *exec.ExecOptions) error {
if len(src.File) == 0 || len(dest.File) == 0 {// 文件名为空报错
return errFileCannotBeEmpty
}
reader, writer := io.Pipe()//创建管道

// strip trailing slash (if any)
if dest.File != "/" && strings.HasSuffix(string(dest.File[len(dest.File)-1]), "/") {//目标文件不为/,并且目标文件有/结尾
dest.File = dest.File[:len(dest.File)-1]//去掉目标文件末尾/
}

if err := o.checkDestinationIsDir(dest); err == nil {//如果目标是目录
// If no error, dest.File was found to be a directory.
// Copy specified src into it
dest.File = dest.File + "/" + path.Base(src.File)//目标文件为目标加源文件
}

go func() {
defer writer.Close()
err := makeTar(src.File, dest.File, writer)//创建tar文件
cmdutil.CheckErr(err)
}()
var cmdArr []string

// TODO: Improve error messages by first testing if 'tar' is present in the container?
if o.NoPreserve {//如果指定no-preserve
cmdArr = []string{"tar", "--no-same-permissions", "--no-same-owner", "-xmf", "-"}//构造命令行
} else {
cmdArr = []string{"tar", "-xmf", "-"}
}
destDir := path.Dir(dest.File)//获取目标文件目录
if len(destDir) > 0 {//如果目标文件目录有值
cmdArr = append(cmdArr, "-C", destDir)//追加命令
}

options.StreamOptions = exec.StreamOptions{//构造流选项
IOStreams: genericclioptions.IOStreams{
In: reader,
Out: o.Out,
ErrOut: o.ErrOut,
},
Stdin: true,

Namespace: dest.PodNamespace,
PodName: dest.PodName,
}

options.Command = cmdArr
options.Executor = &exec.DefaultRemoteExecutor{}
return o.execute(options)//执行拷贝
}

// 执行拷贝
func (o *CopyOptions) execute(options *exec.ExecOptions) error {
if len(options.Namespace) == 0 {//如果名称空间为空,用o的名称空间
options.Namespace = o.Namespace
}

if len(o.Container) > 0 {//如果container不为空,设置container
options.ContainerName = o.Container
}

options.Config = o.ClientConfig//设置restconfig
options.PodClient = o.Clientset.CoreV1()//设置podclient

if err := options.Validate(); err != nil {//执行校验
return err
}

if err := options.Run(); err != nil {//运行拷贝
return err
}
return nil
}

//创建tar文件
func makeTar(srcPath, destPath string, writer io.Writer) error {
// TODO: use compression here?
tarWriter := tar.NewWriter(writer)//包装writer
defer tarWriter.Close()

srcPath = path.Clean(srcPath)//源路径
destPath = path.Clean(destPath)//目标路径
return recursiveTar(path.Dir(srcPath), path.Base(srcPath), path.Dir(destPath), path.Base(destPath), tarWriter)//递归创建tar
}

//从pod拷贝到本地
func (o *CopyOptions) copyFromPod(src, dest fileSpec) error {
if len(src.File) == 0 || len(dest.File) == 0 {//源文件和目标文件不能为空
return errFileCannotBeEmpty
}

reader, outStream := io.Pipe()//创建pipe
options := &exec.ExecOptions{//构造exec选项
StreamOptions: exec.StreamOptions{
IOStreams: genericclioptions.IOStreams{
In: nil,
Out: outStream,
ErrOut: o.Out,
},

Namespace: src.PodNamespace,
PodName: src.PodName,
},

// TODO: Improve error messages by first testing if 'tar' is present in the container?
Command: []string{"tar", "cf", "-", src.File},
Executor: &exec.DefaultRemoteExecutor{},
}

go func() {
defer outStream.Close()
err := o.execute(options)//执行拷贝
cmdutil.CheckErr(err)
}()
prefix := getPrefix(src.File)//获取prefix
prefix = path.Clean(prefix)
// remove extraneous path shortcuts - these could occur if a path contained extra "../"
// and attempted to navigate beyond "/" in a remote filesystem
prefix = stripPathShortcuts(prefix)//修剪prefix
return o.untarAll(src, reader, dest.File, prefix)//执行解压缩
}

举报

相关推荐

0 条评论