forked from snapcore/snapd
/
daemon.go
744 lines (644 loc) · 19.4 KB
/
daemon.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2015-2021 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package daemon
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"gopkg.in/tomb.v2"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/netutil"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/standby"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snapdenv"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/systemd"
)
var ErrRestartSocket = fmt.Errorf("daemon stop requested to wait for socket activation")
var systemdSdNotify = systemd.SdNotify
const (
daemonRestartMsg = "daemon is restarting"
systemRestartMsg = "system is restarting"
systemHaltMsg = "system is halting"
systemPoweroffMsg = "system is powering off"
socketRestartMsg = "daemon is stopping to wait for socket activation"
)
// A Daemon listens for requests and routes them to the right command
type Daemon struct {
Version string
overlord *overlord.Overlord
state *state.State
snapdListener net.Listener
snapListener net.Listener
connTracker *connTracker
serve *http.Server
tomb tomb.Tomb
router *mux.Router
standbyOpinions *standby.StandbyOpinions
// set to what kind of restart was requested if any
requestedRestart state.RestartType
// set to remember that we need to exit the daemon in a way that
// prevents systemd from restarting it
restartSocket bool
// degradedErr is set when the daemon is in degraded mode
degradedErr error
expectedRebootDidNotHappen bool
mu sync.Mutex
}
// A ResponseFunc handles one of the individual verbs for a method
type ResponseFunc func(*Command, *http.Request, *auth.UserState) Response
// A Command routes a request to an individual per-verb ResponseFUnc
type Command struct {
Path string
PathPrefix string
//
GET ResponseFunc
PUT ResponseFunc
POST ResponseFunc
// Access control.
ReadAccess accessChecker
WriteAccess accessChecker
d *Daemon
}
func (c *Command) ServeHTTP(w http.ResponseWriter, r *http.Request) {
st := c.d.state
st.Lock()
// TODO Look at the error and fail if there's an attempt to authenticate with invalid data.
user, _ := userFromRequest(st, r)
st.Unlock()
// check if we are in degradedMode
if c.d.degradedErr != nil && r.Method != "GET" {
InternalError(c.d.degradedErr.Error()).ServeHTTP(w, r)
return
}
ucred, err := ucrednetGet(r.RemoteAddr)
if err != nil && err != errNoID {
logger.Noticef("unexpected error when attempting to get UID: %s", err)
InternalError(err.Error()).ServeHTTP(w, r)
return
}
ctx := store.WithClientUserAgent(r.Context(), r)
r = r.WithContext(ctx)
var rspf ResponseFunc
var access accessChecker
switch r.Method {
case "GET":
rspf = c.GET
access = c.ReadAccess
case "PUT":
rspf = c.PUT
access = c.WriteAccess
case "POST":
rspf = c.POST
access = c.WriteAccess
}
if rspf == nil {
MethodNotAllowed("method %q not allowed", r.Method).ServeHTTP(w, r)
return
}
if rspe := access.CheckAccess(c.d, r, ucred, user); rspe != nil {
rspe.ServeHTTP(w, r)
return
}
rsp := rspf(c, r, user)
if srsp, ok := rsp.(StructuredResponse); ok {
rjson := srsp.JSON()
_, rst := st.Restarting()
rjson.addMaintenanceFromRestartType(rst)
if rjson.Type != ResponseTypeError {
st.Lock()
count, stamp := st.WarningsSummary()
st.Unlock()
rjson.addWarningCount(count, stamp)
}
// serve the updated serialisation
rsp = rjson
}
rsp.ServeHTTP(w, r)
}
type wrappedWriter struct {
w http.ResponseWriter
s int
}
func (w *wrappedWriter) Header() http.Header {
return w.w.Header()
}
func (w *wrappedWriter) Write(bs []byte) (int, error) {
return w.w.Write(bs)
}
func (w *wrappedWriter) WriteHeader(s int) {
w.w.WriteHeader(s)
w.s = s
}
func (w *wrappedWriter) Flush() {
if f, ok := w.w.(http.Flusher); ok {
f.Flush()
}
}
func logit(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := &wrappedWriter{w: w}
t0 := time.Now()
handler.ServeHTTP(ww, r)
t := time.Since(t0)
url := r.URL.String()
if !strings.Contains(url, "/changes/") {
logger.Debugf("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s)
}
})
}
// Init sets up the Daemon's internal workings.
// Don't call more than once.
func (d *Daemon) Init() error {
listenerMap, err := netutil.ActivationListeners()
if err != nil {
return err
}
// The SnapdSocket is required-- without it, die.
if listener, err := netutil.GetListener(dirs.SnapdSocket, listenerMap); err == nil {
d.snapdListener = &ucrednetListener{Listener: listener}
} else {
return fmt.Errorf("when trying to listen on %s: %v", dirs.SnapdSocket, err)
}
if listener, err := netutil.GetListener(dirs.SnapSocket, listenerMap); err == nil {
// This listener may also be nil if that socket wasn't among
// the listeners, so check it before using it.
d.snapListener = &ucrednetListener{Listener: listener}
} else {
logger.Debugf("cannot get listener for %q: %v", dirs.SnapSocket, err)
}
d.addRoutes()
logger.Noticef("started %v.", snapdenv.UserAgent())
return nil
}
// SetDegradedMode puts the daemon into an degraded mode which will the
// error given in the "err" argument for commands that are not marked
// as readonlyOK.
//
// This is useful to report errors to the client when the daemon
// cannot work because e.g. a sanity check failed or the system is out
// of diskspace.
//
// When the system is fine again calling "DegradedMode(nil)" is enough
// to put the daemon into full operation again.
func (d *Daemon) SetDegradedMode(err error) {
d.degradedErr = err
}
func (d *Daemon) addRoutes() {
d.router = mux.NewRouter()
for _, c := range api {
c.d = d
if c.PathPrefix == "" {
d.router.Handle(c.Path, c).Name(c.Path)
} else {
d.router.PathPrefix(c.PathPrefix).Handler(c).Name(c.PathPrefix)
}
}
// also maybe add a /favicon.ico handler...
d.router.NotFoundHandler = NotFound("not found")
}
var (
shutdownTimeout = 25 * time.Second
)
type connTracker struct {
mu sync.Mutex
conns map[net.Conn]struct{}
}
func (ct *connTracker) CanStandby() bool {
ct.mu.Lock()
defer ct.mu.Unlock()
return len(ct.conns) == 0
}
func (ct *connTracker) trackConn(conn net.Conn, state http.ConnState) {
ct.mu.Lock()
defer ct.mu.Unlock()
// we ignore hijacked connections, if we do things with websockets
// we'll need custom shutdown handling for them
if state == http.StateNew || state == http.StateActive {
ct.conns[conn] = struct{}{}
} else {
delete(ct.conns, conn)
}
}
func (d *Daemon) initStandbyHandling() {
d.standbyOpinions = standby.New(d.state)
d.standbyOpinions.AddOpinion(d.connTracker)
d.standbyOpinions.AddOpinion(d.overlord)
d.standbyOpinions.AddOpinion(d.overlord.SnapManager())
d.standbyOpinions.AddOpinion(d.overlord.DeviceManager())
d.standbyOpinions.Start()
}
// Start the Daemon
func (d *Daemon) Start() error {
if d.expectedRebootDidNotHappen {
// we need to schedule and wait for a system restart
d.tomb.Kill(nil)
// avoid systemd killing us again while we wait
systemdSdNotify("READY=1")
return nil
}
if d.overlord == nil {
panic("internal error: no Overlord")
}
to, reasoning, err := d.overlord.StartupTimeout()
if err != nil {
return err
}
if to > 0 {
to = to.Round(time.Microsecond)
us := to.Nanoseconds() / 1000
logger.Noticef("adjusting startup timeout by %v (%s)", to, reasoning)
systemdSdNotify(fmt.Sprintf("EXTEND_TIMEOUT_USEC=%d", us))
}
// now perform expensive overlord/manages initiliazation
if err := d.overlord.StartUp(); err != nil {
return err
}
d.connTracker = &connTracker{conns: make(map[net.Conn]struct{})}
d.serve = &http.Server{
Handler: logit(d.router),
ConnState: d.connTracker.trackConn,
}
// enable standby handling
d.initStandbyHandling()
// before serving actual connections remove the maintenance.json file as we
// are no longer down for maintenance, this state most closely corresponds
// to state.RestartUnset
if err := d.updateMaintenanceFile(state.RestartUnset); err != nil {
return err
}
// the loop runs in its own goroutine
d.overlord.Loop()
d.tomb.Go(func() error {
if d.snapListener != nil {
d.tomb.Go(func() error {
if err := d.serve.Serve(d.snapListener); err != http.ErrServerClosed && d.tomb.Err() == tomb.ErrStillAlive {
return err
}
return nil
})
}
if err := d.serve.Serve(d.snapdListener); err != http.ErrServerClosed && d.tomb.Err() == tomb.ErrStillAlive {
return err
}
return nil
})
// notify systemd that we are ready
systemdSdNotify("READY=1")
return nil
}
// HandleRestart implements overlord.RestartBehavior.
func (d *Daemon) HandleRestart(t state.RestartType) {
d.mu.Lock()
defer d.mu.Unlock()
scheduleFallback := func(a rebootAction) {
if err := reboot(a, rebootWaitTimeout); err != nil {
logger.Noticef("%s", err)
}
}
// die when asked to restart (systemd should get us back up!) etc
switch t {
case state.RestartDaemon:
// save the restart kind to write out a maintenance.json in a bit
d.requestedRestart = t
case state.RestartSystem, state.RestartSystemNow:
// try to schedule a fallback slow reboot already here
// in case we get stuck shutting down
// save the restart kind to write out a maintenance.json in a bit
scheduleFallback(rebootReboot)
d.requestedRestart = t
case state.RestartSystemHaltNow:
scheduleFallback(rebootHalt)
d.requestedRestart = t
case state.RestartSystemPoweroffNow:
scheduleFallback(rebootPoweroff)
d.requestedRestart = t
case state.RestartSocket:
// save the restart kind to write out a maintenance.json in a bit
d.requestedRestart = t
d.restartSocket = true
case state.StopDaemon:
logger.Noticef("stopping snapd as requested")
default:
logger.Noticef("internal error: restart handler called with unknown restart type: %v", t)
}
d.tomb.Kill(nil)
}
var (
rebootNoticeWait = 3 * time.Second
rebootWaitTimeout = 10 * time.Minute
rebootRetryWaitTimeout = 5 * time.Minute
rebootMaxTentatives = 3
)
func (d *Daemon) updateMaintenanceFile(rst state.RestartType) error {
// for unset restart, just remove the maintenance.json file
if rst == state.RestartUnset {
err := os.Remove(dirs.SnapdMaintenanceFile)
// only return err if the error was something other than the file not
// existing
if err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// otherwise marshal and write it out appropriately
b, err := json.Marshal(maintenanceForRestartType(rst))
if err != nil {
return err
}
return osutil.AtomicWrite(dirs.SnapdMaintenanceFile, bytes.NewBuffer(b), 0644, 0)
}
// Stop shuts down the Daemon
func (d *Daemon) Stop(sigCh chan<- os.Signal) error {
// we need to schedule/wait for a system restart again
if d.expectedRebootDidNotHappen {
// make the reboot retry immediate
immediateReboot := true
return d.doReboot(sigCh, state.RestartSystem, immediateReboot, rebootRetryWaitTimeout)
}
if d.overlord == nil {
return fmt.Errorf("internal error: no Overlord")
}
d.tomb.Kill(nil)
// check the state associated with a potential restart with the lock to
// prevent races
d.mu.Lock()
// needsFullShutdown is whether the entire system will
// shutdown or not as a consequence of this request
needsFullShutdown := false
switch d.requestedRestart {
case state.RestartSystem, state.RestartSystemNow, state.RestartSystemHaltNow, state.RestartSystemPoweroffNow:
needsFullShutdown = true
}
immediateShutdown := false
switch d.requestedRestart {
case state.RestartSystemNow, state.RestartSystemHaltNow, state.RestartSystemPoweroffNow:
immediateShutdown = true
}
restartSocket := d.restartSocket
d.mu.Unlock()
// before not accepting any new client connections we need to write the
// maintenance.json file for potential clients to see after the daemon stops
// responding so they can read it correctly and handle the maintenance
if err := d.updateMaintenanceFile(d.requestedRestart); err != nil {
logger.Noticef("error writing maintenance file: %v", err)
}
d.snapdListener.Close()
d.standbyOpinions.Stop()
if d.snapListener != nil {
// stop running hooks first
// and do it more gracefully if we are restarting
hookMgr := d.overlord.HookManager()
if ok, _ := d.state.Restarting(); ok {
logger.Noticef("gracefully waiting for running hooks")
hookMgr.GracefullyWaitRunningHooks()
logger.Noticef("done waiting for running hooks")
}
hookMgr.StopHooks()
d.snapListener.Close()
}
if needsFullShutdown {
// give time to polling clients to notice restart
time.Sleep(rebootNoticeWait)
}
// We're using the background context here because the tomb's
// context will likely already have been cancelled when we are
// called.
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
d.tomb.Kill(d.serve.Shutdown(ctx))
cancel()
if !needsFullShutdown {
// tell systemd that we are stopping
systemdSdNotify("STOPPING=1")
}
if restartSocket {
// At this point we processed all open requests (and
// stopped accepting new requests) - before going into
// socket activated mode we need to check if any of
// those open requests resulted in something that
// prevents us from going into socket activation mode.
//
// If this is the case we do a "normal" snapd restart
// to process the new changes.
if !d.standbyOpinions.CanStandby() {
d.restartSocket = false
}
}
d.overlord.Stop()
if err := d.tomb.Wait(); err != nil {
if err == context.DeadlineExceeded {
logger.Noticef("WARNING: cannot gracefully shut down in-flight snapd API activity within: %v", shutdownTimeout)
// the process is shutting down anyway, so we may just
// as well close the active connections right now
d.serve.Close()
} else {
// do not stop the shutdown even if the tomb errors
// because we already scheduled a slow shutdown and
// exiting here will just restart snapd (via systemd)
// which will lead to confusing results.
if needsFullShutdown {
logger.Noticef("WARNING: cannot stop daemon: %v", err)
} else {
return err
}
}
}
if needsFullShutdown {
return d.doReboot(sigCh, d.requestedRestart, immediateShutdown, rebootWaitTimeout)
}
if d.restartSocket {
return ErrRestartSocket
}
return nil
}
func (d *Daemon) rebootDelay(immediate bool) (time.Duration, error) {
d.state.Lock()
defer d.state.Unlock()
now := time.Now()
// see whether a reboot had already been scheduled
var rebootAt time.Time
err := d.state.Get("daemon-system-restart-at", &rebootAt)
if err != nil && err != state.ErrNoState {
return 0, err
}
rebootDelay := 1 * time.Minute
if immediate {
rebootDelay = 0
}
if err == nil {
rebootDelay = rebootAt.Sub(now)
} else {
ovr := os.Getenv("SNAPD_REBOOT_DELAY") // for tests
if ovr != "" && !immediate {
d, err := time.ParseDuration(ovr)
if err == nil {
rebootDelay = d
}
}
rebootAt = now.Add(rebootDelay)
d.state.Set("daemon-system-restart-at", rebootAt)
}
return rebootDelay, nil
}
func (d *Daemon) doReboot(sigCh chan<- os.Signal, rst state.RestartType, immediate bool, waitTimeout time.Duration) error {
rebootDelay, err := d.rebootDelay(immediate)
if err != nil {
return err
}
action := rebootReboot
switch rst {
case state.RestartSystemHaltNow:
action = rebootHalt
case state.RestartSystemPoweroffNow:
action = rebootPoweroff
}
// ask for shutdown and wait for it to happen.
// if we exit snapd will be restared by systemd
if err := reboot(action, rebootDelay); err != nil {
return err
}
// wait for reboot to happen
logger.Noticef("Waiting for %s", action)
if sigCh != nil {
signal.Stop(sigCh)
if len(sigCh) > 0 {
// a signal arrived in between
return nil
}
close(sigCh)
}
time.Sleep(waitTimeout)
return fmt.Errorf("expected %s did not happen", action)
}
var (
shutdownMsg = i18n.G("reboot scheduled to update the system")
haltMsg = i18n.G("system halt scheduled")
poweroffMsg = i18n.G("system poweroff scheduled")
)
type rebootAction int
func (a rebootAction) String() string {
switch a {
case rebootReboot:
return "system reboot"
case rebootHalt:
return "system halt"
case rebootPoweroff:
return "system poweroff"
default:
panic(fmt.Sprintf("unknown reboot action %d", a))
}
}
const (
rebootReboot rebootAction = iota
rebootHalt
rebootPoweroff
)
func rebootImpl(action rebootAction, rebootDelay time.Duration) error {
if rebootDelay < 0 {
rebootDelay = 0
}
mins := int64(rebootDelay / time.Minute)
var arg, msg string
switch action {
case rebootReboot:
arg = "-r"
msg = shutdownMsg
case rebootHalt:
arg = "--halt"
msg = haltMsg
case rebootPoweroff:
arg = "--poweroff"
msg = poweroffMsg
default:
return fmt.Errorf("unknown reboot action: %v", action)
}
cmd := exec.Command("shutdown", arg, fmt.Sprintf("+%d", mins), msg)
if out, err := cmd.CombinedOutput(); err != nil {
return osutil.OutputErr(out, err)
}
return nil
}
var reboot = rebootImpl
// Dying is a tomb-ish thing
func (d *Daemon) Dying() <-chan struct{} {
return d.tomb.Dying()
}
func clearReboot(st *state.State) {
st.Set("daemon-system-restart-at", nil)
st.Set("daemon-system-restart-tentative", nil)
}
// RebootAsExpected implements part of overlord.RestartBehavior.
func (d *Daemon) RebootAsExpected(st *state.State) error {
clearReboot(st)
return nil
}
// RebootDidNotHappen implements part of overlord.RestartBehavior.
func (d *Daemon) RebootDidNotHappen(st *state.State) error {
var nTentative int
err := st.Get("daemon-system-restart-tentative", &nTentative)
if err != nil && err != state.ErrNoState {
return err
}
nTentative++
if nTentative > rebootMaxTentatives {
// giving up, proceed normally, some in-progress refresh
// might get rolled back!!
st.ClearReboot()
clearReboot(st)
logger.Noticef("snapd was restarted while a system restart was expected, snapd retried to schedule and waited again for a system restart %d times and is giving up", rebootMaxTentatives)
return nil
}
st.Set("daemon-system-restart-tentative", nTentative)
d.state = st
logger.Noticef("snapd was restarted while a system restart was expected, snapd will try to schedule and wait for a system restart again (tenative %d/%d)", nTentative, rebootMaxTentatives)
return state.ErrExpectedReboot
}
// New Daemon
func New() (*Daemon, error) {
d := &Daemon{}
ovld, err := overlord.New(d)
if err == state.ErrExpectedReboot {
// we proceed without overlord until we reach Stop
// where we will schedule and wait again for a system restart.
// ATM we cannot do that in New because we need to satisfy
// systemd notify mechanisms.
d.expectedRebootDidNotHappen = true
return d, nil
}
if err != nil {
return nil, err
}
d.overlord = ovld
d.state = ovld.State()
return d, nil
}