OSDN Git Service

Add validate
[karesansui/karesansui.git] / karesansui / app.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Karesansui.
5 #
6 # Copyright (C) 2009-2010 HDE, Inc.
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13
14 """
15 @author: Kei Funagayama <kei@karesansui-project.info>
16 """
17
18 import sys
19 import os
20 import traceback
21 from os import environ as env
22 import logging
23
24 from prep import fcgi, built_in, chkconfig, have_privilege
25
26 # Initialization
27 if __name__ == "__main__":
28     (config, opts, args) = built_in() # build-in server
29     
30 elif env.has_key('FCGI') is True:
31     (config, opts, args) = fcgi() # FastCGI server
32     
33 else:
34     pass
35
36 try:
37     import karesansui
38 except ImportError, e:
39     print >>sys.stderr, '[Error] There are not enough libraries. - %s' % ''.join(e.args)
40     traceback.format_exc()
41     sys.exit(1)
42     
43 if not karesansui.config:
44     print >>sys.stderr, '[Error] Failed to load configuration file.'
45     sys.exit(1)
46
47 if chkconfig(karesansui.config) is False:
48     sys.exit(1)
49
50 # Check privilege
51 if have_privilege() is not True:
52     from lib.const import KARESANSUI_GROUP
53     print >>sys.stderr, "[Error] Only users who belong to '%s' group are able to run this program." % KARESANSUI_GROUP
54     sys.exit(1)
55
56 # Import
57 import karesansui.lib.log.logger
58
59 try:
60     import web
61     import mako
62     import sqlalchemy
63     if env.has_key('FCGI') is True:
64         import flup
65     import simplejson
66     import libvirt
67     # pysilhouette module
68     import pysilhouette
69 except ImportError, e:
70     print >>sys.stderr, '[Error] There are not enough libraries. - %s' % ''.join(e.args)
71     traceback.format_exc()
72     sys.exit(1)
73
74 # pysilhouette config read.
75 from pysilhouette.prep import readconf
76 karesansui.sheconf = readconf(karesansui.config['pysilhouette.conf.path'])
77
78 if karesansui.sheconf is None:
79     print >>sys.stderr, '[Error] Failed to load configuration file. (PySilhouette)'
80     sys.exit(1)
81     
82 import pysilhouette.prep
83 if pysilhouette.prep.parse_conf(karesansui.sheconf) is False:
84     sys.exit(1)
85
86 # URL structure
87 import karesansui.urls
88 urls = karesansui.urls.urls
89
90
91 def main():
92     """<comment-ja>
93     Web Application 起動処理
94     </comment-ja>
95     <comment-en>
96     TODO: English Comment
97     </comment-en>
98     """
99     # logging load
100     karesansui.lib.log.logger.reload_conf(karesansui.config['application.log.config'])
101     if karesansui.lib.log.logger.is_ready() is False:
102         raise  karesansui.lib.log.logger.KaresansuiLogError("""Warning!!
103         Logging set initial startup failed.
104         example : Does the log configuration file exist?
105         The present file path : %s
106         """ % karesansui.config['application.log.config'])
107
108     logger = logging.getLogger('karesansui.app')
109     logger_trace = logging.getLogger('karesansui_trace.app')
110
111     if not os.popen("ps -eo cmd | grep ^/opt/hde/sbin/libvirtd").read():
112         logger.error('hde-libvirtd not running."/etc/init.d/hde-libvirtd start" Please start.')
113         print >>sys.stderr, '[Error] hde-libvirtd not running."/etc/init.d/hde-libvirtd start" Please start.'
114         sys.exit(1)
115     
116     if web.wsgi._is_dev_mode() is True and env.has_key('FCGI') is False:
117         logger.info('Start Mode [development]')
118         app = web.application(urls, globals(), autoreload=True)
119         app.internalerror = web.debugerror
120         sys.argv = [] # argv clear
121     else:
122         logger.info('Start Mode [fastcgi]')
123         web.config.debug = False
124         app = web.application(urls, globals(), autoreload=False)
125         sys.argv = [] # argv clear
126         
127     # load processor!
128     #  - karesansui database!
129     app.add_processor(load_sqlalchemy_karesansui)
130     logger.info('The load was added. - load_sqlalchemy_karesansui')
131     #  - pysilhouette database!
132     app.add_processor(load_sqlalchemy_pysilhouette)
133     logger.info('The load was added. - load_sqlalchemy_pysilhouette')
134
135     # http://domain/(../..)/hoge
136     if karesansui.config['application.url.prefix']:
137         mapping = (karesansui.config['application.url.prefix'],  app)
138         app = web.subdir_application(mapping)
139         
140     try:
141         if (not opts is None) and opts.shell is True: # shell mode!!
142             shell()
143         else:
144             app.run() # Web Application Start!
145     except Exception, e:
146         logger_trace.critical(traceback.format_exc())
147         print >>sys.stderr, "[ERROR] %s" % str(e.args)
148         print >>sys.stderr, traceback.format_exc()
149         return 1
150
151 # webpy - processor
152 def load_sqlalchemy_karesansui(handler):
153     """<comment-ja>
154     リクエストスコープ単位にKaresansuiデータベースのセッションを割り当てる。
155     </comment-ja>
156     <comment-en>
157     TODO: English Comment
158     </comment-en>
159     """
160     
161     import karesansui.db
162     web.ctx.orm = karesansui.db.get_session()
163     
164     logger = logging.getLogger("karesansui.processor.karesansui")
165
166     logger.debug('Karesansui database session scope [start] - %s' % web.ctx.orm)
167     try:
168         ret = handler()
169         web.ctx.orm.commit()
170         logger.debug('Karesansui database session scope [commit] - %s' % web.ctx.orm)
171         return ret 
172     except web.HTTPError:
173         if web.ctx.status[:1] in ['2', '3']:
174             web.ctx.orm.commit()
175             logger.debug('Karesansui database session scope [commit] : HTTP Status=%s - %s' % (web.ctx.status, web.ctx.orm))
176             raise
177         else:
178             web.ctx.orm.rollback()
179             logger.debug('Karesansui database session scope [rollback] : HTTP Status=%s - %s' % (web.ctx.orm, web.ctx.status))
180             raise
181     except:
182         web.ctx.orm.rollback()
183         logger.debug('Karesansui database session scope [rollback] - %s' % web.ctx.orm)
184         raise
185
186 def load_twophase_sqlalchemy(handler):
187     """<comment-ja>
188     KaresansuiとPysilhouetteデータベースの2フェーズセッションをWeb Applicationに割り当てる。
189     sqiteが2フェーズに対応していないのでVersion1.xでは未対応。
190     </comment-ja>
191     <comment-en>
192     TODO: English Comment
193     </comment-en>
194     """
195     #: <= 2.0
196     # sqlite not supported.
197     Session = sqlalchemy.orm.sessionmaker(twophase=True)
198     Session.configure(binds={karesansui.db.get_metadata():karesansui.db.get_engine(),
199                              karesansui.db._2pysilhouette.get_metadata():karesansui.db._2pysilhouette.get_engine(),
200                              })
201     session = Session()
202
203 def load_sqlalchemy_pysilhouette(handler):
204     """<comment-ja>
205     リクエストスコープ単位にPysilhouetteデータベースのセッションを割り当てる。
206     </comment-ja>
207     <comment-en>
208     TODO: English Comment
209     </comment-en>
210     """
211     
212     import karesansui.db._2pysilhouette
213     from web.utils import Storage
214     web.ctx.pysilhouette = Storage()
215     web.ctx.pysilhouette.orm = karesansui.db._2pysilhouette.get_session()
216     
217     logger = logging.getLogger("karesansui.processor.pysilhouette")
218     
219     try:
220         ret = handler()
221         web.ctx.pysilhouette.orm.commit()
222         logger.debug('Pysilhouette database session scope [commit] - %s' % web.ctx.orm)
223         return ret 
224     except web.HTTPError:
225         if web.ctx.status[:1] in ['2', '3']:
226             web.ctx.pysilhouette.orm.commit()
227             logger.debug('Pysilhouette database session scope [commit] : HTTP Status=%s - %s' % (web.ctx.status, web.ctx.orm))
228             raise
229         else:
230             web.ctx.pysilhouette.orm.rollback()
231             logger.debug('Pysilhouette database session scope [rollback] : HTTP Status=%s - %s' % (web.ctx.orm, web.ctx.status))
232             raise
233     except:
234         web.ctx.pysilhouette.orm.rollback()
235         logger.debug('Karesansui database session scope [commit] - %s' % web.ctx.orm)
236         raise
237
238
239 def shell():
240     """<comment-ja>
241     IPythonを利用したKaresansui コマンドライン
242     </comment-ja>
243     <comment-en>
244     TODO: English Comment
245     </comment-en>
246     """
247     
248     try:
249         from IPython.Shell import IPShellEmbed
250     except ImportError, e:
251         print >>sys.stderr, '[Error] Shell function requires IPython. - %s' % ''.join(e.args)
252         traceback.format_exc()
253         sys.exit(1)
254
255     # karesansui database
256     import karesansui.db
257     kss_engine = karesansui.db.get_engine()
258     kss_metadata = karesansui.db.get_metadata()
259     kss_session = karesansui.db.get_session()
260     # pysilhouette
261     import karesansui.db._2pysilhouette 
262     pyshe_engine = karesansui.db._2pysilhouette.get_engine()
263     pyshe_metadata = karesansui.db._2pysilhouette.get_metadata()
264     pyshe_session = karesansui.db._2pysilhouette.get_session()
265     
266     ipshell = IPShellEmbed()
267     return ipshell()
268
269 if __name__ == "__main__":
270     try:
271         sys.exit(main())
272     except Exception, e:
273         print >>sys.stderr, traceback.format_exc()
274         sys.exit(1)