forked from codetainerapp/codetainer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.go
472 lines (402 loc) · 10.1 KB
/
models.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
package codetainer
import (
"archive/tar"
"bytes"
"encoding/json"
"errors"
"io"
"net/url"
"os"
"strings"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/gorilla/schema"
"github.com/pborman/uuid"
)
func parseObjectFromForm(p interface{}, form url.Values) error {
decoder := schema.NewDecoder()
// r.PostForm is a map of our POST form values
err := decoder.Decode(p, form)
return err
}
type CodetainerConfig struct {
// id
Id string `xorm:"not null unique pk varchar(128)" json:"id" schema:"id"`
Name string `xorm:"not null unique" json:"name" schema:"-"`
// profile string with the CodetainerSpec format
Profile string `json:"profile" schema:"profile"`
CreatedAt time.Time `schema:"-"`
UpdatedAt time.Time `schema:"-"`
Enabled bool
}
func (c *CodetainerConfig) LookupByNameOrId(db *Database) error {
id := c.Id
if c.Lookup(db) != nil {
c.Name = id
c.Id = ""
err := c.Lookup(db)
if err != nil {
return errors.New("No config found: " + id)
}
return err
}
return nil
}
func (c *CodetainerConfig) Lookup(db *Database) error {
Log.Debug("Looking up: ", c)
has, err := db.engine.Get(c)
if err != nil {
return err
}
if !has {
return errors.New("No codetainer config found: " + c.Id)
}
return nil
}
func (c *CodetainerConfig) GetProfileSpec() (*CodetainerProfileSpec, error) {
return parseJsonSpec(strings.NewReader(c.Profile))
}
func (c *CodetainerConfig) Validate() error {
_, err := c.GetProfileSpec()
return err
}
func (c *CodetainerConfig) Save(db *Database) error {
if c.Id != "" {
_, err := db.engine.Update(c)
return err
} else {
c.Id = uuid.New()
_, err := db.engine.Insert(c)
return err
}
}
//
// Container image.
//
// swagger:parameters imageCreate
type CodetainerImage struct {
Id string `xorm:"varchar(128) not null unique" json:"id" schema:"id"`
DefaultStartCommand string `json:"command" schema:"command"`
Description string `json:"description" schema:"description"`
Tags []string `schema:"-"`
CreatedAt time.Time `schema:"-"`
UpdatedAt time.Time `schema:"-"`
Enabled bool
}
func (img *CodetainerImage) Register(db *Database) error {
// check if image is in docker
image := lookupImageInDocker(img.Id)
if image != nil {
img.Id = image.ID
img.Tags = image.RepoTags
img.Enabled = true
Log.Info("Registering New Image: ", img)
_, err := db.engine.Insert(img)
return err
} else {
return errors.New("No image found in docker: " + img.Id)
}
return nil
}
func createTarFile(fileData []byte, fileName string) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
tw := tar.NewWriter(buf)
var file = struct {
Name string
Body []byte
}{Name: fileName, Body: fileData}
hdr := &tar.Header{
Name: file.Name,
Mode: 0600,
Size: int64(len(file.Body)),
}
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
if _, err := tw.Write(file.Body); err != nil {
return nil, err
}
if err := tw.Close(); err != nil {
return nil, err
}
return buf, nil
}
//
// Codetainer data structure.
//
// swagger:parameters codetainerCreate
type Codetainer struct {
Id string `schema:"id" json:"id"`
Name string `schema:"name" json:"name"`
ImageId string `schema:"image-id" json:"image-id"`
Defunct bool `schema"-"` // false if active
Running bool `schema"-" xorm:"-"` // true if running
Profile string `schema:"-"`
CreatedAt time.Time `schema:"-"`
UpdatedAt time.Time `schema:"-"`
}
func (c *Codetainer) GetProfileSpec() (*CodetainerProfileSpec, error) {
return parseJsonSpec(strings.NewReader(c.Profile))
}
func (codetainer *Codetainer) DownloadFile(filePath string) ([]byte, error) {
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return nil, err
}
var buf bytes.Buffer
opts := docker.CopyFromContainerOptions{
OutputStream: &buf,
Container: codetainer.Id,
Resource: filePath,
}
err = client.CopyFromContainer(opts)
if err != nil {
return nil, err
}
br := bytes.NewReader(buf.Bytes())
tr := tar.NewReader(br)
var resultBuf bytes.Buffer
hdr, err := tr.Next()
if err != nil {
return nil, err
}
if hdr.FileInfo().IsDir() {
// it's tarred
return nil, errors.New("File is a directory:" + filePath)
}
io.Copy(&resultBuf, tr)
return resultBuf.Bytes(), nil
}
//
// Upload a file to a `dstPath` in a container.
//
func (codetainer *Codetainer) UploadFile(
fileData []byte,
fileName string,
dstFolder string) error {
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return err
}
buf, err := createTarFile(fileData, fileName)
if err != nil {
return err
}
fi := bytes.NewReader(buf.Bytes())
opts := docker.UploadToContainerOptions{Path: dstFolder}
opts.InputStream = fi
Log.Debug("Writing file to codetainer")
return client.UploadToContainer(codetainer.Id, opts)
}
func (codetainer *Codetainer) Remove(db *Database) error {
Log.Debug("Removing codetainer:", codetainer.Id)
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return err
}
opts := docker.RemoveContainerOptions{
ID: codetainer.Id,
Force: true,
}
err = client.RemoveContainer(opts)
if err != nil {
Log.Error("Problems removing codetainer via Docker API:", err)
}
codetainer.Defunct = true
// for some reason engine.Update() isn't working for shit here
// needless to say, only ever call this function when Id is populated
// by the ORMe
_, err = db.engine.Exec("Update codetainer set defunct = 1 where id = ?", codetainer.Id)
return err
}
func (codetainer *Codetainer) Stop() error {
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return err
}
return client.StopContainer(codetainer.Id, 30)
}
func (codetainer *Codetainer) Start() error {
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return err
}
// TODO fetch config for codetainer
return client.StartContainer(codetainer.Id, &docker.HostConfig{
Binds: []string{
GlobalConfig.UtilsPath() + ":/codetainer/utils:ro",
},
})
}
func (codetainer *Codetainer) LookupByNameOrId(id string, db *Database) error {
codetainer.Id = id
if codetainer.Lookup(db) != nil {
codetainer.Name = id
codetainer.Id = ""
err := codetainer.Lookup(db)
if err != nil {
return errors.New("No codetainer found: " + id)
}
return err
}
return nil
}
func (codetainer *Codetainer) Lookup(db *Database) error {
Log.Debug("Looking up: ", codetainer)
has, err := db.engine.Get(codetainer)
if err != nil {
return err
}
if !has {
return errors.New("No codetainer found: " + codetainer.Id)
}
return nil
}
func (codetainer *Codetainer) Create(db *Database) error {
client, err := GlobalConfig.GetDockerClient()
if err != nil {
return err
}
image, err := db.LookupCodetainerImage(codetainer.ImageId)
if err != nil {
return err
}
if image == nil {
return errors.New("no image found")
}
codetainer.ImageId = image.Id
defaultConfig := &docker.Config{
OpenStdin: true,
Tty: true,
Image: image.Id,
}
defaultHostConfig := &docker.HostConfig{
Binds: []string{
GlobalConfig.UtilsPath() + ":/codetainer/utils:ro",
},
}
if codetainer.Profile != "" {
config, err := codetainer.GetProfileSpec()
if err != nil {
Log.Error("Invalid profile spec", err)
return err
}
if config.Config != nil {
defaultConfig = config.Config
defaultConfig.Tty = true
defaultConfig.Image = image.Id
defaultConfig.OpenStdin = true
}
if config.HostConfig != nil {
defaultHostConfig = config.HostConfig
defaultHostConfig.Binds = []string{
GlobalConfig.UtilsPath() + ":/codetainer/utils:ro",
}
}
}
opts := docker.CreateContainerOptions{
Name: codetainer.Name,
Config: defaultConfig,
HostConfig: defaultHostConfig,
}
Log.Debugf("Creating codetainer with opts: %+v\n", opts)
c, err := client.CreateContainer(opts)
if err != nil {
return err
}
err = client.StartContainer(c.ID, defaultHostConfig)
if err != nil {
return err
}
codetainer.Id = c.ID
return codetainer.Save(db)
}
func (c *Codetainer) Save(db *Database) error {
_, err := db.engine.Insert(c)
return err
}
type ShortFileInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
IsDir bool `json:"is_dir"`
IsLink bool `json:"is_link"`
ModTime time.Time `json:"modified_time"`
}
func NewShortFileInfo(f os.FileInfo) *ShortFileInfo {
fi := ShortFileInfo{}
fi.Name = f.Name()
fi.Size = f.Size()
fi.IsDir = f.IsDir()
fi.ModTime = f.ModTime()
fi.IsLink = (f.Mode()&os.ModeType)&os.ModeSymlink > 0
return &fi
}
func makeShortFiles(data []byte) (*[]ShortFileInfo, error) {
files := make([]ShortFileInfo, 0)
if err := json.Unmarshal(data, &files); err != nil {
return nil, err
}
return &files, nil
}
//
// Return type for errors
//
// swagger:response APIErrorResponse
type APIErrorResponse struct {
Error bool `json:"error" description:"set if an error is returned"`
Message string `json:"message" description:"error message string"`
}
//
// TTY parameters for a codetainer
//
// swagger:parameters updateCurrentTTY
type TTY struct {
Height int `json:"height" description:"height of tty"`
Width int `json:"width" description:"width of tty"`
}
//
// TTY response
//
// swagger:response TTYBody
type TTYBody struct {
Tty TTY `json:"tty"`
}
//
// CodetainerImage response
//
// swagger:response CodetainerImageBody
type CodetainerImageBody struct {
Image CodetainerImage `json:"image"`
}
//
// CodetainerImageList response
//
// swagger:response CodetainerImageListBody
type CodetainerImageListBody struct {
Images []CodetainerImage `json:"images"`
}
//
// Codetainer Create Params
//
// swagger:parameters CodetainerCreate
type CodetainerCreateParams struct {
Codetainer
CodetainerConfigId string `schema:"codetainer-config-id" json:"codetainer-config-id"`
}
//
// Codetainer response
//
// swagger:response CodetainerBody
type CodetainerBody struct {
Codetainer `json:"codetainer"`
}
//
// CodetainerList response
//
// swagger:response CodetainerListBody
type CodetainerListBody struct {
Codetainers []Codetainer `json:"codetainers"`
}
type GenericSuccess struct {
Success bool `json:"success"`
}