/
checkpoint.go
233 lines (208 loc) · 5.75 KB
/
checkpoint.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
// Copyright 2023 cloudeng llc. All rights reserved.
// Use of this source code is governed by the Apache-2.0
// license that can be found in the LICENSE file.
// Package checkpoint provides a mechanism for checkpointing the
// state of an ongoing operation. An operation is defined as any
// application activity that can be meaningfully broken into smaller
// steps and that can be resumed from one of those steps. The record
// of the successful completion of each step is recorded as a 'checkpoint'.
package checkpoint
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"cloudeng.io/os/lockedfile"
)
// Operation is the interface for checkpointing an operation.
type Operation interface {
Init(ctx context.Context, root string) error
// Clear all existing checkpoints.
Clear(context.Context) error
// Compact removes all but the most recent checkpoint and
// renames as the first checkpoint in the sequence.
Compact(ctx context.Context, label string) error
// Checkpoint records the successful completion of a step in the
// operation.
Checkpoint(ctx context.Context, label string, data []byte) (id string, err error)
// Latest reads the latest recorded checkpoint.
Latest(ctx context.Context) ([]byte, error)
// Complete removes all checkpoints since the operation is
// deemed to be have comleted successfully.
Complete(ctx context.Context) error
// Load reads the checkpoint with the specified id, the id
// must have been returned by an earlier call to Checkpoint.
Load(ctx context.Context, id string) ([]byte, error)
}
type dirop struct {
dir string
mu *lockedfile.Mutex
}
const lockfileName = "lock"
// NewDirectoryOperation returns an implementation of Operation that
// uses a directory on the local file system to record checkpoints.
// This implementation locks the directory using os.Lockedfile and
// rescans it on each call to Checkpoint to determine the latest entry.
// Consequently it is not well suited to very large numbers of checkpoints.
func NewDirectoryOperation() Operation {
return &dirop{}
}
func (d *dirop) Init(_ context.Context, dir string) error {
if len(d.dir) > 0 {
return fmt.Errorf("already initialized")
}
d.dir = dir
d.mu = lockedfile.MutexAt(filepath.Join(dir, lockfileName))
return os.MkdirAll(dir, 0755)
}
func (d *dirop) Clear(ctx context.Context) error {
if len(d.dir) == 0 {
return fmt.Errorf("not yet initialized")
}
unlock, err := d.mu.Lock()
if err != nil {
return err
}
defer unlock()
existing, err := readDirSorted(ctx, d.dir)
if err != nil {
return err
}
for _, f := range existing {
if err := os.Remove(filepath.Join(d.dir, f)); err != nil {
return err
}
}
return nil
}
func (d *dirop) Complete(ctx context.Context) error {
unlock, err := d.mu.Lock()
if err != nil {
return err
}
defer unlock()
existing, err := readDirSorted(ctx, d.dir)
if err != nil {
return err
}
for _, f := range existing {
if err := os.Remove(filepath.Join(d.dir, f)); err != nil {
return err
}
}
return nil
}
func (d *dirop) Checkpoint(ctx context.Context, label string, data []byte) (id string, err error) {
unlock, err := d.mu.Lock()
if err != nil {
return "", err
}
defer unlock()
existing, err := readDirSorted(ctx, d.dir)
if err != nil {
return "", err
}
var next string
if len(existing) == 0 {
next = formatFilename(0, label)
} else {
prev := existing[len(existing)-1]
n, err := strconv.Atoi(prev[:checkpointNumFormatSize])
if err != nil {
return "", fmt.Errorf("invalid checkpoint filename %q: %v", prev, err)
}
next = formatFilename(n+1, label)
}
err = os.WriteFile(filepath.Join(d.dir, next), data, 0644)
return next, err
}
func (d *dirop) Load(_ context.Context, id string) ([]byte, error) {
// No need to lock the directory.
return os.ReadFile(filepath.Join(d.dir, id))
}
func (d *dirop) Latest(ctx context.Context) ([]byte, error) {
unlock, err := d.mu.Lock()
if err != nil {
return nil, err
}
defer unlock()
existing, err := readDirSorted(ctx, d.dir)
if err != nil {
return nil, err
}
if len(existing) == 0 {
return nil, nil
}
prev := existing[len(existing)-1]
return os.ReadFile(filepath.Join(d.dir, prev))
}
func (d *dirop) Compact(ctx context.Context, label string) error {
unlock, err := d.mu.Lock()
if err != nil {
return err
}
defer unlock()
existing, err := readDirSorted(ctx, d.dir)
if err != nil {
return err
}
if len(existing) == 0 {
return nil
}
prev := existing[len(existing)-1]
data, err := os.ReadFile(filepath.Join(d.dir, prev))
if err != nil {
return err
}
for _, f := range existing {
if err := os.Remove(filepath.Join(d.dir, f)); err != nil {
return err
}
}
zero := formatFilename(0, label)
return os.WriteFile(filepath.Join(d.dir, zero), data, 0644)
}
func readDirSorted(ctx context.Context, path string) ([]string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
scanSize := 50
files := make([]string, 0, 50)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
infos, err := f.ReadDir(scanSize)
for _, info := range infos {
if n := info.Name(); !info.IsDir() && strings.HasSuffix(n, checkpointSuffix) && len(n) >= (checkpointNumFormatSize+len(checkpointSuffix)) {
files = append(files, n)
}
}
if err == io.EOF {
sortByNumberOnly(files)
return files, nil
}
}
}
// sort files by the number prefix, ignoring the label.
func sortByNumberOnly(files []string) {
sort.Slice(files, func(i, j int) bool {
return files[i][:checkpointNumFormatSize] < files[j][:checkpointNumFormatSize]
})
}
const (
checkpointNumFormat = "%08d"
checkpointNumFormatSize = 8
checkpointSuffix = ".chk"
)
func formatFilename(n int, label string) string {
return fmt.Sprintf(checkpointNumFormat+"%s"+checkpointSuffix, n, label)
}