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

相关推荐
kaixin_learn_qt_ing10 小时前
Bazel CI
ci/cd
创实信息3 天前
GitHub企业版:AWS CodeCommit迁移的最佳路径与技术优势
git·ci/cd·github·aws·github企业版·aws codecommit
Web项目开发3 天前
GoCD 持续集成和部署工具配置指南(CentOS 7)
linux·ci/cd·centos
魔幻云3 天前
第八章:持续集成管理
ci/cd
编码浪子4 天前
devops和ICCID简介
运维·ci/cd·docker·devops
vvw&4 天前
如何在 Ubuntu 22.04 服务器上安装 Jenkins
linux·运维·服务器·ubuntu·ci/cd·自动化·jenkins
优质&青年4 天前
【故障处理系列--gitlab的CI流水线下载安装包提示报错】
linux·运维·ci/cd·云原生·容器·gitlab
明明跟你说过4 天前
在Rocky Linux中安装【Jenkins】的详细指南
linux·运维·服务器·ci/cd·jenkins·devops
Anna_Tong4 天前
探索 CI/CD 工具的力量
ci/cd·开源·jenkins·开源软件·devops
虹科网络安全5 天前
艾体宝案例丨CircleCI 助力 ANA Systems 打造高效 CI/CD 模型
自动化测试·ci/cd·持续集成·saas平台·circleci