This is the codeAbility Sharing Platform! Learn more about the codeAbility Sharing Platform.

Skip to content
Snippets Groups Projects
trigger_project_update.py 2.25 KiB
Newer Older
#!/opt/gitlab/embedded/bin/python3
"""
When this module is installed as a file hook in GitLab, it forwards the event to a web service for further handling

"""
import logging
import logging.config
import requests
from configparser import ConfigParser
import sys
from enum import Enum
import os
import pathlib

from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple


def logger_setup(filepath: str) -> Dict[str, Any]:
    """
    Returns a dictionary which can be used to configure a logger.

    :param filepath: path of the log file
    :return: a dictionary to configure a logger
    """
    return {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "standard": {
                "format": "%(asctime)s %(levelname)-8s [%(filename)-20s:%(lineno)4d]: %(message)s"
            },
        },
        "handlers": {
            "file_handler": {
                "level": "INFO",
                "filename": filepath,
                "class": "logging.handlers.RotatingFileHandler",
                "formatter": "standard",
                "maxBytes": 524288,
                "backupCount": 2,
            }
        },
        "loggers": {
            "": {"handlers": ["file_handler"], "level": "INFO", "propagate": True},
        },
    }


def read_gitlab_event() -> str:
    """
    Reads the GitLab system hook event from stdin.

    :return: The event
    """
    event_content = ""
    for line in sys.stdin:
        event_content = event_content + line
    return event_content

if __name__ == "__main__":  # pragma: no cover

    _LOG_FILE = "/var/log/gitlab/gitlab-rails/trigger_project_update_local.log"
    logger_setup = logger_setup(_LOG_FILE)
    logging.config.dictConfig(logger_setup)
    logger = logging.getLogger(__name__)

Cont Deploy's avatar
Cont Deploy committed
    indexServiceURL = "http://sharing_search:8080/api/gitlab/eventListener"

    if(indexServiceURL is None):
        logger.error("INDEXING_SERVICE_URL is not set")
        sys.exit(1)

    event = read_gitlab_event()

    if event is not None:
        headers = {'Content-Type': 'application/json; charset=utf-8'}
        response = requests.post(indexServiceURL, headers=headers, data=event)
        logger.info('forwarded event to %s: Status %s', indexServiceURL, response.status_code)