2016年二月月 发布的文章

部署私有Docker Registry

安装部署一个私有的Docker Registry是引入、学习和使用Docker这门技术的必经之路之一。尤其是当Docker被所在组织接受,更多人、项目和产品开始接触和使用Docker时,存储和分发自制的Docker image便成了刚需。Docker Registry一如既往的继承了“Docker坑多”的特点,为此这里将自己搭建”各类”Registry过程中执行的步骤、遇到的问题记录下来,为己备忘,为他参考。

Docker在2015年推出了distribution项目,即Docker Registry 2。相比于old registry,Registry 2使用Go实现,在安全性、性能方面均有大幅改进。Registry设计了全新的Rest API,并且在image存储格式等方面不再兼容于old Registry。去年8月份,docker官方hub使用Registriy 2.1替代了原先的old Registry。如果你要与Registry2交互,你的Docker版本至少要是Docker 1.6。

Docker的开发者也一直在致力于改善Registry安装和使用的体验,通过提供官方Registry Image以及Docker Compose工具等来简化Registry的配置。不过在本文中,我们只是利用Docker以及Registry的官方Image来部署Registry,这样更便于全面了解Registry的部署配置细节。

Registry2在镜像存储方面不仅支持本地盘,还支持诸多主流第三方存储方案。通过分布式存储系统你还可以实现一个分布式Docker Registry服务。这里仅以本地盘以及single node registry2为例。

一、环境

这里还是复用以往文章中的Docker环境:

Docker Registry Server: 10.10.105.71 Ubuntu 14.04 3.16.0-57-generic;docker 1.9.1

其他两个工作Server:
10.10.105.72 Ubuntu 14.04 3.19.0-25-generic; docker 1.9.1
10.10.126.101 Ubuntu 12.04 3.16.7-013607-generic; docker 1.9.1

本次Registry使用当前最新stable版本:Registry 2.3.0。由于镜像采用本地磁盘存储,root分区较小,需要映射使用其他volume。

二、初次搭建

本以为Docker Registry的搭建是何其简单的,甚至简单到通过一行命令就可以完成的。比如我们在Registry Server上执行:

在~/dockerregistry下,执行:

$sudo docker run -d -p 5000:5000 -v `pwd`/data:/var/lib/registry --restart=always --name registry registry:2
Unable to find image 'registry:2' locally
2: Pulling from library/registry
f32095d4ba8a: Pull complete
9b607719a62a: Pull complete
973de4038269: Pull complete
2867140211c1: Pull complete
8da16446f5ca: Pull complete
fd8c38b8b68d: Pull complete
136640b01f02: Pull complete
e039ba1c0008: Pull complete
c457c689c328: Pull complete
Digest: sha256:339d702cf9a4b0aa665269cc36255ee7ce424412d56bee9ad8a247afe8c49ef1
Status: Downloaded newer image for registry:2
e9088ef901cb00546c59f89defa4625230f4b36b0a44b3713f38ab3d2a5a2b44

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry            2                   c457c689c328        9 days ago          165.7 MB

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED              STATUS              PORTS                    NAMES
e9088ef901cb        registry:2          "/bin/registry /etc/d"   About a minute ago   Up About a minute   0.0.0.0:5000->5000/tcp   registry

Registry container已经跑起来了,其启动日志可以通过:docker logs registry查看。

我们在71本地给busybox:latest打一个tag,并尝试将新tag下的image push到Registry中去:

$ docker tag busybox:latest 10.10.105.71:5000/tonybai/busybox:latest
$ docker images
REPOSITORY                          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry                            2                   c457c689c328        9 days ago          165.7 MB
busybox                             latest              65e4158d9625        9 days ago          1.114 MB
10.10.105.71:5000/tonybai/busybox   latest              65e4158d9625        9 days ago          1.114 MB
... ...

push到Registry中:

$ docker push 10.10.105.71:5000/tonybai/busybox
The push refers to a repository [10.10.105.71:5000/tonybai/busybox] (len: 1)
unable to ping registry endpoint https://10.10.105.71:5000/v0/
v2 ping attempt failed with error: Get https://10.10.105.71:5000/v2/: Tunnel or SSL Forbidden
 v1 ping attempt failed with error: Get https://10.10.105.71:5000/v1/_ping: Tunnel or SSL Forbidden

出错了!简单分析了一下,可能是71上docker daemon配置中加了http代理的缘故,导致无法ping通registry endpoint。于是在/etc/default/docker中注释掉export http_proxy=”xxx”的设置,并重启docker daemon。

再次尝试push:

$ docker push 10.10.105.71:5000/tonybai/busybox
The push refers to a repository [10.10.105.71:5000/tonybai/busybox] (len: 1)
unable to ping registry endpoint https://10.10.105.71:5000/v0/
v2 ping attempt failed with error: Get https://10.10.105.71:5000/v2/: tls: oversized record received with length 20527
 v1 ping attempt failed with error: Get https://10.10.105.71:5000/v1/_ping: tls: oversized record received with length 20527

虽然还是失败,但错误信息已有所不同了。这次看来连接是可以建立的,但client端通过https访问server端,似乎想tls通信,但这一过程并未完成。

在其他机器上尝试push image到registry也遇到了同样的错误输出,如下:

10.10.105.72:

$ docker push 10.10.105.71:5000/tonybai/ubuntu
The push refers to a repository [10.10.105.71:5000/tonybai/ubuntu] (len: 1)
unable to ping registry endpoint https://10.10.105.71:5000/v0/
v2 ping attempt failed with error: Get https://10.10.105.71:5000/v2/: tls: oversized record received with length 20527
 v1 ping attempt failed with error: Get https://10.10.105.71:5000/v1/_ping: tls: oversized record received with length 20527

从错误信息来看,client与Registry交互,默认将采用https访问,但我们在install Registry时并未配置指定任何tls相关的key和crt文件,https访问定然失败。要想弄清这个问题,只能查看Registry Manual

三、Insecure Registry

Registry的文档还是相对详尽的。在文档中,我们找到了Insecure Registry,即接收plain http访问的Registry的配置和使用方法,虽然这不是官方推荐的。

实际上对于我们内部网络而言,Insecure Registry基本能满足需求,部署过程也避免了secure registry的那些繁琐步骤,比如制作和部署证书等。

为了搭建一个Insecure Registry,我们需要先清理一下上面已经启动的Registry容器。

$ docker stop registry
registry
$ docker rm registry
registry

修改Registry server上的Docker daemon的配置,为DOCKER_OPTS增加–insecure-registry:

DOCKER_OPTS="--insecure-registry 10.10.105.71:5000 ....

重启Docker Daemon,启动Registry容器:

$ sudo service docker restart
docker stop/waiting
docker start/running, process 6712
$ sudo docker run -d -p 5000:5000 -v `pwd`/data:/var/lib/registry --restart=always --name registry registry:2
5966e92fce9c34705050e19368d19574e021a272ede1575385ef35ecf5cea019

尝试再次Push image:

$ docker push 10.10.105.71:5000/tonybai/busybox
The push refers to a repository [10.10.105.71:5000/tonybai/busybox] (len: 1)
65e4158d9625: Pushed
5506dda26018: Pushed
latest: digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892 size: 2739

这回push ok!

我们将本地的tag做untag处理,再从Registry pull相关image:

$ docker images
REPOSITORY                          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry                            2                   c457c689c328        9 days ago          165.7 MB
10.10.105.71:5000/tonybai/busybox   latest              65e4158d9625        9 days ago          1.114 MB
busybox                             latest              65e4158d9625        9 days ago          1.114 MB
ubuntu                              14.04               6cc0fc2a5ee3        5 weeks ago         187.9 MB

$ docker rmi 10.10.105.71:5000/tonybai/busybox
Untagged: 10.10.105.71:5000/tonybai/busybox:latest

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry            2                   c457c689c328        9 days ago          165.7 MB
busybox             latest              65e4158d9625        9 days ago          1.114 MB
ubuntu              14.04               6cc0fc2a5ee3        5 weeks ago         187.9 MB

$ docker pull 10.10.105.71:5000/tonybai/busybox
Using default tag: latest
latest: Pulling from tonybai/busybox
Digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892
Status: Downloaded newer image for 10.10.105.71:5000/tonybai/busybox:latest

$ docker images
REPOSITORY                          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry                            2                   c457c689c328        9 days ago          165.7 MB
10.10.105.71:5000/tonybai/busybox   latest              65e4158d9625        9 days ago          1.114 MB
busybox                             latest              65e4158d9625        9 days ago          1.114 MB
ubuntu                              14.04               6cc0fc2a5ee3        5 weeks ago         187.9 MB

可以看到:Pull过程也很顺利。

在Private Registry2中查看或检索Repository或images,将不能用docker search

$ docker search 10.10.105.71:5000/tonybai/busybox/
Error response from daemon: Unexpected status code 404

但通过v2版本的API,我们可以实现相同目的:

$curl  http://10.10.105.71:5000/v2/_catalog
{"repositories":["tonybai/busybox"]}

$ curl  http://10.10.105.71:5000/v2/tonybai/busybox/tags/list
{"name":"tonybai/busybox","tags":["latest"]}

在其他主机上,我们尝试pull busybox:

10.10.105.72:

$docker pull 10.10.105.71:5000/tonybai/busybox
Using default tag: latest
Error response from daemon: unable to ping registry endpoint https://10.10.105.71:5000/v0/
v2 ping attempt failed with error: Get https://10.10.105.71:5000/v2/: tls: oversized record received with length 20527
 v1 ping attempt failed with error: Get https://10.10.105.71:5000/v1/_ping: tls: oversized record received with length 20527

我们发现依旧不能pull和push!在Registry手册中讲到,如果采用insecure registry的模式,那么所有与Registry交互的主机上的Docker Daemon都要配置:–insecure-registry选项。

我们按照上面的配置方法,修改105.72上的/etc/default/docker,重启Docker daemon,再执行pull/push就会得到正确的结果:

$ sudo vi /etc/default/docker
$ sudo service docker restart
docker stop/waiting
docker start/running, process 10614
$ docker pull 10.10.105.71:5000/tonybai/busybox
Using default tag: latest
latest: Pulling from tonybai/busybox
5506dda26018: Pull complete
65e4158d9625: Pull complete
Digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892
Status: Downloaded newer image for 10.10.105.71:5000/tonybai/busybox:latest

$ docker images
REPOSITORY                          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                              14.04               36248ae4a9ac        8 days ago          187.9 MB
10.10.105.71:5000/tonybai/ubuntu    14.04               36248ae4a9ac        8 days ago          187.9 MB
10.10.105.71:5000/tonybai/busybox   latest              65e4158d9625        9 days ago          1.114 MB

$ docker push 10.10.105.71:5000/tonybai/ubuntu
The push refers to a repository [10.10.105.71:5000/tonybai/ubuntu] (len: 1)
36248ae4a9ac: Pushed
8ea5373bf5a6: Pushed
2e0188208e83: Pushed
e3c70beaa378: Pushed
14.04: digest: sha256:72e56686cb9fb38438f0fd68fecf02ef592ce2ef7069bbf97802d959d568c5cc size: 6781

四、Secure Registry

Docker官方是推荐你采用Secure Registry的工作模式的,即transport采用tls。这样我们就需要为Registry配置tls所需的key和crt文件了。

我们首先清理一下环境,将上面的Insecure Registry停掉并rm掉;将各台主机上Docker Daemon的DOCKER_OPTS配置中的–insecure-registry去掉,并重启Docker Daemon。

如果你拥有一个域名,域名下主机提供Registry服务,并且你拥有某知名CA签署的证书文件,那么你可以建立起一个Secure Registry。不过我这里没有现成的证书,只能使用自签署的证书。严格来讲,使用自签署的证书在Docker官方眼中依旧属于Insecure,不过这里只是借助自签署的证书来说明一下Secure Registry的部署步骤罢了。

1、制作自签署证书

如果你有知名CA签署的证书,那么这步可直接忽略。

$ openssl req -newkey rsa:2048 -nodes -sha256 -keyout certs/domain.key -x509 -days 365 -out certs/domain.crt
Generating a 2048 bit RSA private key
..............+++
............................................+++
writing new private key to 'certs/domain.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Liaoning
Locality Name (eg, city) []:shenyang
Organization Name (eg, company) [Internet Widgits Pty Ltd]:foo
Organizational Unit Name (eg, section) []:bar
Common Name (e.g. server FQDN or YOUR name) []:mydockerhub.com
Email Address []:bigwhite.cn@gmail.com

2、启动Secure Registry

启动带证书的Registry:

$ docker run -d -p 5000:5000 --restart=always --name registry \
  -v `pwd`/data:/var/lib/registry \
  -v `pwd`/certs:/certs \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
  registry:2
35e8ce77dd455f2bd50854e4581cd52be8a137f4aaea717239b6d676c5ea5777

由于证书的CN是mydockerhub.com,我们需要修改一下/etc/hosts文件:

10.10.105.71 mydockerhub.com

重新为busybox制作一个tag:

$docker tag busybox:latest mydockerhub.com:5000/tonybai/busybox:latest

Push到Registry:

$ docker push mydockerhub.com:5000/tonybai/busybox
The push refers to a repository [mydockerhub.com:5000/tonybai/busybox] (len: 1)
unable to ping registry endpoint https://mydockerhub.com:5000/v0/
v2 ping attempt failed with error: Get https://mydockerhub.com:5000/v2/: x509: certificate signed by unknown authority
 v1 ping attempt failed with error: Get https://mydockerhub.com:5000/v1/_ping: x509: certificate signed by unknown authority

push失败了!从错误日志来看,docker client认为server传输过来的证书的签署方是一个unknown authority(未知的CA),因此验证失败。我们需要让docker client安装我们的CA证书:

$ sudo mkdir -p /etc/docker/certs.d/mydockerhub.com:5000
$ sudo cp certs/domain.crt /etc/docker/certs.d/mydockerhub.com:5000/ca.crt
$ sudo service docker restart //安装证书后,重启Docker Daemon

再执行Push,我们看到了成功的输出日志。由于data目录下之前已经被push了tonybai/busybox repository,因此提示“已存在”:

$docker push mydockerhub.com:5000/tonybai/busybox
The push refers to a repository [mydockerhub.com:5000/tonybai/busybox] (len: 1)
65e4158d9625: Image already exists
5506dda26018: Image already exists
latest: digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892 size: 2739

3、外部访问Registry

我们换其他机器试试访问这个secure registry。根据之前的要求,我们照猫画虎的修改一下hosts文件,安装ca.cert,去除–insecure-registry选项,并重启Docker daemon。之后尝试从registry pull image:

$ docker pull mydockerhub.com:5000/tonybai/busybox
Using default tag: latest
latest: Pulling from tonybai/busybox

Digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892
Status: Downloaded newer image for mydockerhub.com:5000/tonybai/busybox:latest

$ docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
10.10.105.71:5000/tonybai/ubuntu       14.04               36248ae4a9ac        9 days ago          187.9 MB
ubuntu                                 14.04               36248ae4a9ac        9 days ago          187.9 MB
10.10.105.71:5000/tonybai/busybox      latest              65e4158d9625        9 days ago          1.114 MB
mydockerhub.com:5000/tonybai/busybox   latest              65e4158d9625        9 days ago          1.114 MB

这样来看,如果使用自签署的证书,那么所有要与Registry交互的Docker主机都需要安装mydockerhub.com的ca.crt(domain.crt)。但如果你使用知名CA,这一步也就可以忽略。

五、Registry的鉴权管理

Registry提供了一种基础的鉴权方式。我们通过下面步骤即可为Registry加上基础鉴权:

在Register server上,为Registry增加foo用户,密码foo123:(之前需要停掉已有的Registry,并删除之)

//生成鉴权密码文件
$ mkdir auth
$ docker run --entrypoint htpasswd registry:2 -Bbn foo foo123  > auth/htpasswd
$ ls auth
htpasswd

//启动带鉴权功能的Registry:
$ docker run -d -p 5000:5000 --restart=always --name registry \
   -v `pwd`/auth:/auth \
   -e "REGISTRY_AUTH=htpasswd" \
   -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" \
   -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \
   -v `pwd`/data:/var/lib/registry \
   -v `pwd`/certs:/certs \
   -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
   -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \
   registry:2
199ad0b3591fb9613b21b1c96f017267f3c39661a7025d30df636c6805e7ab50

在105.72上,我们尝试push image到Registry:

$ docker push mydockerhub.com:5000/tonybai/busybox
The push refers to a repository [mydockerhub.com:5000/tonybai/busybox] (len: 1)
65e4158d9625: Image push failed
Head https://mydockerhub.com:5000/v2/tonybai/busybox/blobs/sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4: no basic auth credentials

错误信息提示:鉴权失败。

在72上执行docker login:

$docker login mydockerhub.com:5000
Username: foo
Password:
Email: bigwhite.cn@gmail.com
WARNING: login credentials saved in /home/baiming/.docker/config.json
Login Succeeded

login成功后,再行Push:

$ docker push mydockerhub.com:5000/tonybai/busybox
The push refers to a repository [mydockerhub.com:5000/tonybai/busybox] (len: 1)
65e4158d9625: Image already exists
5506dda26018: Image already exists
latest: digest: sha256:800f2d4558acd67f52262fbe170c9fc2e67efaa6f230a74b41b555e6fcca2892 size: 2739

Push ok!

六、Registry中images的管理

前面提到过,通过V2版Rest API可以查询Repository和images:

$ curl --cacert domain.crt  --basic --user foo:foo123 https://mydockerhub.com:5000/v2/_catalog
{"repositories":["tonybai/busybox","tonybai/ubuntu"]}

但如果要删除Registry中的Repository或某个tag的Image,目前v2还不支持,原因见Registry的roadmap中的说明

不过如果你的Registry的存储引擎使用的是本地盘,倒是有一些第三方脚本可供使用,比如:delete-docker-registry-image

七、小结

Registry2发布不到1年,目前还有许多问题待解决,就比如delete image的问题,相信在2.4以及后续版本这些问题会被逐个解决掉或能找到一个相对理想的方案。

Go 1.6中值得关注的几个变化

北京时间2016年2月18日凌晨,在Go 1.5发布 半年后,Go 1.6正式Release 了。与Go 1.5的“惊天巨变”(主要指Go自举)相比,Go 1.6的Change 算是很小的了,当然这也与Go 1.6的dev cycle过于短暂有关。但Go社区对此次发布却甚是重视,其热烈程度甚至超出了Go 1.5。在Dave Cheney的倡导 下,Gophers们在全球各地举行了Go 1.6 Release Party。 Go Core Team也在Reddit上开了一个AMA – Ask Me Anything,RobPike、Russ Cox(Rsc)、Bradfitz等Go大神齐上阵,对广大Gophers们在24hour内的问题有问必答。

言归正传,我们来看看Go 1.6中哪些变化值得我们关注。不过在说变化之前,我们先提一嘴Go 1.6没变的,那就是Go语言的language specification,依旧保持Go 1兼容不变。预计在未来的几个stable release版本中,我们也不会看到Go language specification有任何改动。

一、cgo

cgo的变化在于:
1、定义了在Go code和C code间传递Pointer,即C code与Go garbage collector共存的rules和restriction;
2、在runtime加入了对违规传递的检查,检查的开关和力度由GODEBUG=cgocheck=1[0,2]控制。1是默认;0是关闭检 查;2是更全面彻底但代价更高的检查。

这个Proposal是由Ian Lance Taylor提出的。大致分为两种情况:

(一) Go调用C Code时

Go调用C Code时,Go传递给C Code的Go Pointer所指的Go Memory中不能包含任何指向Go Memory的Pointer。我们分为几种情况来探讨一下:

1、传递一个指向Struct的指针

//cgo1_struct.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(struct Foo *f) {
    (f->a)++;
    *(f->p)++;
}
*/
import "C"
import "unsafe"
import "fmt"

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))
    //f.p = &f.a

    C.plusOne(f)
    fmt.Println(int(f.a))
}

从cgo1_struct.go代码中可以看到,Go code向C code传递了一个指向Go Memory(Go分配的)指针f,但f指向的Go Memory中有一个指针p指向了另外一处Go Memory: new(int),我们来run一下这段代码:

$go run cgo1_struct.go
# command-line-arguments
./cgo1_struct.go:12:2: warning: expression result unused [-Wunused-value]
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x4068400, 0xc82000a110)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_struct.go:24 +0xb9
exit status 2

代码出现了Panic,并提示:“cgo argument has Go pointer to Go pointer”。我们的代码违背了Cgo Pointer传递规则,即便让f.p指向struct自身内存也是不行的,比如f.p = &f.a。

2、传递一个指向struct field的指针

按照rules中的说明,如果传递的是一个指向struct field的指针,那么”Go Memory”专指这个field所占用的内存,即便struct中有其他field指向其他Go memory也不打紧:

//cgo1_structfield.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(int *i) {
    (*i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))

    C.plusOne(&f.a)
    fmt.Println(int(f.a))
}

上述程序的运行结果:

$go run cgo1_structfield.go
6

3、传递一个指向slice or array中的element的指针

和传递struct field不同,传递一个指向slice or array中的element的指针时,需要考虑的Go Memory的范围不仅仅是这个element,而是整个Array或整个slice背后的underlying array所占用的内存区域,要保证这个区域内不包含指向任意Go Memory的指针。我们来看代码示例:

//cgo1_sliceelem.go
package main

/*
#include <stdio.h>
void plusOne(int **i) {
    (**i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    sl := make([]*int, 5)
    var a int = 5
    sl[1] = &a
    C.plusOne((**C.int)((unsafe.Pointer)(&sl[0])))
    fmt.Println(sl[0])
}

从这个代码中,我们看到我们传递的是slice的第一个element的地址,即&sl[0]。我们并未给sl[0]赋值,但sl[1] 被赋值为另外一块go memory的address(&a),当我们将&sl[0]传递给plusOne时,执行结果如下:

$go run cgo1_sliceelem.go
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x40dbac0, 0xc8200621d0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_sliceelem.go:19 +0xe4
exit status 2

由于违背规则,因此runtime panic了。

(二) C调用Go Code时

1、C调用的Go函数不能返回指向Go分配的内存的指针

我们看下面例子:

//cgo2_1.go

package main

// extern int* goAdd(int, int);
//
// static int cAdd(int a, int b) {
//     int *i = goAdd(a, b);
//     return *i;
// }
import "C"
import "fmt"

//export goAdd
func goAdd(a, b C.int) *C.int {
    c := a + b
    return &c
}

func main() {
    var a, b int = 5, 6
    i := C.cAdd(C.int(a), C.int(b))
    fmt.Println(int(i))
}

可以看到:goAdd这个Go函数返回了一个指向Go分配的内存(&c)的指针。运行上述代码,结果如下:

$go run cgo2_1.go
panic: runtime error: cgo result has Go pointer

goroutine 1 [running]:
panic(0x40dba40, 0xc82006e1c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main._cgoexpwrap_872b2f2e7532_goAdd.func1(0xc820049d98)
    command-line-arguments/_obj/_cgo_gotypes.go:64 +0x3a
main._cgoexpwrap_872b2f2e7532_goAdd(0x600000005, 0xc82006e19c)
    command-line-arguments/_obj/_cgo_gotypes.go:66 +0x89
main._Cfunc_cAdd(0x600000005, 0x0)
    command-line-arguments/_obj/_cgo_gotypes.go:45 +0x41
main.main()
    /Users/tony/test/go/go16/cgo/cgo2_1.go:20 +0x35
exit status 2

2、Go code不能在C分配的内存中存储指向Go分配的内存的指针

下面的例子模拟了这一情况:

//cgo2_2.go
package main

// #include <stdlib.h>
// extern void goFoo(int**);
//
// static void cFoo() {
//     int **p = malloc(sizeof(int*));
//     goFoo(p);
// }
import "C"

//export goFoo
func goFoo(p **C.int) {
    *p = new(C.int)
}

func main() {
    C.cFoo()
}

不过针对此例,默认的GODEBUG=cgocheck=1偏是无法check出问题。我们将GODEBUG=cgocheck改为=2试试:

$GODEBUG=cgocheck=2 go run cgo2_2.go
write of Go pointer 0xc82000a0f8 to non-Go memory 0x4300000
fatal error: Go pointer stored into non-Go memory

runtime stack:
runtime.throw(0x4089800, 0x24)
    /Users/tony/.bin/go16/src/runtime/panic.go:530 +0x90
runtime.cgoCheckWriteBarrier.func1()
    /Users/tony/.bin/go16/src/runtime/cgocheck.go:44 +0xae
runtime.systemstack(0x7fff5fbff8c0)
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:291 +0x79
runtime.mstart()
    /Users/tony/.bin/go16/src/runtime/proc.go:1048
... ...
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:1998 +0x1
exit status 2

果真runtime panic: write of Go pointer 0xc82000a0f8 to non-Go memory 0×4300000

二、HTTP/2

HTTP/2原本是bradfitz维护的x项目,之前位于golang.org/x/net/http2包中,Go 1.6无缝合入Go标准库net/http包中。并且当你你使用https时,client和server端将自动默认使用HTTP/2协议。

HTTP/2与HTTP1.x协议不同在于其为二进制协议,而非文本协议,性能自是大幅提升。HTTP/2标准已经发布,想必未来若干年将大行其道。

HTTP/2较为复杂,这里不赘述,后续maybe会单独写一篇GO和http2的文章说明。

三、Templates

由于不开发web,templates我日常用的很少。这里粗浅说说templates增加的两个Feature

trim空白字符

Go templates的空白字符包括:空格、水平tab、回车和换行符。在日常编辑模板时,这些空白尤其难于处理,由于是对beatiful format和code readabliity有“强迫症”的同学,更是在这方面话费了不少时间。

Go 1.6提供了{{-和-}}来帮助大家去除action前后的空白字符。下面的例子很好的说明了这一点:

//trimwhitespace.go
package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

func tmplbefore15() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplaftergo16() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    tmplbefore15()
    tmplaftergo16()
}

这个例子的运行结果:

$go run trimwhitespace.go

    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

block action

block action提供了一种在运行时override已有模板形式的能力。

package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

var overrideItemList = `
{{define "list" -}}
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
{{end}}
`

var tmpl = `
    Items:
    {{block "list" . -}}
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    {{end}}
`

var t *template.Template

func init() {
    t = template.Must(template.New("tmpl").Parse(tmpl))
}

func tmplBeforeOverride() {
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplafterOverride() {
    t = template.Must(t.Parse(overrideItemList))
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    fmt.Println("before override:")
    tmplBeforeOverride()
    fmt.Println("after override:")
    tmplafterOverride()
}

原模板tmpl中通过block action定义了一处名为list的内嵌模板锚点以及初始定义。后期运行时通过re-parse overrideItemList达到修改模板展示形式的目的。

上述代码输出结果:

$go run blockaction.go
before override:

    Items:
    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

after override:

    Items:
    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

四、Runtime

降低大内存使用时的GC latency

Go 1.5.x用降低一些吞吐量的代价换取了10ms以下的GC latency。不过针对Go 1.5,官方给出的benchmark图中,内存heap size最多20G左右。一旦超过20G,latency将超过10ms,也许会线性增长。
在Go 1.6中,官方给出的benchmark图中当内存heap size在200G时,GC latency依旧可以稳定在10ms;在heap size在20G以下时,latency降到了6ms甚至更小。

panic info

Go 1.6之前版本,一旦程序以panic方式退出,runtime便会将所有goroutine的stack信息打印出来:

$go version
go version go1.5.2 darwin/amd64
[ ~/test/go/go16/runtime]$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95

goroutine 4 [select (no cases)]:
main.main.func1(0x8200f40f0)
    /Users/tony/test/go/go16/runtime/panic.go:13 +0x26
created by main.main
    /Users/tony/test/go/go16/runtime/panic.go:14 +0x72
... ...

而Go 1.6后,Go只会打印正在running的goroutine的stack信息,因此它才是最有可能造成panic的真正元凶:

go 1.6:
$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
panic(0x61e80, 0x8200ee0c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95
exit status 2

map race detect

Go原生的map类型是goroutine-unsafe的,长久以来,这给很多Gophers带来了烦恼。这次Go 1.6中Runtime增加了对并发访问map的检测以降低gopher们使用map时的心智负担。

这里借用了Francesc Campoy在最近一期”The State of Go”中的示例程序:

package main

import "sync"

func main() {
    const workers = 100

    var wg sync.WaitGroup
    wg.Add(workers)
    m := map[int]int{}
    for i := 1; i <= workers; i++ {
        go func(i int) {
            for j := 0; j < i; j++ {
                m[i]++
            }
            wg.Done()
        }(i)
    }
    wg.Wait()
}

执行结果:

$ go run map.go
fatal error: concurrent map writes
fatal error: concurrent map writes
... ...

这里在双核i5 mac air下亲测时,发现当workers=2,3,4均不能检测出race。当workers >= 5时可以检测到。

五、其他

手写parser替代yacc生成的parser

这个变化对Gopher们是透明的,但对于Go compiler本身却是十分重要的。

Robert Riesemer在Go 1.6代码Freezing前commit了手写Parser,以替代yacc生成的parser。在AMA上RobPike给出了更换Parser的些许理由:
1、Go compiler可以少维护一个yacc工具,这样更加cleaner;
2、手写Parser在性能上可以快那么一点点。

Go 1.6中GO15VENDOREXPERIMENT将默认开启

根据当初在Go 1.5中引入vendor时的计划,Go 1.6中GO15VENDOREXPERIMENT将默认开启。这显然会导致一些不兼容的情况出现:即如果你的代码在之前并未使用vendor机制,但目录组织中有vendor目录。Go Core team给出的解决方法就是删除vendor目录或改名。

遗留问题是否解决

Go 1.5发布后,曾经发现两个问题,直到Go 1.5.3版本发布也未曾解决,那么Go 1.6是否解决了呢?我们来验证一下。

internal问题

该问题的具体细节可参看我在go github上提交的issue 12217,我在自己的experiments中提交了问题的验证环境代码,这次我们使用Go 1.6看看internal问题是否还存在:

$cd $GOPATH/src/github.com/bigwhite/experiments/go15-internal-issue-12217
$cd otherpkg/
$go build main.go
package main
    imports github.com/bigwhite/experiments/go15-internal-issue-12217/mypkg/internal/foo: use of internal package not allowed

这回go compiler给出了error,而不是像之前版本那样顺利编译通过。看来这个问题是fix掉了。

GOPATH之外vendor机制是否起作用的问题

我们先建立实验环境:

$tree
.
└── testvendor
    └── src
        └── proj1
            ├── main.go
            └── vendor
                └── github.com
                    └── bigwhite
                        └── foo
                            └── foolib.go

进入proj1,build main.go

go build main.go
main.go:3:8: cannot find package "github.com/bigwhite/foo" in any of:
    /Users/tony/.bin/go16/src/github.com/bigwhite/foo (from $GOROOT)
    /Users/tony/Test/GoToolsProjects/src/github.com/bigwhite/foo (from $GOPATH)

go 1.6编译器没有关注同路径下的vendor目录,build失败。

我们设置GOPATH=xxx/testvendor后,再来build:

$export GOPATH=~/Test/go/go16/others/testvendor
$go run main.go
Hello from temp vendor

这回编译运行ok。

由此看来,Go 1.6 vendor在GOPATH外依旧不生效。

六、小结

Go 1.6标准库细微变化还是有很多的,在Go 1.6 Release Notes中可细细品味。

Go 1.6的编译速度、编译出的程序的运行性能与Go 1.5.x也大致无二异。

另外本文实现环境如下:

go version go1.6 darwin/amd64
Darwin tonydeair-2.lan 13.1.0 Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64

实验代码可在这里下载。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats