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
200package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os/exec"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
)
type ContainerRequest struct {
GitRepo string `json:"git_repo"`
Name string `json:"name"`
}
type ContainerInfo struct {
Name string `json:"name"`
Replicas int32 `json:"replicas"`
ReadyReplicas int32 `json:"ready_replicas"`
CreationTime string `json:"creation_time"`
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/list", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
deployments, err := clientset.AppsV1().Deployments("default").List(context.TODO(), metav1.ListOptions{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var containers []ContainerInfo
for _, deployment := range deployments.Items {
container := ContainerInfo{
Name: deployment.Name,
Replicas: deployment.Status.Replicas,
ReadyReplicas: deployment.Status.ReadyReplicas,
CreationTime: deployment.CreationTimestamp.String(),
}
containers = append(containers, container)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(containers)
})
http.HandleFunc("/create", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req ContainerRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cmd := exec.Command("git", "clone", req.GitRepo, "/tmp/"+req.Name)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
log.Printf("Git clone error: %v\nStderr: %s", err, stderr.String())
http.Error(w, fmt.Sprintf("Failed to clone repository: %v - %s", err, stderr.String()), http.StatusInternalServerError)
return
}
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: req.Name,
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr(1),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": req.Name,
},
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": req.Name,
},
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: req.Name,
Image: req.Name + ":latest",
},
},
},
},
},
}
_, err = clientset.AppsV1().Deployments("default").Create(context.TODO(), deployment, metav1.CreateOptions{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Container created successfully")
})
http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
err := clientset.AppsV1().Deployments("default").Delete(context.TODO(), name, metav1.DeleteOptions{})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Container deleted successfully")
})
http.HandleFunc("/exec", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req struct {
PodName string `json:"pod_name"`
Namespace string `json:"namespace"`
Command []string `json:"command"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
restClient := clientset.CoreV1().RESTClient()
execReq := restClient.Post().
Resource("pods").
Name(req.PodName).
Namespace(req.Namespace).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Command: req.Command,
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}, metav1.ParameterCodec)
executor, err := remotecommand.NewSPDYExecutor(config, "POST", execReq.URL())
if err != nil {
http.Error(w, fmt.Sprintf("Failed to create executor: %v", err), http.StatusInternalServerError)
return
}
var stdout, stderr bytes.Buffer
err = executor.StreamWithContext(context.TODO(), remotecommand.StreamOptions{
Stdin: nil,
Stdout: &stdout,
Stderr: &stderr,
Tty: true,
})
if err != nil {
http.Error(w, fmt.Sprintf("exec error: %v\n%s", err, stderr.String()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write(stdout.Bytes())
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
func int32Ptr(i int32) *int32 {
return &i
}