/
source_code.go
385 lines (356 loc) · 11.6 KB
/
source_code.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright (C) 2014-2018 Goodrain Co., Ltd.
// RAINBOND, Application Management Platform
// 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 parser
import (
"fmt"
"path"
"strconv"
"strings"
"github.com/Sirupsen/logrus"
"github.com/pquerna/ffjson/ffjson"
"github.com/goodrain/rainbond/builder/parser/code"
"github.com/goodrain/rainbond/builder/sources"
"github.com/goodrain/rainbond/db/model"
"github.com/goodrain/rainbond/event"
"gopkg.in/src-d/go-git.v4/plumbing"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
//"github.com/docker/docker/client"
"github.com/docker/engine-api/client"
)
//SourceCodeParse docker run 命令解析或直接镜像名解析
type SourceCodeParse struct {
ports map[int]*Port
volumes map[string]*Volume
envs map[string]*Env
source string
memory int
image Image
args []string
branchs []string
errors []ParseError
dockerclient *client.Client
logger event.Logger
Lang code.Lang
Runtime bool `json:"runtime"`
Dependencies bool `json:"dependencies"`
Procfile bool `json:"procfile"`
}
//CreateSourceCodeParse create parser
func CreateSourceCodeParse(source string, logger event.Logger) Parser {
return &SourceCodeParse{
source: source,
ports: make(map[int]*Port),
volumes: make(map[string]*Volume),
envs: make(map[string]*Env),
logger: logger,
image: parseImageName("goodrain.me/runner"),
args: []string{"start", "web"},
}
}
//Parse 获取代码 解析代码 检验代码
func (d *SourceCodeParse) Parse() ParseErrorList {
if d.source == "" {
d.logger.Error("源码检查输入参数错误", map[string]string{"step": "parse"})
d.errappend(Errorf(FatalError, "source can not be empty"))
return d.errors
}
var csi sources.CodeSourceInfo
err := ffjson.Unmarshal([]byte(d.source), &csi)
if err != nil {
d.logger.Error("源码检查输入参数错误", map[string]string{"step": "parse"})
d.errappend(Errorf(FatalError, "source data can not be read"))
return d.errors
}
if csi.Branch == "" {
csi.Branch = "master"
}
if csi.ServerType == "" {
csi.ServerType = "git"
}
if csi.RepositoryURL == "" {
d.logger.Error("Git项目仓库地址不能为空", map[string]string{"step": "parse"})
d.errappend(ErrorAndSolve(FatalError, "Git项目仓库地址格式错误", SolveAdvice("modify_url", "请确认并修改仓库地址")))
return d.errors
}
//验证仓库地址
buildInfo, err := sources.CreateRepostoryBuildInfo(csi.RepositoryURL, csi.Branch, csi.TenantID)
if err != nil {
d.logger.Error("Git项目仓库地址格式错误", map[string]string{"step": "parse"})
d.errappend(ErrorAndSolve(FatalError, "Git项目仓库地址格式错误", SolveAdvice("modify_url", "请确认并修改仓库地址")))
return d.errors
}
gitFunc := func() ParseErrorList {
//获取代码
if sources.CheckFileExist(buildInfo.GetCodeHome()) {
if err := sources.RemoveDir(buildInfo.GetCodeHome()); err != nil {
//d.errappend(ErrorAndSolve(err, "清理cache dir错误", "请提交代码到仓库"))
return d.errors
}
}
csi.RepositoryURL = buildInfo.RepostoryURL
rs, err := sources.GitClone(csi, buildInfo.GetCodeHome(), d.logger, 5)
if err != nil {
if err == transport.ErrAuthenticationRequired || err == transport.ErrAuthorizationFailed {
if buildInfo.GetProtocol() == "ssh" {
d.errappend(ErrorAndSolve(FatalError, "Git项目仓库需要安全验证", SolveAdvice("get_publickey", "请获取授权Key配置到你的仓库项目中")))
} else {
d.errappend(ErrorAndSolve(FatalError, "Git项目仓库需要安全验证", SolveAdvice("modify_userpass", "请提供正确的账号密码")))
}
return d.errors
}
if err == plumbing.ErrReferenceNotFound {
solve := "请到代码仓库查看正确的分支情况"
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("Git项目仓库指定分支 %s 不存在", csi.Branch), solve))
return d.errors
}
if err == transport.ErrRepositoryNotFound {
solve := SolveAdvice("modify_repo", "请确认仓库地址是否正确")
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("Git项目仓库不存在"), solve))
return d.errors
}
if err == transport.ErrEmptyRemoteRepository {
solve := SolveAdvice("open_repo", "请确认已提交代码")
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("Git项目仓库无有效文件"), solve))
return d.errors
}
if strings.Contains(err.Error(), "ssh: unable to authenticate") {
solve := SolveAdvice("get_publickey", "请获取授权Key配置到你的仓库项目试试?")
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("远程仓库SSH验证错误"), solve))
return d.errors
}
if strings.Contains(err.Error(), "context deadline exceeded") {
solve := "请确认源码仓库能否正常访问"
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("获取代码超时"), solve))
return d.errors
}
logrus.Errorf("git clone error,%s", err.Error())
d.errappend(ErrorAndSolve(FatalError, fmt.Sprintf("获取代码失败"), "请确认仓库能否正常访问,或联系客服咨询"))
return d.errors
}
//获取分支
branch, err := rs.Branches()
if err == nil {
branch.ForEach(func(re *plumbing.Reference) error {
name := re.Name()
if name.IsBranch() {
d.branchs = append(d.branchs, name.Short())
}
return nil
})
} else {
d.branchs = append(d.branchs, csi.Branch)
}
return nil
}
//获取代码仓库
switch csi.ServerType {
case "git":
if err := gitFunc(); err != nil && err.IsFatalError() {
return err
}
case "svn":
d.errappend(ErrorAndSolve(FatalError, "svn协议暂时不支持", "请使用git协议仓库"))
return d.errors
default:
//按照git处理处理
if err := gitFunc(); err != nil && err.IsFatalError() {
return err
}
}
//读取云帮配置文件
rbdfileConfig, err := code.ReadRainbondFile(buildInfo.GetCodeHome())
if err != nil {
if err == code.ErrRainbondFileNotFound {
d.errappend(ErrorAndSolve(NegligibleError, "rainbondfile未定义", "可以参考文档说明配置此文件定义应用属性"))
} else {
d.errappend(ErrorAndSolve(NegligibleError, "rainbondfile定义格式有误", "可以参考文档说明配置此文件定义应用属性"))
}
}
//判断对象目录
var buildPath = buildInfo.GetCodeBuildAbsPath()
//解析代码类型
var lang code.Lang
if rbdfileConfig != nil && rbdfileConfig.Language != "" {
lang = code.Lang(rbdfileConfig.Language)
} else {
lang, err = code.GetLangType(buildPath)
if err != nil {
if err == code.ErrCodeDirNotExist {
d.errappend(ErrorAndSolve(FatalError, "源码目录不存在", "获取代码任务失败,请联系客服"))
} else if err == code.ErrCodeNotExist {
d.errappend(ErrorAndSolve(FatalError, "仓库中代码不存在", "请提交代码到仓库"))
} else {
d.errappend(ErrorAndSolve(FatalError, "代码无法识别语言类型", "请参考文档查看平台语言支持规范"))
}
return d.errors
}
}
d.Lang = lang
if lang == code.NO {
d.errappend(ErrorAndSolve(FatalError, "代码无法识别语言类型", "请参考文档查看平台语言支持规范"))
return d.errors
}
//check code Specification
spec := code.CheckCodeSpecification(buildPath, lang)
if spec.Advice != nil {
for k, v := range spec.Advice {
d.errappend(ErrorAndSolve(NegligibleError, k, v))
}
}
if spec.Noconform != nil {
for k, v := range spec.Noconform {
d.errappend(ErrorAndSolve(FatalError, k, v))
}
}
if !spec.Conform {
return d.errors
}
//如果是dockerfile 解析dockerfile文件
if lang == code.Dockerfile {
if ok := d.parseDockerfileInfo(path.Join(buildPath, "Dockerfile")); !ok {
return d.errors
}
}
d.Dependencies = code.CheckDependencies(buildPath, lang)
d.Runtime = code.CheckRuntime(buildPath, lang)
d.memory = getRecommendedMemory(lang)
d.Procfile = code.CheckProcfile(buildPath, lang)
if rbdfileConfig != nil {
//handle profile env
for k, v := range rbdfileConfig.Envs {
d.envs[k] = &Env{Name: k, Value: v}
}
//handle profile port
for _, port := range rbdfileConfig.Ports {
d.ports[port.Port] = &Port{ContainerPort: port.Port, Protocol: port.Protocol}
}
}
return d.errors
}
func getRecommendedMemory(lang code.Lang) int {
//java语言推荐1024
if lang == code.JavaJar || lang == code.JavaMaven || lang == code.JaveWar {
return 1024
}
if lang == code.Python {
return 512
}
if lang == code.Nodejs {
return 512
}
if lang == code.PHP {
return 512
}
return 128
}
func (d *SourceCodeParse) errappend(pe ParseError) {
d.errors = append(d.errors, pe)
}
//GetBranchs 获取分支列表
func (d *SourceCodeParse) GetBranchs() []string {
return d.branchs
}
//GetPorts 获取端口列表
func (d *SourceCodeParse) GetPorts() (ports []Port) {
for _, cv := range d.ports {
ports = append(ports, *cv)
}
return ports
}
//GetVolumes 获取存储列表
func (d *SourceCodeParse) GetVolumes() (volumes []Volume) {
for _, cv := range d.volumes {
volumes = append(volumes, *cv)
}
return
}
//GetValid 获取源是否合法
func (d *SourceCodeParse) GetValid() bool {
return false
}
//GetEnvs 环境变量
func (d *SourceCodeParse) GetEnvs() (envs []Env) {
for _, cv := range d.envs {
envs = append(envs, *cv)
}
return
}
//GetImage 获取镜像
func (d *SourceCodeParse) GetImage() Image {
return d.image
}
//GetArgs 启动参数
func (d *SourceCodeParse) GetArgs() []string {
return d.args
}
//GetMemory 获取内存
func (d *SourceCodeParse) GetMemory() int {
return d.memory
}
//GetLang 获取识别语言
func (d *SourceCodeParse) GetLang() code.Lang {
return d.Lang
}
//GetRuntime GetRuntime
func (d *SourceCodeParse) GetRuntime() bool {
return d.Runtime
}
//GetServiceInfo 获取service info
func (d *SourceCodeParse) GetServiceInfo() []ServiceInfo {
serviceInfo := ServiceInfo{
Ports: d.GetPorts(),
Envs: d.GetEnvs(),
Volumes: d.GetVolumes(),
Image: d.GetImage(),
Args: d.GetArgs(),
Branchs: d.GetBranchs(),
Memory: d.memory,
Lang: d.GetLang(),
Dependencies: d.Dependencies,
Procfile: d.Procfile,
Runtime: d.Runtime,
}
return []ServiceInfo{serviceInfo}
}
func (d *SourceCodeParse) parseDockerfileInfo(dockerfile string) bool {
commands, err := sources.ParseFile(dockerfile)
if err != nil {
d.errappend(ErrorAndSolve(FatalError, err.Error(), "请确认Dockerfile格式是否符合规范"))
return false
}
for _, cm := range commands {
switch cm.Cmd {
case "env":
for i := 0; i < len(cm.Value); i++ {
d.envs[cm.Value[i]] = &Env{Name: cm.Value[i], Value: cm.Value[i+1]}
i++
}
case "expose":
for _, v := range cm.Value {
port, _ := strconv.Atoi(v)
if port != 0 {
d.ports[port] = &Port{ContainerPort: port, Protocol: GetPortProtocol(port)}
}
}
case "volume":
for _, v := range cm.Value {
d.volumes[v] = &Volume{VolumePath: v, VolumeType: model.ShareFileVolumeType.String()}
}
}
}
// dockerfile empty args
d.args = []string{}
return true
}