/
zfsmanager.go
402 lines (361 loc) · 11.1 KB
/
zfsmanager.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright (c) 2021 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zfsmanager
import (
"os"
"path/filepath"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/lf-edge/eve/pkg/pillar/agentbase"
"github.com/lf-edge/eve/pkg/pillar/agentlog"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/flextimer"
"github.com/lf-edge/eve/pkg/pillar/pubsub"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/utils/persist"
"github.com/lf-edge/eve/pkg/pillar/utils/wait"
"github.com/lf-edge/eve/pkg/pillar/zfs"
"github.com/sirupsen/logrus"
)
const (
agentName = "zfsmanager"
// Time limits for event loop handlers
errorTime = 3 * time.Minute
warningTime = 40 * time.Second
stillRunningInterval = 25 * time.Second
disksProcessingInterval = 60 * time.Second
zvolsProcessingInterval = 5 * time.Second
)
var (
logger *logrus.Logger
log *base.LogObject
)
type zVolDeviceEvent struct {
delete bool
dataset string
}
type zfsContext struct {
agentbase.AgentBase
ps *pubsub.PubSub
subGlobalConfig pubsub.Subscription
zVolStatusPub pubsub.Publication
storageStatusPub pubsub.Publication
storageMetricsPub pubsub.Publication
subDisksConfig pubsub.Subscription
subVolumeStatus pubsub.Subscription
disksProcessingTrigger chan interface{}
zVolDeviceEvents *base.LockedStringMap // stores device->zVolDeviceEvent mapping to check and publish
zfsIterLock sync.Mutex
globalConfig *types.ConfigItemValueMap
GCInitialized bool
}
// Run - an zfs run
func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, arguments []string) int {
logger = loggerArg
log = logArg
ctxPtr := &zfsContext{
ps: ps,
disksProcessingTrigger: make(chan interface{}, 1),
zVolDeviceEvents: base.NewLockedStringMap(),
globalConfig: types.DefaultConfigItemValueMap(),
}
agentbase.Init(ctxPtr, logger, log, agentName,
agentbase.WithPidFile(),
agentbase.WithWatchdog(ps, warningTime, errorTime),
agentbase.WithArguments(arguments))
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(stillRunningInterval)
ps.StillRunning(agentName, warningTime, errorTime)
// Wait until we have been onboarded aka know our own UUID, but we don't use the UUID
err := wait.WaitForOnboarded(ps, log, agentName, warningTime, errorTime)
if err != nil {
log.Fatal(err)
}
log.Functionf("processed onboarded")
if err := wait.WaitForVault(ps, log, agentName, warningTime, errorTime); err != nil {
log.Fatal(err)
}
log.Functionf("processed Vault Status")
// Publish ZVolStatus for zvol devices
zVolStatusPub, err := ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.ZVolStatus{},
})
if err != nil {
log.Fatal(err)
}
ctxPtr.zVolStatusPub = zVolStatusPub
// Look for global config such as log levels
subGlobalConfig, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedagent",
MyAgentName: agentName,
TopicImpl: types.ConfigItemValueMap{},
Persistent: true,
Activate: false,
Ctx: ctxPtr,
CreateHandler: handleGlobalConfigCreate,
ModifyHandler: handleGlobalConfigModify,
DeleteHandler: handleGlobalConfigDelete,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
ctxPtr.subGlobalConfig = subGlobalConfig
subGlobalConfig.Activate()
// Pick up debug aka log level before we start real work
for !ctxPtr.GCInitialized {
log.Functionf("waiting for GCInitialized")
select {
case change := <-subGlobalConfig.MsgChan():
subGlobalConfig.ProcessChange(change)
case <-stillRunning.C:
}
ps.StillRunning(agentName, warningTime, errorTime)
}
log.Functionf("processed GlobalConfig")
// Look for disks config
subDisksConfig, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedagent",
MyAgentName: agentName,
TopicImpl: types.EdgeNodeDisks{},
Activate: false,
Ctx: ctxPtr,
CreateHandler: handleDisksConfigCreate,
ModifyHandler: handleDisksConfigModify,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
ctxPtr.subDisksConfig = subDisksConfig
subDisksConfig.Activate()
// Publish cloud status
storageStatusPub, err := ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.ZFSPoolStatus{},
Persistent: false,
})
if err != nil {
log.Fatal(err)
}
ctxPtr.storageStatusPub = storageStatusPub
// Publish cloud metrics
storageMetricsPub, err := ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.ZFSPoolMetrics{},
Persistent: false,
})
if err != nil {
log.Fatal(err)
}
ctxPtr.storageMetricsPub = storageMetricsPub
// Look VolumeStatus from volumemgr to getting zVol metrics
subVolumeStatus, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "volumemgr",
MyAgentName: agentName,
TopicImpl: types.VolumeStatus{},
Activate: false,
Ctx: ctxPtr,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
ctxPtr.subVolumeStatus = subVolumeStatus
subVolumeStatus.Activate()
if err := os.MkdirAll(types.ZVolDevicePrefix, os.ModeDir); err != nil {
log.Fatal(err)
}
go processDisksTask(ctxPtr)
go deviceWatcher(ctxPtr)
go storageStatusPublisher(ctxPtr)
go storageMetricsPublisher(ctxPtr)
max := float64(zvolsProcessingInterval)
min := max * 0.3
devicesProcessTicker := flextimer.NewRangeTicker(time.Duration(min),
time.Duration(max))
for {
select {
case change := <-subGlobalConfig.MsgChan():
subGlobalConfig.ProcessChange(change)
case <-devicesProcessTicker.C:
processZVolDeviceEvents(ctxPtr)
case change := <-subDisksConfig.MsgChan():
subDisksConfig.ProcessChange(change)
case change := <-subVolumeStatus.MsgChan():
subVolumeStatus.ProcessChange(change)
case <-stillRunning.C:
}
ps.StillRunning(agentName, warningTime, errorTime)
}
}
// processZVolDeviceEvents iterates over saved zVolDeviceEvent, check for device existence and publish ZVolStatus
func processZVolDeviceEvents(ctxPtr *zfsContext) {
var processedKeys []string
checker := func(key string, val interface{}) bool {
event, ok := val.(zVolDeviceEvent)
if !ok {
log.Fatalf("unexpected type for key: %s", key)
}
zvolStatus := types.ZVolStatus{
Device: key,
Dataset: event.dataset,
}
if event.delete {
if el, _ := ctxPtr.zVolStatusPub.Get(zvolStatus.Key()); el == nil {
processedKeys = append(processedKeys, key)
return true
}
if err := ctxPtr.zVolStatusPub.Unpublish(zvolStatus.Key()); err != nil {
log.Errorf("cannot unpublish device: %s", err)
return true
}
processedKeys = append(processedKeys, key)
return true
}
l, err := filepath.EvalSymlinks(key)
if err != nil {
log.Warnf("failed to EvalSymlinks: %s", err)
return true
}
_, err = os.Stat(l)
if err != nil {
log.Warnf("failed to Stat device: %s", err)
return true
}
if err := ctxPtr.zVolStatusPub.Publish(zvolStatus.Key(), zvolStatus); err != nil {
log.Errorf("cannot publish device: %s", err)
return true
}
processedKeys = append(processedKeys, key)
return true
}
ctxPtr.zVolDeviceEvents.Range(checker)
for _, key := range processedKeys {
ctxPtr.zVolDeviceEvents.Delete(key)
}
}
func deviceWatcher(ctxPtr *zfsContext) {
w, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("NewWatcher: %s", err)
}
defer w.Close()
processRecursive := func(dir string) error {
// walk through exist files
return filepath.Walk(dir, func(walkPath string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
if fi.IsDir() {
return w.Add(walkPath)
} else {
// we expect symlinks created by mdev
if fi.Mode()&os.ModeSymlink != 0 {
dataset := zfs.GetDatasetByDevice(walkPath)
if dataset == "" {
log.Errorf("cannot determine dataset for device: %s", walkPath)
return nil
}
ctxPtr.zVolDeviceEvents.Store(walkPath, zVolDeviceEvent{
dataset: dataset,
})
}
}
return nil
})
}
if err := processRecursive(types.ZVolDevicePrefix); err != nil {
log.Errorf("Failed to Walk in %s: %s", types.ZVolDevicePrefix, err)
}
for event := range w.Events {
log.Functionf("deviceWatcher: %+v", event)
fileName := event.Name
s, err := os.Stat(fileName)
if err == nil && s != nil && s.IsDir() {
if event.Op&fsnotify.Create != 0 {
if err := processRecursive(fileName); err != nil {
log.Errorf("Failed to Walk in %s: %s", fileName, err)
}
}
continue
}
if event.Op&fsnotify.Create != 0 {
dataset := zfs.GetDatasetByDevice(fileName)
if dataset == "" {
log.Errorf("cannot determine dataset for device: %s", fileName)
continue
}
ctxPtr.zVolDeviceEvents.Store(fileName, zVolDeviceEvent{
dataset: dataset,
})
} else if event.Op&fsnotify.Remove != 0 {
ctxPtr.zVolDeviceEvents.Store(fileName, zVolDeviceEvent{
delete: true,
})
}
}
}
func handleGlobalConfigCreate(ctxArg interface{}, key string,
statusArg interface{}) {
handleGlobalConfigImpl(ctxArg, key, statusArg)
}
func handleGlobalConfigModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleGlobalConfigImpl(ctxArg, key, statusArg)
}
func handleGlobalConfigImpl(ctxArg interface{}, key string,
statusArg interface{}) {
ctx := ctxArg.(*zfsContext)
if key != "global" {
log.Functionf("handleGlobalConfigImpl: ignoring %s", key)
return
}
log.Functionf("handleGlobalConfigImpl for %s", key)
gcp := agentlog.HandleGlobalConfig(log, ctx.subGlobalConfig, agentName,
ctx.CLIParams().DebugOverride, logger)
if gcp != nil {
maybeUpdateConfigItems(ctx, gcp)
ctx.globalConfig = gcp
ctx.GCInitialized = true
}
log.Functionf("handleGlobalConfigImpl done for %s", key)
}
func handleGlobalConfigDelete(ctxArg interface{}, key string,
statusArg interface{}) {
ctx := ctxArg.(*zfsContext)
if key != "global" {
log.Functionf("handleGlobalConfigDelete: ignoring %s", key)
return
}
log.Functionf("handleGlobalConfigDelete for %s", key)
agentlog.HandleGlobalConfig(log, ctx.subGlobalConfig, agentName,
ctx.CLIParams().DebugOverride, logger)
*ctx.globalConfig = *types.DefaultConfigItemValueMap()
log.Functionf("handleGlobalConfigDelete done for %s", key)
}
func maybeUpdateConfigItems(ctx *zfsContext, newConfigItemValueMap *types.ConfigItemValueMap) {
log.Functionf("maybeUpdateConfigItems")
oldConfigItemValueMap := ctx.globalConfig
if persist.ReadPersistType() != types.PersistZFS {
return
}
newStorageZfsReserved := newConfigItemValueMap.GlobalValueInt(types.StorageZfsReserved)
oldStorageZfsReserved := oldConfigItemValueMap.GlobalValueInt(types.StorageZfsReserved)
if oldStorageZfsReserved != newStorageZfsReserved {
log.Noticef("StorageZfsReserved changed from %d to %d",
oldStorageZfsReserved, newStorageZfsReserved)
err := zfs.SetReserved(types.PersistDataset,
uint64(newStorageZfsReserved))
if err != nil {
log.Errorf("SetReserved failed: %s", err)
}
}
}