forked from snapcore/snapd
/
services.go
1659 lines (1469 loc) · 50.4 KB
/
services.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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-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 wrappers
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/sys"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/randutil"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/quota"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/systemd"
"github.com/snapcore/snapd/timeout"
"github.com/snapcore/snapd/timeutil"
"github.com/snapcore/snapd/timings"
"github.com/snapcore/snapd/usersession/client"
)
type interacter interface {
Notify(status string)
}
// wait this time between TERM and KILL
var killWait = 5 * time.Second
func serviceStopTimeout(app *snap.AppInfo) time.Duration {
tout := app.StopTimeout
if tout == 0 {
tout = timeout.DefaultTimeout
}
return time.Duration(tout)
}
// TODO: this should not accept AddSnapServicesOptions, it should use some other
// subset of options, specifically it should not accept Preseeding as an option
// here
func generateSnapServiceFile(app *snap.AppInfo, opts *AddSnapServicesOptions) ([]byte, error) {
if err := snap.ValidateApp(app); err != nil {
return nil, err
}
return genServiceFile(app, opts)
}
// generateGroupSliceFile generates a systemd slice unit definition for the
// specified quota group.
func generateGroupSliceFile(grp *quota.Group) ([]byte, error) {
buf := bytes.Buffer{}
template := `[Unit]
Description=Slice for snap quota group %[1]s
Before=slices.target
X-Snappy=yes
[Slice]
# Always enable memory accounting otherwise the MemoryMax setting does nothing.
MemoryAccounting=true
MemoryMax=%[2]d
# for compatibility with older versions of systemd
MemoryLimit=%[2]d
# Always enable task accounting in order to be able to count the processes/
# threads, etc for a slice
TasksAccounting=true
`
fmt.Fprintf(&buf, template, grp.Name, grp.MemoryLimit)
return buf.Bytes(), nil
}
func stopUserServices(cli *client.Client, inter interacter, services ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout.DefaultTimeout))
defer cancel()
failures, err := cli.ServicesStop(ctx, services)
for _, f := range failures {
inter.Notify(fmt.Sprintf("Could not stop service %q for uid %d: %s", f.Service, f.Uid, f.Error))
}
return err
}
func startUserServices(cli *client.Client, inter interacter, services ...string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout.DefaultTimeout))
defer cancel()
startFailures, stopFailures, err := cli.ServicesStart(ctx, services)
for _, f := range startFailures {
inter.Notify(fmt.Sprintf("Could not start service %q for uid %d: %s", f.Service, f.Uid, f.Error))
}
for _, f := range stopFailures {
inter.Notify(fmt.Sprintf("While trying to stop previously started service %q for uid %d: %s", f.Service, f.Uid, f.Error))
}
return err
}
func stopService(sysd systemd.Systemd, app *snap.AppInfo, inter interacter) error {
serviceName := app.ServiceName()
tout := serviceStopTimeout(app)
var extraServices []string
for _, socket := range app.Sockets {
extraServices = append(extraServices, filepath.Base(socket.File()))
}
if app.Timer != nil {
extraServices = append(extraServices, filepath.Base(app.Timer.File()))
}
switch app.DaemonScope {
case snap.SystemDaemon:
stopErrors := []error{}
for _, service := range extraServices {
if err := sysd.Stop(service, tout); err != nil {
stopErrors = append(stopErrors, err)
}
}
if err := sysd.Stop(serviceName, tout); err != nil {
if !systemd.IsTimeout(err) {
return err
}
inter.Notify(fmt.Sprintf("%s refused to stop, killing.", serviceName))
// ignore errors for kill; nothing we'd do differently at this point
sysd.Kill(serviceName, "TERM", "")
time.Sleep(killWait)
sysd.Kill(serviceName, "KILL", "")
}
if len(stopErrors) > 0 {
return stopErrors[0]
}
case snap.UserDaemon:
extraServices = append(extraServices, serviceName)
cli := client.New()
return stopUserServices(cli, inter, extraServices...)
}
return nil
}
// enableServices enables services specified by apps. On success the returned
// disable function can be used to undo all the actions. On error all the
// services get disabled automatically (disable is nil).
func enableServices(apps []*snap.AppInfo, inter interacter) (disable func(), err error) {
var enabled []string
var userEnabled []string
systemSysd := systemd.New(systemd.SystemMode, inter)
userSysd := systemd.New(systemd.GlobalUserMode, inter)
disableEnabledServices := func() {
for _, srvName := range enabled {
if e := systemSysd.Disable(srvName); e != nil {
inter.Notify(fmt.Sprintf("While trying to disable previously enabled service %q: %v", srvName, e))
}
}
for _, s := range userEnabled {
if e := userSysd.Disable(s); e != nil {
inter.Notify(fmt.Sprintf("while trying to disable %s due to previous failure: %v", s, e))
}
}
}
defer func() {
if err != nil {
disableEnabledServices()
}
}()
for _, app := range apps {
var sysd systemd.Systemd
switch app.DaemonScope {
case snap.SystemDaemon:
sysd = systemSysd
case snap.UserDaemon:
sysd = userSysd
}
svcName := app.ServiceName()
switch app.DaemonScope {
case snap.SystemDaemon:
if err = sysd.Enable(svcName); err != nil {
return nil, err
}
enabled = append(enabled, svcName)
case snap.UserDaemon:
if err = userSysd.Enable(svcName); err != nil {
return nil, err
}
userEnabled = append(userEnabled, svcName)
}
}
return disableEnabledServices, nil
}
// StartServicesFlags carries extra flags for StartServices.
type StartServicesFlags struct {
Enable bool
}
// StartServices starts service units for the applications from the snap which
// are services. Service units will be started in the order provided by the
// caller.
func StartServices(apps []*snap.AppInfo, disabledSvcs []string, flags *StartServicesFlags, inter interacter, tm timings.Measurer) (err error) {
if flags == nil {
flags = &StartServicesFlags{}
}
systemSysd := systemd.New(systemd.SystemMode, inter)
userSysd := systemd.New(systemd.GlobalUserMode, inter)
cli := client.New()
var disableEnabledServices func()
defer func() {
if err == nil {
return
}
if disableEnabledServices != nil {
disableEnabledServices()
}
}()
var toEnable []*snap.AppInfo
systemServices := make([]string, 0, len(apps))
userServices := make([]string, 0, len(apps))
// gather all non-sockets, non-timers, and non-dbus activated
// services to enable first
for _, app := range apps {
// they're *supposed* to be all services, but checking doesn't hurt
if !app.IsService() {
continue
}
// sockets and timers are enabled and started separately (and unconditionally) further down.
// dbus activatable services are started on first use.
if len(app.Sockets) == 0 && app.Timer == nil && len(app.ActivatesOn) == 0 {
if strutil.ListContains(disabledSvcs, app.Name) {
continue
}
svcName := app.ServiceName()
switch app.DaemonScope {
case snap.SystemDaemon:
systemServices = append(systemServices, svcName)
case snap.UserDaemon:
userServices = append(userServices, svcName)
}
if flags.Enable {
toEnable = append(toEnable, app)
}
}
}
timings.Run(tm, "enable-services", fmt.Sprintf("enable services %q", toEnable), func(nested timings.Measurer) {
disableEnabledServices, err = enableServices(toEnable, inter)
})
if err != nil {
return err
}
// handle sockets and timers
for _, app := range apps {
// they're *supposed* to be all services, but checking doesn't hurt
if !app.IsService() {
continue
}
var sysd systemd.Systemd
switch app.DaemonScope {
case snap.SystemDaemon:
sysd = systemSysd
case snap.UserDaemon:
sysd = userSysd
}
defer func(app *snap.AppInfo) {
if err == nil {
return
}
if e := stopService(sysd, app, inter); e != nil {
inter.Notify(fmt.Sprintf("While trying to stop previously started service %q: %v", app.ServiceName(), e))
}
for _, socket := range app.Sockets {
socketService := filepath.Base(socket.File())
if e := sysd.Disable(socketService); e != nil {
inter.Notify(fmt.Sprintf("While trying to disable previously enabled socket service %q: %v", socketService, e))
}
}
if app.Timer != nil {
timerService := filepath.Base(app.Timer.File())
if e := sysd.Disable(timerService); e != nil {
inter.Notify(fmt.Sprintf("While trying to disable previously enabled timer service %q: %v", timerService, e))
}
}
}(app)
for _, socket := range app.Sockets {
socketService := filepath.Base(socket.File())
// enable the socket
if err = sysd.Enable(socketService); err != nil {
return err
}
switch app.DaemonScope {
case snap.SystemDaemon:
timings.Run(tm, "start-system-socket-service", fmt.Sprintf("start system socket service %q", socketService), func(nested timings.Measurer) {
err = sysd.Start(socketService)
})
case snap.UserDaemon:
timings.Run(tm, "start-user-socket-service", fmt.Sprintf("start user socket service %q", socketService), func(nested timings.Measurer) {
err = startUserServices(cli, inter, socketService)
})
}
if err != nil {
return err
}
}
if app.Timer != nil {
timerService := filepath.Base(app.Timer.File())
// enable the timer
if err = sysd.Enable(timerService); err != nil {
return err
}
switch app.DaemonScope {
case snap.SystemDaemon:
timings.Run(tm, "start-system-timer-service", fmt.Sprintf("start system timer service %q", timerService), func(nested timings.Measurer) {
err = sysd.Start(timerService)
})
case snap.UserDaemon:
timings.Run(tm, "start-user-timer-service", fmt.Sprintf("start user timer service %q", timerService), func(nested timings.Measurer) {
err = startUserServices(cli, inter, timerService)
})
}
if err != nil {
return err
}
}
}
for _, srv := range systemServices {
// starting all services at once does not create a single
// transaction, but instead spawns multiple jobs, make sure the
// services started in the original order by bring them up one
// by one, see:
// https://github.com/systemd/systemd/issues/8102
// https://lists.freedesktop.org/archives/systemd-devel/2018-January/040152.html
timings.Run(tm, "start-service", fmt.Sprintf("start service %q", srv), func(nested timings.Measurer) {
err = systemSysd.Start(srv)
})
if err != nil {
// cleanup was set up by iterating over apps
return err
}
}
if len(userServices) != 0 {
timings.Run(tm, "start-user-services", "start user services", func(nested timings.Measurer) {
err = startUserServices(cli, inter, userServices...)
})
if err != nil {
return err
}
}
return nil
}
func userDaemonReload() error {
cli := client.New()
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout.DefaultTimeout))
defer cancel()
return cli.ServicesDaemonReload(ctx)
}
func tryFileUpdate(path string, desiredContent []byte) (old *osutil.MemoryFileState, modified bool, err error) {
newFileState := osutil.MemoryFileState{
Content: desiredContent,
Mode: os.FileMode(0644),
}
// get the existing content (if any) of the file to have something to
// rollback to if we have any errors
// note we can't use FileReference here since we may be modifying
// the file, and the FileReference.State() wouldn't be evaluated
// until _after_ we attempted modification
oldFileState := osutil.MemoryFileState{}
if st, err := os.Stat(path); err == nil {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, false, err
}
oldFileState.Content = b
oldFileState.Mode = st.Mode()
newFileState.Mode = st.Mode()
// save the old state of the file
old = &oldFileState
}
if mkdirErr := os.MkdirAll(filepath.Dir(path), 0755); mkdirErr != nil {
return nil, false, mkdirErr
}
ensureErr := osutil.EnsureFileState(path, &newFileState)
switch ensureErr {
case osutil.ErrSameState:
// didn't change the file
return old, false, nil
case nil:
// we successfully modified the file
return old, true, nil
default:
// some other fatal error trying to write the file
return nil, false, ensureErr
}
}
type SnapServiceOptions struct {
// VitalityRank is the rank of all services in the specified snap used by
// the OOM killer when OOM conditions are reached.
VitalityRank int
// QuotaGroup is the quota group for all services in the specified snap.
QuotaGroup *quota.Group
}
// ObserveChangeCallback can be invoked by EnsureSnapServices to observe
// the previous content of a unit and the new on a change.
// unitType can be "service", "socket", "timer". name is empty for a timer.
type ObserveChangeCallback func(app *snap.AppInfo, grp *quota.Group, unitType string, name, old, new string)
// EnsureSnapServicesOptions is the set of options applying to the
// EnsureSnapServices operation. It does not include per-snap specific options
// such as VitalityRank or RequireMountedSnapdSnap from AddSnapServiceOptions,
// since those are expected to be provided in the snaps argument.
type EnsureSnapServicesOptions struct {
// Preseeding is whether the system is currently being preseeded, in which
// case there is not a running systemd for EnsureSnapServicesOptions to
// issue commands like systemctl daemon-reload to.
Preseeding bool
// RequireMountedSnapdSnap is whether the generated units should depend on
// the snapd snap being mounted, this is specific to systems like UC18 and
// UC20 which have the snapd snap and need to have units generated
RequireMountedSnapdSnap bool
}
// EnsureSnapServices will ensure that the specified snap services' file states
// are up to date with the specified options and infos. It will add new services
// if those units don't already exist, but it does not delete existing service
// units that are not present in the snap's Info structures.
// There are two sets of options; there are global options which apply to the
// entire transaction and to every snap service that is ensured, and options
// which are per-snap service and specified in the map argument.
// If any errors are encountered trying to update systemd units, then all
// changes performed up to that point are rolled back, meaning newly written
// units are deleted and modified units are attempted to be restored to their
// previous state.
// To observe which units were added or modified a
// ObserveChangeCallback calllback can be provided. The callback is
// invoked while processing the changes. Because of that it should not
// produce immediate side-effects, as the changes are in effect only
// if the function did not return an error.
// This function is idempotent.
func EnsureSnapServices(snaps map[*snap.Info]*SnapServiceOptions, opts *EnsureSnapServicesOptions, observeChange ObserveChangeCallback, inter interacter) (err error) {
// note, sysd is not used when preseeding
sysd := systemd.New(systemd.SystemMode, inter)
if opts == nil {
opts = &EnsureSnapServicesOptions{}
}
// we only consider the global EnsureSnapServicesOptions to decide if we
// are preseeding or not to reduce confusion about which set of options
// determines whether we are preseeding or not during the ensure operation
preseeding := opts.Preseeding
// modifiedUnitsPreviousState is the set of units that were modified and the previous
// state of the unit before modification that we can roll back to if there
// are any issues.
// note that the rollback is best effort, if we are rebooted in the middle,
// there is no guarantee about the state of files, some may have been
// updated and some may have been rolled back, higher level tasks/changes
// should have do/undo handlers to properly handle the case where this
// function is interrupted midway
modifiedUnitsPreviousState := make(map[string]*osutil.MemoryFileState)
var modifiedSystem, modifiedUser bool
defer func() {
if err == nil {
return
}
for file, state := range modifiedUnitsPreviousState {
if state == nil {
// we don't have anything to rollback to, so just remove the
// file
if e := os.Remove(file); e != nil {
inter.Notify(fmt.Sprintf("while trying to remove %s due to previous failure: %v", file, e))
}
} else {
// rollback the file to the previous state
if e := osutil.EnsureFileState(file, state); e != nil {
inter.Notify(fmt.Sprintf("while trying to rollback %s due to previous failure: %v", file, e))
}
}
}
if modifiedSystem && !preseeding {
if e := sysd.DaemonReload(); e != nil {
inter.Notify(fmt.Sprintf("while trying to perform systemd daemon-reload due to previous failure: %v", e))
}
}
if modifiedUser && !preseeding {
if e := userDaemonReload(); e != nil {
inter.Notify(fmt.Sprintf("while trying to perform user systemd daemon-reload due to previous failure: %v", e))
}
}
}()
handleFileModification := func(app *snap.AppInfo, unitType string, name, path string, content []byte) error {
old, modifiedFile, err := tryFileUpdate(path, content)
if err != nil {
return err
}
if modifiedFile {
if observeChange != nil {
var oldContent []byte
if old != nil {
oldContent = old.Content
}
observeChange(app, nil, unitType, name, string(oldContent), string(content))
}
modifiedUnitsPreviousState[path] = old
// also mark that we need to reload either the system or
// user instance of systemd
switch app.DaemonScope {
case snap.SystemDaemon:
modifiedSystem = true
case snap.UserDaemon:
modifiedUser = true
}
}
return nil
}
neededQuotaGrps := "a.QuotaGroupSet{}
for s, snapSvcOpts := range snaps {
if s.Type() == snap.TypeSnapd {
return fmt.Errorf("internal error: adding explicit services for snapd snap is unexpected")
}
// always use RequireMountedSnapdSnap options from the global options
genServiceOpts := &AddSnapServicesOptions{
RequireMountedSnapdSnap: opts.RequireMountedSnapdSnap,
}
if snapSvcOpts != nil {
// and if there are per-snap options specified, use that for
// VitalityRank
genServiceOpts.VitalityRank = snapSvcOpts.VitalityRank
genServiceOpts.QuotaGroup = snapSvcOpts.QuotaGroup
if snapSvcOpts.QuotaGroup != nil {
if err := neededQuotaGrps.AddAllNecessaryGroups(snapSvcOpts.QuotaGroup); err != nil {
// this error can basically only be a circular reference
// in the quota group tree
return err
}
}
}
// note that the Preseeding option is not used here at all
for _, app := range s.Apps {
if !app.IsService() {
continue
}
// create services first; this doesn't trigger systemd
// Generate new service file state
path := app.ServiceFile()
content, err := generateSnapServiceFile(app, genServiceOpts)
if err != nil {
return err
}
if err := handleFileModification(app, "service", app.Name, path, content); err != nil {
return err
}
// Generate systemd .socket files if needed
socketFiles, err := generateSnapSocketFiles(app)
if err != nil {
return err
}
for name, content := range socketFiles {
path := app.Sockets[name].File()
if err := handleFileModification(app, "socket", name, path, content); err != nil {
return err
}
}
if app.Timer != nil {
content, err := generateSnapTimerFile(app)
if err != nil {
return err
}
path := app.Timer.File()
if err := handleFileModification(app, "timer", "", path, content); err != nil {
return err
}
}
}
}
handleSliceModification := func(grp *quota.Group, path string, content []byte) error {
old, modifiedFile, err := tryFileUpdate(path, content)
if err != nil {
return err
}
if modifiedFile {
if observeChange != nil {
var oldContent []byte
if old != nil {
oldContent = old.Content
}
observeChange(nil, grp, "slice", grp.Name, string(oldContent), string(content))
}
modifiedUnitsPreviousState[path] = old
// also mark that we need to reload the system instance of systemd
// TODO: also handle reloading the user instance of systemd when
// needed
modifiedSystem = true
}
return nil
}
// now make sure that all of the slice units exist
for _, grp := range neededQuotaGrps.AllQuotaGroups() {
content, err := generateGroupSliceFile(grp)
if err != nil {
return err
}
sliceFileName := grp.SliceFileName()
path := filepath.Join(dirs.SnapServicesDir, sliceFileName)
if err := handleSliceModification(grp, path, content); err != nil {
return err
}
}
if !preseeding {
if modifiedSystem {
if err = sysd.DaemonReload(); err != nil {
return err
}
}
if modifiedUser {
if err = userDaemonReload(); err != nil {
return err
}
}
}
return nil
}
// AddSnapServicesOptions is a struct for controlling the generated service
// definition for a snap service.
type AddSnapServicesOptions struct {
// VitalityRank is the rank of all services in the specified snap used by
// the OOM killer when OOM conditions are reached.
VitalityRank int
// QuotaGroup is the quota group for all services in the specified snap.
QuotaGroup *quota.Group
// RequireMountedSnapdSnap is whether the generated units should depend on
// the snapd snap being mounted, this is specific to systems like UC18 and
// UC20 which have the snapd snap and need to have units generated
RequireMountedSnapdSnap bool
// Preseeding is whether the system is currently being preseeded, in which
// case there is not a running systemd for EnsureSnapServicesOptions to
// issue commands like systemctl daemon-reload to.
Preseeding bool
}
// AddSnapServices adds service units for the applications from the snap which
// are services. The services do not get enabled or started.
func AddSnapServices(s *snap.Info, opts *AddSnapServicesOptions, inter interacter) error {
m := map[*snap.Info]*SnapServiceOptions{
s: {},
}
ensureOpts := &EnsureSnapServicesOptions{}
if opts != nil {
// set the per-snap service options
m[s].VitalityRank = opts.VitalityRank
m[s].QuotaGroup = opts.QuotaGroup
// copy the globally applicable opts from AddSnapServicesOptions to
// EnsureSnapServicesOptions, since those options override the per-snap opts
// we put in the map argument
ensureOpts.Preseeding = opts.Preseeding
ensureOpts.RequireMountedSnapdSnap = opts.RequireMountedSnapdSnap
}
return EnsureSnapServices(m, ensureOpts, nil, inter)
}
// StopServicesFlags carries extra flags for StopServices.
type StopServicesFlags struct {
Disable bool
}
// StopServices stops and optionally disables service units for the applications
// from the snap which are services.
func StopServices(apps []*snap.AppInfo, flags *StopServicesFlags, reason snap.ServiceStopReason, inter interacter, tm timings.Measurer) error {
sysd := systemd.New(systemd.SystemMode, inter)
if flags == nil {
flags = &StopServicesFlags{}
}
if reason != snap.StopReasonOther {
logger.Debugf("StopServices called for %q, reason: %v", apps, reason)
} else {
logger.Debugf("StopServices called for %q", apps)
}
for _, app := range apps {
// Handle the case where service file doesn't exist and don't try to stop it as it will fail.
// This can happen with snap try when snap.yaml is modified on the fly and a daemon line is added.
if !app.IsService() || !osutil.FileExists(app.ServiceFile()) {
continue
}
// Skip stop on refresh when refresh mode is set to something
// other than "restart" (or "" which is the same)
if reason == snap.StopReasonRefresh {
logger.Debugf(" %s refresh-mode: %v", app.Name, app.StopMode)
switch app.RefreshMode {
case "endure":
// skip this service
continue
}
}
var err error
timings.Run(tm, "stop-service", fmt.Sprintf("stop service %q", app.ServiceName()), func(nested timings.Measurer) {
err = stopService(sysd, app, inter)
if err == nil && flags.Disable {
err = sysd.Disable(app.ServiceName())
}
})
if err != nil {
return err
}
// ensure the service is really stopped on remove regardless
// of stop-mode
if reason == snap.StopReasonRemove && !app.StopMode.KillAll() && app.DaemonScope == snap.SystemDaemon {
// FIXME: make this smarter and avoid the killWait
// delay if not needed (i.e. if all processes
// have died)
sysd.Kill(app.ServiceName(), "TERM", "all")
time.Sleep(killWait)
sysd.Kill(app.ServiceName(), "KILL", "")
}
}
return nil
}
// ServicesEnableState returns a map of service names from the given snap,
// together with their enable/disable status.
func ServicesEnableState(s *snap.Info, inter interacter) (map[string]bool, error) {
sysd := systemd.New(systemd.SystemMode, inter)
// loop over all services in the snap, querying systemd for the current
// systemd state of the snaps
snapSvcsState := make(map[string]bool, len(s.Apps))
for name, app := range s.Apps {
if !app.IsService() {
continue
}
// FIXME: handle user daemons
if app.DaemonScope != snap.SystemDaemon {
continue
}
state, err := sysd.IsEnabled(app.ServiceName())
if err != nil {
return nil, err
}
snapSvcsState[name] = state
}
return snapSvcsState, nil
}
// RemoveQuotaGroup ensures that the slice file for a quota group is removed. It
// assumes that the slice corresponding to the group is not in use anymore by
// any services or sub-groups of the group when it is invoked. To remove a group
// with sub-groups, one must remove all the sub-groups first.
// This function is idempotent, if the slice file doesn't exist no error is
// returned.
func RemoveQuotaGroup(grp *quota.Group, inter interacter) error {
// TODO: it only works on leaf sub-groups currently
if len(grp.SubGroups) != 0 {
return fmt.Errorf("internal error: cannot remove quota group with sub-groups")
}
systemSysd := systemd.New(systemd.SystemMode, inter)
// remove the slice file
err := os.Remove(filepath.Join(dirs.SnapServicesDir, grp.SliceFileName()))
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
// we deleted the slice unit, so we need to daemon-reload
if err := systemSysd.DaemonReload(); err != nil {
return err
}
}
return nil
}
// RemoveSnapServices disables and removes service units for the applications
// from the snap which are services. The optional flag indicates whether
// services are removed as part of undoing of first install of a given snap.
func RemoveSnapServices(s *snap.Info, inter interacter) error {
if s.Type() == snap.TypeSnapd {
return fmt.Errorf("internal error: removing explicit services for snapd snap is unexpected")
}
systemSysd := systemd.New(systemd.SystemMode, inter)
userSysd := systemd.New(systemd.GlobalUserMode, inter)
var removedSystem, removedUser bool
for _, app := range s.Apps {
if !app.IsService() || !osutil.FileExists(app.ServiceFile()) {
continue
}
var sysd systemd.Systemd
switch app.DaemonScope {
case snap.SystemDaemon:
sysd = systemSysd
removedSystem = true
case snap.UserDaemon:
sysd = userSysd
removedUser = true
}
serviceName := filepath.Base(app.ServiceFile())
for _, socket := range app.Sockets {
path := socket.File()
socketServiceName := filepath.Base(path)
if err := sysd.Disable(socketServiceName); err != nil {
return err
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
logger.Noticef("Failed to remove socket file %q for %q: %v", path, serviceName, err)
}
}
if app.Timer != nil {
path := app.Timer.File()
timerName := filepath.Base(path)
if err := sysd.Disable(timerName); err != nil {
return err
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
logger.Noticef("Failed to remove timer file %q for %q: %v", path, serviceName, err)
}
}
if err := sysd.Disable(serviceName); err != nil {
return err
}
if err := os.Remove(app.ServiceFile()); err != nil && !os.IsNotExist(err) {
logger.Noticef("Failed to remove service file for %q: %v", serviceName, err)
}
}
// only reload if we actually had services
if removedSystem {
if err := systemSysd.DaemonReload(); err != nil {
return err
}
}
if removedUser {
if err := userDaemonReload(); err != nil {
return err
}
}
return nil
}
func genServiceNames(snap *snap.Info, appNames []string) []string {
names := make([]string, 0, len(appNames))
for _, name := range appNames {
if app := snap.Apps[name]; app != nil {
names = append(names, app.ServiceName())
}
}
return names
}
// TODO: this should not accept AddSnapServicesOptions, it should use some other
// subset of options, specifically it should not accept Preseeding as an option
// here
func genServiceFile(appInfo *snap.AppInfo, opts *AddSnapServicesOptions) ([]byte, error) {
if opts == nil {
opts = &AddSnapServicesOptions{}
}
// assemble all of the service directive snippets for all interfaces that
// this service needs to include in the generated systemd file
// use an ordered set to ensure we don't duplicate any keys from interfaces
// that specify the same snippet
// TODO: maybe we should error if multiple interfaces specify different
// values for the same directive, otherwise one of them will overwrite the
// other? What happens right now is that the snippet from the plug that
// comes last will win in the case of directives that can have only one
// value, but for some directives, systemd combines their values into a
// list.
ifaceServiceSnippets := &strutil.OrderedSet{}
for _, plug := range appInfo.Plugs {
iface, err := interfaces.ByName(plug.Interface)
if err != nil {
return nil, fmt.Errorf("error processing plugs while generating service unit for %v: %v", appInfo.SecurityTag(), err)
}
snips, err := interfaces.PermanentPlugServiceSnippets(iface, plug)
if err != nil {
return nil, fmt.Errorf("error processing plugs while generating service unit for %v: %v", appInfo.SecurityTag(), err)
}
for _, snip := range snips {
ifaceServiceSnippets.Put(snip)
}
}
// join the service snippets into one string to be included in the
// template
ifaceSpecifiedServiceSnippet := strings.Join(ifaceServiceSnippets.Items(), "\n")
serviceTemplate := `[Unit]
# Auto-generated, DO NOT EDIT
Description=Service for snap application {{.App.Snap.InstanceName}}.{{.App.Name}}