summaryrefslogtreecommitdiffstats
path: root/cmd/ship/deploy_impl_v2.go
blob: 5b68dc3564e1f631064c16346c34b9f0273eea0f (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
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
package main

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/bdw/ship/internal/output"
	"github.com/bdw/ship/internal/ssh"
	"github.com/bdw/ship/internal/templates"
)

// deployStaticV2 deploys a static site
// 1. rsync path to /var/www/<name>/
// 2. Generate and upload Caddyfile
// 3. Reload Caddy
func deployStaticV2(ctx *deployContext) *output.ErrorResponse {
	client, err := ssh.Connect(ctx.SSHHost)
	if err != nil {
		return output.Err(output.ErrSSHConnectFailed, err.Error())
	}
	defer client.Close()

	name := ctx.Name
	remotePath := fmt.Sprintf("/var/www/%s", name)

	// Create directory and set ownership for upload
	user, _ := client.Run("whoami")
	user = strings.TrimSpace(user)
	if _, err := client.RunSudo(fmt.Sprintf("mkdir -p %s", remotePath)); err != nil {
		return output.Err(output.ErrUploadFailed, "failed to create directory: "+err.Error())
	}
	if _, err := client.RunSudo(fmt.Sprintf("chown -R %s:%s %s", user, user, remotePath)); err != nil {
		return output.Err(output.ErrUploadFailed, "failed to set directory ownership: "+err.Error())
	}

	// Upload files using rsync
	if err := client.UploadDir(ctx.Path, remotePath); err != nil {
		return output.Err(output.ErrUploadFailed, err.Error())
	}

	// Set ownership back to www-data
	if _, err := client.RunSudo(fmt.Sprintf("chown -R www-data:www-data %s", remotePath)); err != nil {
		// Non-fatal, continue
	}

	// Generate Caddyfile only if it doesn't exist (preserve manual edits)
	caddyPath := fmt.Sprintf("/etc/caddy/sites-enabled/%s.caddy", name)
	caddyExists, _ := client.Run(fmt.Sprintf("test -f %s && echo exists", caddyPath))
	if strings.TrimSpace(caddyExists) != "exists" {
		caddyfile, err := templates.StaticCaddy(map[string]string{
			"Domain":  ctx.URL[8:], // Strip https://
			"RootDir": remotePath,
			"Name":    name,
		})
		if err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to generate Caddyfile: "+err.Error())
		}

		if err := client.WriteSudoFile(caddyPath, caddyfile); err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to write Caddyfile: "+err.Error())
		}
	}

	// Reload Caddy
	if _, err := client.RunSudo("systemctl reload caddy"); err != nil {
		return output.Err(output.ErrCaddyFailed, "failed to reload Caddy: "+err.Error())
	}

	return nil
}

// deployDockerV2 deploys a Docker-based app
// 1. Allocate port
// 2. rsync path to /var/lib/<name>/src/
// 3. docker build
// 4. Generate systemd unit and env file
// 5. Generate Caddyfile
// 6. Start service, reload Caddy
func deployDockerV2(ctx *deployContext) *output.ErrorResponse {
	client, err := ssh.Connect(ctx.SSHHost)
	if err != nil {
		return output.Err(output.ErrSSHConnectFailed, err.Error())
	}
	defer client.Close()

	name := ctx.Name

	// Allocate port on server
	port, err := allocatePort(client, name)
	if err != nil {
		return output.Err(output.ErrServiceFailed, "failed to allocate port: "+err.Error())
	}

	srcPath := fmt.Sprintf("/var/lib/%s/src", name)
	dataPath := fmt.Sprintf("/var/lib/%s/data", name)

	// Create directories
	if _, err := client.RunSudo(fmt.Sprintf("mkdir -p %s %s", srcPath, dataPath)); err != nil {
		return output.Err(output.ErrUploadFailed, "failed to create directories: "+err.Error())
	}

	// Set ownership for upload
	user, _ := client.Run("whoami")
	user = strings.TrimSpace(user)
	if _, err := client.RunSudo(fmt.Sprintf("chown -R %s:%s %s", user, user, srcPath)); err != nil {
		return output.Err(output.ErrUploadFailed, "failed to set directory ownership: "+err.Error())
	}

	// Upload source
	if err := client.UploadDir(ctx.Path, srcPath); err != nil {
		return output.Err(output.ErrUploadFailed, err.Error())
	}

	// Docker build
	buildCmd := fmt.Sprintf("docker build -t %s:latest %s", name, srcPath)
	if _, err := client.RunSudo(buildCmd); err != nil {
		return output.Err(output.ErrBuildFailed, err.Error())
	}

	// Generate and write env file
	envContent := fmt.Sprintf("PORT=%d\nSHIP_NAME=%s\nSHIP_URL=%s\n", port, name, ctx.URL)
	for _, e := range ctx.Opts.Env {
		envContent += e + "\n"
	}
	envPath := fmt.Sprintf("/etc/ship/env/%s.env", name)
	if _, err := client.RunSudo("mkdir -p /etc/ship/env"); err != nil {
		// Continue, directory might exist
	}
	if err := client.WriteSudoFile(envPath, envContent); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to write env file: "+err.Error())
	}

	// Generate systemd unit
	containerPort := ctx.Opts.ContainerPort
	if containerPort == 0 {
		containerPort = 80
	}
	service, err := templates.DockerService(map[string]string{
		"Name":          name,
		"Port":          strconv.Itoa(port),
		"ContainerPort": strconv.Itoa(containerPort),
	})
	if err != nil {
		return output.Err(output.ErrServiceFailed, "failed to generate systemd unit: "+err.Error())
	}

	servicePath := fmt.Sprintf("/etc/systemd/system/%s.service", name)
	if err := client.WriteSudoFile(servicePath, service); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to write systemd unit: "+err.Error())
	}

	// Generate Caddyfile only if it doesn't exist (preserve manual edits)
	caddyPath := fmt.Sprintf("/etc/caddy/sites-enabled/%s.caddy", name)
	caddyExists, _ := client.Run(fmt.Sprintf("test -f %s && echo exists", caddyPath))
	if strings.TrimSpace(caddyExists) != "exists" {
		caddyfile, err := templates.AppCaddy(map[string]string{
			"Domain": ctx.URL[8:], // Strip https://
			"Port":   strconv.Itoa(port),
		})
		if err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to generate Caddyfile: "+err.Error())
		}

		if err := client.WriteSudoFile(caddyPath, caddyfile); err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to write Caddyfile: "+err.Error())
		}
	}

	// Reload systemd and start service
	if _, err := client.RunSudo("systemctl daemon-reload"); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to reload systemd: "+err.Error())
	}
	if _, err := client.RunSudo(fmt.Sprintf("systemctl restart %s", name)); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to start service: "+err.Error())
	}

	// Reload Caddy
	if _, err := client.RunSudo("systemctl reload caddy"); err != nil {
		return output.Err(output.ErrCaddyFailed, "failed to reload Caddy: "+err.Error())
	}

	return nil
}

// deployBinaryV2 deploys a pre-built binary
// 1. Allocate port
// 2. scp binary to /usr/local/bin/<name>
// 3. Create user for service
// 4. Generate systemd unit and env file
// 5. Generate Caddyfile
// 6. Start service, reload Caddy
func deployBinaryV2(ctx *deployContext) *output.ErrorResponse {
	client, err := ssh.Connect(ctx.SSHHost)
	if err != nil {
		return output.Err(output.ErrSSHConnectFailed, err.Error())
	}
	defer client.Close()

	name := ctx.Name

	// Allocate port on server
	port, err := allocatePort(client, name)
	if err != nil {
		return output.Err(output.ErrServiceFailed, "failed to allocate port: "+err.Error())
	}

	binaryPath := fmt.Sprintf("/usr/local/bin/%s", name)
	workDir := fmt.Sprintf("/var/lib/%s", name)

	// Upload binary
	if err := client.Upload(ctx.Path, "/tmp/"+name); err != nil {
		return output.Err(output.ErrUploadFailed, err.Error())
	}

	// Move to final location and set permissions
	if _, err := client.RunSudo(fmt.Sprintf("mv /tmp/%s %s && chmod +x %s", name, binaryPath, binaryPath)); err != nil {
		return output.Err(output.ErrUploadFailed, "failed to install binary: "+err.Error())
	}

	// Create work directory
	if _, err := client.RunSudo(fmt.Sprintf("mkdir -p %s", workDir)); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to create work directory: "+err.Error())
	}

	// Create service user (ignore error if exists)
	client.RunSudo(fmt.Sprintf("useradd -r -s /bin/false %s 2>/dev/null || true", name))
	client.RunSudo(fmt.Sprintf("chown -R %s:%s %s", name, name, workDir))

	// Generate and write env file
	envContent := fmt.Sprintf("PORT=%d\nSHIP_NAME=%s\nSHIP_URL=%s\n", port, name, ctx.URL)
	for _, e := range ctx.Opts.Env {
		envContent += e + "\n"
	}
	envPath := fmt.Sprintf("/etc/ship/env/%s.env", name)
	if _, err := client.RunSudo("mkdir -p /etc/ship/env"); err != nil {
		// Continue
	}
	if err := client.WriteSudoFile(envPath, envContent); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to write env file: "+err.Error())
	}

	// Generate systemd unit
	service, err := templates.SystemdService(map[string]string{
		"Name":       name,
		"User":       name,
		"WorkDir":    workDir,
		"EnvFile":    envPath,
		"BinaryPath": binaryPath,
		"Args":       "",
	})
	if err != nil {
		return output.Err(output.ErrServiceFailed, "failed to generate systemd unit: "+err.Error())
	}

	servicePath := fmt.Sprintf("/etc/systemd/system/%s.service", name)
	if err := client.WriteSudoFile(servicePath, service); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to write systemd unit: "+err.Error())
	}

	// Generate Caddyfile only if it doesn't exist (preserve manual edits)
	caddyPath := fmt.Sprintf("/etc/caddy/sites-enabled/%s.caddy", name)
	caddyExists, _ := client.Run(fmt.Sprintf("test -f %s && echo exists", caddyPath))
	if strings.TrimSpace(caddyExists) != "exists" {
		caddyfile, err := templates.AppCaddy(map[string]string{
			"Domain": ctx.URL[8:], // Strip https://
			"Port":   strconv.Itoa(port),
		})
		if err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to generate Caddyfile: "+err.Error())
		}

		if err := client.WriteSudoFile(caddyPath, caddyfile); err != nil {
			return output.Err(output.ErrCaddyFailed, "failed to write Caddyfile: "+err.Error())
		}
	}

	// Reload systemd and start service
	if _, err := client.RunSudo("systemctl daemon-reload"); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to reload systemd: "+err.Error())
	}
	if _, err := client.RunSudo(fmt.Sprintf("systemctl enable --now %s", name)); err != nil {
		return output.Err(output.ErrServiceFailed, "failed to start service: "+err.Error())
	}

	// Reload Caddy
	if _, err := client.RunSudo("systemctl reload caddy"); err != nil {
		return output.Err(output.ErrCaddyFailed, "failed to reload Caddy: "+err.Error())
	}

	return nil
}

// allocatePort allocates or retrieves a port for a service
// Uses atomic increment on /etc/ship/next_port to avoid collisions
func allocatePort(client *ssh.Client, name string) (int, error) {
	portFile := fmt.Sprintf("/etc/ship/ports/%s", name)

	// Try to read existing port for this app
	out, err := client.Run(fmt.Sprintf("cat %s 2>/dev/null || echo ''", portFile))
	if err == nil && out != "" {
		out = strings.TrimSpace(out)
		if port, err := strconv.Atoi(out); err == nil && port > 0 {
			return port, nil
		}
	}

	// Allocate new port atomically using flock
	// This reads next_port, increments it, and writes back while holding a lock
	allocScript := `
flock -x /etc/ship/.port.lock sh -c '
  mkdir -p /etc/ship/ports
  PORT=$(cat /etc/ship/next_port 2>/dev/null || echo 9000)
  echo $((PORT + 1)) > /etc/ship/next_port
  echo $PORT
'`
	out, err = client.RunSudo(allocScript)
	if err != nil {
		return 0, fmt.Errorf("failed to allocate port: %w", err)
	}

	port, err := strconv.Atoi(strings.TrimSpace(out))
	if err != nil {
		return 0, fmt.Errorf("invalid port allocated: %s", out)
	}

	// Write port allocation for this app
	if err := client.WriteSudoFile(portFile, strconv.Itoa(port)); err != nil {
		return 0, err
	}

	return port, nil
}

// setTTLV2 sets auto-expiry for a deploy
func setTTLV2(ctx *deployContext, ttl time.Duration) error {
	client, err := ssh.Connect(ctx.SSHHost)
	if err != nil {
		return err
	}
	defer client.Close()

	expires := time.Now().Add(ttl).Unix()
	ttlPath := fmt.Sprintf("/etc/ship/ttl/%s", ctx.Name)

	if _, err := client.RunSudo("mkdir -p /etc/ship/ttl"); err != nil {
		return err
	}

	return client.WriteSudoFile(ttlPath, strconv.FormatInt(expires, 10))
}

// runHealthCheck verifies the deploy is responding
func runHealthCheck(url, endpoint string) (*output.HealthResult, *output.ErrorResponse) {
	fullURL := url + endpoint

	// Wait for app to start
	time.Sleep(2 * time.Second)

	var lastErr error
	var lastStatus int

	for i := 0; i < 15; i++ {
		start := time.Now()
		resp, err := http.Get(fullURL)
		latency := time.Since(start).Milliseconds()

		if err != nil {
			lastErr = err
			time.Sleep(2 * time.Second)
			continue
		}
		resp.Body.Close()
		lastStatus = resp.StatusCode

		if resp.StatusCode >= 200 && resp.StatusCode < 400 {
			return &output.HealthResult{
				Endpoint:  endpoint,
				Status:    resp.StatusCode,
				LatencyMs: latency,
			}, nil
		}

		time.Sleep(2 * time.Second)
	}

	msg := fmt.Sprintf("health check failed after 30s: ")
	if lastErr != nil {
		msg += lastErr.Error()
	} else {
		msg += fmt.Sprintf("status %d", lastStatus)
	}

	return nil, output.Err(output.ErrHealthCheckFailed, msg)
}