-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
332 lines (270 loc) · 8.11 KB
/
main.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
package main
import (
"context"
"fmt"
"math/rand"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/threefoldtech/zos/pkg/app"
"github.com/threefoldtech/zos/pkg/stubs"
"github.com/threefoldtech/zos/pkg/upgrade"
"github.com/cenkalti/backoff/v3"
"github.com/threefoldtech/zos/pkg"
"github.com/threefoldtech/zos/pkg/environment"
"github.com/threefoldtech/zos/pkg/identity"
"flag"
"github.com/rs/zerolog/log"
"github.com/threefoldtech/zbus"
"github.com/threefoldtech/zos/pkg/utils"
"github.com/threefoldtech/zos/pkg/version"
)
const (
redisSocket = "unix:///var/run/redis.sock"
)
const (
module = "identityd"
seedName = "seed.txt"
)
// Safe makes sure function call not interrupted
// with a signal while exection
func Safe(fn func() error) error {
ch := make(chan os.Signal, 4)
defer close(ch)
defer signal.Stop(ch)
// try to upgraded to latest
// but mean while also make sure the daemon can not be killed by a signal
signal.Notify(ch)
return fn()
}
// This daemon startup has the follow flow:
// 1. Do upgrade to latest version (this might means it needs to restart itself)
// 2. Register the node to BCDB
// 3. start zbus server to serve identity interface
// 4. Start watcher for new version
// 5. On update, re-register the node with new version to BCDB
func main() {
app.Initialize()
var (
broker string
root string
interval int
ver bool
debug bool
id bool
)
flag.StringVar(&root, "root", "/var/cache/modules/identityd", "root working directory of the module")
flag.StringVar(&broker, "broker", redisSocket, "connection string to broker")
flag.IntVar(&interval, "interval", 600, "interval in seconds between update checks, default to 600")
flag.BoolVar(&ver, "v", false, "show version and exit")
flag.BoolVar(&debug, "d", false, "when set, no self update is done before upgradeing")
flag.BoolVar(&id, "id", false, "prints the node ID and exits")
flag.Parse()
if ver {
version.ShowAndExit(false)
}
if id {
ctx := context.Background()
client, err := zbus.NewRedisClient(broker)
if err != nil {
log.Fatal().Err(err).Msg("failed to connect to zbus")
}
stub := stubs.NewIdentityManagerStub(client)
nodeID := stub.NodeID(ctx)
fmt.Println(nodeID)
os.Exit(0)
}
if err := os.MkdirAll(root, 0750); err != nil {
log.Fatal().Err(err).Str("root", root).Msg("failed to create root directory")
}
var boot upgrade.Boot
bootMethod := boot.DetectBootMethod()
// 2. Register the node to BCDB
// at this point we are running latest version
idMgr, err := getIdentityMgr(root)
if err != nil {
log.Fatal().Err(err).Msg("failed to create identity manager")
}
monitor := newVersionMonitor(10 * time.Second)
// 3. start zbus server to serve identity interface
server, err := zbus.NewRedisServer(module, broker, 1)
if err != nil {
log.Fatal().Msgf("fail to connect to message broker server: %v\n", err)
}
server.Register(zbus.ObjectID{Name: "manager", Version: "0.0.1"}, idMgr)
server.Register(zbus.ObjectID{Name: "monitor", Version: "0.0.1"}, monitor)
ctx, cancel := utils.WithSignal(context.Background())
// register the cancel function with defer if the process stops because of a update
defer cancel()
upgrader, err := upgrade.NewUpgrader(root, upgrade.NoSelfUpgrade(debug))
if err != nil {
log.Fatal().Err(err).Msg("failed to initialize upgrader")
}
installBinaries(&boot, upgrader)
go func() {
if err := server.Run(ctx); err != nil && err != context.Canceled {
log.Error().Err(err).Msg("unexpected error")
}
}()
utils.OnDone(ctx, func(_ error) {
log.Info().Msg("received a termination signal")
})
if bootMethod != upgrade.BootMethodFList {
log.Info().Msg("node is not booted from an flist. upgrade is not supported")
<-ctx.Done()
return
}
//NOTE: code after this commit will only
//run if the system is booted from an flist
// 4. Start watcher for new version
log.Info().Msg("start upgrade daemon")
// TODO: do we need to update farmer on node upgrade?
upgradeLoop(ctx, &boot, upgrader, debug, monitor, func(string) error { return nil })
}
// allow reinstall if receive signal USR1
// only allowed in debug mode
func debugReinstall(boot *upgrade.Boot, up *upgrade.Upgrader) {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGUSR1)
go func() {
for range c {
current, err := boot.Current()
if err != nil {
log.Error().Err(err).Msg("couldn't get current flist info")
continue
}
if err := Safe(func() error {
return up.Upgrade(current, current)
}); err != nil {
log.Error().Err(err).Msg("reinstall failed")
} else {
log.Info().Msg("reinstall completed successfully")
}
}
}()
}
func installBinaries(boot *upgrade.Boot, upgrader *upgrade.Upgrader) {
bins, _ := boot.CurrentBins()
env, _ := environment.Get()
repoWatcher := upgrade.FListRepo{
Repo: env.BinRepo,
Current: bins,
}
current, toAdd, toDel, err := repoWatcher.Diff()
if err != nil {
log.Error().Err(err).Msg("failed to list latest binaries to install")
}
for _, pkg := range toDel {
if err := upgrader.UninstallBinary(pkg); err != nil {
log.Error().Err(err).Str("flist", pkg.Fqdn()).Msg("failed to uninstall flist")
}
}
for _, pkg := range toAdd {
if err := upgrader.InstallBinary(pkg); err != nil {
log.Error().Err(err).Str("package", pkg.Fqdn()).Msg("failed to install package")
}
}
boot.SetBins(current)
}
func upgradeLoop(
ctx context.Context,
boot *upgrade.Boot,
upgrader *upgrade.Upgrader,
debug bool,
monitor *monitorStream,
register func(string) error) {
if debug {
debugReinstall(boot, upgrader)
}
var hub upgrade.HubClient
flist := boot.Name()
//current := boot.MustVersion()
for {
// delay in case of error
select {
case <-time.After(5 * time.Second):
case <-ctx.Done():
return
}
current, err := boot.Current()
if err != nil {
log.Fatal().Err(err).Msg("cannot get current boot flist information")
}
latest, err := hub.Info(flist)
if err != nil {
log.Error().Err(err).Msg("failed to get flist info")
continue
}
log.Info().
Str("current", current.TryVersion().String()).
Str("latest", current.TryVersion().String()).
Msg("checking if update is required")
if !latest.TryVersion().GT(current.TryVersion()) {
// We wanted to use the node id to actually calculate the delay to wait but it's not
// possible to get the numeric node id from the identityd
next := time.Duration(60+rand.Intn(60)) * time.Minute
log.Info().Dur("wait", next).Msg("checking for update after milliseconds")
select {
case <-time.After(next):
case <-ctx.Done():
return
}
continue
}
installBinaries(boot, upgrader)
// next check for update
exp := backoff.NewExponentialBackOff()
exp.MaxInterval = 3 * time.Minute
exp.MaxElapsedTime = 60 * time.Minute
err = backoff.Retry(func() error {
log.Debug().Str("version", latest.TryVersion().String()).Msg("trying to update")
err := Safe(func() error {
return upgrader.Upgrade(current, latest)
})
if err == upgrade.ErrRestartNeeded {
return backoff.Permanent(err)
}
if err != nil {
log.Error().Err(err).Msg("update failure. retrying")
}
return err
}, exp)
if err == upgrade.ErrRestartNeeded {
log.Info().Msg("restarting upgraded")
return
} else if err != nil {
//TODO: crash or continue!
log.Error().Err(err).Msg("upgrade failed")
continue
} else {
log.Info().Str("version", latest.TryVersion().String()).Msg("update completed")
}
if err := boot.Set(latest); err != nil {
log.Fatal().Err(err).Msg("failed to update boot information")
}
monitor.C <- latest.TryVersion()
}
}
func getIdentityMgr(root string) (pkg.IdentityManager, error) {
seedPath := filepath.Join(root, seedName)
manager, err := identity.NewManager(seedPath)
if err != nil {
return nil, err
}
env, err := environment.Get()
if err != nil {
return nil, errors.Wrap(err, "failed to parse node environment")
}
nodeID := manager.NodeID()
log.Info().
Str("identity", nodeID.Identity()).
Msg("node identity loaded")
log.Info().
Bool("orphan", env.Orphan).
Uint64("farmer_id", uint64(env.FarmerID)).
Msg("farmer identified")
return manager, nil
}