summaryrefslogtreecommitdiffhomepage
path: root/release/dist/qnap/pkgs.go
blob: 1d69b3eaf3500e2d37f7f9f2633215ae0dfdc655 (plain)
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
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

// Package qnap contains dist Targets for building QNAP Tailscale packages.
//
// QNAP dev docs over at https://www.qnap.com/en/how-to/tutorial/article/qpkg-development-guidelines.
package qnap

import (
	"embed"
	"fmt"
	"io/fs"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"slices"
	"sync"

	"tailscale.com/release/dist"
)

type target struct {
	goenv  map[string]string
	arch   string
	signer *signer
}

type signer struct {
	gcloudCredentialsBase64         string
	gcloudProject                   string
	gcloudKeyring                   string
	keyName                         string
	certificateBase64               string
	certificateIntermediariesBase64 string
}

func (t *target) String() string {
	return fmt.Sprintf("qnap/%s", t.arch)
}

func (t *target) Build(b *dist.Build) ([]string, error) {
	// Stop early if we don't have docker running.
	if _, err := exec.LookPath("docker"); err != nil {
		return nil, fmt.Errorf("docker not found, cannot build: %w", err)
	}

	qnapBuilds := getQnapBuilds(b, t.signer)
	inner, err := qnapBuilds.buildInnerPackage(b, t.goenv)
	if err != nil {
		return nil, err
	}

	return t.buildQPKG(b, qnapBuilds, inner)
}

const (
	qnapTag = "1" // currently static, we don't seem to bump this
)

func (t *target) buildQPKG(b *dist.Build, qnapBuilds *qnapBuilds, inner *innerPkg) ([]string, error) {
	if _, err := exec.LookPath("docker"); err != nil {
		return nil, fmt.Errorf("docker not found, cannot build: %w", err)
	}

	if err := qnapBuilds.makeDockerImage(b); err != nil {
		return nil, fmt.Errorf("makeDockerImage: %w", err)
	}

	filename := fmt.Sprintf("Tailscale_%s-%s_%s.qpkg", b.Version.Short, qnapTag, t.arch)
	filePath := filepath.Join(b.Out, filename)

	args := []string{"run", "--rm",
		"--network=host",
		"-e", fmt.Sprintf("ARCH=%s", t.arch),
		"-e", fmt.Sprintf("TSTAG=%s", b.Version.Short),
		"-e", fmt.Sprintf("QNAPTAG=%s", qnapTag),
		"-v", fmt.Sprintf("%s:/tailscale", inner.tailscalePath),
		"-v", fmt.Sprintf("%s:/tailscaled", inner.tailscaledPath),
		// Tailscale folder has QNAP package setup files needed for building.
		"-v", fmt.Sprintf("%s:/Tailscale", filepath.Join(qnapBuilds.tmpDir, "files/Tailscale")),
		"-v", fmt.Sprintf("%s:/build-qpkg.sh", filepath.Join(qnapBuilds.tmpDir, "files/scripts/build-qpkg.sh")),
		"-v", fmt.Sprintf("%s:/out", b.Out),
	}

	if t.signer != nil {
		log.Println("Will sign with Google Cloud HSM")
		args = append(args,
			"-e", fmt.Sprintf("GCLOUD_CREDENTIALS_BASE64=%s", t.signer.gcloudCredentialsBase64),
			"-e", fmt.Sprintf("GCLOUD_PROJECT=%s", t.signer.gcloudProject),
			"-e", fmt.Sprintf("GCLOUD_KEYRING=%s", t.signer.gcloudKeyring),
			"-e", fmt.Sprintf("QNAP_SIGNING_KEY_NAME=%s", t.signer.keyName),
			"-e", fmt.Sprintf("QNAP_SIGNING_CERT_BASE64=%s", t.signer.certificateBase64),
			"-e", fmt.Sprintf("QNAP_SIGNING_CERT_INTERMEDIARIES_BASE64=%s", t.signer.certificateIntermediariesBase64),
			"-e", fmt.Sprintf("QNAP_SIGNING_SCRIPT=%s", "/sign-qpkg.sh"),
			"-v", fmt.Sprintf("%s:/sign-qpkg.sh", filepath.Join(qnapBuilds.tmpDir, "files/scripts/sign-qpkg.sh")),
		)
	}

	args = append(args,
		"build.tailscale.io/qdk:latest",
		"/build-qpkg.sh",
	)

	cmd := b.Command(b.Repo, "docker", args...)

	// dist.Build runs target builds in parallel goroutines by default.
	// For QNAP, this is an issue because the underlaying qbuild builder will
	// create tmp directories in the shared docker image that end up conflicting
	// with one another.
	// So we use a mutex to only allow one "docker run" at a time.
	qnapBuilds.dockerImageMu.Lock()
	defer qnapBuilds.dockerImageMu.Unlock()

	log.Printf("Building %s", filePath)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("docker run %v: %s", err, out)
	}

	return []string{filePath, filePath + ".md5"}, nil
}

type qnapBuildsMemoizeKey struct{}

type innerPkg struct {
	tailscalePath  string
	tailscaledPath string
}

// qnapBuilds holds extra build context shared by all qnap builds.
type qnapBuilds struct {
	// innerPkgs contains per-goenv compiled binary paths.
	// It is used to avoid repeated compilations for the same architecture.
	innerPkgs     dist.Memoize[*innerPkg]
	dockerImageMu sync.Mutex
	// tmpDir is a temp directory used for building qpkgs.
	// It gets cleaned up when the dist.Build is closed.
	tmpDir string
}

// getQnapBuilds returns the qnapBuilds for b, creating one if needed.
func getQnapBuilds(b *dist.Build, signer *signer) *qnapBuilds {
	return b.Extra(qnapBuildsMemoizeKey{}, func() any {
		builds, err := newQNAPBuilds(b, signer)
		if err != nil {
			panic(fmt.Errorf("setUpTmpDir: %v", err))
		}
		return builds
	}).(*qnapBuilds)
}

//go:embed all:files
var buildFiles embed.FS

// newQNAPBuilds creates a new qnapBuilds instance to hold context shared by
// all qnap targets, and sets up its local temp directory used for building.
//
// The qnapBuilds.tmpDir is filled with the contents of the buildFiles embedded
// FS for building.
//
// We do this to allow for this tailscale.com/release/dist/qnap package to be
// used from both the corp and OSS repos. When built from OSS source directly,
// this is a superfluous extra step, but when imported as a go module to another
// repo (such as corp), we must do this to allow for the module's build files
// to be reachable and editable from docker.
//
// This runs only once per dist.Build instance, is shared by all qnap targets,
// and gets cleaned up upon close of the dist.Build.
//
// When a signer is provided, newQNAPBuilds also sets up the qpkg signature
// files in qbuild's expected location within m.tmpDir.
func newQNAPBuilds(b *dist.Build, signer *signer) (*qnapBuilds, error) {
	m := new(qnapBuilds)

	log.Print("Setting up qnap tmp build directory")
	m.tmpDir = filepath.Join(b.Repo, "tmp-qnap-build")
	b.AddOnCloseFunc(func() error {
		return os.RemoveAll(m.tmpDir)
	})

	if err := fs.WalkDir(buildFiles, "files", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		outPath := filepath.Join(m.tmpDir, path)
		if d.IsDir() {
			return os.MkdirAll(outPath, 0755)
		}
		file, err := fs.ReadFile(buildFiles, path)
		if err != nil {
			return err
		}
		perm := fs.FileMode(0644)
		if slices.Contains([]string{".sh", ".cgi"}, filepath.Ext(path)) {
			perm = 0755
		}
		return os.WriteFile(outPath, file, perm)
	}); err != nil {
		return nil, err
	}

	return m, nil
}

// buildInnerPackage builds the go binaries used for qnap packages.
// These binaries get embedded with Tailscale package metadata to form qnap
// releases.
func (m *qnapBuilds) buildInnerPackage(b *dist.Build, goenv map[string]string) (*innerPkg, error) {
	return m.innerPkgs.Do(goenv, func() (*innerPkg, error) {
		if err := b.BuildWebClientAssets(); err != nil {
			return nil, err
		}
		ts, err := b.BuildGoBinary("tailscale.com/cmd/tailscale", goenv)
		if err != nil {
			return nil, err
		}
		tsd, err := b.BuildGoBinary("tailscale.com/cmd/tailscaled", goenv)
		if err != nil {
			return nil, err
		}

		// The go binaries above get built and put into a /tmp directory created
		// by b.TmpDir(). But, we build QNAP with docker, which doesn't always
		// allow for mounting tmp directories (seemingly dependent on docker
		// host).
		// https://stackoverflow.com/questions/65267251/docker-bind-mount-directory-in-tmp-not-working
		//
		// So here, we move the binaries into a directory within the b.Repo
		// path and clean it up when the builder closes.

		tmpDir := filepath.Join(m.tmpDir, fmt.Sprintf("/binaries-%s-%s-%s", b.Version.Short, goenv["GOOS"], goenv["GOARCH"]))
		if err = os.MkdirAll(tmpDir, 0755); err != nil {
			return nil, err
		}
		b.AddOnCloseFunc(func() error {
			return os.RemoveAll(tmpDir)
		})

		tsBytes, err := os.ReadFile(ts)
		if err != nil {
			return nil, err
		}
		tsdBytes, err := os.ReadFile(tsd)
		if err != nil {
			return nil, err
		}

		tsPath := filepath.Join(tmpDir, "tailscale")
		if err := os.WriteFile(tsPath, tsBytes, 0755); err != nil {
			return nil, err
		}
		tsdPath := filepath.Join(tmpDir, "tailscaled")
		if err := os.WriteFile(tsdPath, tsdBytes, 0755); err != nil {
			return nil, err
		}

		return &innerPkg{tailscalePath: tsPath, tailscaledPath: tsdPath}, nil
	})
}

func (m *qnapBuilds) makeDockerImage(b *dist.Build) error {
	return b.Once("make-qnap-docker-image", func() error {
		log.Printf("Building qnapbuilder docker image")

		cmd := b.Command(b.Repo, "docker", "build",
			"-f", filepath.Join(m.tmpDir, "files/scripts/Dockerfile.qpkg"),
			"-t", "build.tailscale.io/qdk:latest",
			filepath.Join(m.tmpDir, "files/scripts"),
		)
		out, err := cmd.CombinedOutput()
		if err != nil {
			return fmt.Errorf("docker build %v: %s", err, out)
		}
		return nil
	})
}