forked from kubernetes/kops
/
sshfs.go
363 lines (315 loc) · 7.99 KB
/
sshfs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package vfs
import (
"bytes"
"fmt"
"github.com/golang/glog"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"math/rand"
"os"
"path"
"sync"
)
type SSHPath struct {
client *ssh.Client
sudo bool
server string
path string
}
var _ Path = &SSHPath{}
func NewSSHPath(client *ssh.Client, server string, path string, sudo bool) *SSHPath {
return &SSHPath{
client: client,
server: server,
path: path,
sudo: sudo,
}
}
func (p *SSHPath) newClient() (*sftp.Client, error) {
if !p.sudo {
sftpClient, err := sftp.NewClient(p.client)
if err != nil {
return nil, fmt.Errorf("error creating sftp client: %v", err)
}
return sftpClient, nil
} else {
s, err := p.client.NewSession()
if err != nil {
return nil, fmt.Errorf("error creating sftp client (in new-session): %v", err)
}
//if err := s.R("sftp"); err != nil {
// return nil, fmt.Errorf("error creating sftp client (in new-session): %v", err)
//}
stdin, err := s.StdinPipe()
if err != nil {
return nil, fmt.Errorf("error creating sftp client (at stdin pipe): %v", err)
}
stdout, err := s.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("error creating sftp client (at stdout pipe): %v", err)
}
err = s.Start("sudo /usr/lib/openssh/sftp-server")
if err != nil {
return nil, fmt.Errorf("error creating sftp client (executing 'sudo /usr/lib/openssh/sftp-server'): %v", err)
}
return sftp.NewClientPipe(stdout, stdin)
}
}
func (p *SSHPath) Path() string {
return "ssh://" + p.server + p.path
}
func (p *SSHPath) String() string {
return p.Path()
}
func (p *SSHPath) Remove() error {
sftpClient, err := p.newClient()
if err != nil {
return err
}
defer sftpClient.Close()
err = sftpClient.Remove(p.path)
if err != nil {
if os.IsNotExist(err) {
return err
}
return fmt.Errorf("error deleting %s: %v", p, err)
}
return nil
}
func (p *SSHPath) Join(relativePath ...string) Path {
args := []string{p.path}
args = append(args, relativePath...)
joined := path.Join(args...)
return NewSSHPath(p.client, p.server, joined, p.sudo)
}
func mkdirAll(sftpClient *sftp.Client, dir string) error {
if dir == "/" {
// Must always exist
return nil
}
stat, err := sftpClient.Lstat(dir)
if err == nil {
if !stat.IsDir() {
return fmt.Errorf("not a directory: %q", dir)
}
return nil
}
parent := path.Dir(dir)
err = mkdirAll(sftpClient, parent)
if err != nil {
return err
}
err = sftpClient.Mkdir(dir)
if err != nil {
return fmt.Errorf("error creating directory %q over sftp: %v", dir, err)
}
return nil
}
func (p *SSHPath) WriteFile(data []byte) error {
sftpClient, err := p.newClient()
if err != nil {
return err
}
defer sftpClient.Close()
dir := path.Dir(p.path)
err = mkdirAll(sftpClient, dir)
if err != nil {
return err
}
tempfile := path.Join(dir, fmt.Sprintf(".tmp-%d", rand.Int63()))
f, err := sftpClient.Create(tempfile)
if err != nil {
// TODO: Retry if concurrently created?
return fmt.Errorf("error creating temp file in %q: %v", dir, err)
}
// Note from here on in we have to close f and delete or rename the temp file
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if closeErr := f.Close(); err == nil {
err = closeErr
}
if err == nil {
err = sftpClient.Rename(tempfile, p.path)
if err != nil {
err = fmt.Errorf("error during file write of %q: rename failed: %v", p.path, err)
}
}
if err == nil {
return nil
}
// Something went wrong; try to remove the temp file
if removeErr := sftpClient.Remove(tempfile); removeErr != nil {
glog.Warningf("unable to remove temp file %q: %v", tempfile, removeErr)
}
return err
}
// To prevent concurrent creates on the same file while maintaining atomicity of writes,
// we take a process-wide lock during the operation.
// Not a great approach, but fine for a single process (with low concurrency)
var createFileLockSSH sync.Mutex
func (p *SSHPath) CreateFile(data []byte) error {
createFileLockSSH.Lock()
defer createFileLockSSH.Unlock()
// Check if exists
_, err := p.ReadFile()
if err == nil {
return os.ErrExist
}
if !os.IsNotExist(err) {
return err
}
return p.WriteFile(data)
}
func (p *SSHPath) ReadFile() ([]byte, error) {
sftpClient, err := p.newClient()
if err != nil {
return nil, err
}
defer sftpClient.Close()
f, err := sftpClient.Open(p.path)
if err != nil {
return nil, fmt.Errorf("error opening file %s over sftp: %v", p, err)
}
defer f.Close()
var b bytes.Buffer
_, err = f.WriteTo(&b)
if err != nil {
return nil, fmt.Errorf("error reading file %s over sftp: %v", p, err)
}
return b.Bytes(), nil
}
func (p *SSHPath) ReadDir() ([]Path, error) {
sftpClient, err := p.newClient()
if err != nil {
return nil, err
}
defer sftpClient.Close()
files, err := sftpClient.ReadDir(p.path)
if err != nil {
return nil, err
}
var children []Path
for _, f := range files {
child := NewSSHPath(p.client, p.server, path.Join(p.path, f.Name()), p.sudo)
children = append(children, child)
}
return children, nil
}
func (p *SSHPath) ReadTree() ([]Path, error) {
sftpClient, err := p.newClient()
if err != nil {
return nil, err
}
defer sftpClient.Close()
var paths []Path
err = readSFTPTree(sftpClient, p, &paths)
if err != nil {
return nil, err
}
return paths, nil
}
func readSFTPTree(sftpClient *sftp.Client, p *SSHPath, dest *[]Path) error {
files, err := sftpClient.ReadDir(p.path)
if err != nil {
return err
}
for _, f := range files {
child := NewSSHPath(p.client, p.server, path.Join(p.path, f.Name()), p.sudo)
*dest = append(*dest, child)
if f.IsDir() {
err = readSFTPTree(sftpClient, child, dest)
if err != nil {
return err
}
}
}
return nil
}
func (p *SSHPath) Base() string {
return path.Base(p.path)
}
//
//// scpMkdir executes a mkdir against the SSH target, using SCP
//func (s *SSHPath) scpMkdir(dest string, mode os.FileMode) error {
// glog.V(4).Infof("Doing SSH SCP mkdir: %q", dest)
// session, err := s.client.NewSession()
// if err != nil {
// return fmt.Errorf("error establishing SSH session: %v", err)
// }
// defer session.Close()
//
// name := path.Base(dest)
// scpBase := path.Dir(dest)
// //scpBase = "." + scpBase
//
// var stdinErr error
// go func() {
// w, _ := session.StdinPipe()
// defer w.Close()
// _, stdinErr = fmt.Fprintln(w, "D0"+toOctal(mode), 0, name)
// if stdinErr != nil {
// return
// }
// }()
// output, err := session.CombinedOutput("/usr/bin/scp -tr " + scpBase)
// if err != nil {
// glog.Warningf("Error output from SCP: %s", output)
// return fmt.Errorf("error doing SCP mkdir: %v", err)
// }
// if stdinErr != nil {
// glog.Warningf("Error output from SCP: %s", output)
// return fmt.Errorf("error doing SCP mkdir (writing to stdin): %v", stdinErr)
// }
//
// return nil
//}
//
//func toOctal(mode os.FileMode) string {
// return strconv.FormatUint(uint64(mode), 8)
//}
//
//// scpPut copies a file to the SSH target, using SCP
//func (s *SSHPath) scpPut(dest string, length int, content io.Reader, mode os.FileMode) error {
// glog.V(4).Infof("Doing SSH SCP upload: %q", dest)
// session, err := s.client.NewSession()
// if err != nil {
// return fmt.Errorf("error establishing SSH session: %v", err)
// }
// defer session.Close()
//
// name := path.Base(dest)
// scpBase := path.Dir(dest)
// //scpBase = "." + scpBase
//
// var stdinErr error
// go func() {
// w, _ := session.StdinPipe()
// defer w.Close()
// _, stdinErr = fmt.Fprintln(w, "C0"+toOctal(mode), length, name)
// if stdinErr != nil {
// return
// }
// _, stdinErr = io.Copy(w, content)
// if stdinErr != nil {
// return
// }
// _, stdinErr = fmt.Fprint(w, "\x00")
// if stdinErr != nil {
// return
// }
// }()
// output, err := session.CombinedOutput("/usr/bin/scp -tr " + scpBase)
// if err != nil {
// glog.Warningf("Error output from SCP: %s", output)
// return fmt.Errorf("error doing SCP put: %v", err)
// }
// if stdinErr != nil {
// glog.Warningf("Error output from SCP: %s", output)
// return fmt.Errorf("error doing SCP put (writing to stdin): %v", stdinErr)
// }
//
// return nil
//}