forked from goodrain/rainbond
/
slug_build.go
253 lines (237 loc) · 7.68 KB
/
slug_build.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
// RAINBOND, Application Management Platform
// Copyright (C) 2014-2017 Goodrain Co., Ltd.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version. For any non-GPL usage of Rainbond,
// one or multiple Commercial Licenses authorized by Goodrain Co., Ltd.
// must be obtained first.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package build
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"github.com/docker/docker/client"
"github.com/Sirupsen/logrus"
"github.com/fsnotify/fsnotify"
"github.com/goodrain/rainbond/builder"
"github.com/goodrain/rainbond/builder/sources"
"github.com/goodrain/rainbond/event"
"github.com/goodrain/rainbond/util"
"github.com/pquerna/ffjson/ffjson"
)
func slugBuilder() (Build, error) {
return &slugBuild{}, nil
}
type slugBuild struct {
tgzDir string
buildCacheDir string
sourceDir string
}
func (s *slugBuild) Build(re *Request) (*Response, error) {
re.Logger.Info(util.Translation("Start compiling the source code"), map[string]string{"step": "build-exector"})
s.tgzDir = re.TGZDir
s.buildCacheDir = re.CacheDir
packageName := fmt.Sprintf("%s/%s.tgz", s.tgzDir, re.DeployVersion)
if err := s.runBuildContainer(re); err != nil {
re.Logger.Error(util.Translation("Compiling the source code failure"), map[string]string{"step": "build-code", "status": "failure"})
logrus.Error("build slug in container error,", err.Error())
return nil, err
}
fileInfo, err := os.Stat(packageName)
if err != nil {
re.Logger.Error(util.Translation("Check that the build result failure"), map[string]string{"step": "build-code", "status": "failure"})
logrus.Error("build package check error", err.Error())
return nil, fmt.Errorf("build package failure")
}
if fileInfo.Size() == 0 {
re.Logger.Error(util.Translation("Source build failure and result slug size is 0"),
map[string]string{"step": "build-code", "status": "failure"})
return nil, fmt.Errorf("build package failure")
}
re.Logger.Info(util.Translation("Compiling the source code SUCCESS"), map[string]string{"step": "build-code", "status": "success"})
res := &Response{
MediumType: "slug",
MediumPath: packageName,
}
return res, nil
}
func (s *slugBuild) readLogFile(logfile string, logger event.Logger, closed chan struct{}) {
file, _ := os.Open(logfile)
watcher, _ := fsnotify.NewWatcher()
defer watcher.Close()
_ = watcher.Add(logfile)
readerr := bufio.NewReader(file)
for {
line, _, err := readerr.ReadLine()
if err != nil {
if err != io.EOF {
logrus.Errorf("Read build container log error:%s", err.Error())
return
}
wait := func() error {
for {
select {
case <-closed:
return nil
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
return nil
}
case err := <-watcher.Errors:
return err
}
}
}
if err := wait(); err != nil {
logrus.Errorf("Read build container log error:%s", err.Error())
return
}
}
if logger != nil {
var message = make(map[string]string)
if err := ffjson.Unmarshal(line, &message); err == nil {
if m, ok := message["log"]; ok {
logger.Info(m, map[string]string{"step": "build-exector"})
}
} else {
fmt.Println(err.Error())
}
}
select {
case <-closed:
return
default:
}
}
}
func (s *slugBuild) getSourceCodeTarFile(re *Request) (*os.File, error) {
var cmd []string
sourceTarFile := fmt.Sprintf("%s/%s.tar", util.GetParentDirectory(re.SourceDir), re.DeployVersion)
if re.ServerType == "svn" {
cmd = append(cmd, "tar", "-cf", sourceTarFile, "--exclude=.svn", "./")
}
if re.ServerType == "git" {
cmd = append(cmd, "tar", "-cf", sourceTarFile, "--exclude=.git", "./")
}
source := exec.Command(cmd[0], cmd[1:]...)
source.Dir = re.SourceDir
logrus.Debugf("tar source code to file %s", sourceTarFile)
if err := source.Run(); err != nil {
return nil, err
}
return os.OpenFile(sourceTarFile, os.O_RDONLY, 0755)
}
func (s *slugBuild) runBuildContainer(re *Request) error {
envs := []*sources.KeyValue{
&sources.KeyValue{Key: "SLUG_VERSION", Value: re.DeployVersion},
&sources.KeyValue{Key: "SERVICE_ID", Value: re.ServiceID},
&sources.KeyValue{Key: "TENANT_ID", Value: re.TenantID},
&sources.KeyValue{Key: "LANGUAGE", Value: re.Lang.String()},
}
for k, v := range re.BuildEnvs {
envs = append(envs, &sources.KeyValue{Key: k, Value: v})
if k == "PROC_ENV" {
var mapdata = make(map[string]interface{})
if err := json.Unmarshal([]byte(v), &mapdata); err == nil {
if runtime, ok := mapdata["runtimes"]; ok {
envs = append(envs, &sources.KeyValue{Key: "RUNTIME", Value: runtime.(string)})
}
}
}
}
containerConfig := &sources.ContainerConfig{
Metadata: &sources.ContainerMetadata{
Name: re.ServiceID[:8] + "_" + re.DeployVersion,
},
Image: &sources.ImageSpec{
Image: builder.BUILDERIMAGENAME,
},
Mounts: []*sources.Mount{
&sources.Mount{
ContainerPath: "/tmp/cache",
HostPath: re.CacheDir,
Readonly: false,
},
&sources.Mount{
ContainerPath: "/tmp/slug",
HostPath: s.tgzDir,
Readonly: false,
},
},
Envs: envs,
Stdin: true,
StdinOnce: true,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
NetworkConfig: &sources.NetworkConfig{
NetworkMode: "host",
},
Args: []string{"local"},
}
reader, err := s.getSourceCodeTarFile(re)
if err != nil {
return fmt.Errorf("create source code tar file error:%s", err.Error())
}
defer func() {
reader.Close()
os.Remove(reader.Name())
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
containerService := sources.CreateDockerService(ctx, re.DockerClient)
containerID, err := containerService.CreateContainer(containerConfig)
if err != nil {
if client.IsErrNotFound(err) {
// we don't want to write to stdout anything apart from container.ID
if _, err = sources.ImagePull(re.DockerClient, containerConfig.Image.Image, builder.REGISTRYUSER, builder.REGISTRYPASS, re.Logger, 20); err != nil {
return fmt.Errorf("pull builder container image error:%s", err.Error())
}
// Retry
containerID, err = containerService.CreateContainer(containerConfig)
}
if err != nil {
return fmt.Errorf("create builder container error:%s", err.Error())
}
}
errchan := make(chan error, 1)
writer := re.Logger.GetWriter("builder", "info")
close, err := containerService.AttachContainer(containerID, true, true, true, reader, writer, writer, &errchan)
if err != nil {
containerService.RemoveContainer(containerID)
return fmt.Errorf("attach builder container error:%s", err.Error())
}
defer close()
statuschan := containerService.WaitExitOrRemoved(containerID, true)
//start the container
if err := containerService.StartContainer(containerID); err != nil {
containerService.RemoveContainer(containerID)
return fmt.Errorf("start builder container error:%s", err.Error())
}
if err := <-errchan; err != nil {
logrus.Debugf("Error hijack: %s", err)
}
status := <-statuschan
if status != 0 {
return &ErrorBuild{Code: status}
}
return nil
}
//ErrorBuild build error
type ErrorBuild struct {
Code int
}
func (e *ErrorBuild) Error() string {
return fmt.Sprintf("Run build return %d", e.Code)
}