由于生产中项目仓库通过触发tag push行为来接管CI后的行为,需要给每个代码仓库都添加webhooks,这个时候使用系统钩子来实现就很合适了,不用每次手动添加。
以下行为可以触发system hooks:
project_create
project_destroy
project_rename
project_transfer
project_update
user_add_to_team
user_remove_from_team
user_create
user_destroy
user_failed_login
user_rename
key_create
key_destroy
group_create
group_destroy
group_rename
user_add_to_group
user_remove_from_group
php实现脚本,当创建和删除项目时触发system hook:
<?php $sql_host = "gitlab.mysql01.chegva.com"; $sql_user = "git"; $sql_password = "chegva.com"; $database = "gitlabhq_production"; $port = '3306'; $logfile = '/home/anzhihe/data/www/hook/gitlab_webhook.log'; function log_append($message, $time = null) { global $logfile; $time = $time === null ? time() : $time; $date = date('Y-m-d H:i:s'); $pre = $date . ' (' . $_SERVER['REMOTE_ADDR'] . '): '; file_put_contents($logfile, $pre . $message . "\n", FILE_APPEND); } $sql = mysqli_connect($sql_host, $sql_user, $sql_password, $database, $port); if (mysqli_connect_errno()) { exit; } $file = fopen("/home/anzhihe/data/www/hook/sql_error.log", "a"); // you can use this as debug log too ;) $input = json_decode(file_get_contents('php://input'), true); $pid = $input['project_id']; $path_with_namespace = $input['path_with_namespace']; if ($input['event_name'] == "project_create") { log_append('add webhook start... -> pid: ' . $pid); $url = 'http://chegva.com/api/v1/fs/webhook'; // this creates a project hook, specify it for your needs.. $q = mysqli_query($sql, "INSERT INTO gitlabhq_production.web_hooks(url, project_id, push_events, tag_push_events) VALUES('$url', '$pid', '0', '1')"); if (!$q) { fwrite($file, $sql->error); } else { log_append('add web_hook succeed -> path: ' . $path_with_namespace); } } elseif ($input['event_name'] == "project_destroy") { $q = mysqli_query($sql, "DELETE FROM gitlabhq_production.web_hooks WHERE project_id='$pid'"); log_append('project destroy and remove webhook -> pid: ' . $pid); log_append('project destroy succeed -> path: ' . $path_with_namespace); mysqli_close($sql); } else { exit; } ?>
在Gitlab的nginx配置文件加下如下配置:
location = /explore { return 301 https://$http_host; } location = /add_webhook.php { root /home/anzhihe/data/www/hook; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; set $real_script_name $fastcgi_script_name; if ($fastcgi_script_name ~ "^(.+?\\.php)(/.*)?$") { set $real_script_name $1; set $path_info $2; } include fastcgi_params; fastcgi_param SCRIPT_REAL_SCRIPT_NAME $real_script_name; fastcgi_param SCRIPT_FILENAME $document_root$real_script_name; fastcgi_param SCRIPT_NAME $real_script_name; fastcgi_param PATH_INFO $path_info; fastcgi_param HTTP_X_FORWARDED_PORT 80; }
现在可以开始测试了。首先,添加system hooks,点击 Admin area -> System Hooks -> Add system hook
创建一个测试仓库:
可以看到新建的仓库自动添加了webhooks:
查看system hooks详细的执行过程:
查看日志记录:
之后所有新建仓库的时候都会自动加上webhooks,删除仓库时也会删除添加的webhooks,并且还有了日志记录,重要的是不用再手动一个个添加啦!
参考:https://docs.gitlab.com/ee/system_hooks/system_hooks.html