This repository has been archived by the owner on Oct 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgrades.go
192 lines (163 loc) · 4.89 KB
/
upgrades.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
package syscfg
// This file contains tweaks for enabling/disabling unattended upgrades.
import (
"context"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"time"
errw "github.com/pkg/errors"
"go.uber.org/zap"
)
const (
autoUpgradesPath = "/etc/apt/apt.conf.d/20auto-upgrades"
autoUpgradesContentsEnabled = `APT::Periodic::Update-Package-Lists "1";` + "\n" + `APT::Periodic::Unattended-Upgrade "1";` + "\n"
autoUpgradesContentsDisabled = `APT::Periodic::Update-Package-Lists "1";` + "\n" + `APT::Periodic::Unattended-Upgrade "0";` + "\n"
unattendedUpgradesPath = "/etc/apt/apt.conf.d/50unattended-upgrades"
)
type UpgradesConfig struct {
// Type can be
// Empty/missing ("") to make no changes
// "disable" (or "disabled") to disable auto-upgrades
// "security" to enable ONLY security upgrades
// "all" to enable upgrades from all configured sources
Type string `json:"type"`
}
func EnforceUpgrades(ctx context.Context, cfg UpgradesConfig, log *zap.SugaredLogger) {
if cfg.Type == "" {
return
}
err := checkSupportedDistro()
if err != nil {
log.Error(err)
return
}
if cfg.Type == "disable" || cfg.Type == "disabled" {
isNew, err := writeFileIfNew(autoUpgradesPath, []byte(autoUpgradesContentsDisabled))
if err != nil {
log.Error(err)
}
if isNew {
log.Info("Disabled OS auto-upgrades.")
}
return
}
err = verifyInstall()
if err != nil {
err = doInstall(ctx)
if err != nil {
log.Error(err)
return
}
}
securityOnly := cfg.Type == "security"
confContents, err := generateOrigins(securityOnly)
if err != nil {
log.Error(err)
return
}
isNew1, err := writeFileIfNew(autoUpgradesPath, []byte(autoUpgradesContentsEnabled))
if err != nil {
log.Error(err)
return
}
isNew2, err := writeFileIfNew(unattendedUpgradesPath, []byte(confContents))
if err != nil {
log.Error(err)
return
}
if isNew1 || isNew2 {
if securityOnly {
log.Info("Enabled OS auto-upgrades (security only.)")
} else {
log.Info("Enabled OS auto-upgrades (full.)")
}
}
err = enableTimer()
if err != nil {
log.Error(err)
}
}
func checkSupportedDistro() error {
data, err := os.ReadFile("/etc/os-release")
if err != nil {
return err
}
if strings.Contains(string(data), "VERSION_CODENAME=bookworm") || strings.Contains(string(data), "VERSION_CODENAME=bullseye") {
return nil
}
return errw.New("cannot enable automatic upgrades for unknown distro, only support for Debian bullseye and bookworm is available")
}
// make sure the needed package is installed.
func verifyInstall() error {
cmd := exec.Command("unattended-upgrade", "-h")
output, err := cmd.CombinedOutput()
if err != nil {
return errw.Wrapf(err, "executing 'unattended-upgrade -h' %s", output)
}
return nil
}
func enableTimer() error {
// enable here
cmd := exec.Command("systemctl", "enable", "apt-daily-upgrade.timer")
output, err := cmd.CombinedOutput()
if err != nil {
return errw.Wrapf(err, "executing 'systemctl enable apt-daily-upgrade.timer' %s", output)
}
return nil
}
func doInstall(ctx context.Context) error {
// On low bandwidth connections, apt updates/installs can take a while, so start something to handle healthchecks
sleepCtx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
HealthySleep(sleepCtx, time.Hour)
}()
cmd := exec.CommandContext(ctx, "apt", "update")
output, err := cmd.CombinedOutput()
if err != nil {
return errw.Wrapf(err, "executing 'apt update' %s", output)
}
cmd = exec.CommandContext(ctx, "apt", "install", "-y", "unattended-upgrades")
output, err = cmd.CombinedOutput()
if err != nil {
return errw.Wrapf(err, "executing 'apt install -y unattended-upgrades' %s", output)
}
return nil
}
// generates the "Origins-Pattern" section of 50unattended-upgrades file.
func generateOrigins(securityOnly bool) (string, error) {
cmd := exec.Command("apt-cache", "policy")
output, err := cmd.CombinedOutput()
if err != nil {
return "", errw.Wrapf(err, "executing 'apt-cache policy' %s", output)
}
releases := generateOriginsInner(securityOnly, output)
// generate actual file contents
origins := "Unattended-Upgrade::Origins-Pattern {"
for release := range releases {
origins = fmt.Sprintf("%s\n %s", origins, release)
}
origins = fmt.Sprintf("%s\n};\n", origins)
return origins, nil
}
// inner transformation logic of generateOrigins for testing.
func generateOriginsInner(securityOnly bool, output []byte) map[string]bool {
releaseRegex := regexp.MustCompile(`release.*o=([^,]+).*n=([^,]+).*`)
matches := releaseRegex.FindAllStringSubmatch(string(output), -1)
// use map to reduce to unique set
releases := map[string]bool{}
for _, release := range matches {
// we expect at least an origin and a codename from each line
if len(release) != 3 {
continue
}
if securityOnly && !strings.Contains(release[2], "security") {
continue
}
releases[fmt.Sprintf(`"origin=%s,codename=%s";`, release[1], release[2])] = true
}
return releases
}