-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
100 lines (86 loc) · 2.19 KB
/
create.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
package fleet
import (
"fmt"
"strings"
"sync"
"time"
"github.com/coreos/fleet/job"
"github.com/coreos/fleet/schema"
"github.com/coreos/fleet/unit"
)
// Create schedules unit files for the given components.
func (c *FleetClient) Create(
targets []string, wg *sync.WaitGroup, outchan chan string, errchan chan error) {
units := make([]*schema.Unit, len(targets))
for i, target := range targets {
unitName, unitFile, err := c.createUnitFile(target)
if err != nil {
errchan <- err
return
}
units[i] = &schema.Unit{
Name: unitName,
Options: schema.MapUnitFileToSchemaUnitOptions(unitFile),
}
}
for _, unit := range units {
wg.Add(1)
go doCreate(c, unit, wg, outchan, errchan)
}
}
func doCreate(c *FleetClient, unit *schema.Unit, wg *sync.WaitGroup, outchan chan string, errchan chan error) {
defer wg.Done()
// create unit definition
if err := c.Fleet.CreateUnit(unit); err != nil {
// ignore units that already exist
if err.Error() != "job already exists" {
errchan <- err
return
}
}
desiredState := string(job.JobStateLoaded)
out := fmt.Sprintf("\033[0;33m%v:\033[0m loaded \r", unit.Name)
// schedule the unit
if err := c.Fleet.SetUnitTargetState(unit.Name, desiredState); err != nil {
errchan <- err
return
}
// loop until the unit actually exists in unit states
outerLoop:
for {
time.Sleep(250 * time.Millisecond)
unitStates, err := cAPI.UnitStates()
if err != nil {
errchan <- err
}
for _, us := range unitStates {
if strings.HasPrefix(us.Name, unit.Name) {
break outerLoop
}
}
}
outchan <- out
}
func (c *FleetClient) createUnitFile(target string) (unitName string, uf *unit.UnitFile, err error) {
component, num, err := splitTarget(target)
if err != nil {
return
}
unitName, uf, err = c.createServiceUnit(component, num)
if err != nil {
return unitName, uf, err
}
return
}
// Create normal service unit
func (c *FleetClient) createServiceUnit(component string, num int) (name string, uf *unit.UnitFile, err error) {
name, err = formatUnitName(component, num)
if err != nil {
return "", nil, err
}
uf, err = NewUnit(component)
if err != nil {
return
}
return name, uf, nil
}