-
Notifications
You must be signed in to change notification settings - Fork 266
/
utils.go
525 lines (481 loc) · 11.8 KB
/
utils.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*
* Copyright (c) 2024 Yunshan Networks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package common
import (
"bytes"
"compress/zlib"
"crypto/tls"
. "encoding/binary"
"encoding/csv"
"encoding/xml"
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"time"
simplejson "github.com/bitly/go-simplejson"
"github.com/op/go-logging"
"gopkg.in/yaml.v3"
"inet.af/netaddr"
"github.com/deepflowio/deepflow/server/controller/common"
"github.com/deepflowio/deepflow/server/controller/db/mysql"
)
var log = logging.MustGetLogger("genesis.common")
type VifInfo struct {
MaskLen uint32
Address string
Scope string
}
type Iface struct {
Index int
PeerIndex int
MAC string
Name string
Peer string
IPs []VifInfo
}
type KVMUser struct {
UUID string `xml:"uuid,attr"`
Value string `xml:",innerxml"`
}
type KVMProject struct {
UUID string `xml:"uuid,attr"`
Value string `xml:",innerxml"`
}
type KVMOwner struct {
User KVMUser `xml:"user"`
Project KVMProject `xml:"project"`
}
type KVMInstance struct {
Namespace string `xml:"xmlns nova,attr"`
Name string `xml:"name"`
Owner KVMOwner `xml:"owner"`
}
type KVMMetaData struct {
Instance KVMInstance `xml:"instance"`
}
type KVMMac struct {
Value string `xml:"address,attr"`
}
type KVMSource struct {
Value string `xml:"bridge,attr"`
}
type KVMTarget struct {
Value string `xml:"dev,attr"`
}
type KVMModel struct {
Value string `xml:"type,attr"`
}
type KVMAddress struct {
AddressValue string `xml:"type,attr"`
DomainValue string `xml:"domain,attr"`
BusValue string `xml:"bus,attr"`
SlotValue string `xml:"slot,attr"`
FunctionValue string `xml:"function,attr"`
}
type KVMInterface struct {
Type string `xml:"type,attr"`
Mac KVMMac `xml:"mac"`
Source KVMSource `xml:"source"`
Target KVMTarget `xml:"target"`
Model KVMModel `xml:"model"`
Address KVMAddress `xml:"address"`
}
type KVMDevices struct {
Interfaces []KVMInterface `xml:"interface"`
}
type KVMDomain struct {
Type string `xml:"type,attr"`
UUID string `xml:"uuid"`
Name string `xml:"name"`
Label string `xml:"label"`
MetaData KVMMetaData `xml:"metadata"`
Devices KVMDevices `xml:"devices"`
}
type KVMDomains struct {
Domains []KVMDomain `xml:"domain"`
}
type XMLVPC struct {
UUID string
Name string
}
type XMLInterface struct {
Mac string
Target string
}
type XMLVM struct {
UUID string
Name string
Label string
VPC XMLVPC
Interfaces []XMLInterface
}
type scrapeConfig struct {
JobName string `yaml:"job_name"`
HonorLabels bool `yaml:"honor_labels"`
}
type prometheusConfig struct {
ScrapeConfigs []scrapeConfig `yaml:"scrape_configs"`
}
var IfaceRegex = regexp.MustCompile("^(\\d+):\\s+([^@:]+)(@.*)?\\:")
var MACRegex = regexp.MustCompile("^\\s+link/\\S+\\s+(([\\dA-Za-z]{2}:){5}[\\dA-Za-z]{2}) brd.*$")
var IPRegex = regexp.MustCompile("^\\s+inet6?\\s+([\\d\\.A-Za-z:]+)/(\\d+)\\s+.*scope\\s+(global|link|host)")
func ParseIPOutput(s string) ([]Iface, error) {
ifaces := []Iface{}
if s == "" {
return ifaces, nil
}
iface := Iface{Index: -1}
lines := strings.Split(s, "\n")
if len(lines) == 1 && lines[0] == "" {
return ifaces, nil
}
for _, line := range lines {
ifaceMatched := IfaceRegex.FindStringSubmatch(line)
if ifaceMatched != nil {
if iface.Index != -1 {
ifaces = append(ifaces, iface)
iface = Iface{}
}
index, err := strconv.Atoi(ifaceMatched[1])
if err != nil {
return []Iface{}, err
}
iface.Index = index
iface.Name = ifaceMatched[2]
if ifaceMatched[3] != "" {
iface.Peer = ifaceMatched[3][1:]
}
if iface.Peer != "" && strings.HasPrefix(iface.Peer, "if") {
peerIndex, err := strconv.Atoi(iface.Peer[2:])
if err != nil {
return []Iface{}, err
}
iface.PeerIndex = peerIndex
}
}
macMatched := MACRegex.FindStringSubmatch(line)
if macMatched != nil {
iface.MAC = macMatched[1]
} else if strings.HasPrefix(iface.Name, "tunl0") {
iface.MAC = "00:00:00:00:00:00"
}
ipMatched := IPRegex.FindStringSubmatch(line)
if ipMatched != nil {
maskLen, err := strconv.Atoi(ipMatched[2])
if err != nil {
return []Iface{}, err
}
iface.IPs = append(iface.IPs, VifInfo{
Address: ipMatched[1],
Scope: ipMatched[3],
MaskLen: uint32(maskLen),
})
}
}
ifaces = append(ifaces, iface)
return ifaces, nil
}
func ParseCSV(s string, fields ...string) ([]map[string]string, error) {
ret := []map[string]string{}
if s == "" {
return ret, nil
}
sReader := strings.NewReader(s)
csvReader := csv.NewReader(sReader)
csvs, err := csvReader.ReadAll()
if err != nil {
return ret, err
}
for _, c := range csvs[1:] {
item := map[string]string{}
for i, name := range csvs[0] {
sort.Strings(fields)
index := sort.SearchStrings(fields, name)
if len(fields) > 0 && !(index < len(fields) && fields[index] == name) {
continue
}
item[name] = c[i]
}
ret = append(ret, item)
}
return ret, nil
}
func ParseCSVWithKey(s, key string, fields ...string) (map[string]map[string]string, error) {
ret := map[string]map[string]string{}
if s == "" {
return ret, nil
}
sReader := strings.NewReader(s)
csvReader := csv.NewReader(sReader)
csvs, err := csvReader.ReadAll()
if err != nil {
return ret, err
}
for _, c := range csvs[1:] {
item := map[string]string{}
k := ""
for i, name := range csvs[0] {
if name == key {
k = c[i]
}
sort.Strings(fields)
index := sort.SearchStrings(fields, name)
if len(fields) > 0 && !(index < len(fields) && fields[index] == name) {
continue
}
item[name] = c[i]
}
if k != "" {
ret[k] = item
}
}
return ret, nil
}
func ParseKVString(s string) (map[string]string, error) {
options := map[string]string{}
trimString := strings.Trim(s, " ")
kvSlice := strings.Split(trimString, " ")
for _, kvString := range kvSlice {
kv := strings.Split(kvString, "=")
if len(kv) == 1 {
kv = append(kv, "")
}
options[kv[0]] = kv[1]
}
return options, nil
}
func ParseBrctlShow(s string) (map[string][]string, error) {
brs := map[string][]string{}
lines := strings.Split(s, "\n")
if len(lines) <= 1 {
return brs, nil
}
lastBr := ""
for _, line := range lines[1:] {
cols := strings.Split(line, "\t")
brName := cols[0]
ifName := cols[len(cols)-1]
if brName != "" {
lastBr = brName
brs[brName] = []string{}
}
if ifName != "" {
brs[lastBr] = append(brs[lastBr], ifName)
}
}
return brs, nil
}
func ParseVLANConfig(s string) (map[string]int, error) {
configs := map[string]int{}
lines := strings.Split(s, "\n")
if len(lines) <= 2 {
return configs, nil
}
for _, line := range lines[2:] {
cols := strings.Split(line, "|")
if len(cols) != 3 {
continue
}
vlanID, err := strconv.Atoi(strings.Trim(cols[1], " "))
if err != nil {
return configs, err
}
configs[strings.Trim(cols[0], " ")] = vlanID
}
return configs, nil
}
func ParseVMStates(s string) (map[string]int, error) {
vmToState := map[string]int{}
lines := strings.Split(s, "\n")
if len(lines) <= 2 {
return vmToState, nil
}
for _, line := range lines[2:] {
fields := strings.Fields(line)
if len(fields) != 3 && len(fields) != 4 {
continue
}
name := strings.Trim(fields[1], " ")
stateStr := strings.Trim(fields[2], " ")
var state int
switch stateStr {
case "running":
state = common.VM_STATE_RUNNING
case "shut", "关闭":
state = common.VM_STATE_STOPPED
default:
state = common.VM_STATE_EXCEPTION
}
vmToState[name] = state
}
return vmToState, nil
}
func ParseVMXml(s string) ([]XMLVM, error) {
var vms []XMLVM
if s == "" {
return vms, nil
}
// ns := "http://openstack.org/xmlns/libvirt/nova/1.0"
var domains KVMDomains
err := xml.Unmarshal([]byte(s), &domains)
if err != nil {
return vms, err
}
for _, domain := range domains.Domains {
var vm XMLVM
if domain.UUID == "" {
continue
}
vm.UUID = domain.UUID
if domain.Name == "" {
continue
}
vm.Label = domain.Name
vm.Name = domain.MetaData.Instance.Name
if vm.Name == "" {
vm.Name = vm.Label
}
if domain.MetaData.Instance.Owner.Project.UUID != "" {
uuid := domain.MetaData.Instance.Owner.Project.UUID
if len(uuid) == 32 {
uuid = strings.Join([]string{uuid[:8], uuid[8:12], uuid[12:16], uuid[16:20], uuid[20:]}, "-")
}
vm.VPC = XMLVPC{
UUID: uuid,
Name: domain.MetaData.Instance.Owner.Project.Value,
}
}
if len(domain.Devices.Interfaces) != 0 {
var interfaces []XMLInterface
for _, item := range domain.Devices.Interfaces {
var iface XMLInterface
iface.Target = item.Target.Value
iface.Mac = item.Mac.Value
interfaces = append(interfaces, iface)
}
vm.Interfaces = interfaces
}
vms = append(vms, vm)
}
return vms, nil
}
func ParseYMAL(y string) (prometheusConfig, error) {
pConfig := prometheusConfig{}
err := yaml.Unmarshal([]byte(y), &pConfig)
if err != nil {
return prometheusConfig{}, err
}
return pConfig, nil
}
func ParseCompressedInfo(cInfo []byte) (bytes.Buffer, error) {
reader := bytes.NewReader(cInfo)
var out bytes.Buffer
r, err := zlib.NewReader(reader)
if err != nil {
return bytes.Buffer{}, err
}
_, err = out.ReadFrom(r)
if err != nil {
return bytes.Buffer{}, err
}
return out, nil
}
func Uint64ToMac(v uint64) net.HardwareAddr {
bytes := [8]byte{}
BigEndian.PutUint64(bytes[:], v)
return net.HardwareAddr(bytes[2:])
}
func IPInRanges(ip string, ipRanges ...netaddr.IPPrefix) bool {
ipObj, err := netaddr.ParseIP(ip)
if err != nil {
return false
}
for _, ipRange := range ipRanges {
if ipRange.Contains(ipObj) {
return true
}
}
return false
}
func RequestGet(url string, timeout int, queryStrings map[string]string) error {
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: time.Duration(timeout) * time.Second,
}
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
queryData := request.URL.Query()
for k, v := range queryStrings {
queryData.Add(k, v)
}
request.URL.RawQuery = queryData.Encode()
response, err := client.Do(request)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return errors.New(fmt.Sprintf("http status failed: (%d)", response.StatusCode))
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return err
}
respJson, err := simplejson.NewJson(body)
if err != nil {
return errors.New(fmt.Sprintf("response body (%s) serializer to json failed: (%s)", string(body), err.Error()))
}
optStatus := respJson.Get("OPT_STATUS").MustString()
if optStatus != "" && optStatus != "SUCCESS" {
description := respJson.Get("DESCRIPTION").MustString()
return errors.New(fmt.Sprintf("curl (%s) failed, (%v)", request.URL, description))
}
return nil
}
func GetTeamIDToOrgID() (map[string]int, error) {
teamIDToOrgID := map[string]int{}
orgIDs, err := mysql.GetORGIDs()
if err != nil {
return teamIDToOrgID, err
}
for _, orgID := range orgIDs {
db, err := mysql.GetDB(orgID)
if err != nil {
log.Error(err.Error())
continue
}
var teams []mysql.Team
err = db.Find(&teams).Error
if err != nil {
log.Error(err.Error())
continue
}
for _, team := range teams {
teamIDToOrgID[team.ShortLcuuid] = orgID
}
}
return teamIDToOrgID, nil
}