__init__.py 4.27 KB
Newer Older
1 2
# -*- coding: utf-8 -*-
# vim: set et sts=2:
Marco Mariani's avatar
Marco Mariani committed
3
# pylint: disable-msg=W0311,C0301,C0103,C0111,R0904,R0903
4

Łukasz Nowak's avatar
Łukasz Nowak committed
5
import ConfigParser
Marco Mariani's avatar
Marco Mariani committed
6
import datetime
Łukasz Nowak's avatar
Łukasz Nowak committed
7 8 9
import logging
import logging.handlers
import os
10
from slapos.htpasswd import HtpasswdFile
11
from slapos.runner.process import setHandler
Łukasz Nowak's avatar
Łukasz Nowak committed
12
import sys
13
from slapos.runner.utils import runInstanceWithLock
14
from slapos.runner.views import *
Marco Mariani's avatar
Marco Mariani committed
15

16
TRUE_VALUES = (1, '1', True, 'true', 'True')
Łukasz Nowak's avatar
Łukasz Nowak committed
17 18

class Config:
Marco Mariani's avatar
Marco Mariani committed
19 20 21 22 23 24 25
  def __init__(self):
    self.configuration_file_path = None
    self.console = None
    self.log_file = None
    self.logger = None
    self.verbose = None

26
  def setConfig(self):
Łukasz Nowak's avatar
Łukasz Nowak committed
27 28 29
    """
    Set options given by parameters.
    """
30
    self.configuration_file_path = os.path.abspath(os.getenv('RUNNER_CONFIG'))
Łukasz Nowak's avatar
Łukasz Nowak committed
31 32 33

    # Load configuration file
    configuration_parser = ConfigParser.SafeConfigParser()
34
    configuration_parser.read(self.configuration_file_path)
35 36

    for section in ("slaprunner", "slapos", "slapproxy", "slapformat",
37
                    "sshkeys_authority", "gitclient"):
Łukasz Nowak's avatar
Łukasz Nowak committed
38 39 40 41 42 43 44 45 46 47 48
      configuration_dict = dict(configuration_parser.items(section))
      for key in configuration_dict:
        if not getattr(self, key, None):
          setattr(self, key, configuration_dict[key])

    # set up logging
    self.logger = logging.getLogger("slaprunner")
    self.logger.setLevel(logging.INFO)
    if self.console:
      self.logger.addHandler(logging.StreamHandler())

49 50 51 52 53 54 55 56 57 58 59
    self.log_file = self.log_dir + '/slaprunner.log'
    if not os.path.isdir(os.path.dirname(self.log_file)):
    # fallback to console only if directory for logs does not exists and
    # continue to run
      raise ValueError('Please create directory %r to store %r log file' % (
      os.path.dirname(self.log_file), self.log_file))
    else:
      file_handler = logging.FileHandler(self.log_file)
      file_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
      self.logger.addHandler(file_handler)
      self.logger.info('Configured logging to file %r' % self.log_file)
Łukasz Nowak's avatar
Łukasz Nowak committed
60 61

    self.logger.info("Started.")
62
    self.logger.info(os.environ['PATH'])
Łukasz Nowak's avatar
Łukasz Nowak committed
63 64 65 66 67
    if self.verbose:
      self.logger.setLevel(logging.DEBUG)
      self.logger.debug("Verbose mode enabled.")


68 69 70 71 72 73 74 75 76 77 78 79 80
def checkHtpasswd(config):
  """XXX:set for backward compatiblity
  create a htpassword if etc/.users exist"""
  user = os.path.join(config['etc_dir'], '.users')
  htpasswdfile = os.path.join(config['etc_dir'], '.htpasswd')
  if os.path.exists(user) and not os.path.exists(htpasswdfile):
    data = open(user).read().strip().split(';')
    htpasswd = HtpasswdFile(htpasswdfile, create=True)
    htpasswd.update(data[0], data[1])
    htpasswd.save()
  else:
    return

81 82 83 84 85 86 87 88 89 90 91 92 93
def checkJSONConfig(config):
  """create a default json file with some parameters inside
  if the file has never been created"""
  json_file = os.path.join(config['etc_dir'], 'config.json')
  if not os.path.exists(json_file):
    params = {
      'run_instance' : True,
      'run_software' : True,
      'max_run_instance' : 3,
      'max_run_software' : 2
    }
    open(json_file, "w").write(json.dumps(params))
    
94

Łukasz Nowak's avatar
Łukasz Nowak committed
95 96
def run():
  "Run default configuration."
97 98 99 100 101 102 103 104 105
  # Parse arguments
  config = Config()
  config.setConfig()

  if os.getuid() == 0:
    # avoid mistakes (mainly in development mode)
    raise Exception('Do not run SlapRunner as root.')

  serve(config)
Marco Mariani's avatar
Marco Mariani committed
106

Łukasz Nowak's avatar
Łukasz Nowak committed
107
def serve(config):
108
  from werkzeug.contrib.fixers import ProxyFix
109
  workdir = os.path.join(config.runner_workdir, 'project')
110
  software_link = os.path.join(config.runner_workdir, 'softwareLink')
Łukasz Nowak's avatar
Łukasz Nowak committed
111 112 113 114
  app.config.update(**config.__dict__)
  app.config.update(
    software_log=config.software_root.rstrip('/') + '.log',
    instance_log=config.instance_root.rstrip('/') + '.log',
Marco Mariani's avatar
Marco Mariani committed
115
    workspace=workdir,
116
    software_link=software_link,
117 118
    instance_profile='instance.cfg',
    software_profile='software.cfg',
119
    SECRET_KEY=os.urandom(24),
Marco Mariani's avatar
Marco Mariani committed
120
    PERMANENT_SESSION_LIFETIME=datetime.timedelta(days=31),
Łukasz Nowak's avatar
Łukasz Nowak committed
121
  )
122
  checkHtpasswd(app.config)
123
  checkJSONConfig(app.config)
124 125
  if not os.path.exists(workdir):
    os.mkdir(workdir)
126 127
  if not os.path.exists(software_link):
    os.mkdir(software_link)
128
  setHandler()
129
  config.logger.info('Running slapgrid...')
130 131
  if app.config['auto_deploy_instance'] in TRUE_VALUES:
    runInstanceWithLock(app.config)
132
  config.logger.info('Done.')
133
  app.wsgi_app = ProxyFix(app.wsgi_app)
134 135

run()