背景
根据上篇根据goreplay抓取到api的数据后,发现,在接入多个服务后,无法分辨各api是从哪个服务回放进来的,这时需要添加一个字段进行区分,这里准备使用goreplay+kubernetes的环境变量一起实现。
修改部署描述文件
设置ENV,SERVICE=podname
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
- env:
- name: INPUT
value: :8080
- name: OUTPUT
value: --output-http https://example.com/api/goreplay
- name: SERVICE
valueFrom:
fieldRef:
fieldPath: metadata.name
image: registry-vpc.cn-hangzhou.aliyuncs.com/zhangjinhui/goreplay:sidecar
imagePullPolicy: IfNotPresent
name: goreplay
resources:
limits:
cpu: 100m
memory: 100Mi
requests:
cpu: 100m
memory: 100Mi
|
修改goreplay源码
通过描述文件中设置的环境变量SERVICE,随后作为header一并回放到output-http
1
2
3
4
5
6
7
8
9
10
|
// fix #862
if c.config.url.Path == "" && c.config.url.RawQuery == "" {
req.URL.Scheme = c.config.url.Scheme
req.URL.Host = c.config.url.Host
} else {
req.URL.Path = c.config.url.Path + req.URL.Path
req.URL.Scheme = c.config.url.Scheme
req.URL.Host = c.config.url.Host
req.Header.Add("Service", os.Getenv("SERVICE"))
}
|
回放api时抓取Service
1
2
3
4
5
6
7
8
9
10
|
for key, values := range c.Ctx.Request.Header {
for _, value := range values {
if key == "Service" {
// :len(strings.Split(value, "-"))-2表示: 将pod-name-6f6f46b6b8-xc5xn 改为 pod-name
replay.Service = strings.Join(strings.Split(value, "-")[:len(strings.Split(value, "-"))-2], "-")
continue
}
replay.Header += fmt.Sprintf("%s:%s\n", key, value)
}
}
|