-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
194 lines (168 loc) · 5.28 KB
/
list.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
package list
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
message "github.com/efbar/more-serverless/slack-message/slackmessage"
"github.com/ryanuber/columnize"
compute "google.golang.org/api/compute/v1"
"google.golang.org/api/option"
)
type Instance struct {
Name string `json:"name"`
Zone string `json:"zone"`
MachineType string `json:"machine_type"`
Preemptible string `json:"preemptible"`
InternalIP string `json:"internal_ip"`
ExternalIP string `json:"external_ip"`
Status string `json:"status"`
}
type RequestBody struct {
ProjectId string `json:"projectId"`
Region string `json:"region"`
JsonKeyPath string `json:"jsonKeyPath,omitempty"`
SlackToken string `json:"slackToken,omitempty"`
SlackChannel string `json:"slackChannel,omitempty"`
SlackEmoji string `json:"slackEmoji,omitempty"`
}
type Response struct {
Payload []Instance `json:"payload"`
Headers map[string][]string `json:"headers"`
}
func Serve(w http.ResponseWriter, r *http.Request) {
var input []byte
if r.Body != nil {
defer r.Body.Close()
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
input = reqBody
}
if len(input) == 0 {
fmt.Println("empty body")
}
rb := RequestBody{}
err := json.Unmarshal(input, &rb)
if err != nil {
fmt.Println("Json parsing error:", err.Error())
http.Error(w, "Input data error", http.StatusBadRequest)
return
}
projectId := rb.ProjectId
if len(projectId) == 0 {
fmt.Println("empty projectId value")
http.Error(w, "Input data error", http.StatusBadRequest)
return
}
projectRegion := rb.Region
if len(projectRegion) == 0 {
fmt.Println("empty region value")
http.Error(w, "Input data error", http.StatusBadRequest)
return
}
googleCreds := os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")
var serviceAccountPath string
if len(rb.JsonKeyPath) != 0 {
serviceAccountPath = rb.JsonKeyPath
fmt.Printf("using jsonKeyPath value %s\n", rb.JsonKeyPath)
} else {
serviceAccountPath = googleCreds
fmt.Printf("using google creds environment value %s\n", googleCreds)
}
var jsonKey string
if _, err := os.Stat(serviceAccountPath); err == nil {
jsonKeyFile, _ := ioutil.ReadFile(serviceAccountPath)
jsonKey = string(jsonKeyFile)
}
var computeService *compute.Service
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if len(jsonKey) != 0 {
computeService, err = compute.NewService(ctx, option.WithCredentialsFile(rb.JsonKeyPath))
} else {
fmt.Println("jsonkey empty, not using creds option")
computeService, err = compute.NewService(ctx)
}
if err != nil {
fmt.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
region, err := computeService.Regions.Get(projectId, projectRegion).Do()
if err != nil {
fmt.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if r.Header.Get("Content-Type") == "text/plain" {
out := []string{"NAME\tZONE\tMACHINE_TYPE\tPREEMPTIBLE\tINTERNAL_IP\tEXTERNAL_IP\tSTATUS"}
for _, val := range region.Zones {
instances, _ := computeService.Instances.List(projectId, val[strings.LastIndex(val, "/")+1:]).Do()
for _, v := range instances.Items {
zones := strings.Split(v.Zone, "/")
mType := strings.Split(v.MachineType, "/")
out = append(out, v.Name+"\t"+zones[len(zones)-1]+"\t"+mType[len(mType)-1]+"\t"+strconv.FormatBool(v.Scheduling.Preemptible)+"\t"+v.NetworkInterfaces[0].NetworkIP+"\t"+v.NetworkInterfaces[0].AccessConfigs[0].NatIP+"\t"+v.Status)
}
}
columnConf := columnize.DefaultConfig()
columnConf.Delim = "\t"
columnConf.Glue = " "
columnConf.NoTrim = false
resBody := columnize.Format(out, columnConf)
if len(rb.SlackToken) > 0 && len(rb.SlackChannel) > 0 {
slackNotification(&rb, resBody)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-type", "text/plain")
w.Write([]byte(resBody))
} else {
var vmList []Instance
for _, val := range region.Zones {
var vm Instance
instances, _ := computeService.Instances.List(projectId, val[strings.LastIndex(val, "/")+1:]).Do()
for _, v := range instances.Items {
zones := strings.Split(v.Zone, "/")
mType := strings.Split(v.MachineType, "/")
vm.Name = v.Name
vm.Zone = zones[len(zones)-1]
vm.MachineType = mType[len(mType)-1]
vm.Preemptible = strconv.FormatBool(v.Scheduling.Preemptible)
vm.InternalIP = v.NetworkInterfaces[0].NetworkIP
vm.ExternalIP = v.NetworkInterfaces[0].AccessConfigs[0].NatIP
vm.Status = v.Status
vmList = append(vmList, vm)
}
}
jsonResponse := Response{
Payload: vmList,
Headers: r.Header,
}
resBody, err := json.Marshal(jsonResponse)
if err != nil {
fmt.Println(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(resBody)
}
}
func slackNotification(rb *RequestBody, resBody string) {
slackToken := rb.SlackToken
slackChannelID := rb.SlackChannel
slackEmoji := rb.SlackEmoji
slackMessage := "GCP message " + slackEmoji + "\n```" + resBody + "```"
sent, err := message.Send(slackToken, slackMessage, slackChannelID)
if err != nil {
fmt.Printf("slack error: %s\n", err)
}
fmt.Println(sent)
}