forked from bsm/sarama-cluster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
65 lines (52 loc) · 1.35 KB
/
util.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
package cluster
import (
"fmt"
"os"
"sort"
"sync/atomic"
"time"
"github.com/Shopify/sarama"
)
/* Claims map */
type Claims map[int32]*sarama.PartitionConsumer
// PartitionIDs returns the associated partition IDs
func (c Claims) PartitionIDs() []int32 {
ids := make(int32Slice, 0, len(c))
for id, _ := range c {
ids = append(ids, id)
}
return ids.Sorted()
}
/* GUID generator */
// Global UID config
var cGUID struct {
hostname string
pid int
inc uint32
}
// Init GUID configuration
func init() {
cGUID.hostname, _ = os.Hostname()
cGUID.pid = os.Getpid()
cGUID.inc = 0xffffffff
if cGUID.hostname == "" {
cGUID.hostname = "localhost"
}
}
// Create a new GUID
func newGUID(prefix string) string {
return newGUIDAt(prefix, time.Now())
}
// Create a new GUID for a certain time
func newGUIDAt(prefix string, at time.Time) string {
inc := atomic.AddUint32(&cGUID.inc, 1)
uts := at.Unix()
ins := fmt.Sprintf("%08x", inc)
return fmt.Sprintf("%s:%s:%08x-%04x-%s-%s", prefix, cGUID.hostname, uts, cGUID.pid, ins[:4], ins[4:])
}
/* Sortable int32Slice */
type int32Slice []int32
func (s int32Slice) Len() int { return len(s) }
func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s int32Slice) Sorted() []int32 { sort.Sort(s); return []int32(s) }