[pyramid] Add a "pyramid" instance configuration type
authorDenis Laxalde <denis.laxalde@logilab.fr>
Thu, 09 Mar 2017 16:36:33 +0100
changeset 12053 c3c9f2e1424c
parent 12052 1a1d2f5faddb
child 12054 d830ea048c97
[pyramid] Add a "pyramid" instance configuration type In a new module 'cubicweb.pyramid.config' we define a "pyramid" instance configuration type. The noticeable feature of this configuration is that it manages a 'development.ini' file that gets installed in application home (along with `.conf` file). This file is templated and includes generated values for secrets of session and authtk tokens. This means that we can just call: pserve etc/cubicweb.d/<appname>/development.ini or gunicorn --paste etc/cubicweb.d/<appname>/development.ini -b :8080 just after instance creation to get a pyramid instance running without having to hack around a 'pyramid.ini' file. This patch drops 'development.ini' from skeleton and moves it in cubicweb/pyramid so that it gets installed at instance creation which is more appropriate than in cube creation. The new configuration class sets "cubicweb.bwcompat" setting to false so it is not intended to replace the "all-in-one" configuration type (which would require a bit more work). This configuration is close to the the 'repository' configuration type with just a couple of options from WebConfiguration that are needed for Pyramid (anonymous user/password plus some miscellaneous options that I'm not so sure are really needed). Note, in particular, that we do not pull CORS settings to be injected as a WSGI middleware like in wsgi_application_from_cwconfig() since I believe this should be left as an end-user responsibility and since this can be defined in a standard way in paste configuration. This configuration inherits from ServerConfiguration but registers the same appobjects as WebConfiguration. In cubicweb.web.request._CubicWebRequestBase, we guard against access to "uiprops" and "datadir_url" of the config because this new "pyramid" config does not have these (this does not make sense without bwcompat mode). At some point, we should either avoid using `cw_request`'s pyramid request attribute or make cubicweb's web request really independant of existing implementation and drop these assumptions.
MANIFEST.in
cubicweb/cwconfig.py
cubicweb/cwctl.py
cubicweb/devtools/test/unittest_devctl.py
cubicweb/pyramid/config.py
cubicweb/pyramid/development.ini.tmpl
cubicweb/pyramid/pyramidctl.py
cubicweb/pyramid/test/test_config.py
cubicweb/skeleton/development.ini.tmpl
cubicweb/test/unittest_cwctl.py
cubicweb/web/request.py
flake8-ok-files.txt
--- a/MANIFEST.in	Fri Mar 10 12:02:41 2017 +0100
+++ b/MANIFEST.in	Thu Mar 09 16:36:33 2017 +0100
@@ -62,6 +62,8 @@
 recursive-include cubicweb/web/test/data bootstrap_cubes pouet.css *.py
 recursive-include cubicweb/web/test/data/static/jstests *.js *.html *.json
 
+include cubicweb/pyramid/development.ini.tmpl
+
 include cubicweb/web/data/jquery-treeview/*.md
 
 recursive-include cubicweb/skeleton *.py *.css *.js *.po compat *.tmpl rules
--- a/cubicweb/cwconfig.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/cwconfig.py	Thu Mar 09 16:36:33 2017 +0100
@@ -225,7 +225,7 @@
     """return a list of installed configurations in a directory
     according to \*-ctl files
     """
-    return [name for name in ('repository', 'all-in-one')
+    return [name for name in ('repository', 'all-in-one', 'pyramid')
             if exists(join(directory, '%s.conf' % name))]
 
 
@@ -710,7 +710,7 @@
     @classmethod
     def load_available_configs(cls):
         for confmod in ('web.webconfig',  'etwist.twconfig',
-                        'server.serverconfig',):
+                        'server.serverconfig', 'pyramid.config'):
             try:
                 __import__('cubicweb.%s' % confmod)
             except ImportError as exc:
--- a/cubicweb/cwctl.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/cwctl.py	Thu Mar 09 16:36:33 2017 +0100
@@ -326,7 +326,7 @@
           }),
         ('config',
          {'short': 'c', 'type' : 'choice', 'metavar': '<install type>',
-          'choices': ('all-in-one', 'repository'),
+          'choices': ('all-in-one', 'repository', 'pyramid'),
           'default': 'all-in-one',
           'help': 'installation type, telling which part of an instance '
           'should be installed. You can list available configurations using the'
--- a/cubicweb/devtools/test/unittest_devctl.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/devtools/test/unittest_devctl.py	Thu Mar 09 16:36:33 2017 +0100
@@ -47,7 +47,7 @@
         expected_project_content = ['setup.py', 'test', 'MANIFEST.in',
                                     'cubicweb_foo',
                                     'cubicweb-foo.spec', 'debian', 'README',
-                                    'tox.ini', 'development.ini']
+                                    'tox.ini']
         expected_package_content = ['i18n', 'hooks.py', 'views.py',
                                     'migration', 'entities.py', 'schema.py',
                                     '__init__.py', 'data', '__pkginfo__.py']
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cubicweb/pyramid/config.py	Thu Mar 09 16:36:33 2017 +0100
@@ -0,0 +1,64 @@
+# copyright 2017 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of CubicWeb.
+#
+# CubicWeb is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
+"""Configuration for CubicWeb instances on top of a Pyramid application"""
+
+from os import path
+import random
+import string
+
+from logilab.common.configuration import merge_options
+
+from cubicweb.cwconfig import CONFIGURATIONS
+from cubicweb.server.serverconfig import ServerConfiguration
+from cubicweb.toolsutils import fill_templated_file
+from cubicweb.web.webconfig import BaseWebConfiguration
+
+
+def get_random_secret_key():
+    """Return 50-character secret string"""
+    chars = string.ascii_letters + string.digits
+    return "".join([random.choice(chars) for i in range(50)])
+
+
+class CubicWebPyramidConfiguration(BaseWebConfiguration, ServerConfiguration):
+    """Pyramid application with a CubicWeb repository"""
+    name = 'pyramid'
+
+    cubicweb_appobject_path = (BaseWebConfiguration.cubicweb_appobject_path
+                               | ServerConfiguration.cubicweb_appobject_path)
+    cube_appobject_path = (BaseWebConfiguration.cube_appobject_path
+                           | ServerConfiguration.cube_appobject_path)
+
+    options = merge_options(ServerConfiguration.options +
+                            BaseWebConfiguration.options)
+
+    def write_development_ini(self, cubes):
+        """Write a 'development.ini' file into apphome."""
+        template_fpath = path.join(path.dirname(__file__), 'development.ini.tmpl')
+        target_fpath = path.join(self.apphome, 'development.ini')
+        context = {
+            'instance': self.appid,
+            'cubename': cubes[0],
+            'session-secret': get_random_secret_key(),
+            'auth-authtkt-persistent-secret': get_random_secret_key(),
+            'auth-authtkt-session-secret': get_random_secret_key(),
+        }
+        fill_templated_file(template_fpath, target_fpath, context)
+
+
+CONFIGURATIONS.append(CubicWebPyramidConfiguration)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cubicweb/pyramid/development.ini.tmpl	Thu Mar 09 16:36:33 2017 +0100
@@ -0,0 +1,41 @@
+###
+# app configuration
+# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html
+###
+
+[app:main]
+use = egg:cubicweb#main
+
+pyramid.reload_templates = true
+pyramid.debug_authorization = false
+pyramid.debug_notfound = false
+pyramid.debug_routematch = false
+pyramid.default_locale_name = en
+pyramid.includes =
+    pyramid_debugtoolbar
+    cubicweb_%(cubename)s
+
+# By default, the toolbar only appears for clients from IP addresses
+# '127.0.0.1' and '::1'.
+# debugtoolbar.hosts = 127.0.0.1 ::1
+
+##
+# CubicWeb instance settings
+# http://cubicweb.readthedocs.io/en/latest/book/pyramid/settings/
+##
+cubicweb.instance = %(instance)s
+cubicweb.bwcompat = false
+cubicweb.debug = true
+cubicweb.session.secret = %(session-secret)s
+cubicweb.auth.authtkt.persistent.secure = false
+cubicweb.auth.authtkt.persistent.secret = %(auth-authtkt-persistent-secret)s
+cubicweb.auth.authtkt.session.secure = false
+cubicweb.auth.authtkt.session.secret = %(auth-authtkt-session-secret)s
+
+###
+# wsgi server configuration
+###
+
+[server:main]
+use = egg:waitress#main
+listen = 127.0.0.1:6543 [::1]:6543
--- a/cubicweb/pyramid/pyramidctl.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/pyramid/pyramidctl.py	Thu Mar 09 16:36:33 2017 +0100
@@ -41,7 +41,8 @@
 from cubicweb.cwconfig import CubicWebConfiguration as cwcfg
 from cubicweb.cwctl import CWCTL, InstanceCommand, init_cmdline_log_threshold
 from cubicweb.pyramid import wsgi_application_from_cwconfig
-from cubicweb.server import set_debug
+from cubicweb.server import serverctl, set_debug
+from cubicweb.web.webctl import WebCreateHandler
 
 import waitress
 
@@ -51,6 +52,17 @@
 LOG_LEVELS = ('debug', 'info', 'warning', 'error')
 
 
+class PyramidCreateHandler(serverctl.RepositoryCreateHandler,
+                           WebCreateHandler):
+    cfgname = 'pyramid'
+
+    def bootstrap(self, cubes, automatic=False, inputlevel=0):
+        serverctl.RepositoryCreateHandler.bootstrap(self, cubes, automatic, inputlevel)
+        # Call WebCreateHandler.bootstrap to prompt about get anonymous-user.
+        WebCreateHandler.bootstrap(self, cubes, automatic, inputlevel)
+        self.config.write_development_ini(cubes)
+
+
 class PyramidStartHandler(InstanceCommand):
     """Start an interactive pyramid server.
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/cubicweb/pyramid/test/test_config.py	Thu Mar 09 16:36:33 2017 +0100
@@ -0,0 +1,64 @@
+# copyright 2017 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
+#
+# This file is part of CubicWeb.
+#
+# CubicWeb is free software: you can redistribute it and/or modify it under the
+# terms of the GNU Lesser General Public License as published by the Free
+# Software Foundation, either version 2.1 of the License, or (at your option)
+# any later version.
+#
+# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
+# details.
+#
+# You should have received a copy of the GNU Lesser General Public License along
+# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
+"""Tests for cubicweb.pyramid.config module."""
+
+import os
+from os import path
+from unittest import TestCase
+
+from mock import patch
+
+from cubicweb.devtools.testlib import TemporaryDirectory
+
+from cubicweb.pyramid import config
+
+
+class PyramidConfigTC(TestCase):
+
+    def test_get_random_secret_key(self):
+        with patch('random.choice', return_value='0') as patched_choice:
+            secret = config.get_random_secret_key()
+        self.assertEqual(patched_choice.call_count, 50)
+        self.assertEqual(secret, '0' * 50)
+
+    def test_write_development_ini(self):
+        with TemporaryDirectory() as instancedir:
+            appid = 'pyramid-instance'
+            os.makedirs(path.join(instancedir, appid))
+            os.environ['CW_INSTANCES_DIR'] = instancedir
+            try:
+                cfg = config.CubicWebPyramidConfiguration(appid)
+                with patch('random.choice', return_value='0') as patched_choice:
+                    cfg.write_development_ini(['foo', 'bar'])
+            finally:
+                os.environ.pop('CW_INSTANCES_DIR')
+            with open(path.join(instancedir, appid, 'development.ini')) as f:
+                lines = f.readlines()
+        self.assertEqual(patched_choice.call_count, 50 * 3)
+        secret = '0' * 50
+        for option in ('cubicweb.session.secret',
+                       'cubicweb.auth.authtkt.persistent.secret',
+                       'cubicweb.auth.authtkt.session.secret'):
+            self.assertIn('{} = {}\n'.format(option, secret), lines)
+        self.assertIn('cubicweb.instance = {}\n'.format(appid), lines)
+        self.assertIn('    cubicweb_foo\n', lines)
+
+
+if __name__ == '__main__':
+    import unittest
+    unittest.main()
--- a/cubicweb/skeleton/development.ini.tmpl	Fri Mar 10 12:02:41 2017 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-###
-# app configuration
-# http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/environment.html
-###
-
-[app:main]
-use = egg:cubicweb#main
-
-pyramid.reload_templates = true
-pyramid.debug_authorization = false
-pyramid.debug_notfound = false
-pyramid.debug_routematch = false
-pyramid.default_locale_name = en
-pyramid.includes =
-    pyramid_debugtoolbar
-    cubicweb_%(cubename)s
-
-# By default, the toolbar only appears for clients from IP addresses
-# '127.0.0.1' and '::1'.
-# debugtoolbar.hosts = 127.0.0.1 ::1
-
-##
-# CubicWeb instance settings
-# http://cubicweb.readthedocs.io/en/latest/book/pyramid/settings/
-##
-cubicweb.instance = %%(instance)s
-cubicweb.bwcompat = False
-cubicweb.debug = True
-# cubicweb.session.secret =
-# cubicweb.auth.authtkt.persistent.secret =
-cubicweb.auth.authtkt.persistent.secure = False
-# cubicweb.auth.authtkt.session.secret =
-cubicweb.auth.authtkt.session.secure = False
-
-###
-# wsgi server configuration
-###
-
-[server:main]
-use = egg:waitress#main
-listen = 127.0.0.1:6543 [::1]:6543
--- a/cubicweb/test/unittest_cwctl.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/test/unittest_cwctl.py	Thu Mar 09 16:36:33 2017 +0100
@@ -24,6 +24,7 @@
 from six import PY2
 
 from cubicweb.cwconfig import CubicWebConfiguration
+from cubicweb.cwctl import ListCommand
 from cubicweb.devtools.testlib import CubicWebTC
 from cubicweb.server.migractions import ServerMigrationHelper
 
@@ -38,9 +39,15 @@
         sys.stdout = sys.__stdout__
 
     def test_list(self):
-        from cubicweb.cwctl import ListCommand
         ListCommand(None).run([])
 
+    def test_list_configurations(self):
+        ListCommand(None).run(['configurations'])
+        configs = [l[2:].strip() for l in self.stream.getvalue().splitlines()
+                   if l.startswith('* ')]
+        self.assertIn('all-in-one', configs)
+        self.assertIn('pyramid', configs)
+
 
 class CubicWebShellTC(CubicWebTC):
 
--- a/cubicweb/web/request.py	Fri Mar 10 12:02:41 2017 +0100
+++ b/cubicweb/web/request.py	Thu Mar 09 16:36:33 2017 +0100
@@ -116,8 +116,10 @@
         self.uiprops = None
         #: url for serving datadir (see :ref:`resources`)
         self.datadir_url = None
-        self.uiprops = vreg.config.uiprops
-        self.datadir_url = vreg.config.datadir_url
+        # some config (i.e. "pyramid") do not have "uiprops" nor "datadir_url"
+        # attributes)
+        self.uiprops = getattr(vreg.config, 'uiprops', None)
+        self.datadir_url = getattr(vreg.config, 'datadir_url', None)
         #: enable UStringIO's write tracing
         self.tracehtml = False
         if vreg.config.debugmode:
--- a/flake8-ok-files.txt	Fri Mar 10 12:02:41 2017 +0100
+++ b/flake8-ok-files.txt	Thu Mar 09 16:36:33 2017 +0100
@@ -106,6 +106,7 @@
 cubicweb/xy.py
 cubicweb/pyramid/auth.py
 cubicweb/pyramid/bwcompat.py
+cubicweb/pyramid/config.py
 cubicweb/pyramid/core.py
 cubicweb/pyramid/defaults.py
 cubicweb/pyramid/__init__.py
@@ -118,6 +119,7 @@
 cubicweb/pyramid/tools.py
 cubicweb/pyramid/test/__init__.py
 cubicweb/pyramid/test/test_bw_request.py
+cubicweb/pyramid/test/test_config.py
 cubicweb/pyramid/test/test_core.py
 cubicweb/pyramid/test/test_login.py
 cubicweb/pyramid/test/test_rest_api.py