forked from adobe-platform/porter
/
pack.go
254 lines (207 loc) · 6.79 KB
/
pack.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
/*
* Copyright 2016 Adobe Systems Incorporated. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package provision
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
yaml "gopkg.in/yaml.v2"
"io/ioutil"
"os"
"os/exec"
"strings"
"time"
"github.com/adobe-platform/porter/conf"
"github.com/adobe-platform/porter/constants"
"github.com/inconshreveable/log15"
)
// Package creates the service payload to deliver to S3
func Package(log log15.Logger, config *conf.Config) (success bool) {
// clean up old artifacts before building
exec.Command("rm", "-rf", constants.PayloadWorkingDir).Run()
// clean up artifacts after building
defer exec.Command("rm", "-rf", constants.PayloadWorkingDir).Run()
exec.Command("mkdir", "-p", constants.PayloadWorkingDir).Run()
revParseOutput, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output()
if err != nil {
log.Error("git rev-parse", "Error", err)
return
}
now := time.Now().Unix()
sha1 := strings.TrimSpace(string(revParseOutput))
builtContainers := make(map[string]interface{})
// This is in a loop but assumes we're building a single container
// TODO support multiple containers
for _, environment := range config.Environments {
for _, region := range environment.Regions {
for _, container := range region.Containers {
originalName := container.Name
// Alter the name in the config so we know which image names are part
// of the service payload. This is important for hotswap to know which
// of the available images on the host are the ones to be swapped in.
container.Name = fmt.Sprintf("%s-%d-%s", sha1, now, container.Name)
if _, exists := builtContainers[originalName]; !exists {
imagePath := fmt.Sprintf("%s/%s.docker", constants.PayloadWorkingDir, container.Name)
_, err := os.Stat("Dockerfile")
if err != nil {
log.Error("Dockerfile stat", "Error", err)
return
}
haveBuilder := true
_, err = os.Stat("Dockerfile.build")
if err != nil {
haveBuilder = false
}
if haveBuilder {
var err error
buildBuilderCmd := exec.Command("docker", "build", "-t", container.Name+"-builder", "-f", "Dockerfile.build", ".")
buildBuilderCmd.Stdout = os.Stdout
buildBuilderCmd.Stderr = os.Stderr
err = buildBuilderCmd.Run()
if err != nil {
log.Error("build Dockerfile.build", "Error", err)
return
}
runCmd := exec.Command("docker", "run", "--rm", container.Name+"-builder")
runCmdStdoutPipe, err := runCmd.StdoutPipe()
if err != nil {
log.Error("couldn't create StdoutPipe", "Error", err)
return
}
buildCmd := exec.Command("docker", "build", "-t", container.Name, "-")
buildCmd.Stdin = runCmdStdoutPipe
buildCmd.Stdout = os.Stdout
buildCmd.Stderr = os.Stderr
err = runCmd.Start()
if err != nil {
log.Error("docker run", "Error", err)
return
}
err = buildCmd.Start()
if err != nil {
log.Error("build Dockerfile", "Error", err)
return
}
runCmd.Wait()
buildCmd.Wait()
} else {
buildCmd := exec.Command("docker", "build", "-t", container.Name, ".")
buildCmd.Stdout = os.Stdout
buildCmd.Stderr = os.Stderr
err := buildCmd.Run()
if err != nil {
log.Error("build Dockerfile", "Error", err)
return
}
}
log.Info(fmt.Sprintf("saving docker image to %s", imagePath))
saveCmd := exec.Command("docker", "save", "-o", imagePath, container.Name)
saveCmd.Stdout = os.Stdout
saveCmd.Stderr = os.Stderr
err = saveCmd.Run()
if err != nil {
log.Error("docker save", "Error", err)
return
}
builtContainers[originalName] = nil
}
}
}
}
if !copyPathBasedFiles(log, config) {
return
}
configBytes, err := yaml.Marshal(config)
if err != nil {
return
}
// for later build stages
err = ioutil.WriteFile(constants.AlteredConfigPath, configBytes, 0644)
if err != nil {
log.Error("WriteFile", "Path", constants.AlteredConfigPath)
return
}
// for the service payload about to be created
err = ioutil.WriteFile(constants.PackPayloadConfigPath, configBytes, 0644)
if err != nil {
log.Error("WriteFile", "Path", constants.PackPayloadConfigPath)
return
}
log.Info(fmt.Sprintf("creating service payload at %s", constants.PayloadPath))
tarCmd := exec.Command("tar", "-C", constants.PayloadWorkingDir, "-czf", constants.PayloadPath, ".")
tarCmd.Stdout = os.Stdout
tarCmd.Stderr = os.Stderr
err = tarCmd.Run()
if err != nil {
log.Error("tar", "Error", err)
return
}
writePackOutput(sha1)
success = true
return
}
// Ensure the files that are specified with paths in the config are part of the
// temp directory which is passed between the pack and provision stages in GoCD.
// If we fetched materials in every stage then the referenced files would always
// be there, and this function wouldn't be strictly necessary.
func copyPathBasedFiles(log log15.Logger, config *conf.Config) bool {
for _, environment := range config.Environments {
if digest, success := digestAndCopy(log, environment.StackDefinitionPath); success {
environment.StackDefinitionPath = digest
} else {
return false
}
for _, region := range environment.Regions {
if digest, success := digestAndCopy(log, region.StackDefinitionPath); success {
region.StackDefinitionPath = digest
} else {
return false
}
}
}
return true
}
func digestAndCopy(log log15.Logger, filePath string) (string, bool) {
if filePath == "" {
return "", true
}
log = log.New("Filepath", filePath)
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
log.Error("ioutil.ReadFile", "Error", err)
return "", false
}
digestArray := md5.Sum(fileBytes)
digest := hex.EncodeToString(digestArray[:])
newFilePath := constants.TempDir + "/" + digest
err = ioutil.WriteFile(newFilePath, fileBytes, 0644)
if err != nil {
log.Error("ioutil.ReadFile", "Error", err)
return "", false
}
return newFilePath, true
}
func writePackOutput(sha1 string) {
receipt := PackOutput{
SHA: sha1,
}
receiptFile, err := os.Create(constants.PackOutputPath)
if err != nil {
return
}
defer receiptFile.Close()
err = json.NewEncoder(receiptFile).Encode(&receipt)
if err != nil {
return
}
}