forked from buildpacks/pack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
105 lines (91 loc) · 1.98 KB
/
run.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
package pack
import (
"context"
"crypto/md5"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"github.com/pkg/errors"
)
func Run(appDir, buildImage, runImage string) error {
r := &RunFlags{
AppDir: appDir,
Builder: buildImage,
RunImage: runImage,
}
if err := r.Init(); err != nil {
return err
}
return r.Run()
}
type RunFlags struct {
AppDir string
Builder string
RunImage string
Port string
// Below are set by init
Build BuildFlags
}
func (r *RunFlags) Init() error {
var err error
r.AppDir, err = filepath.Abs(r.AppDir)
if err != nil {
return err
}
h := md5.New()
io.WriteString(h, r.AppDir)
repoName := fmt.Sprintf("%x", h.Sum(nil))
r.Build = BuildFlags{
AppDir: r.AppDir,
Builder: r.Builder,
RunImage: r.RunImage,
RepoName: repoName,
Publish: false,
NoPull: false,
}
return r.Build.Init()
}
func (r *RunFlags) Run() error {
ctx := context.Background()
err := r.Build.Run()
if err != nil {
return err
}
fmt.Println("*** RUNNING:")
exposedPorts, portBindings, err := nat.ParsePortSpecs([]string{
fmt.Sprintf("127.0.0.1:%s:8080/tcp", r.Port),
})
if err != nil {
return err
}
ctr, err := r.Build.Cli.ContainerCreate(ctx, &container.Config{
Image: r.Build.RepoName,
AttachStdout: true,
AttachStderr: true,
ExposedPorts: exposedPorts,
}, &container.HostConfig{
AutoRemove: true,
PortBindings: portBindings,
}, nil, "")
// TODO cleanup signal flow
var stopped bool
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
d := time.Duration(5) * time.Second
stopped = true
r.Build.Cli.ContainerStop(ctx, ctr.ID, &d)
}
}()
fmt.Printf("Starting container listing at http://localhost:%s/\n", r.Port)
if err = r.Build.Cli.RunContainer(ctx, ctr.ID, r.Build.Stdout, r.Build.Stderr); err != nil && !stopped {
return errors.Wrap(err, "run built container")
}
return nil
}