-
Notifications
You must be signed in to change notification settings - Fork 9
/
service.go
499 lines (413 loc) · 12.2 KB
/
service.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
// Copyright Nitric Pty Ltd.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package project
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
goruntime "runtime"
"strings"
"syscall"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/go-connections/nat"
"github.com/samber/lo"
"github.com/spf13/afero"
"github.com/nitrictech/cli/pkg/docker"
"github.com/nitrictech/cli/pkg/netx"
"github.com/nitrictech/cli/pkg/project/runtime"
"github.com/nitrictech/nitric/core/pkg/logger"
)
type ServiceBuildStatus string
type Service struct {
Name string
Type string
// filepath relative to the project root directory
filepath string
buildContext runtime.RuntimeBuildContext
startCmd string
}
func (s *Service) GetFilePath() string {
return s.filepath
}
func (s *Service) GetAbsoluteFilePath() (string, error) {
return filepath.Abs(s.filepath)
}
const (
ServiceBuildStatus_InProgress ServiceBuildStatus = "In Progress"
ServiceBuildStatus_Complete ServiceBuildStatus = "Complete"
ServiceBuildStatus_Error ServiceBuildStatus = "Error"
)
type ServiceBuildUpdate struct {
ServiceName string
Message string
Status ServiceBuildStatus
Err error
}
type ServiceRunStatus string
const (
ServiceRunStatus_Running ServiceRunStatus = "Running"
ServiceRunStatus_Done ServiceRunStatus = "Done"
ServiceRunStatus_Error ServiceRunStatus = "Error"
)
type ServiceRunUpdate struct {
ServiceName string
Label string
Message string
Status ServiceRunStatus
Err error
}
type ServiceRunUpdateWriter struct {
updates chan<- ServiceRunUpdate
serviceName string
label string
status ServiceRunStatus
}
func (s *ServiceRunUpdateWriter) Write(data []byte) (int, error) {
msg := string(data)
s.updates <- ServiceRunUpdate{
ServiceName: s.serviceName,
Message: msg,
Status: s.status,
Label: s.label,
}
return len(data), nil
}
type serviceBuildUpdateWriter struct {
serviceName string
buildUpdateChan chan ServiceBuildUpdate
}
func (b *serviceBuildUpdateWriter) Write(data []byte) (int, error) {
b.buildUpdateChan <- ServiceBuildUpdate{
ServiceName: b.serviceName,
Message: string(data),
Status: ServiceBuildStatus_InProgress,
}
return len(data), nil
}
func (s *Service) BuildImage(fs afero.Fs, logs io.Writer) error {
dockerClient, err := docker.New()
if err != nil {
return err
}
err = fs.MkdirAll(tempBuildDir, os.ModePerm)
if err != nil {
return fmt.Errorf("unable to create temporary build directory %s: %w", tempBuildDir, err)
}
tmpDockerFile, err := afero.TempFile(fs, tempBuildDir, fmt.Sprintf("%s-*.dockerfile", s.Name))
if err != nil {
return fmt.Errorf("unable to create temporary dockerfile for service %s: %w", s.Name, err)
}
if err := afero.WriteFile(fs, tmpDockerFile.Name(), []byte(s.buildContext.DockerfileContents), os.ModePerm); err != nil {
return fmt.Errorf("unable to write temporary dockerfile for service %s: %w", s.Name, err)
}
defer func() {
tmpDockerFile.Close()
err := fs.Remove(tmpDockerFile.Name())
if err != nil {
logger.Errorf("unable to remove temporary dockerfile %s: %s", tmpDockerFile.Name(), err)
}
}()
// build the docker image
err = dockerClient.Build(
tmpDockerFile.Name(),
s.buildContext.BaseDirectory,
s.Name,
s.buildContext.BuildArguments,
strings.Split(s.buildContext.IgnoreFileContents, "\n"),
logs,
)
if err != nil {
return err
}
return nil
}
type runContainerOptions struct {
nitricHost string
nitricPort string
nitricEnvironment string
envVars map[string]string
}
type RunContainerOption func(*runContainerOptions)
var defaultRunContainerOptions = runContainerOptions{
nitricHost: "host.docker.internal",
nitricPort: "50051",
nitricEnvironment: "run",
envVars: map[string]string{},
}
func WithNitricHost(host string) RunContainerOption {
return func(o *runContainerOptions) {
o.nitricHost = host
}
}
func WithNitricPort(port string) RunContainerOption {
return func(o *runContainerOptions) {
o.nitricPort = port
}
}
func WithNitricEnvironment(environment string) RunContainerOption {
return func(o *runContainerOptions) {
o.nitricEnvironment = environment
}
}
func WithEnvVars(envVars map[string]string) RunContainerOption {
return func(o *runContainerOptions) {
o.envVars = envVars
}
}
type writerFunc func(p []byte) (n int, err error)
func (wf writerFunc) Write(p []byte) (n int, err error) {
return wf(p)
}
// Run - runs the service using the provided command, typically not in a container.
func (s *Service) Run(stop <-chan bool, updates chan<- ServiceRunUpdate, env map[string]string) error {
if s.startCmd == "" {
return fmt.Errorf("no start command provided for service %s", s.filepath)
}
// this could be improve with real env var substitution.
startCmd := strings.ReplaceAll(s.startCmd, "$SERVICE_PATH", s.filepath)
startCmd = strings.ReplaceAll(startCmd, "${SERVICE_PATH}", s.filepath)
if !strings.Contains(startCmd, s.filepath) {
logger.Warnf("Start cmd for service %s does not contain $SERVICE_PATH, check the service start configuration in nitric.yaml", s.filepath)
}
commandParts := strings.Split(startCmd, " ")
cmd := exec.Command(
commandParts[0],
commandParts[1:]...,
)
cmd.Env = append(cmd.Env, os.Environ()...)
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
// cmd.Env = append(cmd.Env, fmt.Sprintf("SERVICE_PATH=\"%s\"", s.filepath))
cmd.Stdout = &ServiceRunUpdateWriter{
updates: updates,
serviceName: s.Name,
label: s.filepath,
status: ServiceRunStatus_Running,
}
cmd.Stderr = &ServiceRunUpdateWriter{
updates: updates,
serviceName: s.Name,
label: s.filepath,
status: ServiceRunStatus_Error,
}
errChan := make(chan error)
go func() {
err := cmd.Start()
if err != nil {
errChan <- err
} else {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Label: "nitric",
Status: ServiceRunStatus_Running,
Message: fmt.Sprintf("started service %s", s.filepath),
}
}
err = cmd.Wait()
errChan <- err
}()
go func(cmd *exec.Cmd) {
<-stop
err := cmd.Process.Signal(syscall.SIGTERM)
if err != nil {
_ = cmd.Process.Kill()
}
}(cmd)
err := <-errChan
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Status: ServiceRunStatus_Error,
Err: err,
}
return err
}
// RunContainer - Runs a container for the service, blocking until the container exits
func (s *Service) RunContainer(stop <-chan bool, updates chan<- ServiceRunUpdate, opts ...RunContainerOption) error {
runtimeOptions := lo.ToPtr(defaultRunContainerOptions)
for _, opt := range opts {
opt(runtimeOptions)
}
dockerClient, err := docker.New()
if err != nil {
return err
}
hostConfig := &container.HostConfig{
// TODO: make this configurable through an cmd param
AutoRemove: true,
// LogConfig: *f.ce.Logger(f.runCtx).Config(),
LogConfig: container.LogConfig{
Type: "json-file",
Config: map[string]string{
"max-size": "10m",
"max-file": "3",
},
},
}
if goruntime.GOOS == "linux" {
// setup host.docker.internal to route to host gateway
// to access rpc server hosted by local CLI run
hostConfig.ExtraHosts = []string{"host.docker.internal:172.17.0.1"}
}
randomPort, _ := netx.TakePort(1)
hostProxyPort := fmt.Sprint(randomPort[0])
env := []string{
fmt.Sprintf("NITRIC_ENVIRONMENT=%s", runtimeOptions.nitricEnvironment),
// FIXME: Ensure environment variable consistency in all SDKs, then remove duplicates here.
fmt.Sprintf("SERVICE_ADDRESS=%s", fmt.Sprintf("%s:%s", runtimeOptions.nitricHost, runtimeOptions.nitricPort)),
fmt.Sprintf("NITRIC_SERVICE_PORT=%s", runtimeOptions.nitricPort),
fmt.Sprintf("NITRIC_SERVICE_HOST=%s", runtimeOptions.nitricHost),
fmt.Sprintf("NITRIC_HTTP_PROXY_PORT=%d", randomPort[0]),
}
osEnv := os.Environ()
// filter out env vars that can conflict with the container
bannedVars := []string{"TEMP", "TMP", "PATH", "HOME"}
osEnv = lo.Filter(osEnv, func(item string, index int) bool {
return !lo.Contains(bannedVars, strings.Split(item, "=")[0])
})
env = append(env, osEnv...)
for k, v := range runtimeOptions.envVars {
env = append(env, k+"="+v)
}
hostConfig.PortBindings = nat.PortMap{
nat.Port(hostProxyPort): []nat.PortBinding{
{
HostPort: hostProxyPort,
},
},
}
containerConfig := &container.Config{
Image: s.Name, // Select an image to use based on the handler
Env: env,
ExposedPorts: nat.PortSet{
nat.Port(hostProxyPort): struct{}{},
},
}
// Create the container
containerId, err := dockerClient.ContainerCreate(
containerConfig,
hostConfig,
nil,
s.Name,
)
if err != nil {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Status: ServiceRunStatus_Error,
Err: err,
}
return nil
}
err = dockerClient.ContainerStart(context.TODO(), containerId, types.ContainerStartOptions{})
if err != nil {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Status: ServiceRunStatus_Error,
Err: err,
}
return nil
}
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Message: fmt.Sprintf("Service %s started", s.Name),
Status: ServiceRunStatus_Running,
}
// Attach to the container to get stdout and stderr
attachOptions := types.ContainerAttachOptions{
Stream: true,
Stdout: true,
Stderr: true,
}
attachResponse, err := dockerClient.ContainerAttach(context.TODO(), containerId, attachOptions)
if err != nil {
return fmt.Errorf("error attaching to container %s: %w", s.Name, err)
}
// Use a separate goroutine to handle the container's output
go func() {
defer attachResponse.Close()
// Using io.Copy to send the output to a writer
_, err := io.Copy(writerFunc(func(p []byte) (int, error) {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Message: string(p),
Status: ServiceRunStatus_Running,
}
return len(p), nil
}), attachResponse.Reader)
if err != nil {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Status: ServiceRunStatus_Error,
Err: err,
}
}
}()
okChan, errChan := dockerClient.ContainerWait(context.TODO(), containerId, container.WaitConditionNotRunning)
for {
select {
case err := <-errChan:
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Err: err,
Status: ServiceRunStatus_Error,
}
return err
case okBody := <-okChan:
if okBody.StatusCode != 0 {
logOptions := types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Tail: "20"}
logReader, err := dockerClient.ContainerLogs(context.Background(), containerId, logOptions)
if err != nil {
return err
}
// Create a buffer to hold the logs
var logs bytes.Buffer
if _, err := stdcopy.StdCopy(&logs, &logs, logReader); err != nil {
return fmt.Errorf("error reading logs for service %s: %w", s.Name, err)
}
err = fmt.Errorf("service %s exited with non 0 status\n %s", s.Name, logs.String())
updates <- ServiceRunUpdate{
ServiceName: s.Name,
// TODO: Extract the error logs for the container here...
Err: err,
Status: ServiceRunStatus_Error,
}
return err
} else {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Message: "Service successfully exited",
Status: ServiceRunStatus_Done,
}
}
return nil
case <-stop:
if err := dockerClient.ContainerStop(context.Background(), containerId, nil); err != nil {
updates <- ServiceRunUpdate{
ServiceName: s.Name,
Status: ServiceRunStatus_Error,
Err: err,
}
return nil
}
}
}
}