-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathblacksmith.go
297 lines (258 loc) · 8.01 KB
/
blacksmith.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package main // import "github.com/cafebazaar/blacksmith"
import (
"flag"
"fmt"
"net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
etcd "github.com/coreos/etcd/client"
"github.com/cafebazaar/blacksmith/datasource"
"github.com/cafebazaar/blacksmith/dhcp"
"github.com/cafebazaar/blacksmith/pxe"
"github.com/cafebazaar/blacksmith/web"
)
//go:generate esc -o pxe/pxelinux_autogen.go -prefix=pxe -pkg pxe -ignore=README.md pxe/pxelinux
//go:generate esc -o web/ui_autogen.go -prefix=web -ignore=bower_components -pkg web web/static
const (
workspacePathHelp = `Path to workspace which obey following structure
/config/bootparams/main
/config/cloudconfig/main
/config/ignition/main
/images/{core-os-version}/coreos_production_pxe_image.cpio.gz
/images/{core-os-version}/coreos_production_pxe.vmlinuz
/initial.yaml
`
httpListenFlagDefaultTCPAddress = "interface-ip:8000"
)
var (
versionFlag = flag.Bool("version", false, "Print version info and exit")
debugFlag = flag.Bool("debug", false, "Log more things that aren't directly related to booting a recognized client")
listenIFFlag = flag.String("if", "", "Interface name for DHCP and PXE to listen on")
httpListenFlag = flag.String("http-listen", httpListenFlagDefaultTCPAddress, "IP range to listen on for web requests")
workspacePathFlag = flag.String("workspace", "/workspaces/current", workspacePathHelp)
etcdFlag = flag.String("etcd", "", "Etcd endpoints")
clusterNameFlag = flag.String("cluster-name", "blacksmith", "The name of this cluster. Will be used as etcd path prefixes.")
dnsAddressesFlag = flag.String("dns", "8.8.8.8", "comma separated IPs which will be used as default nameservers for skydns.")
leaseStartFlag = flag.String("lease-start", "", "Begining of lease starting IP")
leaseRangeFlag = flag.Int("lease-range", 0, "Lease range")
version string
commit string
buildTime string
)
func init() {
// If version, commit, or build time are not set, make that clear.
if version == "" {
version = "unknown"
}
if commit == "" {
commit = "unknown"
}
if buildTime == "" {
buildTime = "unknown"
}
}
func interfaceIP(iface *net.Interface) (net.IP, error) {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
fs := [](func(net.IP) bool){
net.IP.IsGlobalUnicast,
net.IP.IsLinkLocalUnicast,
net.IP.IsLoopback,
}
for _, f := range fs {
for _, a := range addrs {
ipaddr, ok := a.(*net.IPNet)
if !ok {
continue
}
ip := ipaddr.IP.To4()
if ip == nil {
continue
}
if f(ip) {
return ip, nil
}
}
}
return nil, fmt.Errorf("interface %s has no usable unicast addresses", iface.Name)
}
func gracefulShutdown(etcdDataSource datasource.DataSource) {
err := etcdDataSource.Shutdown()
if err != nil {
fmt.Fprintf(os.Stderr, "\nError while removing the instance: %s\n", err)
} else {
fmt.Fprint(os.Stderr, "\nBlacksmith is gracefully shutdown\n")
}
os.Exit(0)
}
func main() {
var err error
flag.Parse()
fmt.Printf("Blacksmith (%s)\n", version)
fmt.Printf(" Commit: %s\n", commit)
fmt.Printf(" Build Time: %s\n", buildTime)
if *versionFlag {
os.Exit(0)
}
if *debugFlag {
log.SetLevel(log.DebugLevel)
} else {
log.SetLevel(log.InfoLevel)
}
// etcd config
if etcdFlag == nil || clusterNameFlag == nil {
fmt.Fprint(os.Stderr, "\nPlease specify the etcd endpoints\n")
os.Exit(1)
}
// finding interface by interface name
var dhcpIF *net.Interface
if *listenIFFlag != "" {
dhcpIF, err = net.InterfaceByName(*listenIFFlag)
if err != nil {
fmt.Fprintf(os.Stderr, "\nError while trying to get the interface (%s): %s\n", *listenIFFlag, err)
os.Exit(1)
}
} else {
fmt.Fprint(os.Stderr, "\nPlease specify an interface\n")
os.Exit(1)
}
serverIP, err := interfaceIP(dhcpIF)
if err != nil {
fmt.Fprintf(os.Stderr, "\nError while trying to get the ip from the interface (%v)\n", dhcpIF)
os.Exit(1)
}
// web api can be configured to listen on a custom address
webAddr := net.TCPAddr{IP: serverIP, Port: 8000}
if *httpListenFlag != httpListenFlagDefaultTCPAddress {
splitAddress := strings.Split(*httpListenFlag, ":")
if len(splitAddress) > 2 {
fmt.Printf("Incorrect tcp address provided: %s\n", *httpListenFlag)
os.Exit(1)
}
if len(splitAddress) == 1 {
splitAddress = append(splitAddress, "8000")
}
webAddr.IP = net.ParseIP(splitAddress[0])
port, err := strconv.ParseInt(splitAddress[1], 10, 64)
if err != nil {
fmt.Printf("Incorrect tcp address provided: %s\n", *httpListenFlag)
os.Exit(1)
}
webAddr.Port = int(port)
}
// other services are exposed just through the given interface, on hard coded ports
var httpBooterAddr = net.TCPAddr{IP: serverIP, Port: 70}
var tftpAddr = net.UDPAddr{IP: serverIP, Port: 69}
var pxeAddr = net.UDPAddr{IP: serverIP, Port: 4011}
// 67 -> dhcp
// dhcp setting
leaseStart := net.ParseIP(*leaseStartFlag)
leaseRange := *leaseRangeFlag
dnsIPStrings := strings.Split(*dnsAddressesFlag, ",")
if len(dnsIPStrings) == 0 {
fmt.Fprint(os.Stderr, "\nPlease specify an DNS server\n")
os.Exit(1)
}
for _, ipString := range dnsIPStrings {
ip := net.ParseIP(ipString)
if ip == nil {
fmt.Fprintf(os.Stderr, "\nInvalid dns ip: %s\n", ipString)
os.Exit(1)
}
}
if leaseStart == nil {
fmt.Fprint(os.Stderr, "\nPlease specify the lease start ip\n")
os.Exit(1)
}
if leaseRange <= 1 {
fmt.Fprint(os.Stderr, "\nLease range should be greater that 1\n")
os.Exit(1)
}
fmt.Printf("Interface IP: %s\n", serverIP.String())
fmt.Printf("Interface Name: %s\n", dhcpIF.Name)
// datasources
etcdClient, err := etcd.New(etcd.Config{
Endpoints: strings.Split(*etcdFlag, ","),
HeaderTimeoutPerRequest: 5 * time.Second,
})
if err != nil {
fmt.Fprintf(os.Stderr, "\nCouldn't create etcd connection: %s\n", err)
os.Exit(1)
}
kapi := etcd.NewKeysAPI(etcdClient)
selfInfo := datasource.InstanceInfo{
IP: serverIP,
Nic: dhcpIF.HardwareAddr,
WebPort: webAddr.Port,
Version: version,
Commit: commit,
BuildTime: buildTime,
ServiceStartTime: time.Now().UTC().Unix(),
}
etcdDataSource, err := datasource.NewEtcdDataSource(kapi, etcdClient,
leaseStart, leaseRange, *clusterNameFlag, *workspacePathFlag,
dnsIPStrings, selfInfo)
if err != nil {
fmt.Fprintf(os.Stderr, "\nCouldn't create runtime configuration: %s\n", err)
os.Exit(1)
}
// serving api
go func() {
err := web.ServeWeb(etcdDataSource, webAddr)
log.Fatalf("\nError while serving api: %s\n", err)
}()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
go func() {
for _ = range c {
gracefulShutdown(etcdDataSource)
}
}()
// waiting till we're officially the master instance
for etcdDataSource.WhileMaster() != nil {
log.WithFields(log.Fields{
"where": "blacksmith.main",
"action": "debug",
}).Debug("Not master, waiting to be promoted...")
time.Sleep(datasource.StandbyMasterUpdateTime)
}
log.WithFields(log.Fields{
"where": "blacksmith.main",
"action": "debug",
}).Debug("Now we're the master instance. Starting the services...")
// serving http booter
go func() {
err := pxe.ServeHTTPBooter(httpBooterAddr, etcdDataSource, webAddr.Port)
log.Fatalf("\nError while serving http booter: %s\n", err)
}()
// serving tftp
go func() {
err := pxe.ServeTFTP(tftpAddr)
log.Fatalf("\nError while serving tftp: %s\n", err)
}()
// pxe protocol
go func() {
err := pxe.ServePXE(pxeAddr, serverIP, httpBooterAddr)
log.Fatalf("\nError while serving pxe: %s\n", err)
}()
// serving dhcp
go func() {
err := dhcp.StartDHCP(dhcpIF.Name, serverIP, etcdDataSource)
log.Fatalf("\nError while serving dhcp: %s\n", err)
}()
for etcdDataSource.WhileMaster() == nil {
time.Sleep(datasource.ActiveMasterUpdateTime)
}
log.WithFields(log.Fields{
"where": "blacksmith.main",
"action": "debug",
}).Debug("Now we're NOT the master. Terminating. Hoping to be restarted by the service manager.")
gracefulShutdown(etcdDataSource)
}