Gerrit 事件监听实现

环境

Centos 7.9

Gerrit 2.15

Gerrit 2.15容器搭建

docker-compose.yml

version: '3'
services:
  gerrit:
    image: gerritcodereview/gerrit:2.15
    ports:
      - 8080:8080
      - 29418:29418
    volumes:
      - ./review_site:/var/gerrit/review_site
    environment:
      - CANONICAL_WEB_URL=http://localhost:8080/
      - JAVA_HOME=/usr/lib/jvm/java
  postgres:
    image: postgres:12
    environment:
      - POSTGRES_USER=gerrit
      - POSTGRES_PASSWORD=gerrit
      - POSTGRES_DB=gerrit

启动docker

docker-compose up -d

方式一 Gerrit Stream

利用 gerrit stream-events 实现对Gerrit所有事件的监听

生成密钥

ssh-keygen -t rsa -b 4096

配置SSH

配置All-Projects的Stream Events

代码部分

python 复制代码
import subprocess
import json


def handle_data(data):
    # 处理从gerrit stream-events获取的数据
    event_data = json.loads(data)
    # 事件数据
    print('---event_data begin---')
    print(event_data)
    print('---event_data end---')

    # 根据事件类型执行相应的操作
    event_type = event_data.get('type')

    if event_type == 'change-merged':
        # 处理变更合并事件
        change_id = event_data.get('change').get('id')
        print(f'Change {change_id} merged')
        # 执行其他操作...
    elif event_type == 'comment-added':
        # 处理评论添加事件
        change_id = event_data.get('change').get('id')
        comment = event_data.get('comment')
        print(f'New comment on Change {change_id}: {comment}')
    else:
        # 处理其他事件类型
        print(f'Unsupported event type: {event_type}')


def listen_to_gerrit_events():
    cmd = ['ssh', '-p', '29418', '-i', 'C:\\Users\\xxx\\.ssh\\id_rsa', 'admin@192.168.186.138', 'gerrit',
           'stream-events']
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)

    for line in iter(proc.stdout.readline, b''):
        handle_data(line.decode('utf-8'))


if __name__ == "__main__":
    listen_to_gerrit_events()

在Gerrit操作patch,代码会打印相应的事件

方式二 Gerrit Webhook

以Gerrit 2.15为例

使用webhook插件实现Gerrit主动向自己的web服务发送请求

  1. 下载&打包webhooks插件

下载地址:https://gerrit.googlesource.com/plugins/webhooks

(Gerrit 2.15对应https://gerrit.googlesource.com/plugins/webhooks/+/refs/heads/stable-2.15)

安装 bazel(1.1.0版本)

cd /usr/bin && curl -fLO https://releases.bazel.build/1.1.0/release/bazel-1.1.0-linux-x86_64 && chmod +x bazel-1.1.0-linux-x86_64

下载插件代码

git clone https://gerrit.googlesource.com/plugins/webhooks -b stable-2.15

编译插件(需要访问外网)

bazel build //...

查看编译产物

cd bazel-bin
ls

将产物拷贝到Gerrit容器的插件目录下

docker cp webhooks.jar gerrit:/var/gerrit/plugins

重启Gerrit容器

docker restart gerrit
  1. 配置All-Projects

下载All-Projects代码

git clone ssh://admin@xxx:29418/All-Projects

切换分支

git fetch origin refs/meta/config:refs/remotes/origin/meta/config
git checkout meta/config

项目根目录下创建&配置webhooks.config

vi webhooks.config

[remote "changemerged"]
  url = http://192.168.38.1:8081/change-merged
  event = change-merged

[remote "project_created"]
  url = http://192.168.38.1:8081/create-jenkins-project
  event = project-created

其中,192.168.38.1:8081是你的web服务地址

上传修改

git commit -am "Add webhooks config file"
git push origin meta/config:meta/config

本地编写web服务

from flask import Flask, request

app = Flask(__name__)


@app.route('/change-merged', methods=['POST', 'GET'])
def handle_gerrit_webhook():
    print(request.headers)
    data = request.get_json()
    print(data)
    event_type = data['type']
    if event_type == 'change-merged':
        project = data['change']['project']
        branch = data['change']['branch']
        commit_id = data['change']['commitMessage'].split('\n')[0]
        print(f'Code commit {commit_id} has been merged into {project}/{branch}')
    return 'OK'


@app.route('/create-jenkins-project', methods=['POST', 'GET'])
def handle_gerrit_webhook1():
    print(request.headers)
    data = request.get_json()
    print(data)
    event_type = data['type']
    if event_type == 'create-jenkins-project':
        project = data['change']['project']
        branch = data['change']['branch']
        commit_id = data['change']['commitMessage'].split('\n')[0]
        print(f'Code commit {commit_id} has been merged into {project}/{branch}')
    return 'OK'


if __name__ == '__main__':
    app.run(host='192.168.38.1', port=8081, debug=True)

创建新项目

将在Gerrit平台上代码合入,web服务正常监听

相关推荐
安静读书20 小时前
持续集成与持续部署:CI/CD简介
运维·ci/cd
安静读书2 天前
持续集成与持续部署:CI/CD实现教程
ci/cd
AliCloudROS3 天前
2分钟在阿里云ECS控制台部署个人应用(图文示例)
阿里云·ci/cd·持续部署
天草二十六_简村人4 天前
jenkins用户在执行scp的时候如何做免密登录
运维·ci/cd·node.js·jenkins·php·devops
Lalolander4 天前
通过华为鲲鹏认证发行上市的集成平台产品推荐
大数据·人工智能·科技·安全·ci/cd·华为·持续集成
golitter.4 天前
CI/CD认识
运维·ci/cd
莫尔道嘎老范5 天前
vue+vite前端项目ci过程中遇到的问题
前端·vue.js·ci/cd
小技与小术6 天前
CICD持续集成与持续交付
ci/cd·云原生·kubernetes
杨哥带你写代码6 天前
Spring Boot编程训练系统:敏捷开发与持续集成
spring boot·ci/cd·敏捷流程
qq_4337169511 天前
编写第一个 Appium 测试脚本:从安装到运行!
自动化测试·软件测试·jmeter·ci/cd·职场和发展·appium·jenkins