-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
97 lines (85 loc) · 2.32 KB
/
repo.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
package pico
import (
"fmt"
"sync"
"github.com/tuxdude/zzzlogi"
)
type serviceOrHook struct {
cmd string
args []string
}
// launchedService stores information about a single launched service.
type launchedServiceOrHook struct {
// pid of the launched service.
pid int
// Service or Hook information.
entity serviceOrHook
}
// Strings returns the string representation of launched service information.
func (l *launchedServiceOrHook) String() string {
return fmt.Sprintf(
"{pid: %d cmd: %q args: %q}",
l.pid,
l.entity.cmd,
l.entity.args,
)
}
// serviceRepo is a service repository that allows adding, removing and
// querying services or hooks.
type serviceRepo struct {
// Logger used by the service repository.
log zzzlogi.Logger
// Mutex controlling access to the service list.
mu sync.Mutex
// List of services or hooks.
entities map[int]*launchedServiceOrHook
}
// newServiceRepo instantiates a new service repository.
func newServiceRepo(log zzzlogi.Logger) *serviceRepo {
return &serviceRepo{
log: log,
entities: make(map[int]*launchedServiceOrHook),
}
}
// addService adds the specified the launched service to the service list
// in the repository.
func (s *serviceRepo) addService(proc *launchedServiceOrHook) {
s.mu.Lock()
defer s.mu.Unlock()
s.entities[proc.pid] = proc
s.log.Tracef("Added pid: %d to the list of services/hooks", proc.pid)
}
// removeService removes the launched service from the service list in the
// repository based on the specified pid. If the pid doesn't match one of
// the services/hooks in the repository, the call is a no-op.
func (s *serviceRepo) removeService(pid int) (*launchedServiceOrHook, bool) {
s.mu.Lock()
defer s.mu.Unlock()
if proc, ok := s.entities[pid]; ok {
delete(s.entities, pid)
s.log.Tracef("Deleted pid: %d from the list of services/hooks", pid)
return proc, true
}
return nil, false
}
// count returns the count of services/hooks in the repository.
func (s *serviceRepo) count() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.entities)
}
// pids returns the list of pids for the services/hooks in the repository.
func (s *serviceRepo) pids() []int {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.entities) == 0 {
return nil
}
pids := make([]int, len(s.entities))
i := 0
for pid := range s.entities {
pids[i] = pid
i++
}
return pids
}