Merge lp:~brad-marshall/charms/precise/python-moinmoin/python-rewrite-with-openid-fixes into lp:charms/python-moinmoin

Proposed by Brad Marshall
Status: Merged
Merged at revision: 8
Proposed branch: lp:~brad-marshall/charms/precise/python-moinmoin/python-rewrite-with-openid-fixes
Merge into: lp:charms/python-moinmoin
Diff against target: 14878 lines (+13568/-295)
115 files modified
README.md (+0/-62)
config.yaml (+0/-30)
copyright (+0/-17)
files/openidrp.py (+325/-0)
files/openidrp_teams.py (+157/-0)
files/teams.py (+398/-0)
hooks/config-changed (+0/-54)
hooks/hooks.py (+226/-0)
hooks/install (+0/-19)
hooks/start (+0/-4)
hooks/stop (+0/-7)
hooks/website-relation-joined (+0/-2)
lib/charm-helpers/LICENSE.txt (+661/-0)
lib/charm-helpers/MANIFEST.in (+6/-0)
lib/charm-helpers/Makefile (+46/-0)
lib/charm-helpers/README.test (+7/-0)
lib/charm-helpers/README.txt (+8/-0)
lib/charm-helpers/REVISION (+1/-0)
lib/charm-helpers/VERSION (+1/-0)
lib/charm-helpers/bin/README (+1/-0)
lib/charm-helpers/bin/chlp (+7/-0)
lib/charm-helpers/bin/contrib/charmsupport/charmsupport (+31/-0)
lib/charm-helpers/bin/contrib/saltstack/salt-call (+11/-0)
lib/charm-helpers/charmhelpers/cli/README.rst (+57/-0)
lib/charm-helpers/charmhelpers/cli/__init__.py (+147/-0)
lib/charm-helpers/charmhelpers/cli/commands.py (+2/-0)
lib/charm-helpers/charmhelpers/cli/host.py (+14/-0)
lib/charm-helpers/charmhelpers/contrib/ansible/__init__.py (+101/-0)
lib/charm-helpers/charmhelpers/contrib/charmhelpers/IMPORT (+4/-0)
lib/charm-helpers/charmhelpers/contrib/charmhelpers/__init__.py (+184/-0)
lib/charm-helpers/charmhelpers/contrib/charmsupport/IMPORT (+14/-0)
lib/charm-helpers/charmhelpers/contrib/charmsupport/nrpe.py (+218/-0)
lib/charm-helpers/charmhelpers/contrib/charmsupport/volumes.py (+156/-0)
lib/charm-helpers/charmhelpers/contrib/hahelpers/apache.py (+58/-0)
lib/charm-helpers/charmhelpers/contrib/hahelpers/ceph.py (+294/-0)
lib/charm-helpers/charmhelpers/contrib/hahelpers/cluster.py (+181/-0)
lib/charm-helpers/charmhelpers/contrib/jujugui/IMPORT (+4/-0)
lib/charm-helpers/charmhelpers/contrib/jujugui/utils.py (+602/-0)
lib/charm-helpers/charmhelpers/contrib/network/ovs/__init__.py (+72/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/context.py (+294/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/templates/__init__.py (+2/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/templates/ceph.conf (+11/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/templates/haproxy.cfg (+37/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/templates/openstack_https_frontend (+23/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/templating.py (+261/-0)
lib/charm-helpers/charmhelpers/contrib/openstack/utils.py (+276/-0)
lib/charm-helpers/charmhelpers/contrib/saltstack/__init__.py (+149/-0)
lib/charm-helpers/charmhelpers/contrib/ssl/__init__.py (+79/-0)
lib/charm-helpers/charmhelpers/contrib/storage/linux/loopback.py (+62/-0)
lib/charm-helpers/charmhelpers/contrib/storage/linux/lvm.py (+88/-0)
lib/charm-helpers/charmhelpers/contrib/storage/linux/utils.py (+25/-0)
lib/charm-helpers/charmhelpers/contrib/templating/pyformat.py (+13/-0)
lib/charm-helpers/charmhelpers/core/hookenv.py (+340/-0)
lib/charm-helpers/charmhelpers/core/host.py (+241/-0)
lib/charm-helpers/charmhelpers/fetch/__init__.py (+209/-0)
lib/charm-helpers/charmhelpers/fetch/archiveurl.py (+48/-0)
lib/charm-helpers/charmhelpers/fetch/bzrurl.py (+49/-0)
lib/charm-helpers/charmhelpers/payload/__init__.py (+1/-0)
lib/charm-helpers/charmhelpers/payload/archive.py (+57/-0)
lib/charm-helpers/charmhelpers/payload/execd.py (+50/-0)
lib/charm-helpers/debian/compat (+1/-0)
lib/charm-helpers/debian/control (+20/-0)
lib/charm-helpers/debian/rules (+9/-0)
lib/charm-helpers/debian/source/format (+1/-0)
lib/charm-helpers/scripts/README (+1/-0)
lib/charm-helpers/scripts/update-revno (+11/-0)
lib/charm-helpers/setup.cfg (+4/-0)
lib/charm-helpers/setup.py (+42/-0)
lib/charm-helpers/tarmac_tests.sh (+6/-0)
lib/charm-helpers/test_requirements.txt (+18/-0)
lib/charm-helpers/tests/cli/test_cmdline.py (+189/-0)
lib/charm-helpers/tests/cli/test_function_signature_analysis.py (+46/-0)
lib/charm-helpers/tests/contrib/ansible/test_ansible.py (+134/-0)
lib/charm-helpers/tests/contrib/charmhelpers/test_charmhelpers.py (+290/-0)
lib/charm-helpers/tests/contrib/charmsupport/test_nrpe.py (+222/-0)
lib/charm-helpers/tests/contrib/hahelpers/test_apache_utils.py (+44/-0)
lib/charm-helpers/tests/contrib/hahelpers/test_ceph_utils.py (+131/-0)
lib/charm-helpers/tests/contrib/hahelpers/test_cluster_utils.py (+277/-0)
lib/charm-helpers/tests/contrib/jujugui/config/apache-ports.template (+2/-0)
lib/charm-helpers/tests/contrib/jujugui/config/apache-site.template (+30/-0)
lib/charm-helpers/tests/contrib/jujugui/config/config.js.template (+26/-0)
lib/charm-helpers/tests/contrib/jujugui/config/haproxy.cfg.template (+48/-0)
lib/charm-helpers/tests/contrib/jujugui/config/haproxy.conf (+22/-0)
lib/charm-helpers/tests/contrib/jujugui/config/juju-api-agent.conf.template (+14/-0)
lib/charm-helpers/tests/contrib/jujugui/config/juju-api-improv.conf.template (+12/-0)
lib/charm-helpers/tests/contrib/jujugui/deploy.test (+232/-0)
lib/charm-helpers/tests/contrib/jujugui/test_utils.py (+660/-0)
lib/charm-helpers/tests/contrib/jujugui/unit.test (+11/-0)
lib/charm-helpers/tests/contrib/network/test_ovs.py (+202/-0)
lib/charm-helpers/tests/contrib/openstack/test_openstack_utils.py (+421/-0)
lib/charm-helpers/tests/contrib/openstack/test_os_contexts.py (+473/-0)
lib/charm-helpers/tests/contrib/openstack/test_os_templating.py (+232/-0)
lib/charm-helpers/tests/contrib/saltstack/test_saltstates.py (+229/-0)
lib/charm-helpers/tests/contrib/ssl/test_ssl.py (+60/-0)
lib/charm-helpers/tests/contrib/storage/test_linux_storage_loopback.py (+75/-0)
lib/charm-helpers/tests/contrib/storage/test_linux_storage_lvm.py (+70/-0)
lib/charm-helpers/tests/contrib/storage/test_linux_storage_utils.py (+23/-0)
lib/charm-helpers/tests/contrib/templating/test_pyformat.py (+36/-0)
lib/charm-helpers/tests/core/test_hookenv.py (+797/-0)
lib/charm-helpers/tests/core/test_host.py (+678/-0)
lib/charm-helpers/tests/fetch/test_archiveurl.py (+89/-0)
lib/charm-helpers/tests/fetch/test_bzrurl.py (+80/-0)
lib/charm-helpers/tests/fetch/test_fetch.py (+407/-0)
lib/charm-helpers/tests/payload/test_archive.py (+131/-0)
lib/charm-helpers/tests/payload/test_execd.py (+151/-0)
lib/charm-helpers/tests/tools/test_charm_helper_sync.py (+249/-0)
lib/charm-helpers/tools/charm_helpers_sync/README (+114/-0)
lib/charm-helpers/tools/charm_helpers_sync/charm_helpers_sync.py (+225/-0)
lib/charm-helpers/tools/charm_helpers_sync/example-config.yaml (+14/-0)
metadata.yaml (+0/-10)
revision (+0/-1)
templates/gunicorn.conf.tmpl (+0/-18)
templates/logging.conf.tmpl (+0/-31)
templates/wikiconfig.py.tmpl (+0/-30)
templates/wsgi.py.tmpl (+0/-10)
To merge this branch: bzr merge lp:~brad-marshall/charms/precise/python-moinmoin/python-rewrite-with-openid-fixes
Reviewer Review Type Date Requested Status
Marco Ceppi (community) Approve
Review via email: mp+187672@code.launchpad.net

Description of the change

Rewrote the charm in python using charm-helper.

Added openid auth support, testing can be done using:

 $ juju set python-moinmoin use_openid=True openidrp_authorized_teams="['your-openid-team']"

Then try logging into http://<instance>:8080/ with a user in your-openid-team.

To post a comment you must log in.
Revision history for this message
Marco Ceppi (marcoceppi) wrote :

LGTM +1, Thanks for the rewrite. You might want to consider linking to various appropriate sections of the docs in case the README methods become out of date, https://juju.ubuntu.com/docs/charms-config.html#config-deployment for example.

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== added file 'README.md'
--- README.md 1970-01-01 00:00:00 +0000
+++ README.md 2013-09-26 06:24:47 +0000
@@ -0,0 +1,72 @@
1# Overview
2Juju charm for python-moinmoin, charm author: Patrick Hetu <patrick@koumbit.org>
3
4# Deployment
5After a successful bootstrap, you can deploy the service without a configuration or alias with:
6
7 juju deploy python-moinmoin
8 juju expose python-moinmoin
9
10Though, it's recommended you create a yaml file with your parameters, for instance if you were to deploy the service as "mywiki", the configuration would look like:
11
12 mywiki:
13 wiki_name : "My MoinMoin wiki"
14 admin_name: "Admin"
15 languages: English French
16 xapian_search: True
17 port: 80
18
19To then deploy the wiki, with pre-seeded configuration:
20
21 juju deploy --config mywiki.yaml python-moinmoin mywiki
22 juju expose mywiki
23
24# Configuration
25This service contains several configuration options for controlling the moinmoin install
26
27## wiki_name
28Set the name and title of the wiki
29
30 juju set python_moinmoin wiki_name="My new wiki name"
31
32## admin_name
33Name of the admin account
34
35 juju set python_moinmoin admin_name="Adminstrator"
36
37## languages
38List of languages to be installed on the wiki, space delimited
39
40 juju set python_moinmoin languages English Spanish French
41
42To remove a language you'll need to re-enter the entire list, removing the language you no longer want
43
44 juju set python_moinmoin languages="English Spanish"
45
46# xapian_serach
47Enable xapian serach on your wiki (True or False)
48
49 juju set python_moinmoin xapian_search="True"
50
51# port
52The port moinmoin should listen on. By default it's 8080
53
54 juju set python_moinmoin port=80
55
56# use_openid
57Setting to say if the wiki is using OpenID authentication or not.
58
59 juju set python_moinmoin use_openid=True
60
61# openidrp_authorized_teams
62What OpenID teams are authorized to log in, if use_openid is true.
63
64 juju set python_moinmoin openidrp_authorized_teams="['team1', 'team2']"
65
66# Relations
67python-moinmoin can be related to any of the proxy charms, including but not limited to: haproxy, varnish, and squid. An example of connecting squid-reverseproxy to python-moinmoin is listed below:
68
69 juju deploy squid-reverseproxy squid
70 juju unexpose python-moinmoin
71 juju add-relation python-moinmoin squid
72 juju expose squid
073
=== removed file 'README.md'
--- README.md 2013-05-23 13:02:52 +0000
+++ README.md 1970-01-01 00:00:00 +0000
@@ -1,62 +0,0 @@
1# Overview
2Juju charm for python-moinmoin, charm author: Patrick Hetu <patrick@koumbit.org>
3
4# Deployment
5After a successful bootstrap, you can deploy the service without a configuration or alias with:
6
7 juju deploy python-moinmoin
8 juju expose python-moinmoin
9
10Though, it's recommended you create a yaml file with your parameters, for instance if you were to deploy the service as "mywiki", the configuration would look like:
11
12 mywiki:
13 wiki_name : "My MoinMoin wiki"
14 admin_name: "Admin"
15 languages: English French
16 xapian_search: True
17 port: 80
18
19To then deploy the wiki, with pre-seeded configuration:
20
21 juju deploy --config mywiki.yaml python-moinmoin mywiki
22 juju expose mywiki
23
24# Configuration
25This service contains several configuration options for controlling the moinmoin install
26
27## wiki_name
28Set the name and title of the wiki
29
30 juju set python_moinmoin wiki_name="My new wiki name"
31
32## admin_name
33Name of the admin account
34
35 juju set python_moinmoin admin_name="Adminstrator"
36
37## languages
38List of languages to be installed on the wiki, space delimited
39
40 juju set python_moinmoin languages English Spanish French
41
42To remove a language you'll need to re-enter the entire list, removing the language you no longer want
43
44 juju set python_moinmoin languages="English Spanish"
45
46# xapian_serach
47Enable xapian serach on your wiki (True or False)
48
49 juju set python_moinmoin xapian_search="True"
50
51# port
52The port moinmoin should listen on. By default it's 8080
53
54 juju set python_moinmoin port=80
55
56# Relations
57python-moinmoin can be related to any of the proxy charms, including but not limited to: haproxy, varnish, and squid. An example of connecting squid-reverseproxy to python-moinmoin is listed below:
58
59 juju deploy squid-reverseproxy squid
60 juju unexpose python-moinmoin
61 juju add-relation python-moinmoin squid
62 juju expose squid
630
=== added file 'config.yaml'
--- config.yaml 1970-01-01 00:00:00 +0000
+++ config.yaml 2013-09-26 06:24:47 +0000
@@ -0,0 +1,42 @@
1options:
2 wiki_name:
3 default: "My MoinMoin wiki"
4 type: string
5 description: The name of your wiki.
6 admin_name:
7 default: "Admin"
8 type: string
9 description: The wiki name of the admin user.
10 languages:
11 default: "English"
12 type: string
13 description: |
14 Languages to installed in a space-separated format.
15 For available languages see: http://moinmo.in/4ct10n/AttachFile/LanguageSetup?action=AttachFile
16 (write only the language name part)
17 loglevel:
18 default: "INFO"
19 type: string
20 description: Default loglevel, to adjust verbosity DEBUG, INFO, WARNING, ERROR, CRITICAL
21 xapian_search:
22 default: "True"
23 type: string
24 description: Set to True to enable the Xapian search engine.
25 listen_port:
26 default: 8080
27 type: int
28 description: The port for the service to listen on.
29 use_openid:
30 default: "False"
31 type: string
32 description: OpenID authentication used or not.
33 openidrp_authorized_teams:
34 default: "False"
35 type: string
36 description: Define the openid authorized teams for the wiki.
37 extra_settings:
38 default: ""
39 type: string
40 description: |
41 For the list of available configuration options see: http://moinmo.in/HelpOnConfiguration.
42 Also, don't forget to starts your configuration lines with a 4 spaces indentation.
043
=== removed file 'config.yaml'
--- config.yaml 2013-05-07 16:03:30 +0000
+++ config.yaml 1970-01-01 00:00:00 +0000
@@ -1,30 +0,0 @@
1options:
2 wiki_name:
3 default: "My MoinMoin wiki"
4 type: string
5 description: The name of your wiki.
6 admin_name:
7 default: "Admin"
8 type: string
9 description: The wiki name of the admin user.
10 languages:
11 default: "English"
12 type: string
13 description: |
14 Languages to installed in a space-separated format.
15 For available languages see: http://moinmo.in/4ct10n/AttachFile/LanguageSetup?action=AttachFile
16 (write only the language name part)
17 xapian_search:
18 default: "True"
19 type: string
20 description: Set to True to enable the Xapian search engine.
21 listen_port:
22 default: 8080
23 type: int
24 description: The port for the service to listen on.
25 extra_settings:
26 default: ""
27 type: string
28 description: |
29 For the list of available configuration options see: http://moinmo.in/HelpOnConfiguration.
30 Also, don't forget to starts your configuration lines with a 4 spaces indentation.
310
=== added file 'copyright'
--- copyright 1970-01-01 00:00:00 +0000
+++ copyright 2013-09-26 06:24:47 +0000
@@ -0,0 +1,18 @@
1Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2
3Files: *
4Copyright: Copyright 2013, Canonical Ltd., All Rights Reserved.
5License: GPL-3
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10 .
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15 .
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
18
019
=== removed file 'copyright'
--- copyright 2011-11-01 20:33:21 +0000
+++ copyright 1970-01-01 00:00:00 +0000
@@ -1,17 +0,0 @@
1Format: http://dep.debian.net/deps/dep5/
2
3Files: *
4Copyright: Copyright 2011, Patrick Hetu <patrick@koumbit.org>, All Rights Reserved.
5License: GPL-3
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10 .
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15 .
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
180
=== added directory 'files'
=== added file 'files/openidrp.py'
--- files/openidrp.py 1970-01-01 00:00:00 +0000
+++ files/openidrp.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,325 @@
1# -*- coding: iso-8859-1 -*-
2"""
3 MoinMoin - OpenID authorization
4
5 @copyright: 2007 MoinMoin:JohannesBerg
6 @license: GNU GPL, see COPYING for details.
7"""
8from MoinMoin import log
9logging = log.getLogger(__name__)
10
11from MoinMoin.util.moinoid import MoinOpenIDStore
12from MoinMoin import user
13from MoinMoin.auth import BaseAuth
14from openid.consumer import consumer
15from openid.yadis.discover import DiscoveryFailure
16from openid.fetchers import HTTPFetchingError
17from MoinMoin.widget import html
18from MoinMoin.auth import CancelLogin, ContinueLogin
19from MoinMoin.auth import MultistageFormLogin, MultistageRedirectLogin
20from MoinMoin.auth import get_multistage_continuation_url
21from werkzeug import url_encode
22
23class OpenIDAuth(BaseAuth):
24 login_inputs = ['openid_identifier']
25 name = 'openid'
26 logout_possible = True
27 auth_attribs = ()
28
29 def __init__(self, modify_request=None,
30 update_user=None,
31 create_user=None,
32 forced_service=None,
33 idselector_com=None):
34 BaseAuth.__init__(self)
35 self._modify_request = modify_request or (lambda x, c: None)
36 self._update_user = update_user or (lambda i, u, c: None)
37 self._create_user = create_user or (lambda i, u, c: None)
38 self._forced_service = forced_service
39 self._idselector_com = idselector_com
40 if forced_service:
41 self.login_inputs = ['special_no_input']
42
43 def _handle_user_data(self, request, u):
44 create = not u
45 # just in case the wiki admin screwed up
46 if create and user.getUserIdByOpenId(request, request.session['openid.id']):
47 return None
48
49 if create:
50 # pass in a created but unsaved user object
51 u = user.User(request, auth_method=self.name,
52 auth_username=request.session['openid.id'],
53 auth_attribs=self.auth_attribs)
54 # invalid name
55 u.name = ''
56 u = self._create_user(request.session['openid.info'], u, request.cfg)
57
58 if u:
59 self._update_user(request.session['openid.info'], u, request.cfg)
60
61 if not user.isValidName(request, u.name):
62 return None
63
64 if not hasattr(u, 'openids'):
65 u.openids = []
66 if not request.session['openid.id'] in u.openids:
67 u.openids.append(request.session['openid.id'])
68
69 u.save()
70
71 del request.session['openid.id']
72 del request.session['openid.info']
73
74 return u
75
76 def _get_account_name(self, request, form, msg=None):
77 # now we need to ask the user for a new username
78 # that they want to use on this wiki
79 # XXX: request nickname from OP and suggest using it
80 # (if it isn't in use yet)
81 logging.debug("running _get_account_name")
82 _ = request.getText
83 form.append(html.INPUT(type='hidden', name='oidstage', value='2'))
84 table = html.TABLE(border='0')
85 form.append(table)
86 td = html.TD(colspan=2)
87 td.append(html.Raw(_("""Please choose an account name now.
88If you choose an existing account name you will be asked for the
89password and be able to associate the account with your OpenID.""")))
90 table.append(html.TR().append(td))
91 if msg:
92 td = html.TD(colspan='2')
93 td.append(html.P().append(html.STRONG().append(html.Raw(msg))))
94 table.append(html.TR().append(td))
95 td1 = html.TD()
96 td1.append(html.STRONG().append(html.Raw(_('Name'))))
97 td2 = html.TD()
98 td2.append(html.INPUT(type='text', name='username'))
99 table.append(html.TR().append(td1).append(td2))
100 td1 = html.TD()
101 td2 = html.TD()
102 td2.append(html.INPUT(type='submit', name='submit',
103 value=_('Choose this name')))
104 table.append(html.TR().append(td1).append(td2))
105
106 def _get_account_name_inval_user(self, request, form):
107 _ = request.getText
108 msg = _('This is not a valid username, choose a different one.')
109 return self._get_account_name(request, form, msg=msg)
110
111 def _associate_account(self, request, form, accountname, msg=None):
112 _ = request.getText
113
114 form.append(html.INPUT(type='hidden', name='oidstage', value='3'))
115 table = html.TABLE(border='0')
116 form.append(table)
117 td = html.TD(colspan=2)
118 td.append(html.Raw(_("""The username you have chosen is already
119taken. If it is your username, enter your password below to associate
120the username with your OpenID. Otherwise, please choose a different
121username and leave the password field blank.""")))
122 table.append(html.TR().append(td))
123 if msg:
124 td.append(html.P().append(html.STRONG().append(html.Raw(msg))))
125 td1 = html.TD()
126 td1.append(html.STRONG().append(html.Raw(_('Name'))))
127 td2 = html.TD()
128 td2.append(html.INPUT(type='text', name='username', value=accountname))
129 table.append(html.TR().append(td1).append(td2))
130 td1 = html.TD()
131 td1.append(html.STRONG().append(html.Raw(_('Password'))))
132 td2 = html.TD()
133 td2.append(html.INPUT(type='password', name='password'))
134 table.append(html.TR().append(td1).append(td2))
135 td1 = html.TD()
136 td2 = html.TD()
137 td2.append(html.INPUT(type='submit', name='submit',
138 value=_('Associate this name')))
139 table.append(html.TR().append(td1).append(td2))
140
141 def _handle_verify_continuation(self, request):
142 _ = request.getText
143 oidconsumer = consumer.Consumer(request.session,
144 MoinOpenIDStore(request))
145 query = {}
146 for key in request.values.keys():
147 query[key] = request.values.get(key)
148 current_url = get_multistage_continuation_url(request, self.name,
149 {'oidstage': '1'})
150 info = oidconsumer.complete(query, current_url)
151 if info.status == consumer.FAILURE:
152 logging.debug(_("OpenID error: %s.") % info.message)
153 return CancelLogin(_('OpenID error: %s.') % info.message)
154 elif info.status == consumer.CANCEL:
155 logging.debug(_("OpenID verification canceled."))
156 return CancelLogin(_('Verification canceled.'))
157 elif info.status == consumer.SUCCESS:
158 logging.debug(_("OpenID success. id: %s") % info.identity_url)
159 request.session['openid.id'] = info.identity_url
160 request.session['openid.info'] = info
161
162 # try to find user object
163 uid = user.getUserIdByOpenId(request, info.identity_url)
164 if uid:
165 u = user.User(request, id=uid, auth_method=self.name,
166 auth_username=info.identity_url,
167 auth_attribs=self.auth_attribs)
168 else:
169 u = None
170
171 # create or update the user according to the registration data
172 u = self._handle_user_data(request, u)
173 if u:
174 return ContinueLogin(u)
175
176 # if no user found, then we need to ask for a username,
177 # possibly associating an existing account.
178 logging.debug("OpenID: No user found, prompting for username")
179 #request.session['openid.id'] = info.identity_url
180 return MultistageFormLogin(self._get_account_name)
181 else:
182 logging.debug(_("OpenID failure"))
183 return CancelLogin(_('OpenID failure.'))
184
185 def _handle_name_continuation(self, request):
186 _ = request.getText
187 if not 'openid.id' in request.session:
188 return CancelLogin(_('No OpenID found in session.'))
189
190 newname = request.form.get('username', '')
191 if not newname:
192 return MultistageFormLogin(self._get_account_name)
193 if not user.isValidName(request, newname):
194 return MultistageFormLogin(self._get_account_name_inval_user)
195 uid = None
196 if newname:
197 uid = user.getUserId(request, newname)
198 if not uid:
199 # we can create a new user with this name :)
200 u = user.User(request, auth_method=self.name,
201 auth_username=request.session['openid.id'],
202 auth_attribs=self.auth_attribs)
203 u.name = newname
204 u = self._handle_user_data(request, u)
205 return ContinueLogin(u)
206 # requested username already exists. if they know the password,
207 # they can associate that account with the openid.
208 assoc = lambda req, form: self._associate_account(req, form, newname)
209 return MultistageFormLogin(assoc)
210
211 def _handle_associate_continuation(self, request):
212 if not 'openid.id' in request.session:
213 return CancelLogin(_('No OpenID found in session.'))
214
215 _ = request.getText
216 username = request.form.get('username', '')
217 password = request.form.get('password', '')
218 if not password:
219 return self._handle_name_continuation(request)
220 u = user.User(request, name=username, password=password,
221 auth_method=self.name,
222 auth_username=request.session['openid.id'],
223 auth_attribs=self.auth_attribs)
224 if u.valid:
225 self._handle_user_data(request, u)
226 return ContinueLogin(u, _('Your account is now associated to your OpenID.'))
227 else:
228 msg = _('The password you entered is not valid.')
229 assoc = lambda req, form: self._associate_account(req, form, username, msg=msg)
230 return MultistageFormLogin(assoc)
231
232 def _handle_continuation(self, request):
233 _ = request.getText
234 oidstage = request.values.get('oidstage')
235 if oidstage == '1':
236 logging.debug('OpenID: handle verify continuation')
237 return self._handle_verify_continuation(request)
238 elif oidstage == '2':
239 logging.debug('OpenID: handle name continuation')
240 return self._handle_name_continuation(request)
241 elif oidstage == '3':
242 logging.debug('OpenID: handle associate continuation')
243 return self._handle_associate_continuation(request)
244 logging.debug('OpenID error: unknown continuation stage')
245 return CancelLogin(_('OpenID error: unknown continuation stage'))
246
247 def _openid_form(self, request, form, oidhtml):
248 _ = request.getText
249 txt = _('OpenID verification requires that you click this button:')
250 # create JS to automatically submit the form if possible
251 submitjs = """<script type="text/javascript">
252<!--//
253document.getElementById("openid_message").submit();
254//-->
255</script>
256"""
257 return ''.join([txt, oidhtml, submitjs])
258
259 def login(self, request, user_obj, **kw):
260 continuation = kw.get('multistage')
261
262 if continuation:
263 return self._handle_continuation(request)
264
265 # openid is designed to work together with other auths
266 if user_obj and user_obj.valid:
267 return ContinueLogin(user_obj)
268
269 openid_id = kw.get('openid_identifier')
270
271 # nothing entered? continue...
272 if not self._forced_service and not openid_id:
273 return ContinueLogin(user_obj)
274
275 _ = request.getText
276
277 # user entered something but the session can't be stored
278 if not request.cfg.cookie_lifetime[0]:
279 return ContinueLogin(user_obj,
280 _('Anonymous sessions need to be enabled for OpenID login.'))
281
282 oidconsumer = consumer.Consumer(request.session,
283 MoinOpenIDStore(request))
284
285 try:
286 fserv = self._forced_service
287 if fserv:
288 if isinstance(fserv, str) or isinstance(fserv, unicode):
289 oidreq = oidconsumer.begin(fserv)
290 else:
291 oidreq = oidconsumer.beginWithoutDiscovery(fserv)
292 else:
293 oidreq = oidconsumer.begin(openid_id)
294 except HTTPFetchingError:
295 return ContinueLogin(None, _('Failed to resolve OpenID.'))
296 except DiscoveryFailure:
297 return ContinueLogin(None, _('OpenID discovery failure, not a valid OpenID.'))
298 else:
299 if oidreq is None:
300 return ContinueLogin(None, _('No OpenID.'))
301
302 self._modify_request(oidreq, request.cfg)
303
304 return_to = get_multistage_continuation_url(request, self.name,
305 {'oidstage': '1'})
306 trust_root = request.url_root
307 if oidreq.shouldSendRedirect():
308 redirect_url = oidreq.redirectURL(trust_root, return_to)
309 return MultistageRedirectLogin(redirect_url)
310 else:
311 form_html = oidreq.formMarkup(trust_root, return_to,
312 form_tag_attrs={'id': 'openid_message'})
313 mcall = lambda request, form:\
314 self._openid_form(request, form, form_html)
315 ret = MultistageFormLogin(mcall)
316 return ret
317
318 def login_hint(self, request):
319 _ = request.getText
320 msg = u''
321 if self._idselector_com:
322 msg = self._idselector_com
323 msg += _("If you do not have an account yet, you can still log in "
324 "with your OpenID and create one during login.")
325 return msg
0326
=== added file 'files/openidrp_teams.py'
--- files/openidrp_teams.py 1970-01-01 00:00:00 +0000
+++ files/openidrp_teams.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,157 @@
1# -*- coding: iso-8859-1 -*-
2"""
3 MoinMoin - Launchpad Teams Extension for OpenID authorization
4
5 @copyright: 2009 Canonical, Inc.
6 @license: GNU GPL, see COPYING for details.
7"""
8import time
9import re
10import os
11import logging
12import fcntl
13import errno
14import copy
15
16#from MoinMoin.util.moinoid import MoinOpenIDStore
17from MoinMoin import user
18from MoinMoin.auth import BaseAuth
19from MoinMoin.auth.openidrp import OpenIDAuth
20#OpenIDSREGAuth
21#from openid.consumer import consumer
22#from openid.yadis.discover import DiscoveryFailure
23#from openid.fetchers import HTTPFetchingError
24#from MoinMoin.widget import html
25#from MoinMoin.auth import CancelLogin, ContinueLogin
26#from MoinMoin.auth import MultistageFormLogin, MultistageRedirectLogin
27#from MoinMoin.auth import get_multistage_continuation_url
28
29from .teams import TeamsRequest, TeamsResponse, supportsTeams
30from MoinMoin import wikiutil
31from MoinMoin.PageEditor import PageEditor, conflict_markers
32from MoinMoin.Page import Page
33
34def openidrp_teams_modify_request(oidreq, cfg):
35 # Request Launchpad teams information, if configured
36 # should also check supportsTeams() result
37 #if teams_extension_avail and len(cfg.openidrp_authorized_teams) > 0:
38 if len(cfg.openidrp_authorized_teams) > 0:
39 oidreq.addExtension(TeamsRequest(cfg.openidrp_authorized_teams))
40
41def openidrp_teams_create_user(info, u, cfg):
42 # Check for Launchpad teams data in response
43 teams = None
44 #if teams_extension_avail and len(cfg.openidrp_authorized_teams) > 0:
45 teams_response = TeamsResponse.fromSuccessResponse(info)
46 teams = teams_response.is_member
47 if teams:
48 _save_teams_acl(u, teams, cfg)
49 return u
50
51def openidrp_teams_update_user(info, u, cfg):
52 teams = None
53 teams_response = TeamsResponse.fromSuccessResponse(info)
54 teams = teams_response.is_member
55 if teams:
56 _save_teams_acl(u, teams, cfg)
57
58# Take a list of Launchpad teams and add the user to the ACL pages
59# ACL group names cannot have "-" in them, although team names do.
60def _save_teams_acl(u, teams, cfg):
61 logging.log(logging.INFO, "running save_teams_acl...")
62
63 # remove any teams the user is no longer in
64 if not hasattr(u, 'teams'):
65 u.teams = []
66 logging.log(logging.INFO, "old teams: " + str(u.teams)
67 + " new teams: " + str(teams))
68
69 for t in u.teams:
70 if not t in teams:
71 logging.log(logging.INFO, "remove user from team: " + t)
72 team = t.strip().replace("-", "")
73 _remove_user_from_team(u, team, cfg)
74
75 for t in teams:
76 team = t.strip().replace("-", "")
77 if not team:
78 continue
79 logging.log(logging.INFO, "Launchpad team: " + team)
80 _add_user_to_team(u, team, cfg)
81
82 u.teams = teams
83 u.save()
84
85def _add_user_to_team(u, team, cfg):
86 # use admin account to create or edit ACL page
87 # http://moinmo.in/MoinDev/CommonTasks
88 acl_request = u._request
89 acl_request.user = user.User(acl_request, None, cfg.openidrp_acl_admin)
90
91 # PageEditor() is not safe to use concurrently - and browsers
92 # offten try to relogin to multiple tabs on the same wiki
93 # concurrently - due to its underlying reliance on the 'current'
94 # file to determine the current revision and the fact that
95 # PageEditor.saveText() moves 'current' out of the way as a
96 # lockfile. If you lose the race, you end up getting an
97 # apparently empty body for a page which in fact has content.
98 #
99 # Work around this by doing our own locking.
100
101 pagedir = os.path.join(u._request.cfg.data_dir, "pages",
102 team + cfg.openidrp_acl_page_postfix)
103 if not os.path.exists(pagedir):
104 os.mkdir(pagedir)
105 lockfile = os.path.join(pagedir, "openid.lock")
106 lock_fd = os.open(lockfile, os.O_RDWR | os.O_CREAT)
107 got_lock = False
108 retry = 0
109 while not got_lock and retry < 25:
110 retry += 1
111 try:
112 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
113 got_lock = True
114 except IOError, e:
115 got_lock = False
116 if (e.errno == errno.EACCES or e.errno == errno.EAGAIN):
117 time.sleep(0.1)
118 else:
119 raise
120 # If we can't get a lock, give up and return quietly. The user
121 # will simply have to logout and back in.
122 if not got_lock:
123 logging.log(logging.WARNING, "Could not acquire lock on " + lockfile)
124 return
125
126 pe = PageEditor(acl_request, team + cfg.openidrp_acl_page_postfix)
127 acl_text = pe.get_raw_body()
128 logging.log(logging.INFO, "ACL Page content: " + acl_text)
129 # make sure acl command is first line of document
130 # only the admin user specified in wikiconfig should
131 # be allowed to change these acl files
132 if not acl_text or acl_text == "" or acl_text[0] != "#":
133 acl_text = "#acl Known:read All:\n" + acl_text
134 # does ACL want uid, name, username, auth_username?
135 p = re.compile(ur"^ \* %s$" % u.name, re.MULTILINE)
136 if not p.search(acl_text):
137 logging.log(logging.INFO, "did not find user %s in acl, adding..." % u.name)
138 acl_text += u" * %s\n" % u.name
139 pe.saveText(acl_text, 0)
140 os.close(lock_fd)
141
142def _remove_user_from_team(u, team, cfg):
143 acl_request = u._request
144 acl_request.user = user.User(acl_request, None, cfg.openidrp_acl_admin)
145 pe = PageEditor(acl_request, team + cfg.openidrp_acl_page_postfix)
146 acl_text = pe.get_raw_body()
147 logging.log(logging.INFO, "ACL Page content: " + acl_text)
148 # does ACL want uid, name, username, auth_username?
149 p = re.compile(ur"^ \* %s$" % u.name, re.MULTILINE)
150 if p.search(acl_text):
151 logging.log(logging.INFO, "found user %s in acl, removing..." % u.name)
152 acl_text = acl_text.replace(" * %s\n" % u.name, "")
153 try:
154 pe.saveText(acl_text, 0)
155 except PageEditor.EmptyPage:
156 pe.deletePage()
157
0158
=== added file 'files/teams.py'
--- files/teams.py 1970-01-01 00:00:00 +0000
+++ files/teams.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,398 @@
1# Copyright (C) 2009, 2010 Canonical Ltd
2#
3# This program is free software: you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation, either version 3 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16"""Team membership support for Launchpad.
17
18The primary form of communication between the RP and Launchpad is an
19OpenID authentication request. Our solution is to piggyback a team
20membership test onto this interaction.
21
22As part of an OpenID authentication request, the RP includes the
23following fields:
24
25 openid.ns.lp:
26 An OpenID 2.0 namespace URI for the extension. It is not strictly
27 required for 1.1 requests, but including it is good for forward
28 compatibility.
29
30 It must be set to: http://ns.launchpad.net/2007/openid-teams
31
32 openid.lp.query_membership:
33 A comma separated list of Launchpad team names that the RP is
34 interested in.
35
36As part of the positive assertion OpenID response, the following field
37will be provided:
38
39 openid.ns.lp:
40 (as above)
41
42 openid.lp.is_member:
43 A comma separated list of teams that the user is actually a member
44 of. The list may be limited to those teams mentioned in the
45 request.
46
47 This field must be included in the response signature in order to
48 be considered valid (as the response is bounced through the user's
49 web browser, an unsigned value could be modified).
50
51@since: 2.1.1
52"""
53
54from openid.message import registerNamespaceAlias, \
55 NamespaceAliasRegistrationError
56from openid.extension import Extension
57from openid import oidutil
58
59try:
60 basestring #pylint:disable-msg=W0104
61except NameError:
62 # For Python 2.2
63 basestring = (str, unicode) #pylint:disable-msg=W0622
64
65__all__ = [
66 'TeamsRequest',
67 'TeamsResponse',
68 'ns_uri',
69 'supportsTeams',
70 ]
71
72ns_uri = 'http://ns.launchpad.net/2007/openid-teams'
73
74try:
75 registerNamespaceAlias(ns_uri, 'lp')
76except NamespaceAliasRegistrationError, e:
77 oidutil.log('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri,
78 'lp', str(e),))
79
80def supportsTeams(endpoint):
81 """Does the given endpoint advertise support for Launchpad Teams?
82
83 @param endpoint: The endpoint object as returned by OpenID discovery
84 @type endpoint: openid.consumer.discover.OpenIDEndpoint
85
86 @returns: Whether an lp type was advertised by the endpoint
87 @rtype: bool
88 """
89 return endpoint.usesExtension(ns_uri)
90
91class TeamsNamespaceError(ValueError):
92 """The Launchpad teams namespace was not found and could not
93 be created using the expected name (there's another extension
94 using the name 'lp')
95
96 This is not I{illegal}, for OpenID 2, although it probably
97 indicates a problem, since it's not expected that other extensions
98 will re-use the alias that is in use for OpenID 1.
99
100 If this is an OpenID 1 request, then there is no recourse. This
101 should not happen unless some code has modified the namespaces for
102 the message that is being processed.
103 """
104
105def getTeamsNS(message):
106 """Extract the Launchpad teams namespace URI from the given
107 OpenID message.
108
109 @param message: The OpenID message from which to parse Launchpad
110 teams. This may be a request or response message.
111 @type message: C{L{openid.message.Message}}
112
113 @returns: the lp namespace URI for the supplied message. The
114 message may be modified to define a Launchpad teams
115 namespace.
116 @rtype: C{str}
117
118 @raise ValueError: when using OpenID 1 if the message defines
119 the 'lp' alias to be something other than a Launchpad
120 teams type.
121 """
122 # See if there exists an alias for the Launchpad teams type.
123 alias = message.namespaces.getAlias(ns_uri)
124 if alias is None:
125 # There is no alias, so try to add one. (OpenID version 1)
126 try:
127 message.namespaces.addAlias(ns_uri, 'lp')
128 except KeyError, why:
129 # An alias for the string 'lp' already exists, but it's
130 # defined for something other than Launchpad teams
131 raise TeamsNamespaceError(why[0])
132
133 # we know that ns_uri defined, because it's defined in the
134 # else clause of the loop as well, so disable the warning
135 return ns_uri #pylint:disable-msg=W0631
136
137class TeamsRequest(Extension):
138 """An object to hold the state of a Launchpad teams request.
139
140 @ivar query_membership: A comma separated list of Launchpad team
141 names that the RP is interested in.
142 @type required: [str]
143
144 @group Consumer: requestField, requestTeams, getExtensionArgs, addToOpenIDRequest
145 @group Server: fromOpenIDRequest, parseExtensionArgs
146 """
147
148 ns_alias = 'lp'
149
150 def __init__(self, query_membership=None, lp_ns_uri=ns_uri):
151 """Initialize an empty Launchpad teams request"""
152 Extension.__init__(self)
153 self.query_membership = []
154 self.ns_uri = lp_ns_uri
155
156 if query_membership:
157 self.requestTeams(query_membership)
158
159 # Assign getTeamsNS to a static method so that it can be
160 # overridden for testing.
161 _getTeamsNS = staticmethod(getTeamsNS)
162
163 def fromOpenIDRequest(cls, request):
164 """Create a Launchpad teams request that contains the
165 fields that were requested in the OpenID request with the
166 given arguments
167
168 @param request: The OpenID request
169 @type request: openid.server.CheckIDRequest
170
171 @returns: The newly created Launchpad teams request
172 @rtype: C{L{TeamsRequest}}
173 """
174 self = cls()
175
176 # Since we're going to mess with namespace URI mapping, don't
177 # mutate the object that was passed in.
178 message = request.message.copy()
179
180 self.ns_uri = self._getTeamsNS(message)
181 args = message.getArgs(self.ns_uri)
182 self.parseExtensionArgs(args)
183
184 return self
185
186 fromOpenIDRequest = classmethod(fromOpenIDRequest)
187
188 def parseExtensionArgs(self, args, strict=False):
189 """Parse the unqualified Launchpad teams request
190 parameters and add them to this object.
191
192 This method is essentially the inverse of
193 C{L{getExtensionArgs}}. This method restores the serialized
194 Launchpad teams request fields.
195
196 If you are extracting arguments from a standard OpenID
197 checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
198 which will extract the lp namespace and arguments from the
199 OpenID request. This method is intended for cases where the
200 OpenID server needs more control over how the arguments are
201 parsed than that method provides.
202
203 >>> args = message.getArgs(ns_uri)
204 >>> request.parseExtensionArgs(args)
205
206 @param args: The unqualified Launchpad teams arguments
207 @type args: {str:str}
208
209 @param strict: Whether requests with fields that are not
210 defined in the Launchpad teams specification should be
211 tolerated (and ignored)
212 @type strict: bool
213
214 @returns: None; updates this object
215 """
216 items = args.get('query_membership')
217 if items:
218 for team_name in items.split(','):
219 try:
220 self.requestTeam(team_name, strict)
221 except ValueError:
222 if strict:
223 raise
224
225 def allRequestedTeams(self):
226 """A list of all of the Launchpad teams that were
227 requested.
228
229 @rtype: [str]
230 """
231 return self.query_membership
232
233 def wereTeamsRequested(self):
234 """Have any Launchpad teams been requested?
235
236 @rtype: bool
237 """
238 return bool(self.allRequestedTeams())
239
240 def __contains__(self, team_name):
241 """Was this team in the request?"""
242 return team_name in self.query_membership
243
244 def requestTeam(self, team_name, strict=False):
245 """Request the specified team from the OpenID user
246
247 @param team_name: the unqualified Launchpad team name
248 @type team_name: str
249
250 @param strict: whether to raise an exception when a team is
251 added to a request more than once
252
253 @raise ValueError: when strict is set and the team was
254 requested more than once
255 """
256 if strict:
257 if team_name in self.query_membership:
258 raise ValueError('That team has already been requested')
259 else:
260 if team_name in self.query_membership:
261 return
262
263 self.query_membership.append(team_name)
264
265 def requestTeams(self, query_membership, strict=False):
266 """Add the given list of teams to the request
267
268 @param query_membership: The Launchpad teams request
269 @type query_membership: [str]
270
271 @raise ValueError: when a team requested is not a string
272 or strict is set and a team was requested more than once
273 """
274 if isinstance(query_membership, basestring):
275 raise TypeError('Teams should be passed as a list of '
276 'strings (not %r)' % (type(query_membership),))
277
278 for team_name in query_membership:
279 self.requestTeam(team_name, strict=strict)
280
281 def getExtensionArgs(self):
282 """Get a dictionary of unqualified Launchpad teams
283 arguments representing this request.
284
285 This method is essentially the inverse of
286 C{L{parseExtensionArgs}}. This method serializes the Launchpad
287 teams request fields.
288
289 @rtype: {str:str}
290 """
291 args = {}
292
293 if self.query_membership:
294 args['query_membership'] = ','.join(self.query_membership)
295
296 return args
297
298class TeamsResponse(Extension):
299 """Represents the data returned in a Launchpad teams response
300 inside of an OpenID C{id_res} response. This object will be
301 created by the OpenID server, added to the C{id_res} response
302 object, and then extracted from the C{id_res} message by the
303 Consumer.
304
305 @ivar data: The Launchpad teams data, an array.
306
307 @ivar ns_uri: The URI under which the Launchpad teams data was
308 stored in the response message.
309
310 @group Server: extractResponse
311 @group Consumer: fromSuccessResponse
312 @group Read-only dictionary interface: keys, iterkeys, items, iteritems,
313 __iter__, get, __getitem__, keys, has_key
314 """
315
316 ns_alias = 'lp'
317
318 def __init__(self, is_member=None, lp_ns_uri=ns_uri):
319 Extension.__init__(self)
320 if is_member is None:
321 self.is_member = []
322 else:
323 self.is_member = is_member
324
325 self.ns_uri = lp_ns_uri
326
327 def addTeam(self, team_name):
328 if team_name not in self.is_member:
329 self.is_member.append(team_name)
330
331 def extractResponse(cls, request, is_member_str):
332 """Take a C{L{TeamsRequest}} and a list of Launchpad
333 team values and create a C{L{TeamsResponse}}
334 object containing that data.
335
336 @param request: The Launchpad teams request object
337 @type request: TeamsRequest
338
339 @param is_member: The Launchpad teams data for this
340 response, as a list of strings.
341 @type is_member: {str:str}
342
343 @returns: a Launchpad teams response object
344 @rtype: TeamsResponse
345 """
346 self = cls()
347 self.ns_uri = request.ns_uri
348 self.is_member = is_member_str.split(',')
349 return self
350
351 extractResponse = classmethod(extractResponse)
352
353 # Assign getTeamsNS to a static method so that it can be
354 # overridden for testing
355 _getTeamsNS = staticmethod(getTeamsNS)
356
357 def fromSuccessResponse(cls, success_response, signed_only=True):
358 """Create a C{L{TeamsResponse}} object from a successful OpenID
359 library response
360 (C{L{openid.consumer.consumer.SuccessResponse}}) response
361 message
362
363 @param success_response: A SuccessResponse from consumer.complete()
364 @type success_response: C{L{openid.consumer.consumer.SuccessResponse}}
365
366 @param signed_only: Whether to process only data that was
367 signed in the id_res message from the server.
368 @type signed_only: bool
369
370 @rtype: TeamsResponse
371 @returns: A Launchpad teams response containing the data
372 that was supplied with the C{id_res} response.
373 """
374 self = cls()
375 self.ns_uri = self._getTeamsNS(success_response.message)
376 if signed_only:
377 args = success_response.getSignedNS(self.ns_uri)
378 else:
379 args = success_response.message.getArgs(self.ns_uri)
380
381 if "is_member" in args:
382 is_member_str = args["is_member"]
383 self.is_member = is_member_str.split(',')
384 #self.is_member = args["is_member"]
385
386 return self
387
388 fromSuccessResponse = classmethod(fromSuccessResponse)
389
390 def getExtensionArgs(self):
391 """Get the fields to put in the Launchpad teams namespace
392 when adding them to an id_res message.
393
394 @see: openid.extension
395 """
396 ns_args = {'is_member': ','.join(self.is_member),}
397 return ns_args
398
0399
=== added directory 'hooks'
=== removed directory 'hooks'
=== added symlink 'hooks/config-changed'
=== target is u'hooks.py'
=== removed file 'hooks/config-changed'
--- hooks/config-changed 2013-05-07 21:32:01 +0000
+++ hooks/config-changed 1970-01-01 00:00:00 +0000
@@ -1,54 +0,0 @@
1#!/bin/bash
2
3set -eux
4
5export UNIT_NAME=`echo $JUJU_UNIT_NAME | cut -d/ -f1`
6
7export WIKI_NAME=$(config-get wiki_name)
8export ADMIN_NAME=$(config-get admin_name)
9export LANGUAGES=$(config-get languages)
10export XAPIAN_SETTINGS=$(config-get xapian_search)
11export EXTRA_SETTINGS=$(config-get extra_settings)
12export PORT=$(config-get listen_port)
13
14juju-log "variables: WIKI_NAME: $WIKI_NAME,ADMIN_NAME: $ADMIN_NAME ,LANGUAGES: $LANGUAGES ,XAPIAN_SETTINGS: $XAPIAN_SETTINGS"
15
16if [ -f /etc/gunicorn.d/${UNIT_NAME}.conf ]; then
17 CURRENT_PORT=$(grep '\-\-bind' /etc/gunicorn.d/${UNIT_NAME}.conf | cut -d: -f2 | sed "s/'.*//")
18else
19 CURRENT_PORT=$(config-get listen_port)
20fi
21
22cheetah fill --env -p templates/wikiconfig.py.tmpl > /srv/${UNIT_NAME}/wikiconfig.py
23
24cheetah fill --env -p templates/wsgi.py.tmpl > /srv/${UNIT_NAME}/wsgi.py
25
26cheetah fill --env -p templates/logging.conf.tmpl > /srv/${UNIT_NAME}/logging.conf
27
28cheetah fill --env -p templates/gunicorn.conf.tmpl > /etc/gunicorn.d/${UNIT_NAME}.conf
29
30if [ $CURRENT_PORT != $PORT ]; then
31 close-port $CURRENT_PORT/tcp
32 open-port $PORT/tcp
33fi
34
35if [ "$XAPIAN_SETTINGS" == "True" ] ; then
36 if [ ! -e /srv/${UNIT_NAME}/xapian_is_initialized ] ; then
37 moin --config-dir=/srv/${UNIT_NAME}/ index build --mode=add
38 touch /srv/${UNIT_NAME}/xapian_is_initialized
39 else
40 moin --config-dir=/srv/${UNIT_NAME}/ index build --mode=rebuild
41 fi
42fi
43
44cd /srv/${UNIT_NAME}/
45
46for lang in $LANGUAGES; do
47 python -m MoinMoin.packages i ./underlay/pages/LanguageSetup/attachments/${lang}--all_pages.zip
48done
49
50chown root:www-data /srv/${UNIT_NAME}/ -R
51chmod g+rw /srv/${UNIT_NAME}/ -R
52
53/etc/init.d/gunicorn start
54/etc/init.d/gunicorn restart
550
=== added file 'hooks/hooks.py'
--- hooks/hooks.py 1970-01-01 00:00:00 +0000
+++ hooks/hooks.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,226 @@
1#!/usr/bin/env python
2
3# Copyright 2013 Canonical Ltd. All rights reserved.
4# Author: Brad Marshall <brad.marshall@canonical.com>
5
6import glob
7import os
8import sys
9import shutil
10import subprocess
11import socket
12import stat
13import pwd
14import grp
15import json
16import yaml
17import distutils.sysconfig
18
19local_copy = os.path.join(
20 os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
21 "lib", "charm-helpers")
22if os.path.exists(local_copy) and os.path.isdir(local_copy):
23 sys.path.insert(0, local_copy)
24
25
26from charmhelpers.core.host import (
27 mkdir,
28 service,
29 service_start,
30 service_stop,
31 service_restart,
32 write_file,
33)
34
35from charmhelpers.core.hookenv import (
36 Hooks,
37 config,
38 open_port,
39 close_port,
40 relation_get,
41 relation_set,
42 relation_id,
43 remote_unit,
44 local_unit,
45)
46
47from charmhelpers.fetch import (
48 apt_install,
49)
50
51unit_name = local_unit().split("/")[0]
52hostname = socket.getfqdn()
53basedir = "/srv/" + unit_name
54rundir = basedir + "/run"
55logdir = basedir + "/logs"
56staticdir = basedir + "/moin_static"
57wikiconfig = basedir + "/wikiconfig.py"
58wsgipy = basedir + "/wsgi.py"
59loggingconf = basedir + "/logging.conf"
60xapian_initialised = basedir + "/xapian_is_initialized"
61gunicornconf = "/etc/gunicorn.d/" + unit_name + ".conf"
62wiki_name = config().get('wiki_name')
63admin_name = config().get('admin_name')
64languages = config().get('languages')
65loglevel = config().get('loglevel')
66xapian_search = config().get('xapian_search')
67listen_port = config().get('listen_port')
68use_openid = config().get('use_openid')
69openidrp_authorized_teams = config().get('openidrp_authorized_teams')
70extra_settings = config().get('extra_settings')
71
72hook_dir = os.path.abspath(os.path.dirname(__file__))
73charm_dir = os.path.dirname(hook_dir)
74
75required_pkgs = [
76 'python-moinmoin',
77 'python-flup',
78 'gunicorn',
79 'python-eventlet',
80 'python-tz',
81 'unzip',
82 'python-openid',
83 'python-xapian',
84 'python-xappy',
85 'python-docutils',
86 'python-jinja2'
87]
88
89hooks = Hooks()
90
91
92@hooks.hook()
93def install():
94 apt_install(required_pkgs, options=['--force-yes'])
95 if os.path.exists('/etc/moin/farmconfig.py'):
96 os.remove('/etc/moin/farmconfig.py')
97 if not os.path.exists(rundir):
98 os.makedirs(rundir)
99 if not os.path.exists(logdir):
100 os.makedirs(logdir)
101 if not os.path.exists(basedir + "/data"):
102 shutil.copytree('/usr/share/moin/data', basedir + "/data")
103 if not os.path.exists(basedir + "/underlay"):
104 shutil.copytree('/usr/share/moin/underlay', basedir + "/underlay")
105 if not os.path.exists(staticdir):
106 shutil.copytree('/usr/share/moin/htdocs', staticdir)
107
108
109@hooks.hook("config-changed")
110def config_changed():
111 # See if the port has changed
112 if (os.path.exists(gunicornconf)):
113 for line in open(gunicornconf):
114 if "--bind" in line:
115 port = line.split("=")[1].split(":")[1].rstrip("',\r\n")
116 break
117 if (listen_port != port):
118 close_port(port)
119 open_port(listen_port)
120
121 # Create files from templates
122 from jinja2 import Environment, FileSystemLoader
123 template_env = Environment(
124 loader=FileSystemLoader(os.path.join(os.environ['CHARM_DIR'],
125 'templates')))
126 templ_vars = {
127 'basedir': basedir,
128 'unit_name': unit_name,
129 'wiki_name': wiki_name,
130 'admin_name': admin_name,
131 'languages': languages,
132 'loglevel': loglevel,
133 'xapian_search': xapian_search,
134 'listen_port': listen_port,
135 'use_openid': use_openid,
136 'openidrp_authorized_teams': openidrp_authorized_teams,
137 'extra_settings': extra_settings,
138 }
139
140 # gunicorn.conf.tmpl logging.conf.tmpl wikiconfig.py.tmpl wsgi.py.tmpl
141 wikiconfigtemplate = \
142 template_env.get_template('wikiconfig.py.tmpl').render(templ_vars)
143 with open(wikiconfig, 'w') as wikiconfig_config:
144 wikiconfig_config.write(str(wikiconfigtemplate))
145 wsgipytemplate = \
146 template_env.get_template('wsgi.py.tmpl').render(templ_vars)
147 with open(wsgipy, 'w') as wsgipy_config:
148 wsgipy_config.write(str(wsgipytemplate))
149 loggingconftemplate = \
150 template_env.get_template('logging.conf.tmpl').render(templ_vars)
151 with open(loggingconf, 'w') as loggingconf_config:
152 loggingconf_config.write(str(loggingconftemplate))
153 gunicornconftemplate = \
154 template_env.get_template('gunicorn.conf.tmpl').render(templ_vars)
155 with open(gunicornconf, 'w') as gunicornconf_config:
156 gunicornconf_config.write(str(gunicornconftemplate))
157
158 # Handle xapian search updates
159 if (xapian_search == "True"):
160 if not os.path.exists(xapian_initialised):
161 subprocess.call(['moin', "--config-dir=%s/" % (basedir), 'index',
162 'build', '--mode=add'])
163 open(xapian_initialised, 'w').close()
164 else:
165 subprocess.call(['moin', "--config=dir=%s/" % (basedir), 'index',
166 'build', '--mode=rebuild'])
167
168 # Install languages
169 for lang in languages.split():
170 subprocess.call(['python', '-m', 'MoinMoin.packages', 'i',
171 "%s/underlay/pages/LanguageSetup/attachments/%s--all_pages.zip"
172 % (basedir, lang)], cwd=basedir)
173
174 # fix perms to be owned by root:www-data and g+rwX
175 root_uid = pwd.getpwnam('root').pw_uid
176 www_gid = grp.getgrnam('www-data').gr_gid
177 for root, dirs, files in os.walk(basedir):
178 for d in dirs:
179 os.chown(os.path.join(root, d), root_uid, www_gid)
180 os.chmod(os.path.join(root, d), 0775)
181 for f in files:
182 os.chown(os.path.join(root, f), root_uid, www_gid)
183 os.chmod(os.path.join(root, f), 0664)
184
185 # if we are using openid make sure files are in place
186 openid_python_path = "/usr/share/pyshared/MoinMoin/auth/openidrp_ext"
187 dist_dir = distutils.sysconfig.get_python_lib()
188 if (use_openid == "True"):
189 # Copy the openidrp.py file in place
190 shutil.copyfile("files/openidrp.py",
191 "%s/MoinMoin/auth/openidrp.py" % (dist_dir))
192 # Copy the openidrp_teams.py file in place
193 shutil.copyfile("files/openidrp_teams.py",
194 "%s/openidrp_teams.py" % (openid_python_path))
195 # Only copy and symlink the teams.py in place if we don't have it
196 if not os.path.exists("%s/teams.py" % (openid_python_path)):
197 shutil.copyfile("files/teams.py", "%s/teams.py"
198 % (openid_python_path))
199 os.symlink("%s/teams.py" % (openid_python_path),
200 "%s/MoinMoin/auth/openidrp_ext/teams.py" % (dist_dir))
201
202 service_restart('gunicorn')
203
204
205@hooks.hook("website-relation-joined")
206def website_relation_join():
207 relation_set(port=listen_port, hostname=hostname)
208
209
210@hooks.hook("upgrade-charm")
211def upgrade_charm():
212 install()
213
214
215@hooks.hook("start")
216def start():
217 service_start('gunicorn')
218
219
220@hooks.hook("stop")
221def stop():
222 service_stop('gunicorn')
223
224
225if __name__ == "__main__":
226 hooks.execute(sys.argv)
0227
=== added symlink 'hooks/install'
=== target is u'hooks.py'
=== removed file 'hooks/install'
--- hooks/install 2013-05-07 16:36:59 +0000
+++ hooks/install 1970-01-01 00:00:00 +0000
@@ -1,19 +0,0 @@
1#!/bin/bash
2
3UNIT_NAME=`echo $JUJU_UNIT_NAME | cut -d/ -f1`
4
5# --no-install-recommends and not fckeditor: because we don't want apache2 here.
6
7apt-get install --no-install-recommends -y python-moinmoin python-flup \
8 gunicorn python-eventlet unzip python-openid python-xapian python-xappy \
9 python-docutils python-cheetah
10
11# MoinMoin's command line script 'moin' check there first
12# and we don't want that
13rm /etc/moin/farmconfig.py
14
15mkdir -p /srv/${UNIT_NAME}/run
16mkdir -p /srv/${UNIT_NAME}/logs
17
18cp -r /usr/share/moin/data /usr/share/moin/underlay /srv/${UNIT_NAME}/
19cp -r /usr/share/moin/htdocs /srv/${UNIT_NAME}/moin_static
200
=== added symlink 'hooks/start'
=== target is u'hooks.py'
=== removed file 'hooks/start'
--- hooks/start 2011-11-01 20:33:21 +0000
+++ hooks/start 1970-01-01 00:00:00 +0000
@@ -1,4 +0,0 @@
1#!/bin/bash
2# Here put anything that is needed to start the service.
3# Note that currently this is run directly after install
4# i.e. 'service apache2 start'
50
=== added symlink 'hooks/stop'
=== target is u'hooks.py'
=== removed file 'hooks/stop'
--- hooks/stop 2011-11-01 20:33:21 +0000
+++ hooks/stop 1970-01-01 00:00:00 +0000
@@ -1,7 +0,0 @@
1#!/bin/bash
2# This will be run when the service is being torn down, allowing you to disable
3# it in various ways..
4# For example, if your web app uses a text file to signal to the load balancer
5# that it is live... you could remove it and sleep for a bit to allow the load
6# balancer to stop sending traffic.
7# rm /srv/webroot/server-live.txt && sleep 30
80
=== added symlink 'hooks/upgrade-charm'
=== target is u'hooks.py'
=== added symlink 'hooks/website-relation-joined'
=== target is u'hooks.py'
=== removed file 'hooks/website-relation-joined'
--- hooks/website-relation-joined 2013-05-07 16:03:30 +0000
+++ hooks/website-relation-joined 1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
1#!/bin/sh
2relation-set port=$(config-get listen_port) hostname=$(hostname -f)
30
=== added directory 'lib'
=== added directory 'lib/charm-helpers'
=== added file 'lib/charm-helpers/LICENSE.txt'
--- lib/charm-helpers/LICENSE.txt 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/LICENSE.txt 2013-09-26 06:24:47 +0000
@@ -0,0 +1,661 @@
1 GNU AFFERO GENERAL PUBLIC LICENSE
2 Version 3, 19 November 2007
3
4 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5 Everyone is permitted to copy and distribute verbatim copies
6 of this license document, but changing it is not allowed.
7
8 Preamble
9
10 The GNU Affero General Public License is a free, copyleft license for
11software and other kinds of works, specifically designed to ensure
12cooperation with the community in the case of network server software.
13
14 The licenses for most software and other practical works are designed
15to take away your freedom to share and change the works. By contrast,
16our General Public Licenses are intended to guarantee your freedom to
17share and change all versions of a program--to make sure it remains free
18software for all its users.
19
20 When we speak of free software, we are referring to freedom, not
21price. Our General Public Licenses are designed to make sure that you
22have the freedom to distribute copies of free software (and charge for
23them if you wish), that you receive source code or can get it if you
24want it, that you can change the software or use pieces of it in new
25free programs, and that you know you can do these things.
26
27 Developers that use our General Public Licenses protect your rights
28with two steps: (1) assert copyright on the software, and (2) offer
29you this License which gives you legal permission to copy, distribute
30and/or modify the software.
31
32 A secondary benefit of defending all users' freedom is that
33improvements made in alternate versions of the program, if they
34receive widespread use, become available for other developers to
35incorporate. Many developers of free software are heartened and
36encouraged by the resulting cooperation. However, in the case of
37software used on network servers, this result may fail to come about.
38The GNU General Public License permits making a modified version and
39letting the public access it on a server without ever releasing its
40source code to the public.
41
42 The GNU Affero General Public License is designed specifically to
43ensure that, in such cases, the modified source code becomes available
44to the community. It requires the operator of a network server to
45provide the source code of the modified version running there to the
46users of that server. Therefore, public use of a modified version, on
47a publicly accessible server, gives the public access to the source
48code of the modified version.
49
50 An older license, called the Affero General Public License and
51published by Affero, was designed to accomplish similar goals. This is
52a different license, not a version of the Affero GPL, but Affero has
53released a new version of the Affero GPL which permits relicensing under
54this license.
55
56 The precise terms and conditions for copying, distribution and
57modification follow.
58
59 TERMS AND CONDITIONS
60
61 0. Definitions.
62
63 "This License" refers to version 3 of the GNU Affero General Public License.
64
65 "Copyright" also means copyright-like laws that apply to other kinds of
66works, such as semiconductor masks.
67
68 "The Program" refers to any copyrightable work licensed under this
69License. Each licensee is addressed as "you". "Licensees" and
70"recipients" may be individuals or organizations.
71
72 To "modify" a work means to copy from or adapt all or part of the work
73in a fashion requiring copyright permission, other than the making of an
74exact copy. The resulting work is called a "modified version" of the
75earlier work or a work "based on" the earlier work.
76
77 A "covered work" means either the unmodified Program or a work based
78on the Program.
79
80 To "propagate" a work means to do anything with it that, without
81permission, would make you directly or secondarily liable for
82infringement under applicable copyright law, except executing it on a
83computer or modifying a private copy. Propagation includes copying,
84distribution (with or without modification), making available to the
85public, and in some countries other activities as well.
86
87 To "convey" a work means any kind of propagation that enables other
88parties to make or receive copies. Mere interaction with a user through
89a computer network, with no transfer of a copy, is not conveying.
90
91 An interactive user interface displays "Appropriate Legal Notices"
92to the extent that it includes a convenient and prominently visible
93feature that (1) displays an appropriate copyright notice, and (2)
94tells the user that there is no warranty for the work (except to the
95extent that warranties are provided), that licensees may convey the
96work under this License, and how to view a copy of this License. If
97the interface presents a list of user commands or options, such as a
98menu, a prominent item in the list meets this criterion.
99
100 1. Source Code.
101
102 The "source code" for a work means the preferred form of the work
103for making modifications to it. "Object code" means any non-source
104form of a work.
105
106 A "Standard Interface" means an interface that either is an official
107standard defined by a recognized standards body, or, in the case of
108interfaces specified for a particular programming language, one that
109is widely used among developers working in that language.
110
111 The "System Libraries" of an executable work include anything, other
112than the work as a whole, that (a) is included in the normal form of
113packaging a Major Component, but which is not part of that Major
114Component, and (b) serves only to enable use of the work with that
115Major Component, or to implement a Standard Interface for which an
116implementation is available to the public in source code form. A
117"Major Component", in this context, means a major essential component
118(kernel, window system, and so on) of the specific operating system
119(if any) on which the executable work runs, or a compiler used to
120produce the work, or an object code interpreter used to run it.
121
122 The "Corresponding Source" for a work in object code form means all
123the source code needed to generate, install, and (for an executable
124work) run the object code and to modify the work, including scripts to
125control those activities. However, it does not include the work's
126System Libraries, or general-purpose tools or generally available free
127programs which are used unmodified in performing those activities but
128which are not part of the work. For example, Corresponding Source
129includes interface definition files associated with source files for
130the work, and the source code for shared libraries and dynamically
131linked subprograms that the work is specifically designed to require,
132such as by intimate data communication or control flow between those
133subprograms and other parts of the work.
134
135 The Corresponding Source need not include anything that users
136can regenerate automatically from other parts of the Corresponding
137Source.
138
139 The Corresponding Source for a work in source code form is that
140same work.
141
142 2. Basic Permissions.
143
144 All rights granted under this License are granted for the term of
145copyright on the Program, and are irrevocable provided the stated
146conditions are met. This License explicitly affirms your unlimited
147permission to run the unmodified Program. The output from running a
148covered work is covered by this License only if the output, given its
149content, constitutes a covered work. This License acknowledges your
150rights of fair use or other equivalent, as provided by copyright law.
151
152 You may make, run and propagate covered works that you do not
153convey, without conditions so long as your license otherwise remains
154in force. You may convey covered works to others for the sole purpose
155of having them make modifications exclusively for you, or provide you
156with facilities for running those works, provided that you comply with
157the terms of this License in conveying all material for which you do
158not control copyright. Those thus making or running the covered works
159for you must do so exclusively on your behalf, under your direction
160and control, on terms that prohibit them from making any copies of
161your copyrighted material outside their relationship with you.
162
163 Conveying under any other circumstances is permitted solely under
164the conditions stated below. Sublicensing is not allowed; section 10
165makes it unnecessary.
166
167 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
169 No covered work shall be deemed part of an effective technological
170measure under any applicable law fulfilling obligations under article
17111 of the WIPO copyright treaty adopted on 20 December 1996, or
172similar laws prohibiting or restricting circumvention of such
173measures.
174
175 When you convey a covered work, you waive any legal power to forbid
176circumvention of technological measures to the extent such circumvention
177is effected by exercising rights under this License with respect to
178the covered work, and you disclaim any intention to limit operation or
179modification of the work as a means of enforcing, against the work's
180users, your or third parties' legal rights to forbid circumvention of
181technological measures.
182
183 4. Conveying Verbatim Copies.
184
185 You may convey verbatim copies of the Program's source code as you
186receive it, in any medium, provided that you conspicuously and
187appropriately publish on each copy an appropriate copyright notice;
188keep intact all notices stating that this License and any
189non-permissive terms added in accord with section 7 apply to the code;
190keep intact all notices of the absence of any warranty; and give all
191recipients a copy of this License along with the Program.
192
193 You may charge any price or no price for each copy that you convey,
194and you may offer support or warranty protection for a fee.
195
196 5. Conveying Modified Source Versions.
197
198 You may convey a work based on the Program, or the modifications to
199produce it from the Program, in the form of source code under the
200terms of section 4, provided that you also meet all of these conditions:
201
202 a) The work must carry prominent notices stating that you modified
203 it, and giving a relevant date.
204
205 b) The work must carry prominent notices stating that it is
206 released under this License and any conditions added under section
207 7. This requirement modifies the requirement in section 4 to
208 "keep intact all notices".
209
210 c) You must license the entire work, as a whole, under this
211 License to anyone who comes into possession of a copy. This
212 License will therefore apply, along with any applicable section 7
213 additional terms, to the whole of the work, and all its parts,
214 regardless of how they are packaged. This License gives no
215 permission to license the work in any other way, but it does not
216 invalidate such permission if you have separately received it.
217
218 d) If the work has interactive user interfaces, each must display
219 Appropriate Legal Notices; however, if the Program has interactive
220 interfaces that do not display Appropriate Legal Notices, your
221 work need not make them do so.
222
223 A compilation of a covered work with other separate and independent
224works, which are not by their nature extensions of the covered work,
225and which are not combined with it such as to form a larger program,
226in or on a volume of a storage or distribution medium, is called an
227"aggregate" if the compilation and its resulting copyright are not
228used to limit the access or legal rights of the compilation's users
229beyond what the individual works permit. Inclusion of a covered work
230in an aggregate does not cause this License to apply to the other
231parts of the aggregate.
232
233 6. Conveying Non-Source Forms.
234
235 You may convey a covered work in object code form under the terms
236of sections 4 and 5, provided that you also convey the
237machine-readable Corresponding Source under the terms of this License,
238in one of these ways:
239
240 a) Convey the object code in, or embodied in, a physical product
241 (including a physical distribution medium), accompanied by the
242 Corresponding Source fixed on a durable physical medium
243 customarily used for software interchange.
244
245 b) Convey the object code in, or embodied in, a physical product
246 (including a physical distribution medium), accompanied by a
247 written offer, valid for at least three years and valid for as
248 long as you offer spare parts or customer support for that product
249 model, to give anyone who possesses the object code either (1) a
250 copy of the Corresponding Source for all the software in the
251 product that is covered by this License, on a durable physical
252 medium customarily used for software interchange, for a price no
253 more than your reasonable cost of physically performing this
254 conveying of source, or (2) access to copy the
255 Corresponding Source from a network server at no charge.
256
257 c) Convey individual copies of the object code with a copy of the
258 written offer to provide the Corresponding Source. This
259 alternative is allowed only occasionally and noncommercially, and
260 only if you received the object code with such an offer, in accord
261 with subsection 6b.
262
263 d) Convey the object code by offering access from a designated
264 place (gratis or for a charge), and offer equivalent access to the
265 Corresponding Source in the same way through the same place at no
266 further charge. You need not require recipients to copy the
267 Corresponding Source along with the object code. If the place to
268 copy the object code is a network server, the Corresponding Source
269 may be on a different server (operated by you or a third party)
270 that supports equivalent copying facilities, provided you maintain
271 clear directions next to the object code saying where to find the
272 Corresponding Source. Regardless of what server hosts the
273 Corresponding Source, you remain obligated to ensure that it is
274 available for as long as needed to satisfy these requirements.
275
276 e) Convey the object code using peer-to-peer transmission, provided
277 you inform other peers where the object code and Corresponding
278 Source of the work are being offered to the general public at no
279 charge under subsection 6d.
280
281 A separable portion of the object code, whose source code is excluded
282from the Corresponding Source as a System Library, need not be
283included in conveying the object code work.
284
285 A "User Product" is either (1) a "consumer product", which means any
286tangible personal property which is normally used for personal, family,
287or household purposes, or (2) anything designed or sold for incorporation
288into a dwelling. In determining whether a product is a consumer product,
289doubtful cases shall be resolved in favor of coverage. For a particular
290product received by a particular user, "normally used" refers to a
291typical or common use of that class of product, regardless of the status
292of the particular user or of the way in which the particular user
293actually uses, or expects or is expected to use, the product. A product
294is a consumer product regardless of whether the product has substantial
295commercial, industrial or non-consumer uses, unless such uses represent
296the only significant mode of use of the product.
297
298 "Installation Information" for a User Product means any methods,
299procedures, authorization keys, or other information required to install
300and execute modified versions of a covered work in that User Product from
301a modified version of its Corresponding Source. The information must
302suffice to ensure that the continued functioning of the modified object
303code is in no case prevented or interfered with solely because
304modification has been made.
305
306 If you convey an object code work under this section in, or with, or
307specifically for use in, a User Product, and the conveying occurs as
308part of a transaction in which the right of possession and use of the
309User Product is transferred to the recipient in perpetuity or for a
310fixed term (regardless of how the transaction is characterized), the
311Corresponding Source conveyed under this section must be accompanied
312by the Installation Information. But this requirement does not apply
313if neither you nor any third party retains the ability to install
314modified object code on the User Product (for example, the work has
315been installed in ROM).
316
317 The requirement to provide Installation Information does not include a
318requirement to continue to provide support service, warranty, or updates
319for a work that has been modified or installed by the recipient, or for
320the User Product in which it has been modified or installed. Access to a
321network may be denied when the modification itself materially and
322adversely affects the operation of the network or violates the rules and
323protocols for communication across the network.
324
325 Corresponding Source conveyed, and Installation Information provided,
326in accord with this section must be in a format that is publicly
327documented (and with an implementation available to the public in
328source code form), and must require no special password or key for
329unpacking, reading or copying.
330
331 7. Additional Terms.
332
333 "Additional permissions" are terms that supplement the terms of this
334License by making exceptions from one or more of its conditions.
335Additional permissions that are applicable to the entire Program shall
336be treated as though they were included in this License, to the extent
337that they are valid under applicable law. If additional permissions
338apply only to part of the Program, that part may be used separately
339under those permissions, but the entire Program remains governed by
340this License without regard to the additional permissions.
341
342 When you convey a copy of a covered work, you may at your option
343remove any additional permissions from that copy, or from any part of
344it. (Additional permissions may be written to require their own
345removal in certain cases when you modify the work.) You may place
346additional permissions on material, added by you to a covered work,
347for which you have or can give appropriate copyright permission.
348
349 Notwithstanding any other provision of this License, for material you
350add to a covered work, you may (if authorized by the copyright holders of
351that material) supplement the terms of this License with terms:
352
353 a) Disclaiming warranty or limiting liability differently from the
354 terms of sections 15 and 16 of this License; or
355
356 b) Requiring preservation of specified reasonable legal notices or
357 author attributions in that material or in the Appropriate Legal
358 Notices displayed by works containing it; or
359
360 c) Prohibiting misrepresentation of the origin of that material, or
361 requiring that modified versions of such material be marked in
362 reasonable ways as different from the original version; or
363
364 d) Limiting the use for publicity purposes of names of licensors or
365 authors of the material; or
366
367 e) Declining to grant rights under trademark law for use of some
368 trade names, trademarks, or service marks; or
369
370 f) Requiring indemnification of licensors and authors of that
371 material by anyone who conveys the material (or modified versions of
372 it) with contractual assumptions of liability to the recipient, for
373 any liability that these contractual assumptions directly impose on
374 those licensors and authors.
375
376 All other non-permissive additional terms are considered "further
377restrictions" within the meaning of section 10. If the Program as you
378received it, or any part of it, contains a notice stating that it is
379governed by this License along with a term that is a further
380restriction, you may remove that term. If a license document contains
381a further restriction but permits relicensing or conveying under this
382License, you may add to a covered work material governed by the terms
383of that license document, provided that the further restriction does
384not survive such relicensing or conveying.
385
386 If you add terms to a covered work in accord with this section, you
387must place, in the relevant source files, a statement of the
388additional terms that apply to those files, or a notice indicating
389where to find the applicable terms.
390
391 Additional terms, permissive or non-permissive, may be stated in the
392form of a separately written license, or stated as exceptions;
393the above requirements apply either way.
394
395 8. Termination.
396
397 You may not propagate or modify a covered work except as expressly
398provided under this License. Any attempt otherwise to propagate or
399modify it is void, and will automatically terminate your rights under
400this License (including any patent licenses granted under the third
401paragraph of section 11).
402
403 However, if you cease all violation of this License, then your
404license from a particular copyright holder is reinstated (a)
405provisionally, unless and until the copyright holder explicitly and
406finally terminates your license, and (b) permanently, if the copyright
407holder fails to notify you of the violation by some reasonable means
408prior to 60 days after the cessation.
409
410 Moreover, your license from a particular copyright holder is
411reinstated permanently if the copyright holder notifies you of the
412violation by some reasonable means, this is the first time you have
413received notice of violation of this License (for any work) from that
414copyright holder, and you cure the violation prior to 30 days after
415your receipt of the notice.
416
417 Termination of your rights under this section does not terminate the
418licenses of parties who have received copies or rights from you under
419this License. If your rights have been terminated and not permanently
420reinstated, you do not qualify to receive new licenses for the same
421material under section 10.
422
423 9. Acceptance Not Required for Having Copies.
424
425 You are not required to accept this License in order to receive or
426run a copy of the Program. Ancillary propagation of a covered work
427occurring solely as a consequence of using peer-to-peer transmission
428to receive a copy likewise does not require acceptance. However,
429nothing other than this License grants you permission to propagate or
430modify any covered work. These actions infringe copyright if you do
431not accept this License. Therefore, by modifying or propagating a
432covered work, you indicate your acceptance of this License to do so.
433
434 10. Automatic Licensing of Downstream Recipients.
435
436 Each time you convey a covered work, the recipient automatically
437receives a license from the original licensors, to run, modify and
438propagate that work, subject to this License. You are not responsible
439for enforcing compliance by third parties with this License.
440
441 An "entity transaction" is a transaction transferring control of an
442organization, or substantially all assets of one, or subdividing an
443organization, or merging organizations. If propagation of a covered
444work results from an entity transaction, each party to that
445transaction who receives a copy of the work also receives whatever
446licenses to the work the party's predecessor in interest had or could
447give under the previous paragraph, plus a right to possession of the
448Corresponding Source of the work from the predecessor in interest, if
449the predecessor has it or can get it with reasonable efforts.
450
451 You may not impose any further restrictions on the exercise of the
452rights granted or affirmed under this License. For example, you may
453not impose a license fee, royalty, or other charge for exercise of
454rights granted under this License, and you may not initiate litigation
455(including a cross-claim or counterclaim in a lawsuit) alleging that
456any patent claim is infringed by making, using, selling, offering for
457sale, or importing the Program or any portion of it.
458
459 11. Patents.
460
461 A "contributor" is a copyright holder who authorizes use under this
462License of the Program or a work on which the Program is based. The
463work thus licensed is called the contributor's "contributor version".
464
465 A contributor's "essential patent claims" are all patent claims
466owned or controlled by the contributor, whether already acquired or
467hereafter acquired, that would be infringed by some manner, permitted
468by this License, of making, using, or selling its contributor version,
469but do not include claims that would be infringed only as a
470consequence of further modification of the contributor version. For
471purposes of this definition, "control" includes the right to grant
472patent sublicenses in a manner consistent with the requirements of
473this License.
474
475 Each contributor grants you a non-exclusive, worldwide, royalty-free
476patent license under the contributor's essential patent claims, to
477make, use, sell, offer for sale, import and otherwise run, modify and
478propagate the contents of its contributor version.
479
480 In the following three paragraphs, a "patent license" is any express
481agreement or commitment, however denominated, not to enforce a patent
482(such as an express permission to practice a patent or covenant not to
483sue for patent infringement). To "grant" such a patent license to a
484party means to make such an agreement or commitment not to enforce a
485patent against the party.
486
487 If you convey a covered work, knowingly relying on a patent license,
488and the Corresponding Source of the work is not available for anyone
489to copy, free of charge and under the terms of this License, through a
490publicly available network server or other readily accessible means,
491then you must either (1) cause the Corresponding Source to be so
492available, or (2) arrange to deprive yourself of the benefit of the
493patent license for this particular work, or (3) arrange, in a manner
494consistent with the requirements of this License, to extend the patent
495license to downstream recipients. "Knowingly relying" means you have
496actual knowledge that, but for the patent license, your conveying the
497covered work in a country, or your recipient's use of the covered work
498in a country, would infringe one or more identifiable patents in that
499country that you have reason to believe are valid.
500
501 If, pursuant to or in connection with a single transaction or
502arrangement, you convey, or propagate by procuring conveyance of, a
503covered work, and grant a patent license to some of the parties
504receiving the covered work authorizing them to use, propagate, modify
505or convey a specific copy of the covered work, then the patent license
506you grant is automatically extended to all recipients of the covered
507work and works based on it.
508
509 A patent license is "discriminatory" if it does not include within
510the scope of its coverage, prohibits the exercise of, or is
511conditioned on the non-exercise of one or more of the rights that are
512specifically granted under this License. You may not convey a covered
513work if you are a party to an arrangement with a third party that is
514in the business of distributing software, under which you make payment
515to the third party based on the extent of your activity of conveying
516the work, and under which the third party grants, to any of the
517parties who would receive the covered work from you, a discriminatory
518patent license (a) in connection with copies of the covered work
519conveyed by you (or copies made from those copies), or (b) primarily
520for and in connection with specific products or compilations that
521contain the covered work, unless you entered into that arrangement,
522or that patent license was granted, prior to 28 March 2007.
523
524 Nothing in this License shall be construed as excluding or limiting
525any implied license or other defenses to infringement that may
526otherwise be available to you under applicable patent law.
527
528 12. No Surrender of Others' Freedom.
529
530 If conditions are imposed on you (whether by court order, agreement or
531otherwise) that contradict the conditions of this License, they do not
532excuse you from the conditions of this License. If you cannot convey a
533covered work so as to satisfy simultaneously your obligations under this
534License and any other pertinent obligations, then as a consequence you may
535not convey it at all. For example, if you agree to terms that obligate you
536to collect a royalty for further conveying from those to whom you convey
537the Program, the only way you could satisfy both those terms and this
538License would be to refrain entirely from conveying the Program.
539
540 13. Remote Network Interaction; Use with the GNU General Public License.
541
542 Notwithstanding any other provision of this License, if you modify the
543Program, your modified version must prominently offer all users
544interacting with it remotely through a computer network (if your version
545supports such interaction) an opportunity to receive the Corresponding
546Source of your version by providing access to the Corresponding Source
547from a network server at no charge, through some standard or customary
548means of facilitating copying of software. This Corresponding Source
549shall include the Corresponding Source for any work covered by version 3
550of the GNU General Public License that is incorporated pursuant to the
551following paragraph.
552
553 Notwithstanding any other provision of this License, you have
554permission to link or combine any covered work with a work licensed
555under version 3 of the GNU General Public License into a single
556combined work, and to convey the resulting work. The terms of this
557License will continue to apply to the part which is the covered work,
558but the work with which it is combined will remain governed by version
5593 of the GNU General Public License.
560
561 14. Revised Versions of this License.
562
563 The Free Software Foundation may publish revised and/or new versions of
564the GNU Affero General Public License from time to time. Such new versions
565will be similar in spirit to the present version, but may differ in detail to
566address new problems or concerns.
567
568 Each version is given a distinguishing version number. If the
569Program specifies that a certain numbered version of the GNU Affero General
570Public License "or any later version" applies to it, you have the
571option of following the terms and conditions either of that numbered
572version or of any later version published by the Free Software
573Foundation. If the Program does not specify a version number of the
574GNU Affero General Public License, you may choose any version ever published
575by the Free Software Foundation.
576
577 If the Program specifies that a proxy can decide which future
578versions of the GNU Affero General Public License can be used, that proxy's
579public statement of acceptance of a version permanently authorizes you
580to choose that version for the Program.
581
582 Later license versions may give you additional or different
583permissions. However, no additional obligations are imposed on any
584author or copyright holder as a result of your choosing to follow a
585later version.
586
587 15. Disclaimer of Warranty.
588
589 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
598 16. Limitation of Liability.
599
600 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608SUCH DAMAGES.
609
610 17. Interpretation of Sections 15 and 16.
611
612 If the disclaimer of warranty and limitation of liability provided
613above cannot be given local legal effect according to their terms,
614reviewing courts shall apply local law that most closely approximates
615an absolute waiver of all civil liability in connection with the
616Program, unless a warranty or assumption of liability accompanies a
617copy of the Program in return for a fee.
618
619 END OF TERMS AND CONDITIONS
620
621 How to Apply These Terms to Your New Programs
622
623 If you develop a new program, and you want it to be of the greatest
624possible use to the public, the best way to achieve this is to make it
625free software which everyone can redistribute and change under these terms.
626
627 To do so, attach the following notices to the program. It is safest
628to attach them to the start of each source file to most effectively
629state the exclusion of warranty; and each file should have at least
630the "copyright" line and a pointer to where the full notice is found.
631
632 <one line to give the program's name and a brief idea of what it does.>
633 Copyright (C) <year> <name of author>
634
635 This program is free software: you can redistribute it and/or modify
636 it under the terms of the GNU Affero General Public License as published by
637 the Free Software Foundation, either version 3 of the License, or
638 (at your option) any later version.
639
640 This program is distributed in the hope that it will be useful,
641 but WITHOUT ANY WARRANTY; without even the implied warranty of
642 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 GNU Affero General Public License for more details.
644
645 You should have received a copy of the GNU Affero General Public License
646 along with this program. If not, see <http://www.gnu.org/licenses/>.
647
648Also add information on how to contact you by electronic and paper mail.
649
650 If your software can interact with users remotely through a computer
651network, you should also make sure that it provides a way for users to
652get its source. For example, if your program is a web application, its
653interface could display a "Source" link that leads users to an archive
654of the code. There are many ways you could offer source, and different
655solutions will be better for different programs; see section 13 for the
656specific requirements.
657
658 You should also get your employer (if you work as a programmer) or school,
659if any, to sign a "copyright disclaimer" for the program, if necessary.
660For more information on this, and how to apply and follow the GNU AGPL, see
661<http://www.gnu.org/licenses/>.
0662
=== added file 'lib/charm-helpers/MANIFEST.in'
--- lib/charm-helpers/MANIFEST.in 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/MANIFEST.in 2013-09-26 06:24:47 +0000
@@ -0,0 +1,6 @@
1include *.txt
2include Makefile
3include VERSION
4include MANIFEST.in
5include scripts/*
6recursive-include debian *
07
=== added file 'lib/charm-helpers/Makefile'
--- lib/charm-helpers/Makefile 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/Makefile 2013-09-26 06:24:47 +0000
@@ -0,0 +1,46 @@
1PROJECT=charmhelpers
2PYTHON := /usr/bin/env python
3SUITE=unstable
4TESTS=tests/
5
6all:
7 @echo "make source - Create source package"
8 @echo "make sdeb - Create debian source package"
9 @echo "make deb - Create debian package"
10 @echo "make clean"
11 @echo "make userinstall - Install locally"
12
13sdeb: source
14 scripts/build source
15
16deb: source
17 scripts/build
18
19source: setup.py
20 scripts/update-revno
21 python setup.py sdist
22
23clean:
24 python setup.py clean
25 rm -rf build/ MANIFEST
26 find . -name '*.pyc' -delete
27 rm -rf dist/*
28 dh_clean
29
30userinstall:
31 scripts/update-revno
32 python setup.py install --user
33
34test:
35 @echo Starting tests...
36 @$(PYTHON) /usr/bin/nosetests --nologcapture tests/
37
38ftest:
39 @echo Starting fast tests...
40 @$(PYTHON) /usr/bin/nosetests --attr '!slow' --nologcapture tests/
41
42lint:
43 @echo Checking for Python syntax...
44 @flake8 --ignore=E123,E501 $(PROJECT) $(TESTS) && echo OK
45
46build: test lint
047
=== added file 'lib/charm-helpers/README.test'
--- lib/charm-helpers/README.test 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/README.test 2013-09-26 06:24:47 +0000
@@ -0,0 +1,7 @@
1Required Packages for Running Tests
2-----------------------------------
3python-shelltoolbox
4python-tempita
5python-nose
6python-mock
7python-testtools
08
=== added file 'lib/charm-helpers/README.txt'
--- lib/charm-helpers/README.txt 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/README.txt 2013-09-26 06:24:47 +0000
@@ -0,0 +1,8 @@
1============
2CharmHelpers
3============
4
5CharmHelpers provides an opinionated set of tools for building Juju
6charms that work together. In addition to basic tasks like interact-
7ing with the charm environment and the machine it runs on, it also
8helps keep you build hooks and establish relations effortlessly.
09
=== added file 'lib/charm-helpers/REVISION'
--- lib/charm-helpers/REVISION 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/REVISION 2013-09-26 06:24:47 +0000
@@ -0,0 +1,1 @@
176
02
=== added file 'lib/charm-helpers/VERSION'
--- lib/charm-helpers/VERSION 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/VERSION 2013-09-26 06:24:47 +0000
@@ -0,0 +1,1 @@
10.1.2
02
=== added directory 'lib/charm-helpers/bin'
=== added file 'lib/charm-helpers/bin/README'
--- lib/charm-helpers/bin/README 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/bin/README 2013-09-26 06:24:47 +0000
@@ -0,0 +1,1 @@
1This directory contains executables for accessing charmhelpers functionality
02
=== added file 'lib/charm-helpers/bin/chlp'
--- lib/charm-helpers/bin/chlp 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/bin/chlp 2013-09-26 06:24:47 +0000
@@ -0,0 +1,7 @@
1#!/usr/bin/env python
2
3from charmhelpers.cli import cmdline
4from charmhelpers.cli.commands import *
5
6if __name__ == '__main__':
7 cmdline.run()
08
=== added directory 'lib/charm-helpers/bin/contrib'
=== added directory 'lib/charm-helpers/bin/contrib/charmsupport'
=== added file 'lib/charm-helpers/bin/contrib/charmsupport/charmsupport'
--- lib/charm-helpers/bin/contrib/charmsupport/charmsupport 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/bin/contrib/charmsupport/charmsupport 2013-09-26 06:24:47 +0000
@@ -0,0 +1,31 @@
1#!/usr/bin/env python
2
3import argparse
4from charmhelpers.contrib.charmsupport import execd
5
6
7def run_execd(args):
8 execd.execd_run(args.module, args.dir, die_on_error=True)
9
10
11def parse_args():
12 parser = argparse.ArgumentParser(description='Perform common charm tasks')
13 subparsers = parser.add_subparsers(help='Commands')
14
15 execd_parser = subparsers.add_parser('execd',
16 help='Execute a directory of commands')
17 execd_parser.add_argument('--module', default='charm-pre-install',
18 help='module to run (default: charm-pre-install)')
19 execd_parser.add_argument('--dir',
20 help="Override the exec.d directory path")
21 execd_parser.set_defaults(func=run_execd)
22
23 return parser.parse_args()
24
25
26def main():
27 arguments = parse_args()
28 arguments.func(arguments)
29
30if __name__ == '__main__':
31 exit(main())
032
=== added directory 'lib/charm-helpers/bin/contrib/saltstack'
=== added file 'lib/charm-helpers/bin/contrib/saltstack/salt-call'
--- lib/charm-helpers/bin/contrib/saltstack/salt-call 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/bin/contrib/saltstack/salt-call 2013-09-26 06:24:47 +0000
@@ -0,0 +1,11 @@
1#!/usr/bin/env python
2'''
3Directly call a salt command in the modules, does not require a running salt
4minion to run.
5'''
6
7from salt.scripts import salt_call
8
9
10if __name__ == '__main__':
11 salt_call()
012
=== added directory 'lib/charm-helpers/charmhelpers'
=== added file 'lib/charm-helpers/charmhelpers/__init__.py'
=== added directory 'lib/charm-helpers/charmhelpers/cli'
=== added file 'lib/charm-helpers/charmhelpers/cli/README.rst'
--- lib/charm-helpers/charmhelpers/cli/README.rst 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/cli/README.rst 2013-09-26 06:24:47 +0000
@@ -0,0 +1,57 @@
1==========
2Commandant
3==========
4
5-----------------------------------------------------
6Automatic command-line interfaces to Python functions
7-----------------------------------------------------
8
9One of the benefits of ``libvirt`` is the uniformity of the interface: the C API (as well as the bindings in other languages) is a set of functions that accept parameters that are nearly identical to the command-line arguments. If you run ``virsh``, you get an interactive command prompt that supports all of the same commands that your shell scripts use as ``virsh`` subcommands.
10
11Command execution and stdio manipulation is the greatest common factor across all development systems in the POSIX environment. By exposing your functions as commands that manipulate streams of text, you can make life easier for all the Ruby and Erlang and Go programmers in your life.
12
13Goals
14=====
15
16* Single decorator to expose a function as a command.
17 * now two decorators - one "automatic" and one that allows authors to manipulate the arguments for fine-grained control.(MW)
18* Automatic analysis of function signature through ``inspect.getargspec()``
19* Command argument parser built automatically with ``argparse``
20* Interactive interpreter loop object made with ``Cmd``
21* Options to output structured return value data via ``pprint``, ``yaml`` or ``json`` dumps.
22
23Other Important Features that need writing
24------------------------------------------
25
26* Help and Usage documentation can be automatically generated, but it will be important to let users override this behaviour
27* The decorator should allow specifying further parameters to the parser's add_argument() calls, to specify types or to make arguments behave as boolean flags, etc.
28 - Filename arguments are important, as good practice is for functions to accept file objects as parameters.
29 - choices arguments help to limit bad input before the function is called
30* Some automatic behaviour could make for better defaults, once the user can override them.
31 - We could automatically detect arguments that default to False or True, and automatically support --no-foo for foo=True.
32 - We could automatically support hyphens as alternates for underscores
33 - Arguments defaulting to sequence types could support the ``append`` action.
34
35
36-----------------------------------------------------
37Implementing subcommands
38-----------------------------------------------------
39
40(WIP)
41
42So as to avoid dependencies on the cli module, subcommands should be defined separately from their implementations. The recommmendation would be to place definitions into separate modules near the implementations which they expose.
43
44Some examples::
45
46 from charmhelpers.cli import CommandLine
47 from charmhelpers.payload import execd
48 from charmhelpers.foo import bar
49
50 cli = CommandLine()
51
52 cli.subcommand(execd.execd_run)
53
54 @cli.subcommand_builder("bar", help="Bar baz qux")
55 def barcmd_builder(subparser):
56 subparser.add_argument('argument1', help="yackety")
57 return bar
058
=== added file 'lib/charm-helpers/charmhelpers/cli/__init__.py'
--- lib/charm-helpers/charmhelpers/cli/__init__.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/cli/__init__.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,147 @@
1import inspect
2import itertools
3import argparse
4import sys
5
6
7class OutputFormatter(object):
8 def __init__(self, outfile=sys.stdout):
9 self.formats = (
10 "raw",
11 "json",
12 "py",
13 "yaml",
14 "csv",
15 "tab",
16 )
17 self.outfile = outfile
18
19 def add_arguments(self, argument_parser):
20 formatgroup = argument_parser.add_mutually_exclusive_group()
21 choices = self.supported_formats
22 formatgroup.add_argument("--format", metavar='FMT',
23 help="Select output format for returned data, "
24 "where FMT is one of: {}".format(choices),
25 choices=choices, default='raw')
26 for fmt in self.formats:
27 fmtfunc = getattr(self, fmt)
28 formatgroup.add_argument("-{}".format(fmt[0]),
29 "--{}".format(fmt), action='store_const',
30 const=fmt, dest='format',
31 help=fmtfunc.__doc__)
32
33 @property
34 def supported_formats(self):
35 return self.formats
36
37 def raw(self, output):
38 """Output data as raw string (default)"""
39 self.outfile.write(str(output))
40
41 def py(self, output):
42 """Output data as a nicely-formatted python data structure"""
43 import pprint
44 pprint.pprint(output, stream=self.outfile)
45
46 def json(self, output):
47 """Output data in JSON format"""
48 import json
49 json.dump(output, self.outfile)
50
51 def yaml(self, output):
52 """Output data in YAML format"""
53 import yaml
54 yaml.safe_dump(output, self.outfile)
55
56 def csv(self, output):
57 """Output data as excel-compatible CSV"""
58 import csv
59 csvwriter = csv.writer(self.outfile)
60 csvwriter.writerows(output)
61
62 def tab(self, output):
63 """Output data in excel-compatible tab-delimited format"""
64 import csv
65 csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab)
66 csvwriter.writerows(output)
67
68 def format_output(self, output, fmt='raw'):
69 fmtfunc = getattr(self, fmt)
70 fmtfunc(output)
71
72
73class CommandLine(object):
74 argument_parser = None
75 subparsers = None
76 formatter = None
77
78 def __init__(self):
79 if not self.argument_parser:
80 self.argument_parser = argparse.ArgumentParser(description='Perform common charm tasks')
81 if not self.formatter:
82 self.formatter = OutputFormatter()
83 self.formatter.add_arguments(self.argument_parser)
84 if not self.subparsers:
85 self.subparsers = self.argument_parser.add_subparsers(help='Commands')
86
87 def subcommand(self, command_name=None):
88 """
89 Decorate a function as a subcommand. Use its arguments as the
90 command-line arguments"""
91 def wrapper(decorated):
92 cmd_name = command_name or decorated.__name__
93 subparser = self.subparsers.add_parser(cmd_name,
94 description=decorated.__doc__)
95 for args, kwargs in describe_arguments(decorated):
96 subparser.add_argument(*args, **kwargs)
97 subparser.set_defaults(func=decorated)
98 return decorated
99 return wrapper
100
101 def subcommand_builder(self, command_name, description=None):
102 """
103 Decorate a function that builds a subcommand. Builders should accept a
104 single argument (the subparser instance) and return the function to be
105 run as the command."""
106 def wrapper(decorated):
107 subparser = self.subparsers.add_parser(command_name)
108 func = decorated(subparser)
109 subparser.set_defaults(func=func)
110 subparser.description = description or func.__doc__
111 return wrapper
112
113 def run(self):
114 "Run cli, processing arguments and executing subcommands."
115 arguments = self.argument_parser.parse_args()
116 argspec = inspect.getargspec(arguments.func)
117 vargs = []
118 kwargs = {}
119 if argspec.varargs:
120 vargs = getattr(arguments, argspec.varargs)
121 for arg in argspec.args:
122 kwargs[arg] = getattr(arguments, arg)
123 self.formatter.format_output(arguments.func(*vargs, **kwargs), arguments.format)
124
125
126cmdline = CommandLine()
127
128
129def describe_arguments(func):
130 """
131 Analyze a function's signature and return a data structure suitable for
132 passing in as arguments to an argparse parser's add_argument() method."""
133
134 argspec = inspect.getargspec(func)
135 # we should probably raise an exception somewhere if func includes **kwargs
136 if argspec.defaults:
137 positional_args = argspec.args[:-len(argspec.defaults)]
138 keyword_names = argspec.args[-len(argspec.defaults):]
139 for arg, default in itertools.izip(keyword_names, argspec.defaults):
140 yield ('--{}'.format(arg),), {'default': default}
141 else:
142 positional_args = argspec.args
143
144 for arg in positional_args:
145 yield (arg,), {}
146 if argspec.varargs:
147 yield (argspec.varargs,), {'nargs': '*'}
0148
=== added file 'lib/charm-helpers/charmhelpers/cli/commands.py'
--- lib/charm-helpers/charmhelpers/cli/commands.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/cli/commands.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,2 @@
1from . import CommandLine
2import host
03
=== added file 'lib/charm-helpers/charmhelpers/cli/host.py'
--- lib/charm-helpers/charmhelpers/cli/host.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/cli/host.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,14 @@
1from . import cmdline
2from charmhelpers.core import host
3
4
5@cmdline.subcommand()
6def mounts():
7 "List mounts"
8 return host.mounts()
9
10@cmdline.subcommand_builder('service', description="Control system services")
11def service(subparser):
12 subparser.add_argument("action", help="The action to perform (start, stop, etc...)")
13 subparser.add_argument("service_name", help="Name of the service to control")
14 return host.service
015
=== added directory 'lib/charm-helpers/charmhelpers/contrib'
=== added file 'lib/charm-helpers/charmhelpers/contrib/__init__.py'
=== added directory 'lib/charm-helpers/charmhelpers/contrib/ansible'
=== added file 'lib/charm-helpers/charmhelpers/contrib/ansible/__init__.py'
--- lib/charm-helpers/charmhelpers/contrib/ansible/__init__.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/ansible/__init__.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,101 @@
1# Copyright 2013 Canonical Ltd.
2#
3# Authors:
4# Charm Helpers Developers <juju@lists.ubuntu.com>
5"""Charm Helpers ansible - declare the state of your machines.
6
7This helper enables you to declare your machine state, rather than
8program it procedurally (and have to test each change to your procedures).
9Your install hook can be as simple as:
10
11{{{
12import charmhelpers.contrib.ansible
13
14
15def install():
16 charmhelpers.contrib.ansible.install_ansible_support()
17 charmhelpers.contrib.ansible.apply_playbook('playbooks/install.yaml')
18}}}
19
20and won't need to change (nor will its tests) when you change the machine
21state.
22
23All of your juju config and relation-data are available as template
24variables within your playbooks and templates. An install playbook looks
25something like:
26
27{{{
28---
29- hosts: localhost
30 user: root
31
32 tasks:
33 - name: Add private repositories.
34 template:
35 src: ../templates/private-repositories.list.jinja2
36 dest: /etc/apt/sources.list.d/private.list
37
38 - name: Update the cache.
39 apt: update_cache=yes
40
41 - name: Install dependencies.
42 apt: pkg={{ item }}
43 with_items:
44 - python-mimeparse
45 - python-webob
46 - sunburnt
47
48 - name: Setup groups.
49 group: name={{ item.name }} gid={{ item.gid }}
50 with_items:
51 - { name: 'deploy_user', gid: 1800 }
52 - { name: 'service_user', gid: 1500 }
53
54 ...
55}}}
56
57Read more online about playbooks[1] and standard ansible modules[2].
58
59[1] http://www.ansibleworks.com/docs/playbooks.html
60[2] http://www.ansibleworks.com/docs/modules.html
61"""
62import os
63import subprocess
64
65import charmhelpers.contrib.saltstack
66import charmhelpers.core.host
67import charmhelpers.core.hookenv
68import charmhelpers.fetch
69
70
71charm_dir = os.environ.get('CHARM_DIR', '')
72ansible_hosts_path = '/etc/ansible/hosts'
73# Ansible will automatically include any vars in the following
74# file in its inventory when run locally.
75ansible_vars_path = '/etc/ansible/host_vars/localhost'
76
77
78def install_ansible_support(from_ppa=True):
79 """Installs the ansible package.
80
81 By default it is installed from the PPA [1] linked from
82 the ansible website [2].
83
84 [1] https://launchpad.net/~rquillo/+archive/ansible
85 [2] http://www.ansibleworks.com/docs/gettingstarted.html#ubuntu-and-debian
86
87 If from_ppa is false, you must ensure that the package is available
88 from a configured repository.
89 """
90 if from_ppa:
91 charmhelpers.fetch.add_source('ppa:rquillo/ansible')
92 charmhelpers.fetch.apt_update(fatal=True)
93 charmhelpers.fetch.apt_install('ansible')
94 with open(ansible_hosts_path, 'w+') as hosts_file:
95 hosts_file.write('localhost ansible_connection=local')
96
97
98def apply_playbook(playbook):
99 charmhelpers.contrib.saltstack.juju_state_to_yaml(
100 ansible_vars_path, namespace_separator='__')
101 subprocess.check_call(['ansible-playbook', '-c', 'local', playbook])
0102
=== added directory 'lib/charm-helpers/charmhelpers/contrib/charmhelpers'
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmhelpers/IMPORT'
--- lib/charm-helpers/charmhelpers/contrib/charmhelpers/IMPORT 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/charmhelpers/IMPORT 2013-09-26 06:24:47 +0000
@@ -0,0 +1,4 @@
1Source lp:charm-tools/trunk
2
3charm-tools/helpers/python/charmhelpers/__init__.py -> charmhelpers/charmhelpers/contrib/charmhelpers/__init__.py
4charm-tools/helpers/python/charmhelpers/tests/test_charmhelpers.py -> charmhelpers/tests/contrib/charmhelpers/test_charmhelpers.py
05
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmhelpers/__init__.py'
--- lib/charm-helpers/charmhelpers/contrib/charmhelpers/__init__.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/charmhelpers/__init__.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,184 @@
1# Copyright 2012 Canonical Ltd. This software is licensed under the
2# GNU Affero General Public License version 3 (see the file LICENSE).
3
4import warnings
5warnings.warn("contrib.charmhelpers is deprecated", DeprecationWarning)
6
7"""Helper functions for writing Juju charms in Python."""
8
9__metaclass__ = type
10__all__ = [
11 #'get_config', # core.hookenv.config()
12 #'log', # core.hookenv.log()
13 #'log_entry', # core.hookenv.log()
14 #'log_exit', # core.hookenv.log()
15 #'relation_get', # core.hookenv.relation_get()
16 #'relation_set', # core.hookenv.relation_set()
17 #'relation_ids', # core.hookenv.relation_ids()
18 #'relation_list', # core.hookenv.relation_units()
19 #'config_get', # core.hookenv.config()
20 #'unit_get', # core.hookenv.unit_get()
21 #'open_port', # core.hookenv.open_port()
22 #'close_port', # core.hookenv.close_port()
23 #'service_control', # core.host.service()
24 'unit_info', # client-side, NOT IMPLEMENTED
25 'wait_for_machine', # client-side, NOT IMPLEMENTED
26 'wait_for_page_contents', # client-side, NOT IMPLEMENTED
27 'wait_for_relation', # client-side, NOT IMPLEMENTED
28 'wait_for_unit', # client-side, NOT IMPLEMENTED
29]
30
31import operator
32from shelltoolbox import (
33 command,
34)
35import tempfile
36import time
37import urllib2
38import yaml
39
40SLEEP_AMOUNT = 0.1
41# We create a juju_status Command here because it makes testing much,
42# much easier.
43juju_status = lambda: command('juju')('status')
44
45# re-implemented as charmhelpers.fetch.configure_sources()
46#def configure_source(update=False):
47# source = config_get('source')
48# if ((source.startswith('ppa:') or
49# source.startswith('cloud:') or
50# source.startswith('http:'))):
51# run('add-apt-repository', source)
52# if source.startswith("http:"):
53# run('apt-key', 'import', config_get('key'))
54# if update:
55# run('apt-get', 'update')
56
57
58# DEPRECATED: client-side only
59def make_charm_config_file(charm_config):
60 charm_config_file = tempfile.NamedTemporaryFile()
61 charm_config_file.write(yaml.dump(charm_config))
62 charm_config_file.flush()
63 # The NamedTemporaryFile instance is returned instead of just the name
64 # because we want to take advantage of garbage collection-triggered
65 # deletion of the temp file when it goes out of scope in the caller.
66 return charm_config_file
67
68
69# DEPRECATED: client-side only
70def unit_info(service_name, item_name, data=None, unit=None):
71 if data is None:
72 data = yaml.safe_load(juju_status())
73 service = data['services'].get(service_name)
74 if service is None:
75 # XXX 2012-02-08 gmb:
76 # This allows us to cope with the race condition that we
77 # have between deploying a service and having it come up in
78 # `juju status`. We could probably do with cleaning it up so
79 # that it fails a bit more noisily after a while.
80 return ''
81 units = service['units']
82 if unit is not None:
83 item = units[unit][item_name]
84 else:
85 # It might seem odd to sort the units here, but we do it to
86 # ensure that when no unit is specified, the first unit for the
87 # service (or at least the one with the lowest number) is the
88 # one whose data gets returned.
89 sorted_unit_names = sorted(units.keys())
90 item = units[sorted_unit_names[0]][item_name]
91 return item
92
93
94# DEPRECATED: client-side only
95def get_machine_data():
96 return yaml.safe_load(juju_status())['machines']
97
98
99# DEPRECATED: client-side only
100def wait_for_machine(num_machines=1, timeout=300):
101 """Wait `timeout` seconds for `num_machines` machines to come up.
102
103 This wait_for... function can be called by other wait_for functions
104 whose timeouts might be too short in situations where only a bare
105 Juju setup has been bootstrapped.
106
107 :return: A tuple of (num_machines, time_taken). This is used for
108 testing.
109 """
110 # You may think this is a hack, and you'd be right. The easiest way
111 # to tell what environment we're working in (LXC vs EC2) is to check
112 # the dns-name of the first machine. If it's localhost we're in LXC
113 # and we can just return here.
114 if get_machine_data()[0]['dns-name'] == 'localhost':
115 return 1, 0
116 start_time = time.time()
117 while True:
118 # Drop the first machine, since it's the Zookeeper and that's
119 # not a machine that we need to wait for. This will only work
120 # for EC2 environments, which is why we return early above if
121 # we're in LXC.
122 machine_data = get_machine_data()
123 non_zookeeper_machines = [
124 machine_data[key] for key in machine_data.keys()[1:]]
125 if len(non_zookeeper_machines) >= num_machines:
126 all_machines_running = True
127 for machine in non_zookeeper_machines:
128 if machine.get('instance-state') != 'running':
129 all_machines_running = False
130 break
131 if all_machines_running:
132 break
133 if time.time() - start_time >= timeout:
134 raise RuntimeError('timeout waiting for service to start')
135 time.sleep(SLEEP_AMOUNT)
136 return num_machines, time.time() - start_time
137
138
139# DEPRECATED: client-side only
140def wait_for_unit(service_name, timeout=480):
141 """Wait `timeout` seconds for a given service name to come up."""
142 wait_for_machine(num_machines=1)
143 start_time = time.time()
144 while True:
145 state = unit_info(service_name, 'agent-state')
146 if 'error' in state or state == 'started':
147 break
148 if time.time() - start_time >= timeout:
149 raise RuntimeError('timeout waiting for service to start')
150 time.sleep(SLEEP_AMOUNT)
151 if state != 'started':
152 raise RuntimeError('unit did not start, agent-state: ' + state)
153
154
155# DEPRECATED: client-side only
156def wait_for_relation(service_name, relation_name, timeout=120):
157 """Wait `timeout` seconds for a given relation to come up."""
158 start_time = time.time()
159 while True:
160 relation = unit_info(service_name, 'relations').get(relation_name)
161 if relation is not None and relation['state'] == 'up':
162 break
163 if time.time() - start_time >= timeout:
164 raise RuntimeError('timeout waiting for relation to be up')
165 time.sleep(SLEEP_AMOUNT)
166
167
168# DEPRECATED: client-side only
169def wait_for_page_contents(url, contents, timeout=120, validate=None):
170 if validate is None:
171 validate = operator.contains
172 start_time = time.time()
173 while True:
174 try:
175 stream = urllib2.urlopen(url)
176 except (urllib2.HTTPError, urllib2.URLError):
177 pass
178 else:
179 page = stream.read()
180 if validate(page, contents):
181 return page
182 if time.time() - start_time >= timeout:
183 raise RuntimeError('timeout waiting for contents of ' + url)
184 time.sleep(SLEEP_AMOUNT)
0185
=== added directory 'lib/charm-helpers/charmhelpers/contrib/charmsupport'
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmsupport/IMPORT'
--- lib/charm-helpers/charmhelpers/contrib/charmsupport/IMPORT 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/charmsupport/IMPORT 2013-09-26 06:24:47 +0000
@@ -0,0 +1,14 @@
1Source: lp:charmsupport/trunk
2
3charmsupport/charmsupport/execd.py -> charm-helpers/charmhelpers/contrib/charmsupport/execd.py
4charmsupport/charmsupport/hookenv.py -> charm-helpers/charmhelpers/contrib/charmsupport/hookenv.py
5charmsupport/charmsupport/host.py -> charm-helpers/charmhelpers/contrib/charmsupport/host.py
6charmsupport/charmsupport/nrpe.py -> charm-helpers/charmhelpers/contrib/charmsupport/nrpe.py
7charmsupport/charmsupport/volumes.py -> charm-helpers/charmhelpers/contrib/charmsupport/volumes.py
8
9charmsupport/tests/test_execd.py -> charm-helpers/tests/contrib/charmsupport/test_execd.py
10charmsupport/tests/test_hookenv.py -> charm-helpers/tests/contrib/charmsupport/test_hookenv.py
11charmsupport/tests/test_host.py -> charm-helpers/tests/contrib/charmsupport/test_host.py
12charmsupport/tests/test_nrpe.py -> charm-helpers/tests/contrib/charmsupport/test_nrpe.py
13
14charmsupport/bin/charmsupport -> charm-helpers/bin/contrib/charmsupport/charmsupport
015
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmsupport/__init__.py'
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmsupport/nrpe.py'
--- lib/charm-helpers/charmhelpers/contrib/charmsupport/nrpe.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/charmsupport/nrpe.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,218 @@
1"""Compatibility with the nrpe-external-master charm"""
2# Copyright 2012 Canonical Ltd.
3#
4# Authors:
5# Matthew Wedgwood <matthew.wedgwood@canonical.com>
6
7import subprocess
8import pwd
9import grp
10import os
11import re
12import shlex
13import yaml
14
15from charmhelpers.core.hookenv import (
16 config,
17 local_unit,
18 log,
19 relation_ids,
20 relation_set,
21)
22
23from charmhelpers.core.host import service
24
25# This module adds compatibility with the nrpe-external-master and plain nrpe
26# subordinate charms. To use it in your charm:
27#
28# 1. Update metadata.yaml
29#
30# provides:
31# (...)
32# nrpe-external-master:
33# interface: nrpe-external-master
34# scope: container
35#
36# and/or
37#
38# provides:
39# (...)
40# local-monitors:
41# interface: local-monitors
42# scope: container
43
44#
45# 2. Add the following to config.yaml
46#
47# nagios_context:
48# default: "juju"
49# type: string
50# description: |
51# Used by the nrpe subordinate charms.
52# A string that will be prepended to instance name to set the host name
53# in nagios. So for instance the hostname would be something like:
54# juju-myservice-0
55# If you're running multiple environments with the same services in them
56# this allows you to differentiate between them.
57#
58# 3. Add custom checks (Nagios plugins) to files/nrpe-external-master
59#
60# 4. Update your hooks.py with something like this:
61#
62# from charmsupport.nrpe import NRPE
63# (...)
64# def update_nrpe_config():
65# nrpe_compat = NRPE()
66# nrpe_compat.add_check(
67# shortname = "myservice",
68# description = "Check MyService",
69# check_cmd = "check_http -w 2 -c 10 http://localhost"
70# )
71# nrpe_compat.add_check(
72# "myservice_other",
73# "Check for widget failures",
74# check_cmd = "/srv/myapp/scripts/widget_check"
75# )
76# nrpe_compat.write()
77#
78# def config_changed():
79# (...)
80# update_nrpe_config()
81#
82# def nrpe_external_master_relation_changed():
83# update_nrpe_config()
84#
85# def local_monitors_relation_changed():
86# update_nrpe_config()
87#
88# 5. ln -s hooks.py nrpe-external-master-relation-changed
89# ln -s hooks.py local-monitors-relation-changed
90
91
92class CheckException(Exception):
93 pass
94
95
96class Check(object):
97 shortname_re = '[A-Za-z0-9-_]+$'
98 service_template = ("""
99#---------------------------------------------------
100# This file is Juju managed
101#---------------------------------------------------
102define service {{
103 use active-service
104 host_name {nagios_hostname}
105 service_description {nagios_hostname}[{shortname}] """
106 """{description}
107 check_command check_nrpe!{command}
108 servicegroups {nagios_servicegroup}
109}}
110""")
111
112 def __init__(self, shortname, description, check_cmd):
113 super(Check, self).__init__()
114 # XXX: could be better to calculate this from the service name
115 if not re.match(self.shortname_re, shortname):
116 raise CheckException("shortname must match {}".format(
117 Check.shortname_re))
118 self.shortname = shortname
119 self.command = "check_{}".format(shortname)
120 # Note: a set of invalid characters is defined by the
121 # Nagios server config
122 # The default is: illegal_object_name_chars=`~!$%^&*"|'<>?,()=
123 self.description = description
124 self.check_cmd = self._locate_cmd(check_cmd)
125
126 def _locate_cmd(self, check_cmd):
127 search_path = (
128 '/',
129 os.path.join(os.environ['CHARM_DIR'],
130 'files/nrpe-external-master'),
131 '/usr/lib/nagios/plugins',
132 )
133 parts = shlex.split(check_cmd)
134 for path in search_path:
135 if os.path.exists(os.path.join(path, parts[0])):
136 command = os.path.join(path, parts[0])
137 if len(parts) > 1:
138 command += " " + " ".join(parts[1:])
139 return command
140 log('Check command not found: {}'.format(parts[0]))
141 return ''
142
143 def write(self, nagios_context, hostname):
144 nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format(
145 self.command)
146 with open(nrpe_check_file, 'w') as nrpe_check_config:
147 nrpe_check_config.write("# check {}\n".format(self.shortname))
148 nrpe_check_config.write("command[{}]={}\n".format(
149 self.command, self.check_cmd))
150
151 if not os.path.exists(NRPE.nagios_exportdir):
152 log('Not writing service config as {} is not accessible'.format(
153 NRPE.nagios_exportdir))
154 else:
155 self.write_service_config(nagios_context, hostname)
156
157 def write_service_config(self, nagios_context, hostname):
158 for f in os.listdir(NRPE.nagios_exportdir):
159 if re.search('.*{}.cfg'.format(self.command), f):
160 os.remove(os.path.join(NRPE.nagios_exportdir, f))
161
162 templ_vars = {
163 'nagios_hostname': hostname,
164 'nagios_servicegroup': nagios_context,
165 'description': self.description,
166 'shortname': self.shortname,
167 'command': self.command,
168 }
169 nrpe_service_text = Check.service_template.format(**templ_vars)
170 nrpe_service_file = '{}/service__{}_{}.cfg'.format(
171 NRPE.nagios_exportdir, hostname, self.command)
172 with open(nrpe_service_file, 'w') as nrpe_service_config:
173 nrpe_service_config.write(str(nrpe_service_text))
174
175 def run(self):
176 subprocess.call(self.check_cmd)
177
178
179class NRPE(object):
180 nagios_logdir = '/var/log/nagios'
181 nagios_exportdir = '/var/lib/nagios/export'
182 nrpe_confdir = '/etc/nagios/nrpe.d'
183
184 def __init__(self):
185 super(NRPE, self).__init__()
186 self.config = config()
187 self.nagios_context = self.config['nagios_context']
188 self.unit_name = local_unit().replace('/', '-')
189 self.hostname = "{}-{}".format(self.nagios_context, self.unit_name)
190 self.checks = []
191
192 def add_check(self, *args, **kwargs):
193 self.checks.append(Check(*args, **kwargs))
194
195 def write(self):
196 try:
197 nagios_uid = pwd.getpwnam('nagios').pw_uid
198 nagios_gid = grp.getgrnam('nagios').gr_gid
199 except:
200 log("Nagios user not set up, nrpe checks not updated")
201 return
202
203 if not os.path.exists(NRPE.nagios_logdir):
204 os.mkdir(NRPE.nagios_logdir)
205 os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid)
206
207 nrpe_monitors = {}
208 monitors = {"monitors": {"remote": {"nrpe": nrpe_monitors}}}
209 for nrpecheck in self.checks:
210 nrpecheck.write(self.nagios_context, self.hostname)
211 nrpe_monitors[nrpecheck.shortname] = {
212 "command": nrpecheck.command,
213 }
214
215 service('restart', 'nagios-nrpe-server')
216
217 for rid in relation_ids("local-monitors"):
218 relation_set(relation_id=rid, monitors=yaml.dump(monitors))
0219
=== added file 'lib/charm-helpers/charmhelpers/contrib/charmsupport/volumes.py'
--- lib/charm-helpers/charmhelpers/contrib/charmsupport/volumes.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/charmsupport/volumes.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,156 @@
1'''
2Functions for managing volumes in juju units. One volume is supported per unit.
3Subordinates may have their own storage, provided it is on its own partition.
4
5Configuration stanzas:
6 volume-ephemeral:
7 type: boolean
8 default: true
9 description: >
10 If false, a volume is mounted as sepecified in "volume-map"
11 If true, ephemeral storage will be used, meaning that log data
12 will only exist as long as the machine. YOU HAVE BEEN WARNED.
13 volume-map:
14 type: string
15 default: {}
16 description: >
17 YAML map of units to device names, e.g:
18 "{ rsyslog/0: /dev/vdb, rsyslog/1: /dev/vdb }"
19 Service units will raise a configure-error if volume-ephemeral
20 is 'true' and no volume-map value is set. Use 'juju set' to set a
21 value and 'juju resolved' to complete configuration.
22
23Usage:
24 from charmsupport.volumes import configure_volume, VolumeConfigurationError
25 from charmsupport.hookenv import log, ERROR
26 def post_mount_hook():
27 stop_service('myservice')
28 def post_mount_hook():
29 start_service('myservice')
30
31 if __name__ == '__main__':
32 try:
33 configure_volume(before_change=pre_mount_hook,
34 after_change=post_mount_hook)
35 except VolumeConfigurationError:
36 log('Storage could not be configured', ERROR)
37'''
38
39# XXX: Known limitations
40# - fstab is neither consulted nor updated
41
42import os
43from charmhelpers.core import hookenv
44from charmhelpers.core import host
45import yaml
46
47
48MOUNT_BASE = '/srv/juju/volumes'
49
50
51class VolumeConfigurationError(Exception):
52 '''Volume configuration data is missing or invalid'''
53 pass
54
55
56def get_config():
57 '''Gather and sanity-check volume configuration data'''
58 volume_config = {}
59 config = hookenv.config()
60
61 errors = False
62
63 if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'):
64 volume_config['ephemeral'] = True
65 else:
66 volume_config['ephemeral'] = False
67
68 try:
69 volume_map = yaml.safe_load(config.get('volume-map', '{}'))
70 except yaml.YAMLError as e:
71 hookenv.log("Error parsing YAML volume-map: {}".format(e),
72 hookenv.ERROR)
73 errors = True
74 if volume_map is None:
75 # probably an empty string
76 volume_map = {}
77 elif not isinstance(volume_map, dict):
78 hookenv.log("Volume-map should be a dictionary, not {}".format(
79 type(volume_map)))
80 errors = True
81
82 volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME'])
83 if volume_config['device'] and volume_config['ephemeral']:
84 # asked for ephemeral storage but also defined a volume ID
85 hookenv.log('A volume is defined for this unit, but ephemeral '
86 'storage was requested', hookenv.ERROR)
87 errors = True
88 elif not volume_config['device'] and not volume_config['ephemeral']:
89 # asked for permanent storage but did not define volume ID
90 hookenv.log('Ephemeral storage was requested, but there is no volume '
91 'defined for this unit.', hookenv.ERROR)
92 errors = True
93
94 unit_mount_name = hookenv.local_unit().replace('/', '-')
95 volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name)
96
97 if errors:
98 return None
99 return volume_config
100
101
102def mount_volume(config):
103 if os.path.exists(config['mountpoint']):
104 if not os.path.isdir(config['mountpoint']):
105 hookenv.log('Not a directory: {}'.format(config['mountpoint']))
106 raise VolumeConfigurationError()
107 else:
108 host.mkdir(config['mountpoint'])
109 if os.path.ismount(config['mountpoint']):
110 unmount_volume(config)
111 if not host.mount(config['device'], config['mountpoint'], persist=True):
112 raise VolumeConfigurationError()
113
114
115def unmount_volume(config):
116 if os.path.ismount(config['mountpoint']):
117 if not host.umount(config['mountpoint'], persist=True):
118 raise VolumeConfigurationError()
119
120
121def managed_mounts():
122 '''List of all mounted managed volumes'''
123 return filter(lambda mount: mount[0].startswith(MOUNT_BASE), host.mounts())
124
125
126def configure_volume(before_change=lambda: None, after_change=lambda: None):
127 '''Set up storage (or don't) according to the charm's volume configuration.
128 Returns the mount point or "ephemeral". before_change and after_change
129 are optional functions to be called if the volume configuration changes.
130 '''
131
132 config = get_config()
133 if not config:
134 hookenv.log('Failed to read volume configuration', hookenv.CRITICAL)
135 raise VolumeConfigurationError()
136
137 if config['ephemeral']:
138 if os.path.ismount(config['mountpoint']):
139 before_change()
140 unmount_volume(config)
141 after_change()
142 return 'ephemeral'
143 else:
144 # persistent storage
145 if os.path.ismount(config['mountpoint']):
146 mounts = dict(managed_mounts())
147 if mounts.get(config['mountpoint']) != config['device']:
148 before_change()
149 unmount_volume(config)
150 mount_volume(config)
151 after_change()
152 else:
153 before_change()
154 mount_volume(config)
155 after_change()
156 return config['mountpoint']
0157
=== added directory 'lib/charm-helpers/charmhelpers/contrib/hahelpers'
=== added file 'lib/charm-helpers/charmhelpers/contrib/hahelpers/__init__.py'
=== added file 'lib/charm-helpers/charmhelpers/contrib/hahelpers/apache.py'
--- lib/charm-helpers/charmhelpers/contrib/hahelpers/apache.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/hahelpers/apache.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,58 @@
1#
2# Copyright 2012 Canonical Ltd.
3#
4# This file is sourced from lp:openstack-charm-helpers
5#
6# Authors:
7# James Page <james.page@ubuntu.com>
8# Adam Gandelman <adamg@ubuntu.com>
9#
10
11import subprocess
12
13from charmhelpers.core.hookenv import (
14 config as config_get,
15 relation_get,
16 relation_ids,
17 related_units as relation_list,
18 log,
19 INFO,
20)
21
22
23def get_cert():
24 cert = config_get('ssl_cert')
25 key = config_get('ssl_key')
26 if not (cert and key):
27 log("Inspecting identity-service relations for SSL certificate.",
28 level=INFO)
29 cert = key = None
30 for r_id in relation_ids('identity-service'):
31 for unit in relation_list(r_id):
32 if not cert:
33 cert = relation_get('ssl_cert',
34 rid=r_id, unit=unit)
35 if not key:
36 key = relation_get('ssl_key',
37 rid=r_id, unit=unit)
38 return (cert, key)
39
40
41def get_ca_cert():
42 ca_cert = None
43 log("Inspecting identity-service relations for CA SSL certificate.",
44 level=INFO)
45 for r_id in relation_ids('identity-service'):
46 for unit in relation_list(r_id):
47 if not ca_cert:
48 ca_cert = relation_get('ca_cert',
49 rid=r_id, unit=unit)
50 return ca_cert
51
52
53def install_ca_cert(ca_cert):
54 if ca_cert:
55 with open('/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt',
56 'w') as crt:
57 crt.write(ca_cert)
58 subprocess.check_call(['update-ca-certificates', '--fresh'])
059
=== added file 'lib/charm-helpers/charmhelpers/contrib/hahelpers/ceph.py'
--- lib/charm-helpers/charmhelpers/contrib/hahelpers/ceph.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/hahelpers/ceph.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,294 @@
1#
2# Copyright 2012 Canonical Ltd.
3#
4# This file is sourced from lp:openstack-charm-helpers
5#
6# Authors:
7# James Page <james.page@ubuntu.com>
8# Adam Gandelman <adamg@ubuntu.com>
9#
10
11import commands
12import os
13import shutil
14import time
15
16from subprocess import (
17 check_call,
18 check_output,
19 CalledProcessError
20)
21
22from charmhelpers.core.hookenv import (
23 relation_get,
24 relation_ids,
25 related_units,
26 log,
27 INFO,
28 ERROR
29)
30
31from charmhelpers.fetch import (
32 apt_install,
33)
34
35from charmhelpers.core.host import (
36 mount,
37 mounts,
38 service_start,
39 service_stop,
40 umount,
41)
42
43KEYRING = '/etc/ceph/ceph.client.%s.keyring'
44KEYFILE = '/etc/ceph/ceph.client.%s.key'
45
46CEPH_CONF = """[global]
47 auth supported = %(auth)s
48 keyring = %(keyring)s
49 mon host = %(mon_hosts)s
50"""
51
52
53def running(service):
54 # this local util can be dropped as soon the following branch lands
55 # in lp:charm-helpers
56 # https://code.launchpad.net/~gandelman-a/charm-helpers/service_running/
57 try:
58 output = check_output(['service', service, 'status'])
59 except CalledProcessError:
60 return False
61 else:
62 if ("start/running" in output or "is running" in output):
63 return True
64 else:
65 return False
66
67
68def install():
69 ceph_dir = "/etc/ceph"
70 if not os.path.isdir(ceph_dir):
71 os.mkdir(ceph_dir)
72 apt_install('ceph-common', fatal=True)
73
74
75def rbd_exists(service, pool, rbd_img):
76 (rc, out) = commands.getstatusoutput('rbd list --id %s --pool %s' %
77 (service, pool))
78 return rbd_img in out
79
80
81def create_rbd_image(service, pool, image, sizemb):
82 cmd = [
83 'rbd',
84 'create',
85 image,
86 '--size',
87 str(sizemb),
88 '--id',
89 service,
90 '--pool',
91 pool
92 ]
93 check_call(cmd)
94
95
96def pool_exists(service, name):
97 (rc, out) = commands.getstatusoutput("rados --id %s lspools" % service)
98 return name in out
99
100
101def create_pool(service, name):
102 cmd = [
103 'rados',
104 '--id',
105 service,
106 'mkpool',
107 name
108 ]
109 check_call(cmd)
110
111
112def keyfile_path(service):
113 return KEYFILE % service
114
115
116def keyring_path(service):
117 return KEYRING % service
118
119
120def create_keyring(service, key):
121 keyring = keyring_path(service)
122 if os.path.exists(keyring):
123 log('ceph: Keyring exists at %s.' % keyring, level=INFO)
124 cmd = [
125 'ceph-authtool',
126 keyring,
127 '--create-keyring',
128 '--name=client.%s' % service,
129 '--add-key=%s' % key
130 ]
131 check_call(cmd)
132 log('ceph: Created new ring at %s.' % keyring, level=INFO)
133
134
135def create_key_file(service, key):
136 # create a file containing the key
137 keyfile = keyfile_path(service)
138 if os.path.exists(keyfile):
139 log('ceph: Keyfile exists at %s.' % keyfile, level=INFO)
140 fd = open(keyfile, 'w')
141 fd.write(key)
142 fd.close()
143 log('ceph: Created new keyfile at %s.' % keyfile, level=INFO)
144
145
146def get_ceph_nodes():
147 hosts = []
148 for r_id in relation_ids('ceph'):
149 for unit in related_units(r_id):
150 hosts.append(relation_get('private-address', unit=unit, rid=r_id))
151 return hosts
152
153
154def configure(service, key, auth):
155 create_keyring(service, key)
156 create_key_file(service, key)
157 hosts = get_ceph_nodes()
158 mon_hosts = ",".join(map(str, hosts))
159 keyring = keyring_path(service)
160 with open('/etc/ceph/ceph.conf', 'w') as ceph_conf:
161 ceph_conf.write(CEPH_CONF % locals())
162 modprobe_kernel_module('rbd')
163
164
165def image_mapped(image_name):
166 (rc, out) = commands.getstatusoutput('rbd showmapped')
167 return image_name in out
168
169
170def map_block_storage(service, pool, image):
171 cmd = [
172 'rbd',
173 'map',
174 '%s/%s' % (pool, image),
175 '--user',
176 service,
177 '--secret',
178 keyfile_path(service),
179 ]
180 check_call(cmd)
181
182
183def filesystem_mounted(fs):
184 return fs in [f for m, f in mounts()]
185
186
187def make_filesystem(blk_device, fstype='ext4', timeout=10):
188 count = 0
189 e_noent = os.errno.ENOENT
190 while not os.path.exists(blk_device):
191 if count >= timeout:
192 log('ceph: gave up waiting on block device %s' % blk_device,
193 level=ERROR)
194 raise IOError(e_noent, os.strerror(e_noent), blk_device)
195 log('ceph: waiting for block device %s to appear' % blk_device,
196 level=INFO)
197 count += 1
198 time.sleep(1)
199 else:
200 log('ceph: Formatting block device %s as filesystem %s.' %
201 (blk_device, fstype), level=INFO)
202 check_call(['mkfs', '-t', fstype, blk_device])
203
204
205def place_data_on_ceph(service, blk_device, data_src_dst, fstype='ext4'):
206 # mount block device into /mnt
207 mount(blk_device, '/mnt')
208
209 # copy data to /mnt
210 try:
211 copy_files(data_src_dst, '/mnt')
212 except:
213 pass
214
215 # umount block device
216 umount('/mnt')
217
218 _dir = os.stat(data_src_dst)
219 uid = _dir.st_uid
220 gid = _dir.st_gid
221
222 # re-mount where the data should originally be
223 mount(blk_device, data_src_dst, persist=True)
224
225 # ensure original ownership of new mount.
226 cmd = ['chown', '-R', '%s:%s' % (uid, gid), data_src_dst]
227 check_call(cmd)
228
229
230# TODO: re-use
231def modprobe_kernel_module(module):
232 log('ceph: Loading kernel module', level=INFO)
233 cmd = ['modprobe', module]
234 check_call(cmd)
235 cmd = 'echo %s >> /etc/modules' % module
236 check_call(cmd, shell=True)
237
238
239def copy_files(src, dst, symlinks=False, ignore=None):
240 for item in os.listdir(src):
241 s = os.path.join(src, item)
242 d = os.path.join(dst, item)
243 if os.path.isdir(s):
244 shutil.copytree(s, d, symlinks, ignore)
245 else:
246 shutil.copy2(s, d)
247
248
249def ensure_ceph_storage(service, pool, rbd_img, sizemb, mount_point,
250 blk_device, fstype, system_services=[]):
251 """
252 To be called from the current cluster leader.
253 Ensures given pool and RBD image exists, is mapped to a block device,
254 and the device is formatted and mounted at the given mount_point.
255
256 If formatting a device for the first time, data existing at mount_point
257 will be migrated to the RBD device before being remounted.
258
259 All services listed in system_services will be stopped prior to data
260 migration and restarted when complete.
261 """
262 # Ensure pool, RBD image, RBD mappings are in place.
263 if not pool_exists(service, pool):
264 log('ceph: Creating new pool %s.' % pool, level=INFO)
265 create_pool(service, pool)
266
267 if not rbd_exists(service, pool, rbd_img):
268 log('ceph: Creating RBD image (%s).' % rbd_img, level=INFO)
269 create_rbd_image(service, pool, rbd_img, sizemb)
270
271 if not image_mapped(rbd_img):
272 log('ceph: Mapping RBD Image as a Block Device.', level=INFO)
273 map_block_storage(service, pool, rbd_img)
274
275 # make file system
276 # TODO: What happens if for whatever reason this is run again and
277 # the data is already in the rbd device and/or is mounted??
278 # When it is mounted already, it will fail to make the fs
279 # XXX: This is really sketchy! Need to at least add an fstab entry
280 # otherwise this hook will blow away existing data if its executed
281 # after a reboot.
282 if not filesystem_mounted(mount_point):
283 make_filesystem(blk_device, fstype)
284
285 for svc in system_services:
286 if running(svc):
287 log('Stopping services %s prior to migrating data.' % svc,
288 level=INFO)
289 service_stop(svc)
290
291 place_data_on_ceph(service, blk_device, mount_point, fstype)
292
293 for svc in system_services:
294 service_start(svc)
0295
=== added file 'lib/charm-helpers/charmhelpers/contrib/hahelpers/cluster.py'
--- lib/charm-helpers/charmhelpers/contrib/hahelpers/cluster.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/hahelpers/cluster.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,181 @@
1#
2# Copyright 2012 Canonical Ltd.
3#
4# Authors:
5# James Page <james.page@ubuntu.com>
6# Adam Gandelman <adamg@ubuntu.com>
7#
8
9import subprocess
10import os
11
12from socket import gethostname as get_unit_hostname
13
14from charmhelpers.core.hookenv import (
15 log,
16 relation_ids,
17 related_units as relation_list,
18 relation_get,
19 config as config_get,
20 INFO,
21 ERROR,
22 unit_get,
23)
24
25
26class HAIncompleteConfig(Exception):
27 pass
28
29
30def is_clustered():
31 for r_id in (relation_ids('ha') or []):
32 for unit in (relation_list(r_id) or []):
33 clustered = relation_get('clustered',
34 rid=r_id,
35 unit=unit)
36 if clustered:
37 return True
38 return False
39
40
41def is_leader(resource):
42 cmd = [
43 "crm", "resource",
44 "show", resource
45 ]
46 try:
47 status = subprocess.check_output(cmd)
48 except subprocess.CalledProcessError:
49 return False
50 else:
51 if get_unit_hostname() in status:
52 return True
53 else:
54 return False
55
56
57def peer_units():
58 peers = []
59 for r_id in (relation_ids('cluster') or []):
60 for unit in (relation_list(r_id) or []):
61 peers.append(unit)
62 return peers
63
64
65def oldest_peer(peers):
66 local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1])
67 for peer in peers:
68 remote_unit_no = int(peer.split('/')[1])
69 if remote_unit_no < local_unit_no:
70 return False
71 return True
72
73
74def eligible_leader(resource):
75 if is_clustered():
76 if not is_leader(resource):
77 log('Deferring action to CRM leader.', level=INFO)
78 return False
79 else:
80 peers = peer_units()
81 if peers and not oldest_peer(peers):
82 log('Deferring action to oldest service unit.', level=INFO)
83 return False
84 return True
85
86
87def https():
88 '''
89 Determines whether enough data has been provided in configuration
90 or relation data to configure HTTPS
91 .
92 returns: boolean
93 '''
94 if config_get('use-https') == "yes":
95 return True
96 if config_get('ssl_cert') and config_get('ssl_key'):
97 return True
98 for r_id in relation_ids('identity-service'):
99 for unit in relation_list(r_id):
100 if None not in [
101 relation_get('https_keystone', rid=r_id, unit=unit),
102 relation_get('ssl_cert', rid=r_id, unit=unit),
103 relation_get('ssl_key', rid=r_id, unit=unit),
104 relation_get('ca_cert', rid=r_id, unit=unit),
105 ]:
106 return True
107 return False
108
109
110def determine_api_port(public_port):
111 '''
112 Determine correct API server listening port based on
113 existence of HTTPS reverse proxy and/or haproxy.
114
115 public_port: int: standard public port for given service
116
117 returns: int: the correct listening port for the API service
118 '''
119 i = 0
120 if len(peer_units()) > 0 or is_clustered():
121 i += 1
122 if https():
123 i += 1
124 return public_port - (i * 10)
125
126
127def determine_haproxy_port(public_port):
128 '''
129 Description: Determine correct proxy listening port based on public IP +
130 existence of HTTPS reverse proxy.
131
132 public_port: int: standard public port for given service
133
134 returns: int: the correct listening port for the HAProxy service
135 '''
136 i = 0
137 if https():
138 i += 1
139 return public_port - (i * 10)
140
141
142def get_hacluster_config():
143 '''
144 Obtains all relevant configuration from charm configuration required
145 for initiating a relation to hacluster:
146
147 ha-bindiface, ha-mcastport, vip, vip_iface, vip_cidr
148
149 returns: dict: A dict containing settings keyed by setting name.
150 raises: HAIncompleteConfig if settings are missing.
151 '''
152 settings = ['ha-bindiface', 'ha-mcastport', 'vip', 'vip_iface', 'vip_cidr']
153 conf = {}
154 for setting in settings:
155 conf[setting] = config_get(setting)
156 missing = []
157 [missing.append(s) for s, v in conf.iteritems() if v is None]
158 if missing:
159 log('Insufficient config data to configure hacluster.', level=ERROR)
160 raise HAIncompleteConfig
161 return conf
162
163
164def canonical_url(configs, vip_setting='vip'):
165 '''
166 Returns the correct HTTP URL to this host given the state of HTTPS
167 configuration and hacluster.
168
169 :configs : OSTemplateRenderer: A config tempating object to inspect for
170 a complete https context.
171 :vip_setting: str: Setting in charm config that specifies
172 VIP address.
173 '''
174 scheme = 'http'
175 if 'https' in configs.complete_contexts():
176 scheme = 'https'
177 if is_clustered():
178 addr = config_get(vip_setting)
179 else:
180 addr = unit_get('private-address')
181 return '%s://%s' % (scheme, addr)
0182
=== added directory 'lib/charm-helpers/charmhelpers/contrib/jujugui'
=== added file 'lib/charm-helpers/charmhelpers/contrib/jujugui/IMPORT'
--- lib/charm-helpers/charmhelpers/contrib/jujugui/IMPORT 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/jujugui/IMPORT 2013-09-26 06:24:47 +0000
@@ -0,0 +1,4 @@
1Source: lp:charms/juju-gui
2
3juju-gui/hooks/utils.py -> charm-helpers/charmhelpers/contrib/jujugui/utils.py
4juju-gui/tests/test_utils.py -> charm-helpers/tests/contrib/jujugui/test_utils.py
05
=== added file 'lib/charm-helpers/charmhelpers/contrib/jujugui/__init__.py'
=== added file 'lib/charm-helpers/charmhelpers/contrib/jujugui/utils.py'
--- lib/charm-helpers/charmhelpers/contrib/jujugui/utils.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/jujugui/utils.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,602 @@
1"""Juju GUI charm utilities."""
2
3__all__ = [
4 'AGENT',
5 'APACHE',
6 'API_PORT',
7 'CURRENT_DIR',
8 'HAPROXY',
9 'IMPROV',
10 'JUJU_DIR',
11 'JUJU_GUI_DIR',
12 'JUJU_GUI_SITE',
13 'JUJU_PEM',
14 'WEB_PORT',
15 'bzr_checkout',
16 'chain',
17 'cmd_log',
18 'fetch_api',
19 'fetch_gui',
20 'find_missing_packages',
21 'first_path_in_dir',
22 'get_api_address',
23 'get_npm_cache_archive_url',
24 'get_release_file_url',
25 'get_staging_dependencies',
26 'get_zookeeper_address',
27 'legacy_juju',
28 'log_hook',
29 'merge',
30 'parse_source',
31 'prime_npm_cache',
32 'render_to_file',
33 'save_or_create_certificates',
34 'setup_apache',
35 'setup_gui',
36 'start_agent',
37 'start_gui',
38 'start_improv',
39 'write_apache_config',
40]
41
42from contextlib import contextmanager
43import errno
44import json
45import os
46import logging
47import shutil
48from subprocess import CalledProcessError
49import tempfile
50from urlparse import urlparse
51
52import apt
53import tempita
54
55from launchpadlib.launchpad import Launchpad
56from shelltoolbox import (
57 Serializer,
58 apt_get_install,
59 command,
60 environ,
61 install_extra_repositories,
62 run,
63 script_name,
64 search_file,
65 su,
66)
67from charmhelpers.core.host import (
68 service_start,
69)
70from charmhelpers.core.hookenv import (
71 log,
72 config,
73 unit_get,
74)
75
76
77AGENT = 'juju-api-agent'
78APACHE = 'apache2'
79IMPROV = 'juju-api-improv'
80HAPROXY = 'haproxy'
81
82API_PORT = 8080
83WEB_PORT = 8000
84
85CURRENT_DIR = os.getcwd()
86JUJU_DIR = os.path.join(CURRENT_DIR, 'juju')
87JUJU_GUI_DIR = os.path.join(CURRENT_DIR, 'juju-gui')
88JUJU_GUI_SITE = '/etc/apache2/sites-available/juju-gui'
89JUJU_GUI_PORTS = '/etc/apache2/ports.conf'
90JUJU_PEM = 'juju.includes-private-key.pem'
91BUILD_REPOSITORIES = ('ppa:chris-lea/node.js-legacy',)
92DEB_BUILD_DEPENDENCIES = (
93 'bzr', 'imagemagick', 'make', 'nodejs', 'npm',
94)
95DEB_STAGE_DEPENDENCIES = (
96 'zookeeper',
97)
98
99
100# Store the configuration from on invocation to the next.
101config_json = Serializer('/tmp/config.json')
102# Bazaar checkout command.
103bzr_checkout = command('bzr', 'co', '--lightweight')
104# Whether or not the charm is deployed using juju-core.
105# If juju-core has been used to deploy the charm, an agent.conf file must
106# be present in the charm parent directory.
107legacy_juju = lambda: not os.path.exists(
108 os.path.join(CURRENT_DIR, '..', 'agent.conf'))
109
110
111def _get_build_dependencies():
112 """Install deb dependencies for building."""
113 log('Installing build dependencies.')
114 cmd_log(install_extra_repositories(*BUILD_REPOSITORIES))
115 cmd_log(apt_get_install(*DEB_BUILD_DEPENDENCIES))
116
117
118def get_api_address(unit_dir):
119 """Return the Juju API address stored in the uniter agent.conf file."""
120 import yaml # python-yaml is only installed if juju-core is used.
121 # XXX 2013-03-27 frankban bug=1161443:
122 # currently the uniter agent.conf file does not include the API
123 # address. For now retrieve it from the machine agent file.
124 base_dir = os.path.abspath(os.path.join(unit_dir, '..'))
125 for dirname in os.listdir(base_dir):
126 if dirname.startswith('machine-'):
127 agent_conf = os.path.join(base_dir, dirname, 'agent.conf')
128 break
129 else:
130 raise IOError('Juju agent configuration file not found.')
131 contents = yaml.load(open(agent_conf))
132 return contents['apiinfo']['addrs'][0]
133
134
135def get_staging_dependencies():
136 """Install deb dependencies for the stage (improv) environment."""
137 log('Installing stage dependencies.')
138 cmd_log(apt_get_install(*DEB_STAGE_DEPENDENCIES))
139
140
141def first_path_in_dir(directory):
142 """Return the full path of the first file/dir in *directory*."""
143 return os.path.join(directory, os.listdir(directory)[0])
144
145
146def _get_by_attr(collection, attr, value):
147 """Return the first item in collection having attr == value.
148
149 Return None if the item is not found.
150 """
151 for item in collection:
152 if getattr(item, attr) == value:
153 return item
154
155
156def get_release_file_url(project, series_name, release_version):
157 """Return the URL of the release file hosted in Launchpad.
158
159 The returned URL points to a release file for the given project, series
160 name and release version.
161 The argument *project* is a project object as returned by launchpadlib.
162 The arguments *series_name* and *release_version* are strings. If
163 *release_version* is None, the URL of the latest release will be returned.
164 """
165 series = _get_by_attr(project.series, 'name', series_name)
166 if series is None:
167 raise ValueError('%r: series not found' % series_name)
168 # Releases are returned by Launchpad in reverse date order.
169 releases = list(series.releases)
170 if not releases:
171 raise ValueError('%r: series does not contain releases' % series_name)
172 if release_version is not None:
173 release = _get_by_attr(releases, 'version', release_version)
174 if release is None:
175 raise ValueError('%r: release not found' % release_version)
176 releases = [release]
177 for release in releases:
178 for file_ in release.files:
179 if str(file_).endswith('.tgz'):
180 return file_.file_link
181 raise ValueError('%r: file not found' % release_version)
182
183
184def get_zookeeper_address(agent_file_path):
185 """Retrieve the Zookeeper address contained in the given *agent_file_path*.
186
187 The *agent_file_path* is a path to a file containing a line similar to the
188 following::
189
190 env JUJU_ZOOKEEPER="address"
191 """
192 line = search_file('JUJU_ZOOKEEPER', agent_file_path).strip()
193 return line.split('=')[1].strip('"')
194
195
196@contextmanager
197def log_hook():
198 """Log when a hook starts and stops its execution.
199
200 Also log to stdout possible CalledProcessError exceptions raised executing
201 the hook.
202 """
203 script = script_name()
204 log(">>> Entering {}".format(script))
205 try:
206 yield
207 except CalledProcessError as err:
208 log('Exception caught:')
209 log(err.output)
210 raise
211 finally:
212 log("<<< Exiting {}".format(script))
213
214
215def parse_source(source):
216 """Parse the ``juju-gui-source`` option.
217
218 Return a tuple of two elements representing info on how to deploy Juju GUI.
219 Examples:
220 - ('stable', None): latest stable release;
221 - ('stable', '0.1.0'): stable release v0.1.0;
222 - ('trunk', None): latest trunk release;
223 - ('trunk', '0.1.0+build.1'): trunk release v0.1.0 bzr revision 1;
224 - ('branch', 'lp:juju-gui'): release is made from a branch;
225 - ('url', 'http://example.com/gui'): release from a downloaded file.
226 """
227 if source.startswith('url:'):
228 source = source[4:]
229 # Support file paths, including relative paths.
230 if urlparse(source).scheme == '':
231 if not source.startswith('/'):
232 source = os.path.join(os.path.abspath(CURRENT_DIR), source)
233 source = "file://%s" % source
234 return 'url', source
235 if source in ('stable', 'trunk'):
236 return source, None
237 if source.startswith('lp:') or source.startswith('http://'):
238 return 'branch', source
239 if 'build' in source:
240 return 'trunk', source
241 return 'stable', source
242
243
244def render_to_file(template_name, context, destination):
245 """Render the given *template_name* into *destination* using *context*.
246
247 The tempita template language is used to render contents
248 (see http://pythonpaste.org/tempita/).
249 The argument *template_name* is the name or path of the template file:
250 it may be either a path relative to ``../config`` or an absolute path.
251 The argument *destination* is a file path.
252 The argument *context* is a dict-like object.
253 """
254 template_path = os.path.abspath(template_name)
255 template = tempita.Template.from_filename(template_path)
256 with open(destination, 'w') as stream:
257 stream.write(template.substitute(context))
258
259
260results_log = None
261
262
263def _setupLogging():
264 global results_log
265 if results_log is not None:
266 return
267 cfg = config()
268 logging.basicConfig(
269 filename=cfg['command-log-file'],
270 level=logging.INFO,
271 format="%(asctime)s: %(name)s@%(levelname)s %(message)s")
272 results_log = logging.getLogger('juju-gui')
273
274
275def cmd_log(results):
276 global results_log
277 if not results:
278 return
279 if results_log is None:
280 _setupLogging()
281 # Since 'results' may be multi-line output, start it on a separate line
282 # from the logger timestamp, etc.
283 results_log.info('\n' + results)
284
285
286def start_improv(staging_env, ssl_cert_path,
287 config_path='/etc/init/juju-api-improv.conf'):
288 """Start a simulated juju environment using ``improv.py``."""
289 log('Setting up staging start up script.')
290 context = {
291 'juju_dir': JUJU_DIR,
292 'keys': ssl_cert_path,
293 'port': API_PORT,
294 'staging_env': staging_env,
295 }
296 render_to_file('config/juju-api-improv.conf.template', context, config_path)
297 log('Starting the staging backend.')
298 with su('root'):
299 service_start(IMPROV)
300
301
302def start_agent(
303 ssl_cert_path, config_path='/etc/init/juju-api-agent.conf',
304 read_only=False):
305 """Start the Juju agent and connect to the current environment."""
306 # Retrieve the Zookeeper address from the start up script.
307 unit_dir = os.path.realpath(os.path.join(CURRENT_DIR, '..'))
308 agent_file = '/etc/init/juju-{0}.conf'.format(os.path.basename(unit_dir))
309 zookeeper = get_zookeeper_address(agent_file)
310 log('Setting up API agent start up script.')
311 context = {
312 'juju_dir': JUJU_DIR,
313 'keys': ssl_cert_path,
314 'port': API_PORT,
315 'zookeeper': zookeeper,
316 'read_only': read_only
317 }
318 render_to_file('config/juju-api-agent.conf.template', context, config_path)
319 log('Starting API agent.')
320 with su('root'):
321 service_start(AGENT)
322
323
324def start_gui(
325 console_enabled, login_help, readonly, in_staging, ssl_cert_path,
326 charmworld_url, serve_tests, haproxy_path='/etc/haproxy/haproxy.cfg',
327 config_js_path=None, secure=True, sandbox=False):
328 """Set up and start the Juju GUI server."""
329 with su('root'):
330 run('chown', '-R', 'ubuntu:', JUJU_GUI_DIR)
331 # XXX 2013-02-05 frankban bug=1116320:
332 # External insecure resources are still loaded when testing in the
333 # debug environment. For now, switch to the production environment if
334 # the charm is configured to serve tests.
335 if in_staging and not serve_tests:
336 build_dirname = 'build-debug'
337 else:
338 build_dirname = 'build-prod'
339 build_dir = os.path.join(JUJU_GUI_DIR, build_dirname)
340 log('Generating the Juju GUI configuration file.')
341 is_legacy_juju = legacy_juju()
342 user, password = None, None
343 if (is_legacy_juju and in_staging) or sandbox:
344 user, password = 'admin', 'admin'
345 else:
346 user, password = None, None
347
348 api_backend = 'python' if is_legacy_juju else 'go'
349 if secure:
350 protocol = 'wss'
351 else:
352 log('Running in insecure mode! Port 80 will serve unencrypted.')
353 protocol = 'ws'
354
355 context = {
356 'raw_protocol': protocol,
357 'address': unit_get('public-address'),
358 'console_enabled': json.dumps(console_enabled),
359 'login_help': json.dumps(login_help),
360 'password': json.dumps(password),
361 'api_backend': json.dumps(api_backend),
362 'readonly': json.dumps(readonly),
363 'user': json.dumps(user),
364 'protocol': json.dumps(protocol),
365 'sandbox': json.dumps(sandbox),
366 'charmworld_url': json.dumps(charmworld_url),
367 }
368 if config_js_path is None:
369 config_js_path = os.path.join(
370 build_dir, 'juju-ui', 'assets', 'config.js')
371 render_to_file('config/config.js.template', context, config_js_path)
372
373 write_apache_config(build_dir, serve_tests)
374
375 log('Generating haproxy configuration file.')
376 if is_legacy_juju:
377 # The PyJuju API agent is listening on localhost.
378 api_address = '127.0.0.1:{0}'.format(API_PORT)
379 else:
380 # Retrieve the juju-core API server address.
381 api_address = get_api_address(os.path.join(CURRENT_DIR, '..'))
382 context = {
383 'api_address': api_address,
384 'api_pem': JUJU_PEM,
385 'legacy_juju': is_legacy_juju,
386 'ssl_cert_path': ssl_cert_path,
387 # In PyJuju environments, use the same certificate for both HTTPS and
388 # WebSocket connections. In juju-core the system already has the proper
389 # certificate installed.
390 'web_pem': JUJU_PEM,
391 'web_port': WEB_PORT,
392 'secure': secure
393 }
394 render_to_file('config/haproxy.cfg.template', context, haproxy_path)
395 log('Starting Juju GUI.')
396
397
398def write_apache_config(build_dir, serve_tests=False):
399 log('Generating the apache site configuration file.')
400 context = {
401 'port': WEB_PORT,
402 'serve_tests': serve_tests,
403 'server_root': build_dir,
404 'tests_root': os.path.join(JUJU_GUI_DIR, 'test', ''),
405 }
406 render_to_file('config/apache-ports.template', context, JUJU_GUI_PORTS)
407 render_to_file('config/apache-site.template', context, JUJU_GUI_SITE)
408
409
410def get_npm_cache_archive_url(Launchpad=Launchpad):
411 """Figure out the URL of the most recent NPM cache archive on Launchpad."""
412 launchpad = Launchpad.login_anonymously('Juju GUI charm', 'production')
413 project = launchpad.projects['juju-gui']
414 # Find the URL of the most recently created NPM cache archive.
415 npm_cache_url = get_release_file_url(project, 'npm-cache', None)
416 return npm_cache_url
417
418
419def prime_npm_cache(npm_cache_url):
420 """Download NPM cache archive and prime the NPM cache with it."""
421 # Download the cache archive and then uncompress it into the NPM cache.
422 npm_cache_archive = os.path.join(CURRENT_DIR, 'npm-cache.tgz')
423 cmd_log(run('curl', '-L', '-o', npm_cache_archive, npm_cache_url))
424 npm_cache_dir = os.path.expanduser('~/.npm')
425 # The NPM cache directory probably does not exist, so make it if not.
426 try:
427 os.mkdir(npm_cache_dir)
428 except OSError, e:
429 # If the directory already exists then ignore the error.
430 if e.errno != errno.EEXIST: # File exists.
431 raise
432 uncompress = command('tar', '-x', '-z', '-C', npm_cache_dir, '-f')
433 cmd_log(uncompress(npm_cache_archive))
434
435
436def fetch_gui(juju_gui_source, logpath):
437 """Retrieve the Juju GUI release/branch."""
438 # Retrieve a Juju GUI release.
439 origin, version_or_branch = parse_source(juju_gui_source)
440 if origin == 'branch':
441 # Make sure we have the dependencies necessary for us to actually make
442 # a build.
443 _get_build_dependencies()
444 # Create a release starting from a branch.
445 juju_gui_source_dir = os.path.join(CURRENT_DIR, 'juju-gui-source')
446 log('Retrieving Juju GUI source checkout from %s.' % version_or_branch)
447 cmd_log(run('rm', '-rf', juju_gui_source_dir))
448 cmd_log(bzr_checkout(version_or_branch, juju_gui_source_dir))
449 log('Preparing a Juju GUI release.')
450 logdir = os.path.dirname(logpath)
451 fd, name = tempfile.mkstemp(prefix='make-distfile-', dir=logdir)
452 log('Output from "make distfile" sent to %s' % name)
453 with environ(NO_BZR='1'):
454 run('make', '-C', juju_gui_source_dir, 'distfile',
455 stdout=fd, stderr=fd)
456 release_tarball = first_path_in_dir(
457 os.path.join(juju_gui_source_dir, 'releases'))
458 else:
459 log('Retrieving Juju GUI release.')
460 if origin == 'url':
461 file_url = version_or_branch
462 else:
463 # Retrieve a release from Launchpad.
464 launchpad = Launchpad.login_anonymously(
465 'Juju GUI charm', 'production')
466 project = launchpad.projects['juju-gui']
467 file_url = get_release_file_url(project, origin, version_or_branch)
468 log('Downloading release file from %s.' % file_url)
469 release_tarball = os.path.join(CURRENT_DIR, 'release.tgz')
470 cmd_log(run('curl', '-L', '-o', release_tarball, file_url))
471 return release_tarball
472
473
474def fetch_api(juju_api_branch):
475 """Retrieve the Juju branch."""
476 # Retrieve Juju API source checkout.
477 log('Retrieving Juju API source checkout.')
478 cmd_log(run('rm', '-rf', JUJU_DIR))
479 cmd_log(bzr_checkout(juju_api_branch, JUJU_DIR))
480
481
482def setup_gui(release_tarball):
483 """Set up Juju GUI."""
484 # Uncompress the release tarball.
485 log('Installing Juju GUI.')
486 release_dir = os.path.join(CURRENT_DIR, 'release')
487 cmd_log(run('rm', '-rf', release_dir))
488 os.mkdir(release_dir)
489 uncompress = command('tar', '-x', '-z', '-C', release_dir, '-f')
490 cmd_log(uncompress(release_tarball))
491 # Link the Juju GUI dir to the contents of the release tarball.
492 cmd_log(run('ln', '-sf', first_path_in_dir(release_dir), JUJU_GUI_DIR))
493
494
495def setup_apache():
496 """Set up apache."""
497 log('Setting up apache.')
498 if not os.path.exists(JUJU_GUI_SITE):
499 cmd_log(run('touch', JUJU_GUI_SITE))
500 cmd_log(run('chown', 'ubuntu:', JUJU_GUI_SITE))
501 cmd_log(
502 run('ln', '-s', JUJU_GUI_SITE,
503 '/etc/apache2/sites-enabled/juju-gui'))
504
505 if not os.path.exists(JUJU_GUI_PORTS):
506 cmd_log(run('touch', JUJU_GUI_PORTS))
507 cmd_log(run('chown', 'ubuntu:', JUJU_GUI_PORTS))
508
509 with su('root'):
510 run('a2dissite', 'default')
511 run('a2ensite', 'juju-gui')
512
513
514def save_or_create_certificates(
515 ssl_cert_path, ssl_cert_contents, ssl_key_contents):
516 """Generate the SSL certificates.
517
518 If both *ssl_cert_contents* and *ssl_key_contents* are provided, use them
519 as certificates; otherwise, generate them.
520
521 Also create a pem file, suitable for use in the haproxy configuration,
522 concatenating the key and the certificate files.
523 """
524 crt_path = os.path.join(ssl_cert_path, 'juju.crt')
525 key_path = os.path.join(ssl_cert_path, 'juju.key')
526 if not os.path.exists(ssl_cert_path):
527 os.makedirs(ssl_cert_path)
528 if ssl_cert_contents and ssl_key_contents:
529 # Save the provided certificates.
530 with open(crt_path, 'w') as cert_file:
531 cert_file.write(ssl_cert_contents)
532 with open(key_path, 'w') as key_file:
533 key_file.write(ssl_key_contents)
534 else:
535 # Generate certificates.
536 # See http://superuser.com/questions/226192/openssl-without-prompt
537 cmd_log(run(
538 'openssl', 'req', '-new', '-newkey', 'rsa:4096',
539 '-days', '365', '-nodes', '-x509', '-subj',
540 # These are arbitrary test values for the certificate.
541 '/C=GB/ST=Juju/L=GUI/O=Ubuntu/CN=juju.ubuntu.com',
542 '-keyout', key_path, '-out', crt_path))
543 # Generate the pem file.
544 pem_path = os.path.join(ssl_cert_path, JUJU_PEM)
545 if os.path.exists(pem_path):
546 os.remove(pem_path)
547 with open(pem_path, 'w') as pem_file:
548 shutil.copyfileobj(open(key_path), pem_file)
549 shutil.copyfileobj(open(crt_path), pem_file)
550
551
552def find_missing_packages(*packages):
553 """Given a list of packages, return the packages which are not installed.
554 """
555 cache = apt.Cache()
556 missing = set()
557 for pkg_name in packages:
558 try:
559 pkg = cache[pkg_name]
560 except KeyError:
561 missing.add(pkg_name)
562 continue
563 if pkg.is_installed:
564 continue
565 missing.add(pkg_name)
566 return missing
567
568
569## Backend support decorators
570
571def chain(name):
572 """Helper method to compose a set of mixin objects into a callable.
573
574 Each method is called in the context of its mixin instance, and its
575 argument is the Backend instance.
576 """
577 # Chain method calls through all implementing mixins.
578 def method(self):
579 for mixin in self.mixins:
580 a_callable = getattr(type(mixin), name, None)
581 if a_callable:
582 a_callable(mixin, self)
583
584 method.__name__ = name
585 return method
586
587
588def merge(name):
589 """Helper to merge a property from a set of strategy objects
590 into a unified set.
591 """
592 # Return merged property from every providing mixin as a set.
593 @property
594 def method(self):
595 result = set()
596 for mixin in self.mixins:
597 segment = getattr(type(mixin), name, None)
598 if segment and isinstance(segment, (list, tuple, set)):
599 result |= set(segment)
600
601 return result
602 return method
0603
=== added directory 'lib/charm-helpers/charmhelpers/contrib/network'
=== added file 'lib/charm-helpers/charmhelpers/contrib/network/__init__.py'
=== added directory 'lib/charm-helpers/charmhelpers/contrib/network/ovs'
=== added file 'lib/charm-helpers/charmhelpers/contrib/network/ovs/__init__.py'
--- lib/charm-helpers/charmhelpers/contrib/network/ovs/__init__.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/network/ovs/__init__.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,72 @@
1''' Helpers for interacting with OpenvSwitch '''
2import subprocess
3import os
4from charmhelpers.core.hookenv import (
5 log, WARNING
6)
7from charmhelpers.core.host import (
8 service
9)
10
11
12def add_bridge(name):
13 ''' Add the named bridge to openvswitch '''
14 log('Creating bridge {}'.format(name))
15 subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-br", name])
16
17
18def del_bridge(name):
19 ''' Delete the named bridge from openvswitch '''
20 log('Deleting bridge {}'.format(name))
21 subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-br", name])
22
23
24def add_bridge_port(name, port):
25 ''' Add a port to the named openvswitch bridge '''
26 log('Adding port {} to bridge {}'.format(port, name))
27 subprocess.check_call(["ovs-vsctl", "--", "--may-exist", "add-port",
28 name, port])
29 subprocess.check_call(["ip", "link", "set", port, "up"])
30
31
32def del_bridge_port(name, port):
33 ''' Delete a port from the named openvswitch bridge '''
34 log('Deleting port {} from bridge {}'.format(port, name))
35 subprocess.check_call(["ovs-vsctl", "--", "--if-exists", "del-port",
36 name, port])
37 subprocess.check_call(["ip", "link", "set", port, "down"])
38
39
40def set_manager(manager):
41 ''' Set the controller for the local openvswitch '''
42 log('Setting manager for local ovs to {}'.format(manager))
43 subprocess.check_call(['ovs-vsctl', 'set-manager',
44 'ssl:{}'.format(manager)])
45
46
47CERT_PATH = '/etc/openvswitch/ovsclient-cert.pem'
48
49
50def get_certificate():
51 ''' Read openvswitch certificate from disk '''
52 if os.path.exists(CERT_PATH):
53 log('Reading ovs certificate from {}'.format(CERT_PATH))
54 with open(CERT_PATH, 'r') as cert:
55 full_cert = cert.read()
56 begin_marker = "-----BEGIN CERTIFICATE-----"
57 end_marker = "-----END CERTIFICATE-----"
58 begin_index = full_cert.find(begin_marker)
59 end_index = full_cert.rfind(end_marker)
60 if end_index == -1 or begin_index == -1:
61 raise RuntimeError("Certificate does not contain valid begin"
62 " and end markers.")
63 full_cert = full_cert[begin_index:(end_index + len(end_marker))]
64 return full_cert
65 else:
66 log('Certificate not found', level=WARNING)
67 return None
68
69
70def full_restart():
71 ''' Full restart and reload of openvswitch '''
72 service('force-reload-kmod', 'openvswitch-switch')
073
=== added directory 'lib/charm-helpers/charmhelpers/contrib/openstack'
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/__init__.py'
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/context.py'
--- lib/charm-helpers/charmhelpers/contrib/openstack/context.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/context.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,294 @@
1import os
2
3from base64 import b64decode
4
5from subprocess import (
6 check_call
7)
8
9from charmhelpers.core.hookenv import (
10 config,
11 local_unit,
12 log,
13 relation_get,
14 relation_ids,
15 related_units,
16 unit_get,
17)
18
19from charmhelpers.contrib.hahelpers.cluster import (
20 determine_api_port,
21 determine_haproxy_port,
22 https,
23 is_clustered,
24 peer_units,
25)
26
27from charmhelpers.contrib.hahelpers.apache import (
28 get_cert,
29 get_ca_cert,
30)
31
32CA_CERT_PATH = '/usr/local/share/ca-certificates/keystone_juju_ca_cert.crt'
33
34
35class OSContextError(Exception):
36 pass
37
38
39def context_complete(ctxt):
40 _missing = []
41 for k, v in ctxt.iteritems():
42 if v is None or v == '':
43 _missing.append(k)
44 if _missing:
45 log('Missing required data: %s' % ' '.join(_missing), level='INFO')
46 return False
47 return True
48
49
50class OSContextGenerator(object):
51 interfaces = []
52
53 def __call__(self):
54 raise NotImplementedError
55
56
57class SharedDBContext(OSContextGenerator):
58 interfaces = ['shared-db']
59
60 def __call__(self):
61 log('Generating template context for shared-db')
62 conf = config()
63 try:
64 database = conf['database']
65 username = conf['database-user']
66 except KeyError as e:
67 log('Could not generate shared_db context. '
68 'Missing required charm config options: %s.' % e)
69 raise OSContextError
70 ctxt = {}
71 for rid in relation_ids('shared-db'):
72 for unit in related_units(rid):
73 ctxt = {
74 'database_host': relation_get('db_host', rid=rid,
75 unit=unit),
76 'database': database,
77 'database_user': username,
78 'database_password': relation_get('password', rid=rid,
79 unit=unit)
80 }
81 if not context_complete(ctxt):
82 return {}
83 return ctxt
84
85
86class IdentityServiceContext(OSContextGenerator):
87 interfaces = ['identity-service']
88
89 def __call__(self):
90 log('Generating template context for identity-service')
91 ctxt = {}
92
93 for rid in relation_ids('identity-service'):
94 for unit in related_units(rid):
95 ctxt = {
96 'service_port': relation_get('service_port', rid=rid,
97 unit=unit),
98 'service_host': relation_get('service_host', rid=rid,
99 unit=unit),
100 'auth_host': relation_get('auth_host', rid=rid, unit=unit),
101 'auth_port': relation_get('auth_port', rid=rid, unit=unit),
102 'admin_tenant_name': relation_get('service_tenant',
103 rid=rid, unit=unit),
104 'admin_user': relation_get('service_username', rid=rid,
105 unit=unit),
106 'admin_password': relation_get('service_password', rid=rid,
107 unit=unit),
108 # XXX: Hard-coded http.
109 'service_protocol': 'http',
110 'auth_protocol': 'http',
111 }
112 if not context_complete(ctxt):
113 return {}
114 return ctxt
115
116
117class AMQPContext(OSContextGenerator):
118 interfaces = ['amqp']
119
120 def __call__(self):
121 log('Generating template context for amqp')
122 conf = config()
123 try:
124 username = conf['rabbit-user']
125 vhost = conf['rabbit-vhost']
126 except KeyError as e:
127 log('Could not generate shared_db context. '
128 'Missing required charm config options: %s.' % e)
129 raise OSContextError
130
131 ctxt = {}
132 for rid in relation_ids('amqp'):
133 for unit in related_units(rid):
134 if relation_get('clustered', rid=rid, unit=unit):
135 rabbitmq_host = relation_get('vip', rid=rid, unit=unit)
136 else:
137 rabbitmq_host = relation_get('private-address',
138 rid=rid, unit=unit)
139 ctxt = {
140 'rabbitmq_host': rabbitmq_host,
141 'rabbitmq_user': username,
142 'rabbitmq_password': relation_get('password', rid=rid,
143 unit=unit),
144 'rabbitmq_virtual_host': vhost,
145 }
146 if not context_complete(ctxt):
147 return {}
148 return ctxt
149
150
151class CephContext(OSContextGenerator):
152 interfaces = ['ceph']
153
154 def __call__(self):
155 '''This generates context for /etc/ceph/ceph.conf templates'''
156 log('Generating tmeplate context for ceph')
157 mon_hosts = []
158 auth = None
159 for rid in relation_ids('ceph'):
160 for unit in related_units(rid):
161 mon_hosts.append(relation_get('private-address', rid=rid,
162 unit=unit))
163 auth = relation_get('auth', rid=rid, unit=unit)
164
165 ctxt = {
166 'mon_hosts': ' '.join(mon_hosts),
167 'auth': auth,
168 }
169 if not context_complete(ctxt):
170 return {}
171 return ctxt
172
173
174class HAProxyContext(OSContextGenerator):
175 interfaces = ['cluster']
176
177 def __call__(self):
178 '''
179 Builds half a context for the haproxy template, which describes
180 all peers to be included in the cluster. Each charm needs to include
181 its own context generator that describes the port mapping.
182 '''
183 if not relation_ids('cluster'):
184 return {}
185
186 cluster_hosts = {}
187 l_unit = local_unit().replace('/', '-')
188 cluster_hosts[l_unit] = unit_get('private-address')
189
190 for rid in relation_ids('cluster'):
191 for unit in related_units(rid):
192 _unit = unit.replace('/', '-')
193 addr = relation_get('private-address', rid=rid, unit=unit)
194 cluster_hosts[_unit] = addr
195
196 ctxt = {
197 'units': cluster_hosts,
198 }
199 if len(cluster_hosts.keys()) > 1:
200 # Enable haproxy when we have enough peers.
201 log('Ensuring haproxy enabled in /etc/default/haproxy.')
202 with open('/etc/default/haproxy', 'w') as out:
203 out.write('ENABLED=1\n')
204 return ctxt
205 log('HAProxy context is incomplete, this unit has no peers.')
206 return {}
207
208
209class ImageServiceContext(OSContextGenerator):
210 interfaces = ['image-servce']
211
212 def __call__(self):
213 '''
214 Obtains the glance API server from the image-service relation. Useful
215 in nova and cinder (currently).
216 '''
217 log('Generating template context for image-service.')
218 rids = relation_ids('image-service')
219 if not rids:
220 return {}
221 for rid in rids:
222 for unit in related_units(rid):
223 api_server = relation_get('glance-api-server',
224 rid=rid, unit=unit)
225 if api_server:
226 return {'glance_api_servers': api_server}
227 log('ImageService context is incomplete. '
228 'Missing required relation data.')
229 return {}
230
231
232class ApacheSSLContext(OSContextGenerator):
233 """
234 Generates a context for an apache vhost configuration that configures
235 HTTPS reverse proxying for one or many endpoints. Generated context
236 looks something like:
237 {
238 'namespace': 'cinder',
239 'private_address': 'iscsi.mycinderhost.com',
240 'endpoints': [(8776, 8766), (8777, 8767)]
241 }
242
243 The endpoints list consists of a tuples mapping external ports
244 to internal ports.
245 """
246 interfaces = ['https']
247
248 # charms should inherit this context and set external ports
249 # and service namespace accordingly.
250 external_ports = []
251 service_namespace = None
252
253 def enable_modules(self):
254 cmd = ['a2enmod', 'ssl', 'proxy', 'proxy_http']
255 check_call(cmd)
256
257 def configure_cert(self):
258 if not os.path.isdir('/etc/apache2/ssl'):
259 os.mkdir('/etc/apache2/ssl')
260 ssl_dir = os.path.join('/etc/apache2/ssl/', self.service_namespace)
261 if not os.path.isdir(ssl_dir):
262 os.mkdir(ssl_dir)
263 cert, key = get_cert()
264 with open(os.path.join(ssl_dir, 'cert'), 'w') as cert_out:
265 cert_out.write(b64decode(cert))
266 with open(os.path.join(ssl_dir, 'key'), 'w') as key_out:
267 key_out.write(b64decode(key))
268 ca_cert = get_ca_cert()
269 if ca_cert:
270 with open(CA_CERT_PATH, 'w') as ca_out:
271 ca_out.write(b64decode(ca_cert))
272
273 def __call__(self):
274 if isinstance(self.external_ports, basestring):
275 self.external_ports = [self.external_ports]
276 if (not self.external_ports or not https()):
277 return {}
278
279 self.configure_cert()
280 self.enable_modules()
281
282 ctxt = {
283 'namespace': self.service_namespace,
284 'private_address': unit_get('private-address'),
285 'endpoints': []
286 }
287 for ext_port in self.external_ports:
288 if peer_units() or is_clustered():
289 int_port = determine_haproxy_port(ext_port)
290 else:
291 int_port = determine_api_port(ext_port)
292 portmap = (int(ext_port), int(int_port))
293 ctxt['endpoints'].append(portmap)
294 return ctxt
0295
=== added directory 'lib/charm-helpers/charmhelpers/contrib/openstack/templates'
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/templates/__init__.py'
--- lib/charm-helpers/charmhelpers/contrib/openstack/templates/__init__.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/templates/__init__.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,2 @@
1# dummy __init__.py to fool syncer into thinking this is a syncable python
2# module
03
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/templates/ceph.conf'
--- lib/charm-helpers/charmhelpers/contrib/openstack/templates/ceph.conf 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/templates/ceph.conf 2013-09-26 06:24:47 +0000
@@ -0,0 +1,11 @@
1###############################################################################
2# [ WARNING ]
3# cinder configuration file maintained by Juju
4# local changes may be overwritten.
5###############################################################################
6{% if auth -%}
7[global]
8 auth_supported = {{ auth }}
9 keyring = /etc/ceph/$cluster.$name.keyring
10 mon host = {{ mon_hosts }}
11{% endif -%}
012
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/templates/haproxy.cfg'
--- lib/charm-helpers/charmhelpers/contrib/openstack/templates/haproxy.cfg 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/templates/haproxy.cfg 2013-09-26 06:24:47 +0000
@@ -0,0 +1,37 @@
1global
2 log 127.0.0.1 local0
3 log 127.0.0.1 local1 notice
4 maxconn 20000
5 user haproxy
6 group haproxy
7 spread-checks 0
8
9defaults
10 log global
11 mode http
12 option httplog
13 option dontlognull
14 retries 3
15 timeout queue 1000
16 timeout connect 1000
17 timeout client 30000
18 timeout server 30000
19
20listen stats :8888
21 mode http
22 stats enable
23 stats hide-version
24 stats realm Haproxy\ Statistics
25 stats uri /
26 stats auth admin:password
27
28{% if units -%}
29{% for service, ports in service_ports.iteritems() -%}
30listen {{ service }} 0.0.0.0:{{ ports[0] }}
31 balance roundrobin
32 option tcplog
33 {% for unit, address in units.iteritems() -%}
34 server {{ unit }} {{ address }}:{{ ports[1] }} check
35 {% endfor %}
36{% endfor -%}
37{% endif -%}
038
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/templates/openstack_https_frontend'
--- lib/charm-helpers/charmhelpers/contrib/openstack/templates/openstack_https_frontend 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/templates/openstack_https_frontend 2013-09-26 06:24:47 +0000
@@ -0,0 +1,23 @@
1{% if endpoints -%}
2{% for ext, int in endpoints -%}
3Listen {{ ext }}
4NameVirtualHost *:{{ ext }}
5<VirtualHost *:{{ ext }}>
6 ServerName {{ private_address }}
7 SSLEngine on
8 SSLCertificateFile /etc/apache2/ssl/{{ namespace }}/cert
9 SSLCertificateKeyFile /etc/apache2/ssl/{{ namespace }}/key
10 ProxyPass / http://localhost:{{ int }}/
11 ProxyPassReverse / http://localhost:{{ int }}/
12 ProxyPreserveHost on
13</VirtualHost>
14<Proxy *>
15 Order deny,allow
16 Allow from all
17</Proxy>
18<Location />
19 Order allow,deny
20 Allow from all
21</Location>
22{% endfor -%}
23{% endif -%}
024
=== added file 'lib/charm-helpers/charmhelpers/contrib/openstack/templating.py'
--- lib/charm-helpers/charmhelpers/contrib/openstack/templating.py 1970-01-01 00:00:00 +0000
+++ lib/charm-helpers/charmhelpers/contrib/openstack/templating.py 2013-09-26 06:24:47 +0000
@@ -0,0 +1,261 @@
1import os
2
3from charmhelpers.fetch import apt_install
4
5from charmhelpers.core.hookenv import (
6 log,
7 ERROR,
8 INFO
9)
10
11from charmhelpers.contrib.openstack.utils import OPENSTACK_CODENAMES
12
13try:
14 from jinja2 import FileSystemLoader, ChoiceLoader, Environment
15except ImportError:
16 # python-jinja2 may not be installed yet, or we're running unittests.
17 FileSystemLoader = ChoiceLoader = Environment = None
18
19
20class OSConfigException(Exception):
21 pass
22
23
24def get_loader(templates_dir, os_release):
25 """
26 Create a jinja2.ChoiceLoader containing template dirs up to
27 and including os_release. If directory template directory
28 is missing at templates_dir, it will be omitted from the loader.
29 templates_dir is added to the bottom of the search list as a base
30 loading dir.
31
32 A charm may also ship a templates dir with this module
33 and it will be appended to the bottom of the search list, eg:
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches

to all changes: