-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
264 lines (220 loc) · 6.18 KB
/
state.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
// Copyright 2024 Aerospike, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package backup
import (
"context"
"encoding/gob"
"fmt"
"io"
"log/slog"
"sync"
"time"
a "github.com/aerospike/aerospike-client-go/v7"
"github.com/aerospike/backup-go/models"
)
// State contains current backups status data.
type State struct {
// Global backup context.
ctx context.Context
// Counter to count how many times State instance was initialized.
// Is used to create suffix for backup files.
Counter int
// RecordsStateChan communication channel to save current filter state.
RecordsStateChan chan models.PartitionFilterSerialized
// RecordStates store states of all filters.
RecordStates map[int]models.PartitionFilterSerialized
RecordStatesSaved map[int]models.PartitionFilterSerialized
// SaveCommandChan command to save current state for worker.
SaveCommandChan chan int
// Mutex for RecordStates operations.
// Ordinary mutex is used, because we must not allow any writings when we read state.
mu sync.Mutex
// File to save state to.
FileName string
// writer is used to create a state file.
writer Writer
// logger for logging errors.
logger *slog.Logger
}
// NewState returns new state instance depending on config.
// If we continue back up, the state will be loaded from a state file,
// if it is the first operation, new state instance will be returned.
func NewState(
ctx context.Context,
config *BackupConfig,
reader StreamingReader,
writer Writer,
logger *slog.Logger,
) (*State, error) {
switch {
case config.isStateFirstRun():
logger.Debug("initializing new state")
return newState(ctx, config, writer, logger), nil
case config.isStateContinue():
logger.Debug("initializing state from file", slog.String("file", config.StateFile))
return newStateFromFile(ctx, config, reader, writer, logger)
}
return nil, nil
}
// newState creates status service from parameters, for backup operations.
func newState(
ctx context.Context,
config *BackupConfig,
writer Writer,
logger *slog.Logger,
) *State {
s := &State{
ctx: ctx,
// RecordsStateChan must not be buffered, so we can stop all operations.
RecordsStateChan: make(chan models.PartitionFilterSerialized),
RecordStates: make(map[int]models.PartitionFilterSerialized),
RecordStatesSaved: make(map[int]models.PartitionFilterSerialized),
SaveCommandChan: make(chan int),
FileName: config.StateFile,
writer: writer,
logger: logger,
}
// Run watcher on initialization.
go s.serve()
go s.serveRecords()
return s
}
// newStateFromFile creates a status service from the file, to continue operations.
func newStateFromFile(
ctx context.Context,
config *BackupConfig,
reader StreamingReader,
writer Writer,
logger *slog.Logger,
) (*State, error) {
f, err := openFile(ctx, reader, config.StateFile)
if err != nil {
return nil, fmt.Errorf("failed to open state file: %w", err)
}
dec := gob.NewDecoder(f)
var s State
if err = dec.Decode(&s); err != nil {
return nil, fmt.Errorf("failed to decode state: %w", err)
}
s.ctx = ctx
s.writer = writer
s.logger = logger
s.RecordsStateChan = make(chan models.PartitionFilterSerialized)
s.SaveCommandChan = make(chan int)
s.Counter++
// Init current state.
for k, v := range s.RecordStatesSaved {
s.RecordStates[k] = v
}
logger.Debug("loaded state file successfully", slog.Int("filters loaded", len(s.RecordStatesSaved)))
// Run watcher on initialization.
go s.serve()
go s.serveRecords()
return &s, nil
}
// serve dumps files to disk.
func (s *State) serve() {
for {
select {
case <-s.ctx.Done():
return
case msg := <-s.SaveCommandChan:
if err := s.dump(msg); err != nil {
s.logger.Error("failed to dump state", slog.Any("error", err))
return
}
}
}
}
func (s *State) dump(n int) error {
file, err := s.writer.NewWriter(s.ctx, s.FileName)
if err != nil {
return fmt.Errorf("failed to create state file %s: %w", s.FileName, err)
}
enc := gob.NewEncoder(file)
s.mu.Lock()
defer s.mu.Unlock()
if n > -1 {
s.RecordStatesSaved[n] = s.RecordStates[n]
}
if err = enc.Encode(s); err != nil {
return fmt.Errorf("failed to encode state data: %w", err)
}
if err = file.Close(); err != nil {
return fmt.Errorf("failed to close state file: %w", err)
}
s.logger.Debug("state file dumped", slog.Time("saved at", time.Now()))
return nil
}
func (s *State) initState(pf []*a.PartitionFilter) error {
s.mu.Lock()
for i := range pf {
pfs, err := models.NewPartitionFilterSerialized(pf[i])
if err != nil {
return err
}
s.RecordStates[i] = pfs
s.RecordStatesSaved[i] = pfs
}
// Do not move this Unlock() to defer!
s.mu.Unlock()
return s.dump(-1)
}
func (s *State) loadPartitionFilters() ([]*a.PartitionFilter, error) {
s.mu.Lock()
defer s.mu.Unlock()
result := make([]*a.PartitionFilter, 0, len(s.RecordStatesSaved))
for _, state := range s.RecordStatesSaved {
f, err := state.Decode()
if err != nil {
return nil, err
}
result = append(result, f)
}
return result, nil
}
func (s *State) serveRecords() {
for {
select {
case <-s.ctx.Done():
return
case state := <-s.RecordsStateChan:
if state.IsEmpty() {
continue
}
s.mu.Lock()
s.RecordStates[state.N] = state
s.mu.Unlock()
}
}
}
func (s *State) getFileSuffix() string {
if s.Counter > 0 {
return fmt.Sprintf("(%d)", s.Counter)
}
return ""
}
func openFile(ctx context.Context, reader StreamingReader, fileName string) (io.ReadCloser, error) {
readCh := make(chan io.ReadCloser)
errCh := make(chan error)
go reader.StreamFile(ctx, fileName, readCh, errCh)
select {
case <-ctx.Done():
return nil, ctx.Err()
case err := <-errCh:
return nil, err
case file := <-readCh:
return file, nil
}
}