-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
181 lines (169 loc) · 4.57 KB
/
main.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
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"math"
"os"
"os/exec"
"strconv"
"strings"
)
func main() {
//Setup flags
iface := flag.String("iface", "vmbr0", "network interface")
format := flag.String("format", "hosts", "output format (ansible or hosts)")
flag.Parse()
// Check is -output flag is acceptable
checkFormat(*format)
//Checking is pve cluster available (currently relying on /etc/pve/corosync.conf)
detectPveCluster()
fmt.Fprintln(os.Stderr, "Gathering info about cluster nodes...")
list := getNodeNamelist()
ipAddr := getIPaddressess(list, *iface)
fmt.Fprintln(os.Stderr, "Printing result...")
printResult(ipAddr, *format)
fmt.Fprintln(os.Stderr, "Done!")
}
// Accessing Proxmox API to get list of nodes
func getNodeNamelist() []string {
var list []string
var v interface{}
jsonRaw := apiGetReq("nodes")
json.Unmarshal(jsonRaw, &v)
v1 := v.([]interface{})
for i := range v1 {
data := v1[i].(map[string]interface{})
for k, v := range data {
if k == "node" {
list = append(list, v.(string))
}
}
}
return list
}
//GET request to PVE API
func apiGetReq(path string) []byte {
var rawJSON []byte
resp, err := exec.Command("pvesh", "get", path, "-output-format", "json").CombinedOutput()
check(err)
reader := bytes.NewReader(resp)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
firstChar := string(scanner.Text()[0])
if firstChar == "[" {
rawJSON = []byte(scanner.Text())
if json.Valid(rawJSON) {
break
} else {
rawJSON = nil
}
}
}
return rawJSON
}
//Getting /nodes/{$nodename}/network json for every node and iterating through it
func getIPaddressess(nodeList []string, iface string) map[string]string {
var ipMap map[string]string
var v interface{}
var ifmap map[string]string
ipMap = make(map[string]string)
for i := range nodeList {
ifmap = make(map[string]string)
nodeName := nodeList[i]
_, _ = fmt.Fprintln(os.Stderr, strings.Join([]string{"[", strconv.Itoa(i + 1), "/", strconv.Itoa(len(nodeList)), "]"}, ""), "Gathering info about", nodeList[i], "\b...")
apiPath := strings.Join([]string{"/nodes/", nodeName, "/network"}, "")
rawJSON := apiGetReq(apiPath)
if rawJSON == nil {
fmt.Println("Failed to get information about", nodeName)
os.Exit(10)
}
json.Unmarshal(rawJSON, &v)
v1 := v.([]interface{}) // Getting array of JSONs with network interfaces information here
for i := range v1 { // And iterating through it
data := v1[i].(map[string]interface{}) // Getting interfaces name and ip
var addr string
var ifname string
for k, v := range data {
if k == "address" {
addr = v.(string)
}
if k == "iface" {
ifname = v.(string)
}
}
ifmap[ifname] = addr // Writing data to map
}
if ipAddr, ok := ifmap[iface]; ok { // If interface provided with flag exist, write it to final map
ipMap[nodeList[i]] = ipAddr
}
}
for k := range ipMap {
splittedAddr := strings.Split(ipMap[k], ".") // Separating CIDR mask if present
splittedOctet := strings.Split(splittedAddr[3], "/")
if len(splittedOctet) == 1 {
ipMap[k] = strings.Join(splittedAddr, ".")
} else {
splittedAddr[3] = splittedOctet[0]
ipMap[k] = strings.Join(splittedAddr, ".")
}
}
return ipMap
}
func printResult(ipMap map[string]string, format string) {
var longest int
longest = 0
for k := range ipMap {
if len(ipMap[k]) > longest {
longest = len(ipMap[k])
}
}
maxDivider, _ := math.Modf(float64(longest) / 8)
for k := range ipMap {
tabulator := "\t"
divider, _ := math.Modf(float64(len(k)) / 8)
tabs := maxDivider - divider
for i := 0; i < int(tabs); i++ {
tabulator = strings.Join([]string{tabulator, "\t"}, "")
}
if format == "ansible" {
fmt.Printf("%s%sansible_host=%s\n", k, tabulator, ipMap[k])
} else if format == "hosts" {
fmt.Println(strings.Join([]string{ipMap[k], tabulator, k}, ""))
}
}
}
func printResultAnsible(ipMap map[string]string) {
for k, v := range ipMap {
splittedAddr := strings.Split(v, ".")
splittedOctet := strings.Split(splittedAddr[3], "/")
if len(splittedOctet) > 1 {
splittedAddr[3] = splittedOctet[0]
}
v = strings.Join(splittedAddr, ".")
fmt.Printf("%s ansible_host=%s\n", k, v)
}
}
func detectPveCluster() {
_, err := os.Stat("/etc/pve/corosync.conf")
if err != nil {
fmt.Println("Proxmox corosync config not detected on host. Exiting...")
os.Exit(1)
}
}
func checkFormat(format string) {
switch format {
case "ansible", "hosts":
return
default:
fmt.Println("Incorrect format definition. Use ansible or hosts.")
os.Exit(10)
}
}
func check(e error) {
if e != nil {
panic(e)
}
}