-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
208 lines (161 loc) · 4.21 KB
/
main.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
package main
import (
"os"
"flag"
"fmt"
"log"
"net/http"
"time"
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/goji/httpauth"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/rest"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
batch_v1 "k8s.io/client-go/pkg/apis/batch/v1"
)
var flagKubeconfigPath string
var flagInCluster bool
var deletePolicy = meta_v1.DeletePropagationForeground
var authUsername = os.Getenv("GORUNIT_USERNAME")
var authPassword = os.Getenv("GORUNIT_PASSWORD")
func getInClusterConfig() (*rest.Config, error) {
return rest.InClusterConfig()
}
func getOutOfClusterConfig() (*rest.Config, error) {
config, err := clientcmd.BuildConfigFromFlags("", flagKubeconfigPath)
if err != nil {
return nil, err
}
return config, err
}
func getKubeClientset() (*kubernetes.Clientset, error) {
var config *rest.Config
var err error
if flagInCluster {
config, err = getInClusterConfig()
} else {
config, err = getOutOfClusterConfig()
}
if err != nil {
return nil, err
}
return kubernetes.NewForConfig(config)
}
func jobLog(job *batch_v1.Job, message string) {
log.Printf("%s: %s\n", job.ObjectMeta.Name, message)
}
func deleteJob(job *batch_v1.Job) {
jobLog(job, "cleaning up")
client, _ := getKubeClientset()
err := client.BatchV1().Jobs(job.ObjectMeta.Namespace).Delete(
job.ObjectMeta.Name,
&meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
if err != nil {
jobLog(job, "error when trying to remove")
} else {
jobLog(job, "removed")
}
}
func watchAndCleanUpJob(job *batch_v1.Job) {
defer deleteJob(job)
for {
client, _ := getKubeClientset()
j, err := client.BatchV1().Jobs(job.ObjectMeta.Namespace).Get(
job.ObjectMeta.Name,
meta_v1.GetOptions{})
if err != nil {
jobLog(job, "something went terribly wrong, can't retrieve job status")
}
if j.Status.Active == 1 {
jobLog(job, "active")
} else if j.Status.Succeeded == 1 {
jobLog(job, "finished")
break
} else if j.Status.Failed == 1 {
jobLog(job, "failed")
break
} else {
jobLog(job, "I have no idea what the fuck is happening")
}
time.Sleep(time.Second)
}
}
func getJobFromRequestBody(r *http.Request) (*batch_v1.Job, error) {
var job batch_v1.Job
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
if err := decoder.Decode(&job); err != nil {
return nil, err
}
return &job, nil
}
func handleCreateJob(w http.ResponseWriter, r *http.Request) {
client, _ := getKubeClientset()
job, err := getJobFromRequestBody(r)
if err != nil {
fmt.Fprint(w, "failed to parse request body")
return
}
// quick hack to randomize job names a bit
name := fmt.Sprintf("%s-%s", job.ObjectMeta.Name, uuid.New().String())
job.ObjectMeta.Name = name
job.Spec.Template.ObjectMeta.Name = name
j, err := client.BatchV1().Jobs(job.ObjectMeta.Namespace).Create(job)
if err != nil {
jobLog(j, "failed to create")
return
}
jobLog(j, "created")
defer func() {
go watchAndCleanUpJob(j)
}()
}
func init() {
flag.StringVar(
&flagKubeconfigPath,
"kubeconfig",
"kubeconfig",
"Absolute path to the kubeconfig file.")
flag.BoolVar(
&flagInCluster,
"in-cluster",
false,
"Running inside Kubernetes cluster")
flag.Parse()
}
func handleHome(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Go run it!")
}
func handleKubePing(w http.ResponseWriter, r *http.Request) {
client, _ := getKubeClientset()
pods, err := client.CoreV1().Pods("").List(meta_v1.ListOptions{})
if err != nil {
fmt.Fprint(w, "can't talk to the cluster")
} else {
fmt.Fprintf(w, "%d pods running\n", len(pods.Items))
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/v1/ping", handleKubePing).Methods("GET")
r.HandleFunc("/v1/jobs", handleCreateJob).Methods("POST")
r.HandleFunc("/", handleHome).Methods("GET")
var handler http.Handler
if len(authUsername) != 0 && len(authPassword) != 0 {
handler = httpauth.SimpleBasicAuth(authUsername, authPassword)(r)
} else {
handler = r
}
s := &http.Server{
Handler: handler,
Addr: ":8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Println("Listening on :8080")
log.Fatal(s.ListenAndServe())
}