<commit_before># 2014. 12. 9 by <NAME> <EMAIL>

__version__ = "0.28.7.26"

version_info = tuple (map (lambda x: not x.isdigit () and x or int (x),  __version__.split (".")))
NAME = "Skitai/%s.%s" % version_info [:2]

import threading
import sys, os
import h2
from rs4 import deco, importer
from rs4.psutil import service
from rs4.attrdict import AttrDict
from aquests.protocols import dns
from aquests.dbapi import DB_PGSQL, DB_POSTGRESQL, DB_SQLITE3, DB_REDIS, DB_MONGODB
from aquests.protocols.smtp import composer
import tempfile
import getopt
from . import lifetime
from . import mounted

if "---production" in sys.argv:
	os.environ ["SKITAI_ENV"] = "PRODUCTION"	

def test_client (*args, **kargs):
	from .testutil.launcher import Launcher
	return Launcher (*args, **kargs)

def websocket (varname, timeout = 60, onopen = None, onclose = None):
    from functools import wraps
    from skitai import was as the_was
    
    def decorator(f):
        @wraps(f)
        def wrapper (*args, **kwargs):            
            was = the_was._get ()            
            if not was.wshasevent ():
                return f (*args, **kwargs)
            if was.wsinit ():
                return was.wsconfig (1, timeout, [varname,])
            elif was.wsopened ():
            	return onopen and onopen () or ''
            elif was.wsclosed ():                    
                return onclose and onclose () or ''
        return wrapper
    return decorator

    	
HAS_ATILA = None

PROTO_HTTP = "http"
PROTO_HTTPS = "https"
PROTO_WS = "ws"
PROTO_WSS = "wss"
DJANGO = "django"

STA_REQFAIL = REQFAIL = -1
STA_UNSENT = UNSENT = 0
STA_TIMEOUT = TIMEOUT = 1
STA_NETERR = NETERR = 2
STA_NORMAL = NORMAL = 3

WEBSOCKET_SIMPLE = 1
WEBSOCKET_GROUPCHAT = 5

WS_SIMPLE = 1
WS_THREADSAFE = 6
WS_GROUPCHAT = 5
WS_NQ = 128

WS_EVT_INIT = "init"
WS_EVT_OPEN = "open"
WS_EVT_CLOSE = "close"
WS_EVT_NONE = None

WS_MSG_JSON = "json"
WS_MSG_XMLRPC = "xmlrpc"
WS_MSG_GRPC = "grpc"
WS_MSG_TEXT = "text"
WS_MSG_DEFAULT = "text"

WS_OPCODE_TEXT = 0x1
WS_OPCODE_BINARY = 0x2
WS_OPCODE_CLOSE = 0x8
WS_OPCODE_PING = 0x9
WS_OPCODE_PONG = 0xa

class _WASPool:
	def __init__ (self):
		self.__wasc = None
		self.__p = {}
		
	def __get_id (self):
		return id (threading.currentThread ())
	
	def __repr__ (self):
		return "<class skitai.WASPool at %x>" % id (self)
			
	def __getattr__ (self, attr):
		_was = self._get ()
		if not _was.in__dict__ ("app") and hasattr (_was, 'request'):
			# it will be called WSGI middlewares except Atila,
			# So request object not need
			del _was.request			
		return  getattr (_was, attr)
			
	def __setattr__ (self, attr, value):
		if attr.startswith ("_WASPool__"):
			self.__dict__[attr] = value
		else:	
			setattr (self.__wasc, attr, value)
			for _id in self.__p:
				setattr (self.__p [_id], attr, value)
	
	def __delattr__ (self, attr):
		delattr (self.__wasc, attr)
		for _id in self.__p:
			delattr (self.__p [_id], attr, value)
	
	def _start (self, wasc):
		self.__wasc = wasc
	
	def _del (self):
		_id = self.__get_id ()
		try:
			del self.__p [_id]
		except KeyError:
			pass

	def _get (self):
		_id = self.__get_id ()
		try:
			return self.__p [_id]
		except KeyError:
			_was = self.__wasc ()
			self.__p [_id] = _was
			return _was


was = _WASPool ()
def start_was (wasc):
	global was
	
	detect_atila ()
	was._start (wasc)

def detect_atila ():
	# for avoid recursive importing
	try:
		import atila
	except ImportError:
		pass
	else:
		global HAS_ATILA
		HAS_ATILA = atila.Atila
			

#------------------------------------------------
# Configure
#------------------------------------------------
dconf = {'mount': {"default": []}, 'clusters': {}, 'max_ages': {}, 'log_off': [], 'dns_protocol': 'tcp'}

def pref (preset = False):
	from .wsgi_apps import Config
	
	class Pref (AttrDict):
		def __init__ (self):
			super (Pref, self).__init__ (self)
			self.__dict__ ["mountables"] = [] 
			
		def mount (self, *args, **kargs):
			self.__dict__ ["mountables"].append ((args, kargs))
	
	d = Pref ()
	d.config = Config (preset)
	return d

PROCESS_NAME = None
def get_proc_title ():	
	global PROCESS_NAME
	
	if PROCESS_NAME is None:
		a, b = os.path.split (os.path.join (os.getcwd (), sys.argv [0]))
		script = b.split(".")[0]
				
		PROCESS_NAME =  "skitai/%s%s" % (
			os.path.basename (a),
			script != "app" and "-" + script or ''
		)
	return PROCESS_NAME	
	
def getswd ():
	return os.path.dirname (os.path.join (os.getcwd (), sys.argv [0]))

def is_devel ():
	return os.environ.get ('SKITAI_ENV') != "PRODUCTION"

def joinpath (*pathes):
	return os.path.normpath (os.path.join (getswd (), *pathes))
abspath = joinpath

Win32Service = None
def set_service (service_class):
	global Win32Service	
	Win32Service = service_class

def manual_gc (interval = 60.0):
	lifetime.manual_gc (interval)	
	
def set_worker_critical_point (cpu_percent = 90.0, continuous = 3, interval = 20):
	from .http_server import http_server
	from .https_server import https_server	
	
	http_server.critical_point_cpu_overload = https_server.critical_point_cpu_overload = cpu_percent
	http_server.critical_point_continuous = https_server.critical_point_continuous = continuous
	http_server.maintern_interval = https_server.maintern_interval = interval
	
def log_off (*path):		
	global dconf
	for each in path:
		dconf ['log_off'].append (each)	

def set_dns_protocol (protocol = 'tcp'):		
	global dconf
	dconf ['dns_protocol'] = protocol
	<commit_msg>fix getswd ()<commit_after># 2014. 12. 9 by <NAME> <EMAIL>

__version__ = "0.28.7.27"

version_info = tuple (map (lambda x: not x.isdigit () and x or int (x),  __version__.split (".")))
NAME = "Skitai/%s.%s" % version_info [:2]

import threading
import sys, os
import h2
from rs4 import deco, importer
from rs4.psutil import service
from rs4.attrdict import AttrDict
from aquests.protocols import dns
from aquests.dbapi import DB_PGSQL, DB_POSTGRESQL, DB_SQLITE3, DB_REDIS, DB_MONGODB
from aquests.protocols.smtp import composer
import tempfile
import getopt
from . import lifetime
from . import mounted

if "---production" in sys.argv:
	os.environ ["SKITAI_ENV"] = "PRODUCTION"	

def test_client (*args, **kargs):
	from .testutil.launcher import Launcher
	return Launcher (*args, **kargs)

def websocket (varname, timeout = 60, onopen = None, onclose = None):
    from functools import wraps
    from skitai import was as the_was
    
    def decorator(f):
        @wraps(f)
        def wrapper (*args, **kwargs):            
            was = the_was._get ()            
            if not was.wshasevent ():
                return f (*args, **kwargs)
            if was.wsinit ():
                return was.wsconfig (1, timeout, [varname,])
            elif was.wsopened ():
            	return onopen and onopen () or ''
            elif was.wsclosed ():                    
                return onclose and onclose () or ''
        return wrapper
    return decorator

    	
HAS_ATILA = None

PROTO_HTTP = "http"
PROTO_HTTPS = "https"
PROTO_WS = "ws"
PROTO_WSS = "wss"
DJANGO = "django"

STA_REQFAIL = REQFAIL = -1
STA_UNSENT = UNSENT = 0
STA_TIMEOUT = TIMEOUT = 1
STA_NETERR = NETERR = 2
STA_NORMAL = NORMAL = 3

WEBSOCKET_SIMPLE = 1
WEBSOCKET_GROUPCHAT = 5

WS_SIMPLE = 1
WS_THREADSAFE = 6
WS_GROUPCHAT = 5
WS_NQ = 128

WS_EVT_INIT = "init"
WS_EVT_OPEN = "open"
WS_EVT_CLOSE = "close"
WS_EVT_NONE = None

WS_MSG_JSON = "json"
WS_MSG_XMLRPC = "xmlrpc"
WS_MSG_GRPC = "grpc"
WS_MSG_TEXT = "text"
WS_MSG_DEFAULT = "text"

WS_OPCODE_TEXT = 0x1
WS_OPCODE_BINARY = 0x2
WS_OPCODE_CLOSE = 0x8
WS_OPCODE_PING = 0x9
WS_OPCODE_PONG = 0xa

class _WASPool:
	def __init__ (self):
		self.__wasc = None
		self.__p = {}
		
	def __get_id (self):
		return id (threading.currentThread ())
	
	def __repr__ (self):
		return "<class skitai.WASPool at %x>" % id (self)
			
	def __getattr__ (self, attr):
		_was = self._get ()
		if not _was.in__dict__ ("app") and hasattr (_was, 'request'):
			# it will be called WSGI middlewares except Atila,
			# So request object not need
			del _was.request			
		return  getattr (_was, attr)
			
	def __setattr__ (self, attr, value):
		if attr.startswith ("_WASPool__"):
			self.__dict__[attr] = value
		else:	
			setattr (self.__wasc, attr, value)
			for _id in self.__p:
				setattr (self.__p [_id], attr, value)
	
	def __delattr__ (self, attr):
		delattr (self.__wasc, attr)
		for _id in self.__p:
			delattr (self.__p [_id], attr, value)
	
	def _start (self, wasc):
		self.__wasc = wasc
	
	def _del (self):
		_id = self.__get_id ()
		try:
			del self.__p [_id]
		except KeyError:
			pass

	def _get (self):
		_id = self.__get_id ()
		try:
			return self.__p [_id]
		except KeyError:
			_was = self.__wasc ()
			self.__p [_id] = _was
			return _was


was = _WASPool ()
def start_was (wasc):
	global was
	
	detect_atila ()
	was._start (wasc)

def detect_atila ():
	# for avoid recursive importing
	try:
		import atila
	except ImportError:
		pass
	else:
		global HAS_ATILA
		HAS_ATILA = atila.Atila
			

#------------------------------------------------
# Configure
#------------------------------------------------
dconf = {'mount': {"default": []}, 'clusters': {}, 'max_ages': {}, 'log_off': [], 'dns_protocol': 'tcp'}

def pref (preset = False):
	from .wsgi_apps import Config
	
	class Pref (AttrDict):
		def __init__ (self):
			super (Pref, self).__init__ (self)
			self.__dict__ ["mountables"] = [] 
			
		def mount (self, *args, **kargs):
			self.__dict__ ["mountables"].append ((args, kargs))
	
	d = Pref ()
	d.config = Config (preset)
	return d

PROCESS_NAME = None
def get_proc_title ():	
	global PROCESS_NAME
	
	if PROCESS_NAME is None:
		a, b = os.path.split (os.path.join (os.getcwd (), sys.argv [0]))
		script = b.split(".")[0]
				
		PROCESS_NAME =  "skitai/%s%s" % (
			os.path.basename (a),
			script != "app" and "-" + script or ''
		)
	return PROCESS_NAME	

SWD = None	
def getswd ():
	global SWD
	if SWD is None:
		SWD = os.path.dirname (os.path.join (os.getcwd (), sys.argv [0]))
	return SWD

def is_devel ():
	return os.environ.get ('SKITAI_ENV') != "PRODUCTION"

def joinpath (*pathes):	
	return os.path.normpath (os.path.join (getswd (), *pathes))
abspath = joinpath

Win32Service = None
def set_service (service_class):
	global Win32Service	
	Win32Service = service_class

def manual_gc (interval = 60.0):
	lifetime.manual_gc (interval)	
	
def set_worker_critical_point (cpu_percent = 90.0, continuous = 3, interval = 20):
	from .http_server import http_server
	from .https_server import https_server	
	
	http_server.critical_point_cpu_overload = https_server.critical_point_cpu_overload = cpu_percent
	http_server.critical_point_continuous = https_server.critical_point_continuous = continuous
	http_server.maintern_interval = https_server.maintern_interval = interval
	
def log_off (*path):		
	global dconf
	for each in path:
		dconf ['log_off'].append (each)	

def set_dns_protocol (protocol = 'tcp'):		
	global dconf
	dconf ['dns_protocol'] = protocol
	
{'fraction_non_alphanumeric': 0.1329743542940586, 'fraction_numerical': 0.011316966322898603, 'mean_word_length': 3.0888059701492536, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '612668', 'n_tokens_mistral': 4362, 'n_tokens_neox': 3990, 'n_words': 1088}