/
api.go
119 lines (104 loc) · 2.63 KB
/
api.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
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/odewahn/swarm-manager/db"
"github.com/odewahn/swarm-manager/manager"
"github.com/odewahn/swarm-manager/models"
)
type SpawnRequest struct {
Image string
}
func Spawn(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
image := r.FormValue("image")
if len(image) == 0 {
image = "zischwartz/notebook"
}
user := r.FormValue("user")
if len(user) == 0 {
user = "odewahn"
}
m := &models.Container{
Image: image,
User: user,
Domainname: os.Getenv("THEBE_SERVER_BASE_URL"),
}
status := make(chan string)
go manager.Start(m, status)
<-status //block until we get a message back that the status record is ready
fmt.Fprintf(w, m.Serialize()+"\n")
}
func ListContainer(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hostname := vars["hostname"]
c := db.GetContainer(hostname)
fmt.Fprintln(w, c.Serialize())
}
func KillContainer(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
hostname := vars["hostname"]
c := db.GetContainer(hostname)
status := make(chan string)
go manager.Kill(&c, status)
<-status // block until the status updates
fmt.Fprintln(w, c.Serialize())
}
func ListContainers(w http.ResponseWriter, r *http.Request) {
containers := db.GetContainers()
out, err := json.MarshalIndent(containers, "", " ")
if err != nil {
log.Println(err)
}
fmt.Fprintf(w, string(out)+"\n")
}
func Stats(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "{}\n")
}
func ManageContainers(w http.ResponseWriter, r *http.Request) {
containers := db.GetContainers()
t, _ := template.New("index").Parse(`
<html>
<h1>Swarm Manager</h1>
<h2>Launch a container</h2>
<form action="/api/spawn/" method="POST">
Image: <input type="text" name="image" value="ipython/scipystack"/><br>
User: <input type="text" name="user" value="odewahn"/><br>
<input type="submit"/>
</form>
<h2>Active Containers</h2>
<table>
{{ range .}}
{{ if .IsActive }}
<tr>
<td>
<a target=_blank href="http://{{.Url}}">{{.Url}}</a>
</td>
<td>
{{.Image}}
</td>
<td>
{{.User}}
</td>
<td>
{{.Status}}
</td>
<td>
{{.StartTime}}
</td>
<td>
<a href="/api/container/{{.Hostname}}/kill">Kill</a>
</td>
</tr>
{{ end }}
{{end}}
</table>
</html>
`)
t.Execute(w, containers)
}