-
Notifications
You must be signed in to change notification settings - Fork 583
/
services.go
1190 lines (1074 loc) · 34.7 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-2016 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"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/snapcore/snapd/dirs"
"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/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)
}
func generateSnapServiceFile(app *snap.AppInfo, opts *AddSnapServicesOptions) ([]byte, error) {
if err := snap.ValidateApp(app); err != nil {
return nil, err
}
return genServiceFile(app, opts), 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
}
// 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, inter interacter, tm timings.Measurer) (err error) {
systemSysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, inter)
userSysd := systemd.New(dirs.GlobalRootDir, systemd.GlobalUserMode, inter)
cli := client.New()
systemServices := make([]string, 0, len(apps))
userServices := make([]string, 0, len(apps))
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)
if len(app.Sockets) == 0 && app.Timer == nil && app.Daemon != "dbus" {
// check if the service is disabled, if so don't start it up
// this could happen for example if the service was disabled in
// the install hook by snapctl or if the service was disabled in
// the previous installation
isEnabled, err := sysd.IsEnabled(app.ServiceName())
if err != nil {
return err
}
if isEnabled {
switch app.DaemonScope {
case snap.SystemDaemon:
systemServices = append(systemServices, app.ServiceName())
case snap.UserDaemon:
userServices = append(userServices, app.ServiceName())
}
}
}
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)
}
type AddSnapServicesOptions struct {
Preseeding bool
VitalityRank int
}
// AddSnapServices adds service units for the applications from the snap which are services.
func AddSnapServices(s *snap.Info, disabledSvcs []string, opts *AddSnapServicesOptions, inter interacter) (err error) {
if s.GetType() == snap.TypeSnapd {
return fmt.Errorf("internal error: adding explicit services for snapd snap is unexpected")
}
if opts == nil {
opts = &AddSnapServicesOptions{}
}
// check if any previously disabled services are now no longer services and
// log messages about that
for _, svc := range disabledSvcs {
app, ok := s.Apps[svc]
if !ok {
logger.Noticef("previously disabled service %s no longer exists", svc)
} else if !app.IsService() {
logger.Noticef("previously disabled service %s is now an app and not a service", svc)
}
}
// TODO: remove once services get enabled on start and not when created.
preseeding := opts.Preseeding
sysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, inter)
userSysd := systemd.New(dirs.GlobalRootDir, systemd.GlobalUserMode, inter)
var written []string
var writtenSystem, writtenUser bool
var enabled []string
var userEnabled []string
defer func() {
if err == nil {
return
}
for _, s := range enabled {
if e := sysd.Disable(s); e != nil {
inter.Notify(fmt.Sprintf("while trying to disable %s due to previous failure: %v", s, 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))
}
}
for _, s := range written {
if e := os.Remove(s); e != nil {
inter.Notify(fmt.Sprintf("while trying to remove %s due to previous failure: %v", s, e))
}
}
if writtenSystem && !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 writtenUser && !preseeding {
if e := userDaemonReload(); e != nil {
inter.Notify(fmt.Sprintf("while trying to perform user systemd daemon-reload due to previous failure: %v", e))
}
}
}()
for _, app := range s.Apps {
if !app.IsService() {
continue
}
// Generate service file
content, err := generateSnapServiceFile(app, opts)
if err != nil {
return err
}
svcFilePath := app.ServiceFile()
os.MkdirAll(filepath.Dir(svcFilePath), 0755)
if err := osutil.AtomicWriteFile(svcFilePath, content, 0644, 0); err != nil {
return err
}
written = append(written, svcFilePath)
switch app.DaemonScope {
case snap.SystemDaemon:
writtenSystem = true
case snap.UserDaemon:
writtenUser = true
}
// Generate systemd .socket files if needed
socketFiles, err := generateSnapSocketFiles(app)
if err != nil {
return err
}
for path, content := range *socketFiles {
os.MkdirAll(filepath.Dir(path), 0755)
if err := osutil.AtomicWriteFile(path, content, 0644, 0); err != nil {
return err
}
written = append(written, path)
}
if app.Timer != nil {
content, err := generateSnapTimerFile(app)
if err != nil {
return err
}
path := app.Timer.File()
os.MkdirAll(filepath.Dir(path), 0755)
if err := osutil.AtomicWriteFile(path, content, 0644, 0); err != nil {
return err
}
written = append(written, path)
}
if app.Timer != nil || len(app.Sockets) != 0 || app.Daemon == "dbus" {
// service is dbus, socket, or timer activated,
// not during the boot
continue
}
svcName := app.ServiceName()
switch app.DaemonScope {
case snap.SystemDaemon:
if strutil.ListContains(disabledSvcs, app.Name) {
// service is disabled, nothing to do
continue
}
if !preseeding {
if err := sysd.Enable(svcName); err != nil {
return err
}
enabled = append(enabled, svcName)
}
case snap.UserDaemon:
if !preseeding {
if err := userSysd.Enable(svcName); err != nil {
return err
}
userEnabled = append(userEnabled, svcName)
}
}
}
if !preseeding {
if writtenSystem {
if err := sysd.DaemonReload(); err != nil {
return err
}
}
if writtenUser {
if err := userDaemonReload(); err != nil {
return err
}
}
}
return nil
}
// EnableSnapServices enables all services of the snap; the main use case for this is
// the first boot of a pre-seeded image with service files already in place but not enabled.
// XXX: it should go away once services are fixed and enabled on start.
func EnableSnapServices(s *snap.Info, inter interacter) (err error) {
sysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, inter)
for _, app := range s.Apps {
if app.IsService() {
svcName := app.ServiceName()
if err := sysd.Enable(svcName); err != nil {
return err
}
}
}
return nil
}
// StopServices stops service units for the applications from the snap which are services.
func StopServices(apps []*snap.AppInfo, reason snap.ServiceStopReason, inter interacter, tm timings.Measurer) error {
sysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, inter)
logger.Debugf("StopServices called for %q, reason: %v", apps, reason)
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 {
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(dirs.GlobalRootDir, 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
}
// 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.GetType() == snap.TypeSnapd {
return fmt.Errorf("internal error: removing explicit services for snapd snap is unexpected")
}
systemSysd := systemd.New(dirs.GlobalRootDir, systemd.SystemMode, inter)
userSysd := systemd.New(dirs.GlobalRootDir, 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
}
func genServiceFile(appInfo *snap.AppInfo, opts *AddSnapServicesOptions) []byte {
if opts == nil {
opts = &AddSnapServicesOptions{}
}
serviceTemplate := `[Unit]
# Auto-generated, DO NOT EDIT
Description=Service for snap application {{.App.Snap.InstanceName}}.{{.App.Name}}
{{- if .MountUnit }}
Requires={{.MountUnit}}
{{- end }}
{{- if .PrerequisiteTarget}}
Wants={{.PrerequisiteTarget}}
{{- end}}
{{- if .After}}
After={{ stringsJoin .After " " }}
{{- end}}
{{- if .Before}}
Before={{ stringsJoin .Before " "}}
{{- end}}
X-Snappy=yes
[Service]
EnvironmentFile=-/etc/environment
ExecStart={{.App.LauncherCommand}}
SyslogIdentifier={{.App.Snap.InstanceName}}.{{.App.Name}}
Restart={{.Restart}}
{{- if .App.RestartDelay}}
RestartSec={{.App.RestartDelay.Seconds}}
{{- end}}
WorkingDirectory={{.WorkingDir}}
{{- if .App.StopCommand}}
ExecStop={{.App.LauncherStopCommand}}
{{- end}}
{{- if .App.ReloadCommand}}
ExecReload={{.App.LauncherReloadCommand}}
{{- end}}
{{- if .App.PostStopCommand}}
ExecStopPost={{.App.LauncherPostStopCommand}}
{{- end}}
{{- if .StopTimeout}}
TimeoutStopSec={{.StopTimeout.Seconds}}
{{- end}}
{{- if .StartTimeout}}
TimeoutStartSec={{.StartTimeout.Seconds}}
{{- end}}
Type={{.App.Daemon}}
{{- if .Remain}}
RemainAfterExit={{.Remain}}
{{- end}}
{{- if .BusName}}
BusName={{.BusName}}
{{- end}}
{{- if .App.WatchdogTimeout}}
WatchdogSec={{.App.WatchdogTimeout.Seconds}}
{{- end}}
{{- if .KillMode}}
KillMode={{.KillMode}}
{{- end}}
{{- if .KillSignal}}
KillSignal={{.KillSignal}}
{{- end}}
{{- if .OOMAdjustScore }}
OOMScoreAdjust={{.OOMAdjustScore}}
{{- end}}
{{- if not .App.Sockets}}
[Install]
WantedBy={{.ServicesTarget}}
{{- end}}
`
var templateOut bytes.Buffer
tmpl := template.New("service-wrapper")
tmpl.Funcs(template.FuncMap{
"stringsJoin": strings.Join,
})
t := template.Must(tmpl.Parse(serviceTemplate))
restartCond := appInfo.RestartCond.String()
if restartCond == "" {
restartCond = snap.RestartOnFailure.String()
}
// use score -900+vitalityRank, where vitalityRank starts at 1
// and considering snapd itself has OOMScoreAdjust=-900
const baseOOMAdjustScore = -900
var oomAdjustScore int
if opts.VitalityRank > 0 {
oomAdjustScore = baseOOMAdjustScore + opts.VitalityRank
}
var remain string
if appInfo.Daemon == "oneshot" {
// any restart condition other than "no" is invalid for oneshot daemons
restartCond = "no"
// If StopExec is present for a oneshot service than we also need
// RemainAfterExit=yes
if appInfo.StopCommand != "" {
remain = "yes"
}
}
var killMode string
if !appInfo.StopMode.KillAll() {
killMode = "process"
}
var busName string
if appInfo.Daemon == "dbus" && len(appInfo.ActivatesOn) > 0 {
slot := appInfo.ActivatesOn[len(appInfo.ActivatesOn)-1]
if err := slot.Attr("name", &busName); err != nil {
logger.Noticef("Cannot get 'name' attribute of dbus slot %q: %v", slot.Name, err)
}
}
wrapperData := struct {
App *snap.AppInfo
Restart string
WorkingDir string
StopTimeout time.Duration
StartTimeout time.Duration
ServicesTarget string
PrerequisiteTarget string
MountUnit string
Remain string
KillMode string
KillSignal string
OOMAdjustScore int
BusName string
Before []string
After []string
Home string
EnvVars string
}{
App: appInfo,
Restart: restartCond,
StopTimeout: serviceStopTimeout(appInfo),
StartTimeout: time.Duration(appInfo.StartTimeout),
Remain: remain,
KillMode: killMode,
KillSignal: appInfo.StopMode.KillSignal(),
OOMAdjustScore: oomAdjustScore,
BusName: busName,
Before: genServiceNames(appInfo.Snap, appInfo.Before),
After: genServiceNames(appInfo.Snap, appInfo.After),
// systemd runs as PID 1 so %h will not work.
Home: "/root",
}
switch appInfo.DaemonScope {
case snap.SystemDaemon:
wrapperData.ServicesTarget = systemd.ServicesTarget
wrapperData.PrerequisiteTarget = systemd.PrerequisiteTarget
wrapperData.MountUnit = filepath.Base(systemd.MountUnitPath(appInfo.Snap.MountDir()))
wrapperData.WorkingDir = appInfo.Snap.DataDir()
wrapperData.After = append(wrapperData.After, "snapd.apparmor.service")
case snap.UserDaemon:
wrapperData.ServicesTarget = systemd.UserServicesTarget
// FIXME: ideally use UserDataDir("%h"), but then the
// unit fails if the directory doesn't exist.
wrapperData.WorkingDir = appInfo.Snap.DataDir()
default:
panic("unknown snap.DaemonScope")
}
// Add extra "After" targets
if wrapperData.PrerequisiteTarget != "" {
wrapperData.After = append([]string{wrapperData.PrerequisiteTarget}, wrapperData.After...)
}
if wrapperData.MountUnit != "" {
wrapperData.After = append([]string{wrapperData.MountUnit}, wrapperData.After...)
}
if err := t.Execute(&templateOut, wrapperData); err != nil {
// this can never happen, except we forget a variable
logger.Panicf("Unable to execute template: %v", err)
}
return templateOut.Bytes()
}
func genServiceSocketFile(appInfo *snap.AppInfo, socketName string) []byte {
socketTemplate := `[Unit]
# Auto-generated, DO NOT EDIT
Description=Socket {{.SocketName}} for snap application {{.App.Snap.InstanceName}}.{{.App.Name}}
{{- if .MountUnit}}
Requires={{.MountUnit}}
After={{.MountUnit}}
{{- end}}
X-Snappy=yes
[Socket]
Service={{.ServiceFileName}}
FileDescriptorName={{.SocketInfo.Name}}
ListenStream={{.ListenStream}}
{{- if .SocketInfo.SocketMode}}
SocketMode={{.SocketInfo.SocketMode | printf "%04o"}}
{{- end}}
[Install]
WantedBy={{.SocketsTarget}}
`
var templateOut bytes.Buffer
t := template.Must(template.New("socket-wrapper").Parse(socketTemplate))
socket := appInfo.Sockets[socketName]
listenStream := renderListenStream(socket)
wrapperData := struct {
App *snap.AppInfo
ServiceFileName string
SocketsTarget string
MountUnit string
SocketName string
SocketInfo *snap.SocketInfo
ListenStream string
}{
App: appInfo,
ServiceFileName: filepath.Base(appInfo.ServiceFile()),
SocketsTarget: systemd.SocketsTarget,
SocketName: socketName,
SocketInfo: socket,
ListenStream: listenStream,
}
switch appInfo.DaemonScope {
case snap.SystemDaemon:
wrapperData.MountUnit = filepath.Base(systemd.MountUnitPath(appInfo.Snap.MountDir()))
case snap.UserDaemon:
// nothing
default:
panic("unknown snap.DaemonScope")
}
if err := t.Execute(&templateOut, wrapperData); err != nil {
// this can never happen, except we forget a variable
logger.Panicf("Unable to execute template: %v", err)
}
return templateOut.Bytes()
}
func generateSnapSocketFiles(app *snap.AppInfo) (*map[string][]byte, error) {
if err := snap.ValidateApp(app); err != nil {
return nil, err
}
socketFiles := make(map[string][]byte)
for name, socket := range app.Sockets {
socketFiles[socket.File()] = genServiceSocketFile(app, name)
}
return &socketFiles, nil
}
func renderListenStream(socket *snap.SocketInfo) string {
s := socket.App.Snap
listenStream := socket.ListenStream
switch socket.App.DaemonScope {
case snap.SystemDaemon:
listenStream = strings.Replace(listenStream, "$SNAP_DATA", s.DataDir(), -1)
// TODO: when we support User/Group in the generated
// systemd unit, adjust this accordingly
serviceUserUid := sys.UserID(0)
runtimeDir := s.UserXdgRuntimeDir(serviceUserUid)
listenStream = strings.Replace(listenStream, "$XDG_RUNTIME_DIR", runtimeDir, -1)
listenStream = strings.Replace(listenStream, "$SNAP_COMMON", s.CommonDataDir(), -1)
case snap.UserDaemon:
listenStream = strings.Replace(listenStream, "$SNAP_USER_DATA", s.UserDataDir("%h"), -1)
listenStream = strings.Replace(listenStream, "$SNAP_USER_COMMON", s.UserCommonDataDir("%h"), -1)
// FIXME: find some way to share code with snap.UserXdgRuntimeDir()
listenStream = strings.Replace(listenStream, "$XDG_RUNTIME_DIR", fmt.Sprintf("%%t/snap.%s", s.InstanceName()), -1)
default:
panic("unknown snap.DaemonScope")
}
return listenStream
}
func generateSnapTimerFile(app *snap.AppInfo) ([]byte, error) {
timerTemplate := `[Unit]
# Auto-generated, DO NOT EDIT
Description=Timer {{.TimerName}} for snap application {{.App.Snap.InstanceName}}.{{.App.Name}}
{{- if .MountUnit}}
Requires={{.MountUnit}}
After={{.MountUnit}}
{{- end}}
X-Snappy=yes
[Timer]
Unit={{.ServiceFileName}}
{{ range .Schedules }}OnCalendar={{ . }}
{{ end }}
[Install]
WantedBy={{.TimersTarget}}
`
var templateOut bytes.Buffer
t := template.Must(template.New("timer-wrapper").Parse(timerTemplate))
timerSchedule, err := timeutil.ParseSchedule(app.Timer.Timer)
if err != nil {
return nil, err
}
schedules := generateOnCalendarSchedules(timerSchedule)
wrapperData := struct {
App *snap.AppInfo
ServiceFileName string
TimersTarget string
TimerName string
MountUnit string
Schedules []string
}{
App: app,
ServiceFileName: filepath.Base(app.ServiceFile()),
TimersTarget: systemd.TimersTarget,
TimerName: app.Name,
Schedules: schedules,
}
switch app.DaemonScope {
case snap.SystemDaemon:
wrapperData.MountUnit = filepath.Base(systemd.MountUnitPath(app.Snap.MountDir()))
case snap.UserDaemon:
// nothing
default:
panic("unknown snap.DaemonScope")
}
if err := t.Execute(&templateOut, wrapperData); err != nil {
// this can never happen, except we forget a variable
logger.Panicf("Unable to execute template: %v", err)
}
return templateOut.Bytes(), nil
}
func makeAbbrevWeekdays(start time.Weekday, end time.Weekday) []string {
out := make([]string, 0, 7)
for w := start; w%7 != (end + 1); w++ {
out = append(out, time.Weekday(w % 7).String()[0:3])
}
return out
}
// daysRange generates a string representing a continuous range between given
// day numbers, which due to compatiblilty with old systemd version uses a
// verbose syntax of x,y,z instead of x..z
func daysRange(start, end uint) string {
var buf bytes.Buffer
for i := start; i <= end; i++ {
buf.WriteString(strconv.FormatInt(int64(i), 10))
if i < end {
buf.WriteRune(',')
}
}
return buf.String()
}
// generateOnCalendarSchedules converts a schedule into OnCalendar schedules
// suitable for use in systemd *.timer units using systemd.time(7)
// https://www.freedesktop.org/software/systemd/man/systemd.time.html
// XXX: old systemd versions do not support x..y ranges
func generateOnCalendarSchedules(schedule []*timeutil.Schedule) []string {
calendarEvents := make([]string, 0, len(schedule))
for _, sched := range schedule {
days := make([]string, 0, len(sched.WeekSpans))
for _, week := range sched.WeekSpans {
abbrev := strings.Join(makeAbbrevWeekdays(week.Start.Weekday, week.End.Weekday), ",")
if week.Start.Pos == timeutil.EveryWeek && week.End.Pos == timeutil.EveryWeek {
// eg: mon, mon-fri, fri-mon
days = append(days, fmt.Sprintf("%s *-*-*", abbrev))
continue
}
// examples:
// mon1 - Mon *-*-1..7 (Monday during the first 7 days)
// fri1 - Fri *-*-1..7 (Friday during the first 7 days)
// entries below will make systemd timer expire more
// frequently than the schedule suggests, however snap
// runner evaluates current time and gates the actual
// action
//
// mon1-tue - *-*-1..7 *-*-8 (anchored at first
// Monday; Monday happens during the 7 days,