-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontainer.go
182 lines (170 loc) · 4.65 KB
/
container.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
package main
import (
"bufio"
"encoding/json"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/container"
"github.com/docker/engine-api/types/network"
"golang.org/x/net/context"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"runtime"
"strings"
"text/template"
"time"
)
// Container is a container for a MongoDB session
type Container struct {
name string
id string
started bool
h *hub
quit chan int
mgoSession *mgo.Session
}
// Process is the metadata for a process
type Process struct {
Name string `json:"name,omitempty"`
User string `json:"user,omitempty"`
PID string `json:"pid,omitempty"`
STime string `json:"stime,omitempty"`
Time string `json:"time,omitempty"`
}
// MgoURL is a MongoDB URL
type MgoURL struct {
Container string `bson:"container,omitempty"`
User string `bson:"user,omitempty"`
URL string `bson:"url,omitempty"`
}
func create(cli *client.Client, name string, h *hub, session *mgo.Session) *Container {
split := strings.SplitN(name, "_", 2)
containerOptions := container.Config{
Hostname: name,
User: "",
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
OpenStdin: true,
StdinOnce: true,
Image: "canopy",
WorkingDir: "",
Env: []string{"HOST=" + *addr, "PORT=" + *port, "KEY=" + split[0], "NAME=" + split[1]},
}
hostOptions := container.HostConfig{
NetworkMode: "bridge",
}
id, err := cli.ContainerCreate(context.Background(), &containerOptions, &hostOptions, &network.NetworkingConfig{}, name)
if err != nil {
log.Println(err)
return nil
}
log.Println("Created container:", name)
return &Container{name: name, id: id.ID, started: false, h: h, quit: make(chan int), mgoSession: session}
}
func (c *Container) statusUpdater() {
for {
exit := false
select {
case <-c.quit:
exit = true
default:
list, err := c.h.cli.ContainerTop(context.Background(), c.id, []string{})
if err == nil {
processes := make([]Process, 0)
for _, p := range list.Processes {
proc := Process{Name: p[7], User: p[0], PID: p[1], STime: p[4], Time: p[6]}
processes = append(processes, proc)
}
res, _ := json.Marshal(processes)
c.h.dbw.write("SET", "containers:"+c.name+":processes", res)
} else {
c.h.dbw.write("SET", "containers:"+c.name+":processes", "[]")
}
// read, err := c.h.cli.ContainerStats(context.TODO(), c.id, false)
// if err == nil {
// out := make([]byte, 1788)
// read.Read(out)
// read.Close()
// }
if exit {
break
}
time.Sleep(100 * time.Millisecond)
}
}
}
// TemplateStruct is a template structure
type TemplateStruct struct {
Array string
}
func (c *Container) start() {
col := c.mgoSession.DB("meteor").C("urls")
user := c.name[:strings.Index(c.name, "_")]
name := c.name[strings.Index(c.name, "_")+1:]
result := []MgoURL{}
iter := col.Find(bson.M{"container": name, "user": user}).Iter()
e := iter.All(&result)
log.Println(result)
if e != nil {
log.Println(e)
} else {
_, filename, _, _ := runtime.Caller(1)
abspath := path.Join(path.Dir(filename), "docker/package_loader_template.sh")
tmpl, err := template.ParseFiles(abspath)
arrayString := ""
for _, item := range result {
arrayString += "\"" + item.URL + "\" "
}
data := TemplateStruct{arrayString}
if err != nil {
log.Println(err)
}
tmpfile, err := ioutil.TempFile(path.Dir(filename), c.name)
writer := bufio.NewWriter(tmpfile)
err = tmpl.Execute(writer, data)
writer.Flush()
tmpfile.Close()
if err == nil {
//err = c.h.cli.CopyToContainer(context.Background(), c.id, "package_loader.sh", bufio.NewReader(tmpfile), types.CopyToContainerOptions{false})
exec.Command("docker", "cp", tmpfile.Name(), c.name+":/package_loader.sh").Output()
if err != nil {
log.Println(err)
}
os.Remove(tmpfile.Name())
} else {
log.Println(err)
}
}
startOptions := types.ContainerStartOptions{
CheckpointID: "",
}
err := c.h.cli.ContainerStart(context.Background(), c.id, startOptions)
if err != nil {
return
}
c.started = true
log.Println("Started container:", c.name)
}
func (c *Container) stop() {
var dur = time.Duration(10)
c.h.cli.ContainerStop(context.Background(), c.id, &dur)
c.started = false
log.Println("Stopped container:", c.name)
}
func (c *Container) remove() {
containerRmOptions := types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
}
c.h.cli.ContainerRemove(context.Background(), c.id, containerRmOptions)
c.started = false
close(c.quit)
log.Println("Removed container:", c.name)
}