/
api.go
217 lines (201 loc) · 5.74 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
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
package api
import "C"
import (
"encoding/json"
"errors"
"fmt"
"github.com/datianshi/pxeboot/pkg/config"
"github.com/datianshi/pxeboot/pkg/util"
"github.com/gobuffalo/packr/v2"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
type API struct {
r *mux.Router
cfg *config.Config
imageUploader *ImageUploader
htmlBox *packr.Box
}
func NewAPI(c *config.Config) *API {
return &API{
r: mux.NewRouter(),
cfg: c,
imageUploader: &ImageUploader{
c,
},
htmlBox: packr.New("html", "./public"),
}
}
func (a *API) Start() {
var port int
if a.cfg.HTTPPort != 0 {
port = a.cfg.HTTPPort
} else {
port = 80
}
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", a.cfg.ManagementIp, port),
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: a.r, // Pass our instance of gorilla/mux in.
}
a.r.HandleFunc("/api/conf", a.GetConfigHandler())
a.r.HandleFunc("/api/conf/nics", a.GetNics())
a.r.HandleFunc("/api/conf/nic/{mac_address}", a.GetNic()).Methods("GET")
a.r.HandleFunc("/api/conf/nic/{mac_address}", a.UpdateNicConfig()).Methods("PUT")
a.r.HandleFunc("/api/conf/nic/{mac_address}", a.DeleteNic()).Methods("DELETE")
a.r.HandleFunc("/api/conf/deletenics", a.DeleteAllNics()).Methods("DELETE")
a.r.HandleFunc("/api/conf/nic", a.CreateNicConfig()).Methods("POST")
a.r.HandleFunc("/api/image", a.imageUploader.UploadHandler()).Methods("POST")
if err := a.RegisterUITemplate(a.r); err != nil {
log.Fatal(err)
}
if err := srv.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
func (api *API) GetConfigHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
js, err := json.Marshal(api.cfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
}
func (api *API) GetNics() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
js, err := json.Marshal(convertToServerItems(api.cfg.Nics))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
}
func (api *API) GetNic() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var serverConfig config.ServerConfig
vars := mux.Vars(r)
mac_address := vars["mac_address"]
serverConfig , found := api.cfg.Nics[mac_address]
if !found {
w.WriteHeader(404) // unprocessable entity
w.Write([]byte(fmt.Sprintf("nic %s does not exists", mac_address)))
}
item := ServerItem{
serverConfig.Ip,
serverConfig.Hostname,
mac_address,
serverConfig.Gateway,
serverConfig.Netmask,
}
js, err := json.Marshal(item)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
}
func convertToServerItems(nics map[string]config.ServerConfig) []ServerItem {
var items []ServerItem
for k,v := range nics {
item := ServerItem{
v.Ip,
v.Hostname,
k,
v.Gateway,
v.Netmask,
}
items = append(items, item)
}
return items
}
func (api *API) UpdateNicConfig() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("update")
var serverConfig config.ServerConfig
vars := mux.Vars(r)
mac_address := vars["mac_address"]
_ , found := api.cfg.Nics[mac_address]
if !found {
w.WriteHeader(422) // unprocessable entity
w.Write([]byte(fmt.Sprintf("nic %s does not exists", mac_address)))
panic(errors.New(fmt.Sprintf("nic %s does not exists", mac_address)))
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
if err := json.Unmarshal(body, &serverConfig); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
} else {
api.cfg.Nics[mac_address] = serverConfig
w.WriteHeader(http.StatusAccepted)
}
}
}
func (api *API) DeleteNic() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
mac_address := vars["mac_address"]
_ , found := api.cfg.Nics[mac_address]
if !found {
w.WriteHeader(422) // unprocessable entity
w.Write([]byte(fmt.Sprintf("nic %s does not exists", mac_address)))
panic(errors.New(fmt.Sprintf("nic %s does not exists", mac_address)))
} else {
delete(api.cfg.Nics, mac_address)
w.WriteHeader(http.StatusAccepted)
}
}
}
func (api *API) DeleteAllNics() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
api.cfg.Nics = map[string]config.ServerConfig{}
w.WriteHeader(http.StatusAccepted)
}
}
func (api *API) CreateNicConfig() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var serverItem ServerItem
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
if err := json.Unmarshal(body, &serverItem); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
} else {
if err:= serverItem.Validate(); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
} else {
serverConfig := config.ServerConfig{serverItem.Ip, serverItem.Hostname, serverItem.Gateway, serverItem.Netmask}
api.cfg.Nics[convertLowerCaseDash(serverItem.MacAddress)] = serverConfig
w.WriteHeader(http.StatusAccepted)
}
}
}
}
func convertLowerCaseDash(mac_address string) string{
return strings.ToLower(util.Colon_To_Dash(mac_address))
}