-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhyper-v-web-console.go
312 lines (287 loc) · 8.56 KB
/
hyper-v-web-console.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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
package main
import (
"bytes"
"encoding/json"
"html/template"
"net/http"
"os/exec"
"regexp"
"strconv"
"crypto/subtle"
"io/ioutil"
"log"
)
// Username & pass for basic auth
type Configuration struct {
Username string `json:"Username"`
Password string `json:"Password"`
}
// VM Infomation struct from powershell command 'Get-VM'.
type VM struct {
Name string `json:"Name"`
State int `json:"State"`
CPUUsage int `json:"CPUUsage"`
MemoryAssigned int `json:"MemoryAssigned"`
Uptime Uptime `json:"Uptime"`
Notes string `json:"Notes"`
StateDesc string `json:"StateDesc"`
IsRunning bool `json:"IsRunning"`
HHMMSS string `json:"HHMMSS"`
}
// Uptime is the VM's Uptime
type Uptime struct {
Days int `json:"Days"`
Hours int `json:"Hours"`
Minutes int `json:"Minutes"`
Seconds int `json:"Seconds"`
}
// VMs is a slice of structs.
type VMs struct {
vm []VM
}
func LoadConfig(path string) Configuration {
file, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("Config File Missing. ", err)
}
var config Configuration
err = json.Unmarshal(file, &config)
if err != nil {
log.Fatal("Config Parse Error: ", err)
}
return config
}
func BasicAuth(handler http.HandlerFunc, username, password, realm string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorised.\n"))
return
}
handler(w, r)
}
}
func main() {
config := LoadConfig("./config.json")
http.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
})
http.HandleFunc("/", BasicAuth(indexHandler, config.Username, config.Password, "Please enter your username and password for this site"))
http.HandleFunc("/checkpoint", checkpointHandler)
http.HandleFunc("/help", helpHandler)
http.HandleFunc("/startvm", startVMHandler)
http.HandleFunc("/restartvm", restartVMHandler)
http.HandleFunc("/stopvm", stopVMHandler)
// set the port and start server.
http.ListenAndServe(":8081", nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
// change the charaset encode of powershell to UTF-8.
errEnc := setEncodeUtf8()
if errEnc != nil {
errMsg := errEnc.Error() + "\nCouldn't encode to UTF-8."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
// get the VM's information from powershell command "Get-VM".
cmd := exec.Command("powershell", "Get-VM | Select-Object Name, State, CPUUsage, MemoryAssigned, Uptime, Notes | ConvertTo-Json")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
errMsg := err.Error() + "\nCouldn't get the vm information."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
// decode JSON.
dec := json.NewDecoder(bytes.NewReader(out.Bytes()))
var vms VMs
errDec := dec.Decode(&vms.vm)
if errDec != nil {
errMsg := err.Error() + "\nCouldn't decode JSON."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
// set the VM Struct's element values.
setVMElem(&vms)
// render a template web page.
var indexTemplate = template.Must(template.ParseFiles("./public/index.html"))
indexTemplate.Execute(w, vms.vm)
}
// checkpoint
func checkpointHandler(w http.ResponseWriter, r *http.Request) {
var indexTemplate = template.Must(template.ParseFiles("./public/checkpoint.html"))
indexTemplate.Execute(w, nil)
}
// help
func helpHandler(w http.ResponseWriter, r *http.Request) {
var indexTemplate = template.Must(template.ParseFiles("./public/help.html"))
indexTemplate.Execute(w, nil)
}
// start vm from POST using powershell command "Start-VM".
func startVMHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
vmName := r.FormValue("vmName")
// check an unsupported charactert in the parameter
if hasUnsupportedChar(vmName) {
errMsg := "\nThe post parameter has an unsupported character. Please check the parameter."
http.Error(w, errMsg, http.StatusBadRequest)
return
}
pscmd := "Start-VM -name " + vmName
cmd := exec.Command("powershell", pscmd)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
errMsg := err.Error() + "\nCouldn't start the VM.\nThe memory on the host server is not enough to start the vm, probably."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
}
}
// restart vm from POST using powershell command "Reboot-VM".
func restartVMHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
vmName := r.FormValue("vmName")
// check an unsupported charactert in the parameter
if hasUnsupportedChar(vmName) {
errMsg := "\nThe post parameter has an unsupported character. Please check the parameter."
http.Error(w, errMsg, http.StatusBadRequest)
return
}
pscmd := "Restart-VM -name " + vmName + " -Force"
cmd := exec.Command("powershell", pscmd)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
errMsg := err.Error() + "\nCouldn't reboot the VM.\nThe memory on the host server is not enough to start the vm, probably."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
}
}
// stop vm from POST using powershell command "Stop-VM".
func stopVMHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
vmName := r.FormValue("vmName")
// check an unsupported charactert in the parameter
if hasUnsupportedChar(vmName) {
errMsg := "\nThe post parameter has an unsupported character. Please check the parameter."
http.Error(w, errMsg, http.StatusBadRequest)
return
}
pscmd := "Stop-VM -name " + vmName
cmd := exec.Command("powershell", pscmd)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
errMsg := err.Error() + "\nCouldn't stop the VM."
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
} else {
http.Redirect(w, r, "/", http.StatusMethodNotAllowed)
}
}
// setVMElem set the vm struct's element values
// such as StateDesc, IsRunning, HHMMSS.
func setVMElem(vms *VMs) {
for i := range vms.vm {
vm := &vms.vm[i]
vm.MemoryAssigned = vm.MemoryAssigned / 1024 / 1024 // MB
vm.StateDesc, vm.IsRunning = parseState(vm.State)
vm.HHMMSS = toHHMMSS(&vm.Uptime)
}
}
// The parseState check the vm's state
// and return the stateDesc and the boolean value that the vm is runnning or not
func parseState(st int) (state string, isRun bool) {
switch st {
case 0:
state = "Unknown"
isRun = false
case 2:
state = "Running"
isRun = true
case 3:
state = "Stopped"
isRun = false
case 32768:
state = "Paused"
isRun = false
case 32769:
state = "Suspended"
isRun = false
case 32270:
state = "Starting"
isRun = true
case 32771:
state = "Snapshotting"
isRun = false
case 32773:
state = "Saving"
isRun = false
case 32774:
state = "Stopping"
isRun = false
case 32776:
state = "Pausing"
isRun = false
case 32777:
state = "Resuming"
isRun = true
default:
state = "other"
isRun = false
}
return state, isRun
}
// setEncodeUtf8 change a powershell output's enode to utf-8
// because golang cannot read utf-8 directory.
func setEncodeUtf8() error {
cmd := exec.Command("chcp", "65001")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
return err
}
// toHHMMSS change to "HHMMSS" string from vm's uptime
func toHHMMSS(uptime *Uptime) string {
var D, hh, mm, ss string
if uptime.Days > 0 {
D = strconv.Itoa(uptime.Days) + "."
}
if uptime.Hours < 10 {
hh = "0" + strconv.Itoa(uptime.Hours)
} else {
hh = strconv.Itoa(uptime.Hours)
}
if uptime.Minutes < 10 {
mm = "0" + strconv.Itoa(uptime.Minutes)
} else {
mm = strconv.Itoa(uptime.Minutes)
}
if uptime.Seconds < 10 {
ss = "0" + strconv.Itoa(uptime.Seconds)
} else {
ss = strconv.Itoa(uptime.Seconds)
}
return D + hh + ":" + mm + ":" + ss
}
// hasUnsupportedChar check the parameters that contain unsupported characters
func hasUnsupportedChar(str string) bool {
reg := `[^0-9a-zA-Z-_\.\s]` // add some characters that contain in the vm names
return regexp.MustCompile(reg).Match([]byte(str))
}