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服务正常监听

相关推荐
IT-民工2111011 小时前
CI/CD 实践总结
运维·ci/cd·自动化
蚊子不吸吸1 天前
DevOps开发运维简述
linux·运维·ci/cd·oracle·kubernetes·gitlab·devops
老攀呀2 天前
CI/CD 的概念
ci/cd
aklry2 天前
CI_CD
ci/cd
flying robot6 天前
GitHub Actions的 CI/CD
ci/cd·github
程序员雷叔6 天前
自动化测试类型与持续集成频率的关系
功能测试·测试工具·jmeter·ci/cd·单元测试·测试用例·postman
檀越剑指大厂6 天前
【MySQL系列】理解 `utf8mb4` 和 `utf8mb4_unicode_ci`
数据库·mysql·ci/cd
划碎、时光7 天前
Jenkins Pipeline 部署总结
ci/cd·jenkins
IT-民工211107 天前
Tekton 与其他 CI/CD 工具相比,有什么不同之处
ci/cd·tekton
一叶飘零_sweeeet7 天前
Jenkins 发布 Java 项目:高效持续集成与部署
java·ci/cd·jenkins