-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
83 lines (67 loc) · 1.73 KB
/
core.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
package bitbox
import (
"fmt"
"sync"
"github.com/google/uuid"
"github.com/jmbarzee/bitbox/proc"
)
// Core offers the central functionality of BitBox.
// Core supports basic process control and interaction.
type Core struct {
sync.RWMutex
processes map[uuid.UUID]*proc.Proc
}
// Start initiates a process.
func (c *Core) Start(cmd string, args ...string) (uuid.UUID, error) {
id := uuid.New()
proc, err := proc.NewProc(cmd, args...)
if err != nil {
return uuid.UUID{}, c.newError("Start", err)
}
c.Lock()
c.processes[id] = proc // Chance of colision (16 byte id, so roughly 2^128 chance)
c.Unlock()
return id, nil
}
// Stop halts a process.
func (c *Core) Stop(id uuid.UUID) error {
var p *proc.Proc
var err error
if p, err = c.findProcess(id); err != nil {
return c.newError("Stop", err)
}
if err = p.Stop(); err != nil {
return c.newError("Stop", err)
}
return nil
}
// Status returns the status of the process.
func (c *Core) Status(id uuid.UUID) (proc.ProcStatus, error) {
var p *proc.Proc
var err error
if p, err = c.findProcess(id); err != nil {
return proc.Exited, c.newError("Status", err)
}
return p.Status(), nil
}
// Query streams the output/result of a process.
func (c *Core) Query(id uuid.UUID) (<-chan proc.ProcOutput, error) {
var p *proc.Proc
var err error
if p, err = c.findProcess(id); err != nil {
return nil, c.newError("Query", err)
}
return p.Query()
}
func (c *Core) findProcess(id uuid.UUID) (*proc.Proc, error) {
c.RLock()
defer c.RUnlock()
p, ok := c.processes[id]
if !ok {
return nil, fmt.Errorf("could not find specified process %v", id)
}
return p, nil
}
func (*Core) newError(action string, err error) error {
return fmt.Errorf("could not %v process: %w", action, err)
}