/
syncer.go
210 lines (171 loc) · 5.94 KB
/
syncer.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
package objutil
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"github.com/couchbase/tools-common/cloud/v3/objstore/objcli"
"github.com/couchbase/tools-common/cloud/v3/objstore/objval"
fsutil "github.com/couchbase/tools-common/fs/util"
"github.com/couchbase/tools-common/sync/v2/hofp"
ioiface "github.com/couchbase/tools-common/types/iface"
"github.com/couchbase/tools-common/types/ratelimit"
)
// Syncer exposes the ability to sync files and directories to/from a remote cloud provider.
type Syncer struct {
opts SyncOptions
logger *slog.Logger
}
// NewSyncer creates a new syncer using the given options.
func NewSyncer(opts SyncOptions) *Syncer {
// Fill out any missing fields with the sane defaults
opts.defaults()
syncer := Syncer{
opts: opts,
logger: opts.Logger,
}
return &syncer
}
// addTrailingPathSeparator adds a trailing path separator to path if it does not have one already.
func (s *Syncer) addTrailingPathSeparator(path string) string {
if !strings.HasSuffix(path, string(os.PathSeparator)) {
return path + string(os.PathSeparator)
}
return path
}
// Upload a directory from the local file system to cloud storage. Assumes source is a file:// URL and destination is a
// cloud-specific one.
func (s *Syncer) Upload(source, destination *CloudOrFileURL) error {
// Add a trailing path separator so when we trim the path in ul below the result is a relative path, not an absolute
// one
srcPrefix := s.addTrailingPathSeparator(source.Path)
if !strings.HasSuffix(source.Path, string(os.PathSeparator)) {
srcPrefix = s.addTrailingPathSeparator(filepath.Dir(source.Path))
}
pool := hofp.NewPool(hofp.Options{
Context: s.opts.Context,
})
ul := func(ctx context.Context, path string) error {
// Get the path relative to the directory we're uploading which we then use as the destination subpath
var (
suffix = strings.TrimPrefix(path, srcPrefix)
newDestination = destination.Join(suffix)
)
newSource, err := ParseCloudOrFileURL(path)
if err != nil {
return fmt.Errorf("could not parse file path: %w", err)
}
return s.uploadFile(ctx, newSource, newDestination)
}
err := filepath.Walk(source.Path, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
return pool.Queue(func(ctx context.Context) error { return ul(ctx, path) })
})
if err != nil {
return fmt.Errorf("could not walk directory: %w", err)
}
err = pool.Stop()
if err != nil {
return fmt.Errorf("error whilst uploading directory: %w", err)
}
return nil
}
// uploadFile uploads a file to the given cloud provider. Assumes source is a file:// URL to a file, and
// destination is a cloud path.
func (s *Syncer) uploadFile(ctx context.Context, source, destination *CloudOrFileURL) error {
s.logger.Debug("uploading file", "source", source, "destination", destination)
file, err := fsutil.OpenRandAccess(source.Path, 0, 0)
if err != nil {
return fmt.Errorf("could not open specified file: %w", err)
}
defer file.Close()
var reader ioiface.ReadAtSeeker = file
if s.opts.Limiter != nil {
reader = ratelimit.NewRateLimitedReadAtSeeker(ctx, reader, s.opts.Limiter)
}
opts := UploadOptions{
Options: s.opts.Options.WithContext(ctx),
Client: s.opts.Client,
Bucket: destination.Bucket,
Key: destination.Path,
Body: reader,
MPUThreshold: s.opts.MPUThreshold,
}
return Upload(opts)
}
// Download all files under the prefix in opts.Source to the given destination. Assumes source is a cloud path and
// destination is a local path to a directory.
//
// NOTE: If you specify a source such as "path/to/dir" then the directory "path/to/dir/" is considered under the source,
// so a "dir" directory will be created under your destination. To avoid this specify your source with a trailing slash.
func (s *Syncer) Download(source, destination *CloudOrFileURL) error {
destination.Path = s.addTrailingPathSeparator(destination.Path)
pool := hofp.NewPool(hofp.Options{
Context: s.opts.Context,
})
keyPrefix := path.Dir(source.Path)
if strings.HasSuffix(source.Path, "/") {
keyPrefix = source.Path
}
if !strings.HasSuffix(keyPrefix, "/") {
keyPrefix += "/"
}
dl := func(ctx context.Context, key string) error {
var (
newSource = CloudOrFileURL{Bucket: source.Bucket, Provider: source.Provider, Path: key}
newDestination = destination.Join(strings.TrimPrefix(key, keyPrefix))
)
return s.downloadFile(ctx, &newSource, newDestination)
}
queue := func(attrs *objval.ObjectAttrs) error {
if attrs.IsDir() {
return nil
}
return pool.Queue(func(ctx context.Context) error { return dl(ctx, attrs.Key) })
}
err := s.opts.Client.IterateObjects(s.opts.Context, objcli.IterateObjectsOptions{
Bucket: source.Bucket,
Prefix: source.Path,
Func: queue,
})
if err != nil {
return fmt.Errorf("could not iterate objects: %w", err)
}
err = pool.Stop()
if err != nil {
return fmt.Errorf("error whilst downloading: %w", err)
}
return nil
}
// downloadFile downloads a file in the cloud to a file on disk. Assumes source is a cloud URL to an object and
// destination is a file:// URL to a file.
func (s *Syncer) downloadFile(ctx context.Context, source, destination *CloudOrFileURL) error {
s.logger.Debug("downloading file", "source", source, "destination", destination)
err := fsutil.Mkdir(filepath.Dir(destination.Path), 0, true, true)
if err != nil {
return fmt.Errorf("could not create subdirectories: %w", err)
}
file, err := fsutil.CreateFile(destination.Path, os.O_WRONLY, 0)
if err != nil {
return fmt.Errorf("could not open specified file: %w", err)
}
defer file.Close()
var writer io.WriterAt = file
if s.opts.Limiter != nil {
writer = ratelimit.NewRateLimitedWriterAt(ctx, writer, s.opts.Limiter)
}
opts := DownloadOptions{
Options: s.opts.Options.WithContext(ctx),
Client: s.opts.Client,
Bucket: source.Bucket,
Key: source.Path,
Writer: writer,
}
return Download(opts)
}