forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwork.go
96 lines (78 loc) · 1.88 KB
/
work.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
package detect
import (
"sort"
"strings"
"sync"
"github.com/evcc-io/evcc/detect/tasks"
"github.com/evcc-io/evcc/util"
"github.com/fatih/structs"
"github.com/jeremywohl/flatten"
)
func workers(log *util.Logger, num int, tasks <-chan string, hits chan<- []tasks.Result) *sync.WaitGroup {
var wg sync.WaitGroup
for i := 0; i < num; i++ {
wg.Add(1)
go func() {
workunit(log, tasks, hits)
wg.Done()
}()
}
return &wg
}
func workunit(log *util.Logger, ips <-chan string, hits chan<- []tasks.Result) {
for ip := range ips {
res := taskList.Test(log, "", tasks.ResultDetails{IP: ip})
hits <- res
}
}
func Work(log *util.Logger, num int, hosts []string) []tasks.Result {
ip := make(chan string)
hits := make(chan []tasks.Result)
done := make(chan struct{})
// log.INFO.Println(
// "\n" +
// strings.Join(
// lo.Map(taskList.tasks, func(t tasks.Task) string {
// return fmt.Sprintf("task: %s\ttype: %s\tdepends: %s\n", t.ID, t.Type, t.Depends)
// }).([]string),
// "",
// ),
// )
wg := workers(log, num, ip, hits)
var res []tasks.Result
go func() {
for hits := range hits {
res = append(res, hits...)
}
done <- struct{}{}
}()
for _, host := range hosts {
ip <- host
}
close(ip)
wg.Wait()
close(hits)
<-done
return postProcess(res)
}
func postProcess(res []tasks.Result) []tasks.Result {
for idx, hit := range res {
// if sma, ok := hit.Details.(SmaResult); ok {
// hit.Host = sma.Addr
// }
hit.Attributes = make(map[string]interface{})
flat, _ := flatten.Flatten(structs.Map(hit), "", flatten.DotStyle)
for k, v := range flat {
hit.Attributes[strings.ToLower(k)] = v
}
res[idx] = hit
}
// sort by host
sort.Slice(res, func(i, j int) bool {
if res[i].ResultDetails.IP == res[j].ResultDetails.IP {
return res[i].Type < res[j].Type
}
return res[i].ResultDetails.IP < res[j].ResultDetails.IP
})
return res
}