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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#!/usr/bin/env python3
from configparser import ConfigParser
from sys import stderr, exit, argv
from zlib import compress

from aiohttp import web

from psycopg2cffi.pool import SimpleConnectionPool

from concurrent.futures import ThreadPoolExecutor

import asyncio
import base64
import json


class NoSuchRepository(Exception):
    def __init__(self, repo):
        self.repo = repo


if len(argv) < 2:
    print("Usage: gitsrv.py <config>", file=stderr)
    exit(1)

cfg = ConfigParser()
cfg.read(argv[1])

executor = ThreadPoolExecutor(max_workers=cfg.getint(
    'workers',
    'threads',
    fallback=10
))

memcached = None  # type: pylibmc.Client

if cfg.getboolean('memcached', 'enabled', fallback=False):
    import pylibmc

    servers = str(cfg.get('memcached', 'servers', fallback='127.0.0.1:11211'))

    memcached = pylibmc.Client(
        servers.split(' '),
        username=cfg.get('memcached', 'username', fallback=None),
        password=cfg.get('memcached', 'password', fallback=None),
        binary=True
    )

if not cfg.has_section('postgres'):
    print("ERROR: PostgreSQL configuration section missing.", file=stderr)
    exit(1)

db_conn_info = ''
for item in cfg.items('postgres'):
    db_conn_info += " {}='{}'".format(item[0], item[1])
db_conn_info = db_conn_info.lstrip()

object_count = 0
cache_hit_count = 0


def map_repo_to_db(name: str):
    mapped = cfg.get('databases', name, fallback=None)
    if mapped is None:
        raise NoSuchRepository(name)
    return mapped


pools = {}  # type: dict[str, SimpleConnectionPool]


def grab_connection(repo_name):
    if repo_name is None:
        raise NoSuchRepository(None)

    db_name = map_repo_to_db(repo_name)
    if db_name not in pools:
        conn_info = db_conn_info + (" dbname='{0}'".format(db_name))
        pools[db_name] = SimpleConnectionPool(
            1,
            cfg.getint(
                'workers',
                'sql',
                fallback=10
            ),
            conn_info
        )
    pool = pools[db_name]
    return pool, pool.getconn()


def put_connection(pool, conn):
    pool.putconn(conn)


def fetch_object(repo_name, object_hash):
    binary = None
    cursor = None
    pool = None
    conn = None

    try:
        pool, conn = grab_connection(repo_name)
        cursor = conn.cursor()
        cursor.execute("SELECT content FROM objects WHERE hash = %s", (object_hash,))
        binary = cursor.fetchone()[0]

    finally:
        cursor.close()
        put_connection(pool, conn)

        return binary


async def fetch_shallow_pack(repo_name, commit_hash, request, resp):
    resp.enable_chunked_encoding()

    cursor = None
    pool = None
    conn = None
    binary = None
    try:
        pool, conn = grab_connection(repo_name)
        cursor = conn.cursor()
        q = cursor.mogrify(
            "WITH objects AS (SELECT hash FROM git_shallow_crawl(%s))" +
            " SELECT part FROM git_create_pack((SELECT array_agg(hash) FROM objects))",
            (commit_hash,))
        cursor.execute(q)
        cursor.itersize = 10
        for row in cursor:
            if binary is None:
                await resp.prepare(request)
            binary = row[0]
            resp.write(binary.tobytes())
        resp.write_eof()
    except Exception:
        if binary is not None:
            await resp.write_eof()
        else:
            await resp.prepare(status=417)
            await resp.write_eof()
    finally:
        cursor.close()
        put_connection(pool, conn)


def fetch_commit_info(repo_name, commit_hash):
    pool = None
    conn = None
    cursor = None

    out = None
    try:
        pool, conn = grab_connection(repo_name)
        cursor = conn.cursor()
        q = cursor.mogrify("SELECT * FROM git_lookup_commit(%s)", (commit_hash,))
        cursor.execute(q)
        for row in cursor:
            out = row
    finally:
        cursor.close()
        put_connection(pool, conn)
    return out


def fetch_tree_info(repo_name, tree_hash):
    pool = None
    conn = None
    cursor = None

    out = None
    try:
        pool, conn = grab_connection(repo_name)
        cursor = conn.cursor()
        q = cursor.mogrify("SELECT * FROM git_lookup_tree(%s)", (tree_hash,))
        cursor.execute(q)
        out = cursor.fetchall()
    finally:
        cursor.close()
        put_connection(pool, conn)
    return out


def fetch_blob(repo_name, blob_hash):
    pool = None
    conn = None
    cursor = None

    out = None
    try:
        pool, conn = grab_connection(repo_name)
        cursor = conn.cursor()
        q = cursor.mogrify("SELECT content FROM contents WHERE hash = %s", (blob_hash,))
        cursor.execute(q)
        for item in cursor:
            out = item[0].tobytes()
    finally:
        cursor.close()
        put_connection(pool, conn)
    return out


async def handle_object_route(request):
    prefix = request.match_info['hash_prefix']
    suffix = request.match_info['hash_suffix']
    object_hash = prefix + suffix

    binary = None

    if memcached:
        cache_key = 'git.object[%s]' % object_hash
        cached_b64 = memcached.get(cache_key, None)
        if cached_b64 is not None:
            global cache_hit_count
            binary = base64.b64decode(cached_b64)
            cache_hit_count += 1

    if binary is None:
        binary = await asyncio.get_event_loop().run_in_executor(
            executor,
            fetch_object,
            request.match_info['repo'],
            object_hash
        )

        if memcached and len(binary) < 1024 * 1024:
            try:
                cache_key = 'git.object[%s]' % object_hash
                b64 = base64.b64encode(binary)
                memcached.set(cache_key, b64)
            except pylibmc.TooBig:
                pass

    if binary is None:
        print("[WARN] Tried to fetch object %s, but it does not exist." % object_hash)
        return web.Response(text='Object not found.', status=404)

    if type(binary) is bytearray or type(binary) is memoryview:
        binary = binary.tobytes()

    global object_count
    object_count += 1
    return web.Response(body=compress(binary))


async def handle_dlpack_route(request):
    resp = web.StreamResponse(status=200)
    f = await asyncio.get_event_loop().run_in_executor(
        executor,
        fetch_shallow_pack,
        request.match_info['repo'],
        request.match_info['commit'],
        request,
        resp
    )
    await f
    return resp


async def handle_commit_info_route(request):
    info = await asyncio.get_event_loop().run_in_executor(
        executor,
        fetch_commit_info,
        request.match_info['repo'],
        request.match_info['commit']
    )

    if info is None:
        return web.Response(status=404, text=json.dumps({
            "error": "not found"
        }))

    out = {
        'hash': info[0],
        'tree': info[1],
        'parent': info[2],
        'author': info[3],
        'committer': info[4],
        'author_time': str(info[5]),
        'commit_time': str(info[6]),
        'message': info[7],
        'pgp': info[8]
    }

    return web.Response(text=json.dumps(out, indent=2))


async def handle_tree_info_route(request):
    info = await asyncio.get_event_loop().run_in_executor(
        executor,
        fetch_tree_info,
        request.match_info['repo'],
        request.match_info['tree']
    )

    if info is None:
        return web.Response(status=404, text=json.dumps({
            "error": "not found"
        }))

    out = []

    for item in info:
        out.append({
            'parent': item[0],
            'mode': item[1],
            'name': item[2],
            'leaf': item[3]
        })

    return web.Response(text=json.dumps(out, indent=2))


async def handle_blob_route(request):
    data = await asyncio.get_event_loop().run_in_executor(
        executor,
        fetch_blob,
        request.match_info['repo'],
        request.match_info['blob']
    )

    if data is None:
        return web.Response(status=404, text=json.dumps({
            "error": "not found"
        }))

    return web.Response(body=data)


def handle_info_route(request):
    return web.Response(text='Not found.', status=404)


def handle_refs_route(request):
    pool, conn = grab_connection(request.match_info['repo'])
    cursor = conn.cursor()

    try:
        cursor.execute('SELECT name FROM refs')
        rows = cursor.fetchall()
        result = ""
        for row in rows:
            ref = row[0]
            cursor.execute("SELECT git_resolve_ref(%s)", (ref,))
            real = cursor.fetchone()[0]
            result += '{0}\t{1}\n'.format(real, ref)

        return web.Response(text=result)
    finally:
        cursor.close()
        put_connection(pool, conn)


app = web.Application()

app.router.add_get(
    '/{repo}/objects/info/{info_type}',
    handle_info_route
)

app.router.add_get(
    '/{repo}/dlpack/{commit}',
    handle_dlpack_route
)

app.router.add_get(
    '/{repo}/objects/{hash_prefix}/{hash_suffix}',
    handle_object_route
)

app.router.add_get(
    '/{repo}/info/refs',
    handle_refs_route
)

app.router.add_get(
    '/{repo}/commits/{commit}',
    handle_commit_info_route
)

app.router.add_get(
    '/{repo}/blobs/{blob}',
    handle_blob_route
)

app.router.add_get(
    '/{repo}/trees/{tree}',
    handle_tree_info_route
)


def object_count_info():
    global object_count
    global cache_hit_count

    if object_count > 0:
        print("[Statistics] %i objects were fetched" % object_count)
        object_count = 0

    if cache_hit_count > 0:
        print("[Statistics] %i objects hit the cache" % cache_hit_count)
        cache_hit_count = 0

    app.loop.call_later(1, object_count_info)


asyncio.get_event_loop().call_later(1, object_count_info)

web.run_app(
    app,
    host=cfg.get('bind', 'host', fallback='0.0.0.0'),
    port=cfg.getint('bind', 'port', fallback=8080)
)