changeset 567:16344424dfcc

First attempt at irker logging from level server.
author Simon Cross <hodgestar@gmail.com>
date Tue, 20 Nov 2012 22:08:05 +0200
parents 9bf1d649f594
children 7eb5ecda4667
files mamba/forest.py
diffstat 1 files changed, 96 insertions(+), 15 deletions(-) [+]
line wrap: on
line diff
--- a/mamba/forest.py	Fri Dec 23 01:19:17 2011 +0200
+++ b/mamba/forest.py	Tue Nov 20 22:08:05 2012 +0200
@@ -4,14 +4,16 @@
 from flask import Flask, request, abort
 
 from datetime import datetime
+from ConfigParser import SafeConfigParser
 import xmlrpclib
 import time
 import os
 import sys
+import socket
+import json
 
 app = Flask(__name__)
-app.config['LEVEL_FOLDER'] = None  # set later
-app.config['CIA_PROJECT'] = None  # set to activate CIA sending
+app.config = None  # set later
 
 
 def path(ctype):
@@ -58,6 +60,7 @@
         with open(levelpath, 'w') as level:
             level.write(leveldata)
         inform_cia(levelname, "New level uploaded.", branch="uncurated")
+        inform_irker(levelname, "New level uploaded.", branch="uncurated")
         return "Ssss."
     else:
         abort(405, "Post levels here. Hsss.")
@@ -65,6 +68,7 @@
 
 MAMBA_VERSION = "0.1"
 MAMBA_URL = "https://ctpug.org.za/hg/mamba"
+IRKER_PORT = 6659
 CIA_URL = "http://cia.navi.cx"
 CIA_MSG_TEMPLATE = """
 <message
@@ -100,12 +104,12 @@
 
 
 def inform_cia(filename, log, branch='uncurated'):
-    if app.config['CIA_PROJECT'] is None:
+    if app.config.cia is None:
         return
     msg = CIA_MSG_TEMPLATE % {
         'mamba_version': MAMBA_VERSION,
         'mamba_url': MAMBA_URL,
-        'project': app.config['CIA_PROJECT'],
+        'project': app.config.cia.project,
         'module': 'level-server',
         'branch': branch,
         'timestamp': int(time.time()),
@@ -114,21 +118,100 @@
         'file': filename,
         'log': log,
         }
-    srv = xmlrpclib.Server(CIA_URL)
+    srv = xmlrpclib.Server(app.config.cia.url)
     srv.hub.deliver(msg)
 
 
+def format_irker_message(project, filename, log, branch='uncurated'):
+    return "%(project)s: %(branch)s * %(filename): %(log)s" % {
+        "project": project,
+        "filename": filename,
+        "log": log,
+        "branch": branch,
+    }
+
+
+def inform_irker(filename, log, branch='uncurated'):
+    if app.config.irker is None:
+        return
+    irker = app.config.irker
+    privmsg = format_irker_message(irker.project, filename, log, branch)
+    message = json.dumps({"to": irker.channels, "privmsg": privmsg})
+    try:
+        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        sock.connect(irker.host, irker.port)
+        sock.sendall(message + "\n")
+    finally:
+        sock.close()
+
+
+class ForestConfig(object):
+
+    class SubConfig(object):
+        """Holder for sub-config."""
+
+    def __init__(self, filenames):
+        self._config = SafeConfigParser()
+        self._config.read(filenames)
+        self.main = self._parse("main")
+        self.irker = self._parse("irker")
+
+    def _parse(self, section):
+        conf = dict(self._config.items(section))
+        return getattr(self, "_parse_%s" % section)(conf)
+
+    def _parse_main(self, conf):
+        main = self.SubConfig()
+        main.host = conf.get('host', '0.0.0.0')
+        main.port = int(conf['port'])
+        main.level_folder = conf['level_folder']
+
+    def _parse_irker(self, conf):
+        if 'project' not in conf:
+            return None
+        irker = self.SubConfig()
+        irker.project = conf['project']
+        irker.host = conf.get('host', 'localhost')
+        irker.port = conf.get('port', IRKER_PORT)
+        irker.channels = conf['channels']
+        return irker
+
+    def _parse_cia(self, conf, cia):
+        if 'project' not in conf:
+            return None
+        cia = self.SubConfig()
+        cia.project = conf['project']
+        cia.url = conf.get('url', CIA_URL)
+        return cia
+
+
+USAGE = """Usage: python -m mamba.forest <config file>
+
+The config file should look like:
+
+[main]
+host=0.0.0.0  # optional
+port=8000
+level_folder=./my/levels
+
+[irker]
+host=localhost  # optional
+port=8001
+project=mamba-levels
+channels=channel1,channel2
+"""
+
+
 if __name__ == "__main__":
-    if len(sys.argv) not in (3, 4):
-        print ("Usage: python -m mamba.forest <port> <level folder>"
-               " [<cia project>]")
+    if len(sys.argv) != 2:
+        print USAGE
         sys.exit(1)
 
-    host = '0.0.0.0'
-    port = int(sys.argv[1])
-    level_folder = sys.argv[2]
+    app.config = ForestConfig([sys.argv[1]])
+    main = app.config.main
+
     for ctype in ("curated", "uncurated"):
-        folder = os.path.join(level_folder, ctype)
+        folder = os.path.join(main.level_folder, ctype)
         if not os.path.exists(folder):
             os.makedirs(folder)
         if not os.path.isdir(folder):
@@ -136,7 +219,5 @@
             sys.exit(1)
     cia_project = sys.argv[3] if len(sys.argv) > 3 else None
 
-    app.config['LEVEL_FOLDER'] = level_folder
-    app.config['CIA_PROJECT'] = cia_project
     # app.debug = True
-    app.run(host=host, port=port)
+    app.run(host=main.host, port=main.port)