-
Notifications
You must be signed in to change notification settings - Fork 44
/
sftp.go
282 lines (260 loc) · 6.95 KB
/
sftp.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
package desync
import (
"bytes"
"context"
"io"
"io/ioutil"
"math/rand"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"path"
"github.com/pkg/errors"
"github.com/pkg/sftp"
)
var _ WriteStore = &SFTPStore{}
// SFTPStoreBase is the base object for SFTP chunk and index stores.
type SFTPStoreBase struct {
location *url.URL
path string
client *sftp.Client
cancel context.CancelFunc
opt StoreOptions
}
// SFTPStore is a chunk store that uses SFTP over SSH.
type SFTPStore struct {
pool chan *SFTPStoreBase
location *url.URL
n int
converters Converters
}
// Creates a base sftp client
func newSFTPStoreBase(location *url.URL, opt StoreOptions) (*SFTPStoreBase, error) {
sshCmd := os.Getenv("CASYNC_SSH_PATH")
if sshCmd == "" {
sshCmd = "ssh"
}
host := location.Host
path := location.Path
if !strings.HasSuffix(path, "/") {
path += "/"
}
// If a username was given in the URL, prefix the host
if location.User != nil {
host = location.User.Username() + "@" + location.Host
}
ctx, cancel := context.WithCancel(context.Background())
c := exec.CommandContext(ctx, sshCmd, host, "-s", "sftp")
c.Stderr = os.Stderr
r, err := c.StdoutPipe()
if err != nil {
cancel()
return nil, err
}
w, err := c.StdinPipe()
if err != nil {
cancel()
return nil, err
}
if err = c.Start(); err != nil {
cancel()
return nil, err
}
client, err := sftp.NewClientPipe(r, w)
if err != nil {
cancel()
return nil, err
}
// The stat has really two jobs. Confirm that the path actually exists on the
// server, and also make sure the handshake has happened successfully. SSH
// may fail if multiple instances access the SSH agent concurrently.
if _, err = client.Stat(path); err != nil {
cancel()
return nil, errors.Wrapf(err, "failed to stat '%s'", path)
}
return &SFTPStoreBase{location, path, client, cancel, opt}, nil
}
// StoreObject adds a new object to a writable index or chunk store.
func (s *SFTPStoreBase) StoreObject(name string, r io.Reader) error {
// Write to a tempfile on the remote server. This is not 100% guaranteed to not
// conflict between gorouties, there's no tempfile() function for remote servers.
// Use a large enough random number instead to build a tempfile
tmpfile := name + strconv.Itoa(rand.Int())
d := path.Dir(name)
var errCount int
retry:
f, err := s.client.Create(tmpfile)
if err != nil {
// It's possible the parent dir doesn't yet exist. Create it while ignoring
// errors since that could be racy and fail if another goroutine does the
// same.
if errCount < 1 {
s.client.Mkdir(d)
errCount++
goto retry
}
return errors.Wrap(err, "sftp:create "+tmpfile)
}
if _, err := io.Copy(f, r); err != nil {
s.client.Remove(tmpfile)
return errors.Wrap(err, "sftp:copying chunk data to "+tmpfile)
}
if err = f.Close(); err != nil {
return errors.Wrap(err, "sftp:closing "+tmpfile)
}
return errors.Wrap(s.client.PosixRename(tmpfile, name), "sftp:renaming "+tmpfile+" to "+name)
}
// Close terminates all client connections
func (s *SFTPStoreBase) Close() error {
if s.cancel != nil {
defer s.cancel()
}
return s.client.Close()
}
func (s *SFTPStoreBase) String() string {
return s.location.String()
}
// Returns the path for a chunk
func (s *SFTPStoreBase) nameFromID(id ChunkID) string {
sID := id.String()
name := s.path + sID[0:4] + "/" + sID
if s.opt.Uncompressed {
name += UncompressedChunkExt
} else {
name += CompressedChunkExt
}
return name
}
// NewSFTPStore initializes a chunk store using SFTP over SSH.
func NewSFTPStore(location *url.URL, opt StoreOptions) (*SFTPStore, error) {
s := &SFTPStore{make(chan *SFTPStoreBase, opt.N), location, opt.N, opt.converters()}
for i := 0; i < opt.N; i++ {
c, err := newSFTPStoreBase(location, opt)
if err != nil {
return nil, err
}
s.pool <- c
}
return s, nil
}
// GetChunk returns a chunk from an SFTP store, returns ChunkMissing if the file does not exist
func (s *SFTPStore) GetChunk(id ChunkID) (*Chunk, error) {
c := <-s.pool
defer func() { s.pool <- c }()
name := c.nameFromID(id)
f, err := c.client.Open(name)
if err != nil {
if os.IsNotExist(err) {
err = ChunkMissing{id}
}
return nil, err
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Wrapf(err, "unable to read from %s", name)
}
return NewChunkFromStorage(id, b, s.converters, c.opt.SkipVerify)
}
// RemoveChunk deletes a chunk, typically an invalid one, from the filesystem.
// Used when verifying and repairing caches.
func (s *SFTPStore) RemoveChunk(id ChunkID) error {
c := <-s.pool
defer func() { s.pool <- c }()
name := c.nameFromID(id)
if _, err := c.client.Stat(name); err != nil {
return ChunkMissing{id}
}
return c.client.Remove(name)
}
// StoreChunk adds a new chunk to the store
func (s *SFTPStore) StoreChunk(chunk *Chunk) error {
c := <-s.pool
defer func() { s.pool <- c }()
name := c.nameFromID(chunk.ID())
b, err := chunk.Data()
if err != nil {
return err
}
b, err = s.converters.toStorage(b)
if err != nil {
return err
}
return c.StoreObject(name, bytes.NewReader(b))
}
// HasChunk returns true if the chunk is in the store
func (s *SFTPStore) HasChunk(id ChunkID) (bool, error) {
c := <-s.pool
defer func() { s.pool <- c }()
name := c.nameFromID(id)
_, err := c.client.Stat(name)
return err == nil, nil
}
// Prune removes any chunks from the store that are not contained in a list
// of chunks
func (s *SFTPStore) Prune(ctx context.Context, ids map[ChunkID]struct{}) error {
c := <-s.pool
defer func() { s.pool <- c }()
walker := c.client.Walk(c.path)
for walker.Step() {
// See if we're meant to stop
select {
case <-ctx.Done():
return Interrupted{}
default:
}
if err := walker.Err(); err != nil {
return err
}
info := walker.Stat()
if info.IsDir() { // Skip dirs
continue
}
path := walker.Path()
if !strings.HasSuffix(path, CompressedChunkExt) { // Skip files without chunk extension
continue
}
// Skip compressed chunks if this is running in uncompressed mode and vice-versa
var sID string
if c.opt.Uncompressed {
if !strings.HasSuffix(path, UncompressedChunkExt) {
return nil
}
sID = strings.TrimSuffix(filepath.Base(path), UncompressedChunkExt)
} else {
if !strings.HasSuffix(path, CompressedChunkExt) {
return nil
}
sID = strings.TrimSuffix(filepath.Base(path), CompressedChunkExt)
}
// Convert the name into a checksum, if that fails we're probably not looking
// at a chunk file and should skip it.
id, err := ChunkIDFromString(sID)
if err != nil {
continue
}
// See if the chunk we're looking at is in the list we want to keep, if not
// remove it.
if _, ok := ids[id]; !ok {
if err = s.RemoveChunk(id); err != nil {
return err
}
}
}
return nil
}
// Close terminates all client connections
func (s *SFTPStore) Close() error {
var err error
for i := 0; i < s.n; i++ {
c := <-s.pool
err = c.Close()
}
return err
}
func (s *SFTPStore) String() string {
return s.location.String()
}