# Path: settings.py
# MASTERZONESERVERPORT = 1236
# 
# PROTOCOL = "http"
# 
# HOSTNAME = "localhost"
# 
# ZONESTARTUPTIME = 20
# 
# START_ZONE_WITH = SUBPROCESS
# 
# SUPERVISORD = 'supervisord' # Constant
# 
# SUBPROCESS = 'subprocess' # Constant
# 
# DOCKER = 'docker' # Constant
# 
# Path: baseserver.py
# class BaseServer(Application):
#     def __init__(self, extra_handlers):
#         '''Expects a list of tuple handlers like:
#                 [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
#         '''
#         url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
# 
#         app_settings = {
#                 "cookie_secret": settings.COOKIE_SECRET,
#                 "login_url": ''.join((url, "/login")),
#                 }
# 
#         handlers = []
#         handlers.append((r"/version", VersionHandler))
#         handlers.append((r"/source", SelfServe))
#         handlers.append((r"/ping", PingHandler))
#         handlers.append((r"/", PingHandler))
# 
#         handlers.extend(extra_handlers)
# 
#         options.parse_command_line()
#         dburi = options.dburi
# 
#         # Connect to the elixir db
#         setup(db_uri=dburi)
# 
#         Application.__init__(self, handlers, debug=True, **app_settings)
# 
#     def start(self):
#         IOLoop.current().start()
# 
# class SimpleHandler(BaseHandler):
#     def __init__(self, output, *args):
#         self.output = output
#         RequestHandler.__init__(self, *args)
# 
#     def get(self):
#         self.write(self.output)
# 
# class BaseHandler(RequestHandler):
#     def _handle_request_exception(self, e):
#         if client:
#             client.captureException()
#         RequestHandler._handle_request_exception(self, e)
# 
#     def get_login_url(self):
#         return u"/login"
# 
#     def get_current_user(self):
#         user_json = self.get_secure_cookie("user")
#         if user_json:
#             return user_json
#         else:
#             return None
# 
#     def HTTPError(self, code, message):
#         def write_error(status_code, **kwargs):
#             self.write(message)
#         self.write_error = write_error
#         self.send_error(code)
#         self.write_error = old_write_error
# 
# Path: elixir_models.py
# class Zone(BaseModel):
#     '''Zone stores connection information about the zoneservers.'''
# 
#     zoneid = CharField(unique=True)
#     port = IntegerField(unique=False)
#     url = CharField(unique=True, null=True)
# 
#     character = ForeignKeyField(Character, related_name='zones')
# 
# class Character(BaseModel):
#     '''Character contains the details for characters that users may control.'''
# 
#     name = CharField(unique=True)
# 
#     speed = FloatField(default=1)
# 
#     user = ForeignKeyField(User, related_name='characters')
#     # Also has 'zones'
# 
# 
#     def __repr__(self):
#         return '<Character "%s" owned by "%s">' % (self.name, self.user.username)


import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
                     START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
                from start_supervisord_process import start_zone
                from start_subprocess import start_zone, start_scriptserver
                from start_zone_docker import start_zone, start_scriptserver
    instance of the zone for that player.'''

    @tornado.web.authenticated
    def get(self, zoneid):
        self.cleanup()
        # Check that the authed user owns that zoneid in the database.
        try:
            self.write(self.get_url(zoneid))
        except UserWarning, exc:
            if "timed out." in exc:
                raise tornado.web.HTTPError(504, exc)

    def get_url(self, zoneid):
        '''Gets the zone URL from the database based on its id.
        ZoneServer ports start at 1300.'''
        logging.info("Launching zone %s" % zoneid)
        instance_type, name, owner = zoneid.split("-")
        return self.launch_zone(instance_type, name, owner)

    def launch_zone(self, instance_type, name, owner):
        '''Starts a zone given the type of instance, name and character that owns it.
        Returns the zone URL for the new zone server.'''
        # Make sure the instance type is allowed
        # Make sure the name exists
        # Make sure owner is real

        zoneid = '-'.join((instance_type, name, owner))

        # If it's in the database, it's probably still up:
        try:

# Path: settings.py
# MASTERZONESERVERPORT = 1236
# 
# PROTOCOL = "http"
# 
# HOSTNAME = "localhost"
# 
# ZONESTARTUPTIME = 20
# 
# START_ZONE_WITH = SUBPROCESS
# 
# SUPERVISORD = 'supervisord' # Constant
# 
# SUBPROCESS = 'subprocess' # Constant
# 
# DOCKER = 'docker' # Constant
# 
# Path: baseserver.py
# class BaseServer(Application):
#     def __init__(self, extra_handlers):
#         '''Expects a list of tuple handlers like:
#                 [(r"/", MainHandler), (r"/chatsocket", ChatSocketHandler),]
#         '''
#         url = settings._server_str % (settings.PROTOCOL, settings.HOSTNAME, settings.AUTHSERVERPORT)
# 
#         app_settings = {
#                 "cookie_secret": settings.COOKIE_SECRET,
#                 "login_url": ''.join((url, "/login")),
#                 }
# 
#         handlers = []
#         handlers.append((r"/version", VersionHandler))
#         handlers.append((r"/source", SelfServe))
#         handlers.append((r"/ping", PingHandler))
#         handlers.append((r"/", PingHandler))
# 
#         handlers.extend(extra_handlers)
# 
#         options.parse_command_line()
#         dburi = options.dburi
# 
#         # Connect to the elixir db
#         setup(db_uri=dburi)
# 
#         Application.__init__(self, handlers, debug=True, **app_settings)
# 
#     def start(self):
#         IOLoop.current().start()
# 
# class SimpleHandler(BaseHandler):
#     def __init__(self, output, *args):
#         self.output = output
#         RequestHandler.__init__(self, *args)
# 
#     def get(self):
#         self.write(self.output)
# 
# class BaseHandler(RequestHandler):
#     def _handle_request_exception(self, e):
#         if client:
#             client.captureException()
#         RequestHandler._handle_request_exception(self, e)
# 
#     def get_login_url(self):
#         return u"/login"
# 
#     def get_current_user(self):
#         user_json = self.get_secure_cookie("user")
#         if user_json:
#             return user_json
#         else:
#             return None
# 
#     def HTTPError(self, code, message):
#         def write_error(status_code, **kwargs):
#             self.write(message)
#         self.write_error = write_error
#         self.send_error(code)
#         self.write_error = old_write_error
# 
# Path: elixir_models.py
# class Zone(BaseModel):
#     '''Zone stores connection information about the zoneservers.'''
# 
#     zoneid = CharField(unique=True)
#     port = IntegerField(unique=False)
#     url = CharField(unique=True, null=True)
# 
#     character = ForeignKeyField(Character, related_name='zones')
# 
# class Character(BaseModel):
#     '''Character contains the details for characters that users may control.'''
# 
#     name = CharField(unique=True)
# 
#     speed = FloatField(default=1)
# 
#     user = ForeignKeyField(User, related_name='characters')
#     # Also has 'zones'
# 
# 
#     def __repr__(self):
#         return '<Character "%s" owned by "%s">' % (self.name, self.user.username)


# Path: masterzoneserver.py
import time
import logging
import tornado
import requests
from signal import SIGINT
from settings import MASTERZONESERVERPORT, PROTOCOL, HOSTNAME, ZONESTARTUPTIME,\
                     START_ZONE_WITH, SUPERVISORD, SUBPROCESS, DOCKER
from baseserver import BaseServer, SimpleHandler, BaseHandler
from elixir_models import Zone, Character
                from start_supervisord_process import start_zone
                from start_subprocess import start_zone, start_scriptserver
                from start_zone_docker import start_zone, start_scriptserver

    instance of the zone for that player.'''

    @tornado.web.authenticated
    def get(self, zoneid):
        self.cleanup()
        # Check that the authed user owns that zoneid in the database.
        try:
            self.write(self.get_url(zoneid))
        except UserWarning, exc:
            if "timed out." in exc:
                raise tornado.web.HTTPError(504, exc)

    def get_url(self, zoneid):
        '''Gets the zone URL from the database based on its id.
        ZoneServer ports start at 1300.'''
        logging.info("Launching zone %s" % zoneid)
        instance_type, name, owner = zoneid.split("-")
        return self.launch_zone(instance_type, name, owner)

    def launch_zone(self, instance_type, name, owner):
        '''Starts a zone given the type of instance, name and character that owns it.
        Returns the zone URL for the new zone server.'''
        # Make sure the instance type is allowed
        # Make sure the name exists
        # Make sure owner is real

        zoneid = '-'.join((instance_type, name, owner))

        # If it's in the database, it's probably still up:
        try:

            zone = Zone.get(zoneid=zoneid)