Mercurial > libervia-web
comparison src/twisted/plugins/libervia_server.py @ 1113:cdd389ef97bc
server: code style reformatting using black
author | Goffi <goffi@goffi.org> |
---|---|
date | Fri, 29 Jun 2018 17:45:26 +0200 |
parents | ed67265205c4 |
children | d2036b2db6be |
comparison
equal
deleted
inserted
replaced
1112:f287fc8bb31a | 1113:cdd389ef97bc |
---|---|
18 | 18 |
19 # You should have received a copy of the GNU Affero General Public License | 19 # You should have received a copy of the GNU Affero General Public License |
20 # along with this program. If not, see <http://www.gnu.org/licenses/>. | 20 # along with this program. If not, see <http://www.gnu.org/licenses/>. |
21 | 21 |
22 from twisted.internet import defer | 22 from twisted.internet import defer |
23 | |
23 if defer.Deferred.debug: | 24 if defer.Deferred.debug: |
24 # if we are in debug mode, we want to use ipdb instead of pdb | 25 # if we are in debug mode, we want to use ipdb instead of pdb |
25 try: | 26 try: |
26 import ipdb | 27 import ipdb |
27 import pdb | 28 import pdb |
29 | |
28 pdb.set_trace = ipdb.set_trace | 30 pdb.set_trace = ipdb.set_trace |
29 pdb.post_mortem = ipdb.post_mortem | 31 pdb.post_mortem = ipdb.post_mortem |
30 except ImportError: | 32 except ImportError: |
31 pass | 33 pass |
32 | 34 |
48 | 50 |
49 | 51 |
50 CONFIG_SECTION = C.APP_NAME.lower() | 52 CONFIG_SECTION = C.APP_NAME.lower() |
51 if libervia.__version__ != sat.__version__: | 53 if libervia.__version__ != sat.__version__: |
52 import sys | 54 import sys |
53 sys.stderr.write(u"""sat module version ({sat_version}) and {current_app} version ({current_version}) mismatch | 55 |
56 sys.stderr.write( | |
57 u"""sat module version ({sat_version}) and {current_app} version ({current_version}) mismatch | |
54 | 58 |
55 sat module is located at {sat_path} | 59 sat module is located at {sat_path} |
56 libervia module is located at {libervia_path} | 60 libervia module is located at {libervia_path} |
57 | 61 |
58 Please be sure to have the same version running | 62 Please be sure to have the same version running |
59 """.format( | 63 """.format( |
60 sat_version = sat.__version__, | 64 sat_version=sat.__version__, |
61 current_app = C.APP_NAME, | 65 current_app=C.APP_NAME, |
62 current_version = libervia.__version__, | 66 current_version=libervia.__version__, |
63 sat_path = os.path.dirname(sat.__file__), | 67 sat_path=os.path.dirname(sat.__file__), |
64 libervia_path = os.path.dirname(libervia.__file__), | 68 libervia_path=os.path.dirname(libervia.__file__), |
65 ).encode('utf-8')) | 69 ).encode( |
70 "utf-8" | |
71 ) | |
72 ) | |
66 sys.stderr.flush() | 73 sys.stderr.flush() |
67 # we call os._exit to avoid help to be printed by twisted | 74 # we call os._exit to avoid help to be printed by twisted |
68 import os | 75 import os |
76 | |
69 os._exit(1) | 77 os._exit(1) |
70 | 78 |
71 | 79 |
72 def coerceConnectionType(value): # called from Libervia.OPT_PARAMETERS | 80 def coerceConnectionType(value): # called from Libervia.OPT_PARAMETERS |
73 allowed_values = ('http', 'https', 'both') | 81 allowed_values = ("http", "https", "both") |
74 if value not in allowed_values: | 82 if value not in allowed_values: |
75 raise ValueError("%(given)s not in %(expected)s" % {'given': value, 'expected': str(allowed_values)}) | 83 raise ValueError( |
84 "%(given)s not in %(expected)s" | |
85 % {"given": value, "expected": str(allowed_values)} | |
86 ) | |
76 return value | 87 return value |
88 | |
77 | 89 |
78 def coerceDataDir(value): # called from Libervia.OPT_PARAMETERS | 90 def coerceDataDir(value): # called from Libervia.OPT_PARAMETERS |
79 if isinstance(value, unicode): | 91 if isinstance(value, unicode): |
80 # XXX: if value comes from sat.conf, it's unicode, | 92 # XXX: if value comes from sat.conf, it's unicode, |
81 # and we need byte str here (for twisted) | 93 # and we need byte str here (for twisted) |
82 value = value.encode('utf-8') | 94 value = value.encode("utf-8") |
83 value = value.encode('utf-8') | 95 value = value.encode("utf-8") |
84 html = os.path.join(value, C.HTML_DIR) | 96 html = os.path.join(value, C.HTML_DIR) |
85 if not os.path.isfile(os.path.join(html, C.LIBERVIA_MAIN_PAGE)): | 97 if not os.path.isfile(os.path.join(html, C.LIBERVIA_MAIN_PAGE)): |
86 raise ValueError("%s is not a Libervia's browser HTML directory" % os.path.realpath(html)) | 98 raise ValueError( |
99 "%s is not a Libervia's browser HTML directory" % os.path.realpath(html) | |
100 ) | |
87 themes_dir = os.path.join(value, C.THEMES_DIR) | 101 themes_dir = os.path.join(value, C.THEMES_DIR) |
88 if not os.path.isfile(os.path.join(themes_dir, 'default/styles/blog.css')): | 102 if not os.path.isfile(os.path.join(themes_dir, "default/styles/blog.css")): |
89 raise ValueError("%s is not a Libervia's server data directory" % os.path.realpath(themes_dir)) | 103 raise ValueError( |
104 "%s is not a Libervia's server data directory" % os.path.realpath(themes_dir) | |
105 ) | |
90 return value | 106 return value |
107 | |
91 | 108 |
92 def coerceBool(value): | 109 def coerceBool(value): |
93 return C.bool(value) | 110 return C.bool(value) |
111 | |
94 | 112 |
95 def coerceUnicode(value): | 113 def coerceUnicode(value): |
96 # XXX: we use this method to check which value to convert to Unicode | 114 # XXX: we use this method to check which value to convert to Unicode |
97 # but we don't do the conversion here as Twisted expect str | 115 # but we don't do the conversion here as Twisted expect str |
98 return value | 116 return value |
99 | 117 |
118 | |
100 DATA_DIR_DEFAULT = '' | 119 DATA_DIR_DEFAULT = '' |
101 OPT_PARAMETERS_BOTH = [['connection_type', 't', 'https', _(u"'http', 'https' or 'both' (to launch both servers).").encode('utf-8'), coerceConnectionType], | 120 # options which are in sat.conf and on command line, |
102 ['port', 'p', 8080, _(u'The port number to listen HTTP on.').encode('utf-8'), int], | 121 # see https://twistedmatrix.com/documents/current/api/twisted.python.usage.Options.html |
103 ['port_https', 's', 8443, _(u'The port number to listen HTTPS on.').encode('utf-8'), int], | 122 OPT_PARAMETERS_BOTH = [['connection_type', 't', 'https', _(u"'http', 'https' or 'both' " |
104 ['port_https_ext', 'e', 0, _(u'The external port number used for HTTPS (0 means port_https value).').encode('utf-8'), int], | 123 "(to launch both servers).").encode('utf-8'), |
105 ['tls_private_key', '', '', _(u'TLS certificate private key (PEM format)').encode('utf-8'), coerceUnicode], | 124 coerceConnectionType], |
106 ['tls_certificate', 'c', 'libervia.pem', _(u'TLS public certificate or private key and public certificate combined (PEM format)').encode('utf-8'), coerceUnicode], | 125 ['port', 'p', 8080, |
107 ['tls_chain', '', '', _(u'TLS certificate intermediate chain (PEM format)').encode('utf-8'), coerceUnicode], | 126 _(u'The port number to listen HTTP on.').encode('utf-8'), int], |
108 ['redirect_to_https', 'r', True, _(u'Automatically redirect from HTTP to HTTPS.').encode('utf-8'), coerceBool], | 127 ['port_https', 's', 8443, |
109 ['security_warning', 'w', True, _(u'Warn user that he is about to connect on HTTP.').encode('utf-8'), coerceBool], | 128 _(u'The port number to listen HTTPS on.').encode('utf-8'), int], |
110 ['passphrase', 'k', '', (_(u"Passphrase for the SàT profile named '%s'") % C.SERVICE_PROFILE).encode('utf-8'), coerceUnicode], | 129 ['port_https_ext', 'e', 0, _(u'The external port number used for ' |
111 ['data_dir', 'd', DATA_DIR_DEFAULT, _(u'Data directory for Libervia').encode('utf-8'), coerceDataDir], | 130 u'HTTPS (0 means port_https value).').encode('utf-8'), int], |
112 ['allow_registration', '', True, _(u'Allow user to register new account').encode('utf-8'), coerceBool], | 131 ['tls_private_key', '', '', _(u'TLS certificate private key (PEM ' |
113 ['base_url_ext', '', '', _(u'The external URL to use as base URL').encode('utf-8'), coerceUnicode], | 132 u'format)').encode('utf-8'), coerceUnicode], |
114 ] # options which are in sat.conf and on command line, see https://twistedmatrix.com/documents/current/api/twisted.python.usage.Options.html | 133 ['tls_certificate', 'c', 'libervia.pem', _(u'TLS public ' |
134 u'certificate or private key and public certificate combined ' | |
135 u'(PEM format)').encode('utf-8'), coerceUnicode], | |
136 ['tls_chain', '', '', _(u'TLS certificate intermediate chain (PEM ' | |
137 u'format)').encode('utf-8'), coerceUnicode], | |
138 ['redirect_to_https', 'r', True, _(u'Automatically redirect from ' | |
139 u'HTTP to HTTPS.').encode('utf-8'), coerceBool], | |
140 ['security_warning', 'w', True, _(u'Warn user that he is about to ' | |
141 u'connect on HTTP.').encode('utf-8'), coerceBool], | |
142 ['passphrase', 'k', '', (_(u"Passphrase for the SàT profile " | |
143 u"named '%s'") % C.SERVICE_PROFILE).encode('utf-8'), | |
144 coerceUnicode], | |
145 ['data_dir', 'd', DATA_DIR_DEFAULT, _(u'Data directory for ' | |
146 u'Libervia').encode('utf-8'), coerceDataDir], | |
147 ['allow_registration', '', True, _(u'Allow user to register new ' | |
148 u'account').encode('utf-8'), coerceBool], | |
149 ['base_url_ext', '', '', | |
150 _(u'The external URL to use as base URL').encode('utf-8'), | |
151 coerceUnicode], | |
152 ] | |
115 # Options which are in sat.conf only | 153 # Options which are in sat.conf only |
116 OPT_PARAMETERS_CFG = [ | 154 OPT_PARAMETERS_CFG = [ |
117 ['empty_password_allowed_warning_dangerous_list', None, '', None], | 155 ["empty_password_allowed_warning_dangerous_list", None, "", None], |
118 ['url_redirections_profile', None, '', None], | 156 ["url_redirections_profile", None, "", None], |
119 ['url_redirections_dict', None, {}, None], | 157 ["url_redirections_dict", None, {}, None], |
120 ['menu_json', None, C.DEFAULT_MENU, None], | 158 ["menu_json", None, C.DEFAULT_MENU, None], |
121 ['tickets_trackers_json', None, None, None], | 159 ["tickets_trackers_json", None, None, None], |
122 ['mr_handlers_json', None, None, None], | 160 ["mr_handlers_json", None, None, None], |
123 ] | 161 ] |
162 | |
124 | 163 |
125 def initialise(options): | 164 def initialise(options): |
126 """Method to initialise global modules""" | 165 """Method to initialise global modules""" |
127 from twisted.internet import glib2reactor | 166 from twisted.internet import glib2reactor |
167 | |
128 glib2reactor.install() | 168 glib2reactor.install() |
129 # XXX: We need to configure logs before any log method is used, so here is the best place. | 169 # XXX: We need to configure logs before any log method is used, |
170 # so here is the best place. | |
130 from sat.core import log_config | 171 from sat.core import log_config |
172 | |
131 log_config.satConfigure(C.LOG_BACKEND_TWISTED, C, backend_data=options) | 173 log_config.satConfigure(C.LOG_BACKEND_TWISTED, C, backend_data=options) |
132 from libervia.server import server | 174 from libervia.server import server |
175 | |
133 # we can't import this file from libervia.server.server because it's not a true module | 176 # we can't import this file from libervia.server.server because it's not a true module |
134 # (there is no __init__.py file, as required by twistd plugin system), so we set the | 177 # (there is no __init__.py file, as required by twistd plugin system), so we set the |
135 # global values from here | 178 # global values from here |
136 server.DATA_DIR_DEFAULT = DATA_DIR_DEFAULT | 179 server.DATA_DIR_DEFAULT = DATA_DIR_DEFAULT |
137 server.OPT_PARAMETERS_BOTH = OPT_PARAMETERS_BOTH | 180 server.OPT_PARAMETERS_BOTH = OPT_PARAMETERS_BOTH |
142 class Options(usage.Options): | 185 class Options(usage.Options): |
143 # optArgs is not really useful in our case, we need more than a flag | 186 # optArgs is not really useful in our case, we need more than a flag |
144 optParameters = OPT_PARAMETERS_BOTH | 187 optParameters = OPT_PARAMETERS_BOTH |
145 | 188 |
146 def __init__(self): | 189 def __init__(self): |
147 """Read SàT configuration file in order to overwrite the hard-coded default values. | 190 """Read SàT configuration file in order to overwrite the hard-coded default values |
148 | 191 |
149 Priority for the usage of the values is (from lowest to highest): | 192 Priority for the usage of the values is (from lowest to highest): |
150 - hard-coded default values | 193 - hard-coded default values |
151 - values from SàT configuration files | 194 - values from SàT configuration files |
152 - values passed on the command line | 195 - values passed on the command line |
153 """ | 196 """ |
154 # If we do it the reading later: after the command line options have been parsed, there's no good way to know | 197 # If we do it the reading later: after the command line options have been parsed, |
155 # if the options values are the hard-coded ones or if they have been passed on the command line. | 198 # there's no good way to know |
199 # if the options values are the hard-coded ones or if they have been passed | |
200 # on the command line. | |
156 | 201 |
157 # FIXME: must be refactored + code can be factorised with backend | 202 # FIXME: must be refactored + code can be factorised with backend |
158 config_parser = ConfigParser.SafeConfigParser() | 203 config_parser = ConfigParser.SafeConfigParser() |
159 config_parser.read(C.CONFIG_FILES) | 204 config_parser.read(C.CONFIG_FILES) |
160 self.handleDeprecated(config_parser) | 205 self.handleDeprecated(config_parser) |
161 for param in self.optParameters + OPT_PARAMETERS_CFG: | 206 for param in self.optParameters + OPT_PARAMETERS_CFG: |
162 name = param[0] | 207 name = param[0] |
163 try: | 208 try: |
164 value = config.getConfig(config_parser, CONFIG_SECTION, name, Exception) | 209 value = config.getConfig(config_parser, CONFIG_SECTION, name, Exception) |
165 if isinstance(value, unicode): | 210 if isinstance(value, unicode): |
166 value = value.encode('utf-8') | 211 value = value.encode("utf-8") |
167 try: | 212 try: |
168 param[2] = param[4](value) | 213 param[2] = param[4](value) |
169 except IndexError: # the coerce method is optional | 214 except IndexError: # the coerce method is optional |
170 param[2] = value | 215 param[2] = value |
171 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): | 216 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): |
172 pass | 217 pass |
173 usage.Options.__init__(self) | 218 usage.Options.__init__(self) |
174 for opt_data in OPT_PARAMETERS_CFG: | 219 for opt_data in OPT_PARAMETERS_CFG: |
177 def handleDeprecated(self, config_parser): | 222 def handleDeprecated(self, config_parser): |
178 """display warning and/or change option when a deprecated option if found | 223 """display warning and/or change option when a deprecated option if found |
179 | 224 |
180 param config_parser(ConfigParser): read ConfigParser instance for sat.conf | 225 param config_parser(ConfigParser): read ConfigParser instance for sat.conf |
181 """ | 226 """ |
182 replacements = (('ssl_certificate', 'tls_certificate'),) | 227 replacements = (("ssl_certificate", "tls_certificate"),) |
183 for old, new in replacements: | 228 for old, new in replacements: |
184 try: | 229 try: |
185 value = config.getConfig(config_parser, CONFIG_SECTION, old, Exception) | 230 value = config.getConfig(config_parser, CONFIG_SECTION, old, Exception) |
186 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): | 231 except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): |
187 pass | 232 pass |
188 else: | 233 else: |
189 print u"\n/!\\ Use of {old} is deprecated, please use {new} instead\n".format(old=old, new=new) | 234 print(u"\n/!\\ Use of {old} is deprecated, please use {new} instead\n" |
235 .format(old=old, new=new)) | |
190 config_parser.set(CONFIG_SECTION, new, value) | 236 config_parser.set(CONFIG_SECTION, new, value) |
191 | 237 |
192 | 238 |
193 class LiberviaMaker(object): | 239 class LiberviaMaker(object): |
194 implements(IServiceMaker, IPlugin) | 240 implements(IServiceMaker, IPlugin) |
195 | 241 |
196 tapname = C.APP_NAME_FILE | 242 tapname = C.APP_NAME_FILE |
197 description = _(u'The web frontend of Salut à Toi') | 243 description = _(u"The web frontend of Salut à Toi") |
198 options = Options | 244 options = Options |
199 | 245 |
200 def makeService(self, options): | 246 def makeService(self, options): |
201 for opt in OPT_PARAMETERS_BOTH: | 247 for opt in OPT_PARAMETERS_BOTH: |
202 # FIXME: that's a ugly way to get unicode in Libervia | 248 # FIXME: that's a ugly way to get unicode in Libervia |
205 try: | 251 try: |
206 coerce_cb = opt[4] | 252 coerce_cb = opt[4] |
207 except IndexError: | 253 except IndexError: |
208 continue | 254 continue |
209 if coerce_cb == coerceUnicode: | 255 if coerce_cb == coerceUnicode: |
210 options[opt[0]] = options[opt[0]].decode('utf-8') | 256 options[opt[0]] = options[opt[0]].decode("utf-8") |
211 initialise(options.parent) | 257 initialise(options.parent) |
212 from libervia.server import server | 258 from libervia.server import server |
259 | |
213 return server.Libervia(options) | 260 return server.Libervia(options) |
214 | 261 |
215 | 262 |
216 # affectation to some variable is necessary for twisted introspection to work | 263 # affectation to some variable is necessary for twisted introspection to work |
217 serviceMaker = LiberviaMaker() | 264 serviceMaker = LiberviaMaker() |