summaryrefslogtreecommitdiff
path: root/sitemodules/profiles/files/icinga2_master/icinga2-git-pull-hook
blob: a0d37118b7a531d9d92df4bf027a6b03747e5f19 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3

"""
This script takes care of updating the configuration in a directory by
performing git pull when triggered via an HTTP request to port 8000.

The script needs the sshpass and git packages installed.

Configuration is read from /etc/default/icinga2-git-pull-hook.ini,
~/.icinga2-git-pull-hook.ini and a icinga2-git-pull-hook.ini in the working
directory in that order.
"""

import logging
import logging.config
import os
import subprocess
from configparser import ConfigParser
from http import HTTPStatus
from http.server import HTTPServer, BaseHTTPRequestHandler

ENV_FOR_GIT = {"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}

TOKENS = []
GIT_DIRECTORY = ""
GIT_REPOSITORY = ""
GIT_BRANCH = ""

LOGGER = None


def read_ini():
    global ENV_FOR_GIT, TOKENS, GIT_DIRECTORY, GIT_REPOSITORY, GIT_BRANCH, LOGGER
    config = ConfigParser()
    config.read(
        [
            "/etc/default/icinga2-git-pull-hook.ini",
            os.path.expanduser("~/.icinga2-git-pull-hook.ini"),
            "icinga2-git-pull-hook.ini",
        ]
    )
    ENV_FOR_GIT["SSHPASS"] = config["icinga2-git-pull-hook"]["ssh_passphrase"]
    TOKENS = [
        token.strip() for token in config["icinga2-git-pull-hook"]["tokens"].split(",")
    ]
    GIT_DIRECTORY = config["icinga2-git-pull-hook"]["git_directory"]
    GIT_REPOSITORY = config["icinga2-git-pull-hook"]["git_repository"]
    GIT_BRANCH = config["icinga2-git-pull-hook"]["git_branch"]

    logging.config.dictConfig(
        {
            "version": 1,
            "formatters": {
                "full": {
                    "format": "%(asctime)s %(levelname)-8s %(message)s",
                    "datefmt": "%Y-%m-%d %H:%M:%S",
                }
            },
            "handlers": {
                "file": {
                    "class": "logging.FileHandler",
                    "filename": config.get("icinga2-git-pull-hook", "logfile"),
                    "formatter": "full",
                }
            },
            "loggers": {
                "icinga2-git-pull-hook": {"handlers": ["file"], "level": "INFO"}
            },
        }
    )
    LOGGER = logging.getLogger("icinga2-git-pull-hook")


class GitHookRequestHandler(BaseHTTPRequestHandler):
    """
    Custom HTTP request handler for updating a git repository when called
    with a known authentication token in an "Authentication" HTTP header.
    """

    def __init__(self, request, client_address, server):
        global LOGGER
        self.log = LOGGER
        super().__init__(request, client_address, server)

    def _send_data(self, message):
        self.send_header("Content-Type", "text/plain; charset=utf8")
        self.end_headers()
        self.wfile.write(("%s\r\n" % message).encode("UTF-8"))

    def _handle_pull(self):
        try:
            git_proc = subprocess.run(
                [
                    "sshpass",
                    "-e",
                    "-P",
                    "passphrase",
                    "git",
                    "subtree",
                    "pull",
                    "--prefix",
                    "icinga2/conf.d",
                    GIT_REPOSITORY,
                    GIT_BRANCH,
                ],
                env=ENV_FOR_GIT,
                cwd="/etc",
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                check=True,
                universal_newlines=True,
            )
            for line in git_proc.stdout.splitlines():
                self.log_message("git: %s", line)
        except subprocess.CalledProcessError as e:
            self.log_error(
                "Could not pull changes for %s: %s", GIT_DIRECTORY, e.returncode
            )
            for line in e.stdout.splitlines():
                self.log_message("git: %s", line)
            self.send_response(HTTPStatus.INTERNAL_SERVER_ERROR)
            self._send_data("Error updating the repository.")
            return
        self._send_data("updated %s" % GIT_DIRECTORY)
        try:
            icinga2_config_check_proc = subprocess.run(
                ["/usr/sbin/icinga2", "daemon", "-C"],
                cwd=GIT_DIRECTORY,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                check=True,
                universal_newlines=True,
            )
            for line in icinga2_config_check_proc.stdout.splitlines():
                self.log_message("icinga2: %s", line)
        except subprocess.CalledProcessError as e:
            self.log_error("configuration check failed: %d", e.returncode)
            for line in e.stdout.splitlines():
                self.log_message("icinga2: %s", line)
            self.send_response(HTTPStatus.INTERNAL_SERVER_ERROR)
            self._send_data("Error updating configuration.")
            return
        try:
            icinga2_reload_check_proc = subprocess.run(
                ["/bin/systemctl", "reload", "icinga2.service"],
                cwd=GIT_DIRECTORY,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                check=True,
                universal_newlines=True,
            )
            for line in icinga2_reload_check_proc.stdout.splitlines():
                self.log_message("systemctl: %s", line)
        except subprocess.CalledProcessError as e:
            self.log_error("reload failed: %s", e.returncode)
            for line in e.stdout.splitlines():
                self.log_message("systemctl: %s", line)
            self.send_response(HTTPStatus.INTERNAL_SERVER_ERROR)
            self._send_data("Error reloading icinga2.")
            return

        self.send_response(HTTPStatus.OK)
        self._send_data("Updated icinga2 configuration")
        return

    # noinspection PyPep8Naming
    def do_GET(self):
        """
        Handle GET requests, requests to /health are allowed for every caller.
        """
        if self.path == "/health":
            self.send_response(HTTPStatus.OK)
            self._send_data("I'm healthy!")
        else:
            self.send_error(
                HTTPStatus.NOT_FOUND, "You requested something I do not understand."
            )

    # noinspection PyPep8Naming
    def do_POST(self):
        """
        Handle POST requests requests to / need a valid token in the
        "Authentication" HTTP header and trigger a git pull in the configured
        directory.
        """
        if self.path == "/":
            if self.headers["Authentication"] in [token for token in TOKENS]:
                self._handle_pull()
            else:
                self.send_error(
                    HTTPStatus.UNAUTHORIZED,
                    'You have to send a valid token in the "Authentication" header.',
                )
        else:
            self.send_error(
                HTTPStatus.NOT_FOUND, "You requested something I do not understand."
            )

    def log_error(self, format, *args):
        self.log.error("%s - %s" % (self.address_string(), format), *args)

    def log_message(self, format, *args):
        self.log.info("%s - %s" % (self.address_string(), format), *args)


def run(server_class=HTTPServer, handler_class=GitHookRequestHandler):
    server_address = ("", 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()


if __name__ == "__main__":
    read_ini()
    run()