/
filemover.go
294 lines (250 loc) · 7.49 KB
/
filemover.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
package a1upgrade
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"github.com/chef/automate/components/automate-deployment/pkg/cli"
"github.com/chef/automate/lib/io/fileutils"
"github.com/chef/automate/lib/platform/command"
)
const defaultFileMoverTimeout = 300 * time.Second
const defaultUser = "hab"
const defaultGroup = "hab"
const defaultRsyncCmd = "hab"
// A FileMover moves directories of files on the same system.
// Abstracted into our own type so we can consistently add behaviors
// such as permissions setting and timeouts.
type FileMover struct {
RelDestPath string
ServiceName string
SrcPath string
Timeout time.Duration
c command.Executor
User string
Group string
RsyncCmd string
forceCopy bool
habBasePath string
}
// var rather than const here since we reset these in some tests
var defaultHabBaseDir = "/hab/svc"
// FileMoversForConfig returns the file migrations that should take
// place given the passed DeliveryRunning configuration
func FileMoversForConfig(d *DeliveryRunning, workflow bool) []*FileMover {
fileMovers := []*FileMover{
NewFileMover(d.Delivery.Insights.DataDirectory, "automate-elasticsearch", "data"),
NewFileMover(d.Delivery.Compliance.ProfilesPath, "compliance-service", "data/profiles"),
}
// if workflow is enabled, we will add the file mover for the git repositories
if workflow {
fileMovers = append(
fileMovers,
NewFileMover(d.Delivery.Delivery.GitRepos, "automate-workflow-server", "data/git/repos"),
)
}
return fileMovers
}
// FileMoverOpt sets properties of the file mover
type FileMoverOpt func(*FileMover)
// ForceCopy is a FileMover option that forces the file to
// be copied
func ForceCopy() FileMoverOpt {
return func(f *FileMover) {
f.forceCopy = true
}
}
// NewFileMover returns a FileMover with the default timeout and
// commandExector.
func NewFileMover(src string, serviceName string, relDst string, opts ...FileMoverOpt) *FileMover {
f := &FileMover{
SrcPath: src,
ServiceName: serviceName,
RelDestPath: strings.TrimLeft(relDst, "/"),
Timeout: defaultFileMoverTimeout,
User: defaultUser,
Group: defaultGroup,
RsyncCmd: defaultRsyncCmd,
c: command.NewExecExecutor(),
habBasePath: defaultHabBaseDir,
}
for _, o := range opts {
o(f)
}
return f
}
func (f *FileMover) DestPath() string {
return path.Join(f.habBasePath, f.ServiceName, f.RelDestPath)
}
func (f *FileMover) doneSentinelPath() string {
destPath := f.DestPath()
dir := filepath.Dir(destPath)
base := filepath.Base(destPath)
return filepath.Join(dir, fmt.Sprintf(".%s-a1-migration-move-complete", base))
}
func (f *FileMover) startedSentinelPath() string {
destPath := f.DestPath()
dir := filepath.Dir(destPath)
base := filepath.Base(destPath)
return filepath.Join(dir, fmt.Sprintf(".%s-a1-migration-move-started", base))
}
// AlreadyMoved returns true if the directory has already been
// migrated.
func (f *FileMover) AlreadyMoved() (bool, error) {
exists, err := fileutils.PathExists(f.doneSentinelPath())
if err != nil {
return false, err
}
return exists, nil
}
// MoveStarted returns true if we've previously attempted to move this
// directory.
func (f *FileMover) MoveStarted() (bool, error) {
exists, err := fileutils.PathExists(f.startedSentinelPath())
if err != nil {
return false, err
}
return exists, nil
}
func (f *FileMover) markAsMoved() error {
return os.Rename(f.startedSentinelPath(), f.doneSentinelPath())
}
func (f *FileMover) markStarted() error {
file, err := os.OpenFile(f.startedSentinelPath(), os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
return err
}
return file.Close()
}
// Move performs the file move
func (f *FileMover) Move(w cli.BodyWriter) error {
destPath := f.DestPath()
destParent := filepath.Dir(destPath)
err := os.MkdirAll(destParent, os.ModePerm)
if err != nil {
return errors.Wrapf(err, "could not create destination data directory parent %s", destParent)
}
moved, err := f.AlreadyMoved()
if err != nil {
return errors.Wrap(err, "could not determine if directory has already been moved")
}
if !moved {
err = f.doMove(w)
if err != nil {
return err
}
} else {
w.Bodyf("skipping %s -> %s (already moved)", f.SrcPath, destPath)
}
return f.fixupPermissions(w)
}
// fixupPermissions on the data directory to the configured user and group.
// TODO: (yzl) perms should match just deploying a hab package
func (f *FileMover) fixupPermissions(w cli.BodyWriter) error {
svcPath := path.Join(f.habBasePath, f.ServiceName)
splitRelPath := strings.Split(f.RelDestPath, "/")
chownPath := path.Join(svcPath, splitRelPath[0])
ownerSpec := fmt.Sprintf("%s:%s", f.User, f.Group)
w.Bodyf("setting ownership on %s to %s", chownPath, ownerSpec)
_, err := f.c.Output("chown", command.Args("-R", ownerSpec, chownPath), command.Timeout(f.Timeout))
if err != nil {
return errors.Wrapf(err, "error changing ownership of new data directory %s: %s", chownPath, command.StderrFromError(err))
}
return nil
}
func (f *FileMover) doMove(w cli.BodyWriter) error {
err := f.markStarted()
if err != nil {
return errors.Wrapf(err, "error creating file migration sentinel file")
}
destPath := f.DestPath()
sameFs, err := IsSameFilesystem(f.SrcPath, destPath)
if err != nil {
return err
}
dstExist, err := fileutils.PathExists(destPath)
if err != nil {
return err
}
if sameFs && !dstExist && !f.forceCopy {
w.Bodyf("moving %s -> %s (rename)", f.SrcPath, destPath)
err = f.doRenameMove()
} else {
w.Bodyf("moving %s -> %s (rsync)", f.SrcPath, destPath)
err = f.doRsyncMove()
}
if err != nil {
return err
}
err = f.markAsMoved()
if err != nil {
// TODO(ssd) 2018-03-16: This is a pretty nasty case.
// If we just fail marking it as moved, we can't retry
// safely :/
return errors.Wrapf(err, "error marking data directory as moved")
}
return nil
}
func (f *FileMover) doRsyncMove() error {
// Rsync options quick reference:
//
// -h: output numbers in a human-readable format
// -S: handle sparse files efficiently
// -a: "archive", equals -rlptgoD (no -H,-A,-X)
//
// -r: recurses into directories
// -l: preserve links
// -p: preserve permissions
// -t: preserve modification times
// -g: preserve group
// -o: preserve owner
// -D: preserve special files and devices
//
// We want to generate an rsync command in the form of:
//
// For dir sources:
// rsync OPTS /SRC_PARENT_PATH/src/ /DST_PARENTPATH/dst
// For file sources:
// rsync OPTS /SRC_PARENT_PATH/src /DST_PARENTPATH
destPath := f.DestPath()
rsyncSrc := f.SrcPath
rsyncDst := destPath
stat, err := os.Stat(rsyncSrc)
if err != nil {
return errors.Wrapf(err, "Failed to stat %s", rsyncSrc)
}
if stat.IsDir() {
if !strings.HasSuffix(rsyncSrc, "/") {
rsyncSrc = rsyncSrc + "/"
}
rsyncDst = strings.TrimRight(destPath, "/")
}
args := []string{
"-haS",
rsyncSrc,
rsyncDst,
}
// Special case for hab-based rsync. Actually, the common case.
if f.RsyncCmd == "hab" {
args = append([]string{"pkg", "exec", "core/rsync", "rsync"}, args...)
}
_, err = f.c.Output(f.RsyncCmd,
command.Args(args...),
command.Envvar("HAB_LICENSE", "accept-no-persist"),
command.Timeout(f.Timeout))
if err != nil {
return errors.Wrapf(err, "rsync failed: %s", command.StderrFromError(err))
}
return nil
}
func (f *FileMover) doRenameMove() error {
destPath := f.DestPath()
err := os.Rename(f.SrcPath, destPath)
if err != nil {
return errors.Wrap(err, "rename failed")
}
return nil
}