* The Fetch module retrieves files from remote hosts to the local machine. This module allows users to download files from remote hosts to specified local destinations. Configuration: Users can specify the source and destination paths: fetch: src: /remote/path/file # required: source file pat
(ctx context.Context, opts internal.ExecOptions)
| 65 | |
| 66 | // ModuleFetch handles the "fetch" module, retrieving files from remote hosts |
| 67 | func ModuleFetch(ctx context.Context, opts internal.ExecOptions) (string, string, error) { |
| 68 | // get host variable |
| 69 | ha, err := opts.GetAllVariables() |
| 70 | if err != nil { |
| 71 | return internal.StdoutFailed, internal.StderrGetHostVariable, err |
| 72 | } |
| 73 | // check args |
| 74 | args := variable.Extension2Variables(opts.Args) |
| 75 | srcParam, err := variable.StringVar(ha, args, "src") |
| 76 | if err != nil { |
| 77 | return internal.StdoutFailed, "\"src\" in args should be string", err |
| 78 | } |
| 79 | destParam, err := variable.StringVar(ha, args, "dest") |
| 80 | if err != nil { |
| 81 | return internal.StdoutFailed, "\"dest\" in args should be string", err |
| 82 | } |
| 83 | tmpDir, err := variable.StringVar(ha, ha, "tmp_dir") |
| 84 | if err != nil || tmpDir == "" { |
| 85 | tmpDir = "/tmp/kubekey/" |
| 86 | } |
| 87 | |
| 88 | // get connector |
| 89 | conn, err := opts.GetConnector(ctx) |
| 90 | if err != nil { |
| 91 | return internal.StdoutFailed, internal.StderrGetConnector, err |
| 92 | } |
| 93 | defer conn.Close(ctx) |
| 94 | |
| 95 | // fetch file |
| 96 | if _, err := os.Stat(filepath.Dir(destParam)); os.IsNotExist(err) { |
| 97 | if err := os.MkdirAll(filepath.Dir(destParam), os.ModePerm); err != nil { |
| 98 | return internal.StdoutFailed, "failed to create dest dir", err |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | destFile, err := os.Create(destParam) |
| 103 | if err != nil { |
| 104 | return internal.StdoutFailed, "failed to create dest file", err |
| 105 | } |
| 106 | defer destFile.Close() |
| 107 | |
| 108 | tmpFetchFileName := filepath.Join(tmpDir, fmt.Sprintf("fetch-%s-%s", opts.Task.GetUID(), rand.String(5))) |
| 109 | |
| 110 | _, _, err = conn.ExecuteCommand(ctx, fmt.Sprintf("cp %s %s\nchmod 755 %s", srcParam, tmpFetchFileName, tmpFetchFileName)) |
| 111 | |
| 112 | if err != nil { |
| 113 | return internal.StdoutFailed, "failed to fetch file", err |
| 114 | } |
| 115 | |
| 116 | if err = conn.FetchFile(ctx, tmpFetchFileName, destFile); err != nil { |
| 117 | return internal.StdoutFailed, "failed to fetch file", err |
| 118 | } |
| 119 | |
| 120 | return internal.StdoutSuccess, "", nil |
| 121 | } |