Skip to content

Commit 6870fc4

Browse files
committed
v1.0
0 parents  commit 6870fc4

File tree

6 files changed

+266
-0
lines changed

6 files changed

+266
-0
lines changed

.gitignore

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Binaries for programs and plugins
2+
*.exe
3+
*.exe~
4+
*.dll
5+
*.so
6+
*.dylib
7+
8+
# Test binary, build with `go test -c`
9+
*.test
10+
11+
# Output of the go coverage tool, specifically when used with LiteIDE
12+
*.out

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 Keith Kim
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

Makefile

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Go parameters
2+
OS_MACH=$(shell uname -s; uname -m)
3+
BINARY_NAME=vultrdata
4+
ifeq ($(OS_MACH),Linux x86_64)
5+
BINARY_LINUX=$(BINARY_NAME)
6+
else
7+
BINARY_LINUX=$(BINARY_NAME)-linux
8+
endif
9+
10+
all: test build
11+
12+
rebuild: delete-binary build
13+
14+
rebuild-linux: delete-binary-linux build-linux
15+
16+
delete-binary:
17+
-rm $(BINARY_NAME) 2>/dev/null
18+
19+
delete-binary-linux:
20+
-rm $(BINARY_LINUX) 2>/dev/null
21+
22+
build:
23+
go build -o $(BINARY_NAME) -v
24+
25+
build-linux:
26+
CGO_ENABLED= GOOS=linux GOARCH=amd64 go build -o $(BINARY_LINUX) -v
27+
28+
build-darwin:
29+
CGO_ENABLED= GOOS=darwin GOARCH=amd64 go build -o $(BINARY_DARWIN) -v
30+
31+
test:
32+
go test -v ./...
33+
34+
clean:
35+
go clean
36+
rm -f $(BINARY_NAME)
37+
rm -f $(BINARY_LINUX)
38+
39+
deploy-prod: build-linux
40+
ssh prod "mv /opt/vultrdata/$(BINARY_NAME) /opt/vultrdata/$(BINARY_NAME)-old || true"
41+
scp $(BINARY_LINUX) prod:/opt/vultrdata/$(BINARY_NAME)
42+
ssh prod "sudo service vultrdata restart"
43+
44+
run: deps
45+
go run -race main.go
46+
47+
deps:
48+
go get github.com/kuangchanglang/graceful

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# vultrdata
2+
3+
Service to return sanitized data about the requesting instance.
4+
5+
## Installation
6+
7+
For systemd Linux systems:
8+
9+
- Run `make deps build-linux`
10+
- Create the directory /opt/vultrdata
11+
- Copy `vultrdata-linux` to /opt/vultrdata/vultrdata
12+
(or copy the file named `vultrdata` if make run on a Linux system)
13+
- Copy the file vultrdata.service to /etc/systemd/vultrdata.service
14+
- Edit that vultrdata.service file changing the API_KEY value as well as listen addr/port and/or removing --userdata option
15+
- On that system: `sudo systemctl daemon-reload`
16+
- On that system: `sudo systemctl enable vultrdata`
17+
- On that system: `sudo systemctl start vultrdata`
18+
19+
It is recommended that the listen address is chosen to be on the internal network for security. When instances are created with internal networking enabled it usually has an additional address starting with 10. or possibly some other non-routing range.
20+
21+
## Testing
22+
23+
- `curl -si 'http://10.1.1.1:8888/'`
24+
(Using whichever listen addr/port was chosen in vultrdata.service)
25+
- Run the same command from another instance which should return data for that instance different than the first

vultrdata.go

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"flag"
6+
"fmt"
7+
"io"
8+
"io/ioutil"
9+
"log"
10+
"net/http"
11+
"os"
12+
"strconv"
13+
"strings"
14+
"time"
15+
16+
"github.com/kuangchanglang/graceful"
17+
)
18+
19+
var (
20+
httpClient = &http.Client{
21+
Timeout: time.Second * 10,
22+
}
23+
)
24+
25+
var (
26+
addr = flag.String("addr", "0.0.0.0", "Listen address")
27+
port = flag.Int("port", 8888, "Listen port")
28+
userdata = flag.Bool("userdata", false, "Also return 'userdata'")
29+
apiKey = ""
30+
)
31+
32+
func instanceHandler(w http.ResponseWriter, r *http.Request) {
33+
body, err := doApiRequest(w, r, "GET", "https://api.vultr.com/v1/server/list", nil)
34+
if err != nil {
35+
w.WriteHeader(http.StatusInternalServerError)
36+
w.Header().Set("content-type", "text/plain")
37+
w.Write([]byte(err.Error() + "\n"))
38+
return
39+
}
40+
41+
var subidData map[string]map[string]interface{}
42+
err = json.Unmarshal(body, &subidData)
43+
if err != nil {
44+
w.WriteHeader(http.StatusInternalServerError)
45+
w.Header().Set("content-type", "text/plain")
46+
w.Write([]byte(err.Error() + "\n"))
47+
return
48+
}
49+
50+
remoteAddr := strings.Split(r.RemoteAddr, ":")[0]
51+
52+
found := findByIpAddress(subidData, remoteAddr)
53+
if found == nil {
54+
w.WriteHeader(http.StatusNotFound)
55+
w.Header().Set("content-type", "text/plain")
56+
w.Write([]byte(""))
57+
return
58+
}
59+
60+
delete(found, "default_password")
61+
delete(found, "kvm_url")
62+
63+
if *userdata {
64+
url := fmt.Sprintf("https://api.vultr.com/v1/server/get_user_data?SUBID=%v", found["SUBID"])
65+
body, err = doApiRequest(w, r, "GET", url, nil)
66+
if err != nil {
67+
w.WriteHeader(http.StatusInternalServerError)
68+
w.Header().Set("content-type", "text/plain")
69+
w.Write([]byte(err.Error() + "\n"))
70+
return
71+
}
72+
var kv map[string]string
73+
json.Unmarshal(body, &kv)
74+
if kv != nil {
75+
if v, ok := kv["userdata"]; ok {
76+
found["userdata"] = v
77+
}
78+
}
79+
}
80+
81+
data, err := json.MarshalIndent(found, "", " ")
82+
if err != nil {
83+
w.WriteHeader(http.StatusInternalServerError)
84+
w.Header().Set("content-type", "text/plain")
85+
w.Write([]byte(err.Error() + "\n"))
86+
return
87+
}
88+
89+
w.Header().Set("content-type", "application/json")
90+
w.Write(data)
91+
}
92+
93+
func doApiRequest(w http.ResponseWriter, r *http.Request, method, url string, body io.Reader) ([]byte, error) {
94+
req, err := http.NewRequest(method, url, body)
95+
if err != nil {
96+
return nil, err
97+
}
98+
99+
req.Header.Set("API-Key", apiKey)
100+
resp, err := httpClient.Do(req)
101+
if err != nil {
102+
return nil, err
103+
}
104+
105+
defer resp.Body.Close()
106+
data, err := ioutil.ReadAll(resp.Body)
107+
if err != nil {
108+
return nil, err
109+
}
110+
return data, nil
111+
}
112+
113+
func findByIpAddress(subidData map[string]map[string]interface{}, remoteAddr string) map[string]interface{} {
114+
for _, data := range subidData {
115+
for _, name := range []string{"internal_ip", "main_ip", "v6_main_ip"} {
116+
value := data[name]
117+
if s, ok := value.(string); ok {
118+
if s == remoteAddr {
119+
return data
120+
}
121+
}
122+
}
123+
}
124+
return nil
125+
}
126+
127+
func main() {
128+
flag.Parse()
129+
130+
apiKey = os.Getenv("API_KEY")
131+
if apiKey == "" {
132+
fmt.Printf("Missing API_KEY environment variable.")
133+
os.Exit(1)
134+
}
135+
136+
http.HandleFunc("/", instanceHandler)
137+
138+
server := graceful.NewServer()
139+
140+
server.Register(*addr+":"+strconv.Itoa(*port), http.DefaultServeMux)
141+
if graceful.IsWorker() {
142+
log.Printf("Listening on %v:%d\n", *addr, *port)
143+
}
144+
if err := server.Run(); err != nil {
145+
fmt.Printf("graceful.Server.Run: %v", err)
146+
}
147+
}

vultrdata.service

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[Unit]
2+
Description=Vultr Instance Data Service
3+
After=network.target
4+
5+
[Service]
6+
User=ubuntu
7+
WorkingDirectory=/opt/vultrdata
8+
Restart=always
9+
Environment=API_KEY=____________________________________
10+
ExecStart=/opt/vultrdata/vultrdata --addr 127.0.0.1 --port 8888 --userdata
11+
12+
[Install]
13+
WantedBy=multi-user.target

0 commit comments

Comments
 (0)