本以为很简单的一件事情搞了一天多的时间,郁闷啊。
目标:通过编写.drone.yml配置持续集成。最先测试的配置文件为:
.drone.yml
workspace:
base: /go
path: src/test/demo
pipeline:
build:
image: golang:latest
commands:
- go get
- go build
- go test
代码:
package main
import (
"fmt"
)
func main() {
fmt.Println("hello world!")
}
测试一切正常,如果就这么简单就不用往下写了。最终目标是实际生产中需要的带数据库的集成。然后就悲剧了:(
配置文件如下:
.drone.yml
workspace:
base: /go
path: src/test/demo
pipeline:
build:
image: golang:latest
commands:
- go get
- go build
- go test
services:
database:
image: mongo
main.go
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
Phone string
}
func main() {
r, _ := conn_mgo()
fmt.Println(r.Phone)
}
func conn_mgo() (*Person, error) {
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("people")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
if err != nil {
return nil, err
}
result := Person{}
err = c.Find(bson.M{"name": "Ale"}).One(&result)
if err != nil {
return nil, err
}
// fmt.Println("Phone:", result.Phone)
return &result, nil
}
main_test.go
package main
import (
"testing"
)
func Test_connmgo(t *testing.T) {
result, err := conn_mgo()
if err != nil {
t.Error(err)
}
t.Log(result.Phone)
}
编译失败。考虑几种可能
- 文档中描述的mongodb镜像未启动所以增加了 sleep选项
workspace:
base: /go
path: src/sunsl/demo
pipeline:
build:
image: golang:latest
commands:
- cat /etc/hosts
- sleep 10 #休眠
- go build
- go test
services:
database:
image: mongo:latest
commands:
- cat /etc/hosts
---失败!!
- 数据库连接错误
workspace:
base: /go
path: src/sunsl/demo
pipeline:
build:
image: golang:latest
commands:
- cat /etc/hosts
- sleep 10
- go build
- go test
services:
database:
image: mongo:
commands:
- cat /etc/hosts
意外发现在dababase下面增加name可以改变输出名称,呵呵,后面再说
.drone.yml
workspace:
base: /go
path: src/sunsl/demo
pipeline:
build:
image: golang:latest
commands:
- cat /etc/hosts
- sleep 10
- go build
- go test
services:
database:
name: mongo #改变名称?
image: mongo
commands:
- cat /etc/hosts
--失败!看到输出信息中database是exit code 0 (服务直接退出了?database与build一样的IP,神马情况?)
好吧,继续阅读官方文档,在仔细阅读后发现如下说明:
Services are accessed using custom hostnames. In the above example the mysql service is assigned the hostname database and is available at database:3306.
原来如(比)啊,一夜的测试还不如仔细阅读文档,为了简单去掉build节省时间:
.drone.yml
workspace:
base: /go
path: src/sunsl/demo
pipeline:
build:
image: golang:latest
commands:
- go test
services:
database:
image: mongo:latest
service正常退出的原因是因为加了command输出信息
mgo连接字符串应该为
mgo.Dial("database:27017")
上面说的修改名称修改的mongo实际上修改的是服务名称,如果改为如下设置:
workspace:
base: /go
path: src/sunsl/demo
pipeline:
build:
image: golang:latest
commands:
- cat /etc/hosts
- go test
services:
db: #服务名称修改
image: mongo:latest
这时连接字符串则需要修改为:
mgo.Dial("db:27017")
总算成功了,来张成功的图庆祝一下,然后睡觉!!!