<commit_before>#!/usr/bin/env python

import daemon
import fcntl
import getopt
import logging
import os
import sys
import traceback

from ConfigParser import ConfigParser
from flask import Flask, jsonify
from adventures import adventures
from clusters import clusters
from nodes import nodes
from index import index
from tasks import tasks

from db import api, models, database

import backends


# Stolen: http://code.activestate.com/recipes/\
#         577911-context-manager-for-a-daemon-pid-file/
class PidFile(object):
    def __init__(self, path):
        self.path = path
        self.pidfile = None

    def __enter__(self):
        self.pidfile = open(self.path, 'a+')
        try:
            fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            raise SystemExit('Pid file in use')

        self.pidfile.seek(0)
        self.pidfile.truncate()
        self.pidfile.write(str(os.getpid()))
        self.pidfile.flush()
        self.pidfile.seek(0)
        return self.pidfile

    def __exit__(self, exc_type=None, exc_value=None, exc_tb=None):
        try:
            self.pidfile.close()
        except IOError as err:
            if err.errno != 9:
                raise
        os.remove(self.path)


class Thing(Flask):
    def __init__(self, name, argv=None, configfile=None,
                 confighash=None, debug=False):
        daemonize = False
        self.registered_models = []

        super(Thing, self).__init__(name)

        if argv:
            try:
                opts, args = getopt.getopt(argv, 'c:vd')
            except getopt.GetoptError as err:
                print str(err)
                sys.exit(1)

            for o, a in opts:
                if o == '-c':
                    configfile = a
                elif o == '-v':
                    debug = True
                elif o == '-d':
                    daemonize = True
                else:
                    print "Bad option"
                    sys.exit(1)

            sys.argv = [sys.argv[0]] + args

        defaults = {'main':
                    {'bind_address': '0.0.0.0',
                     'bind_port': 8080,
                     'backend': './backends',
                     'loglevel': 'WARNING',
                     'database_uri': 'sqlite:///',
                     'daemonize': False,
                     'pidfile': None},
                    'ChefClientBackend':
                    {'role_location': '/etc/roush/roles.d'},
                    'ChefServerBackend': {},
                    'UnprovisionedBackend': {}}

        if configfile:
            config = ConfigParser()
            config.read(configfile)

            configfile_hash = dict(
                [(s, dict(config.items(s))) for s in config.sections()])

            for section in configfile_hash:
                if section in defaults:
                    defaults[section].update(configfile_hash[section])
                else:
                    defaults[section] = configfile_hash[section]

        if confighash:
            defaults.update(confighash)

        logging.basicConfig(level=logging.WARNING)
        LOG = logging.getLogger()

        if debug:<commit_msg>default backends to /dev/null if not specified<commit_after>#!/usr/bin/env python

import daemon
import fcntl
import getopt
import logging
import os
import sys
import traceback

from ConfigParser import ConfigParser
from flask import Flask, jsonify
from adventures import adventures
from clusters import clusters
from nodes import nodes
from index import index
from tasks import tasks

from db import api, models, database

import backends


# Stolen: http://code.activestate.com/recipes/\
#         577911-context-manager-for-a-daemon-pid-file/
class PidFile(object):
    def __init__(self, path):
        self.path = path
        self.pidfile = None

    def __enter__(self):
        self.pidfile = open(self.path, 'a+')
        try:
            fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            raise SystemExit('Pid file in use')

        self.pidfile.seek(0)
        self.pidfile.truncate()
        self.pidfile.write(str(os.getpid()))
        self.pidfile.flush()
        self.pidfile.seek(0)
        return self.pidfile

    def __exit__(self, exc_type=None, exc_value=None, exc_tb=None):
        try:
            self.pidfile.close()
        except IOError as err:
            if err.errno != 9:
                raise
        os.remove(self.path)


class Thing(Flask):
    def __init__(self, name, argv=None, configfile=None,
                 confighash=None, debug=False):
        daemonize = False
        self.registered_models = []

        super(Thing, self).__init__(name)

        if argv:
            try:
                opts, args = getopt.getopt(argv, 'c:vd')
            except getopt.GetoptError as err:
                print str(err)
                sys.exit(1)

            for o, a in opts:
                if o == '-c':
                    configfile = a
                elif o == '-v':
                    debug = True
                elif o == '-d':
                    daemonize = True
                else:
                    print "Bad option"
                    sys.exit(1)

            sys.argv = [sys.argv[0]] + args

        defaults = {'main':
                    {'bind_address': '0.0.0.0',
                     'bind_port': 8080,
                     'backend': '/dev/null',
                     'loglevel': 'WARNING',
                     'database_uri': 'sqlite:///',
                     'daemonize': False,
                     'pidfile': None},
                    'ChefClientBackend':
                    {'role_location': '/etc/roush/roles.d'},
                    'ChefServerBackend': {},
                    'UnprovisionedBackend': {}}

        if configfile:
            config = ConfigParser()
            config.read(configfile)

            configfile_hash = dict(
                [(s, dict(config.items(s))) for s in config.sections()])

            for section in configfile_hash:
                if section in defaults:
                    defaults[section].update(configfile_hash[section])
                else:
                    defaults[section] = configfile_hash[section]

        if confighash:
            defaults.update(confighash)

        logging.basicConfig(level=logging.WARNING)
        LOG = logging.getLogger()

        if debug:
{'fraction_non_alphanumeric': 0.10256410256410256, 'fraction_numerical': 0.006178560395427865, 'mean_word_length': 1.5462052693668895, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5587657', 'n_tokens_mistral': 1862, 'n_tokens_neox': 1757, 'n_words': 433}