├── ckan_multisite ├── __init__.py ├── tests │ ├── __init__.py │ └── router_tests.py ├── templates │ ├── list.html │ ├── create.html │ ├── login.html │ └── edit.html ├── app.py ├── pw.py ├── login.py ├── task.py ├── config.py.template ├── site.py ├── static │ ├── edit.js │ └── main.css ├── admin.py ├── api.py └── router.py ├── diagrams ├── ckan-multisite.png └── ckan-multisite.graphml ├── requirements.txt ├── uwsgi.ini ├── .gitignore ├── setup.py ├── LICENSE ├── manage.sh ├── promoted.html ├── run.sh ├── README.md ├── development.ini └── redis.conf /ckan_multisite/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ckan_multisite/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /diagrams/ckan-multisite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/datacats/ckan-multisite/HEAD/diagrams/ckan-multisite.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-admin 3 | flask-login 4 | flask-sqlalchemy 5 | celery 6 | redis 7 | uwsgi 8 | datacats 9 | passlib 10 | -------------------------------------------------------------------------------- /ckan_multisite/templates/list.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/model/list.html' %} 2 | 3 | {% block head %} 4 | {{ super() }} 5 | 6 | 7 | 8 | {% endblock %} -------------------------------------------------------------------------------- /ckan_multisite/templates/create.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/model/create.html' %} 2 | 3 | {% block head %} 4 | {{ super() }} 5 | 6 | 7 | 8 | {% endblock %} -------------------------------------------------------------------------------- /uwsgi.ini: -------------------------------------------------------------------------------- 1 | [uwsgi] 2 | socket = /tmp/uwsgi.sock 3 | processes = 4 4 | master = 1 5 | module = ckan_multisite.app:app 6 | chmod-socket = 666 7 | logto=uwsgi.log 8 | harakiri-verbose = False 9 | log-maxsize = 10485760 10 | master = True 11 | 12 | max-requests = 5000 13 | buffer-size = 32768 14 | post-buffering = 4096 15 | processes = 4 16 | stats = :1717 17 | enable-threads = True 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python compiled 2 | *.pyc 3 | __pycache__ 4 | 5 | # Server logs 6 | redis-server.log 7 | 8 | # SQLite 9 | *.db 10 | 11 | # Pip stuffs 12 | *.egg* 13 | 14 | # Multisite environment generate by default script 15 | multisite 16 | 17 | # virtualenv generated by script 18 | virtualenv 19 | 20 | # Our configuration file built from the template 21 | ckan_multisite/config.py 22 | -------------------------------------------------------------------------------- /ckan_multisite/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | {% with messages = get_flashed_messages() %} 10 | {% if messages %} 11 | 16 | {% endif %} 17 | {% endwith %} 18 | 19 |
20 | 21 | 22 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2015 Boxkite Inc. 4 | 5 | # This file is part of the ckan-multisite package and is released 6 | # under the terms of the MIT License. 7 | # See LICENSE or http://opensource.org/licenses/MIT 8 | 9 | from setuptools import setup 10 | import sys 11 | 12 | install_requires=[ 13 | 'datacats', 14 | 'flask' 15 | ] 16 | 17 | __version__ = '0.01dev' 18 | 19 | setup( 20 | name='ckan-multisite', 21 | version=__version__, 22 | description='Web wrapper around Datacats child environment functionality', 23 | license='MIT', 24 | author='Boxkite', 25 | author_email='contact@boxkite.ca', 26 | url='https://github.com/boxkite/ckan-multisite', 27 | packages=[ 28 | 'ckan_multisite' 29 | ], 30 | install_requires=install_requires, 31 | include_package_data=True, 32 | zip_safe=False, 33 | entry_points = """ 34 | [console_scripts] 35 | ckan-multisite=ckan_multisite.api:main 36 | """, 37 | ) 38 | -------------------------------------------------------------------------------- /ckan_multisite/app.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Boxkite Inc. 2 | 3 | # This file is part of the ckan-multisite package and is released 4 | # under the terms of the MIT License. 5 | # See LICENSE or http://opensource.org/licenses/MIT 6 | 7 | from flask import Flask, redirect, request, url_for 8 | from flask.ext.admin import Admin 9 | from ckan_multisite.api import bp as api_bp 10 | from ckan_multisite.admin import admin 11 | from ckan_multisite import site 12 | from ckan_multisite.pw import check_login_cookie 13 | from ckan_multisite.config import SECRET_KEY, DEBUG, ADDRESS, PORT 14 | from ckan_multisite.login import bp as login_bp 15 | 16 | app = Flask(__name__) 17 | app.config['PROPAGATE_EXCEPTIONS'] = True 18 | app.secret_key = SECRET_KEY 19 | admin.init_app(app) 20 | app.register_blueprint(api_bp) 21 | app.register_blueprint(login_bp) 22 | 23 | 24 | @app.route('/') 25 | def index(): 26 | return redirect('/admin/site') 27 | 28 | 29 | if __name__ == '__main__': 30 | app.run(debug=DEBUG, use_reloader=False, host=ADDRESS, port=PORT) 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 boxkite 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /ckan_multisite/pw.py: -------------------------------------------------------------------------------- 1 | from passlib.hash import sha256_crypt 2 | 3 | from itertools import cycle, izip 4 | 5 | from flask import request, session 6 | 7 | try: 8 | from ckan_multisite.config import ADMIN_PW, SECRET_KEY 9 | except ImportError: 10 | pass 11 | 12 | def encrypt(password): 13 | return sha256_crypt.encrypt(password) 14 | 15 | 16 | def verify(txt, hash): 17 | return sha256_crypt.verify(txt, hash) 18 | 19 | 20 | def _xor_encrypt(thing, key): 21 | return ''.join([chr(ord(thing_c) ^ ord(key_c)) for thing_c, key_c in izip(thing, cycle(key))]) 22 | 23 | 24 | def _xor_decrypt(encrypted, key): 25 | return _xor_encrypt(encrypted, key) 26 | 27 | 28 | def remove_login_cookie(): 29 | session.clear() 30 | 31 | 32 | def place_login_cookie(pw): 33 | if verify(pw, ADMIN_PW): 34 | session['pwhash'] = _xor_encrypt(ADMIN_PW, SECRET_KEY) 35 | return True 36 | else: 37 | return False 38 | 39 | 40 | def check_login_cookie(): 41 | """ 42 | This function checks for the ADMIN_PW and the secret in config.py in 43 | the Flask request context's cookies. 44 | """ 45 | session_cookie = session.get('pwhash') 46 | if not session_cookie: 47 | return False 48 | else: 49 | pwhash = _xor_decrypt(session_cookie, SECRET_KEY) 50 | return pwhash == ADMIN_PW 51 | -------------------------------------------------------------------------------- /ckan_multisite/tests/router_tests.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Boxkite Inc. 2 | 3 | # This file is part of the ckan-multisite package and is released 4 | # under the terms of the MIT License. 5 | # See LICENSE or http://opensource.org/licenses/MIT 6 | 7 | from unittest import TestCase 8 | from ckan_multisite import router 9 | from ckan_multisite.router import DatacatsNginxConfig 10 | from tempfile import gettempdir 11 | from os.path import exists 12 | 13 | DEFAULT_PATH = router.BASE_PATH 14 | 15 | class RouterTest(TestCase): 16 | def setUp(self): 17 | self.router = DatacatsNginxConfig('testenv') 18 | self.tmpdir = gettempdir() 19 | router.BASE_PATH = self.tmpdir 20 | 21 | def test_config_names(self): 22 | router.BASE_PATH = DEFAULT_PATH 23 | name = router._get_site_config_name('testsite') 24 | self.assertEqual(name, '/etc/nginx/sites-available/testsite') 25 | 26 | def test_add_config(self): 27 | self.router.add_site('testaddsite', 2000) 28 | self.assert_(exists(self.tmpdir + '/testaddsite')) 29 | 30 | def test_remove_config(self): 31 | router.BASE_PATH = self.tmpdir 32 | fname = router._get_site_config_name('testremsite') 33 | with open(fname, 'a'): 34 | pass 35 | self.router.remove_site('testremsite', 2000) 36 | self.assert_(not exists(fname)) 37 | -------------------------------------------------------------------------------- /ckan_multisite/login.py: -------------------------------------------------------------------------------- 1 | from ckan_multisite.pw import check_login_cookie, place_login_cookie, remove_login_cookie 2 | 3 | from flask import request, url_for, render_template, redirect, Blueprint, flash 4 | 5 | from wtforms import Form, PasswordField, validators 6 | 7 | bp = Blueprint('login', __name__, template_folder='templates') 8 | 9 | 10 | @bp.route('/logout', methods=('GET',)) 11 | def logout(): 12 | remove_login_cookie() 13 | return redirect(url_for('index')) 14 | 15 | 16 | @bp.route('/login', methods=('GET', 'POST')) 17 | def login(): 18 | # If they're already logged in, forward them to their destination. 19 | if check_login_cookie(): 20 | print 'Redirecting for already auth' 21 | return redirect(request.values.get('next') if 'next' in request.values else url_for('index'), code=302) 22 | 23 | if request.method == 'POST': 24 | # Otherwise, we need to get the password from the form, validate it, and 25 | if 'pw' in request.values: 26 | if place_login_cookie(request.values['pw']): 27 | print 'Login successful!' 28 | return redirect(request.values.get('next') if 'next' in request.values else url_for('index'), code=302) 29 | else: 30 | flash('Incorrect password.') 31 | else: 32 | flash('Incomplete request.') 33 | return render_template('login.html') 34 | -------------------------------------------------------------------------------- /ckan_multisite/task.py: -------------------------------------------------------------------------------- 1 | """ 2 | A collection of tasks for the celeryd 3 | """ 4 | 5 | from celery import Celery 6 | from config import CELERY_BACKEND_URL, HOSTNAME 7 | from router import nginx 8 | from site import site_by_name 9 | from datacats.error import WebCommandError 10 | from datacats.cli.create import create_environment 11 | 12 | app = Celery('ckan-multisite', broker=CELERY_BACKEND_URL, backend=CELERY_BACKEND_URL) 13 | 14 | @app.task 15 | def create_site_task(site): 16 | try: 17 | environment = site.environment 18 | create_environment(environment.name, None, '2.3', 19 | True, environment.site_name, False, False, 20 | '0.0.0.0', False, True, True, 21 | site_url='{}.{}'.format(environment.site_name, HOSTNAME)) 22 | # Serialize the site display name to its datadir 23 | site.serialize_display_name() 24 | nginx.add_site(environment.site_name, environment.port) 25 | print 'create done!' 26 | except WebCommandError as e: 27 | raise 28 | 29 | 30 | @app.task 31 | def remove_site_task(site): 32 | print 'starting purge' 33 | environment = site.environment 34 | nginx.remove_site(environment.site_name) 35 | print 'site removed' 36 | environment.stop_ckan() 37 | environment.stop_supporting_containers() 38 | print 'containers stopped' 39 | assert environment.site_name in environment.sites, str(environment.sites) + ' ' + environment.site_name 40 | environment.purge_data([environment.site_name], never_delete=True) 41 | print 'Purge done!' 42 | -------------------------------------------------------------------------------- /ckan_multisite/templates/edit.html: -------------------------------------------------------------------------------- 1 | {% extends 'admin/model/edit.html' %} 2 | 3 | {% block head %} 4 | {{ super() }} 5 | 6 | 7 | 8 | 9 | {% endblock %} 10 | 11 | {% block body %} 12 | 13 |

{{ model.name }}

14 |

15 | Environment Actions: 16 | 17 | 18 | 19 |

20 |
21 |
22 |

Reset your admin password

23 | 24 |
25 |
26 |
27 |
28 |
29 | 30 |
31 | 32 | 33 |

34 | {{ super() }} 35 |

36 | {% endblock %} 37 | 38 | {% block tail %} 39 | 40 | 41 | {% endblock %} 42 | -------------------------------------------------------------------------------- /ckan_multisite/config.py.template: -------------------------------------------------------------------------------- 1 | """ 2 | Contains configuration options 3 | 4 | If this is your first time seeing this file - it's probably when you 5 | are running the run.sh script. In which case, hi! 6 | 7 | This is the config file for CKAN multisite. You should look through 8 | all of these options - hopefully the comments above them will guide 9 | you towards how you should set them. 10 | """ 11 | 12 | from os.path import expanduser 13 | 14 | # The base hostname of your site, e.x. datacats.com 15 | HOSTNAME = 'example.com' 16 | # This is generated by the script which installs ckan-multisite. If you are 17 | # manually installing this, you should definitely change this from its 18 | # (rather weak) development value. 19 | # If you're running from run.sh - ignore this option. 20 | #SECRET_KEY = 'my_key' 21 | # This is generated again by the script and is a hash of the admin password. 22 | # use manage.sh changepw. 23 | #ADMIN_PW 24 | # The name of the environment to use for multisite. 25 | # This must be created using the `datacats` command line tool prior to usage of this 26 | # application 27 | MAIN_ENV_NAME = 'multisite' 28 | # The datacats directory. This probably shouldn't change but 29 | # is in config to future-proof from new versions of datacats. 30 | DATACATS_DIRECTORY = expanduser('~/.datacats') 31 | # The URI for the backend (either RabbitMQ or Redis) for Celeryd. 32 | # We recommend redis. 33 | CELERY_BACKEND_URL = 'redis://localhost:6379/0' 34 | # An address to listen on 35 | ADDRESS = '0.0.0.0' 36 | PORT = 5000 37 | # True if the server should run in debugging mode (give tracebacks, etc). 38 | # THIS MUST BE FALSE ON A PRODUCTION SERVER 39 | DEBUG = True 40 | # This says that we should generate the default nginx configuration. 41 | GENERATE_NGINX_DEFAULT = False 42 | -------------------------------------------------------------------------------- /manage.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ProgName=$(basename $0) 4 | 5 | sub_help(){ 6 | echo "Usage: $ProgName [options]\n" 7 | echo "Subcommands:" 8 | echo " regenerate Regenerate the configuration files for nginx" 9 | echo " changepw Changes the password for the ckan-multisite admin." 10 | echo "" 11 | } 12 | 13 | sub_regenerate() { 14 | python -c "from ckan_multisite.router import nginx;nginx.regenerate_config()" 15 | } 16 | 17 | sub_changepw() { 18 | password="" 19 | password_confirm="n" 20 | while [ "$password" != "$password_confirm" ]; do 21 | read -s -p "Please enter the admin user password you wish to use: " password 22 | echo 23 | read -s -p "Please confirm the password: " password_confirm 24 | echo 25 | done 26 | pw_hash=$(python -c "from ckan_multisite.pw import encrypt; print encrypt('$password')" | sed -e 's/[\/&]/\\&/g') 27 | if [ $? != 0 ]; then 28 | echo 'Python failed. See above output. Could not change pw.' 29 | exit 1 30 | fi 31 | sed -i "s/.*ADMIN_PW.*/ADMIN_PW= '$pw_hash'/gw changes.txt" ckan_multisite/config.py 32 | if [ -s changes.txt ]; then 33 | echo 'Password changed successfully.' 34 | rm changes.txt 35 | else 36 | echo 'Pattern not found. Cannot change.' 37 | rm changes.txt 38 | exit 1 39 | fi 40 | } 41 | 42 | 43 | source virtualenv/bin/activate 44 | 45 | subcommand=$1 46 | case $subcommand in 47 | "" | "-h" | "--help") 48 | sub_help 49 | ;; 50 | *) 51 | shift 52 | sub_${subcommand} $@ 53 | if [ $? = 127 ]; then 54 | echo "Error: '$subcommand' is not a known subcommand." >&2 55 | echo " Run '$ProgName --help' for a list of known subcommands." >&2 56 | exit 1 57 | fi 58 | ;; 59 | esac 60 | -------------------------------------------------------------------------------- /promoted.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ _("New DataCats Environment") }}

4 |

5 | {% trans %} 6 | Welcome to your new data catalog! 7 | Log in with the 8 | "admin" account password you created, then create a 9 | new dataset or a 10 | new organization. 11 | {% endtrans %} 12 |

13 |

14 | {% if g.site_title == "multisite" %} 15 | Welcome to a CKAN-multisite environment! As you can see, it's 16 | effectively a template, and you can customize it as much as 17 | you'd like at the sysadmin config panel in the top right (the 18 | little hammer). 19 | {% endif %} 20 |

21 |

22 | This is a new multisite environment. If you are the admin of this 23 | environment, you can look in the multisite/ckanext-multisitetheme 24 | directory and edit the templates to customize this site however 25 | you'd like! If you're having issues with this environment or the 26 | multisite administrative interface, visit the issues page 27 | and file an issue. We'll be glad to help you out! 28 |

29 |

30 | Otherwise, you should get your admin password set by the admin 31 | and then change the name of your site in the settings. 32 |

33 |
34 | 35 | {% block home_image %} 36 | 44 | {% endblock %} 45 |
46 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ ! -e "$PWD/run.sh" ]; then 4 | echo "This script must be run from the same directory as 'run.sh' in the ckan_multisite directory." 5 | exit 1 6 | fi 7 | 8 | if [ ! -e ./virtualenv ]; then 9 | read -p "This script will attempt to set up your server for use with CKAN multisite. We're making the assumption that you're running some Debian-based distro. If not, see manual instructions in the README.md. Please enter y if you'd like to continue, n otherwise: " -n 1 -r 10 | echo 11 | if [[ "$REPLY" =~ ^[Yy]$ ]]; then 12 | set -e 13 | sudo apt-get update -y && sudo apt-get upgrade -y 14 | sudo apt-get install -y python python-dev python-virtualenv redis-server nginx 15 | virtualenv virtualenv 16 | source virtualenv/bin/activate 17 | pip install -r requirements.txt 18 | python setup.py develop 19 | if ! command -v docker > /dev/null 2>&1; then 20 | wget -qO- https://get.docker.io/ | sh 21 | sudo usermod -aG docker $(whoami) 22 | fi 23 | sudo chown -R $(whoami): /etc/nginx/ 24 | sudostr="$(whoami) ALL=NOPASSWD: /usr/sbin/service nginx reload" 25 | echo $sudostr | sudo tee -a /etc/sudoers 26 | # Generate a secret key 27 | sed "s/#SECRET_.*/SECRET_KEY = '$(python -c 'import os;print os.urandom(20)' | base64 | sed -e 's/[\/&]/\\&/g')'/" ckan_multisite/config.py.template > ckan_multisite/config.py 28 | ./manage.sh changepw 29 | "${EDITOR:-nano}" ckan_multisite/config.py 30 | echo "Due to an unfortunate limitation in Linux (group addition doesn't take effect until you log out and in), you will need to log out and back in from your system and then run this script again." 31 | exit 0 32 | else 33 | echo "Please see instructions in README.md" 34 | exit 1 35 | fi 36 | fi 37 | 38 | source virtualenv/bin/activate 39 | 40 | set -xe 41 | 42 | if [ ! -e ~/.datacats/multisite ]; then 43 | datacats pull 44 | datacats create multisite -in 45 | cp promoted.html multisite/ckanext-multisitetheme/ckanext/multisitetheme/templates/home/snippets 46 | datacats reload multisite 47 | echo "You should now be all set up to use CKAN multisite." 48 | fi 49 | 50 | redis-server redis.conf 51 | celery -A ckan_multisite.task worker & 52 | trap "kill $!" EXIT 53 | 54 | if [ "$1" == "prod" ]; then 55 | uwsgi --ini uwsgi.ini 56 | else 57 | python ckan_multisite/app.py 58 | fi 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ckan-multisite 2 | Administrator interface and tools for managing CKAN Data Catalogs 3 | 4 | (under development) 5 | 6 | ![ckan-multisite overview](diagrams/ckan-multisite.png) 7 | 8 | ckan-multisite includes three main components: 9 | 10 | 1. HTTP router 11 | 2. Multisite admin 12 | 3. [datacats](https://github.com/boxkite/datacats) 13 | 14 | To use this project you must have a wildcard domain configured 15 | e.g. `*.mysite.mydomain` that will route visitors to your server. 16 | For development you may add static entries in your /etc/hosts file. 17 | 18 | ## HTTP router 19 | 20 | ckan-multisite includes nginx configuration that will route incoming 21 | connections on port 80 to the multisite admin application or to one 22 | of many CKAN sites on the same server. 23 | 24 | ## multisite admin 25 | 26 | The multisite admin application is a flask application that may be 27 | used to: 28 | 29 | 1. create ckan instances 30 | 2. remove ckan instances 31 | 3. reset admin passwords 32 | 33 | These are implemented by using 34 | [datacats](https://github.com/boxkite/datacats) 35 | as a library to manage all the necessary docker containers 36 | and issue commands within those containers 37 | 38 | ## datacats environment 39 | 40 | The default datacats environment includes many of the common ckan 41 | extensions and a safe default configuration. This same environment 42 | is used for all CKAN sites created by ckan-multisite. 43 | 44 | You may replace the configuration, and extensions on your server 45 | with a new datacats environment that suits your organization's needs. 46 | 47 | For more information about using datacats environments, see the 48 | [datacats documentation](http://docs.datacats.com/). 49 | 50 | ## Setup 51 | 52 | Recommended specifications for a server running CKAN-Multisite are 53 | a fresh Ubuntu 14.04 Server machine. For this supported platform we 54 | have developed an automated installation script. This script should 55 | run if you execute the ``run.sh`` script in the root directory of 56 | this repository. It will create a virtualenv and install various 57 | packages that are required for the operation of multisite itself. 58 | 59 | If you wish to do a manual install of CKAN-multisite, the run.sh 60 | script is fairly self-documenting and you should be able to read 61 | through it and get a good idea of what needs to be installed and 62 | set up. 63 | 64 | ## License 65 | 66 | This software is licensed under the MIT license, but incorporates 67 | software from boxkite (datacats) and Open Knowledge (ckan) 68 | which are released under the terms of the AGPLv3 license. 69 | -------------------------------------------------------------------------------- /ckan_multisite/site.py: -------------------------------------------------------------------------------- 1 | from ckan_multisite.config import MAIN_ENV_NAME, DATACATS_DIRECTORY 2 | 3 | from datacats.environment import Environment 4 | 5 | from os import listdir, mkdir 6 | from os.path import join as path_join, expanduser, exists 7 | 8 | from bisect import insort_left 9 | 10 | from router import nginx 11 | 12 | MULTISITE_CONFIG_NAME = '.multisite-config' 13 | 14 | SITES_PATH = expanduser(path_join(DATACATS_DIRECTORY, MAIN_ENV_NAME, 'sites')) 15 | 16 | def get_sites(): 17 | if not exists(path_join(DATACATS_DIRECTORY)): 18 | mkdir(path_join(DATACATS_DIRECTORY)) 19 | dcats_listing = listdir(SITES_PATH) 20 | sites = [] 21 | # Primary child isn't mean for them 22 | if 'primary' in dcats_listing: 23 | dcats_listing.remove('primary') 24 | for s in dcats_listing: 25 | # Since Flask-admin does things in unicode convert to unicode strings for 26 | config_path = path_join(SITES_PATH, s, MULTISITE_CONFIG_NAME) 27 | if not exists(config_path): 28 | print 'Making up a name for site {}: {}'.format(s, s.capitalize()) 29 | with open(config_path, 'w') as wf: 30 | wf.write(s.capitalize()) 31 | with open(config_path) as f: 32 | sites.append(Site(unicode(s), f.read(), sort=False)) 33 | 34 | # Sort the list initially 35 | sites.sort() 36 | 37 | return sites 38 | 39 | def site_by_name(name): 40 | return next(site for site in get_sites() if site.name == name) 41 | 42 | class Site(object): 43 | def __init__(self, name, display_name, finished_create=True, sort=True): 44 | """ 45 | Initializes a site object. Also places it into the global `sites` list. 46 | 47 | :param name: The name of the site to be created. 48 | :param display_name: The name of the site to be shown to the user. 49 | :param sort: True if we should maintain the sorted order of the `sites` list. 50 | For all uses except internal ones this should ALWAYS be True or 51 | Bad Things Will Happen (TM). 52 | """ 53 | self.name = name 54 | self.display_name = display_name 55 | self.environment = Environment.load(MAIN_ENV_NAME, name) 56 | self.port = self.environment.port 57 | self.finished_create = finished_create 58 | self.celery_task = None 59 | 60 | def __repr__(self): 61 | return self.name.__repr__() 62 | 63 | def __eq__(self, site): 64 | return (hasattr(site, 'name') and site.name == self.name) or site == self.name 65 | 66 | def __lt__(self, site): 67 | return self.name < site.name 68 | 69 | def serialize_display_name(self): 70 | config_path = path_join(SITES_PATH, self.name, MULTISITE_CONFIG_NAME) 71 | with open(config_path, 'w') as f: 72 | f.write(self.display_name) 73 | 74 | 75 | def __gt__(self, site): 76 | return self.name > site.name 77 | 78 | -------------------------------------------------------------------------------- /ckan_multisite/static/edit.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | // Does a ajax request to the ckan-multisite API 3 | function simple_api_request(endpoint, success, failure, method, params) { 4 | $("html").css("cursor", "wait"); 5 | if (success == undefined) { 6 | success = function (data) { 7 | $("#alert_field").text(data.success); 8 | $("#alert_field").removeClass('hidden'); 9 | $("html").css("cursor", "auto"); 10 | }; 11 | } 12 | if (failure == undefined) { 13 | failure = function (data) { 14 | $("#alert_field").text("Error: " + data.responseJSON.error); 15 | $("#alert_field").removeClass('hidden'); 16 | $("html").css("cursor", "auto"); 17 | }; 18 | } 19 | if (params == undefined) { 20 | params = {name: $("#site_name").val()} 21 | } 22 | if (method == undefined) { 23 | method = 'POST'; 24 | } 25 | 26 | $.ajax({ 27 | type: "POST", 28 | url: "/api/v1/" + endpoint, 29 | data: params, 30 | success: success, 31 | error: failure 32 | }); 33 | } 34 | 35 | $("#start_button").click(function () { 36 | simple_api_request("start"); 37 | }); 38 | 39 | $("#stop_button").click(function () { 40 | simple_api_request("stop"); 41 | }); 42 | 43 | $("#status_button").click(function () { 44 | simple_api_request("status", function (data) { 45 | $("#alert_field").text("Default port: " + data.default_port + " Containers Running: " + data.containers_running); 46 | $("#alert_field").removeClass('hidden'); 47 | $("html").css("cursor", "auto"); 48 | }) 49 | }); 50 | 51 | function submit_pw_form(event) { 52 | // Stop form submission via HTTP 53 | event.preventDefault(); 54 | // First we validate the form 55 | group = $("#pw_control_group"); 56 | pw = $("#pw"); 57 | confirm_pw = $("#confirm_pw"); 58 | error_label = $("#pw_error_label"); 59 | 60 | if (pw.val() != confirm_pw.val()) { 61 | group.addClass("error"); 62 | error_label.text("Password and confirm must match."); 63 | } 64 | else if (pw.val() == "" || confirm_pw.val() == "") { 65 | group.addClass("error"); 66 | error_label.text("Passwords cannot be blank."); 67 | } 68 | else if (pw.val().length < 4) { 69 | group.addClass("error"); 70 | error_label.text("Passwords must be more than 4 characters"); 71 | } 72 | else { 73 | // Remove error class and error if no error 74 | group.removeClass("error"); 75 | error_label.text(""); 76 | simple_api_request("change_admin", undefined, undefined, undefined, {name: $("#site_name").val(), password: pw.val()}); 77 | } 78 | } 79 | 80 | $("#reset_pw_button").click(submit_pw_form); 81 | $("#pw,#confirm_pw").keypress(function(event) { 82 | // Enter key 83 | if (event.which == 13) { 84 | submit_pw_form(event); 85 | } 86 | }); 87 | 88 | function enable_buttons() { 89 | $('#status_button,#pw,#confirm_pw,#reset_pw_button,#start_button,#stop_button,#display_name').removeAttr('disabled') 90 | } 91 | 92 | function disable_buttons() { 93 | $('#status_button,#pw,#confirm_pw,#reset_pw_button,#start_button,#stop_button,#display_name').prop('disabled', 'true') 94 | } 95 | 96 | 97 | function poll_create_done() { 98 | simple_api_request("is_site_ready", function (data) { 99 | if (data.ready) { 100 | enable_buttons(); 101 | $("html").css("cursor", "auto"); 102 | } 103 | else { 104 | setTimeout(poll_create_done, 3000); 105 | } 106 | }); 107 | } 108 | 109 | if ($('#finished_create').val() !== "True") { 110 | disable_buttons(); 111 | poll_create_done(); 112 | } 113 | }); 114 | -------------------------------------------------------------------------------- /ckan_multisite/admin.py: -------------------------------------------------------------------------------- 1 | from flask.ext.admin import Admin 2 | from flask.ext.admin.model import BaseModelView 3 | from flask.ext.admin.model.fields import ListEditableFieldList 4 | from flask.ext.admin.form import BaseForm 5 | from flask.ext.admin import AdminIndexView, expose 6 | 7 | from flask import url_for, request, redirect 8 | 9 | from wtforms import TextField, validators 10 | 11 | from datacats.environment import Environment 12 | from datacats.validate import DATACATS_NAME_RE 13 | 14 | from ckan_multisite.site import Site, get_sites 15 | from ckan_multisite.router import nginx 16 | from ckan_multisite.config import MAIN_ENV_NAME 17 | from ckan_multisite.task import create_site_task, remove_site_task 18 | from ckan_multisite.pw import check_login_cookie 19 | 20 | from ckan_multisite import config 21 | 22 | class MultisiteHomeView(AdminIndexView): 23 | def is_accessible(self): 24 | return False 25 | @expose('/') 26 | def index(self): 27 | return redirect('/admin/site') 28 | 29 | admin = Admin(index_view=MultisiteHomeView()) 30 | 31 | class SiteAddForm(BaseForm): 32 | name = TextField('Site name', [ 33 | validators.Length(min=4, max=25), 34 | validators.Required(), 35 | validators.Regexp(DATACATS_NAME_RE, message='Names must be composed of all lowercase letters and numbers, and start with a lowercase letter.')]) 36 | display_name = TextField('Display Name', [ 37 | validators.Required() 38 | ]) 39 | 40 | class SiteEditForm(BaseForm): 41 | display_name = TextField('Display name', [ 42 | validators.Required() 43 | ]) 44 | 45 | # Auth is handled by HTTP 46 | # A lot of the class-members are magic things from BaseModelView 47 | class SitesView(BaseModelView): 48 | def __init__(self): 49 | super(SitesView, self).__init__(Site) 50 | 51 | def is_accessible(self): 52 | return True 53 | 54 | def _handle_view(self, name, **kwargs): 55 | if not check_login_cookie(): 56 | return redirect(url_for('login.login', next=request.url), code=302) 57 | 58 | def delete_model(self, site): 59 | remove_site_task.apply_async(args=(site,)) 60 | return True 61 | 62 | def create_model(self, form): 63 | # Sites start not having their data finished. 64 | site = Site(form.name.data, form.display_name.data, finished_create=False) 65 | result = create_site_task.apply_async(args=(site,)) 66 | site.result = result 67 | return site 68 | 69 | def update_model(self, form, site): 70 | if form.display_name.data != site.display_name: 71 | site.display_name = form.display_name.data 72 | site.serialize_display_name() 73 | nginx.update_site(site) 74 | 75 | def get_list(self, page, sort_field, sort_desc, search, filters): 76 | print 'HELLO {}'.format(get_sites()) 77 | # `page` is zero-based 78 | if not sort_field: 79 | sort_field = 'name' 80 | 81 | page_start = page*SitesView.page_size 82 | page_end = page_start + SitesView.page_size 83 | slice_unsorted = get_sites()[page_start:page_end] 84 | slice_sorted = sorted( 85 | slice_unsorted, 86 | # Magic to get a specific sort field out of a site 87 | key=lambda s: getattr(s, sort_field), 88 | reverse=sort_desc) 89 | 90 | return len(slice_sorted), slice_sorted 91 | 92 | def get_one(self, id): 93 | # ids come in as strs (unicode) 94 | return get_sites()[int(id)] if int(id) < len(get_sites()) else None 95 | 96 | def scaffold_form(self): 97 | return SiteAddForm 98 | 99 | def scaffold_list_columns(self): 100 | # List of tuples with form names and display names 101 | return column_list 102 | 103 | def scaffold_list_form(self, custom_fieldset=ListEditableFieldList, validators=None): 104 | # just have it so that it shows text 105 | return SiteAddForm 106 | 107 | def get_edit_form(self): 108 | return SiteEditForm 109 | 110 | def scaffold_sortable_columns(self): 111 | return dict(zip(SitesView.column_sortable_list, SitesView.column_sortable_list)) 112 | 113 | def get_pk_value(self, model): 114 | sites = get_sites() 115 | if model in sites: 116 | return sites.index(model) 117 | else: 118 | return None 119 | 120 | column_list = ['name', 'display_name'] 121 | column_label = {'name': 'Name', 'display_name': 'Display Name'} 122 | column_sortable_list = column_list 123 | column_searchable_list = column_list 124 | column_editable_list = [] 125 | edit_template = 'edit.html' 126 | form_columns = column_list 127 | column_default_sort = 'name' 128 | list_template = 'list.html' 129 | create_template = 'create.html' 130 | 131 | admin.add_view(SitesView()) 132 | -------------------------------------------------------------------------------- /ckan_multisite/static/main.css: -------------------------------------------------------------------------------- 1 | .hidden { 2 | display: none; 3 | } 4 | 5 | .btn-large { 6 | padding: 5px; 7 | font-size: 12px; 8 | -webkit-border-radius: 6px; 9 | -moz-border-radius: 6px; 10 | border-radius: 6px; 11 | } 12 | 13 | body { 14 | padding-top: 6em; 15 | background-color: #fff; 16 | font-family: 'Roboto', sans-serif; 17 | text-rendering: optimizeLegibility; 18 | -webkit-font-smoothing: antialiased; 19 | -moz-osx-font-smoothing: grayscale; 20 | width:100%; 21 | } 22 | 23 | .navbar { 24 | position: fixed; 25 | width:100%; 26 | top:0; 27 | left:0; 28 | right:0; 29 | color:#fff; 30 | } 31 | 32 | .navbar-inner { 33 | min-height: 50px; 34 | padding-left:10em; 35 | padding-top: 1em; 36 | background-color: #3B404E; 37 | color:#fff; 38 | background-image: none; 39 | /*background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2)); 40 | background-image: -webkit-linear-gradient(top, #ffffff, #f2f2f2); 41 | background-image: -o-linear-gradient(top, #ffffff, #f2f2f2); 42 | background-image: linear-gradient(to bottom, #ffffff, #f2f2f2);*/ 43 | background-repeat: no-repeat; 44 | border: none; 45 | -webkit-border-radius: 0px; 46 | -moz-border-radius: 0px; 47 | border-radius: 0px; 48 | -webkit-box-shadow: none; 49 | -moz-box-shadow:none; 50 | box-shadow: none; 51 | } 52 | 53 | .navbar .brand { 54 | display: block; 55 | float: left; 56 | padding: 10px 20px 10px; 57 | margin-left: -20px; 58 | font-size: 20px; 59 | font-weight: 200; 60 | color: #fff; 61 | text-shadow: none; 62 | border-right:1px solid #e4e4e4; 63 | } 64 | 65 | .navbar .nav > li > a { 66 | font-size: 18px; 67 | font-weight: 700; 68 | float: none; 69 | padding: 11px 20px 10px; 70 | color: #fff; 71 | text-decoration: none; 72 | text-shadow: none; 73 | transition:all 150ms linear; 74 | } 75 | 76 | .navbar .nav > .active > a:hover { 77 | color:#EEF0EA; 78 | text-decoration: none; 79 | background-color: #3B404E; 80 | -webkit-box-shadow: none; 81 | -moz-box-shadow: none; 82 | box-shadow: none; 83 | 84 | } 85 | 86 | .navbar .nav > .active > a, 87 | .navbar .nav > .active > a:focus { 88 | color: #DFBDA3; 89 | text-decoration: none; 90 | background-color: #3B404E; 91 | -webkit-box-shadow: none; 92 | -moz-box-shadow: none; 93 | box-shadow: none; 94 | } 95 | 96 | .env { 97 | font-size: 1.5em; 98 | margin: 1.5em 0; 99 | } 100 | 101 | button { 102 | background-color: #3B404E; 103 | border:none; 104 | padding:.5em 1em; 105 | margin-right: 1em; 106 | border-radius: 5px; 107 | font-weight: 700; 108 | color:#fff; 109 | transition:all 150ms linear; 110 | } 111 | 112 | #start_button { 113 | margin-left: 1em; 114 | } 115 | 116 | #start_button:hover { 117 | background-color: #667D5F; 118 | 119 | } 120 | 121 | #stop_button:hover { 122 | background-color: #BD362F; 123 | 124 | } 125 | 126 | #status_button:hover { 127 | background-color: #686A75; 128 | 129 | } 130 | 131 | #reset_pw_button:hover { 132 | background-color: #59857A; 133 | 134 | } 135 | 136 | .btn-primary { 137 | color: #ffffff; 138 | text-shadow: none; 139 | background-color: #006dcc; 140 | background-image: none; 141 | background-repeat: no-repeat; 142 | border-color: none; 143 | filter: progid:none; 144 | transition:all 150ms linear; 145 | } 146 | .btn { 147 | display: inline-block; 148 | padding: .5em 1em; 149 | margin-bottom: 0; 150 | margin-right: .75em; 151 | font-size: 14px; 152 | font-weight: 700; 153 | line-height: 20px; 154 | color: #fff; 155 | text-align: center; 156 | text-shadow: none; 157 | vertical-align: middle; 158 | cursor: pointer; 159 | background-color: #3B404E; 160 | background-image: none; 161 | background-repeat: no-repeat; 162 | border: 1px solid #3B404E; 163 | filter: none; 164 | box-shadow: none; 165 | transition:all 150ms linear; 166 | } 167 | 168 | .nav-tabs { 169 | margin-top: 4em; 170 | } 171 | 172 | .nav-tabs > .active > a, 173 | .nav-tabs > .active > a:hover, 174 | .nav-tabs > .active > a:focus { 175 | color: #fff; 176 | font-weight: 700; 177 | cursor: default; 178 | background-color: #58A3BA; 179 | border: none; 180 | border-bottom:none; 181 | padding: .5em 2em; 182 | 183 | } 184 | 185 | thead { 186 | background-color: #58A3BA; 187 | color:#fff; 188 | } 189 | 190 | thead a { 191 | color:#fff; 192 | transition:all 150ms linear; 193 | } 194 | 195 | thead a:hover { 196 | text-decoration: none; 197 | color:#EDE1B9; 198 | } 199 | .nav-tabs > li > a { 200 | padding-top: 8px; 201 | padding-bottom: 8px; 202 | line-height: 20px; 203 | border: none; 204 | -webkit-border-radius: 4px 4px 0 0; 205 | -moz-border-radius: 4px 4px 0 0; 206 | border-radius: 4px 4px 0 0; 207 | } 208 | 209 | .fa { 210 | margin-left: 5px; 211 | } -------------------------------------------------------------------------------- /development.ini: -------------------------------------------------------------------------------- 1 | # 2 | # CKAN - Pylons configuration 3 | # 4 | # These are some of the configuration options available for your CKAN 5 | # instance. Check the documentation in 'doc/configuration.rst' or at the 6 | # following URL for a description of what they do and the full list of 7 | # available options: 8 | # 9 | # http://docs.ckan.org/en/latest/maintaining/configuration.html 10 | # 11 | # The %(here)s variable will be replaced with the parent directory of this file 12 | # 13 | 14 | [DEFAULT] 15 | 16 | # WARNING: *THIS SETTING MUST BE SET TO FALSE ON A PRODUCTION ENVIRONMENT* 17 | debug = false 18 | 19 | [server:main] 20 | use = egg:Paste#http 21 | host = 0.0.0.0 22 | port = 5000 23 | 24 | [app:main] 25 | use = egg:ckan 26 | full_stack = true 27 | cache_dir = /tmp/%(ckan.site_id)s/ 28 | beaker.session.key = ckan 29 | 30 | # This is the secret token that the beaker library uses to hash the cookie sent 31 | # to the client. `paster make-config` generates a unique value for this each 32 | # time it generates a config file. 33 | beaker.session.secret = NMTSSHp3nAuwOsOfI+JwDu2tE 34 | 35 | # `paster make-config` generates a unique value for this each time it generates 36 | # a config file. 37 | app_instance_uuid = {84a7cef8-83aa-46e3-bdd5-a280136f80a2} 38 | 39 | # repoze.who config 40 | who.config_file = %(here)s/who.ini 41 | who.log_level = warning 42 | who.log_file = %(cache_dir)s/who_log.ini 43 | # Session timeout (user logged out after period of inactivity, in seconds). 44 | # Inactive by default, so the session doesn't expire. 45 | # who.timeout = 86400 46 | 47 | ## Database Settings 48 | sqlalchemy.url = postgresql:// 49 | 50 | ckan.datastore.write_url = postgresql:// 51 | ckan.datastore.read_url = postgresql:// 52 | 53 | # PostgreSQL' full-text search parameters 54 | ckan.datastore.default_fts_lang = english 55 | ckan.datastore.default_fts_index_method = gist 56 | 57 | ## Site Settings 58 | 59 | ckan.site_url = 60 | 61 | 62 | ## Authorization Settings 63 | 64 | ckan.auth.anon_create_dataset = false 65 | ckan.auth.create_unowned_dataset = true 66 | ckan.auth.create_dataset_if_not_in_organization = true 67 | ckan.auth.user_create_groups = true 68 | ckan.auth.user_create_organizations = true 69 | ckan.auth.user_delete_groups = true 70 | ckan.auth.user_delete_organizations = true 71 | ckan.auth.create_user_via_api = false 72 | ckan.auth.create_user_via_web = false 73 | ckan.auth.roles_that_cascade_to_sub_groups = admin 74 | 75 | 76 | ## Search Settings 77 | 78 | ckan.site_id = default 79 | solr_url = http://solr:8080/solr 80 | 81 | #ckan.simple_search = 1 82 | 83 | 84 | ## CORS Settings 85 | 86 | # If cors.origin_allow_all is true, all origins are allowed. 87 | # If false, the cors.origin_whitelist is used. 88 | # ckan.cors.origin_allow_all = true 89 | # cors.origin_whitelist is a space separated list of allowed domains. 90 | # ckan.cors.origin_whitelist = http://example1.com http://example2.com 91 | 92 | 93 | ## Plugins Settings 94 | 95 | # Note: Add ``datastore`` to enable the CKAN DataStore 96 | # Add ``datapusher`` to enable DataPusher 97 | # Add ``resource_proxy`` to enable resorce proxying and get around the 98 | # same origin policy 99 | ckan.plugins = datastore resource_proxy text_view datapusher recline_grid_view recline_graph_view multisite_theme 100 | 101 | # Define which views should be created by default 102 | # (plugins must be loaded in ckan.plugins) 103 | ckan.views.default_views = image_view text_view recline_view 104 | 105 | 106 | ## Front-End Settings 107 | ckan.site_title = A Multisite Site 108 | ckan.site_logo = 109 | ckan.site_description = 110 | ckan.favicon = /images/icons/ckan.ico 111 | ckan.gravatar_default = identicon 112 | ckan.preview.direct = png jpg gif 113 | ckan.preview.loadable = html htm rdf+xml owl+xml xml n3 n-triples turtle plain atom csv tsv rss txt json 114 | 115 | # package_hide_extras = for_search_index_only 116 | #package_edit_return_url = http://another.frontend/dataset/ 117 | #package_new_return_url = http://another.frontend/dataset/ 118 | #ckan.recaptcha.publickey = 119 | #ckan.recaptcha.privatekey = 120 | #licenses_group_url = http://licenses.opendefinition.org/licenses/groups/ckan.json 121 | # ckan.template_footer_end = 122 | 123 | 124 | ## Internationalisation Settings 125 | ckan.locale_default = en 126 | ckan.locale_order = en pt_BR ja it cs_CZ ca es fr el sv sr sr@latin no sk fi ru de pl nl bg ko_KR hu sa sl lv 127 | ckan.locales_offered = 128 | ckan.locales_filtered_out = en_GB 129 | 130 | ## Feeds Settings 131 | 132 | ckan.feeds.authority_name = 133 | ckan.feeds.date = 134 | ckan.feeds.author_name = 135 | ckan.feeds.author_link = 136 | 137 | ## Storage Settings 138 | 139 | ckan.storage_path = /var/www/storage 140 | #ckan.max_resource_size = 10 141 | #ckan.max_image_size = 2 142 | 143 | ## Datapusher settings 144 | 145 | # Make sure you have set up the DataStore 146 | 147 | #ckan.datapusher.formats = csv xls xlsx tsv application/csv application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 148 | ckan.datapusher.url = http://datapusher:8800 149 | 150 | # Resource Proxy settings 151 | # Preview size limit, default: 1MB 152 | #ckan.resource_proxy.max_file_size = 1 * 1024 * 1024 153 | 154 | ## Activity Streams Settings 155 | 156 | #ckan.activity_streams_enabled = true 157 | #ckan.activity_list_limit = 31 158 | #ckan.activity_streams_email_notifications = true 159 | #ckan.email_notifications_since = 2 days 160 | ckan.hide_activity_from_users = %(ckan.site_id)s 161 | 162 | 163 | ## Email settings 164 | 165 | #email_to = you@yourdomain.com 166 | #error_email_from = paste@localhost 167 | #smtp.server = localhost 168 | #smtp.starttls = False 169 | #smtp.user = your_username@gmail.com 170 | #smtp.password = your_password 171 | #smtp.mail_from = 172 | 173 | 174 | ## Logging configuration 175 | [loggers] 176 | keys = root, ckan, ckanext 177 | 178 | [handlers] 179 | keys = console 180 | 181 | [formatters] 182 | keys = generic 183 | 184 | [logger_root] 185 | level = WARNING 186 | handlers = console 187 | 188 | [logger_ckan] 189 | level = INFO 190 | handlers = console 191 | qualname = ckan 192 | propagate = 0 193 | 194 | [logger_ckanext] 195 | level = DEBUG 196 | handlers = console 197 | qualname = ckanext 198 | propagate = 0 199 | 200 | [handler_console] 201 | class = StreamHandler 202 | args = (sys.stderr,) 203 | level = NOTSET 204 | formatter = generic 205 | 206 | [formatter_generic] 207 | format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s 208 | -------------------------------------------------------------------------------- /ckan_multisite/api.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Boxkite Inc. 2 | 3 | # This file is part of the ckan-multisite package and is released 4 | # under the terms of the MIT License. 5 | # See LICENSE or http://opensource.org/licenses/MIT 6 | 7 | from ckan_multisite.router import DatacatsNginxConfig 8 | from ckan_multisite.config import MAIN_ENV_NAME 9 | from ckan_multisite.task import create_site_task, remove_site_task 10 | from ckan_multisite.site import site_by_name, Site 11 | 12 | from flask import Blueprint, request, jsonify 13 | from datacats.environment import Environment, DatacatsError 14 | 15 | from os.path import isdir, expanduser, join 16 | from functools import wraps 17 | 18 | MAIN_DATADIR_PATH = join(expanduser('~'), '.datacats', MAIN_ENV_NAME) 19 | # HTTP status for when THEY messed up 20 | CLIENT_ERROR_CODE = 409 21 | # HTTP status for when WE messed up 22 | SERVER_ERROR_CODE = 500 23 | 24 | bp = Blueprint('api', __name__, template_folder='templates') 25 | 26 | 27 | def api_has_parameters(*keys): 28 | """ 29 | Decorator that ensures that certain parameters exist and have sensible 30 | values (i.e. not empty, not None). If one of the keys isn't in the request 31 | parameters, an error will be returned. 32 | 33 | :param f: The function to be decorated 34 | """ 35 | def decorator(func): 36 | @wraps(func) 37 | def wrapper(*f_args): 38 | if all([key in request.values and request.values[key] 39 | for key in keys]): 40 | # Let the function deal with it - valid 41 | return func(*f_args) 42 | else: 43 | return jsonify({ 44 | 'error': 'One or more parameters missing. ' 45 | 'Required parameters are: {}, supplied: {}' 46 | .format(list(keys), request.values) 47 | }), CLIENT_ERROR_CODE 48 | 49 | return wrapper 50 | 51 | return decorator 52 | 53 | 54 | def env_must_exist(func): 55 | """ 56 | Wraps a Flask endpoint function and ensures that the main environment 57 | exists. 58 | """ 59 | @wraps(func) 60 | def _check(*f_args): 61 | if isdir(MAIN_DATADIR_PATH): 62 | return func(*f_args) 63 | else: 64 | return jsonify({ 65 | 'error': 'Environment {} doesn\'t exist. Please follow setup ' 66 | 'instructions.'.format(MAIN_ENV_NAME) 67 | }), CLIENT_ERROR_CODE 68 | return _check 69 | 70 | 71 | def datacats_api_command(require_valid_site=False, *keys): 72 | """ 73 | Wraps a function with safety measures to report a DatacatsError 74 | back in a 409 response. 75 | 76 | :param requires_valid_site True if an endpoint requires a site to exist 77 | for it to be able to work. 78 | :param keys List of arguments that are required for this 79 | environment shouldn't operate. 80 | """ 81 | def decorator(func): 82 | @wraps(func) 83 | @api_has_parameters(*keys) 84 | @env_must_exist 85 | def wrapper(): 86 | if 'name' not in request.values: 87 | site_name = 'primary' 88 | else: 89 | site_name = request.values.get('name') 90 | 91 | try: 92 | environment = Environment.load(MAIN_ENV_NAME, site_name) 93 | 94 | if require_valid_site: 95 | environment.require_valid_site() 96 | 97 | return func(environment) 98 | except DatacatsError as e: 99 | return jsonify({'error': str(e)}), CLIENT_ERROR_CODE 100 | return wrapper 101 | return decorator 102 | 103 | 104 | @bp.route('/api/v1/create', methods=['POST']) 105 | @datacats_api_command(False, 'name') 106 | def make_site(environment): 107 | site = Site(environment.site_name, finished_create=False) 108 | create_site_task.apply_async(args=(site,)) 109 | return jsonify({'success': 'Multisite environment {} created.' 110 | .format(environment.site_name)}) 111 | 112 | 113 | @bp.route('/api/v1/start', methods=['POST']) 114 | @datacats_api_command(True, 'name') 115 | def start_site(environment): 116 | environment.start_supporting_containers() 117 | environment.start_ckan(production=True) 118 | 119 | return jsonify({'success': 'Multisite environment {} started.' 120 | .format(environment.site_name)}) 121 | 122 | 123 | 124 | @bp.route('/api/v1/purge', methods=['POST']) 125 | @datacats_api_command(True, 'name') 126 | def purge_site(environment): 127 | remove_site_task.apply_async(args=(site_by_name(environment.site_name),)) 128 | return jsonify({'success': 'Multisite environment {} purged.' 129 | .format(environment.site_name)}) 130 | 131 | 132 | @bp.route('/api/v1/stop', methods=['POST']) 133 | @datacats_api_command(True, 'name') 134 | def stop_site(environment): 135 | environment.stop_ckan() 136 | environment.stop_supporting_containers() 137 | 138 | return jsonify({'success': 'Multisite environment {} stopped.' 139 | .format(environment.site_name)}) 140 | 141 | 142 | @bp.route('/api/v1/status', methods=['POST']) 143 | @datacats_api_command(True, 'name') 144 | def site_status(environment): 145 | return jsonify({ 146 | 'default_port': str(environment.port), 147 | 'name': environment.site_name, 148 | 'containers_running': ' '.join(environment.containers_running()) 149 | }) 150 | 151 | 152 | @bp.route('/api/v1/is_site_ready', methods=['POST']) 153 | @datacats_api_command(False, 'name') 154 | def site_ready(environment): 155 | site = site_by_name(environment.site_name) 156 | if not site.result or site.result.ready(): 157 | site.finished_create = True 158 | else: 159 | site.finished_create = False 160 | 161 | return jsonify({'ready': site_by_name(environment.site_name).finished_create}) 162 | 163 | 164 | @bp.route('/api/v1/list', methods=['GET']) 165 | @datacats_api_command() 166 | def list_sites(environment): 167 | return jsonify({'sites': environment.sites}) 168 | 169 | @bp.route('/api/v1/change_admin', methods=['POST']) 170 | @datacats_api_command(True, 'name', 'password') 171 | def change_admin_pw(environment): 172 | temp_start = 'postgres' not in environment.containers_running() 173 | if temp_start: 174 | environment.start_supporting_containers() 175 | try: 176 | environment.create_admin_set_password(request.values['password']) 177 | finally: 178 | if temp_start: 179 | environment.stop_supporting_containers() 180 | return jsonify({'success': 'Admin password successfully changed.'}) 181 | -------------------------------------------------------------------------------- /ckan_multisite/router.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 Boxkite Inc. 2 | 3 | # This file is part of the ckan-multisite package and is released 4 | # under the terms of the MIT License. 5 | # See LICENSE or http://opensource.org/licenses/MIT 6 | 7 | """ 8 | A library which allows for the creation and modification of 9 | nginx configuration files related to datacats sites. 10 | """ 11 | 12 | from ckan_multisite import config 13 | from ckan_multisite.config import MAIN_ENV_NAME, DEBUG, PORT 14 | try: 15 | from ckan_multisite.config import GENERATE_NGINX_DEFAULT 16 | except ImportError: 17 | GENERATE_NGINX_DEFAULT = True 18 | from os import symlink 19 | from os.path import exists 20 | import subprocess 21 | 22 | REDIRECT_TEMPLATE = """server {{ 23 | listen 80; 24 | server_name {site_name}.{hostname}; 25 | 26 | location / {{ 27 | proxy_pass http://127.0.0.1:{site_port}; 28 | proxy_set_header Host $host; 29 | proxy_set_header X-Real-IP $remote_addr; 30 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 31 | proxy_set_header X-Forwarded-Proto $scheme; 32 | }} 33 | }} 34 | """ 35 | 36 | if not DEBUG: 37 | DEFAULT_TEMPLATE = """server {{ 38 | listen 80; 39 | server_name {hostname}; 40 | 41 | location / {{ 42 | try_files $uri @ckan_multisite; 43 | }} 44 | 45 | location @ckan_multisite {{ 46 | include uwsgi_params; 47 | uwsgi_pass unix:/tmp/uwsgi.sock; 48 | }} 49 | }} 50 | """ 51 | else: 52 | # Template for proxy passing (i.e. flask server) 53 | DEFAULT_TEMPLATE = """server {{ 54 | listen 80; 55 | server_name {hostname}; 56 | 57 | location / {{ 58 | proxy_pass http://127.0.0.1:""" + str(PORT) + """; 59 | proxy_set_header Host $host; 60 | proxy_set_header X-Real-IP $remote_addr; 61 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 62 | proxy_set_header X-Forwarded-Proto $scheme; 63 | }} 64 | }} 65 | """ 66 | 67 | from os import listdir, remove 68 | from os.path import join as path_join, exists 69 | 70 | from datacats.environment import Environment 71 | 72 | NGINX_CONFIG_DIR = path_join('/', 'etc', 'nginx') 73 | SITES_AVAILABLE_PATH = path_join(NGINX_CONFIG_DIR, 'sites-available') 74 | SITES_ENABLED_PATH = path_join(NGINX_CONFIG_DIR, 'sites-enabled') 75 | 76 | 77 | class DatacatsNginxConfig(object): 78 | def __init__(self, name): 79 | """ 80 | Reads configuration files for the given environment and 81 | initializes this object with it. 82 | 83 | :param name: The name of the environment we are working with. 84 | """ 85 | self.update_default() 86 | self.sync_with_fs() 87 | self.env_name = name 88 | # Make sure that Nginx is up to date with the directory. 89 | self.reload_nginx() 90 | 91 | def sync_with_fs(self): 92 | self.sites = listdir(SITES_AVAILABLE_PATH) 93 | self.sites.remove('default') 94 | 95 | def update_default(self): 96 | """ 97 | Updates the configuration of the nginx default site. 98 | """ 99 | if GENERATE_NGINX_DEFAULT: 100 | with open(_get_site_config_name('default'), 'w') as f: 101 | f.write(DEFAULT_TEMPLATE.format(hostname=config.HOSTNAME)) 102 | if not exists(_get_site_enabled_name('default')): 103 | symlink(_get_site_config_name('default'), _get_site_enabled_name('default')) 104 | 105 | def update_site(self, site): 106 | """ 107 | Recreates the configuration for a site. 108 | 109 | :param site: The site to recreate the configuration of. 110 | """ 111 | self.remove_site(site) 112 | self.add_site(site) 113 | 114 | def reload_nginx(self): 115 | # TODO: We should probably check that this succeeds 116 | # We can use sudo because of the weird sudoers hack in run.sh 117 | subprocess.call(['sudo', 'service', 'nginx', 'reload']) 118 | 119 | def add_site(self, site, port=None): 120 | """ 121 | Adds a configuration file to nginx to route a specific site 122 | 123 | :param site: The Site object to add. This is interpreted as 124 | a string if the port is specified and as a Site 125 | object if the port isn't specified. 126 | :param port: The port on which the environment is running, 127 | defaulting to asking the site object. 128 | """ 129 | self.sync_with_fs() 130 | if port: 131 | name = site 132 | else: 133 | name = site.name 134 | port = site.port 135 | 136 | text = REDIRECT_TEMPLATE.format( 137 | site_name=name, 138 | site_port=port, 139 | hostname=config.HOSTNAME) 140 | 141 | with open(_get_site_config_name(name), 'w') as config_file: 142 | config_file.write(text) 143 | self.sites.append(name) 144 | 145 | symlink(_get_site_config_name(name), _get_site_enabled_name(name)) 146 | self.reload_nginx() 147 | 148 | def remove_site(self, site): 149 | """ 150 | Removes a configuration file from the nginx configuration. 151 | 152 | :param site: The site to remove. This can weither be a string 153 | or a Site object, and this function will operate 154 | correctly. 155 | """ 156 | self.sync_with_fs() 157 | if hasattr(site, 'name'): 158 | name = site.name 159 | else: 160 | name = site 161 | if exists(_get_site_enabled_name(name)): 162 | remove(_get_site_enabled_name(name)) 163 | if exists(_get_site_config_name(name)): 164 | # Remove the site config itself and the enabled symlink 165 | remove(_get_site_config_name(name)) 166 | self.sites.remove(name) 167 | self.reload_nginx() 168 | 169 | def regenerate_config(self): 170 | """ 171 | Regenerates all configuration files with new settings. 172 | """ 173 | # Avoid a recursive import 174 | from ckan_multisite.site import get_sites 175 | self.update_default() 176 | for site in get_sites(): 177 | self.update_site(site) 178 | 179 | 180 | def _get_site_enabled_name(name): 181 | return path_join(SITES_ENABLED_PATH, name) 182 | 183 | 184 | def _get_site_config_name(name): 185 | """ 186 | Gets the name of a configuration file for a given site. 187 | 188 | :param name: The name of the site to get the name for. 189 | """ 190 | return path_join(SITES_AVAILABLE_PATH, name) 191 | 192 | nginx = DatacatsNginxConfig(MAIN_ENV_NAME) 193 | -------------------------------------------------------------------------------- /redis.conf: -------------------------------------------------------------------------------- 1 | # Redis configuration file example 2 | 3 | # Note on units: when memory size is needed, it is possible to specify 4 | # it in the usual form of 1k 5GB 4M and so forth: 5 | # 6 | # 1k => 1000 bytes 7 | # 1kb => 1024 bytes 8 | # 1m => 1000000 bytes 9 | # 1mb => 1024*1024 bytes 10 | # 1g => 1000000000 bytes 11 | # 1gb => 1024*1024*1024 bytes 12 | # 13 | # units are case insensitive so 1GB 1Gb 1gB are all the same. 14 | 15 | ################################## INCLUDES ################################### 16 | 17 | # Include one or more other config files here. This is useful if you 18 | # have a standard template that goes to all Redis server but also need 19 | # to customize a few per-server settings. Include files can include 20 | # other files, so use this wisely. 21 | # 22 | # Notice option "include" won't be rewritten by command "CONFIG REWRITE" 23 | # from admin or Redis Sentinel. Since Redis always uses the last processed 24 | # line as value of a configuration directive, you'd better put includes 25 | # at the beginning of this file to avoid overwriting config change at runtime. 26 | # 27 | # If instead you are interested in using includes to override configuration 28 | # options, it is better to use include as the last line. 29 | # 30 | # include /path/to/local.conf 31 | # include /path/to/other.conf 32 | 33 | ################################ GENERAL ##################################### 34 | 35 | # By default Redis does not run as a daemon. Use 'yes' if you need it. 36 | # Note that Redis will write a pid file in /var/run/redis.pid when daemonized. 37 | daemonize yes 38 | 39 | # When running daemonized, Redis writes a pid file in /var/run/redis.pid by 40 | # default. You can specify a custom pid file location here. 41 | pidfile /var/run/redis/redis-server.pid 42 | 43 | # Accept connections on the specified port, default is 6379. 44 | # If port 0 is specified Redis will not listen on a TCP socket. 45 | port 6379 46 | 47 | # By default Redis listens for connections from all the network interfaces 48 | # available on the server. It is possible to listen to just one or multiple 49 | # interfaces using the "bind" configuration directive, followed by one or 50 | # more IP addresses. 51 | # 52 | # Examples: 53 | # 54 | # bind 192.168.1.100 10.0.0.1 55 | bind 127.0.0.1 56 | 57 | # Specify the path for the unix socket that will be used to listen for 58 | # incoming connections. There is no default, so Redis will not listen 59 | # on a unix socket when not specified. 60 | # 61 | # unixsocket /var/run/redis/redis.sock 62 | # unixsocketperm 755 63 | 64 | # Close the connection after a client is idle for N seconds (0 to disable) 65 | timeout 0 66 | 67 | # TCP keepalive. 68 | # 69 | # If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence 70 | # of communication. This is useful for two reasons: 71 | # 72 | # 1) Detect dead peers. 73 | # 2) Take the connection alive from the point of view of network 74 | # equipment in the middle. 75 | # 76 | # On Linux, the specified value (in seconds) is the period used to send ACKs. 77 | # Note that to close the connection the double of the time is needed. 78 | # On other kernels the period depends on the kernel configuration. 79 | # 80 | # A reasonable value for this option is 60 seconds. 81 | tcp-keepalive 0 82 | 83 | # Specify the server verbosity level. 84 | # This can be one of: 85 | # debug (a lot of information, useful for development/testing) 86 | # verbose (many rarely useful info, but not a mess like the debug level) 87 | # notice (moderately verbose, what you want in production probably) 88 | # warning (only very important / critical messages are logged) 89 | loglevel notice 90 | 91 | # Specify the log file name. Also the empty string can be used to force 92 | # Redis to log on the standard output. Note that if you use standard 93 | # output for logging but daemonize, logs will be sent to /dev/null 94 | logfile redis-server.log 95 | 96 | # To enable logging to the system logger, just set 'syslog-enabled' to yes, 97 | # and optionally update the other syslog parameters to suit your needs. 98 | # syslog-enabled no 99 | 100 | # Specify the syslog identity. 101 | # syslog-ident redis 102 | 103 | # Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. 104 | # syslog-facility local0 105 | 106 | # Set the number of databases. The default database is DB 0, you can select 107 | # a different one on a per-connection basis using SELECT where 108 | # dbid is a number between 0 and 'databases'-1 109 | databases 16 110 | 111 | ################################ SNAPSHOTTING ################################ 112 | # 113 | # Save the DB on disk: 114 | # 115 | # save 116 | # 117 | # Will save the DB if both the given number of seconds and the given 118 | # number of write operations against the DB occurred. 119 | # 120 | # In the example below the behaviour will be to save: 121 | # after 900 sec (15 min) if at least 1 key changed 122 | # after 300 sec (5 min) if at least 10 keys changed 123 | # after 60 sec if at least 10000 keys changed 124 | # 125 | # Note: you can disable saving at all commenting all the "save" lines. 126 | # 127 | # It is also possible to remove all the previously configured save 128 | # points by adding a save directive with a single empty string argument 129 | # like in the following example: 130 | # 131 | # save "" 132 | 133 | save 900 1 134 | save 300 10 135 | save 60 10000 136 | 137 | # By default Redis will stop accepting writes if RDB snapshots are enabled 138 | # (at least one save point) and the latest background save failed. 139 | # This will make the user aware (in a hard way) that data is not persisting 140 | # on disk properly, otherwise chances are that no one will notice and some 141 | # disaster will happen. 142 | # 143 | # If the background saving process will start working again Redis will 144 | # automatically allow writes again. 145 | # 146 | # However if you have setup your proper monitoring of the Redis server 147 | # and persistence, you may want to disable this feature so that Redis will 148 | # continue to work as usual even if there are problems with disk, 149 | # permissions, and so forth. 150 | stop-writes-on-bgsave-error yes 151 | 152 | # Compress string objects using LZF when dump .rdb databases? 153 | # For default that's set to 'yes' as it's almost always a win. 154 | # If you want to save some CPU in the saving child set it to 'no' but 155 | # the dataset will likely be bigger if you have compressible values or keys. 156 | rdbcompression yes 157 | 158 | # Since version 5 of RDB a CRC64 checksum is placed at the end of the file. 159 | # This makes the format more resistant to corruption but there is a performance 160 | # hit to pay (around 10%) when saving and loading RDB files, so you can disable it 161 | # for maximum performances. 162 | # 163 | # RDB files created with checksum disabled have a checksum of zero that will 164 | # tell the loading code to skip the check. 165 | rdbchecksum yes 166 | 167 | # The filename where to dump the DB 168 | dbfilename dump.rdb 169 | 170 | # The working directory. 171 | # 172 | # The DB will be written inside this directory, with the filename specified 173 | # above using the 'dbfilename' configuration directive. 174 | # 175 | # The Append Only File will also be created inside this directory. 176 | # 177 | # Note that you must specify a directory here, not a file name. 178 | dir /var/lib/redis 179 | 180 | ################################# REPLICATION ################################# 181 | 182 | # Master-Slave replication. Use slaveof to make a Redis instance a copy of 183 | # another Redis server. Note that the configuration is local to the slave 184 | # so for example it is possible to configure the slave to save the DB with a 185 | # different interval, or to listen to another port, and so on. 186 | # 187 | # slaveof 188 | 189 | # If the master is password protected (using the "requirepass" configuration 190 | # directive below) it is possible to tell the slave to authenticate before 191 | # starting the replication synchronization process, otherwise the master will 192 | # refuse the slave request. 193 | # 194 | # masterauth 195 | 196 | # When a slave loses its connection with the master, or when the replication 197 | # is still in progress, the slave can act in two different ways: 198 | # 199 | # 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will 200 | # still reply to client requests, possibly with out of date data, or the 201 | # data set may just be empty if this is the first synchronization. 202 | # 203 | # 2) if slave-serve-stale-data is set to 'no' the slave will reply with 204 | # an error "SYNC with master in progress" to all the kind of commands 205 | # but to INFO and SLAVEOF. 206 | # 207 | slave-serve-stale-data yes 208 | 209 | # You can configure a slave instance to accept writes or not. Writing against 210 | # a slave instance may be useful to store some ephemeral data (because data 211 | # written on a slave will be easily deleted after resync with the master) but 212 | # may also cause problems if clients are writing to it because of a 213 | # misconfiguration. 214 | # 215 | # Since Redis 2.6 by default slaves are read-only. 216 | # 217 | # Note: read only slaves are not designed to be exposed to untrusted clients 218 | # on the internet. It's just a protection layer against misuse of the instance. 219 | # Still a read only slave exports by default all the administrative commands 220 | # such as CONFIG, DEBUG, and so forth. To a limited extent you can improve 221 | # security of read only slaves using 'rename-command' to shadow all the 222 | # administrative / dangerous commands. 223 | slave-read-only yes 224 | 225 | # Slaves send PINGs to server in a predefined interval. It's possible to change 226 | # this interval with the repl_ping_slave_period option. The default value is 10 227 | # seconds. 228 | # 229 | # repl-ping-slave-period 10 230 | 231 | # The following option sets the replication timeout for: 232 | # 233 | # 1) Bulk transfer I/O during SYNC, from the point of view of slave. 234 | # 2) Master timeout from the point of view of slaves (data, pings). 235 | # 3) Slave timeout from the point of view of masters (REPLCONF ACK pings). 236 | # 237 | # It is important to make sure that this value is greater than the value 238 | # specified for repl-ping-slave-period otherwise a timeout will be detected 239 | # every time there is low traffic between the master and the slave. 240 | # 241 | # repl-timeout 60 242 | 243 | # Disable TCP_NODELAY on the slave socket after SYNC? 244 | # 245 | # If you select "yes" Redis will use a smaller number of TCP packets and 246 | # less bandwidth to send data to slaves. But this can add a delay for 247 | # the data to appear on the slave side, up to 40 milliseconds with 248 | # Linux kernels using a default configuration. 249 | # 250 | # If you select "no" the delay for data to appear on the slave side will 251 | # be reduced but more bandwidth will be used for replication. 252 | # 253 | # By default we optimize for low latency, but in very high traffic conditions 254 | # or when the master and slaves are many hops away, turning this to "yes" may 255 | # be a good idea. 256 | repl-disable-tcp-nodelay no 257 | 258 | # Set the replication backlog size. The backlog is a buffer that accumulates 259 | # slave data when slaves are disconnected for some time, so that when a slave 260 | # wants to reconnect again, often a full resync is not needed, but a partial 261 | # resync is enough, just passing the portion of data the slave missed while 262 | # disconnected. 263 | # 264 | # The biggest the replication backlog, the longer the time the slave can be 265 | # disconnected and later be able to perform a partial resynchronization. 266 | # 267 | # The backlog is only allocated once there is at least a slave connected. 268 | # 269 | # repl-backlog-size 1mb 270 | 271 | # After a master has no longer connected slaves for some time, the backlog 272 | # will be freed. The following option configures the amount of seconds that 273 | # need to elapse, starting from the time the last slave disconnected, for 274 | # the backlog buffer to be freed. 275 | # 276 | # A value of 0 means to never release the backlog. 277 | # 278 | # repl-backlog-ttl 3600 279 | 280 | # The slave priority is an integer number published by Redis in the INFO output. 281 | # It is used by Redis Sentinel in order to select a slave to promote into a 282 | # master if the master is no longer working correctly. 283 | # 284 | # A slave with a low priority number is considered better for promotion, so 285 | # for instance if there are three slaves with priority 10, 100, 25 Sentinel will 286 | # pick the one with priority 10, that is the lowest. 287 | # 288 | # However a special priority of 0 marks the slave as not able to perform the 289 | # role of master, so a slave with priority of 0 will never be selected by 290 | # Redis Sentinel for promotion. 291 | # 292 | # By default the priority is 100. 293 | slave-priority 100 294 | 295 | # It is possible for a master to stop accepting writes if there are less than 296 | # N slaves connected, having a lag less or equal than M seconds. 297 | # 298 | # The N slaves need to be in "online" state. 299 | # 300 | # The lag in seconds, that must be <= the specified value, is calculated from 301 | # the last ping received from the slave, that is usually sent every second. 302 | # 303 | # This option does not GUARANTEES that N replicas will accept the write, but 304 | # will limit the window of exposure for lost writes in case not enough slaves 305 | # are available, to the specified number of seconds. 306 | # 307 | # For example to require at least 3 slaves with a lag <= 10 seconds use: 308 | # 309 | # min-slaves-to-write 3 310 | # min-slaves-max-lag 10 311 | # 312 | # Setting one or the other to 0 disables the feature. 313 | # 314 | # By default min-slaves-to-write is set to 0 (feature disabled) and 315 | # min-slaves-max-lag is set to 10. 316 | 317 | ################################## SECURITY ################################### 318 | 319 | # Require clients to issue AUTH before processing any other 320 | # commands. This might be useful in environments in which you do not trust 321 | # others with access to the host running redis-server. 322 | # 323 | # This should stay commented out for backward compatibility and because most 324 | # people do not need auth (e.g. they run their own servers). 325 | # 326 | # Warning: since Redis is pretty fast an outside user can try up to 327 | # 150k passwords per second against a good box. This means that you should 328 | # use a very strong password otherwise it will be very easy to break. 329 | # 330 | # requirepass foobared 331 | 332 | # Command renaming. 333 | # 334 | # It is possible to change the name of dangerous commands in a shared 335 | # environment. For instance the CONFIG command may be renamed into something 336 | # hard to guess so that it will still be available for internal-use tools 337 | # but not available for general clients. 338 | # 339 | # Example: 340 | # 341 | # rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 342 | # 343 | # It is also possible to completely kill a command by renaming it into 344 | # an empty string: 345 | # 346 | # rename-command CONFIG "" 347 | # 348 | # Please note that changing the name of commands that are logged into the 349 | # AOF file or transmitted to slaves may cause problems. 350 | 351 | ################################### LIMITS #################################### 352 | 353 | # Set the max number of connected clients at the same time. By default 354 | # this limit is set to 10000 clients, however if the Redis server is not 355 | # able to configure the process file limit to allow for the specified limit 356 | # the max number of allowed clients is set to the current file limit 357 | # minus 32 (as Redis reserves a few file descriptors for internal uses). 358 | # 359 | # Once the limit is reached Redis will close all the new connections sending 360 | # an error 'max number of clients reached'. 361 | # 362 | # maxclients 10000 363 | 364 | # Don't use more memory than the specified amount of bytes. 365 | # When the memory limit is reached Redis will try to remove keys 366 | # according to the eviction policy selected (see maxmemory-policy). 367 | # 368 | # If Redis can't remove keys according to the policy, or if the policy is 369 | # set to 'noeviction', Redis will start to reply with errors to commands 370 | # that would use more memory, like SET, LPUSH, and so on, and will continue 371 | # to reply to read-only commands like GET. 372 | # 373 | # This option is usually useful when using Redis as an LRU cache, or to set 374 | # a hard memory limit for an instance (using the 'noeviction' policy). 375 | # 376 | # WARNING: If you have slaves attached to an instance with maxmemory on, 377 | # the size of the output buffers needed to feed the slaves are subtracted 378 | # from the used memory count, so that network problems / resyncs will 379 | # not trigger a loop where keys are evicted, and in turn the output 380 | # buffer of slaves is full with DELs of keys evicted triggering the deletion 381 | # of more keys, and so forth until the database is completely emptied. 382 | # 383 | # In short... if you have slaves attached it is suggested that you set a lower 384 | # limit for maxmemory so that there is some free RAM on the system for slave 385 | # output buffers (but this is not needed if the policy is 'noeviction'). 386 | # 387 | # maxmemory 388 | 389 | # MAXMEMORY POLICY: how Redis will select what to remove when maxmemory 390 | # is reached. You can select among five behaviors: 391 | # 392 | # volatile-lru -> remove the key with an expire set using an LRU algorithm 393 | # allkeys-lru -> remove any key accordingly to the LRU algorithm 394 | # volatile-random -> remove a random key with an expire set 395 | # allkeys-random -> remove a random key, any key 396 | # volatile-ttl -> remove the key with the nearest expire time (minor TTL) 397 | # noeviction -> don't expire at all, just return an error on write operations 398 | # 399 | # Note: with any of the above policies, Redis will return an error on write 400 | # operations, when there are not suitable keys for eviction. 401 | # 402 | # At the date of writing this commands are: set setnx setex append 403 | # incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd 404 | # sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby 405 | # zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby 406 | # getset mset msetnx exec sort 407 | # 408 | # The default is: 409 | # 410 | # maxmemory-policy volatile-lru 411 | 412 | # LRU and minimal TTL algorithms are not precise algorithms but approximated 413 | # algorithms (in order to save memory), so you can select as well the sample 414 | # size to check. For instance for default Redis will check three keys and 415 | # pick the one that was used less recently, you can change the sample size 416 | # using the following configuration directive. 417 | # 418 | # maxmemory-samples 3 419 | 420 | ############################## APPEND ONLY MODE ############################### 421 | 422 | # By default Redis asynchronously dumps the dataset on disk. This mode is 423 | # good enough in many applications, but an issue with the Redis process or 424 | # a power outage may result into a few minutes of writes lost (depending on 425 | # the configured save points). 426 | # 427 | # The Append Only File is an alternative persistence mode that provides 428 | # much better durability. For instance using the default data fsync policy 429 | # (see later in the config file) Redis can lose just one second of writes in a 430 | # dramatic event like a server power outage, or a single write if something 431 | # wrong with the Redis process itself happens, but the operating system is 432 | # still running correctly. 433 | # 434 | # AOF and RDB persistence can be enabled at the same time without problems. 435 | # If the AOF is enabled on startup Redis will load the AOF, that is the file 436 | # with the better durability guarantees. 437 | # 438 | # Please check http://redis.io/topics/persistence for more information. 439 | 440 | appendonly no 441 | 442 | # The name of the append only file (default: "appendonly.aof") 443 | 444 | appendfilename "appendonly.aof" 445 | 446 | # The fsync() call tells the Operating System to actually write data on disk 447 | # instead to wait for more data in the output buffer. Some OS will really flush 448 | # data on disk, some other OS will just try to do it ASAP. 449 | # 450 | # Redis supports three different modes: 451 | # 452 | # no: don't fsync, just let the OS flush the data when it wants. Faster. 453 | # always: fsync after every write to the append only log . Slow, Safest. 454 | # everysec: fsync only one time every second. Compromise. 455 | # 456 | # The default is "everysec", as that's usually the right compromise between 457 | # speed and data safety. It's up to you to understand if you can relax this to 458 | # "no" that will let the operating system flush the output buffer when 459 | # it wants, for better performances (but if you can live with the idea of 460 | # some data loss consider the default persistence mode that's snapshotting), 461 | # or on the contrary, use "always" that's very slow but a bit safer than 462 | # everysec. 463 | # 464 | # More details please check the following article: 465 | # http://antirez.com/post/redis-persistence-demystified.html 466 | # 467 | # If unsure, use "everysec". 468 | 469 | # appendfsync always 470 | appendfsync everysec 471 | # appendfsync no 472 | 473 | # When the AOF fsync policy is set to always or everysec, and a background 474 | # saving process (a background save or AOF log background rewriting) is 475 | # performing a lot of I/O against the disk, in some Linux configurations 476 | # Redis may block too long on the fsync() call. Note that there is no fix for 477 | # this currently, as even performing fsync in a different thread will block 478 | # our synchronous write(2) call. 479 | # 480 | # In order to mitigate this problem it's possible to use the following option 481 | # that will prevent fsync() from being called in the main process while a 482 | # BGSAVE or BGREWRITEAOF is in progress. 483 | # 484 | # This means that while another child is saving, the durability of Redis is 485 | # the same as "appendfsync none". In practical terms, this means that it is 486 | # possible to lose up to 30 seconds of log in the worst scenario (with the 487 | # default Linux settings). 488 | # 489 | # If you have latency problems turn this to "yes". Otherwise leave it as 490 | # "no" that is the safest pick from the point of view of durability. 491 | 492 | no-appendfsync-on-rewrite no 493 | 494 | # Automatic rewrite of the append only file. 495 | # Redis is able to automatically rewrite the log file implicitly calling 496 | # BGREWRITEAOF when the AOF log size grows by the specified percentage. 497 | # 498 | # This is how it works: Redis remembers the size of the AOF file after the 499 | # latest rewrite (if no rewrite has happened since the restart, the size of 500 | # the AOF at startup is used). 501 | # 502 | # This base size is compared to the current size. If the current size is 503 | # bigger than the specified percentage, the rewrite is triggered. Also 504 | # you need to specify a minimal size for the AOF file to be rewritten, this 505 | # is useful to avoid rewriting the AOF file even if the percentage increase 506 | # is reached but it is still pretty small. 507 | # 508 | # Specify a percentage of zero in order to disable the automatic AOF 509 | # rewrite feature. 510 | 511 | auto-aof-rewrite-percentage 100 512 | auto-aof-rewrite-min-size 64mb 513 | 514 | ################################ LUA SCRIPTING ############################### 515 | 516 | # Max execution time of a Lua script in milliseconds. 517 | # 518 | # If the maximum execution time is reached Redis will log that a script is 519 | # still in execution after the maximum allowed time and will start to 520 | # reply to queries with an error. 521 | # 522 | # When a long running script exceed the maximum execution time only the 523 | # SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be 524 | # used to stop a script that did not yet called write commands. The second 525 | # is the only way to shut down the server in the case a write commands was 526 | # already issue by the script but the user don't want to wait for the natural 527 | # termination of the script. 528 | # 529 | # Set it to 0 or a negative value for unlimited execution without warnings. 530 | lua-time-limit 5000 531 | 532 | ################################## SLOW LOG ################################### 533 | 534 | # The Redis Slow Log is a system to log queries that exceeded a specified 535 | # execution time. The execution time does not include the I/O operations 536 | # like talking with the client, sending the reply and so forth, 537 | # but just the time needed to actually execute the command (this is the only 538 | # stage of command execution where the thread is blocked and can not serve 539 | # other requests in the meantime). 540 | # 541 | # You can configure the slow log with two parameters: one tells Redis 542 | # what is the execution time, in microseconds, to exceed in order for the 543 | # command to get logged, and the other parameter is the length of the 544 | # slow log. When a new command is logged the oldest one is removed from the 545 | # queue of logged commands. 546 | 547 | # The following time is expressed in microseconds, so 1000000 is equivalent 548 | # to one second. Note that a negative number disables the slow log, while 549 | # a value of zero forces the logging of every command. 550 | slowlog-log-slower-than 10000 551 | 552 | # There is no limit to this length. Just be aware that it will consume memory. 553 | # You can reclaim memory used by the slow log with SLOWLOG RESET. 554 | slowlog-max-len 128 555 | 556 | ############################# Event notification ############################## 557 | 558 | # Redis can notify Pub/Sub clients about events happening in the key space. 559 | # This feature is documented at http://redis.io/topics/keyspace-events 560 | # 561 | # For instance if keyspace events notification is enabled, and a client 562 | # performs a DEL operation on key "foo" stored in the Database 0, two 563 | # messages will be published via Pub/Sub: 564 | # 565 | # PUBLISH __keyspace@0__:foo del 566 | # PUBLISH __keyevent@0__:del foo 567 | # 568 | # It is possible to select the events that Redis will notify among a set 569 | # of classes. Every class is identified by a single character: 570 | # 571 | # K Keyspace events, published with __keyspace@__ prefix. 572 | # E Keyevent events, published with __keyevent@__ prefix. 573 | # g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... 574 | # $ String commands 575 | # l List commands 576 | # s Set commands 577 | # h Hash commands 578 | # z Sorted set commands 579 | # x Expired events (events generated every time a key expires) 580 | # e Evicted events (events generated when a key is evicted for maxmemory) 581 | # A Alias for g$lshzxe, so that the "AKE" string means all the events. 582 | # 583 | # The "notify-keyspace-events" takes as argument a string that is composed 584 | # by zero or multiple characters. The empty string means that notifications 585 | # are disabled at all. 586 | # 587 | # Example: to enable list and generic events, from the point of view of the 588 | # event name, use: 589 | # 590 | # notify-keyspace-events Elg 591 | # 592 | # Example 2: to get the stream of the expired keys subscribing to channel 593 | # name __keyevent@0__:expired use: 594 | # 595 | # notify-keyspace-events Ex 596 | # 597 | # By default all notifications are disabled because most users don't need 598 | # this feature and the feature has some overhead. Note that if you don't 599 | # specify at least one of K or E, no events will be delivered. 600 | notify-keyspace-events "" 601 | 602 | ############################### ADVANCED CONFIG ############################### 603 | 604 | # Hashes are encoded using a memory efficient data structure when they have a 605 | # small number of entries, and the biggest entry does not exceed a given 606 | # threshold. These thresholds can be configured using the following directives. 607 | hash-max-ziplist-entries 512 608 | hash-max-ziplist-value 64 609 | 610 | # Similarly to hashes, small lists are also encoded in a special way in order 611 | # to save a lot of space. The special representation is only used when 612 | # you are under the following limits: 613 | list-max-ziplist-entries 512 614 | list-max-ziplist-value 64 615 | 616 | # Sets have a special encoding in just one case: when a set is composed 617 | # of just strings that happens to be integers in radix 10 in the range 618 | # of 64 bit signed integers. 619 | # The following configuration setting sets the limit in the size of the 620 | # set in order to use this special memory saving encoding. 621 | set-max-intset-entries 512 622 | 623 | # Similarly to hashes and lists, sorted sets are also specially encoded in 624 | # order to save a lot of space. This encoding is only used when the length and 625 | # elements of a sorted set are below the following limits: 626 | zset-max-ziplist-entries 128 627 | zset-max-ziplist-value 64 628 | 629 | # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in 630 | # order to help rehashing the main Redis hash table (the one mapping top-level 631 | # keys to values). The hash table implementation Redis uses (see dict.c) 632 | # performs a lazy rehashing: the more operation you run into a hash table 633 | # that is rehashing, the more rehashing "steps" are performed, so if the 634 | # server is idle the rehashing is never complete and some more memory is used 635 | # by the hash table. 636 | # 637 | # The default is to use this millisecond 10 times every second in order to 638 | # active rehashing the main dictionaries, freeing memory when possible. 639 | # 640 | # If unsure: 641 | # use "activerehashing no" if you have hard latency requirements and it is 642 | # not a good thing in your environment that Redis can reply form time to time 643 | # to queries with 2 milliseconds delay. 644 | # 645 | # use "activerehashing yes" if you don't have such hard requirements but 646 | # want to free memory asap when possible. 647 | activerehashing yes 648 | 649 | # The client output buffer limits can be used to force disconnection of clients 650 | # that are not reading data from the server fast enough for some reason (a 651 | # common reason is that a Pub/Sub client can't consume messages as fast as the 652 | # publisher can produce them). 653 | # 654 | # The limit can be set differently for the three different classes of clients: 655 | # 656 | # normal -> normal clients 657 | # slave -> slave clients and MONITOR clients 658 | # pubsub -> clients subscribed to at least one pubsub channel or pattern 659 | # 660 | # The syntax of every client-output-buffer-limit directive is the following: 661 | # 662 | # client-output-buffer-limit 663 | # 664 | # A client is immediately disconnected once the hard limit is reached, or if 665 | # the soft limit is reached and remains reached for the specified number of 666 | # seconds (continuously). 667 | # So for instance if the hard limit is 32 megabytes and the soft limit is 668 | # 16 megabytes / 10 seconds, the client will get disconnected immediately 669 | # if the size of the output buffers reach 32 megabytes, but will also get 670 | # disconnected if the client reaches 16 megabytes and continuously overcomes 671 | # the limit for 10 seconds. 672 | # 673 | # By default normal clients are not limited because they don't receive data 674 | # without asking (in a push way), but just after a request, so only 675 | # asynchronous clients may create a scenario where data is requested faster 676 | # than it can read. 677 | # 678 | # Instead there is a default limit for pubsub and slave clients, since 679 | # subscribers and slaves receive data in a push fashion. 680 | # 681 | # Both the hard or the soft limit can be disabled by setting them to zero. 682 | client-output-buffer-limit normal 0 0 0 683 | client-output-buffer-limit slave 256mb 64mb 60 684 | client-output-buffer-limit pubsub 32mb 8mb 60 685 | 686 | # Redis calls an internal function to perform many background tasks, like 687 | # closing connections of clients in timeout, purging expired keys that are 688 | # never requested, and so forth. 689 | # 690 | # Not all tasks are performed with the same frequency, but Redis checks for 691 | # tasks to perform accordingly to the specified "hz" value. 692 | # 693 | # By default "hz" is set to 10. Raising the value will use more CPU when 694 | # Redis is idle, but at the same time will make Redis more responsive when 695 | # there are many keys expiring at the same time, and timeouts may be 696 | # handled with more precision. 697 | # 698 | # The range is between 1 and 500, however a value over 100 is usually not 699 | # a good idea. Most users should use the default of 10 and raise this up to 700 | # 100 only in environments where very low latency is required. 701 | hz 10 702 | 703 | # When a child rewrites the AOF file, if the following option is enabled 704 | # the file will be fsync-ed every 32 MB of data generated. This is useful 705 | # in order to commit the file to the disk more incrementally and avoid 706 | # big latency spikes. 707 | aof-rewrite-incremental-fsync yes 708 | 709 | -------------------------------------------------------------------------------- /diagrams/ckan-multisite.graphml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | ckan-multisite 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 2 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | datacats 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 3 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | environment 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 1 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | ckan 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | config 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | ckan extensions 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | child-1 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 1 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | db 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | files 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | solr 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 1 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | child-2 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 1 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | child-n 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | HTTP router 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | multisite admin 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | Internet 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | dns server: 378 | *.mysite.mydomain 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | --------------------------------------------------------------------------------