forked from canonical/lxd
/
devlxd.go
246 lines (203 loc) · 6.79 KB
/
devlxd.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gorilla/mux"
"github.com/lxc/lxd/lxd/daemon"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/version"
)
// DevLxdServer creates an http.Server capable of handling requests against the
// /dev/lxd Unix socket endpoint created inside VMs.
func devLxdServer(d *Daemon) *http.Server {
return &http.Server{
Handler: devLxdAPI(d),
}
}
type devLxdResponse struct {
content interface{}
code int
ctype string
}
type instanceData struct {
Name string `json:"name"`
Config map[string]string `json:"config,omitempty"`
}
func okResponse(ct interface{}, ctype string) *devLxdResponse {
return &devLxdResponse{ct, http.StatusOK, ctype}
}
type devLxdHandler struct {
path string
/*
* This API will have to be changed slightly when we decide to support
* websocket events upgrading, but since we don't have events on the
* server side right now either, I went the simple route to avoid
* needless noise.
*/
f func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse
}
var devlxdConfigGet = devLxdHandler{"/1.0/config", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
data, err := ioutil.ReadFile("instance-data")
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
var instance instanceData
err = json.Unmarshal(data, &instance)
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
filtered := []string{}
for k := range instance.Config {
if strings.HasPrefix(k, "user.") {
filtered = append(filtered, fmt.Sprintf("/1.0/config/%s", k))
}
}
return okResponse(filtered, "json")
}}
var devlxdConfigKeyGet = devLxdHandler{"/1.0/config/{key}", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
key := mux.Vars(r)["key"]
if !strings.HasPrefix(key, "user.") {
return &devLxdResponse{"not authorized", http.StatusForbidden, "raw"}
}
data, err := ioutil.ReadFile("instance-data")
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
var instance instanceData
err = json.Unmarshal(data, &instance)
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
value, ok := instance.Config[key]
if !ok {
return &devLxdResponse{"not found", http.StatusNotFound, "raw"}
}
return okResponse(value, "raw")
}}
var devlxdMetadataGet = devLxdHandler{"/1.0/meta-data", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
data, err := ioutil.ReadFile("instance-data")
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
var instance instanceData
err = json.Unmarshal(data, &instance)
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
value := instance.Config["user.meta-data"]
return okResponse(fmt.Sprintf("#cloud-config\ninstance-id: %s\nlocal-hostname: %s\n%s", instance.Name, instance.Name, value), "raw")
}}
var devLxdEventsGet = devLxdHandler{"/1.0/events", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
err := eventsGet(d, r).Render(w)
if err != nil {
return &devLxdResponse{"internal server error", http.StatusInternalServerError, "raw"}
}
return okResponse("", "raw")
}}
var handlers = []devLxdHandler{
{"/", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
return okResponse([]string{"/1.0"}, "json")
}},
{"/1.0", func(d *Daemon, w http.ResponseWriter, r *http.Request) *devLxdResponse {
return okResponse(shared.Jmap{"api_version": version.APIVersion}, "json")
}},
devlxdConfigGet,
devlxdConfigKeyGet,
devlxdMetadataGet,
devLxdEventsGet,
}
func hoistReq(f func(*Daemon, http.ResponseWriter, *http.Request) *devLxdResponse, d *Daemon) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
resp := f(d, w, r)
if resp.code != http.StatusOK {
http.Error(w, fmt.Sprintf("%s", resp.content), resp.code)
} else if resp.ctype == "json" {
w.Header().Set("Content-Type", "application/json")
util.WriteJSON(w, resp.content, daemon.Debug)
} else if resp.ctype != "websocket" {
w.Header().Set("Content-Type", "application/octet-stream")
fmt.Fprintf(w, resp.content.(string))
}
}
}
func devLxdAPI(d *Daemon) http.Handler {
m := mux.NewRouter()
for _, handler := range handlers {
m.HandleFunc(handler.path, hoistReq(handler.f, d))
}
return m
}
// Create a new net.Listener bound to the unix socket of the devlxd endpoint.
func createDevLxdlListener(dir string) (net.Listener, error) {
path := filepath.Join(dir, "lxd", "sock")
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
return nil, err
}
// If this socket exists, that means a previous LXD instance died and
// didn't clean up. We assume that such LXD instance is actually dead
// if we get this far, since localCreateListener() tries to connect to
// the actual lxd socket to make sure that it is actually dead. So, it
// is safe to remove it here without any checks.
//
// Also, it would be nice to SO_REUSEADDR here so we don't have to
// delete the socket, but we can't:
// http://stackoverflow.com/questions/15716302/so-reuseaddr-and-af-unix
//
// Note that this will force clients to reconnect when LXD is restarted.
err = socketUnixRemoveStale(path)
if err != nil {
return nil, err
}
listener, err := socketUnixListen(path)
if err != nil {
return nil, err
}
err = socketUnixSetPermissions(path, 0600)
if err != nil {
listener.Close()
return nil, err
}
return listener, nil
}
// Remove any stale socket file at the given path.
func socketUnixRemoveStale(path string) error {
// If there's no socket file at all, there's nothing to do.
if !shared.PathExists(path) {
return nil
}
logger.Debugf("Detected stale unix socket, deleting")
err := os.Remove(path)
if err != nil {
return fmt.Errorf("could not delete stale local socket: %v", err)
}
return nil
}
// Change the file mode of the given unix socket file,
func socketUnixSetPermissions(path string, mode os.FileMode) error {
err := os.Chmod(path, mode)
if err != nil {
return fmt.Errorf("cannot set permissions on local socket: %v", err)
}
return nil
}
// Bind to the given unix socket path.
func socketUnixListen(path string) (net.Listener, error) {
addr, err := net.ResolveUnixAddr("unix", path)
if err != nil {
return nil, fmt.Errorf("cannot resolve socket address: %v", err)
}
listener, err := net.ListenUnix("unix", addr)
if err != nil {
return nil, fmt.Errorf("cannot bind socket: %v", err)
}
return listener, err
}