/
bundle.go
291 lines (251 loc) · 7.3 KB
/
bundle.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
package activities
import (
"bufio"
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/go-logr/logr"
"github.com/otiai10/copy"
temporal_tools "go.artefactual.dev/tools/temporal"
"github.com/artefactual-sdps/enduro/internal/bagit"
"github.com/artefactual-sdps/enduro/internal/bundler"
"github.com/artefactual-sdps/enduro/internal/fsutil"
)
const (
ModeDir = 0o750
ModeFile = 0o640
)
type BundleActivity struct {
logger logr.Logger
}
func NewBundleActivity(logger logr.Logger) *BundleActivity {
return &BundleActivity{logger: logger}
}
type BundleActivityParams struct {
// SourcePath is the path of the transfer file or directory.
SourcePath string
// TransferDir is the target directory for the bundled package.
TransferDir string
// IsDir indicates that the transfer is a local directory when true. If true
// the transfer will be copied to TransferDir without modification.
IsDir bool
}
type BundleActivityResult struct {
FullPath string // Full path to the transfer in the worker running the session.
}
func (a *BundleActivity) Execute(ctx context.Context, params *BundleActivityParams) (*BundleActivityResult, error) {
var (
res = &BundleActivityResult{}
err error
)
a.logger.V(1).Info("Executing BundleActivity",
"SourcePath", params.SourcePath,
"TransferDir", params.TransferDir,
"IsDir", params.IsDir,
)
if params.TransferDir == "" {
params.TransferDir, err = os.MkdirTemp("", "*-enduro-transfer")
if err != nil {
return nil, err
}
}
if params.IsDir {
res.FullPath, err = a.Bundle(ctx, params.SourcePath, params.TransferDir)
if err != nil {
err = fmt.Errorf("bundle dir: %v", err)
}
} else {
res.FullPath, err = a.SingleFile(ctx, params.SourcePath, params.TransferDir)
if err != nil {
err = fmt.Errorf("bundle single file: %v", err)
}
}
if err != nil {
return nil, temporal_tools.NewNonRetryableError(err)
}
err = unbag(res.FullPath)
if err != nil {
return nil, temporal_tools.NewNonRetryableError(
fmt.Errorf("bundle: unbag: %v", err),
)
}
if err = fsutil.SetFileModes(res.FullPath, ModeDir, ModeFile); err != nil {
return nil, temporal_tools.NewNonRetryableError(
fmt.Errorf("bundle: set permissions: %v", err),
)
}
return res, nil
}
// SingleFile bundles a transfer with the downloaded blob in it.
//
// TODO: Write metadata.csv and checksum files to the metadata dir.
func (a *BundleActivity) SingleFile(
ctx context.Context,
sourcePath string,
transferDir string,
) (string, error) {
b, err := bundler.NewBundlerWithTempDir(transferDir)
if err != nil {
return "", fmt.Errorf("create bundler: %v", err)
}
src, err := os.Open(sourcePath) // #nosec G304 -- trusted file path.
if err != nil {
return "", fmt.Errorf("open source file: %v", err)
}
defer src.Close()
err = b.Write(filepath.Join("objects", filepath.Base(sourcePath)), src)
if err != nil {
return "", fmt.Errorf("write file: %v", err)
}
if err := b.Bundle(); err != nil {
return "", fmt.Errorf("write bundle: %v", err)
}
return b.FullBaseFsPath(), nil
}
// Bundle a transfer with the contents found in the archive.
func (a *BundleActivity) Bundle(
ctx context.Context,
sourcePath string,
transferDir string,
) (string, error) {
tempDir, err := a.Copy(ctx, sourcePath, transferDir)
if err != nil {
return "", fmt.Errorf("bundle: %v", err)
}
// Delete the archive. We still have a copy in the watched source.
_ = os.Remove(sourcePath)
return tempDir, nil
}
// Copy a transfer in the given destination using an intermediate temp. directory.
func (a *BundleActivity) Copy(ctx context.Context, src, dst string) (string, error) {
const prefix = "enduro"
tempDir, err := os.MkdirTemp(dst, prefix)
if err != nil {
return "", fmt.Errorf("error creating temporary directory: %s", err)
}
if err := copy.Copy(src, tempDir); err != nil {
return "", fmt.Errorf("error copying transfer: %v", err)
}
return tempDir, nil
}
// unbag converts a bagged transfer into a standard Archivematica transfer.
// It returns a nil error if a bag is not identified, and non-nil errors when
// the bag seems invalid, without verifying the actual file contents.
func unbag(path string) error {
fi, err := os.Stat(path)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New("not a directory")
}
// Only continue if we have a bag.
securePath, _ := securejoin.SecureJoin(path, "bagit.txt")
_, err = os.Stat(securePath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
// Confirm completeness of the bag.
if err := bagit.Complete(path); err != nil {
return err
}
// Move files in data up one level if 'objects' folder already exists.
// Otherwise, rename data to objects.
dataPath, _ := securejoin.SecureJoin(path, "data")
if fi, err := os.Stat(dataPath); !os.IsNotExist(err) && fi.IsDir() {
items, err := os.ReadDir(dataPath)
if err != nil {
return err
}
for _, item := range items {
src, _ := securejoin.SecureJoin(dataPath, item.Name())
dst, _ := securejoin.SecureJoin(path, filepath.Base(src))
if err := os.Rename(src, dst); err != nil {
return err
}
}
if err := os.RemoveAll(dataPath); err != nil {
return err
}
} else {
dst, _ := securejoin.SecureJoin(path, "objects")
if err := os.Rename(dataPath, dst); err != nil {
return err
}
}
// Create metadata and submissionDocumentation directories.
metadataPath, _ := securejoin.SecureJoin(path, "metadata")
err = os.MkdirAll(metadataPath, ModeDir)
if err != nil {
return err
}
docPath, _ := securejoin.SecureJoin(metadataPath, "submissionDocumentation")
err = os.MkdirAll(docPath, ModeDir)
if err != nil {
return err
}
// Write manifest checksums to checksum file.
for _, item := range [][2]string{
{"manifest-sha512.txt", "checksum.sha512"},
{"manifest-sha256.txt", "checksum.sha256"},
{"manifest-sha1.txt", "checksum.sha1"},
{"manifest-md5.txt", "checksum.md5"},
} {
securePath, _ := securejoin.SecureJoin(path, item[0])
file, err := os.Open(
securePath,
) //#nosec G304 -- Potential file inclusion not possible. item[0] is coming from controlled list.
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
}
defer file.Close()
securePath, _ = securejoin.SecureJoin(metadataPath, item[1])
newFile, err := os.Create(
securePath,
) //#nosec G304 -- Potential file inclusion not possible. item[1] is coming from controlled list.
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
}
defer newFile.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
newLine := ""
if strings.Contains(line, "data/objects/") {
newLine = strings.Replace(line, "data/objects/", "../objects/", 1)
} else {
newLine = strings.Replace(line, "data/", "../objects/", 1)
}
fmt.Fprintln(newFile, newLine)
}
break // One file is enough.
}
// Move bag files to submissionDocumentation.
for _, item := range []string{
"bag-info.txt",
"bagit.txt",
"manifest-md5.txt",
"tagmanifest-md5.txt",
"manifest-sha1.txt",
"tagmanifest-sha1.txt",
"manifest-sha256.txt",
"tagmanifest-sha256.txt",
"manifest-sha512.txt",
"tagmanifest-sha512.txt",
} {
src, _ := securejoin.SecureJoin(path, item)
dst, _ := securejoin.SecureJoin(docPath, item)
_ = os.Rename(src, dst)
}
return nil
}