-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
119 lines (101 loc) · 2.32 KB
/
client.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
package uniex
import (
"context"
"encoding/json"
"sort"
"sync"
"time"
"github.com/gocarina/gocsv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
func (c *Config) clientInventory(db *mongo.Client) ([]byte, error) {
// setup
var (
err error
wg sync.WaitGroup
devices []Device
stats []Stat
)
// get all device records
wg.Add(1)
go func() {
// clean exit
defer wg.Done()
// setup user db query context
c := db.Database("ace").Collection("user")
// setup query
q, err := c.Find(context.TODO(), bson.M{})
if err != nil {
panic(err)
}
// perform query
if err := q.All(context.TODO(), &devices); err != nil {
panic(err)
}
}()
// fetch all stats snipets
wg.Add(1)
go func() {
// clean exit
defer wg.Done()
// setup user db query context
c := db.Database("ace_stat").Collection("stat_archive")
// setup query
q, err := c.Find(context.TODO(), bson.M{})
if err != nil {
panic(err)
}
// perform query
if err := q.All(context.TODO(), &stats); err != nil {
panic(err)
}
}()
// wait till all queries done
wg.Wait()
// parse all stats, add missing data into device records
var ts int64
for i, d := range devices {
d.LASTSEEN_UNIX = d.LASTSEEN_UNIX * 1000 // stats stamps have higher time resolution
ts = d.LASTSEEN_UNIX
d.LASTSEEN_UNIX = 0
for _, s := range stats {
// find latest matching stats record, get data
if d.MAC == s.MAC {
if d.LASTSEEN_UNIX < s.LASTSEEN_UNIX {
d.LASTSEEN_UNIX = s.LASTSEEN_UNIX
d.HOSTNAME = s.HOSTNAME
d.IP = s.IP
if d.SWITCHMAC == s.SWITCHMAC {
d.SWITCHPORT = s.SWITCHPORT
}
}
}
}
if ts > d.LASTSEEN_UNIX {
d.LASTSEEN_UNIX = ts
}
d.LASTSEEN_UNIX = d.LASTSEEN_UNIX / 1000
d.LASTSEEN = time.Unix(d.LASTSEEN_UNIX, 0).Format(time.RFC3339)
d.FIRSTSEEN = time.Unix(d.FIRSTSEEN_UNIX, 0).Format(time.RFC3339)
devices[i] = d // write back in the array
}
// sort devices by name
sort.Slice(devices, func(i, j int) bool {
return devices[i].NAME < devices[j].NAME
})
// output
var out []byte
switch c.Format {
case "csv":
out, err = gocsv.MarshalBytes(&devices)
case "json":
out, err = json.Marshal(&devices)
default:
panic("internal error, unsupported output format") // unreachable
}
if err != nil {
return nil, err
}
return out, nil
}