-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
265 lines (222 loc) · 6.2 KB
/
api.go
File metadata and controls
265 lines (222 loc) · 6.2 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
)
type APIServer struct {
store Store
addr string
}
func NewAPIServer(store Store, addr string) *APIServer {
return &APIServer{
store: store,
addr: addr,
}
}
func (s *APIServer) Start() error {
http.HandleFunc("/nodes/register", func(w http.ResponseWriter, r *http.Request) {
var node Node
if err := json.NewDecoder(r.Body).Decode(&node); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
node.LastSeen = time.Now()
node.State = NodeReady
if err := s.store.SaveNode(context.Background(), &node); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("Node registered: %s at %v\n", node.ID, node.Address)
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("/nodes/heartbeat", func(w http.ResponseWriter, r *http.Request) {
var hb struct {
NodeID string `json:"node_id"`
}
if err := json.NewDecoder(r.Body).Decode(&hb); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
node, err := s.store.GetNode(context.Background(), hb.NodeID)
if err != nil {
http.Error(w, "node not found", http.StatusNotFound)
return
}
node.LastSeen = time.Now()
s.store.SaveNode(context.Background(), node)
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("/containers/assigned", func(w http.ResponseWriter, r *http.Request) {
nodeID := r.URL.Query().Get("node_id")
if nodeID == "" {
http.Error(w, "node_id parameter required", http.StatusBadRequest)
return
}
containers, err := s.store.ListContainers(context.Background())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
assigned := []*Container{}
for _, c := range containers {
if c.NodeID == nodeID && c.Scheduled {
assigned = append(assigned, c)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(assigned)
})
http.HandleFunc("/containers", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
var container Container
if err := json.NewDecoder(r.Body).Decode(&container); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.store.SaveContainer(context.Background(), &container); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{
"id": container.ID,
"status": "scheduled",
})
case http.MethodDelete:
parts := strings.Split(r.URL.Path, "/")
if len(parts) < 3 {
http.Error(w, "Container ID required", http.StatusBadRequest)
return
}
containerID := parts[2]
if err := s.store.DelContainer(context.Background(), containerID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("[API] Container deleted: %s", containerID)
w.WriteHeader(http.StatusOK)
}
})
http.HandleFunc("/containers/status", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var container Container
if err := json.NewDecoder(r.Body).Decode(&container); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.store.SaveContainer(context.Background(), &container); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("[API] Container status updated: %s -> %s", container.ID, container.State)
w.WriteHeader(http.StatusOK)
})
return http.ListenAndServe(s.addr, nil)
}
type APIClient struct {
controlPlaneURL string
nodeID string
client *http.Client
}
func NewAPIClient(controlPlaneURL string, nodeID string) *APIClient {
return &APIClient{
controlPlaneURL: controlPlaneURL,
nodeID: nodeID,
client: &http.Client{Timeout: 5 * time.Second},
}
}
func (c *APIClient) Register(node *Node) error {
data, _ := json.Marshal(node)
resp, err := c.client.Post(
c.controlPlaneURL+"/nodes/register",
"application/json",
bytes.NewBuffer(data),
)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *APIClient) SendHeartbeat() error {
data, _ := json.Marshal(map[string]string{
"node_id": c.nodeID,
})
resp, err := c.client.Post(
c.controlPlaneURL+"/nodes/heartbeat",
"application/json",
bytes.NewBuffer(data),
)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *APIClient) GetAssignedContainers(nodeID string) ([]*Container, error) {
url := fmt.Sprintf("%s/containers/assigned?node_id=%s", c.controlPlaneURL, nodeID)
resp, err := c.client.Get(url)
if err != nil {
return nil, fmt.Errorf("Failed to get containers: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API returned status: %v", err)
}
var containers []*Container
if err := json.NewDecoder(resp.Body).Decode(&containers); err != nil {
return nil, fmt.Errorf("Failed to decode response: %v", err)
}
return containers, nil
}
func (c *APIClient) UpdateContainerStatus(container *Container) error {
data, err := json.Marshal(container)
if err != nil {
return err
}
resp, err := c.client.Post(
c.controlPlaneURL+"/containers/status",
"application/json",
bytes.NewBuffer(data),
)
if err != nil {
return fmt.Errorf("failed to update status: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
return nil
}
func (c *APIClient) DeleteContainer(containerID string) error {
req, err := http.NewRequest(
http.MethodDelete,
fmt.Sprintf("%s/containers/%s", c.controlPlaneURL, containerID),
nil,
)
if err != nil {
return err
}
resp, err := c.client.Do(req)
if err != nil {
return fmt.Errorf("Failed to delete container: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
return nil
}