-
Notifications
You must be signed in to change notification settings - Fork 3
/
vboxapi.go
193 lines (178 loc) · 4.71 KB
/
vboxapi.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
/* vboxapi.go: this api provides limited virtualbox control through a restapi
* the api mimicks a limited version of vboxmanage-rest-api
* (https://www.npmjs.com/package/vboxmanage-rest-api)
*
* Author: J. Lowell Wofford <lowell@lanl.gov>
*
* This software is open source software available under the BSD-3 license.
* Copyright (c) 2018, Triad National Security, LLC
* See LICENSE file for details.
*/
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os/exec"
"regexp"
"strings"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var listenIP, urlBase, vbmPath *string
var listenPort *uint
var verbose *bool
type vbmResponse struct {
Err int32 `json:"e,omitempty"`
ErrMsg string `json:"err_msg,omitempty"`
Off []uint32 `json:"off,omitempty"`
On []uint32 `json:"on,omitempty"`
}
func main() {
urlBase = flag.String("base", "/vboxmanage", "base URL for api")
vbmPath = flag.String("vbm", "/usr/local/bin/vboxmanage", "full path to vboxmanage command")
listenIP = flag.String("ip", "127.0.0.1", "ip to listen on")
listenPort = flag.Uint("port", 8269, "port to listen on")
verbose = flag.Bool("v", false, "verbose messages")
flag.Parse()
router := mux.NewRouter()
router.HandleFunc(*urlBase+"/showvminfo/{name}", showVMInfo).Methods("GET")
router.HandleFunc(*urlBase+"/controlvm/{name}/poweroff", powerOff).Methods("GET")
router.HandleFunc(*urlBase+"/startvm/{name}", startVM).Methods("GET")
router.HandleFunc(*urlBase+"/startvm/{name}", startVM).Methods("GET").Queries("type", "{type}")
srv := &http.Server{
Handler: handlers.CORS(
handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization"}),
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedMethods([]string{"GET"}),
)(router),
Addr: fmt.Sprintf("%s:%d", *listenIP, *listenPort),
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Printf("starting http service at: http://%s:%d%s", *listenIP, *listenPort, *urlBase)
if e := srv.ListenAndServe(); e != nil {
log.Printf("failed to start http service: %v", e)
return
}
}
func showVMInfo(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
params := mux.Vars(req)
cmd := exec.Command(*vbmPath, "showvminfo", params["name"])
if *verbose {
log.Printf("Run: %v\n", cmd.Args)
}
co, e := cmd.Output()
if e != nil {
w.WriteHeader(http.StatusNotFound)
return
}
// parse out values
var rs struct {
Name string
Uuid string
Ram string
Vram string
State string
}
ret := map[string]string{
"Name": "",
"UUID": "",
"Memory size": "",
"VRAM size": "",
"State": "",
}
re, _ := regexp.Compile("^([^:]*): ([^(]*)(?: \\(.*)?$")
read := bytes.NewReader(co)
scan := bufio.NewScanner(read)
for scan.Scan() {
m := re.FindStringSubmatch(scan.Text())
if m == nil {
continue
}
if len(m) < 3 {
continue
}
ret[m[1]] = m[2]
}
rs.State = strings.TrimSpace(ret["State"])
rs.Name = strings.TrimSpace(ret["Name"])
rs.Uuid = strings.TrimSpace(ret["UUID"])
rs.Ram = strings.TrimSpace(ret["Memory size"])
rs.Vram = strings.TrimSpace(ret["VRAM size"])
w.Header().Set("Access-Control-Allow-Origin", "*")
j, _ := json.Marshal(rs)
if *verbose {
log.Printf("%s\n", j)
}
w.Write(j)
}
func powerOff(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
params := mux.Vars(req)
cmd := exec.Command(*vbmPath, "controlvm", params["name"], "poweroff")
if *verbose {
log.Printf("Run: %v\n", cmd.Args)
}
co, e := cmd.CombinedOutput()
var rs struct {
Shell struct {
Command string
Directory string
ExitCode int
Output string
}
}
rs.Shell.Command = strings.Join(cmd.Args, " ")
rs.Shell.Directory = "NOT_IMPLEMENTED"
if e != nil {
rs.Shell.ExitCode = 1
rs.Shell.Output = string(co)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
j, _ := json.Marshal(rs)
if *verbose {
log.Printf("%s\n", j)
}
w.Write(j)
}
func startVM(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
params := mux.Vars(req)
guiType := req.FormValue("type")
args := []string{"startvm", params["name"]}
if guiType != "" {
args = append(args, "--type", guiType)
}
cmd := exec.Command(*vbmPath, args...)
if *verbose {
log.Printf("Run: %v\n", cmd.Args)
}
co, e := cmd.CombinedOutput()
var rs struct {
Shell struct {
Command string
Directory string
ExitCode int
Output string
}
}
rs.Shell.Command = strings.Join(cmd.Args, " ")
rs.Shell.Directory = "NOT_IMPLEMENTED"
if e != nil {
rs.Shell.ExitCode = 1
rs.Shell.Output = string(co)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
j, _ := json.Marshal(rs)
if *verbose {
log.Printf("%s\n", j)
}
w.Write(j)
}