forked from fujiwara/stretcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stretcher.go
177 lines (159 loc) · 3.82 KB
/
stretcher.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
package stretcher
import (
"bufio"
"bytes"
crand "crypto/rand"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
mrand "math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/AdRoll/goamz/aws"
"github.com/AdRoll/goamz/s3"
)
var (
AWSAuth aws.Auth
AWSRegion aws.Region
LogBuffer bytes.Buffer
Version string
)
type Config struct {
MaxBandWidth uint64
Timeout time.Duration
InitSleep time.Duration
Retry int
RetryWait time.Duration
}
const Nanoseconds = 1000 * 1000 * 1000
func init() {
log.SetOutput(io.MultiWriter(os.Stderr, &LogBuffer))
}
func RandomTime(delay float64) time.Duration {
if delay <= 0 {
return time.Duration(0)
}
// http://stackoverflow.com/questions/6181260/generating-random-numbers-in-go
var s int64
if err := binary.Read(crand.Reader, binary.LittleEndian, &s); err != nil {
s = time.Now().UnixNano()
}
mrand.Seed(s)
n := mrand.Int63n(int64(delay * Nanoseconds))
return time.Duration(n)
}
func Run(conf Config) error {
var err error
log.Println("Starting up stretcher agent", Version)
if conf.InitSleep > 0 {
log.Printf("Sleeping %s", conf.InitSleep)
time.Sleep(conf.InitSleep)
}
manifestURL, err := parseEvents()
if err != nil {
return fmt.Errorf("Could not parse event: %s", err)
}
log.Println("Loading manifest:", manifestURL)
m, err := getManifest(manifestURL)
if err != nil {
return fmt.Errorf("Load manifest failed: %s", err)
}
log.Printf("Executing manifest %#v", m)
err = m.Deploy(conf)
if err != nil {
log.Println("Deploy manifest failed:", err)
if ferr := m.Commands.Failure.InvokePipe(&LogBuffer); ferr != nil {
log.Println(ferr)
}
return fmt.Errorf("Deploy manifest failed: %s", err)
}
log.Println("Deploy manifest succeeded.")
err = m.Commands.Success.InvokePipe(&LogBuffer)
if err != nil {
log.Println(err)
}
log.Println("Done")
return nil
}
func getS3(u *url.URL) (io.ReadCloser, error) {
var err error
if AWSAuth.AccessKey == "" || AWSRegion.Name == "" {
AWSAuth, AWSRegion, err = LoadAWSCredentials("")
if err != nil {
return nil, err
}
log.Println("region:", AWSRegion.Name)
log.Println("aws_access_key_id:", AWSAuth.AccessKey)
}
client := s3.New(AWSAuth, AWSRegion)
bucket := client.Bucket(u.Host)
return bucket.GetReader(u.Path)
}
func getFile(u *url.URL) (io.ReadCloser, error) {
return os.Open(u.Path)
}
func getHTTP(u *url.URL) (io.ReadCloser, error) {
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", "Stretcher/"+Version)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
return resp.Body, nil
}
func getURL(urlStr string) (io.ReadCloser, error) {
log.Println("Loading URL", urlStr)
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
switch u.Scheme {
case "s3":
return getS3(u)
case "http", "https":
return getHTTP(u)
case "file":
return getFile(u)
default:
return nil, fmt.Errorf("manifest URL scheme must be s3 or http(s) or file: %s", urlStr)
}
}
func getManifest(manifestURL string) (*Manifest, error) {
rc, err := getURL(manifestURL)
if err != nil {
return nil, err
}
data, _ := ioutil.ReadAll(rc)
return ParseManifest(data)
}
func parseEvents() (string, error) {
log.Println("Waiting for events from STDIN...")
reader := bufio.NewReader(os.Stdin)
b, err := reader.Peek(1)
if err != nil {
return "", err
}
if os.Getenv("CONSUL_INDEX") != "" || string(b) == "[" {
log.Println("Reading Consul event")
ev, err := ParseConsulEvents(reader)
if err != nil {
return "", err
}
return string(ev.Payload), nil
} else {
if userEvent := os.Getenv("SERF_USER_EVENT"); userEvent != "" {
log.Println("Reading Serf user event:", userEvent)
}
// event passed by stdin (raw string)
line, err := reader.ReadString('\n')
return strings.Trim(line, "\n"), err
}
}