Repository navigation
Expand file tree
/
Copy pathmssql.go
More file actions
276 lines (250 loc) · 9.23 KB
/
Copy pathmssql.go
File metadata and controls
276 lines (250 loc) · 9.23 KB
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
package main
import (
"fmt"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
)
const (
// mssqlRelease is the SQL Server release installed from Microsoft's
// apt repository, the one internal/goldeneye generates the dialect
// from.
mssqlRelease = "2025"
// mssqlSAPassword is the sa password the server is set up with: the
// one docker-compose.yml and CI use.
mssqlSAPassword = "Mysecretpassword1!"
mssqlPort = "1433"
mssqlServer = "/opt/mssql/bin/sqlservr"
mssqlConf = "/opt/mssql/bin/mssql-conf"
mssqlLog = "/var/opt/mssql/log/errorlog"
)
// mssqlUbuntuReleases lists the Ubuntu releases Microsoft publishes SQL
// Server packages for.
var mssqlUbuntuReleases = map[string]bool{"22.04": true, "24.04": true}
// installMSSQL installs SQL Server from Microsoft's apt repository and
// runs its setup non-interactively, accepting the EULA on the user's
// behalf. It is a no-op when the server is already installed and set up,
// reruns only the setup when an earlier install stopped before it
// finished, and skips platforms the packages are not published for:
// Ubuntu 22.04 and 24.04 on amd64 and arm64.
func installMSSQL() error {
log.Printf("--- Installing SQL Server %s ---", mssqlRelease)
if _, err := os.Stat(mssqlServer); err == nil {
if mssqlConfigured() {
log.Printf("sql server is already installed at %s", mssqlServer)
return nil
}
log.Printf("sql server is installed at %s but not set up", mssqlServer)
return setupMSSQL()
}
ubuntu, err := mssqlSupported()
if err != nil {
log.Printf("skipping: %s", err)
return nil
}
tmp, err := os.MkdirTemp("", "sqlc-mssql-")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
key := filepath.Join(tmp, "microsoft.asc")
log.Println("adding microsoft's package signing key")
if err := downloadFile(key, "https://packages.microsoft.com/keys/microsoft.asc"); err != nil {
return fmt.Errorf("downloading the signing key: %w", err)
}
if err := run("sudo", "gpg", "--dearmor", "--yes", "-o", "/usr/share/keyrings/microsoft-prod.gpg", key); err != nil {
return fmt.Errorf("installing the signing key: %w", err)
}
list := filepath.Join(tmp, "mssql-server.list")
listURL := "https://packages.microsoft.com/config/ubuntu/" + ubuntu + "/mssql-server-" + mssqlRelease + ".list"
log.Printf("adding the apt repository from %s", listURL)
if err := downloadFile(list, listURL); err != nil {
return fmt.Errorf("downloading the repository list: %w", err)
}
if err := run("sudo", "cp", list, "/etc/apt/sources.list.d/mssql-server-"+mssqlRelease+".list"); err != nil {
return err
}
if err := run("sudo", "apt-get", "update"); err != nil {
return fmt.Errorf("apt-get update: %w", err)
}
log.Println("installing mssql-server")
if err := run("sudo", "env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "mssql-server"); err != nil {
return fmt.Errorf("apt-get install mssql-server: %w", err)
}
return setupMSSQL()
}
// setupMSSQL runs mssql-conf setup, which accepts the EULA, sets the sa
// password and writes the server's configuration, then starts the service
// through systemd. Where there is no systemd that last step fails, and the
// configuration it wrote is what install needs, since start brings the
// server up. Anywhere else a failure is setup's own.
func setupMSSQL() error {
log.Println("running mssql-conf setup")
cmd := exec.Command("sudo", "env", "ACCEPT_EULA=Y", "MSSQL_PID=Developer", "MSSQL_SA_PASSWORD="+mssqlSAPassword,
mssqlConf, "-n", "setup", "accept-eula")
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
// The command line carries the sa password, so it is not logged the
// way run logs one.
log.Printf("exec: sudo env ACCEPT_EULA=Y MSSQL_PID=Developer MSSQL_SA_PASSWORD=... %s -n setup accept-eula", mssqlConf)
err := cmd.Run()
if err == nil {
return nil
}
if systemdRunning() || !mssqlConfigured() {
return fmt.Errorf("mssql-conf setup: %w", err)
}
log.Printf("mssql-conf setup wrote the configuration but could not start the service without systemd (%s); start will", err)
return nil
}
// mssqlConfigured reports whether mssql-conf setup has written the
// server's configuration. /var/opt/mssql is readable by the mssql user
// only, so the check goes through sudo rather than a stat as this user.
func mssqlConfigured() bool {
return exec.Command("sudo", "test", "-f", "/var/opt/mssql/mssql.conf").Run() == nil
}
// mssqlSupported reports whether Microsoft publishes SQL Server packages
// for this machine, returning its Ubuntu release, and otherwise why not.
func mssqlSupported() (string, error) {
ubuntu, err := ubuntuRelease()
if err != nil {
return "", fmt.Errorf("sql server packages are published for Ubuntu only: %w", err)
}
if runtime.GOOS != "linux" || (runtime.GOARCH != "amd64" && runtime.GOARCH != "arm64") || !mssqlUbuntuReleases[ubuntu] {
return "", fmt.Errorf("sql server packages are not published for Ubuntu %s on %s/%s", ubuntu, runtime.GOOS, runtime.GOARCH)
}
return ubuntu, nil
}
// ubuntuRelease reads the Ubuntu release from /etc/os-release.
func ubuntuRelease() (string, error) {
data, err := os.ReadFile("/etc/os-release")
if err != nil {
return "", err
}
var id, version string
for _, line := range strings.Split(string(data), "\n") {
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
value = strings.Trim(value, `"`)
switch key {
case "ID":
id = value
case "VERSION_ID":
version = value
}
}
if id != "ubuntu" {
return "", fmt.Errorf("this is %s, not ubuntu", id)
}
return version, nil
}
// startMSSQL starts SQL Server and waits until it is ready for client
// connections: through systemd where it runs, otherwise by running the
// server in the background as its own user. When the server is already
// listening it only waits for it to be ready, and it skips machines the
// server is not installed on.
func startMSSQL() error {
log.Println("--- Starting SQL Server ---")
if mssqlListening() {
// A server this machine does not run, such as the one
// docker-compose.yml starts, has no log here to wait on.
if _, err := os.Stat(mssqlServer); err != nil {
log.Println("sql server is already running and accepting connections")
return nil
}
// mssql-conf setup starts the service through systemd, so the
// server can be listening while it still recovers its databases.
log.Println("sql server is already running")
return waitForMSSQL()
}
if _, err := os.Stat(mssqlServer); err != nil {
if _, err := mssqlSupported(); err != nil {
log.Printf("sql server is not installed here, skipping: %s", err)
return nil
}
return fmt.Errorf("sql server is not installed: run `sqlc-test-setup install mssql` first")
}
if systemdRunning() {
log.Println("starting mssql-server through systemd")
if err := run("sudo", "systemctl", "start", "mssql-server"); err != nil {
return fmt.Errorf("systemctl start mssql-server: %w", err)
}
} else {
// The server's own log is mssqlLog; what it prints goes to a file
// of its own rather than this process's output, which a detached
// process would otherwise hold open.
cache, err := os.UserCacheDir()
if err != nil {
return err
}
dir := filepath.Join(cache, "sqlc-mssql")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
logFile, err := os.Create(filepath.Join(dir, "sqlservr.log"))
if err != nil {
return err
}
defer logFile.Close()
log.Printf("starting %s in the background", mssqlServer)
cmd := exec.Command("sudo", "-u", "mssql", "env", "ACCEPT_EULA=Y", "MSSQL_SA_PASSWORD="+mssqlSAPassword, mssqlServer)
cmd.Stdout = logFile
cmd.Stderr = logFile
cmd.SysProcAttr = detachedProcess()
if err := cmd.Start(); err != nil {
return fmt.Errorf("starting sqlservr: %w", err)
}
if err := cmd.Process.Release(); err != nil {
return err
}
}
return waitForMSSQL()
}
// waitForMSSQL polls until the server listens and its log says it is ready
// for client connections, or three minutes pass.
func waitForMSSQL() error {
log.Println("waiting for sql server to accept connections")
deadline := time.Now().Add(3 * time.Minute)
for time.Now().Before(deadline) {
if mssqlListening() && mssqlReadyForClients() {
log.Println("sql server is accepting connections")
return nil
}
time.Sleep(2 * time.Second)
}
return fmt.Errorf("sql server did not start in time (see %s)", mssqlLog)
}
// systemdRunning reports whether systemd is the init system here, so a
// service can be started through it.
func systemdRunning() bool {
out, err := exec.Command("systemctl", "is-system-running").Output()
state := strings.TrimSpace(string(out))
if err != nil && state == "" {
return false
}
return state != "offline" && state != "unknown"
}
// mssqlListening reports whether something accepts connections on the SQL
// Server port.
func mssqlListening() bool {
conn, err := net.DialTimeout("tcp", "127.0.0.1:"+mssqlPort, time.Second)
if err != nil {
return false
}
conn.Close()
return true
}
// mssqlReadyForClients reports whether the server's log says it is ready
// for client connections, which comes a moment after it starts listening.
// The log is readable by the mssql user only, so it is read through sudo.
func mssqlReadyForClients() bool {
return exec.Command("sudo", "grep", "-q", "ready for client connections", mssqlLog).Run() == nil
}