Merge lp:~lazypower/charms/trusty/mariadb/replace-bintar-with-repository into lp:~dbart/charms/trusty/mariadb/trunk
- Trusty Tahr (14.04)
- replace-bintar-with-repository
- Merge into trunk
Proposed by
Charles Butler
Status: | Merged |
---|---|
Approved by: | Daniel Bartholomew |
Approved revision: | 26 |
Merged at revision: | 20 |
Proposed branch: | lp:~lazypower/charms/trusty/mariadb/replace-bintar-with-repository |
Merge into: | lp:~dbart/charms/trusty/mariadb/trunk |
Diff against target: |
3588 lines (+3005/-333) 24 files modified
ENTERPRISE-LICENSE.md (+72/-0) README.md (+13/-1) charm-helpers.yaml (+6/-0) config.yaml (+17/-1) hooks/config-changed (+70/-64) hooks/install (+57/-177) lib/charmhelpers/core/fstab.py (+118/-0) lib/charmhelpers/core/hookenv.py (+540/-0) lib/charmhelpers/core/host.py (+396/-0) lib/charmhelpers/core/services/__init__.py (+2/-0) lib/charmhelpers/core/services/base.py (+313/-0) lib/charmhelpers/core/services/helpers.py (+243/-0) lib/charmhelpers/core/sysctl.py (+34/-0) lib/charmhelpers/core/templating.py (+52/-0) lib/charmhelpers/fetch/__init__.py (+416/-0) lib/charmhelpers/fetch/archiveurl.py (+145/-0) lib/charmhelpers/fetch/bzrurl.py (+54/-0) lib/charmhelpers/fetch/giturl.py (+48/-0) lib/charmhelpers/payload/__init__.py (+1/-0) lib/charmhelpers/payload/archive.py (+57/-0) lib/charmhelpers/payload/execd.py (+50/-0) scripts/charm_helpers_sync.py (+223/-0) tests/10-deploy-and-upgrade (+78/-0) tests/10-deploy-test.py (+0/-90) |
To merge this branch: | bzr merge lp:~lazypower/charms/trusty/mariadb/replace-bintar-with-repository |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Daniel Bartholomew | Approve | ||
Review via email:
|
Commit message
Description of the change
Replace bintar delivery with a pure PPA based approach
To post a comment you must log in.
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === added file 'ENTERPRISE-LICENSE.md' | |||
2 | --- ENTERPRISE-LICENSE.md 1970-01-01 00:00:00 +0000 | |||
3 | +++ ENTERPRISE-LICENSE.md 2014-12-15 18:28:33 +0000 | |||
4 | @@ -0,0 +1,72 @@ | |||
5 | 1 | # Evaluation Agreement | ||
6 | 2 | |||
7 | 3 | |||
8 | 4 | Our fee-bearing, annual subscriptions for MariaDB Enterprise, MariaDB Enterprise | ||
9 | 5 | Cluster, MariaDB Galera Cluster, MariaDB MaxScale or other MariaDB products | ||
10 | 6 | (“MariaDB Subscriptions”) includes access to: (a) software; and (b) services, | ||
11 | 7 | such as software support, access to our customer portal and related product | ||
12 | 8 | documentation, and the right to receive executable binaries of our software | ||
13 | 9 | patches, updates and security fixes (“Services”). | ||
14 | 10 | |||
15 | 11 | The purpose of this Evaluation Agreement is to provide you with access to a | ||
16 | 12 | MariaDB Subscription on an evaluation basis (an “Evaluation Subscription”). | ||
17 | 13 | Some of the differences between an Evaluation Subscription and a MariaDB | ||
18 | 14 | Subscription are described below. | ||
19 | 15 | |||
20 | 16 | An Evaluation Subscription for MariaDB Enterprise, MariaDB Enterprise Cluster, | ||
21 | 17 | MariaDB Galera Cluster, MariaDB MaxScale entitles you to: | ||
22 | 18 | |||
23 | 19 | - executable binary code | ||
24 | 20 | - patches | ||
25 | 21 | - bug fixes | ||
26 | 22 | - security updates | ||
27 | 23 | - the customer portal | ||
28 | 24 | - product documentation | ||
29 | 25 | - software trials for MONYog | ||
30 | 26 | - limited support from MariaDB's Sales Engineering team | ||
31 | 27 | |||
32 | 28 | A full, annual MariaDB Subscription for MariaDB Enterprise or MariaDB Enterprise | ||
33 | 29 | Cluster entitles you to: | ||
34 | 30 | |||
35 | 31 | - executable binary code | ||
36 | 32 | - patches | ||
37 | 33 | - bug fixes | ||
38 | 34 | - security updates | ||
39 | 35 | - the customer portal | ||
40 | 36 | - product documentation | ||
41 | 37 | - Full access to MONYog Ultimate Monitor | ||
42 | 38 | - product roadmaps | ||
43 | 39 | - 24/7 help desk support from MariaDB’s Technical Support team | ||
44 | 40 | - Other items that may be added at MariaDB’s discretion | ||
45 | 41 | |||
46 | 42 | While access to software components of an Evaluation Subscription are subject | ||
47 | 43 | to underlying applicable open source or proprietary license(s), as the case may | ||
48 | 44 | be (and this Evaluation Agreement does not limit or further restrict any open | ||
49 | 45 | source license rights), access to any Services or non-open source software | ||
50 | 46 | components is for the sole purpose of evaluating and testing | ||
51 | 47 | (“Evaluation Purpose”) the suitability of a MariaDB Subscription for your own | ||
52 | 48 | use for a defined time period and support level. | ||
53 | 49 | |||
54 | 50 | Your right to access an Evaluation Subscription without charge is conditioned on | ||
55 | 51 | the following: (a) you agree to the MariaDB Enterprise Terms and Conditions | ||
56 | 52 | (the “Subscription Agreement”); | ||
57 | 53 | (b) you agree that this Evaluation Subscription does not grant any right or | ||
58 | 54 | license, express or implied, for the use of any MariaDB or third party trade | ||
59 | 55 | names, service marks or trademarks, including, without limitation, the right to | ||
60 | 56 | distribute any software using any such marks; and (c) if you use our Services | ||
61 | 57 | for any purpose other than Evaluation Purposes, you agree to pay MariaDB | ||
62 | 58 | per-unit Subscription Fee(s) pursuant to the Subscription Agreement. Using our | ||
63 | 59 | Services in ways that do not constitute an Evaluation Purpose include (but are | ||
64 | 60 | not limited to) using Services in connection with Production Purposes or third | ||
65 | 61 | parties, or as a complement or supplement to third party support services. | ||
66 | 62 | Capitalized terms not defined in this Evaluation Agreement shall have the | ||
67 | 63 | meaning provided in the Subscription Agreement, which is incorporated by | ||
68 | 64 | reference in its entirety. | ||
69 | 65 | |||
70 | 66 | By using any of our Services, you affirm that you have read, understood, and | ||
71 | 67 | agree to all of the terms and conditions of this Evaluation Agreement | ||
72 | 68 | (including the Subscription Agreement). If you are an individual acting on | ||
73 | 69 | behalf of an entity, you represent that you have the authority to enter into | ||
74 | 70 | this Evaluation Agreement on behalf of that entity. If you do not accept the | ||
75 | 71 | terms and conditions of this Evaluation Agreement, then you must not use any | ||
76 | 72 | of our Services. | ||
77 | 0 | 73 | ||
78 | === modified file 'README.md' | |||
79 | --- README.md 2014-09-26 18:37:52 +0000 | |||
80 | +++ README.md 2014-12-15 18:28:33 +0000 | |||
81 | @@ -32,7 +32,19 @@ | |||
82 | 32 | juju ssh mariadb/0 | 32 | juju ssh mariadb/0 |
83 | 33 | mysql -u root -p$(sudo cat /var/lib/mysql/mysql.passwd) | 33 | mysql -u root -p$(sudo cat /var/lib/mysql/mysql.passwd) |
84 | 34 | 34 | ||
86 | 35 | # Scale Out Usage | 35 | ## To upgrade from Community to Enterprise Evaluation |
87 | 36 | |||
88 | 37 | Once you have obtained a username/password from the [MariaDB Portal](http://mariadb.com) | ||
89 | 38 | there will be a repository provided for your enterprise trial installation. You can enable | ||
90 | 39 | this in the charm with the following configuration: | ||
91 | 40 | |||
92 | 41 | juju set mariadb enterprise-eula=true source="deb https://username:password@code.mariadb.com/mariadb-enterprise/10.0/repo/ubuntu trusty main" | ||
93 | 42 | |||
94 | 43 | This will perform an in-place binary upgrade on all the mariadb nodes from community | ||
95 | 44 | edition to the Enterprise Evaluation. You must agree to all terms contained in | ||
96 | 45 | `ENTERPRISE-LICENSE.md` in the charm directory | ||
97 | 46 | |||
98 | 47 | # Scale Out Usage | ||
99 | 36 | 48 | ||
100 | 37 | ## Replication | 49 | ## Replication |
101 | 38 | 50 | ||
102 | 39 | 51 | ||
103 | === added file 'charm-helpers.yaml' | |||
104 | --- charm-helpers.yaml 1970-01-01 00:00:00 +0000 | |||
105 | +++ charm-helpers.yaml 2014-12-15 18:28:33 +0000 | |||
106 | @@ -0,0 +1,6 @@ | |||
107 | 1 | destination: lib/charmhelpers | ||
108 | 2 | branch: lp:charm-helpers | ||
109 | 3 | include: | ||
110 | 4 | - core | ||
111 | 5 | - fetch | ||
112 | 6 | - payload | ||
113 | 0 | 7 | ||
114 | === modified file 'config.yaml' | |||
115 | --- config.yaml 2014-09-25 20:29:40 +0000 | |||
116 | +++ config.yaml 2014-12-15 18:28:33 +0000 | |||
117 | @@ -100,4 +100,20 @@ | |||
118 | 100 | rbd pool has been created, changing this value will not have any | 100 | rbd pool has been created, changing this value will not have any |
119 | 101 | effect (although it can be changed in ceph by manually configuring | 101 | effect (although it can be changed in ceph by manually configuring |
120 | 102 | your ceph cluster). | 102 | your ceph cluster). |
122 | 103 | 103 | enterprise-eula: | |
123 | 104 | type: boolean | ||
124 | 105 | default: false | ||
125 | 106 | description: | | ||
126 | 107 | I have read and agree to the ENTERPRISE TRIAL agreement, located | ||
127 | 108 | in ENTERPRISE-LICENSE.md located in the charm, or on the web here: | ||
128 | 109 | https://mariadb.com/about/legal/evaluation-agreement | ||
129 | 110 | source: | ||
130 | 111 | type: string | ||
131 | 112 | default: "deb http://mirror.jmu.edu/pub/mariadb/repo/10.0/ubuntu trusty main" | ||
132 | 113 | description: | | ||
133 | 114 | Repository Mirror string to install MariaDB from | ||
134 | 115 | key: | ||
135 | 116 | type: string | ||
136 | 117 | default: "0xcbcb082a1bb943db" | ||
137 | 118 | description: | | ||
138 | 119 | GPG Key used to verify apt packages. | ||
139 | 104 | 120 | ||
140 | === modified file 'hooks/config-changed' | |||
141 | --- hooks/config-changed 2014-09-25 20:29:40 +0000 | |||
142 | +++ hooks/config-changed 2014-12-15 18:28:33 +0000 | |||
143 | @@ -1,6 +1,6 @@ | |||
144 | 1 | #!/usr/bin/python | 1 | #!/usr/bin/python |
145 | 2 | 2 | ||
147 | 3 | from subprocess import check_output,check_call, CalledProcessError, Popen, PIPE | 3 | from subprocess import check_output, check_call, CalledProcessError |
148 | 4 | import tempfile | 4 | import tempfile |
149 | 5 | import json | 5 | import json |
150 | 6 | import re | 6 | import re |
151 | @@ -9,15 +9,30 @@ | |||
152 | 9 | import sys | 9 | import sys |
153 | 10 | import platform | 10 | import platform |
154 | 11 | from string import upper | 11 | from string import upper |
155 | 12 | from subprocess import Popen, PIPE | ||
156 | 13 | |||
157 | 14 | sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib')) | ||
158 | 15 | |||
159 | 16 | from charmhelpers import fetch | ||
160 | 17 | |||
161 | 18 | from charmhelpers.core import ( | ||
162 | 19 | hookenv, | ||
163 | 20 | host, | ||
164 | 21 | ) | ||
165 | 22 | |||
166 | 23 | log = hookenv.log | ||
167 | 24 | config = hookenv.config() | ||
168 | 12 | 25 | ||
169 | 13 | num_re = re.compile('^[0-9]+$') | 26 | num_re = re.compile('^[0-9]+$') |
170 | 27 | package = 'mysql-server' | ||
171 | 28 | |||
172 | 14 | 29 | ||
173 | 15 | # There should be a library for this | 30 | # There should be a library for this |
174 | 16 | def human_to_bytes(human): | 31 | def human_to_bytes(human): |
175 | 17 | if num_re.match(human): | 32 | if num_re.match(human): |
176 | 18 | return human | 33 | return human |
179 | 19 | factors = { 'K' : 1024 , 'M' : 1048576, 'G' : 1073741824, 'T' : 1099511627776 } | 34 | factors = {'K': 1024, 'M': 1048576, 'G': 1073741824, 'T': 1099511627776} |
180 | 20 | modifier=human[-1] | 35 | modifier = human[-1] |
181 | 21 | if modifier in factors: | 36 | if modifier in factors: |
182 | 22 | return int(human[:-1]) * factors[modifier] | 37 | return int(human[:-1]) * factors[modifier] |
183 | 23 | if modifier == '%': | 38 | if modifier == '%': |
184 | @@ -41,18 +56,17 @@ | |||
185 | 41 | IS_32BIT_SYSTEM = True | 56 | IS_32BIT_SYSTEM = True |
186 | 42 | 57 | ||
187 | 43 | if platform.machine() in ['armv7l']: | 58 | if platform.machine() in ['armv7l']: |
189 | 44 | SYS_MEM_LIMIT = human_to_bytes('2700M') # experimentally determined | 59 | SYS_MEM_LIMIT = human_to_bytes('2700M') # experimentally determined |
190 | 45 | else: | 60 | else: |
191 | 46 | SYS_MEM_LIMIT = human_to_bytes('4G') | 61 | SYS_MEM_LIMIT = human_to_bytes('4G') |
192 | 47 | 62 | ||
193 | 48 | if IS_32BIT_SYSTEM: | 63 | if IS_32BIT_SYSTEM: |
195 | 49 | check_call(['juju-log','-l','INFO','32bit system restrictions in play']) | 64 | log("32bit system restrictions in play", "INFO") |
196 | 50 | 65 | ||
198 | 51 | configs=json.loads(check_output(['config-get','--format=json'])) | 66 | configs = json.loads(check_output(['config-get','--format=json'])) |
199 | 52 | 67 | ||
200 | 53 | def get_memtotal(): | 68 | def get_memtotal(): |
201 | 54 | with open('/proc/meminfo') as meminfo_file: | 69 | with open('/proc/meminfo') as meminfo_file: |
202 | 55 | meminfo = {} | ||
203 | 56 | for line in meminfo_file: | 70 | for line in meminfo_file: |
204 | 57 | (key, mem) = line.split(':', 2) | 71 | (key, mem) = line.split(':', 2) |
205 | 58 | if key == 'MemTotal': | 72 | if key == 'MemTotal': |
206 | @@ -60,48 +74,40 @@ | |||
207 | 60 | return '%s%s' % (mtot, upper(modifier[0])) | 74 | return '%s%s' % (mtot, upper(modifier[0])) |
208 | 61 | 75 | ||
209 | 62 | 76 | ||
245 | 63 | # There is preliminary code for mariadb, but switching | 77 | |
246 | 64 | # from mariadb -> mysql fails badly, so it is disabled for now. | 78 | source = config['source'] |
247 | 65 | valid_flavors = ['distro'] | 79 | accepted = config['enterprise-eula'] |
248 | 66 | 80 | ||
249 | 67 | #remove_pkgs=[] | 81 | |
250 | 68 | #apt_sources = [] | 82 | # set MariaDB Root Password |
251 | 69 | #package = 'mariadb-server' | 83 | with open('/var/lib/mysql/mysql.passwd', 'r') as rpw: |
252 | 70 | # | 84 | root_pass = rpw.read() |
253 | 71 | #series = check_output(['lsb_release','-cs']) | 85 | |
254 | 72 | # | 86 | |
255 | 73 | #for source in apt_sources: | 87 | # preseed debconf with our admin password |
256 | 74 | # server = source.split('/')[0] | 88 | dconf = Popen(['debconf-set-selections'], stdin=PIPE) |
257 | 75 | # if os.path.exists('keys/%s' % server): | 89 | dconf.stdin.write("%s %s/root_password password %s\n" % (package, package, root_pass)) |
258 | 76 | # check_call(['apt-key','add','keys/%s' % server]) | 90 | dconf.stdin.write("%s %s/root_password_again password %s\n" % (package, package, root_pass)) |
259 | 77 | # else: | 91 | dconf.communicate() |
260 | 78 | # check_call(['juju-log','-l','ERROR', | 92 | dconf.wait() |
261 | 79 | # 'No key for %s' % (server)]) | 93 | |
262 | 80 | # sys.exit(1) | 94 | # assumption of mariadb packages being delivered from code.mariadb |
263 | 81 | # check_call(['add-apt-repository','-y','deb http://%s %s main' % (source, series)]) | 95 | if not accepted and "code.mariadb" in source: |
264 | 82 | # check_call(['apt-get','update']) | 96 | log('EULA not accepted - doing nothing', 'WARNING') |
265 | 83 | # | 97 | host.service_stop('mysql') |
266 | 84 | #with open('/var/lib/mysql/mysql.passwd','r') as rpw: | 98 | else: |
267 | 85 | # root_pass = rpw.read() | 99 | fetch.add_source(source, config['key']) |
268 | 86 | # | 100 | fetch.apt_update() |
269 | 87 | #dconf = Popen(['debconf-set-selections'], stdin=PIPE) | 101 | |
270 | 88 | #dconf.stdin.write("%s %s/root_password password %s\n" % (package, package, root_pass)) | 102 | packages = ['mariadb-server', 'mariadb-client'] |
271 | 89 | #dconf.stdin.write("%s %s/root_password_again password %s\n" % (package, package, root_pass)) | 103 | fetch.apt_install(packages) |
237 | 90 | #dconf.stdin.write("%s-5.5 mysql-server/root_password password %s\n" % (package, root_pass)) | ||
238 | 91 | #dconf.stdin.write("%s-5.5 mysql-server/root_password_again password %s\n" % (package, root_pass)) | ||
239 | 92 | #dconf.communicate() | ||
240 | 93 | #dconf.wait() | ||
241 | 94 | # | ||
242 | 95 | #if len(remove_pkgs): | ||
243 | 96 | # check_call(['apt-get','-y','remove'] + remove_pkgs) | ||
244 | 97 | #check_call(['apt-get','-y','install','-qq',package]) | ||
272 | 98 | 104 | ||
273 | 99 | # smart-calc stuff in the configs | 105 | # smart-calc stuff in the configs |
274 | 100 | dataset_bytes = human_to_bytes(configs['dataset-size']) | 106 | dataset_bytes = human_to_bytes(configs['dataset-size']) |
275 | 101 | 107 | ||
277 | 102 | check_call(['juju-log','-l','INFO','dataset size in bytes: %d' % dataset_bytes]) | 108 | log('dataset size in bytes: %d' % dataset_bytes) |
278 | 103 | 109 | ||
280 | 104 | if configs['query-cache-size'] == -1 and configs['query-cache-type'] in ['ON','DEMAND']: | 110 | if configs['query-cache-size'] == -1 and configs['query-cache-type'] in ['ON', 'DEMAND']: |
281 | 105 | qcache_bytes = (dataset_bytes * 0.20) | 111 | qcache_bytes = (dataset_bytes * 0.20) |
282 | 106 | qcache_bytes = int(qcache_bytes - (qcache_bytes % PAGE_SIZE)) | 112 | qcache_bytes = int(qcache_bytes - (qcache_bytes % PAGE_SIZE)) |
283 | 107 | configs['query-cache-size'] = qcache_bytes | 113 | configs['query-cache-size'] = qcache_bytes |
284 | @@ -109,20 +115,20 @@ | |||
285 | 109 | 115 | ||
286 | 110 | # 5.5 allows the words, but not 5.1 | 116 | # 5.5 allows the words, but not 5.1 |
287 | 111 | if configs['query-cache-type'] == 'ON': | 117 | if configs['query-cache-type'] == 'ON': |
289 | 112 | configs['query-cache-type']=1 | 118 | configs['query-cache-type'] = 1 |
290 | 113 | elif configs['query-cache-type'] == 'DEMAND': | 119 | elif configs['query-cache-type'] == 'DEMAND': |
292 | 114 | configs['query-cache-type']=2 | 120 | configs['query-cache-type'] = 2 |
293 | 115 | else: | 121 | else: |
295 | 116 | configs['query-cache-type']=0 | 122 | configs['query-cache-type'] = 0 |
296 | 117 | 123 | ||
298 | 118 | preferred_engines=configs['preferred-storage-engine'].split(',') | 124 | preferred_engines = configs['preferred-storage-engine'].split(',') |
299 | 119 | chunk_size = int(dataset_bytes / len(preferred_engines)) | 125 | chunk_size = int(dataset_bytes / len(preferred_engines)) |
302 | 120 | configs['innodb-flush-log-at-trx-commit']=1 | 126 | configs['innodb-flush-log-at-trx-commit'] = 1 |
303 | 121 | configs['sync-binlog']=1 | 127 | configs['sync-binlog'] = 1 |
304 | 122 | if 'InnoDB' in preferred_engines: | 128 | if 'InnoDB' in preferred_engines: |
305 | 123 | configs['innodb-buffer-pool-size'] = chunk_size | 129 | configs['innodb-buffer-pool-size'] = chunk_size |
306 | 124 | if configs['tuning-level'] == 'fast': | 130 | if configs['tuning-level'] == 'fast': |
308 | 125 | configs['innodb-flush-log-at-trx-commit']=2 | 131 | configs['innodb-flush-log-at-trx-commit'] = 2 |
309 | 126 | else: | 132 | else: |
310 | 127 | configs['innodb-buffer-pool-size'] = 0 | 133 | configs['innodb-buffer-pool-size'] = 0 |
311 | 128 | 134 | ||
312 | @@ -135,14 +141,14 @@ | |||
313 | 135 | configs['key-buffer'] = human_to_bytes('8M') | 141 | configs['key-buffer'] = human_to_bytes('8M') |
314 | 136 | 142 | ||
315 | 137 | if configs['tuning-level'] == 'fast': | 143 | if configs['tuning-level'] == 'fast': |
317 | 138 | configs['sync-binlog']=0 | 144 | configs['sync-binlog'] = 0 |
318 | 139 | 145 | ||
319 | 140 | if configs['max-connections'] == -1: | 146 | if configs['max-connections'] == -1: |
320 | 141 | configs['max-connections'] = '# max_connections = ?' | 147 | configs['max-connections'] = '# max_connections = ?' |
321 | 142 | else: | 148 | else: |
322 | 143 | configs['max-connections'] = 'max_connections = %s' % configs['max-connections'] | 149 | configs['max-connections'] = 'max_connections = %s' % configs['max-connections'] |
323 | 144 | 150 | ||
325 | 145 | template=""" | 151 | template = """ |
326 | 146 | ###################################### | 152 | ###################################### |
327 | 147 | # | 153 | # |
328 | 148 | # | 154 | # |
329 | @@ -160,7 +166,7 @@ | |||
330 | 160 | # You can copy this to one of: | 166 | # You can copy this to one of: |
331 | 161 | # - "/etc/mysql/my.cnf" to set global options, | 167 | # - "/etc/mysql/my.cnf" to set global options, |
332 | 162 | # - "~/.my.cnf" to set user-specific options. | 168 | # - "~/.my.cnf" to set user-specific options. |
334 | 163 | # | 169 | # |
335 | 164 | # One can use all long options that the program supports. | 170 | # One can use all long options that the program supports. |
336 | 165 | # Run program with --help to get a list of available options and with | 171 | # Run program with --help to get a list of available options and with |
337 | 166 | # --print-defaults to see which it would actually understand and use. | 172 | # --print-defaults to see which it would actually understand and use. |
338 | @@ -299,38 +305,38 @@ | |||
339 | 299 | binlog_template = """ | 305 | binlog_template = """ |
340 | 300 | [mysqld] | 306 | [mysqld] |
341 | 301 | server_id = %s | 307 | server_id = %s |
343 | 302 | log_bin = /usr/local/mysql/data/mysql-bin.log | 308 | log_bin = /var/log/mysql/mysql-bin.log |
344 | 303 | binlog_format = %s | 309 | binlog_format = %s |
345 | 304 | """ | 310 | """ |
346 | 305 | 311 | ||
347 | 306 | binlog_cnf = binlog_template % (unit_id, | 312 | binlog_cnf = binlog_template % (unit_id, |
349 | 307 | configs.get('binlog-format','MIXED')) | 313 | configs.get('binlog-format', 'MIXED')) |
350 | 308 | 314 | ||
352 | 309 | mycnf=template % configs | 315 | mycnf = template % configs |
353 | 310 | 316 | ||
354 | 311 | targets = {'/etc/my.cnf.d/binlog.cnf': binlog_cnf, | 317 | targets = {'/etc/my.cnf.d/binlog.cnf': binlog_cnf, |
355 | 312 | '/etc/my.cnf': mycnf, | 318 | '/etc/my.cnf': mycnf, |
356 | 313 | } | 319 | } |
357 | 314 | 320 | ||
358 | 315 | need_restart = False | 321 | need_restart = False |
361 | 316 | for target,content in targets.iteritems(): | 322 | for target, content in targets.iteritems(): |
362 | 317 | tdir = os.path.dirname(target) | 323 | tdir = os.path.dirname(target) |
363 | 318 | if len(content) == 0 and os.path.exists(target): | 324 | if len(content) == 0 and os.path.exists(target): |
364 | 319 | os.unlink(target) | 325 | os.unlink(target) |
365 | 320 | need_restart = True | 326 | need_restart = True |
366 | 321 | continue | 327 | continue |
368 | 322 | with tempfile.NamedTemporaryFile(mode='w',dir=tdir,delete=False) as t: | 328 | with tempfile.NamedTemporaryFile(mode='w', dir=tdir, delete=False) as t: |
369 | 323 | t.write(content) | 329 | t.write(content) |
370 | 324 | t.flush() | 330 | t.flush() |
371 | 325 | tmd5 = hashlib.md5() | 331 | tmd5 = hashlib.md5() |
372 | 326 | tmd5.update(content) | 332 | tmd5.update(content) |
373 | 327 | if os.path.exists(target): | 333 | if os.path.exists(target): |
376 | 328 | with open(target,'r') as old: | 334 | with open(target, 'r') as old: |
377 | 329 | md5=hashlib.md5() | 335 | md5 = hashlib.md5() |
378 | 330 | md5.update(old.read()) | 336 | md5.update(old.read()) |
379 | 331 | oldhash = md5.digest() | 337 | oldhash = md5.digest() |
380 | 332 | if oldhash != tmd5.digest(): | 338 | if oldhash != tmd5.digest(): |
382 | 333 | os.rename(target,'%s.%s' % (target, md5.hexdigest())) | 339 | os.rename(target, '%s.%s' % (target, md5.hexdigest())) |
383 | 334 | need_restart = True | 340 | need_restart = True |
384 | 335 | else: | 341 | else: |
385 | 336 | need_restart = True | 342 | need_restart = True |
386 | @@ -340,5 +346,5 @@ | |||
387 | 340 | try: | 346 | try: |
388 | 341 | check_call(['service', 'mysql', 'restart']) | 347 | check_call(['service', 'mysql', 'restart']) |
389 | 342 | except CalledProcessError: | 348 | except CalledProcessError: |
391 | 343 | check_call(['juju-log', '-l', 'INFO', 'Restart failed, trying again']) | 349 | log('Restart failed, trying again', 'INFO') |
392 | 344 | check_call(['service', 'mysql', 'restart']) | 350 | check_call(['service', 'mysql', 'restart']) |
393 | 345 | 351 | ||
394 | === modified file 'hooks/install' | |||
395 | --- hooks/install 2014-11-12 18:30:06 +0000 | |||
396 | +++ hooks/install 2014-12-15 18:28:33 +0000 | |||
397 | @@ -1,177 +1,57 @@ | |||
575 | 1 | #!/bin/bash | 1 | #!/usr/bin/env python |
576 | 2 | #=============================================================================== | 2 | |
577 | 3 | # | 3 | import os |
578 | 4 | # FILE: install | 4 | import sys |
579 | 5 | # | 5 | import uuid |
580 | 6 | # DESCRIPTION: Install hook for MariaDB-bintar charm | 6 | |
581 | 7 | # | 7 | sys.path.insert(0, os.path.join(os.environ['CHARM_DIR'], 'lib')) |
582 | 8 | # AUTHOR: Daniel Bartholomew <dbart@mariadb.com> | 8 | |
583 | 9 | # ORGANIZATION: MariaDB | 9 | from charmhelpers import fetch |
584 | 10 | # CREATED: 09/18/2014 10:36 | 10 | from charmhelpers.core import hookenv |
585 | 11 | # REVISION: 003 | 11 | |
586 | 12 | #=============================================================================== | 12 | hooks = hookenv.Hooks() |
587 | 13 | 13 | log = hookenv.log | |
588 | 14 | # mbruzek: we recommend set -e so the script stops when an error is encountered. | 14 | config = hookenv.config() |
589 | 15 | set -ex | 15 | PASSFILE = "/var/lib/mysql/mysql.passwd" |
590 | 16 | 16 | ||
591 | 17 | #------------------------------------------------------------------------------- | 17 | ''' Do all preinstallation work here, as the app is installed in config-changed |
592 | 18 | # Variables | 18 | hook to handle repository updates, and code de-duplication ''' |
593 | 19 | #------------------------------------------------------------------------------- | 19 | @hooks.hook('install') |
594 | 20 | 20 | def install(): | |
595 | 21 | TREE="10.0" # MariaDB tree to use | 21 | fetch.apt_update() |
596 | 22 | REV="4416" # Revision in the tree to use | 22 | |
597 | 23 | VER="10.0.14" # MariaDB version number | 23 | packages = ['debconf-utils', |
598 | 24 | ARCH="$(uname -p)" # MariaDB CPU architechture | 24 | 'python-mysqldb', |
599 | 25 | LOCATION="http://bb01.mariadb.net/10.0" # Where the builds are | 25 | 'uuid', |
600 | 26 | PASSFILE="/var/lib/mysql/mysql.passwd" # Password file for mysql "root" user | 26 | 'pwgen', |
601 | 27 | 27 | 'dnsutils'] | |
602 | 28 | #------------------------------------------------------------------------------- | 28 | fetch.apt_install(packages) |
603 | 29 | # Main Script | 29 | admin_maria() |
604 | 30 | #------------------------------------------------------------------------------- | 30 | |
605 | 31 | 31 | def admin_maria(): | |
606 | 32 | # Install necessary packages | 32 | # If there is no existing ${PASSFILE}, use the UUID command to generate a |
607 | 33 | apt-get update -qq | 33 | # new MariaDB root user password and store it in the ${PASSFILE} |
608 | 34 | apt-get -y install uuid pwgen dnsutils libaio1 python-dev python-pip libssl-dev | 34 | varpath = os.path.join(os.path.sep, 'var', 'lib', 'mysql') |
609 | 35 | 35 | if not os.path.exists(PASSFILE): | |
610 | 36 | # Install MariaDB under /usr/local/ | 36 | try: |
611 | 37 | cd /usr/local | 37 | os.makedirs(varpath) |
612 | 38 | if [ ! -d "bintar_${TREE}_rev${REV}" ]; then | 38 | with open(PASSFILE, 'a'): |
613 | 39 | mkdir bintar_${TREE}_rev${REV} | 39 | os.utime(PASSFILE, None) |
614 | 40 | fi | 40 | os.chmod(PASSFILE, 0600) |
615 | 41 | 41 | except: | |
616 | 42 | cd bintar_${TREE}_rev${REV} | 42 | pass |
617 | 43 | # If the file exists in the charm directory | 43 | # Touch the passfile |
618 | 44 | if [ -f ${CHARM_DIR}/files/mariadb-${VER}-linux-${ARCH}.tar.gz ]; then | 44 | |
619 | 45 | # if the file also exists in the current directory | 45 | with open(PASSFILE, 'a') as fd: |
620 | 46 | if [ -f "mariadb-${VER}-linux-${ARCH}.tar.gz" ]; then | 46 | fd.seek(0, os.SEEK_END) |
621 | 47 | echo "File is already in place." | 47 | if fd.tell() == 0: |
622 | 48 | else | 48 | fd.seek(0) |
623 | 49 | # Copy the file from the charm directory. | 49 | fd.write(str(uuid.uuid4())) |
624 | 50 | cp -v ${CHARM_DIR}/files/mariadb-${VER}-linux-${ARCH}.tar.gz . | 50 | etc_path = os.path.join(os.path.sep, 'etc', 'my.cnf.d') |
625 | 51 | fi | 51 | if not os.path.exists(etc_path): |
626 | 52 | else | 52 | os.makedirs(os.path.join(os.path.sep, 'etc', 'my.cnf.d')) |
627 | 53 | # Download the bintar using -nv to avoid printing progress to the log files. | 53 | |
628 | 54 | wget -Nnv ${LOCATION}/bintar_${TREE}_rev${REV}/mariadb-${VER}-linux-${ARCH}.tar.gz | 54 | |
629 | 55 | wget -Nnv ${LOCATION}/bintar_${TREE}_rev${REV}/mariadb-${VER}-linux-${ARCH}.tar.gz.sha1sum | 55 | if __name__ == "__main__": |
630 | 56 | # check the sha1sum to make sure the file we downloaded is good | 56 | # execute a hook based on the name the program is called by |
631 | 57 | if sha1sum -c --quiet mariadb-${VER}-linux-${ARCH}.tar.gz.sha1sum;then | 57 | hooks.execute(sys.argv) |
455 | 58 | echo "file is good" | ||
456 | 59 | else | ||
457 | 60 | echo "file is corrupt, replace" | ||
458 | 61 | exit 1 | ||
459 | 62 | fi | ||
460 | 63 | fi | ||
461 | 64 | |||
462 | 65 | # Expand the bintar to /usr/local/bintar_${TREE}_rev${REV}/ | ||
463 | 66 | tar zxf mariadb-${VER}-linux-${ARCH}.tar.gz | ||
464 | 67 | |||
465 | 68 | cd /usr/local | ||
466 | 69 | |||
467 | 70 | # If the mysql symlink already exists, remove it so we know we're pointing at | ||
468 | 71 | # the version we just untarred | ||
469 | 72 | if [ -e "/usr/local/mysql" ]; then | ||
470 | 73 | rm /usr/local/mysql | ||
471 | 74 | fi | ||
472 | 75 | |||
473 | 76 | # Create a symlink to the real MariaDB directory. | ||
474 | 77 | # The symlink is named "mysql" for compatibility. | ||
475 | 78 | ln -s bintar_${TREE}_rev${REV}/mariadb-${VER}-linux-${ARCH} mysql | ||
476 | 79 | |||
477 | 80 | # Check if the lib dir has been added to /etc/ld.so.conf and if not, add it, | ||
478 | 81 | # then run ldconfig to apply the change | ||
479 | 82 | if grep -q -e "/usr/local/mysql/lib" /etc/ld.so.conf; then | ||
480 | 83 | echo "ld.so.conf entry already exists" | ||
481 | 84 | else | ||
482 | 85 | echo "/usr/local/mysql/lib" >> /etc/ld.so.conf | ||
483 | 86 | fi | ||
484 | 87 | ldconfig | ||
485 | 88 | |||
486 | 89 | cd /usr/local/mysql | ||
487 | 90 | |||
488 | 91 | # Check if the "mysql" group has already been created. If not, create it. | ||
489 | 92 | if grep -q -e "^mysql" /etc/group; then | ||
490 | 93 | echo "Group mysql already created." | ||
491 | 94 | else | ||
492 | 95 | groupadd mysql | ||
493 | 96 | fi | ||
494 | 97 | |||
495 | 98 | # Check if the user has already been created. If not, create it. | ||
496 | 99 | if grep -q -e "^mysql" /etc/passwd; then | ||
497 | 100 | echo "User mysql already created." | ||
498 | 101 | else | ||
499 | 102 | useradd -r -g mysql mysql | ||
500 | 103 | fi | ||
501 | 104 | |||
502 | 105 | # Install the default mysql database and privilege tables. If they already | ||
503 | 106 | # exist, the script will not overwrite them, so it's always safe to run. | ||
504 | 107 | # It's also always safe to chown the directories. | ||
505 | 108 | ./scripts/mysql_install_db --user=mysql | ||
506 | 109 | chown -R root:root . | ||
507 | 110 | chown -R mysql data | ||
508 | 111 | |||
509 | 112 | # Add /usr/local/mysql/bin to the PATH | ||
510 | 113 | if grep -q -e '/usr/local/mysql/bin:$PATH' /etc/profile; then | ||
511 | 114 | echo "/etc/profile PATH entry already exists." | ||
512 | 115 | else | ||
513 | 116 | echo 'export PATH=/usr/local/mysql/bin:$PATH' >> /etc/profile | ||
514 | 117 | fi | ||
515 | 118 | |||
516 | 119 | # Add /usr/local/mysql/man to the MANPATH | ||
517 | 120 | if grep -q -e '/usr/local/mysql/man:$MANPATH' /etc/profile; then | ||
518 | 121 | echo "/etc/profile MANPATH entry already exists." | ||
519 | 122 | else | ||
520 | 123 | echo 'export MANPATH=/usr/local/mysql/man:$MANPATH' >> /etc/profile | ||
521 | 124 | fi | ||
522 | 125 | |||
523 | 126 | # Apply the above changes to PATH and MANPATH | ||
524 | 127 | source /etc/profile | ||
525 | 128 | |||
526 | 129 | # Add init script to /etc/init.d/, removing any existing version, if it exists | ||
527 | 130 | if [ -f "/etc/init.d/mysql" ]; then | ||
528 | 131 | rm /etc/init.d/mysql | ||
529 | 132 | fi | ||
530 | 133 | cp support-files/mysql.server /etc/init.d/mysql | ||
531 | 134 | chmod 755 /etc/init.d/mysql | ||
532 | 135 | update-rc.d mysql defaults | ||
533 | 136 | |||
534 | 137 | |||
535 | 138 | # Start MariaDB so we can set the MariaDB root user password | ||
536 | 139 | /etc/init.d/mysql start | ||
537 | 140 | |||
538 | 141 | # If there is no existing ${PASSFILE}, use the UUID command to generate a new | ||
539 | 142 | # MariaDB root user password and store it in the ${PASSFILE} | ||
540 | 143 | if ! [ -f ${PASSFILE} ] ; then | ||
541 | 144 | mkdir -p /var/lib/mysql | ||
542 | 145 | touch ${PASSFILE} | ||
543 | 146 | fi | ||
544 | 147 | chmod 0600 ${PASSFILE} | ||
545 | 148 | if ! [ -s ${PASSFILE} ] ; then | ||
546 | 149 | uuid > ${PASSFILE} | ||
547 | 150 | fi | ||
548 | 151 | |||
549 | 152 | # if the root password is not set, set it | ||
550 | 153 | if mysql -u root -e "quit";then | ||
551 | 154 | mysqladmin -u root password "$(cat ${PASSFILE})" | ||
552 | 155 | fi | ||
553 | 156 | |||
554 | 157 | # if the password in ${PASSFILE} doesn't work, we have a problem | ||
555 | 158 | if ! mysql -u root -p$(cat ${PASSFILE}) -e "quit";then | ||
556 | 159 | echo "+ The password in ${PASSFILE} doesn't work." | ||
557 | 160 | exit 1 | ||
558 | 161 | else | ||
559 | 162 | echo "+ Password tested, it works!" | ||
560 | 163 | fi | ||
561 | 164 | |||
562 | 165 | # Create /etc/my.cnf.d, if it doesn't exist | ||
563 | 166 | if [ ! -d "/etc/my.cnf.d" ]; then | ||
564 | 167 | mkdir -p /etc/my.cnf.d | ||
565 | 168 | fi | ||
566 | 169 | |||
567 | 170 | # Install python MySQLdb module | ||
568 | 171 | pip install MySQL-python | ||
569 | 172 | |||
570 | 173 | # As the last step of the install process, stop MariaDB (the start trigger | ||
571 | 174 | # handles starting MariaDB). | ||
572 | 175 | /etc/init.d/mysql stop | ||
573 | 176 | |||
574 | 177 | |||
632 | 178 | 58 | ||
633 | === added directory 'lib/charmhelpers' | |||
634 | === added file 'lib/charmhelpers/__init__.py' | |||
635 | === added directory 'lib/charmhelpers/core' | |||
636 | === added file 'lib/charmhelpers/core/__init__.py' | |||
637 | === added file 'lib/charmhelpers/core/fstab.py' | |||
638 | --- lib/charmhelpers/core/fstab.py 1970-01-01 00:00:00 +0000 | |||
639 | +++ lib/charmhelpers/core/fstab.py 2014-12-15 18:28:33 +0000 | |||
640 | @@ -0,0 +1,118 @@ | |||
641 | 1 | #!/usr/bin/env python | ||
642 | 2 | # -*- coding: utf-8 -*- | ||
643 | 3 | |||
644 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
645 | 5 | |||
646 | 6 | import io | ||
647 | 7 | import os | ||
648 | 8 | |||
649 | 9 | |||
650 | 10 | class Fstab(io.FileIO): | ||
651 | 11 | """This class extends file in order to implement a file reader/writer | ||
652 | 12 | for file `/etc/fstab` | ||
653 | 13 | """ | ||
654 | 14 | |||
655 | 15 | class Entry(object): | ||
656 | 16 | """Entry class represents a non-comment line on the `/etc/fstab` file | ||
657 | 17 | """ | ||
658 | 18 | def __init__(self, device, mountpoint, filesystem, | ||
659 | 19 | options, d=0, p=0): | ||
660 | 20 | self.device = device | ||
661 | 21 | self.mountpoint = mountpoint | ||
662 | 22 | self.filesystem = filesystem | ||
663 | 23 | |||
664 | 24 | if not options: | ||
665 | 25 | options = "defaults" | ||
666 | 26 | |||
667 | 27 | self.options = options | ||
668 | 28 | self.d = int(d) | ||
669 | 29 | self.p = int(p) | ||
670 | 30 | |||
671 | 31 | def __eq__(self, o): | ||
672 | 32 | return str(self) == str(o) | ||
673 | 33 | |||
674 | 34 | def __str__(self): | ||
675 | 35 | return "{} {} {} {} {} {}".format(self.device, | ||
676 | 36 | self.mountpoint, | ||
677 | 37 | self.filesystem, | ||
678 | 38 | self.options, | ||
679 | 39 | self.d, | ||
680 | 40 | self.p) | ||
681 | 41 | |||
682 | 42 | DEFAULT_PATH = os.path.join(os.path.sep, 'etc', 'fstab') | ||
683 | 43 | |||
684 | 44 | def __init__(self, path=None): | ||
685 | 45 | if path: | ||
686 | 46 | self._path = path | ||
687 | 47 | else: | ||
688 | 48 | self._path = self.DEFAULT_PATH | ||
689 | 49 | super(Fstab, self).__init__(self._path, 'rb+') | ||
690 | 50 | |||
691 | 51 | def _hydrate_entry(self, line): | ||
692 | 52 | # NOTE: use split with no arguments to split on any | ||
693 | 53 | # whitespace including tabs | ||
694 | 54 | return Fstab.Entry(*filter( | ||
695 | 55 | lambda x: x not in ('', None), | ||
696 | 56 | line.strip("\n").split())) | ||
697 | 57 | |||
698 | 58 | @property | ||
699 | 59 | def entries(self): | ||
700 | 60 | self.seek(0) | ||
701 | 61 | for line in self.readlines(): | ||
702 | 62 | line = line.decode('us-ascii') | ||
703 | 63 | try: | ||
704 | 64 | if line.strip() and not line.startswith("#"): | ||
705 | 65 | yield self._hydrate_entry(line) | ||
706 | 66 | except ValueError: | ||
707 | 67 | pass | ||
708 | 68 | |||
709 | 69 | def get_entry_by_attr(self, attr, value): | ||
710 | 70 | for entry in self.entries: | ||
711 | 71 | e_attr = getattr(entry, attr) | ||
712 | 72 | if e_attr == value: | ||
713 | 73 | return entry | ||
714 | 74 | return None | ||
715 | 75 | |||
716 | 76 | def add_entry(self, entry): | ||
717 | 77 | if self.get_entry_by_attr('device', entry.device): | ||
718 | 78 | return False | ||
719 | 79 | |||
720 | 80 | self.write((str(entry) + '\n').encode('us-ascii')) | ||
721 | 81 | self.truncate() | ||
722 | 82 | return entry | ||
723 | 83 | |||
724 | 84 | def remove_entry(self, entry): | ||
725 | 85 | self.seek(0) | ||
726 | 86 | |||
727 | 87 | lines = [l.decode('us-ascii') for l in self.readlines()] | ||
728 | 88 | |||
729 | 89 | found = False | ||
730 | 90 | for index, line in enumerate(lines): | ||
731 | 91 | if not line.startswith("#"): | ||
732 | 92 | if self._hydrate_entry(line) == entry: | ||
733 | 93 | found = True | ||
734 | 94 | break | ||
735 | 95 | |||
736 | 96 | if not found: | ||
737 | 97 | return False | ||
738 | 98 | |||
739 | 99 | lines.remove(line) | ||
740 | 100 | |||
741 | 101 | self.seek(0) | ||
742 | 102 | self.write(''.join(lines).encode('us-ascii')) | ||
743 | 103 | self.truncate() | ||
744 | 104 | return True | ||
745 | 105 | |||
746 | 106 | @classmethod | ||
747 | 107 | def remove_by_mountpoint(cls, mountpoint, path=None): | ||
748 | 108 | fstab = cls(path=path) | ||
749 | 109 | entry = fstab.get_entry_by_attr('mountpoint', mountpoint) | ||
750 | 110 | if entry: | ||
751 | 111 | return fstab.remove_entry(entry) | ||
752 | 112 | return False | ||
753 | 113 | |||
754 | 114 | @classmethod | ||
755 | 115 | def add(cls, device, mountpoint, filesystem, options=None, path=None): | ||
756 | 116 | return cls(path=path).add_entry(Fstab.Entry(device, | ||
757 | 117 | mountpoint, filesystem, | ||
758 | 118 | options=options)) | ||
759 | 0 | 119 | ||
760 | === added file 'lib/charmhelpers/core/hookenv.py' | |||
761 | --- lib/charmhelpers/core/hookenv.py 1970-01-01 00:00:00 +0000 | |||
762 | +++ lib/charmhelpers/core/hookenv.py 2014-12-15 18:28:33 +0000 | |||
763 | @@ -0,0 +1,540 @@ | |||
764 | 1 | "Interactions with the Juju environment" | ||
765 | 2 | # Copyright 2013 Canonical Ltd. | ||
766 | 3 | # | ||
767 | 4 | # Authors: | ||
768 | 5 | # Charm Helpers Developers <juju@lists.ubuntu.com> | ||
769 | 6 | |||
770 | 7 | import os | ||
771 | 8 | import json | ||
772 | 9 | import yaml | ||
773 | 10 | import subprocess | ||
774 | 11 | import sys | ||
775 | 12 | from subprocess import CalledProcessError | ||
776 | 13 | |||
777 | 14 | import six | ||
778 | 15 | if not six.PY3: | ||
779 | 16 | from UserDict import UserDict | ||
780 | 17 | else: | ||
781 | 18 | from collections import UserDict | ||
782 | 19 | |||
783 | 20 | CRITICAL = "CRITICAL" | ||
784 | 21 | ERROR = "ERROR" | ||
785 | 22 | WARNING = "WARNING" | ||
786 | 23 | INFO = "INFO" | ||
787 | 24 | DEBUG = "DEBUG" | ||
788 | 25 | MARKER = object() | ||
789 | 26 | |||
790 | 27 | cache = {} | ||
791 | 28 | |||
792 | 29 | |||
793 | 30 | def cached(func): | ||
794 | 31 | """Cache return values for multiple executions of func + args | ||
795 | 32 | |||
796 | 33 | For example:: | ||
797 | 34 | |||
798 | 35 | @cached | ||
799 | 36 | def unit_get(attribute): | ||
800 | 37 | pass | ||
801 | 38 | |||
802 | 39 | unit_get('test') | ||
803 | 40 | |||
804 | 41 | will cache the result of unit_get + 'test' for future calls. | ||
805 | 42 | """ | ||
806 | 43 | def wrapper(*args, **kwargs): | ||
807 | 44 | global cache | ||
808 | 45 | key = str((func, args, kwargs)) | ||
809 | 46 | try: | ||
810 | 47 | return cache[key] | ||
811 | 48 | except KeyError: | ||
812 | 49 | res = func(*args, **kwargs) | ||
813 | 50 | cache[key] = res | ||
814 | 51 | return res | ||
815 | 52 | return wrapper | ||
816 | 53 | |||
817 | 54 | |||
818 | 55 | def flush(key): | ||
819 | 56 | """Flushes any entries from function cache where the | ||
820 | 57 | key is found in the function+args """ | ||
821 | 58 | flush_list = [] | ||
822 | 59 | for item in cache: | ||
823 | 60 | if key in item: | ||
824 | 61 | flush_list.append(item) | ||
825 | 62 | for item in flush_list: | ||
826 | 63 | del cache[item] | ||
827 | 64 | |||
828 | 65 | |||
829 | 66 | def log(message, level=None): | ||
830 | 67 | """Write a message to the juju log""" | ||
831 | 68 | command = ['juju-log'] | ||
832 | 69 | if level: | ||
833 | 70 | command += ['-l', level] | ||
834 | 71 | command += [message] | ||
835 | 72 | subprocess.call(command) | ||
836 | 73 | |||
837 | 74 | |||
838 | 75 | class Serializable(UserDict): | ||
839 | 76 | """Wrapper, an object that can be serialized to yaml or json""" | ||
840 | 77 | |||
841 | 78 | def __init__(self, obj): | ||
842 | 79 | # wrap the object | ||
843 | 80 | UserDict.__init__(self) | ||
844 | 81 | self.data = obj | ||
845 | 82 | |||
846 | 83 | def __getattr__(self, attr): | ||
847 | 84 | # See if this object has attribute. | ||
848 | 85 | if attr in ("json", "yaml", "data"): | ||
849 | 86 | return self.__dict__[attr] | ||
850 | 87 | # Check for attribute in wrapped object. | ||
851 | 88 | got = getattr(self.data, attr, MARKER) | ||
852 | 89 | if got is not MARKER: | ||
853 | 90 | return got | ||
854 | 91 | # Proxy to the wrapped object via dict interface. | ||
855 | 92 | try: | ||
856 | 93 | return self.data[attr] | ||
857 | 94 | except KeyError: | ||
858 | 95 | raise AttributeError(attr) | ||
859 | 96 | |||
860 | 97 | def __getstate__(self): | ||
861 | 98 | # Pickle as a standard dictionary. | ||
862 | 99 | return self.data | ||
863 | 100 | |||
864 | 101 | def __setstate__(self, state): | ||
865 | 102 | # Unpickle into our wrapper. | ||
866 | 103 | self.data = state | ||
867 | 104 | |||
868 | 105 | def json(self): | ||
869 | 106 | """Serialize the object to json""" | ||
870 | 107 | return json.dumps(self.data) | ||
871 | 108 | |||
872 | 109 | def yaml(self): | ||
873 | 110 | """Serialize the object to yaml""" | ||
874 | 111 | return yaml.dump(self.data) | ||
875 | 112 | |||
876 | 113 | |||
877 | 114 | def execution_environment(): | ||
878 | 115 | """A convenient bundling of the current execution context""" | ||
879 | 116 | context = {} | ||
880 | 117 | context['conf'] = config() | ||
881 | 118 | if relation_id(): | ||
882 | 119 | context['reltype'] = relation_type() | ||
883 | 120 | context['relid'] = relation_id() | ||
884 | 121 | context['rel'] = relation_get() | ||
885 | 122 | context['unit'] = local_unit() | ||
886 | 123 | context['rels'] = relations() | ||
887 | 124 | context['env'] = os.environ | ||
888 | 125 | return context | ||
889 | 126 | |||
890 | 127 | |||
891 | 128 | def in_relation_hook(): | ||
892 | 129 | """Determine whether we're running in a relation hook""" | ||
893 | 130 | return 'JUJU_RELATION' in os.environ | ||
894 | 131 | |||
895 | 132 | |||
896 | 133 | def relation_type(): | ||
897 | 134 | """The scope for the current relation hook""" | ||
898 | 135 | return os.environ.get('JUJU_RELATION', None) | ||
899 | 136 | |||
900 | 137 | |||
901 | 138 | def relation_id(): | ||
902 | 139 | """The relation ID for the current relation hook""" | ||
903 | 140 | return os.environ.get('JUJU_RELATION_ID', None) | ||
904 | 141 | |||
905 | 142 | |||
906 | 143 | def local_unit(): | ||
907 | 144 | """Local unit ID""" | ||
908 | 145 | return os.environ['JUJU_UNIT_NAME'] | ||
909 | 146 | |||
910 | 147 | |||
911 | 148 | def remote_unit(): | ||
912 | 149 | """The remote unit for the current relation hook""" | ||
913 | 150 | return os.environ['JUJU_REMOTE_UNIT'] | ||
914 | 151 | |||
915 | 152 | |||
916 | 153 | def service_name(): | ||
917 | 154 | """The name service group this unit belongs to""" | ||
918 | 155 | return local_unit().split('/')[0] | ||
919 | 156 | |||
920 | 157 | |||
921 | 158 | def hook_name(): | ||
922 | 159 | """The name of the currently executing hook""" | ||
923 | 160 | return os.path.basename(sys.argv[0]) | ||
924 | 161 | |||
925 | 162 | |||
926 | 163 | class Config(dict): | ||
927 | 164 | """A dictionary representation of the charm's config.yaml, with some | ||
928 | 165 | extra features: | ||
929 | 166 | |||
930 | 167 | - See which values in the dictionary have changed since the previous hook. | ||
931 | 168 | - For values that have changed, see what the previous value was. | ||
932 | 169 | - Store arbitrary data for use in a later hook. | ||
933 | 170 | |||
934 | 171 | NOTE: Do not instantiate this object directly - instead call | ||
935 | 172 | ``hookenv.config()``, which will return an instance of :class:`Config`. | ||
936 | 173 | |||
937 | 174 | Example usage:: | ||
938 | 175 | |||
939 | 176 | >>> # inside a hook | ||
940 | 177 | >>> from charmhelpers.core import hookenv | ||
941 | 178 | >>> config = hookenv.config() | ||
942 | 179 | >>> config['foo'] | ||
943 | 180 | 'bar' | ||
944 | 181 | >>> # store a new key/value for later use | ||
945 | 182 | >>> config['mykey'] = 'myval' | ||
946 | 183 | |||
947 | 184 | |||
948 | 185 | >>> # user runs `juju set mycharm foo=baz` | ||
949 | 186 | >>> # now we're inside subsequent config-changed hook | ||
950 | 187 | >>> config = hookenv.config() | ||
951 | 188 | >>> config['foo'] | ||
952 | 189 | 'baz' | ||
953 | 190 | >>> # test to see if this val has changed since last hook | ||
954 | 191 | >>> config.changed('foo') | ||
955 | 192 | True | ||
956 | 193 | >>> # what was the previous value? | ||
957 | 194 | >>> config.previous('foo') | ||
958 | 195 | 'bar' | ||
959 | 196 | >>> # keys/values that we add are preserved across hooks | ||
960 | 197 | >>> config['mykey'] | ||
961 | 198 | 'myval' | ||
962 | 199 | |||
963 | 200 | """ | ||
964 | 201 | CONFIG_FILE_NAME = '.juju-persistent-config' | ||
965 | 202 | |||
966 | 203 | def __init__(self, *args, **kw): | ||
967 | 204 | super(Config, self).__init__(*args, **kw) | ||
968 | 205 | self.implicit_save = True | ||
969 | 206 | self._prev_dict = None | ||
970 | 207 | self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME) | ||
971 | 208 | if os.path.exists(self.path): | ||
972 | 209 | self.load_previous() | ||
973 | 210 | |||
974 | 211 | def __getitem__(self, key): | ||
975 | 212 | """For regular dict lookups, check the current juju config first, | ||
976 | 213 | then the previous (saved) copy. This ensures that user-saved values | ||
977 | 214 | will be returned by a dict lookup. | ||
978 | 215 | |||
979 | 216 | """ | ||
980 | 217 | try: | ||
981 | 218 | return dict.__getitem__(self, key) | ||
982 | 219 | except KeyError: | ||
983 | 220 | return (self._prev_dict or {})[key] | ||
984 | 221 | |||
985 | 222 | def keys(self): | ||
986 | 223 | prev_keys = [] | ||
987 | 224 | if self._prev_dict is not None: | ||
988 | 225 | prev_keys = self._prev_dict.keys() | ||
989 | 226 | return list(set(prev_keys + list(dict.keys(self)))) | ||
990 | 227 | |||
991 | 228 | def load_previous(self, path=None): | ||
992 | 229 | """Load previous copy of config from disk. | ||
993 | 230 | |||
994 | 231 | In normal usage you don't need to call this method directly - it | ||
995 | 232 | is called automatically at object initialization. | ||
996 | 233 | |||
997 | 234 | :param path: | ||
998 | 235 | |||
999 | 236 | File path from which to load the previous config. If `None`, | ||
1000 | 237 | config is loaded from the default location. If `path` is | ||
1001 | 238 | specified, subsequent `save()` calls will write to the same | ||
1002 | 239 | path. | ||
1003 | 240 | |||
1004 | 241 | """ | ||
1005 | 242 | self.path = path or self.path | ||
1006 | 243 | with open(self.path) as f: | ||
1007 | 244 | self._prev_dict = json.load(f) | ||
1008 | 245 | |||
1009 | 246 | def changed(self, key): | ||
1010 | 247 | """Return True if the current value for this key is different from | ||
1011 | 248 | the previous value. | ||
1012 | 249 | |||
1013 | 250 | """ | ||
1014 | 251 | if self._prev_dict is None: | ||
1015 | 252 | return True | ||
1016 | 253 | return self.previous(key) != self.get(key) | ||
1017 | 254 | |||
1018 | 255 | def previous(self, key): | ||
1019 | 256 | """Return previous value for this key, or None if there | ||
1020 | 257 | is no previous value. | ||
1021 | 258 | |||
1022 | 259 | """ | ||
1023 | 260 | if self._prev_dict: | ||
1024 | 261 | return self._prev_dict.get(key) | ||
1025 | 262 | return None | ||
1026 | 263 | |||
1027 | 264 | def save(self): | ||
1028 | 265 | """Save this config to disk. | ||
1029 | 266 | |||
1030 | 267 | If the charm is using the :mod:`Services Framework <services.base>` | ||
1031 | 268 | or :meth:'@hook <Hooks.hook>' decorator, this | ||
1032 | 269 | is called automatically at the end of successful hook execution. | ||
1033 | 270 | Otherwise, it should be called directly by user code. | ||
1034 | 271 | |||
1035 | 272 | To disable automatic saves, set ``implicit_save=False`` on this | ||
1036 | 273 | instance. | ||
1037 | 274 | |||
1038 | 275 | """ | ||
1039 | 276 | if self._prev_dict: | ||
1040 | 277 | for k, v in six.iteritems(self._prev_dict): | ||
1041 | 278 | if k not in self: | ||
1042 | 279 | self[k] = v | ||
1043 | 280 | with open(self.path, 'w') as f: | ||
1044 | 281 | json.dump(self, f) | ||
1045 | 282 | |||
1046 | 283 | |||
1047 | 284 | @cached | ||
1048 | 285 | def config(scope=None): | ||
1049 | 286 | """Juju charm configuration""" | ||
1050 | 287 | config_cmd_line = ['config-get'] | ||
1051 | 288 | if scope is not None: | ||
1052 | 289 | config_cmd_line.append(scope) | ||
1053 | 290 | config_cmd_line.append('--format=json') | ||
1054 | 291 | try: | ||
1055 | 292 | config_data = json.loads( | ||
1056 | 293 | subprocess.check_output(config_cmd_line).decode('UTF-8')) | ||
1057 | 294 | if scope is not None: | ||
1058 | 295 | return config_data | ||
1059 | 296 | return Config(config_data) | ||
1060 | 297 | except ValueError: | ||
1061 | 298 | return None | ||
1062 | 299 | |||
1063 | 300 | |||
1064 | 301 | @cached | ||
1065 | 302 | def relation_get(attribute=None, unit=None, rid=None): | ||
1066 | 303 | """Get relation information""" | ||
1067 | 304 | _args = ['relation-get', '--format=json'] | ||
1068 | 305 | if rid: | ||
1069 | 306 | _args.append('-r') | ||
1070 | 307 | _args.append(rid) | ||
1071 | 308 | _args.append(attribute or '-') | ||
1072 | 309 | if unit: | ||
1073 | 310 | _args.append(unit) | ||
1074 | 311 | try: | ||
1075 | 312 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1076 | 313 | except ValueError: | ||
1077 | 314 | return None | ||
1078 | 315 | except CalledProcessError as e: | ||
1079 | 316 | if e.returncode == 2: | ||
1080 | 317 | return None | ||
1081 | 318 | raise | ||
1082 | 319 | |||
1083 | 320 | |||
1084 | 321 | def relation_set(relation_id=None, relation_settings=None, **kwargs): | ||
1085 | 322 | """Set relation information for the current unit""" | ||
1086 | 323 | relation_settings = relation_settings if relation_settings else {} | ||
1087 | 324 | relation_cmd_line = ['relation-set'] | ||
1088 | 325 | if relation_id is not None: | ||
1089 | 326 | relation_cmd_line.extend(('-r', relation_id)) | ||
1090 | 327 | for k, v in (list(relation_settings.items()) + list(kwargs.items())): | ||
1091 | 328 | if v is None: | ||
1092 | 329 | relation_cmd_line.append('{}='.format(k)) | ||
1093 | 330 | else: | ||
1094 | 331 | relation_cmd_line.append('{}={}'.format(k, v)) | ||
1095 | 332 | subprocess.check_call(relation_cmd_line) | ||
1096 | 333 | # Flush cache of any relation-gets for local unit | ||
1097 | 334 | flush(local_unit()) | ||
1098 | 335 | |||
1099 | 336 | |||
1100 | 337 | @cached | ||
1101 | 338 | def relation_ids(reltype=None): | ||
1102 | 339 | """A list of relation_ids""" | ||
1103 | 340 | reltype = reltype or relation_type() | ||
1104 | 341 | relid_cmd_line = ['relation-ids', '--format=json'] | ||
1105 | 342 | if reltype is not None: | ||
1106 | 343 | relid_cmd_line.append(reltype) | ||
1107 | 344 | return json.loads( | ||
1108 | 345 | subprocess.check_output(relid_cmd_line).decode('UTF-8')) or [] | ||
1109 | 346 | return [] | ||
1110 | 347 | |||
1111 | 348 | |||
1112 | 349 | @cached | ||
1113 | 350 | def related_units(relid=None): | ||
1114 | 351 | """A list of related units""" | ||
1115 | 352 | relid = relid or relation_id() | ||
1116 | 353 | units_cmd_line = ['relation-list', '--format=json'] | ||
1117 | 354 | if relid is not None: | ||
1118 | 355 | units_cmd_line.extend(('-r', relid)) | ||
1119 | 356 | return json.loads( | ||
1120 | 357 | subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | ||
1121 | 358 | |||
1122 | 359 | |||
1123 | 360 | @cached | ||
1124 | 361 | def relation_for_unit(unit=None, rid=None): | ||
1125 | 362 | """Get the json represenation of a unit's relation""" | ||
1126 | 363 | unit = unit or remote_unit() | ||
1127 | 364 | relation = relation_get(unit=unit, rid=rid) | ||
1128 | 365 | for key in relation: | ||
1129 | 366 | if key.endswith('-list'): | ||
1130 | 367 | relation[key] = relation[key].split() | ||
1131 | 368 | relation['__unit__'] = unit | ||
1132 | 369 | return relation | ||
1133 | 370 | |||
1134 | 371 | |||
1135 | 372 | @cached | ||
1136 | 373 | def relations_for_id(relid=None): | ||
1137 | 374 | """Get relations of a specific relation ID""" | ||
1138 | 375 | relation_data = [] | ||
1139 | 376 | relid = relid or relation_ids() | ||
1140 | 377 | for unit in related_units(relid): | ||
1141 | 378 | unit_data = relation_for_unit(unit, relid) | ||
1142 | 379 | unit_data['__relid__'] = relid | ||
1143 | 380 | relation_data.append(unit_data) | ||
1144 | 381 | return relation_data | ||
1145 | 382 | |||
1146 | 383 | |||
1147 | 384 | @cached | ||
1148 | 385 | def relations_of_type(reltype=None): | ||
1149 | 386 | """Get relations of a specific type""" | ||
1150 | 387 | relation_data = [] | ||
1151 | 388 | reltype = reltype or relation_type() | ||
1152 | 389 | for relid in relation_ids(reltype): | ||
1153 | 390 | for relation in relations_for_id(relid): | ||
1154 | 391 | relation['__relid__'] = relid | ||
1155 | 392 | relation_data.append(relation) | ||
1156 | 393 | return relation_data | ||
1157 | 394 | |||
1158 | 395 | |||
1159 | 396 | @cached | ||
1160 | 397 | def relation_types(): | ||
1161 | 398 | """Get a list of relation types supported by this charm""" | ||
1162 | 399 | charmdir = os.environ.get('CHARM_DIR', '') | ||
1163 | 400 | mdf = open(os.path.join(charmdir, 'metadata.yaml')) | ||
1164 | 401 | md = yaml.safe_load(mdf) | ||
1165 | 402 | rel_types = [] | ||
1166 | 403 | for key in ('provides', 'requires', 'peers'): | ||
1167 | 404 | section = md.get(key) | ||
1168 | 405 | if section: | ||
1169 | 406 | rel_types.extend(section.keys()) | ||
1170 | 407 | mdf.close() | ||
1171 | 408 | return rel_types | ||
1172 | 409 | |||
1173 | 410 | |||
1174 | 411 | @cached | ||
1175 | 412 | def relations(): | ||
1176 | 413 | """Get a nested dictionary of relation data for all related units""" | ||
1177 | 414 | rels = {} | ||
1178 | 415 | for reltype in relation_types(): | ||
1179 | 416 | relids = {} | ||
1180 | 417 | for relid in relation_ids(reltype): | ||
1181 | 418 | units = {local_unit(): relation_get(unit=local_unit(), rid=relid)} | ||
1182 | 419 | for unit in related_units(relid): | ||
1183 | 420 | reldata = relation_get(unit=unit, rid=relid) | ||
1184 | 421 | units[unit] = reldata | ||
1185 | 422 | relids[relid] = units | ||
1186 | 423 | rels[reltype] = relids | ||
1187 | 424 | return rels | ||
1188 | 425 | |||
1189 | 426 | |||
1190 | 427 | @cached | ||
1191 | 428 | def is_relation_made(relation, keys='private-address'): | ||
1192 | 429 | ''' | ||
1193 | 430 | Determine whether a relation is established by checking for | ||
1194 | 431 | presence of key(s). If a list of keys is provided, they | ||
1195 | 432 | must all be present for the relation to be identified as made | ||
1196 | 433 | ''' | ||
1197 | 434 | if isinstance(keys, str): | ||
1198 | 435 | keys = [keys] | ||
1199 | 436 | for r_id in relation_ids(relation): | ||
1200 | 437 | for unit in related_units(r_id): | ||
1201 | 438 | context = {} | ||
1202 | 439 | for k in keys: | ||
1203 | 440 | context[k] = relation_get(k, rid=r_id, | ||
1204 | 441 | unit=unit) | ||
1205 | 442 | if None not in context.values(): | ||
1206 | 443 | return True | ||
1207 | 444 | return False | ||
1208 | 445 | |||
1209 | 446 | |||
1210 | 447 | def open_port(port, protocol="TCP"): | ||
1211 | 448 | """Open a service network port""" | ||
1212 | 449 | _args = ['open-port'] | ||
1213 | 450 | _args.append('{}/{}'.format(port, protocol)) | ||
1214 | 451 | subprocess.check_call(_args) | ||
1215 | 452 | |||
1216 | 453 | |||
1217 | 454 | def close_port(port, protocol="TCP"): | ||
1218 | 455 | """Close a service network port""" | ||
1219 | 456 | _args = ['close-port'] | ||
1220 | 457 | _args.append('{}/{}'.format(port, protocol)) | ||
1221 | 458 | subprocess.check_call(_args) | ||
1222 | 459 | |||
1223 | 460 | |||
1224 | 461 | @cached | ||
1225 | 462 | def unit_get(attribute): | ||
1226 | 463 | """Get the unit ID for the remote unit""" | ||
1227 | 464 | _args = ['unit-get', '--format=json', attribute] | ||
1228 | 465 | try: | ||
1229 | 466 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) | ||
1230 | 467 | except ValueError: | ||
1231 | 468 | return None | ||
1232 | 469 | |||
1233 | 470 | |||
1234 | 471 | def unit_private_ip(): | ||
1235 | 472 | """Get this unit's private IP address""" | ||
1236 | 473 | return unit_get('private-address') | ||
1237 | 474 | |||
1238 | 475 | |||
1239 | 476 | class UnregisteredHookError(Exception): | ||
1240 | 477 | """Raised when an undefined hook is called""" | ||
1241 | 478 | pass | ||
1242 | 479 | |||
1243 | 480 | |||
1244 | 481 | class Hooks(object): | ||
1245 | 482 | """A convenient handler for hook functions. | ||
1246 | 483 | |||
1247 | 484 | Example:: | ||
1248 | 485 | |||
1249 | 486 | hooks = Hooks() | ||
1250 | 487 | |||
1251 | 488 | # register a hook, taking its name from the function name | ||
1252 | 489 | @hooks.hook() | ||
1253 | 490 | def install(): | ||
1254 | 491 | pass # your code here | ||
1255 | 492 | |||
1256 | 493 | # register a hook, providing a custom hook name | ||
1257 | 494 | @hooks.hook("config-changed") | ||
1258 | 495 | def config_changed(): | ||
1259 | 496 | pass # your code here | ||
1260 | 497 | |||
1261 | 498 | if __name__ == "__main__": | ||
1262 | 499 | # execute a hook based on the name the program is called by | ||
1263 | 500 | hooks.execute(sys.argv) | ||
1264 | 501 | """ | ||
1265 | 502 | |||
1266 | 503 | def __init__(self, config_save=True): | ||
1267 | 504 | super(Hooks, self).__init__() | ||
1268 | 505 | self._hooks = {} | ||
1269 | 506 | self._config_save = config_save | ||
1270 | 507 | |||
1271 | 508 | def register(self, name, function): | ||
1272 | 509 | """Register a hook""" | ||
1273 | 510 | self._hooks[name] = function | ||
1274 | 511 | |||
1275 | 512 | def execute(self, args): | ||
1276 | 513 | """Execute a registered hook based on args[0]""" | ||
1277 | 514 | hook_name = os.path.basename(args[0]) | ||
1278 | 515 | if hook_name in self._hooks: | ||
1279 | 516 | self._hooks[hook_name]() | ||
1280 | 517 | if self._config_save: | ||
1281 | 518 | cfg = config() | ||
1282 | 519 | if cfg.implicit_save: | ||
1283 | 520 | cfg.save() | ||
1284 | 521 | else: | ||
1285 | 522 | raise UnregisteredHookError(hook_name) | ||
1286 | 523 | |||
1287 | 524 | def hook(self, *hook_names): | ||
1288 | 525 | """Decorator, registering them as hooks""" | ||
1289 | 526 | def wrapper(decorated): | ||
1290 | 527 | for hook_name in hook_names: | ||
1291 | 528 | self.register(hook_name, decorated) | ||
1292 | 529 | else: | ||
1293 | 530 | self.register(decorated.__name__, decorated) | ||
1294 | 531 | if '_' in decorated.__name__: | ||
1295 | 532 | self.register( | ||
1296 | 533 | decorated.__name__.replace('_', '-'), decorated) | ||
1297 | 534 | return decorated | ||
1298 | 535 | return wrapper | ||
1299 | 536 | |||
1300 | 537 | |||
1301 | 538 | def charm_dir(): | ||
1302 | 539 | """Return the root directory of the current charm""" | ||
1303 | 540 | return os.environ.get('CHARM_DIR') | ||
1304 | 0 | 541 | ||
1305 | === added file 'lib/charmhelpers/core/host.py' | |||
1306 | --- lib/charmhelpers/core/host.py 1970-01-01 00:00:00 +0000 | |||
1307 | +++ lib/charmhelpers/core/host.py 2014-12-15 18:28:33 +0000 | |||
1308 | @@ -0,0 +1,396 @@ | |||
1309 | 1 | """Tools for working with the host system""" | ||
1310 | 2 | # Copyright 2012 Canonical Ltd. | ||
1311 | 3 | # | ||
1312 | 4 | # Authors: | ||
1313 | 5 | # Nick Moffitt <nick.moffitt@canonical.com> | ||
1314 | 6 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
1315 | 7 | |||
1316 | 8 | import os | ||
1317 | 9 | import re | ||
1318 | 10 | import pwd | ||
1319 | 11 | import grp | ||
1320 | 12 | import random | ||
1321 | 13 | import string | ||
1322 | 14 | import subprocess | ||
1323 | 15 | import hashlib | ||
1324 | 16 | from contextlib import contextmanager | ||
1325 | 17 | from collections import OrderedDict | ||
1326 | 18 | |||
1327 | 19 | import six | ||
1328 | 20 | |||
1329 | 21 | from .hookenv import log | ||
1330 | 22 | from .fstab import Fstab | ||
1331 | 23 | |||
1332 | 24 | |||
1333 | 25 | def service_start(service_name): | ||
1334 | 26 | """Start a system service""" | ||
1335 | 27 | return service('start', service_name) | ||
1336 | 28 | |||
1337 | 29 | |||
1338 | 30 | def service_stop(service_name): | ||
1339 | 31 | """Stop a system service""" | ||
1340 | 32 | return service('stop', service_name) | ||
1341 | 33 | |||
1342 | 34 | |||
1343 | 35 | def service_restart(service_name): | ||
1344 | 36 | """Restart a system service""" | ||
1345 | 37 | return service('restart', service_name) | ||
1346 | 38 | |||
1347 | 39 | |||
1348 | 40 | def service_reload(service_name, restart_on_failure=False): | ||
1349 | 41 | """Reload a system service, optionally falling back to restart if | ||
1350 | 42 | reload fails""" | ||
1351 | 43 | service_result = service('reload', service_name) | ||
1352 | 44 | if not service_result and restart_on_failure: | ||
1353 | 45 | service_result = service('restart', service_name) | ||
1354 | 46 | return service_result | ||
1355 | 47 | |||
1356 | 48 | |||
1357 | 49 | def service(action, service_name): | ||
1358 | 50 | """Control a system service""" | ||
1359 | 51 | cmd = ['service', service_name, action] | ||
1360 | 52 | return subprocess.call(cmd) == 0 | ||
1361 | 53 | |||
1362 | 54 | |||
1363 | 55 | def service_running(service): | ||
1364 | 56 | """Determine whether a system service is running""" | ||
1365 | 57 | try: | ||
1366 | 58 | output = subprocess.check_output( | ||
1367 | 59 | ['service', service, 'status'], | ||
1368 | 60 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1369 | 61 | except subprocess.CalledProcessError: | ||
1370 | 62 | return False | ||
1371 | 63 | else: | ||
1372 | 64 | if ("start/running" in output or "is running" in output): | ||
1373 | 65 | return True | ||
1374 | 66 | else: | ||
1375 | 67 | return False | ||
1376 | 68 | |||
1377 | 69 | |||
1378 | 70 | def service_available(service_name): | ||
1379 | 71 | """Determine whether a system service is available""" | ||
1380 | 72 | try: | ||
1381 | 73 | subprocess.check_output( | ||
1382 | 74 | ['service', service_name, 'status'], | ||
1383 | 75 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1384 | 76 | except subprocess.CalledProcessError as e: | ||
1385 | 77 | return 'unrecognized service' not in e.output | ||
1386 | 78 | else: | ||
1387 | 79 | return True | ||
1388 | 80 | |||
1389 | 81 | |||
1390 | 82 | def adduser(username, password=None, shell='/bin/bash', system_user=False): | ||
1391 | 83 | """Add a user to the system""" | ||
1392 | 84 | try: | ||
1393 | 85 | user_info = pwd.getpwnam(username) | ||
1394 | 86 | log('user {0} already exists!'.format(username)) | ||
1395 | 87 | except KeyError: | ||
1396 | 88 | log('creating user {0}'.format(username)) | ||
1397 | 89 | cmd = ['useradd'] | ||
1398 | 90 | if system_user or password is None: | ||
1399 | 91 | cmd.append('--system') | ||
1400 | 92 | else: | ||
1401 | 93 | cmd.extend([ | ||
1402 | 94 | '--create-home', | ||
1403 | 95 | '--shell', shell, | ||
1404 | 96 | '--password', password, | ||
1405 | 97 | ]) | ||
1406 | 98 | cmd.append(username) | ||
1407 | 99 | subprocess.check_call(cmd) | ||
1408 | 100 | user_info = pwd.getpwnam(username) | ||
1409 | 101 | return user_info | ||
1410 | 102 | |||
1411 | 103 | |||
1412 | 104 | def add_user_to_group(username, group): | ||
1413 | 105 | """Add a user to a group""" | ||
1414 | 106 | cmd = [ | ||
1415 | 107 | 'gpasswd', '-a', | ||
1416 | 108 | username, | ||
1417 | 109 | group | ||
1418 | 110 | ] | ||
1419 | 111 | log("Adding user {} to group {}".format(username, group)) | ||
1420 | 112 | subprocess.check_call(cmd) | ||
1421 | 113 | |||
1422 | 114 | |||
1423 | 115 | def rsync(from_path, to_path, flags='-r', options=None): | ||
1424 | 116 | """Replicate the contents of a path""" | ||
1425 | 117 | options = options or ['--delete', '--executability'] | ||
1426 | 118 | cmd = ['/usr/bin/rsync', flags] | ||
1427 | 119 | cmd.extend(options) | ||
1428 | 120 | cmd.append(from_path) | ||
1429 | 121 | cmd.append(to_path) | ||
1430 | 122 | log(" ".join(cmd)) | ||
1431 | 123 | return subprocess.check_output(cmd).decode('UTF-8').strip() | ||
1432 | 124 | |||
1433 | 125 | |||
1434 | 126 | def symlink(source, destination): | ||
1435 | 127 | """Create a symbolic link""" | ||
1436 | 128 | log("Symlinking {} as {}".format(source, destination)) | ||
1437 | 129 | cmd = [ | ||
1438 | 130 | 'ln', | ||
1439 | 131 | '-sf', | ||
1440 | 132 | source, | ||
1441 | 133 | destination, | ||
1442 | 134 | ] | ||
1443 | 135 | subprocess.check_call(cmd) | ||
1444 | 136 | |||
1445 | 137 | |||
1446 | 138 | def mkdir(path, owner='root', group='root', perms=0o555, force=False): | ||
1447 | 139 | """Create a directory""" | ||
1448 | 140 | log("Making dir {} {}:{} {:o}".format(path, owner, group, | ||
1449 | 141 | perms)) | ||
1450 | 142 | uid = pwd.getpwnam(owner).pw_uid | ||
1451 | 143 | gid = grp.getgrnam(group).gr_gid | ||
1452 | 144 | realpath = os.path.abspath(path) | ||
1453 | 145 | if os.path.exists(realpath): | ||
1454 | 146 | if force and not os.path.isdir(realpath): | ||
1455 | 147 | log("Removing non-directory file {} prior to mkdir()".format(path)) | ||
1456 | 148 | os.unlink(realpath) | ||
1457 | 149 | else: | ||
1458 | 150 | os.makedirs(realpath, perms) | ||
1459 | 151 | os.chown(realpath, uid, gid) | ||
1460 | 152 | |||
1461 | 153 | |||
1462 | 154 | def write_file(path, content, owner='root', group='root', perms=0o444): | ||
1463 | 155 | """Create or overwrite a file with the contents of a string""" | ||
1464 | 156 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | ||
1465 | 157 | uid = pwd.getpwnam(owner).pw_uid | ||
1466 | 158 | gid = grp.getgrnam(group).gr_gid | ||
1467 | 159 | with open(path, 'w') as target: | ||
1468 | 160 | os.fchown(target.fileno(), uid, gid) | ||
1469 | 161 | os.fchmod(target.fileno(), perms) | ||
1470 | 162 | target.write(content) | ||
1471 | 163 | |||
1472 | 164 | |||
1473 | 165 | def fstab_remove(mp): | ||
1474 | 166 | """Remove the given mountpoint entry from /etc/fstab | ||
1475 | 167 | """ | ||
1476 | 168 | return Fstab.remove_by_mountpoint(mp) | ||
1477 | 169 | |||
1478 | 170 | |||
1479 | 171 | def fstab_add(dev, mp, fs, options=None): | ||
1480 | 172 | """Adds the given device entry to the /etc/fstab file | ||
1481 | 173 | """ | ||
1482 | 174 | return Fstab.add(dev, mp, fs, options=options) | ||
1483 | 175 | |||
1484 | 176 | |||
1485 | 177 | def mount(device, mountpoint, options=None, persist=False, filesystem="ext3"): | ||
1486 | 178 | """Mount a filesystem at a particular mountpoint""" | ||
1487 | 179 | cmd_args = ['mount'] | ||
1488 | 180 | if options is not None: | ||
1489 | 181 | cmd_args.extend(['-o', options]) | ||
1490 | 182 | cmd_args.extend([device, mountpoint]) | ||
1491 | 183 | try: | ||
1492 | 184 | subprocess.check_output(cmd_args) | ||
1493 | 185 | except subprocess.CalledProcessError as e: | ||
1494 | 186 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | ||
1495 | 187 | return False | ||
1496 | 188 | |||
1497 | 189 | if persist: | ||
1498 | 190 | return fstab_add(device, mountpoint, filesystem, options=options) | ||
1499 | 191 | return True | ||
1500 | 192 | |||
1501 | 193 | |||
1502 | 194 | def umount(mountpoint, persist=False): | ||
1503 | 195 | """Unmount a filesystem""" | ||
1504 | 196 | cmd_args = ['umount', mountpoint] | ||
1505 | 197 | try: | ||
1506 | 198 | subprocess.check_output(cmd_args) | ||
1507 | 199 | except subprocess.CalledProcessError as e: | ||
1508 | 200 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | ||
1509 | 201 | return False | ||
1510 | 202 | |||
1511 | 203 | if persist: | ||
1512 | 204 | return fstab_remove(mountpoint) | ||
1513 | 205 | return True | ||
1514 | 206 | |||
1515 | 207 | |||
1516 | 208 | def mounts(): | ||
1517 | 209 | """Get a list of all mounted volumes as [[mountpoint,device],[...]]""" | ||
1518 | 210 | with open('/proc/mounts') as f: | ||
1519 | 211 | # [['/mount/point','/dev/path'],[...]] | ||
1520 | 212 | system_mounts = [m[1::-1] for m in [l.strip().split() | ||
1521 | 213 | for l in f.readlines()]] | ||
1522 | 214 | return system_mounts | ||
1523 | 215 | |||
1524 | 216 | |||
1525 | 217 | def file_hash(path, hash_type='md5'): | ||
1526 | 218 | """ | ||
1527 | 219 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
1528 | 220 | |||
1529 | 221 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
1530 | 222 | such as md5, sha1, sha256, sha512, etc. | ||
1531 | 223 | """ | ||
1532 | 224 | if os.path.exists(path): | ||
1533 | 225 | h = getattr(hashlib, hash_type)() | ||
1534 | 226 | with open(path, 'rb') as source: | ||
1535 | 227 | h.update(source.read()) | ||
1536 | 228 | return h.hexdigest() | ||
1537 | 229 | else: | ||
1538 | 230 | return None | ||
1539 | 231 | |||
1540 | 232 | |||
1541 | 233 | def check_hash(path, checksum, hash_type='md5'): | ||
1542 | 234 | """ | ||
1543 | 235 | Validate a file using a cryptographic checksum. | ||
1544 | 236 | |||
1545 | 237 | :param str checksum: Value of the checksum used to validate the file. | ||
1546 | 238 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
1547 | 239 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1548 | 240 | such as md5, sha1, sha256, sha512, etc. | ||
1549 | 241 | :raises ChecksumError: If the file fails the checksum | ||
1550 | 242 | |||
1551 | 243 | """ | ||
1552 | 244 | actual_checksum = file_hash(path, hash_type) | ||
1553 | 245 | if checksum != actual_checksum: | ||
1554 | 246 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
1555 | 247 | |||
1556 | 248 | |||
1557 | 249 | class ChecksumError(ValueError): | ||
1558 | 250 | pass | ||
1559 | 251 | |||
1560 | 252 | |||
1561 | 253 | def restart_on_change(restart_map, stopstart=False): | ||
1562 | 254 | """Restart services based on configuration files changing | ||
1563 | 255 | |||
1564 | 256 | This function is used a decorator, for example:: | ||
1565 | 257 | |||
1566 | 258 | @restart_on_change({ | ||
1567 | 259 | '/etc/ceph/ceph.conf': [ 'cinder-api', 'cinder-volume' ] | ||
1568 | 260 | }) | ||
1569 | 261 | def ceph_client_changed(): | ||
1570 | 262 | pass # your code here | ||
1571 | 263 | |||
1572 | 264 | In this example, the cinder-api and cinder-volume services | ||
1573 | 265 | would be restarted if /etc/ceph/ceph.conf is changed by the | ||
1574 | 266 | ceph_client_changed function. | ||
1575 | 267 | """ | ||
1576 | 268 | def wrap(f): | ||
1577 | 269 | def wrapped_f(*args): | ||
1578 | 270 | checksums = {} | ||
1579 | 271 | for path in restart_map: | ||
1580 | 272 | checksums[path] = file_hash(path) | ||
1581 | 273 | f(*args) | ||
1582 | 274 | restarts = [] | ||
1583 | 275 | for path in restart_map: | ||
1584 | 276 | if checksums[path] != file_hash(path): | ||
1585 | 277 | restarts += restart_map[path] | ||
1586 | 278 | services_list = list(OrderedDict.fromkeys(restarts)) | ||
1587 | 279 | if not stopstart: | ||
1588 | 280 | for service_name in services_list: | ||
1589 | 281 | service('restart', service_name) | ||
1590 | 282 | else: | ||
1591 | 283 | for action in ['stop', 'start']: | ||
1592 | 284 | for service_name in services_list: | ||
1593 | 285 | service(action, service_name) | ||
1594 | 286 | return wrapped_f | ||
1595 | 287 | return wrap | ||
1596 | 288 | |||
1597 | 289 | |||
1598 | 290 | def lsb_release(): | ||
1599 | 291 | """Return /etc/lsb-release in a dict""" | ||
1600 | 292 | d = {} | ||
1601 | 293 | with open('/etc/lsb-release', 'r') as lsb: | ||
1602 | 294 | for l in lsb: | ||
1603 | 295 | k, v = l.split('=') | ||
1604 | 296 | d[k.strip()] = v.strip() | ||
1605 | 297 | return d | ||
1606 | 298 | |||
1607 | 299 | |||
1608 | 300 | def pwgen(length=None): | ||
1609 | 301 | """Generate a random pasword.""" | ||
1610 | 302 | if length is None: | ||
1611 | 303 | length = random.choice(range(35, 45)) | ||
1612 | 304 | alphanumeric_chars = [ | ||
1613 | 305 | l for l in (string.ascii_letters + string.digits) | ||
1614 | 306 | if l not in 'l0QD1vAEIOUaeiou'] | ||
1615 | 307 | random_chars = [ | ||
1616 | 308 | random.choice(alphanumeric_chars) for _ in range(length)] | ||
1617 | 309 | return(''.join(random_chars)) | ||
1618 | 310 | |||
1619 | 311 | |||
1620 | 312 | def list_nics(nic_type): | ||
1621 | 313 | '''Return a list of nics of given type(s)''' | ||
1622 | 314 | if isinstance(nic_type, six.string_types): | ||
1623 | 315 | int_types = [nic_type] | ||
1624 | 316 | else: | ||
1625 | 317 | int_types = nic_type | ||
1626 | 318 | interfaces = [] | ||
1627 | 319 | for int_type in int_types: | ||
1628 | 320 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] | ||
1629 | 321 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1630 | 322 | ip_output = (line for line in ip_output if line) | ||
1631 | 323 | for line in ip_output: | ||
1632 | 324 | if line.split()[1].startswith(int_type): | ||
1633 | 325 | matched = re.search('.*: (bond[0-9]+\.[0-9]+)@.*', line) | ||
1634 | 326 | if matched: | ||
1635 | 327 | interface = matched.groups()[0] | ||
1636 | 328 | else: | ||
1637 | 329 | interface = line.split()[1].replace(":", "") | ||
1638 | 330 | interfaces.append(interface) | ||
1639 | 331 | |||
1640 | 332 | return interfaces | ||
1641 | 333 | |||
1642 | 334 | |||
1643 | 335 | def set_nic_mtu(nic, mtu): | ||
1644 | 336 | '''Set MTU on a network interface''' | ||
1645 | 337 | cmd = ['ip', 'link', 'set', nic, 'mtu', mtu] | ||
1646 | 338 | subprocess.check_call(cmd) | ||
1647 | 339 | |||
1648 | 340 | |||
1649 | 341 | def get_nic_mtu(nic): | ||
1650 | 342 | cmd = ['ip', 'addr', 'show', nic] | ||
1651 | 343 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') | ||
1652 | 344 | mtu = "" | ||
1653 | 345 | for line in ip_output: | ||
1654 | 346 | words = line.split() | ||
1655 | 347 | if 'mtu' in words: | ||
1656 | 348 | mtu = words[words.index("mtu") + 1] | ||
1657 | 349 | return mtu | ||
1658 | 350 | |||
1659 | 351 | |||
1660 | 352 | def get_nic_hwaddr(nic): | ||
1661 | 353 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] | ||
1662 | 354 | ip_output = subprocess.check_output(cmd).decode('UTF-8') | ||
1663 | 355 | hwaddr = "" | ||
1664 | 356 | words = ip_output.split() | ||
1665 | 357 | if 'link/ether' in words: | ||
1666 | 358 | hwaddr = words[words.index('link/ether') + 1] | ||
1667 | 359 | return hwaddr | ||
1668 | 360 | |||
1669 | 361 | |||
1670 | 362 | def cmp_pkgrevno(package, revno, pkgcache=None): | ||
1671 | 363 | '''Compare supplied revno with the revno of the installed package | ||
1672 | 364 | |||
1673 | 365 | * 1 => Installed revno is greater than supplied arg | ||
1674 | 366 | * 0 => Installed revno is the same as supplied arg | ||
1675 | 367 | * -1 => Installed revno is less than supplied arg | ||
1676 | 368 | |||
1677 | 369 | ''' | ||
1678 | 370 | import apt_pkg | ||
1679 | 371 | from charmhelpers.fetch import apt_cache | ||
1680 | 372 | if not pkgcache: | ||
1681 | 373 | pkgcache = apt_cache() | ||
1682 | 374 | pkg = pkgcache[package] | ||
1683 | 375 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | ||
1684 | 376 | |||
1685 | 377 | |||
1686 | 378 | @contextmanager | ||
1687 | 379 | def chdir(d): | ||
1688 | 380 | cur = os.getcwd() | ||
1689 | 381 | try: | ||
1690 | 382 | yield os.chdir(d) | ||
1691 | 383 | finally: | ||
1692 | 384 | os.chdir(cur) | ||
1693 | 385 | |||
1694 | 386 | |||
1695 | 387 | def chownr(path, owner, group): | ||
1696 | 388 | uid = pwd.getpwnam(owner).pw_uid | ||
1697 | 389 | gid = grp.getgrnam(group).gr_gid | ||
1698 | 390 | |||
1699 | 391 | for root, dirs, files in os.walk(path): | ||
1700 | 392 | for name in dirs + files: | ||
1701 | 393 | full = os.path.join(root, name) | ||
1702 | 394 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | ||
1703 | 395 | if not broken_symlink: | ||
1704 | 396 | os.chown(full, uid, gid) | ||
1705 | 0 | 397 | ||
1706 | === added directory 'lib/charmhelpers/core/services' | |||
1707 | === added file 'lib/charmhelpers/core/services/__init__.py' | |||
1708 | --- lib/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
1709 | +++ lib/charmhelpers/core/services/__init__.py 2014-12-15 18:28:33 +0000 | |||
1710 | @@ -0,0 +1,2 @@ | |||
1711 | 1 | from .base import * # NOQA | ||
1712 | 2 | from .helpers import * # NOQA | ||
1713 | 0 | 3 | ||
1714 | === added file 'lib/charmhelpers/core/services/base.py' | |||
1715 | --- lib/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
1716 | +++ lib/charmhelpers/core/services/base.py 2014-12-15 18:28:33 +0000 | |||
1717 | @@ -0,0 +1,313 @@ | |||
1718 | 1 | import os | ||
1719 | 2 | import re | ||
1720 | 3 | import json | ||
1721 | 4 | from collections import Iterable | ||
1722 | 5 | |||
1723 | 6 | from charmhelpers.core import host | ||
1724 | 7 | from charmhelpers.core import hookenv | ||
1725 | 8 | |||
1726 | 9 | |||
1727 | 10 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
1728 | 11 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
1729 | 12 | 'service_restart', 'service_stop'] | ||
1730 | 13 | |||
1731 | 14 | |||
1732 | 15 | class ServiceManager(object): | ||
1733 | 16 | def __init__(self, services=None): | ||
1734 | 17 | """ | ||
1735 | 18 | Register a list of services, given their definitions. | ||
1736 | 19 | |||
1737 | 20 | Service definitions are dicts in the following formats (all keys except | ||
1738 | 21 | 'service' are optional):: | ||
1739 | 22 | |||
1740 | 23 | { | ||
1741 | 24 | "service": <service name>, | ||
1742 | 25 | "required_data": <list of required data contexts>, | ||
1743 | 26 | "provided_data": <list of provided data contexts>, | ||
1744 | 27 | "data_ready": <one or more callbacks>, | ||
1745 | 28 | "data_lost": <one or more callbacks>, | ||
1746 | 29 | "start": <one or more callbacks>, | ||
1747 | 30 | "stop": <one or more callbacks>, | ||
1748 | 31 | "ports": <list of ports to manage>, | ||
1749 | 32 | } | ||
1750 | 33 | |||
1751 | 34 | The 'required_data' list should contain dicts of required data (or | ||
1752 | 35 | dependency managers that act like dicts and know how to collect the data). | ||
1753 | 36 | Only when all items in the 'required_data' list are populated are the list | ||
1754 | 37 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
1755 | 38 | information. | ||
1756 | 39 | |||
1757 | 40 | The 'provided_data' list should contain relation data providers, most likely | ||
1758 | 41 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
1759 | 42 | that will indicate a set of data to set on a given relation. | ||
1760 | 43 | |||
1761 | 44 | The 'data_ready' value should be either a single callback, or a list of | ||
1762 | 45 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
1763 | 46 | Each callback will be called with the service name as the only parameter. | ||
1764 | 47 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
1765 | 48 | are fired. | ||
1766 | 49 | |||
1767 | 50 | The 'data_lost' value should be either a single callback, or a list of | ||
1768 | 51 | callbacks, to be called when a 'required_data' item no longer passes | ||
1769 | 52 | `is_ready()`. Each callback will be called with the service name as the | ||
1770 | 53 | only parameter. After all of the 'data_lost' callbacks are called, | ||
1771 | 54 | the 'stop' callbacks are fired. | ||
1772 | 55 | |||
1773 | 56 | The 'start' value should be either a single callback, or a list of | ||
1774 | 57 | callbacks, to be called when starting the service, after the 'data_ready' | ||
1775 | 58 | callbacks are complete. Each callback will be called with the service | ||
1776 | 59 | name as the only parameter. This defaults to | ||
1777 | 60 | `[host.service_start, services.open_ports]`. | ||
1778 | 61 | |||
1779 | 62 | The 'stop' value should be either a single callback, or a list of | ||
1780 | 63 | callbacks, to be called when stopping the service. If the service is | ||
1781 | 64 | being stopped because it no longer has all of its 'required_data', this | ||
1782 | 65 | will be called after all of the 'data_lost' callbacks are complete. | ||
1783 | 66 | Each callback will be called with the service name as the only parameter. | ||
1784 | 67 | This defaults to `[services.close_ports, host.service_stop]`. | ||
1785 | 68 | |||
1786 | 69 | The 'ports' value should be a list of ports to manage. The default | ||
1787 | 70 | 'start' handler will open the ports after the service is started, | ||
1788 | 71 | and the default 'stop' handler will close the ports prior to stopping | ||
1789 | 72 | the service. | ||
1790 | 73 | |||
1791 | 74 | |||
1792 | 75 | Examples: | ||
1793 | 76 | |||
1794 | 77 | The following registers an Upstart service called bingod that depends on | ||
1795 | 78 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
1796 | 79 | restarting the service, and a Runit service called spadesd:: | ||
1797 | 80 | |||
1798 | 81 | manager = services.ServiceManager([ | ||
1799 | 82 | { | ||
1800 | 83 | 'service': 'bingod', | ||
1801 | 84 | 'ports': [80, 443], | ||
1802 | 85 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
1803 | 86 | 'data_ready': [ | ||
1804 | 87 | services.template(source='bingod.conf'), | ||
1805 | 88 | services.template(source='bingod.ini', | ||
1806 | 89 | target='/etc/bingod.ini', | ||
1807 | 90 | owner='bingo', perms=0400), | ||
1808 | 91 | ], | ||
1809 | 92 | }, | ||
1810 | 93 | { | ||
1811 | 94 | 'service': 'spadesd', | ||
1812 | 95 | 'data_ready': services.template(source='spadesd_run.j2', | ||
1813 | 96 | target='/etc/sv/spadesd/run', | ||
1814 | 97 | perms=0555), | ||
1815 | 98 | 'start': runit_start, | ||
1816 | 99 | 'stop': runit_stop, | ||
1817 | 100 | }, | ||
1818 | 101 | ]) | ||
1819 | 102 | manager.manage() | ||
1820 | 103 | """ | ||
1821 | 104 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
1822 | 105 | self._ready = None | ||
1823 | 106 | self.services = {} | ||
1824 | 107 | for service in services or []: | ||
1825 | 108 | service_name = service['service'] | ||
1826 | 109 | self.services[service_name] = service | ||
1827 | 110 | |||
1828 | 111 | def manage(self): | ||
1829 | 112 | """ | ||
1830 | 113 | Handle the current hook by doing The Right Thing with the registered services. | ||
1831 | 114 | """ | ||
1832 | 115 | hook_name = hookenv.hook_name() | ||
1833 | 116 | if hook_name == 'stop': | ||
1834 | 117 | self.stop_services() | ||
1835 | 118 | else: | ||
1836 | 119 | self.provide_data() | ||
1837 | 120 | self.reconfigure_services() | ||
1838 | 121 | cfg = hookenv.config() | ||
1839 | 122 | if cfg.implicit_save: | ||
1840 | 123 | cfg.save() | ||
1841 | 124 | |||
1842 | 125 | def provide_data(self): | ||
1843 | 126 | """ | ||
1844 | 127 | Set the relation data for each provider in the ``provided_data`` list. | ||
1845 | 128 | |||
1846 | 129 | A provider must have a `name` attribute, which indicates which relation | ||
1847 | 130 | to set data on, and a `provide_data()` method, which returns a dict of | ||
1848 | 131 | data to set. | ||
1849 | 132 | """ | ||
1850 | 133 | hook_name = hookenv.hook_name() | ||
1851 | 134 | for service in self.services.values(): | ||
1852 | 135 | for provider in service.get('provided_data', []): | ||
1853 | 136 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
1854 | 137 | data = provider.provide_data() | ||
1855 | 138 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
1856 | 139 | if _ready: | ||
1857 | 140 | hookenv.relation_set(None, data) | ||
1858 | 141 | |||
1859 | 142 | def reconfigure_services(self, *service_names): | ||
1860 | 143 | """ | ||
1861 | 144 | Update all files for one or more registered services, and, | ||
1862 | 145 | if ready, optionally restart them. | ||
1863 | 146 | |||
1864 | 147 | If no service names are given, reconfigures all registered services. | ||
1865 | 148 | """ | ||
1866 | 149 | for service_name in service_names or self.services.keys(): | ||
1867 | 150 | if self.is_ready(service_name): | ||
1868 | 151 | self.fire_event('data_ready', service_name) | ||
1869 | 152 | self.fire_event('start', service_name, default=[ | ||
1870 | 153 | service_restart, | ||
1871 | 154 | manage_ports]) | ||
1872 | 155 | self.save_ready(service_name) | ||
1873 | 156 | else: | ||
1874 | 157 | if self.was_ready(service_name): | ||
1875 | 158 | self.fire_event('data_lost', service_name) | ||
1876 | 159 | self.fire_event('stop', service_name, default=[ | ||
1877 | 160 | manage_ports, | ||
1878 | 161 | service_stop]) | ||
1879 | 162 | self.save_lost(service_name) | ||
1880 | 163 | |||
1881 | 164 | def stop_services(self, *service_names): | ||
1882 | 165 | """ | ||
1883 | 166 | Stop one or more registered services, by name. | ||
1884 | 167 | |||
1885 | 168 | If no service names are given, stops all registered services. | ||
1886 | 169 | """ | ||
1887 | 170 | for service_name in service_names or self.services.keys(): | ||
1888 | 171 | self.fire_event('stop', service_name, default=[ | ||
1889 | 172 | manage_ports, | ||
1890 | 173 | service_stop]) | ||
1891 | 174 | |||
1892 | 175 | def get_service(self, service_name): | ||
1893 | 176 | """ | ||
1894 | 177 | Given the name of a registered service, return its service definition. | ||
1895 | 178 | """ | ||
1896 | 179 | service = self.services.get(service_name) | ||
1897 | 180 | if not service: | ||
1898 | 181 | raise KeyError('Service not registered: %s' % service_name) | ||
1899 | 182 | return service | ||
1900 | 183 | |||
1901 | 184 | def fire_event(self, event_name, service_name, default=None): | ||
1902 | 185 | """ | ||
1903 | 186 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
1904 | 187 | """ | ||
1905 | 188 | service = self.get_service(service_name) | ||
1906 | 189 | callbacks = service.get(event_name, default) | ||
1907 | 190 | if not callbacks: | ||
1908 | 191 | return | ||
1909 | 192 | if not isinstance(callbacks, Iterable): | ||
1910 | 193 | callbacks = [callbacks] | ||
1911 | 194 | for callback in callbacks: | ||
1912 | 195 | if isinstance(callback, ManagerCallback): | ||
1913 | 196 | callback(self, service_name, event_name) | ||
1914 | 197 | else: | ||
1915 | 198 | callback(service_name) | ||
1916 | 199 | |||
1917 | 200 | def is_ready(self, service_name): | ||
1918 | 201 | """ | ||
1919 | 202 | Determine if a registered service is ready, by checking its 'required_data'. | ||
1920 | 203 | |||
1921 | 204 | A 'required_data' item can be any mapping type, and is considered ready | ||
1922 | 205 | if `bool(item)` evaluates as True. | ||
1923 | 206 | """ | ||
1924 | 207 | service = self.get_service(service_name) | ||
1925 | 208 | reqs = service.get('required_data', []) | ||
1926 | 209 | return all(bool(req) for req in reqs) | ||
1927 | 210 | |||
1928 | 211 | def _load_ready_file(self): | ||
1929 | 212 | if self._ready is not None: | ||
1930 | 213 | return | ||
1931 | 214 | if os.path.exists(self._ready_file): | ||
1932 | 215 | with open(self._ready_file) as fp: | ||
1933 | 216 | self._ready = set(json.load(fp)) | ||
1934 | 217 | else: | ||
1935 | 218 | self._ready = set() | ||
1936 | 219 | |||
1937 | 220 | def _save_ready_file(self): | ||
1938 | 221 | if self._ready is None: | ||
1939 | 222 | return | ||
1940 | 223 | with open(self._ready_file, 'w') as fp: | ||
1941 | 224 | json.dump(list(self._ready), fp) | ||
1942 | 225 | |||
1943 | 226 | def save_ready(self, service_name): | ||
1944 | 227 | """ | ||
1945 | 228 | Save an indicator that the given service is now data_ready. | ||
1946 | 229 | """ | ||
1947 | 230 | self._load_ready_file() | ||
1948 | 231 | self._ready.add(service_name) | ||
1949 | 232 | self._save_ready_file() | ||
1950 | 233 | |||
1951 | 234 | def save_lost(self, service_name): | ||
1952 | 235 | """ | ||
1953 | 236 | Save an indicator that the given service is no longer data_ready. | ||
1954 | 237 | """ | ||
1955 | 238 | self._load_ready_file() | ||
1956 | 239 | self._ready.discard(service_name) | ||
1957 | 240 | self._save_ready_file() | ||
1958 | 241 | |||
1959 | 242 | def was_ready(self, service_name): | ||
1960 | 243 | """ | ||
1961 | 244 | Determine if the given service was previously data_ready. | ||
1962 | 245 | """ | ||
1963 | 246 | self._load_ready_file() | ||
1964 | 247 | return service_name in self._ready | ||
1965 | 248 | |||
1966 | 249 | |||
1967 | 250 | class ManagerCallback(object): | ||
1968 | 251 | """ | ||
1969 | 252 | Special case of a callback that takes the `ServiceManager` instance | ||
1970 | 253 | in addition to the service name. | ||
1971 | 254 | |||
1972 | 255 | Subclasses should implement `__call__` which should accept three parameters: | ||
1973 | 256 | |||
1974 | 257 | * `manager` The `ServiceManager` instance | ||
1975 | 258 | * `service_name` The name of the service it's being triggered for | ||
1976 | 259 | * `event_name` The name of the event that this callback is handling | ||
1977 | 260 | """ | ||
1978 | 261 | def __call__(self, manager, service_name, event_name): | ||
1979 | 262 | raise NotImplementedError() | ||
1980 | 263 | |||
1981 | 264 | |||
1982 | 265 | class PortManagerCallback(ManagerCallback): | ||
1983 | 266 | """ | ||
1984 | 267 | Callback class that will open or close ports, for use as either | ||
1985 | 268 | a start or stop action. | ||
1986 | 269 | """ | ||
1987 | 270 | def __call__(self, manager, service_name, event_name): | ||
1988 | 271 | service = manager.get_service(service_name) | ||
1989 | 272 | new_ports = service.get('ports', []) | ||
1990 | 273 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
1991 | 274 | if os.path.exists(port_file): | ||
1992 | 275 | with open(port_file) as fp: | ||
1993 | 276 | old_ports = fp.read().split(',') | ||
1994 | 277 | for old_port in old_ports: | ||
1995 | 278 | if bool(old_port): | ||
1996 | 279 | old_port = int(old_port) | ||
1997 | 280 | if old_port not in new_ports: | ||
1998 | 281 | hookenv.close_port(old_port) | ||
1999 | 282 | with open(port_file, 'w') as fp: | ||
2000 | 283 | fp.write(','.join(str(port) for port in new_ports)) | ||
2001 | 284 | for port in new_ports: | ||
2002 | 285 | if event_name == 'start': | ||
2003 | 286 | hookenv.open_port(port) | ||
2004 | 287 | elif event_name == 'stop': | ||
2005 | 288 | hookenv.close_port(port) | ||
2006 | 289 | |||
2007 | 290 | |||
2008 | 291 | def service_stop(service_name): | ||
2009 | 292 | """ | ||
2010 | 293 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
2011 | 294 | messages in the logs. | ||
2012 | 295 | """ | ||
2013 | 296 | if host.service_running(service_name): | ||
2014 | 297 | host.service_stop(service_name) | ||
2015 | 298 | |||
2016 | 299 | |||
2017 | 300 | def service_restart(service_name): | ||
2018 | 301 | """ | ||
2019 | 302 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
2020 | 303 | messages in the logs. | ||
2021 | 304 | """ | ||
2022 | 305 | if host.service_available(service_name): | ||
2023 | 306 | if host.service_running(service_name): | ||
2024 | 307 | host.service_restart(service_name) | ||
2025 | 308 | else: | ||
2026 | 309 | host.service_start(service_name) | ||
2027 | 310 | |||
2028 | 311 | |||
2029 | 312 | # Convenience aliases | ||
2030 | 313 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
2031 | 0 | 314 | ||
2032 | === added file 'lib/charmhelpers/core/services/helpers.py' | |||
2033 | --- lib/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
2034 | +++ lib/charmhelpers/core/services/helpers.py 2014-12-15 18:28:33 +0000 | |||
2035 | @@ -0,0 +1,243 @@ | |||
2036 | 1 | import os | ||
2037 | 2 | import yaml | ||
2038 | 3 | from charmhelpers.core import hookenv | ||
2039 | 4 | from charmhelpers.core import templating | ||
2040 | 5 | |||
2041 | 6 | from charmhelpers.core.services.base import ManagerCallback | ||
2042 | 7 | |||
2043 | 8 | |||
2044 | 9 | __all__ = ['RelationContext', 'TemplateCallback', | ||
2045 | 10 | 'render_template', 'template'] | ||
2046 | 11 | |||
2047 | 12 | |||
2048 | 13 | class RelationContext(dict): | ||
2049 | 14 | """ | ||
2050 | 15 | Base class for a context generator that gets relation data from juju. | ||
2051 | 16 | |||
2052 | 17 | Subclasses must provide the attributes `name`, which is the name of the | ||
2053 | 18 | interface of interest, `interface`, which is the type of the interface of | ||
2054 | 19 | interest, and `required_keys`, which is the set of keys required for the | ||
2055 | 20 | relation to be considered complete. The data for all interfaces matching | ||
2056 | 21 | the `name` attribute that are complete will used to populate the dictionary | ||
2057 | 22 | values (see `get_data`, below). | ||
2058 | 23 | |||
2059 | 24 | The generated context will be namespaced under the relation :attr:`name`, | ||
2060 | 25 | to prevent potential naming conflicts. | ||
2061 | 26 | |||
2062 | 27 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2063 | 28 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2064 | 29 | """ | ||
2065 | 30 | name = None | ||
2066 | 31 | interface = None | ||
2067 | 32 | required_keys = [] | ||
2068 | 33 | |||
2069 | 34 | def __init__(self, name=None, additional_required_keys=None): | ||
2070 | 35 | if name is not None: | ||
2071 | 36 | self.name = name | ||
2072 | 37 | if additional_required_keys is not None: | ||
2073 | 38 | self.required_keys.extend(additional_required_keys) | ||
2074 | 39 | self.get_data() | ||
2075 | 40 | |||
2076 | 41 | def __bool__(self): | ||
2077 | 42 | """ | ||
2078 | 43 | Returns True if all of the required_keys are available. | ||
2079 | 44 | """ | ||
2080 | 45 | return self.is_ready() | ||
2081 | 46 | |||
2082 | 47 | __nonzero__ = __bool__ | ||
2083 | 48 | |||
2084 | 49 | def __repr__(self): | ||
2085 | 50 | return super(RelationContext, self).__repr__() | ||
2086 | 51 | |||
2087 | 52 | def is_ready(self): | ||
2088 | 53 | """ | ||
2089 | 54 | Returns True if all of the `required_keys` are available from any units. | ||
2090 | 55 | """ | ||
2091 | 56 | ready = len(self.get(self.name, [])) > 0 | ||
2092 | 57 | if not ready: | ||
2093 | 58 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
2094 | 59 | return ready | ||
2095 | 60 | |||
2096 | 61 | def _is_ready(self, unit_data): | ||
2097 | 62 | """ | ||
2098 | 63 | Helper method that tests a set of relation data and returns True if | ||
2099 | 64 | all of the `required_keys` are present. | ||
2100 | 65 | """ | ||
2101 | 66 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
2102 | 67 | |||
2103 | 68 | def get_data(self): | ||
2104 | 69 | """ | ||
2105 | 70 | Retrieve the relation data for each unit involved in a relation and, | ||
2106 | 71 | if complete, store it in a list under `self[self.name]`. This | ||
2107 | 72 | is automatically called when the RelationContext is instantiated. | ||
2108 | 73 | |||
2109 | 74 | The units are sorted lexographically first by the service ID, then by | ||
2110 | 75 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
2111 | 76 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
2112 | 77 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
2113 | 78 | set of data, the relation data for the units will be stored in the | ||
2114 | 79 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
2115 | 80 | |||
2116 | 81 | If you only care about a single unit on the relation, you can just | ||
2117 | 82 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
2118 | 83 | support multiple units on a relation, you should iterate over the list, | ||
2119 | 84 | like:: | ||
2120 | 85 | |||
2121 | 86 | {% for unit in interface -%} | ||
2122 | 87 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
2123 | 88 | {%- endfor %} | ||
2124 | 89 | |||
2125 | 90 | Note that since all sets of relation data from all related services and | ||
2126 | 91 | units are in a single list, if you need to know which service or unit a | ||
2127 | 92 | set of data came from, you'll need to extend this class to preserve | ||
2128 | 93 | that information. | ||
2129 | 94 | """ | ||
2130 | 95 | if not hookenv.relation_ids(self.name): | ||
2131 | 96 | return | ||
2132 | 97 | |||
2133 | 98 | ns = self.setdefault(self.name, []) | ||
2134 | 99 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
2135 | 100 | for unit in sorted(hookenv.related_units(rid)): | ||
2136 | 101 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
2137 | 102 | if self._is_ready(reldata): | ||
2138 | 103 | ns.append(reldata) | ||
2139 | 104 | |||
2140 | 105 | def provide_data(self): | ||
2141 | 106 | """ | ||
2142 | 107 | Return data to be relation_set for this interface. | ||
2143 | 108 | """ | ||
2144 | 109 | return {} | ||
2145 | 110 | |||
2146 | 111 | |||
2147 | 112 | class MysqlRelation(RelationContext): | ||
2148 | 113 | """ | ||
2149 | 114 | Relation context for the `mysql` interface. | ||
2150 | 115 | |||
2151 | 116 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2152 | 117 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2153 | 118 | """ | ||
2154 | 119 | name = 'db' | ||
2155 | 120 | interface = 'mysql' | ||
2156 | 121 | required_keys = ['host', 'user', 'password', 'database'] | ||
2157 | 122 | |||
2158 | 123 | |||
2159 | 124 | class HttpRelation(RelationContext): | ||
2160 | 125 | """ | ||
2161 | 126 | Relation context for the `http` interface. | ||
2162 | 127 | |||
2163 | 128 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2164 | 129 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2165 | 130 | """ | ||
2166 | 131 | name = 'website' | ||
2167 | 132 | interface = 'http' | ||
2168 | 133 | required_keys = ['host', 'port'] | ||
2169 | 134 | |||
2170 | 135 | def provide_data(self): | ||
2171 | 136 | return { | ||
2172 | 137 | 'host': hookenv.unit_get('private-address'), | ||
2173 | 138 | 'port': 80, | ||
2174 | 139 | } | ||
2175 | 140 | |||
2176 | 141 | |||
2177 | 142 | class RequiredConfig(dict): | ||
2178 | 143 | """ | ||
2179 | 144 | Data context that loads config options with one or more mandatory options. | ||
2180 | 145 | |||
2181 | 146 | Once the required options have been changed from their default values, all | ||
2182 | 147 | config options will be available, namespaced under `config` to prevent | ||
2183 | 148 | potential naming conflicts (for example, between a config option and a | ||
2184 | 149 | relation property). | ||
2185 | 150 | |||
2186 | 151 | :param list *args: List of options that must be changed from their default values. | ||
2187 | 152 | """ | ||
2188 | 153 | |||
2189 | 154 | def __init__(self, *args): | ||
2190 | 155 | self.required_options = args | ||
2191 | 156 | self['config'] = hookenv.config() | ||
2192 | 157 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
2193 | 158 | self.config = yaml.load(fp).get('options', {}) | ||
2194 | 159 | |||
2195 | 160 | def __bool__(self): | ||
2196 | 161 | for option in self.required_options: | ||
2197 | 162 | if option not in self['config']: | ||
2198 | 163 | return False | ||
2199 | 164 | current_value = self['config'][option] | ||
2200 | 165 | default_value = self.config[option].get('default') | ||
2201 | 166 | if current_value == default_value: | ||
2202 | 167 | return False | ||
2203 | 168 | if current_value in (None, '') and default_value in (None, ''): | ||
2204 | 169 | return False | ||
2205 | 170 | return True | ||
2206 | 171 | |||
2207 | 172 | def __nonzero__(self): | ||
2208 | 173 | return self.__bool__() | ||
2209 | 174 | |||
2210 | 175 | |||
2211 | 176 | class StoredContext(dict): | ||
2212 | 177 | """ | ||
2213 | 178 | A data context that always returns the data that it was first created with. | ||
2214 | 179 | |||
2215 | 180 | This is useful to do a one-time generation of things like passwords, that | ||
2216 | 181 | will thereafter use the same value that was originally generated, instead | ||
2217 | 182 | of generating a new value each time it is run. | ||
2218 | 183 | """ | ||
2219 | 184 | def __init__(self, file_name, config_data): | ||
2220 | 185 | """ | ||
2221 | 186 | If the file exists, populate `self` with the data from the file. | ||
2222 | 187 | Otherwise, populate with the given data and persist it to the file. | ||
2223 | 188 | """ | ||
2224 | 189 | if os.path.exists(file_name): | ||
2225 | 190 | self.update(self.read_context(file_name)) | ||
2226 | 191 | else: | ||
2227 | 192 | self.store_context(file_name, config_data) | ||
2228 | 193 | self.update(config_data) | ||
2229 | 194 | |||
2230 | 195 | def store_context(self, file_name, config_data): | ||
2231 | 196 | if not os.path.isabs(file_name): | ||
2232 | 197 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2233 | 198 | with open(file_name, 'w') as file_stream: | ||
2234 | 199 | os.fchmod(file_stream.fileno(), 0o600) | ||
2235 | 200 | yaml.dump(config_data, file_stream) | ||
2236 | 201 | |||
2237 | 202 | def read_context(self, file_name): | ||
2238 | 203 | if not os.path.isabs(file_name): | ||
2239 | 204 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2240 | 205 | with open(file_name, 'r') as file_stream: | ||
2241 | 206 | data = yaml.load(file_stream) | ||
2242 | 207 | if not data: | ||
2243 | 208 | raise OSError("%s is empty" % file_name) | ||
2244 | 209 | return data | ||
2245 | 210 | |||
2246 | 211 | |||
2247 | 212 | class TemplateCallback(ManagerCallback): | ||
2248 | 213 | """ | ||
2249 | 214 | Callback class that will render a Jinja2 template, for use as a ready | ||
2250 | 215 | action. | ||
2251 | 216 | |||
2252 | 217 | :param str source: The template source file, relative to | ||
2253 | 218 | `$CHARM_DIR/templates` | ||
2254 | 219 | |||
2255 | 220 | :param str target: The target to write the rendered template to | ||
2256 | 221 | :param str owner: The owner of the rendered file | ||
2257 | 222 | :param str group: The group of the rendered file | ||
2258 | 223 | :param int perms: The permissions of the rendered file | ||
2259 | 224 | """ | ||
2260 | 225 | def __init__(self, source, target, | ||
2261 | 226 | owner='root', group='root', perms=0o444): | ||
2262 | 227 | self.source = source | ||
2263 | 228 | self.target = target | ||
2264 | 229 | self.owner = owner | ||
2265 | 230 | self.group = group | ||
2266 | 231 | self.perms = perms | ||
2267 | 232 | |||
2268 | 233 | def __call__(self, manager, service_name, event_name): | ||
2269 | 234 | service = manager.get_service(service_name) | ||
2270 | 235 | context = {} | ||
2271 | 236 | for ctx in service.get('required_data', []): | ||
2272 | 237 | context.update(ctx) | ||
2273 | 238 | templating.render(self.source, self.target, context, | ||
2274 | 239 | self.owner, self.group, self.perms) | ||
2275 | 240 | |||
2276 | 241 | |||
2277 | 242 | # Convenience aliases for templates | ||
2278 | 243 | render_template = template = TemplateCallback | ||
2279 | 0 | 244 | ||
2280 | === added file 'lib/charmhelpers/core/sysctl.py' | |||
2281 | --- lib/charmhelpers/core/sysctl.py 1970-01-01 00:00:00 +0000 | |||
2282 | +++ lib/charmhelpers/core/sysctl.py 2014-12-15 18:28:33 +0000 | |||
2283 | @@ -0,0 +1,34 @@ | |||
2284 | 1 | #!/usr/bin/env python | ||
2285 | 2 | # -*- coding: utf-8 -*- | ||
2286 | 3 | |||
2287 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
2288 | 5 | |||
2289 | 6 | import yaml | ||
2290 | 7 | |||
2291 | 8 | from subprocess import check_call | ||
2292 | 9 | |||
2293 | 10 | from charmhelpers.core.hookenv import ( | ||
2294 | 11 | log, | ||
2295 | 12 | DEBUG, | ||
2296 | 13 | ) | ||
2297 | 14 | |||
2298 | 15 | |||
2299 | 16 | def create(sysctl_dict, sysctl_file): | ||
2300 | 17 | """Creates a sysctl.conf file from a YAML associative array | ||
2301 | 18 | |||
2302 | 19 | :param sysctl_dict: a dict of sysctl options eg { 'kernel.max_pid': 1337 } | ||
2303 | 20 | :type sysctl_dict: dict | ||
2304 | 21 | :param sysctl_file: path to the sysctl file to be saved | ||
2305 | 22 | :type sysctl_file: str or unicode | ||
2306 | 23 | :returns: None | ||
2307 | 24 | """ | ||
2308 | 25 | sysctl_dict = yaml.load(sysctl_dict) | ||
2309 | 26 | |||
2310 | 27 | with open(sysctl_file, "w") as fd: | ||
2311 | 28 | for key, value in sysctl_dict.items(): | ||
2312 | 29 | fd.write("{}={}\n".format(key, value)) | ||
2313 | 30 | |||
2314 | 31 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict), | ||
2315 | 32 | level=DEBUG) | ||
2316 | 33 | |||
2317 | 34 | check_call(["sysctl", "-p", sysctl_file]) | ||
2318 | 0 | 35 | ||
2319 | === added file 'lib/charmhelpers/core/templating.py' | |||
2320 | --- lib/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
2321 | +++ lib/charmhelpers/core/templating.py 2014-12-15 18:28:33 +0000 | |||
2322 | @@ -0,0 +1,52 @@ | |||
2323 | 1 | import os | ||
2324 | 2 | |||
2325 | 3 | from charmhelpers.core import host | ||
2326 | 4 | from charmhelpers.core import hookenv | ||
2327 | 5 | |||
2328 | 6 | |||
2329 | 7 | def render(source, target, context, owner='root', group='root', | ||
2330 | 8 | perms=0o444, templates_dir=None): | ||
2331 | 9 | """ | ||
2332 | 10 | Render a template. | ||
2333 | 11 | |||
2334 | 12 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
2335 | 13 | |||
2336 | 14 | The `target` path should be absolute. | ||
2337 | 15 | |||
2338 | 16 | The context should be a dict containing the values to be replaced in the | ||
2339 | 17 | template. | ||
2340 | 18 | |||
2341 | 19 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
2342 | 20 | |||
2343 | 21 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
2344 | 22 | |||
2345 | 23 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
2346 | 24 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
2347 | 25 | """ | ||
2348 | 26 | try: | ||
2349 | 27 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2350 | 28 | except ImportError: | ||
2351 | 29 | try: | ||
2352 | 30 | from charmhelpers.fetch import apt_install | ||
2353 | 31 | except ImportError: | ||
2354 | 32 | hookenv.log('Could not import jinja2, and could not import ' | ||
2355 | 33 | 'charmhelpers.fetch to install it', | ||
2356 | 34 | level=hookenv.ERROR) | ||
2357 | 35 | raise | ||
2358 | 36 | apt_install('python-jinja2', fatal=True) | ||
2359 | 37 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2360 | 38 | |||
2361 | 39 | if templates_dir is None: | ||
2362 | 40 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
2363 | 41 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
2364 | 42 | try: | ||
2365 | 43 | source = source | ||
2366 | 44 | template = loader.get_template(source) | ||
2367 | 45 | except exceptions.TemplateNotFound as e: | ||
2368 | 46 | hookenv.log('Could not load template %s from %s.' % | ||
2369 | 47 | (source, templates_dir), | ||
2370 | 48 | level=hookenv.ERROR) | ||
2371 | 49 | raise e | ||
2372 | 50 | content = template.render(context) | ||
2373 | 51 | host.mkdir(os.path.dirname(target)) | ||
2374 | 52 | host.write_file(target, content, owner, group, perms) | ||
2375 | 0 | 53 | ||
2376 | === added directory 'lib/charmhelpers/fetch' | |||
2377 | === added file 'lib/charmhelpers/fetch/__init__.py' | |||
2378 | --- lib/charmhelpers/fetch/__init__.py 1970-01-01 00:00:00 +0000 | |||
2379 | +++ lib/charmhelpers/fetch/__init__.py 2014-12-15 18:28:33 +0000 | |||
2380 | @@ -0,0 +1,416 @@ | |||
2381 | 1 | import importlib | ||
2382 | 2 | from tempfile import NamedTemporaryFile | ||
2383 | 3 | import time | ||
2384 | 4 | from yaml import safe_load | ||
2385 | 5 | from charmhelpers.core.host import ( | ||
2386 | 6 | lsb_release | ||
2387 | 7 | ) | ||
2388 | 8 | import subprocess | ||
2389 | 9 | from charmhelpers.core.hookenv import ( | ||
2390 | 10 | config, | ||
2391 | 11 | log, | ||
2392 | 12 | ) | ||
2393 | 13 | import os | ||
2394 | 14 | |||
2395 | 15 | import six | ||
2396 | 16 | if six.PY3: | ||
2397 | 17 | from urllib.parse import urlparse, urlunparse | ||
2398 | 18 | else: | ||
2399 | 19 | from urlparse import urlparse, urlunparse | ||
2400 | 20 | |||
2401 | 21 | |||
2402 | 22 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | ||
2403 | 23 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | ||
2404 | 24 | """ | ||
2405 | 25 | PROPOSED_POCKET = """# Proposed | ||
2406 | 26 | deb http://archive.ubuntu.com/ubuntu {}-proposed main universe multiverse restricted | ||
2407 | 27 | """ | ||
2408 | 28 | CLOUD_ARCHIVE_POCKETS = { | ||
2409 | 29 | # Folsom | ||
2410 | 30 | 'folsom': 'precise-updates/folsom', | ||
2411 | 31 | 'precise-folsom': 'precise-updates/folsom', | ||
2412 | 32 | 'precise-folsom/updates': 'precise-updates/folsom', | ||
2413 | 33 | 'precise-updates/folsom': 'precise-updates/folsom', | ||
2414 | 34 | 'folsom/proposed': 'precise-proposed/folsom', | ||
2415 | 35 | 'precise-folsom/proposed': 'precise-proposed/folsom', | ||
2416 | 36 | 'precise-proposed/folsom': 'precise-proposed/folsom', | ||
2417 | 37 | # Grizzly | ||
2418 | 38 | 'grizzly': 'precise-updates/grizzly', | ||
2419 | 39 | 'precise-grizzly': 'precise-updates/grizzly', | ||
2420 | 40 | 'precise-grizzly/updates': 'precise-updates/grizzly', | ||
2421 | 41 | 'precise-updates/grizzly': 'precise-updates/grizzly', | ||
2422 | 42 | 'grizzly/proposed': 'precise-proposed/grizzly', | ||
2423 | 43 | 'precise-grizzly/proposed': 'precise-proposed/grizzly', | ||
2424 | 44 | 'precise-proposed/grizzly': 'precise-proposed/grizzly', | ||
2425 | 45 | # Havana | ||
2426 | 46 | 'havana': 'precise-updates/havana', | ||
2427 | 47 | 'precise-havana': 'precise-updates/havana', | ||
2428 | 48 | 'precise-havana/updates': 'precise-updates/havana', | ||
2429 | 49 | 'precise-updates/havana': 'precise-updates/havana', | ||
2430 | 50 | 'havana/proposed': 'precise-proposed/havana', | ||
2431 | 51 | 'precise-havana/proposed': 'precise-proposed/havana', | ||
2432 | 52 | 'precise-proposed/havana': 'precise-proposed/havana', | ||
2433 | 53 | # Icehouse | ||
2434 | 54 | 'icehouse': 'precise-updates/icehouse', | ||
2435 | 55 | 'precise-icehouse': 'precise-updates/icehouse', | ||
2436 | 56 | 'precise-icehouse/updates': 'precise-updates/icehouse', | ||
2437 | 57 | 'precise-updates/icehouse': 'precise-updates/icehouse', | ||
2438 | 58 | 'icehouse/proposed': 'precise-proposed/icehouse', | ||
2439 | 59 | 'precise-icehouse/proposed': 'precise-proposed/icehouse', | ||
2440 | 60 | 'precise-proposed/icehouse': 'precise-proposed/icehouse', | ||
2441 | 61 | # Juno | ||
2442 | 62 | 'juno': 'trusty-updates/juno', | ||
2443 | 63 | 'trusty-juno': 'trusty-updates/juno', | ||
2444 | 64 | 'trusty-juno/updates': 'trusty-updates/juno', | ||
2445 | 65 | 'trusty-updates/juno': 'trusty-updates/juno', | ||
2446 | 66 | 'juno/proposed': 'trusty-proposed/juno', | ||
2447 | 67 | 'juno/proposed': 'trusty-proposed/juno', | ||
2448 | 68 | 'trusty-juno/proposed': 'trusty-proposed/juno', | ||
2449 | 69 | 'trusty-proposed/juno': 'trusty-proposed/juno', | ||
2450 | 70 | } | ||
2451 | 71 | |||
2452 | 72 | # The order of this list is very important. Handlers should be listed in from | ||
2453 | 73 | # least- to most-specific URL matching. | ||
2454 | 74 | FETCH_HANDLERS = ( | ||
2455 | 75 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | ||
2456 | 76 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | ||
2457 | 77 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
2458 | 78 | ) | ||
2459 | 79 | |||
2460 | 80 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | ||
2461 | 81 | APT_NO_LOCK_RETRY_DELAY = 10 # Wait 10 seconds between apt lock checks. | ||
2462 | 82 | APT_NO_LOCK_RETRY_COUNT = 30 # Retry to acquire the lock X times. | ||
2463 | 83 | |||
2464 | 84 | |||
2465 | 85 | class SourceConfigError(Exception): | ||
2466 | 86 | pass | ||
2467 | 87 | |||
2468 | 88 | |||
2469 | 89 | class UnhandledSource(Exception): | ||
2470 | 90 | pass | ||
2471 | 91 | |||
2472 | 92 | |||
2473 | 93 | class AptLockError(Exception): | ||
2474 | 94 | pass | ||
2475 | 95 | |||
2476 | 96 | |||
2477 | 97 | class BaseFetchHandler(object): | ||
2478 | 98 | |||
2479 | 99 | """Base class for FetchHandler implementations in fetch plugins""" | ||
2480 | 100 | |||
2481 | 101 | def can_handle(self, source): | ||
2482 | 102 | """Returns True if the source can be handled. Otherwise returns | ||
2483 | 103 | a string explaining why it cannot""" | ||
2484 | 104 | return "Wrong source type" | ||
2485 | 105 | |||
2486 | 106 | def install(self, source): | ||
2487 | 107 | """Try to download and unpack the source. Return the path to the | ||
2488 | 108 | unpacked files or raise UnhandledSource.""" | ||
2489 | 109 | raise UnhandledSource("Wrong source type {}".format(source)) | ||
2490 | 110 | |||
2491 | 111 | def parse_url(self, url): | ||
2492 | 112 | return urlparse(url) | ||
2493 | 113 | |||
2494 | 114 | def base_url(self, url): | ||
2495 | 115 | """Return url without querystring or fragment""" | ||
2496 | 116 | parts = list(self.parse_url(url)) | ||
2497 | 117 | parts[4:] = ['' for i in parts[4:]] | ||
2498 | 118 | return urlunparse(parts) | ||
2499 | 119 | |||
2500 | 120 | |||
2501 | 121 | def filter_installed_packages(packages): | ||
2502 | 122 | """Returns a list of packages that require installation""" | ||
2503 | 123 | cache = apt_cache() | ||
2504 | 124 | _pkgs = [] | ||
2505 | 125 | for package in packages: | ||
2506 | 126 | try: | ||
2507 | 127 | p = cache[package] | ||
2508 | 128 | p.current_ver or _pkgs.append(package) | ||
2509 | 129 | except KeyError: | ||
2510 | 130 | log('Package {} has no installation candidate.'.format(package), | ||
2511 | 131 | level='WARNING') | ||
2512 | 132 | _pkgs.append(package) | ||
2513 | 133 | return _pkgs | ||
2514 | 134 | |||
2515 | 135 | |||
2516 | 136 | def apt_cache(in_memory=True): | ||
2517 | 137 | """Build and return an apt cache""" | ||
2518 | 138 | import apt_pkg | ||
2519 | 139 | apt_pkg.init() | ||
2520 | 140 | if in_memory: | ||
2521 | 141 | apt_pkg.config.set("Dir::Cache::pkgcache", "") | ||
2522 | 142 | apt_pkg.config.set("Dir::Cache::srcpkgcache", "") | ||
2523 | 143 | return apt_pkg.Cache() | ||
2524 | 144 | |||
2525 | 145 | |||
2526 | 146 | def apt_install(packages, options=None, fatal=False): | ||
2527 | 147 | """Install one or more packages""" | ||
2528 | 148 | if options is None: | ||
2529 | 149 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2530 | 150 | |||
2531 | 151 | cmd = ['apt-get', '--assume-yes'] | ||
2532 | 152 | cmd.extend(options) | ||
2533 | 153 | cmd.append('install') | ||
2534 | 154 | if isinstance(packages, six.string_types): | ||
2535 | 155 | cmd.append(packages) | ||
2536 | 156 | else: | ||
2537 | 157 | cmd.extend(packages) | ||
2538 | 158 | log("Installing {} with options: {}".format(packages, | ||
2539 | 159 | options)) | ||
2540 | 160 | _run_apt_command(cmd, fatal) | ||
2541 | 161 | |||
2542 | 162 | |||
2543 | 163 | def apt_upgrade(options=None, fatal=False, dist=False): | ||
2544 | 164 | """Upgrade all packages""" | ||
2545 | 165 | if options is None: | ||
2546 | 166 | options = ['--option=Dpkg::Options::=--force-confold'] | ||
2547 | 167 | |||
2548 | 168 | cmd = ['apt-get', '--assume-yes'] | ||
2549 | 169 | cmd.extend(options) | ||
2550 | 170 | if dist: | ||
2551 | 171 | cmd.append('dist-upgrade') | ||
2552 | 172 | else: | ||
2553 | 173 | cmd.append('upgrade') | ||
2554 | 174 | log("Upgrading with options: {}".format(options)) | ||
2555 | 175 | _run_apt_command(cmd, fatal) | ||
2556 | 176 | |||
2557 | 177 | |||
2558 | 178 | def apt_update(fatal=False): | ||
2559 | 179 | """Update local apt cache""" | ||
2560 | 180 | cmd = ['apt-get', 'update'] | ||
2561 | 181 | _run_apt_command(cmd, fatal) | ||
2562 | 182 | |||
2563 | 183 | |||
2564 | 184 | def apt_purge(packages, fatal=False): | ||
2565 | 185 | """Purge one or more packages""" | ||
2566 | 186 | cmd = ['apt-get', '--assume-yes', 'purge'] | ||
2567 | 187 | if isinstance(packages, six.string_types): | ||
2568 | 188 | cmd.append(packages) | ||
2569 | 189 | else: | ||
2570 | 190 | cmd.extend(packages) | ||
2571 | 191 | log("Purging {}".format(packages)) | ||
2572 | 192 | _run_apt_command(cmd, fatal) | ||
2573 | 193 | |||
2574 | 194 | |||
2575 | 195 | def apt_hold(packages, fatal=False): | ||
2576 | 196 | """Hold one or more packages""" | ||
2577 | 197 | cmd = ['apt-mark', 'hold'] | ||
2578 | 198 | if isinstance(packages, six.string_types): | ||
2579 | 199 | cmd.append(packages) | ||
2580 | 200 | else: | ||
2581 | 201 | cmd.extend(packages) | ||
2582 | 202 | log("Holding {}".format(packages)) | ||
2583 | 203 | |||
2584 | 204 | if fatal: | ||
2585 | 205 | subprocess.check_call(cmd) | ||
2586 | 206 | else: | ||
2587 | 207 | subprocess.call(cmd) | ||
2588 | 208 | |||
2589 | 209 | |||
2590 | 210 | def add_source(source, key=None): | ||
2591 | 211 | """Add a package source to this system. | ||
2592 | 212 | |||
2593 | 213 | @param source: a URL or sources.list entry, as supported by | ||
2594 | 214 | add-apt-repository(1). Examples:: | ||
2595 | 215 | |||
2596 | 216 | ppa:charmers/example | ||
2597 | 217 | deb https://stub:key@private.example.com/ubuntu trusty main | ||
2598 | 218 | |||
2599 | 219 | In addition: | ||
2600 | 220 | 'proposed:' may be used to enable the standard 'proposed' | ||
2601 | 221 | pocket for the release. | ||
2602 | 222 | 'cloud:' may be used to activate official cloud archive pockets, | ||
2603 | 223 | such as 'cloud:icehouse' | ||
2604 | 224 | 'distro' may be used as a noop | ||
2605 | 225 | |||
2606 | 226 | @param key: A key to be added to the system's APT keyring and used | ||
2607 | 227 | to verify the signatures on packages. Ideally, this should be an | ||
2608 | 228 | ASCII format GPG public key including the block headers. A GPG key | ||
2609 | 229 | id may also be used, but be aware that only insecure protocols are | ||
2610 | 230 | available to retrieve the actual public key from a public keyserver | ||
2611 | 231 | placing your Juju environment at risk. ppa and cloud archive keys | ||
2612 | 232 | are securely added automtically, so sould not be provided. | ||
2613 | 233 | """ | ||
2614 | 234 | if source is None: | ||
2615 | 235 | log('Source is not present. Skipping') | ||
2616 | 236 | return | ||
2617 | 237 | |||
2618 | 238 | if (source.startswith('ppa:') or | ||
2619 | 239 | source.startswith('http') or | ||
2620 | 240 | source.startswith('deb ') or | ||
2621 | 241 | source.startswith('cloud-archive:')): | ||
2622 | 242 | subprocess.check_call(['add-apt-repository', '--yes', source]) | ||
2623 | 243 | elif source.startswith('cloud:'): | ||
2624 | 244 | apt_install(filter_installed_packages(['ubuntu-cloud-keyring']), | ||
2625 | 245 | fatal=True) | ||
2626 | 246 | pocket = source.split(':')[-1] | ||
2627 | 247 | if pocket not in CLOUD_ARCHIVE_POCKETS: | ||
2628 | 248 | raise SourceConfigError( | ||
2629 | 249 | 'Unsupported cloud: source option %s' % | ||
2630 | 250 | pocket) | ||
2631 | 251 | actual_pocket = CLOUD_ARCHIVE_POCKETS[pocket] | ||
2632 | 252 | with open('/etc/apt/sources.list.d/cloud-archive.list', 'w') as apt: | ||
2633 | 253 | apt.write(CLOUD_ARCHIVE.format(actual_pocket)) | ||
2634 | 254 | elif source == 'proposed': | ||
2635 | 255 | release = lsb_release()['DISTRIB_CODENAME'] | ||
2636 | 256 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | ||
2637 | 257 | apt.write(PROPOSED_POCKET.format(release)) | ||
2638 | 258 | elif source == 'distro': | ||
2639 | 259 | pass | ||
2640 | 260 | else: | ||
2641 | 261 | log("Unknown source: {!r}".format(source)) | ||
2642 | 262 | |||
2643 | 263 | if key: | ||
2644 | 264 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: | ||
2645 | 265 | with NamedTemporaryFile('w+') as key_file: | ||
2646 | 266 | key_file.write(key) | ||
2647 | 267 | key_file.flush() | ||
2648 | 268 | key_file.seek(0) | ||
2649 | 269 | subprocess.check_call(['apt-key', 'add', '-'], stdin=key_file) | ||
2650 | 270 | else: | ||
2651 | 271 | # Note that hkp: is in no way a secure protocol. Using a | ||
2652 | 272 | # GPG key id is pointless from a security POV unless you | ||
2653 | 273 | # absolutely trust your network and DNS. | ||
2654 | 274 | subprocess.check_call(['apt-key', 'adv', '--keyserver', | ||
2655 | 275 | 'hkp://keyserver.ubuntu.com:80', '--recv', | ||
2656 | 276 | key]) | ||
2657 | 277 | |||
2658 | 278 | |||
2659 | 279 | def configure_sources(update=False, | ||
2660 | 280 | sources_var='install_sources', | ||
2661 | 281 | keys_var='install_keys'): | ||
2662 | 282 | """ | ||
2663 | 283 | Configure multiple sources from charm configuration. | ||
2664 | 284 | |||
2665 | 285 | The lists are encoded as yaml fragments in the configuration. | ||
2666 | 286 | The frament needs to be included as a string. Sources and their | ||
2667 | 287 | corresponding keys are of the types supported by add_source(). | ||
2668 | 288 | |||
2669 | 289 | Example config: | ||
2670 | 290 | install_sources: | | ||
2671 | 291 | - "ppa:foo" | ||
2672 | 292 | - "http://example.com/repo precise main" | ||
2673 | 293 | install_keys: | | ||
2674 | 294 | - null | ||
2675 | 295 | - "a1b2c3d4" | ||
2676 | 296 | |||
2677 | 297 | Note that 'null' (a.k.a. None) should not be quoted. | ||
2678 | 298 | """ | ||
2679 | 299 | sources = safe_load((config(sources_var) or '').strip()) or [] | ||
2680 | 300 | keys = safe_load((config(keys_var) or '').strip()) or None | ||
2681 | 301 | |||
2682 | 302 | if isinstance(sources, six.string_types): | ||
2683 | 303 | sources = [sources] | ||
2684 | 304 | |||
2685 | 305 | if keys is None: | ||
2686 | 306 | for source in sources: | ||
2687 | 307 | add_source(source, None) | ||
2688 | 308 | else: | ||
2689 | 309 | if isinstance(keys, six.string_types): | ||
2690 | 310 | keys = [keys] | ||
2691 | 311 | |||
2692 | 312 | if len(sources) != len(keys): | ||
2693 | 313 | raise SourceConfigError( | ||
2694 | 314 | 'Install sources and keys lists are different lengths') | ||
2695 | 315 | for source, key in zip(sources, keys): | ||
2696 | 316 | add_source(source, key) | ||
2697 | 317 | if update: | ||
2698 | 318 | apt_update(fatal=True) | ||
2699 | 319 | |||
2700 | 320 | |||
2701 | 321 | def install_remote(source, *args, **kwargs): | ||
2702 | 322 | """ | ||
2703 | 323 | Install a file tree from a remote source | ||
2704 | 324 | |||
2705 | 325 | The specified source should be a url of the form: | ||
2706 | 326 | scheme://[host]/path[#[option=value][&...]] | ||
2707 | 327 | |||
2708 | 328 | Schemes supported are based on this modules submodules. | ||
2709 | 329 | Options supported are submodule-specific. | ||
2710 | 330 | Additional arguments are passed through to the submodule. | ||
2711 | 331 | |||
2712 | 332 | For example:: | ||
2713 | 333 | |||
2714 | 334 | dest = install_remote('http://example.com/archive.tgz', | ||
2715 | 335 | checksum='deadbeef', | ||
2716 | 336 | hash_type='sha1') | ||
2717 | 337 | |||
2718 | 338 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
2719 | 339 | the file is ok, extract it and return the directory in which it | ||
2720 | 340 | was extracted. If the checksum fails, it will raise | ||
2721 | 341 | :class:`charmhelpers.core.host.ChecksumError`. | ||
2722 | 342 | """ | ||
2723 | 343 | # We ONLY check for True here because can_handle may return a string | ||
2724 | 344 | # explaining why it can't handle a given source. | ||
2725 | 345 | handlers = [h for h in plugins() if h.can_handle(source) is True] | ||
2726 | 346 | installed_to = None | ||
2727 | 347 | for handler in handlers: | ||
2728 | 348 | try: | ||
2729 | 349 | installed_to = handler.install(source, *args, **kwargs) | ||
2730 | 350 | except UnhandledSource: | ||
2731 | 351 | pass | ||
2732 | 352 | if not installed_to: | ||
2733 | 353 | raise UnhandledSource("No handler found for source {}".format(source)) | ||
2734 | 354 | return installed_to | ||
2735 | 355 | |||
2736 | 356 | |||
2737 | 357 | def install_from_config(config_var_name): | ||
2738 | 358 | charm_config = config() | ||
2739 | 359 | source = charm_config[config_var_name] | ||
2740 | 360 | return install_remote(source) | ||
2741 | 361 | |||
2742 | 362 | |||
2743 | 363 | def plugins(fetch_handlers=None): | ||
2744 | 364 | if not fetch_handlers: | ||
2745 | 365 | fetch_handlers = FETCH_HANDLERS | ||
2746 | 366 | plugin_list = [] | ||
2747 | 367 | for handler_name in fetch_handlers: | ||
2748 | 368 | package, classname = handler_name.rsplit('.', 1) | ||
2749 | 369 | try: | ||
2750 | 370 | handler_class = getattr( | ||
2751 | 371 | importlib.import_module(package), | ||
2752 | 372 | classname) | ||
2753 | 373 | plugin_list.append(handler_class()) | ||
2754 | 374 | except (ImportError, AttributeError): | ||
2755 | 375 | # Skip missing plugins so that they can be ommitted from | ||
2756 | 376 | # installation if desired | ||
2757 | 377 | log("FetchHandler {} not found, skipping plugin".format( | ||
2758 | 378 | handler_name)) | ||
2759 | 379 | return plugin_list | ||
2760 | 380 | |||
2761 | 381 | |||
2762 | 382 | def _run_apt_command(cmd, fatal=False): | ||
2763 | 383 | """ | ||
2764 | 384 | Run an APT command, checking output and retrying if the fatal flag is set | ||
2765 | 385 | to True. | ||
2766 | 386 | |||
2767 | 387 | :param: cmd: str: The apt command to run. | ||
2768 | 388 | :param: fatal: bool: Whether the command's output should be checked and | ||
2769 | 389 | retried. | ||
2770 | 390 | """ | ||
2771 | 391 | env = os.environ.copy() | ||
2772 | 392 | |||
2773 | 393 | if 'DEBIAN_FRONTEND' not in env: | ||
2774 | 394 | env['DEBIAN_FRONTEND'] = 'noninteractive' | ||
2775 | 395 | |||
2776 | 396 | if fatal: | ||
2777 | 397 | retry_count = 0 | ||
2778 | 398 | result = None | ||
2779 | 399 | |||
2780 | 400 | # If the command is considered "fatal", we need to retry if the apt | ||
2781 | 401 | # lock was not acquired. | ||
2782 | 402 | |||
2783 | 403 | while result is None or result == APT_NO_LOCK: | ||
2784 | 404 | try: | ||
2785 | 405 | result = subprocess.check_call(cmd, env=env) | ||
2786 | 406 | except subprocess.CalledProcessError as e: | ||
2787 | 407 | retry_count = retry_count + 1 | ||
2788 | 408 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | ||
2789 | 409 | raise | ||
2790 | 410 | result = e.returncode | ||
2791 | 411 | log("Couldn't acquire DPKG lock. Will retry in {} seconds." | ||
2792 | 412 | "".format(APT_NO_LOCK_RETRY_DELAY)) | ||
2793 | 413 | time.sleep(APT_NO_LOCK_RETRY_DELAY) | ||
2794 | 414 | |||
2795 | 415 | else: | ||
2796 | 416 | subprocess.call(cmd, env=env) | ||
2797 | 0 | 417 | ||
2798 | === added file 'lib/charmhelpers/fetch/archiveurl.py' | |||
2799 | --- lib/charmhelpers/fetch/archiveurl.py 1970-01-01 00:00:00 +0000 | |||
2800 | +++ lib/charmhelpers/fetch/archiveurl.py 2014-12-15 18:28:33 +0000 | |||
2801 | @@ -0,0 +1,145 @@ | |||
2802 | 1 | import os | ||
2803 | 2 | import hashlib | ||
2804 | 3 | import re | ||
2805 | 4 | |||
2806 | 5 | import six | ||
2807 | 6 | if six.PY3: | ||
2808 | 7 | from urllib.request import ( | ||
2809 | 8 | build_opener, install_opener, urlopen, urlretrieve, | ||
2810 | 9 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
2811 | 10 | ) | ||
2812 | 11 | from urllib.parse import urlparse, urlunparse, parse_qs | ||
2813 | 12 | from urllib.error import URLError | ||
2814 | 13 | else: | ||
2815 | 14 | from urllib import urlretrieve | ||
2816 | 15 | from urllib2 import ( | ||
2817 | 16 | build_opener, install_opener, urlopen, | ||
2818 | 17 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
2819 | 18 | URLError | ||
2820 | 19 | ) | ||
2821 | 20 | from urlparse import urlparse, urlunparse, parse_qs | ||
2822 | 21 | |||
2823 | 22 | from charmhelpers.fetch import ( | ||
2824 | 23 | BaseFetchHandler, | ||
2825 | 24 | UnhandledSource | ||
2826 | 25 | ) | ||
2827 | 26 | from charmhelpers.payload.archive import ( | ||
2828 | 27 | get_archive_handler, | ||
2829 | 28 | extract, | ||
2830 | 29 | ) | ||
2831 | 30 | from charmhelpers.core.host import mkdir, check_hash | ||
2832 | 31 | |||
2833 | 32 | |||
2834 | 33 | def splituser(host): | ||
2835 | 34 | '''urllib.splituser(), but six's support of this seems broken''' | ||
2836 | 35 | _userprog = re.compile('^(.*)@(.*)$') | ||
2837 | 36 | match = _userprog.match(host) | ||
2838 | 37 | if match: | ||
2839 | 38 | return match.group(1, 2) | ||
2840 | 39 | return None, host | ||
2841 | 40 | |||
2842 | 41 | |||
2843 | 42 | def splitpasswd(user): | ||
2844 | 43 | '''urllib.splitpasswd(), but six's support of this is missing''' | ||
2845 | 44 | _passwdprog = re.compile('^([^:]*):(.*)$', re.S) | ||
2846 | 45 | match = _passwdprog.match(user) | ||
2847 | 46 | if match: | ||
2848 | 47 | return match.group(1, 2) | ||
2849 | 48 | return user, None | ||
2850 | 49 | |||
2851 | 50 | |||
2852 | 51 | class ArchiveUrlFetchHandler(BaseFetchHandler): | ||
2853 | 52 | """ | ||
2854 | 53 | Handler to download archive files from arbitrary URLs. | ||
2855 | 54 | |||
2856 | 55 | Can fetch from http, https, ftp, and file URLs. | ||
2857 | 56 | |||
2858 | 57 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
2859 | 58 | |||
2860 | 59 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
2861 | 60 | """ | ||
2862 | 61 | def can_handle(self, source): | ||
2863 | 62 | url_parts = self.parse_url(source) | ||
2864 | 63 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | ||
2865 | 64 | return "Wrong source type" | ||
2866 | 65 | if get_archive_handler(self.base_url(source)): | ||
2867 | 66 | return True | ||
2868 | 67 | return False | ||
2869 | 68 | |||
2870 | 69 | def download(self, source, dest): | ||
2871 | 70 | """ | ||
2872 | 71 | Download an archive file. | ||
2873 | 72 | |||
2874 | 73 | :param str source: URL pointing to an archive file. | ||
2875 | 74 | :param str dest: Local path location to download archive file to. | ||
2876 | 75 | """ | ||
2877 | 76 | # propogate all exceptions | ||
2878 | 77 | # URLError, OSError, etc | ||
2879 | 78 | proto, netloc, path, params, query, fragment = urlparse(source) | ||
2880 | 79 | if proto in ('http', 'https'): | ||
2881 | 80 | auth, barehost = splituser(netloc) | ||
2882 | 81 | if auth is not None: | ||
2883 | 82 | source = urlunparse((proto, barehost, path, params, query, fragment)) | ||
2884 | 83 | username, password = splitpasswd(auth) | ||
2885 | 84 | passman = HTTPPasswordMgrWithDefaultRealm() | ||
2886 | 85 | # Realm is set to None in add_password to force the username and password | ||
2887 | 86 | # to be used whatever the realm | ||
2888 | 87 | passman.add_password(None, source, username, password) | ||
2889 | 88 | authhandler = HTTPBasicAuthHandler(passman) | ||
2890 | 89 | opener = build_opener(authhandler) | ||
2891 | 90 | install_opener(opener) | ||
2892 | 91 | response = urlopen(source) | ||
2893 | 92 | try: | ||
2894 | 93 | with open(dest, 'w') as dest_file: | ||
2895 | 94 | dest_file.write(response.read()) | ||
2896 | 95 | except Exception as e: | ||
2897 | 96 | if os.path.isfile(dest): | ||
2898 | 97 | os.unlink(dest) | ||
2899 | 98 | raise e | ||
2900 | 99 | |||
2901 | 100 | # Mandatory file validation via Sha1 or MD5 hashing. | ||
2902 | 101 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
2903 | 102 | tempfile, headers = urlretrieve(url) | ||
2904 | 103 | check_hash(tempfile, hashsum, validate) | ||
2905 | 104 | return tempfile | ||
2906 | 105 | |||
2907 | 106 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
2908 | 107 | """ | ||
2909 | 108 | Download and install an archive file, with optional checksum validation. | ||
2910 | 109 | |||
2911 | 110 | The checksum can also be given on the `source` URL's fragment. | ||
2912 | 111 | For example:: | ||
2913 | 112 | |||
2914 | 113 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
2915 | 114 | |||
2916 | 115 | :param str source: URL pointing to an archive file. | ||
2917 | 116 | :param str dest: Local destination path to install to. If not given, | ||
2918 | 117 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
2919 | 118 | :param str checksum: If given, validate the archive file after download. | ||
2920 | 119 | :param str hash_type: Algorithm used to generate `checksum`. | ||
2921 | 120 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
2922 | 121 | such as md5, sha1, sha256, sha512, etc. | ||
2923 | 122 | |||
2924 | 123 | """ | ||
2925 | 124 | url_parts = self.parse_url(source) | ||
2926 | 125 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | ||
2927 | 126 | if not os.path.exists(dest_dir): | ||
2928 | 127 | mkdir(dest_dir, perms=0o755) | ||
2929 | 128 | dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path)) | ||
2930 | 129 | try: | ||
2931 | 130 | self.download(source, dld_file) | ||
2932 | 131 | except URLError as e: | ||
2933 | 132 | raise UnhandledSource(e.reason) | ||
2934 | 133 | except OSError as e: | ||
2935 | 134 | raise UnhandledSource(e.strerror) | ||
2936 | 135 | options = parse_qs(url_parts.fragment) | ||
2937 | 136 | for key, value in options.items(): | ||
2938 | 137 | if not six.PY3: | ||
2939 | 138 | algorithms = hashlib.algorithms | ||
2940 | 139 | else: | ||
2941 | 140 | algorithms = hashlib.algorithms_available | ||
2942 | 141 | if key in algorithms: | ||
2943 | 142 | check_hash(dld_file, value, key) | ||
2944 | 143 | if checksum: | ||
2945 | 144 | check_hash(dld_file, checksum, hash_type) | ||
2946 | 145 | return extract(dld_file, dest) | ||
2947 | 0 | 146 | ||
2948 | === added file 'lib/charmhelpers/fetch/bzrurl.py' | |||
2949 | --- lib/charmhelpers/fetch/bzrurl.py 1970-01-01 00:00:00 +0000 | |||
2950 | +++ lib/charmhelpers/fetch/bzrurl.py 2014-12-15 18:28:33 +0000 | |||
2951 | @@ -0,0 +1,54 @@ | |||
2952 | 1 | import os | ||
2953 | 2 | from charmhelpers.fetch import ( | ||
2954 | 3 | BaseFetchHandler, | ||
2955 | 4 | UnhandledSource | ||
2956 | 5 | ) | ||
2957 | 6 | from charmhelpers.core.host import mkdir | ||
2958 | 7 | |||
2959 | 8 | import six | ||
2960 | 9 | if six.PY3: | ||
2961 | 10 | raise ImportError('bzrlib does not support Python3') | ||
2962 | 11 | |||
2963 | 12 | try: | ||
2964 | 13 | from bzrlib.branch import Branch | ||
2965 | 14 | except ImportError: | ||
2966 | 15 | from charmhelpers.fetch import apt_install | ||
2967 | 16 | apt_install("python-bzrlib") | ||
2968 | 17 | from bzrlib.branch import Branch | ||
2969 | 18 | |||
2970 | 19 | |||
2971 | 20 | class BzrUrlFetchHandler(BaseFetchHandler): | ||
2972 | 21 | """Handler for bazaar branches via generic and lp URLs""" | ||
2973 | 22 | def can_handle(self, source): | ||
2974 | 23 | url_parts = self.parse_url(source) | ||
2975 | 24 | if url_parts.scheme not in ('bzr+ssh', 'lp'): | ||
2976 | 25 | return False | ||
2977 | 26 | else: | ||
2978 | 27 | return True | ||
2979 | 28 | |||
2980 | 29 | def branch(self, source, dest): | ||
2981 | 30 | url_parts = self.parse_url(source) | ||
2982 | 31 | # If we use lp:branchname scheme we need to load plugins | ||
2983 | 32 | if not self.can_handle(source): | ||
2984 | 33 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
2985 | 34 | if url_parts.scheme == "lp": | ||
2986 | 35 | from bzrlib.plugin import load_plugins | ||
2987 | 36 | load_plugins() | ||
2988 | 37 | try: | ||
2989 | 38 | remote_branch = Branch.open(source) | ||
2990 | 39 | remote_branch.bzrdir.sprout(dest).open_branch() | ||
2991 | 40 | except Exception as e: | ||
2992 | 41 | raise e | ||
2993 | 42 | |||
2994 | 43 | def install(self, source): | ||
2995 | 44 | url_parts = self.parse_url(source) | ||
2996 | 45 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
2997 | 46 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
2998 | 47 | branch_name) | ||
2999 | 48 | if not os.path.exists(dest_dir): | ||
3000 | 49 | mkdir(dest_dir, perms=0o755) | ||
3001 | 50 | try: | ||
3002 | 51 | self.branch(source, dest_dir) | ||
3003 | 52 | except OSError as e: | ||
3004 | 53 | raise UnhandledSource(e.strerror) | ||
3005 | 54 | return dest_dir | ||
3006 | 0 | 55 | ||
3007 | === added file 'lib/charmhelpers/fetch/giturl.py' | |||
3008 | --- lib/charmhelpers/fetch/giturl.py 1970-01-01 00:00:00 +0000 | |||
3009 | +++ lib/charmhelpers/fetch/giturl.py 2014-12-15 18:28:33 +0000 | |||
3010 | @@ -0,0 +1,48 @@ | |||
3011 | 1 | import os | ||
3012 | 2 | from charmhelpers.fetch import ( | ||
3013 | 3 | BaseFetchHandler, | ||
3014 | 4 | UnhandledSource | ||
3015 | 5 | ) | ||
3016 | 6 | from charmhelpers.core.host import mkdir | ||
3017 | 7 | |||
3018 | 8 | import six | ||
3019 | 9 | if six.PY3: | ||
3020 | 10 | raise ImportError('GitPython does not support Python 3') | ||
3021 | 11 | |||
3022 | 12 | try: | ||
3023 | 13 | from git import Repo | ||
3024 | 14 | except ImportError: | ||
3025 | 15 | from charmhelpers.fetch import apt_install | ||
3026 | 16 | apt_install("python-git") | ||
3027 | 17 | from git import Repo | ||
3028 | 18 | |||
3029 | 19 | |||
3030 | 20 | class GitUrlFetchHandler(BaseFetchHandler): | ||
3031 | 21 | """Handler for git branches via generic and github URLs""" | ||
3032 | 22 | def can_handle(self, source): | ||
3033 | 23 | url_parts = self.parse_url(source) | ||
3034 | 24 | # TODO (mattyw) no support for ssh git@ yet | ||
3035 | 25 | if url_parts.scheme not in ('http', 'https', 'git'): | ||
3036 | 26 | return False | ||
3037 | 27 | else: | ||
3038 | 28 | return True | ||
3039 | 29 | |||
3040 | 30 | def clone(self, source, dest, branch): | ||
3041 | 31 | if not self.can_handle(source): | ||
3042 | 32 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
3043 | 33 | |||
3044 | 34 | repo = Repo.clone_from(source, dest) | ||
3045 | 35 | repo.git.checkout(branch) | ||
3046 | 36 | |||
3047 | 37 | def install(self, source, branch="master"): | ||
3048 | 38 | url_parts = self.parse_url(source) | ||
3049 | 39 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
3050 | 40 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
3051 | 41 | branch_name) | ||
3052 | 42 | if not os.path.exists(dest_dir): | ||
3053 | 43 | mkdir(dest_dir, perms=0o755) | ||
3054 | 44 | try: | ||
3055 | 45 | self.clone(source, dest_dir, branch) | ||
3056 | 46 | except OSError as e: | ||
3057 | 47 | raise UnhandledSource(e.strerror) | ||
3058 | 48 | return dest_dir | ||
3059 | 0 | 49 | ||
3060 | === added directory 'lib/charmhelpers/payload' | |||
3061 | === added file 'lib/charmhelpers/payload/__init__.py' | |||
3062 | --- lib/charmhelpers/payload/__init__.py 1970-01-01 00:00:00 +0000 | |||
3063 | +++ lib/charmhelpers/payload/__init__.py 2014-12-15 18:28:33 +0000 | |||
3064 | @@ -0,0 +1,1 @@ | |||
3065 | 1 | "Tools for working with files injected into a charm just before deployment." | ||
3066 | 0 | 2 | ||
3067 | === added file 'lib/charmhelpers/payload/archive.py' | |||
3068 | --- lib/charmhelpers/payload/archive.py 1970-01-01 00:00:00 +0000 | |||
3069 | +++ lib/charmhelpers/payload/archive.py 2014-12-15 18:28:33 +0000 | |||
3070 | @@ -0,0 +1,57 @@ | |||
3071 | 1 | import os | ||
3072 | 2 | import tarfile | ||
3073 | 3 | import zipfile | ||
3074 | 4 | from charmhelpers.core import ( | ||
3075 | 5 | host, | ||
3076 | 6 | hookenv, | ||
3077 | 7 | ) | ||
3078 | 8 | |||
3079 | 9 | |||
3080 | 10 | class ArchiveError(Exception): | ||
3081 | 11 | pass | ||
3082 | 12 | |||
3083 | 13 | |||
3084 | 14 | def get_archive_handler(archive_name): | ||
3085 | 15 | if os.path.isfile(archive_name): | ||
3086 | 16 | if tarfile.is_tarfile(archive_name): | ||
3087 | 17 | return extract_tarfile | ||
3088 | 18 | elif zipfile.is_zipfile(archive_name): | ||
3089 | 19 | return extract_zipfile | ||
3090 | 20 | else: | ||
3091 | 21 | # look at the file name | ||
3092 | 22 | for ext in ('.tar', '.tar.gz', '.tgz', 'tar.bz2', '.tbz2', '.tbz'): | ||
3093 | 23 | if archive_name.endswith(ext): | ||
3094 | 24 | return extract_tarfile | ||
3095 | 25 | for ext in ('.zip', '.jar'): | ||
3096 | 26 | if archive_name.endswith(ext): | ||
3097 | 27 | return extract_zipfile | ||
3098 | 28 | |||
3099 | 29 | |||
3100 | 30 | def archive_dest_default(archive_name): | ||
3101 | 31 | archive_file = os.path.basename(archive_name) | ||
3102 | 32 | return os.path.join(hookenv.charm_dir(), "archives", archive_file) | ||
3103 | 33 | |||
3104 | 34 | |||
3105 | 35 | def extract(archive_name, destpath=None): | ||
3106 | 36 | handler = get_archive_handler(archive_name) | ||
3107 | 37 | if handler: | ||
3108 | 38 | if not destpath: | ||
3109 | 39 | destpath = archive_dest_default(archive_name) | ||
3110 | 40 | if not os.path.isdir(destpath): | ||
3111 | 41 | host.mkdir(destpath) | ||
3112 | 42 | handler(archive_name, destpath) | ||
3113 | 43 | return destpath | ||
3114 | 44 | else: | ||
3115 | 45 | raise ArchiveError("No handler for archive") | ||
3116 | 46 | |||
3117 | 47 | |||
3118 | 48 | def extract_tarfile(archive_name, destpath): | ||
3119 | 49 | "Unpack a tar archive, optionally compressed" | ||
3120 | 50 | archive = tarfile.open(archive_name) | ||
3121 | 51 | archive.extractall(destpath) | ||
3122 | 52 | |||
3123 | 53 | |||
3124 | 54 | def extract_zipfile(archive_name, destpath): | ||
3125 | 55 | "Unpack a zip file" | ||
3126 | 56 | archive = zipfile.ZipFile(archive_name) | ||
3127 | 57 | archive.extractall(destpath) | ||
3128 | 0 | 58 | ||
3129 | === added file 'lib/charmhelpers/payload/execd.py' | |||
3130 | --- lib/charmhelpers/payload/execd.py 1970-01-01 00:00:00 +0000 | |||
3131 | +++ lib/charmhelpers/payload/execd.py 2014-12-15 18:28:33 +0000 | |||
3132 | @@ -0,0 +1,50 @@ | |||
3133 | 1 | #!/usr/bin/env python | ||
3134 | 2 | |||
3135 | 3 | import os | ||
3136 | 4 | import sys | ||
3137 | 5 | import subprocess | ||
3138 | 6 | from charmhelpers.core import hookenv | ||
3139 | 7 | |||
3140 | 8 | |||
3141 | 9 | def default_execd_dir(): | ||
3142 | 10 | return os.path.join(os.environ['CHARM_DIR'], 'exec.d') | ||
3143 | 11 | |||
3144 | 12 | |||
3145 | 13 | def execd_module_paths(execd_dir=None): | ||
3146 | 14 | """Generate a list of full paths to modules within execd_dir.""" | ||
3147 | 15 | if not execd_dir: | ||
3148 | 16 | execd_dir = default_execd_dir() | ||
3149 | 17 | |||
3150 | 18 | if not os.path.exists(execd_dir): | ||
3151 | 19 | return | ||
3152 | 20 | |||
3153 | 21 | for subpath in os.listdir(execd_dir): | ||
3154 | 22 | module = os.path.join(execd_dir, subpath) | ||
3155 | 23 | if os.path.isdir(module): | ||
3156 | 24 | yield module | ||
3157 | 25 | |||
3158 | 26 | |||
3159 | 27 | def execd_submodule_paths(command, execd_dir=None): | ||
3160 | 28 | """Generate a list of full paths to the specified command within exec_dir. | ||
3161 | 29 | """ | ||
3162 | 30 | for module_path in execd_module_paths(execd_dir): | ||
3163 | 31 | path = os.path.join(module_path, command) | ||
3164 | 32 | if os.access(path, os.X_OK) and os.path.isfile(path): | ||
3165 | 33 | yield path | ||
3166 | 34 | |||
3167 | 35 | |||
3168 | 36 | def execd_run(command, execd_dir=None, die_on_error=False, stderr=None): | ||
3169 | 37 | """Run command for each module within execd_dir which defines it.""" | ||
3170 | 38 | for submodule_path in execd_submodule_paths(command, execd_dir): | ||
3171 | 39 | try: | ||
3172 | 40 | subprocess.check_call(submodule_path, shell=True, stderr=stderr) | ||
3173 | 41 | except subprocess.CalledProcessError as e: | ||
3174 | 42 | hookenv.log("Error ({}) running {}. Output: {}".format( | ||
3175 | 43 | e.returncode, e.cmd, e.output)) | ||
3176 | 44 | if die_on_error: | ||
3177 | 45 | sys.exit(e.returncode) | ||
3178 | 46 | |||
3179 | 47 | |||
3180 | 48 | def execd_preinstall(execd_dir=None): | ||
3181 | 49 | """Run charm-pre-install for each module within execd_dir.""" | ||
3182 | 50 | execd_run('charm-pre-install', execd_dir=execd_dir) | ||
3183 | 0 | 51 | ||
3184 | === added file 'scripts/charm_helpers_sync.py' | |||
3185 | --- scripts/charm_helpers_sync.py 1970-01-01 00:00:00 +0000 | |||
3186 | +++ scripts/charm_helpers_sync.py 2014-12-15 18:28:33 +0000 | |||
3187 | @@ -0,0 +1,223 @@ | |||
3188 | 1 | #!/usr/bin/env python | ||
3189 | 2 | # Copyright 2013 Canonical Ltd. | ||
3190 | 3 | |||
3191 | 4 | # Authors: | ||
3192 | 5 | # Adam Gandelman <adamg@ubuntu.com> | ||
3193 | 6 | |||
3194 | 7 | import logging | ||
3195 | 8 | import optparse | ||
3196 | 9 | import os | ||
3197 | 10 | import subprocess | ||
3198 | 11 | import shutil | ||
3199 | 12 | import sys | ||
3200 | 13 | import tempfile | ||
3201 | 14 | import yaml | ||
3202 | 15 | |||
3203 | 16 | from fnmatch import fnmatch | ||
3204 | 17 | |||
3205 | 18 | CHARM_HELPERS_BRANCH = 'lp:charm-helpers' | ||
3206 | 19 | |||
3207 | 20 | |||
3208 | 21 | def parse_config(conf_file): | ||
3209 | 22 | if not os.path.isfile(conf_file): | ||
3210 | 23 | logging.error('Invalid config file: %s.' % conf_file) | ||
3211 | 24 | return False | ||
3212 | 25 | return yaml.load(open(conf_file).read()) | ||
3213 | 26 | |||
3214 | 27 | |||
3215 | 28 | def clone_helpers(work_dir, branch): | ||
3216 | 29 | dest = os.path.join(work_dir, 'charm-helpers') | ||
3217 | 30 | logging.info('Checking out %s to %s.' % (branch, dest)) | ||
3218 | 31 | cmd = ['bzr', 'branch', branch, dest] | ||
3219 | 32 | subprocess.check_call(cmd) | ||
3220 | 33 | return dest | ||
3221 | 34 | |||
3222 | 35 | |||
3223 | 36 | def _module_path(module): | ||
3224 | 37 | return os.path.join(*module.split('.')) | ||
3225 | 38 | |||
3226 | 39 | |||
3227 | 40 | def _src_path(src, module): | ||
3228 | 41 | return os.path.join(src, 'charmhelpers', _module_path(module)) | ||
3229 | 42 | |||
3230 | 43 | |||
3231 | 44 | def _dest_path(dest, module): | ||
3232 | 45 | return os.path.join(dest, _module_path(module)) | ||
3233 | 46 | |||
3234 | 47 | |||
3235 | 48 | def _is_pyfile(path): | ||
3236 | 49 | return os.path.isfile(path + '.py') | ||
3237 | 50 | |||
3238 | 51 | |||
3239 | 52 | def ensure_init(path): | ||
3240 | 53 | ''' | ||
3241 | 54 | ensure directories leading up to path are importable, omitting | ||
3242 | 55 | parent directory, eg path='/hooks/helpers/foo'/: | ||
3243 | 56 | hooks/ | ||
3244 | 57 | hooks/helpers/__init__.py | ||
3245 | 58 | hooks/helpers/foo/__init__.py | ||
3246 | 59 | ''' | ||
3247 | 60 | for d, dirs, files in os.walk(os.path.join(*path.split('/')[:2])): | ||
3248 | 61 | _i = os.path.join(d, '__init__.py') | ||
3249 | 62 | if not os.path.exists(_i): | ||
3250 | 63 | logging.info('Adding missing __init__.py: %s' % _i) | ||
3251 | 64 | open(_i, 'wb').close() | ||
3252 | 65 | |||
3253 | 66 | |||
3254 | 67 | def sync_pyfile(src, dest): | ||
3255 | 68 | src = src + '.py' | ||
3256 | 69 | src_dir = os.path.dirname(src) | ||
3257 | 70 | logging.info('Syncing pyfile: %s -> %s.' % (src, dest)) | ||
3258 | 71 | if not os.path.exists(dest): | ||
3259 | 72 | os.makedirs(dest) | ||
3260 | 73 | shutil.copy(src, dest) | ||
3261 | 74 | if os.path.isfile(os.path.join(src_dir, '__init__.py')): | ||
3262 | 75 | shutil.copy(os.path.join(src_dir, '__init__.py'), | ||
3263 | 76 | dest) | ||
3264 | 77 | ensure_init(dest) | ||
3265 | 78 | |||
3266 | 79 | |||
3267 | 80 | def get_filter(opts=None): | ||
3268 | 81 | opts = opts or [] | ||
3269 | 82 | if 'inc=*' in opts: | ||
3270 | 83 | # do not filter any files, include everything | ||
3271 | 84 | return None | ||
3272 | 85 | |||
3273 | 86 | def _filter(dir, ls): | ||
3274 | 87 | incs = [opt.split('=').pop() for opt in opts if 'inc=' in opt] | ||
3275 | 88 | _filter = [] | ||
3276 | 89 | for f in ls: | ||
3277 | 90 | _f = os.path.join(dir, f) | ||
3278 | 91 | |||
3279 | 92 | if not os.path.isdir(_f) and not _f.endswith('.py') and incs: | ||
3280 | 93 | if True not in [fnmatch(_f, inc) for inc in incs]: | ||
3281 | 94 | logging.debug('Not syncing %s, does not match include ' | ||
3282 | 95 | 'filters (%s)' % (_f, incs)) | ||
3283 | 96 | _filter.append(f) | ||
3284 | 97 | else: | ||
3285 | 98 | logging.debug('Including file, which matches include ' | ||
3286 | 99 | 'filters (%s): %s' % (incs, _f)) | ||
3287 | 100 | elif (os.path.isfile(_f) and not _f.endswith('.py')): | ||
3288 | 101 | logging.debug('Not syncing file: %s' % f) | ||
3289 | 102 | _filter.append(f) | ||
3290 | 103 | elif (os.path.isdir(_f) and not | ||
3291 | 104 | os.path.isfile(os.path.join(_f, '__init__.py'))): | ||
3292 | 105 | logging.debug('Not syncing directory: %s' % f) | ||
3293 | 106 | _filter.append(f) | ||
3294 | 107 | return _filter | ||
3295 | 108 | return _filter | ||
3296 | 109 | |||
3297 | 110 | |||
3298 | 111 | def sync_directory(src, dest, opts=None): | ||
3299 | 112 | if os.path.exists(dest): | ||
3300 | 113 | logging.debug('Removing existing directory: %s' % dest) | ||
3301 | 114 | shutil.rmtree(dest) | ||
3302 | 115 | logging.info('Syncing directory: %s -> %s.' % (src, dest)) | ||
3303 | 116 | |||
3304 | 117 | shutil.copytree(src, dest, ignore=get_filter(opts)) | ||
3305 | 118 | ensure_init(dest) | ||
3306 | 119 | |||
3307 | 120 | |||
3308 | 121 | def sync(src, dest, module, opts=None): | ||
3309 | 122 | if os.path.isdir(_src_path(src, module)): | ||
3310 | 123 | sync_directory(_src_path(src, module), _dest_path(dest, module), opts) | ||
3311 | 124 | elif _is_pyfile(_src_path(src, module)): | ||
3312 | 125 | sync_pyfile(_src_path(src, module), | ||
3313 | 126 | os.path.dirname(_dest_path(dest, module))) | ||
3314 | 127 | else: | ||
3315 | 128 | logging.warn('Could not sync: %s. Neither a pyfile or directory, ' | ||
3316 | 129 | 'does it even exist?' % module) | ||
3317 | 130 | |||
3318 | 131 | |||
3319 | 132 | def parse_sync_options(options): | ||
3320 | 133 | if not options: | ||
3321 | 134 | return [] | ||
3322 | 135 | return options.split(',') | ||
3323 | 136 | |||
3324 | 137 | |||
3325 | 138 | def extract_options(inc, global_options=None): | ||
3326 | 139 | global_options = global_options or [] | ||
3327 | 140 | if global_options and isinstance(global_options, basestring): | ||
3328 | 141 | global_options = [global_options] | ||
3329 | 142 | if '|' not in inc: | ||
3330 | 143 | return (inc, global_options) | ||
3331 | 144 | inc, opts = inc.split('|') | ||
3332 | 145 | return (inc, parse_sync_options(opts) + global_options) | ||
3333 | 146 | |||
3334 | 147 | |||
3335 | 148 | def sync_helpers(include, src, dest, options=None): | ||
3336 | 149 | if not os.path.isdir(dest): | ||
3337 | 150 | os.mkdir(dest) | ||
3338 | 151 | |||
3339 | 152 | global_options = parse_sync_options(options) | ||
3340 | 153 | |||
3341 | 154 | for inc in include: | ||
3342 | 155 | if isinstance(inc, str): | ||
3343 | 156 | inc, opts = extract_options(inc, global_options) | ||
3344 | 157 | sync(src, dest, inc, opts) | ||
3345 | 158 | elif isinstance(inc, dict): | ||
3346 | 159 | # could also do nested dicts here. | ||
3347 | 160 | for k, v in inc.iteritems(): | ||
3348 | 161 | if isinstance(v, list): | ||
3349 | 162 | for m in v: | ||
3350 | 163 | inc, opts = extract_options(m, global_options) | ||
3351 | 164 | sync(src, dest, '%s.%s' % (k, inc), opts) | ||
3352 | 165 | |||
3353 | 166 | if __name__ == '__main__': | ||
3354 | 167 | parser = optparse.OptionParser() | ||
3355 | 168 | parser.add_option('-c', '--config', action='store', dest='config', | ||
3356 | 169 | default=None, help='helper config file') | ||
3357 | 170 | parser.add_option('-D', '--debug', action='store_true', dest='debug', | ||
3358 | 171 | default=False, help='debug') | ||
3359 | 172 | parser.add_option('-b', '--branch', action='store', dest='branch', | ||
3360 | 173 | help='charm-helpers bzr branch (overrides config)') | ||
3361 | 174 | parser.add_option('-d', '--destination', action='store', dest='dest_dir', | ||
3362 | 175 | help='sync destination dir (overrides config)') | ||
3363 | 176 | (opts, args) = parser.parse_args() | ||
3364 | 177 | |||
3365 | 178 | if opts.debug: | ||
3366 | 179 | logging.basicConfig(level=logging.DEBUG) | ||
3367 | 180 | else: | ||
3368 | 181 | logging.basicConfig(level=logging.INFO) | ||
3369 | 182 | |||
3370 | 183 | if opts.config: | ||
3371 | 184 | logging.info('Loading charm helper config from %s.' % opts.config) | ||
3372 | 185 | config = parse_config(opts.config) | ||
3373 | 186 | if not config: | ||
3374 | 187 | logging.error('Could not parse config from %s.' % opts.config) | ||
3375 | 188 | sys.exit(1) | ||
3376 | 189 | else: | ||
3377 | 190 | config = {} | ||
3378 | 191 | |||
3379 | 192 | if 'branch' not in config: | ||
3380 | 193 | config['branch'] = CHARM_HELPERS_BRANCH | ||
3381 | 194 | if opts.branch: | ||
3382 | 195 | config['branch'] = opts.branch | ||
3383 | 196 | if opts.dest_dir: | ||
3384 | 197 | config['destination'] = opts.dest_dir | ||
3385 | 198 | |||
3386 | 199 | if 'destination' not in config: | ||
3387 | 200 | logging.error('No destination dir. specified as option or config.') | ||
3388 | 201 | sys.exit(1) | ||
3389 | 202 | |||
3390 | 203 | if 'include' not in config: | ||
3391 | 204 | if not args: | ||
3392 | 205 | logging.error('No modules to sync specified as option or config.') | ||
3393 | 206 | sys.exit(1) | ||
3394 | 207 | config['include'] = [] | ||
3395 | 208 | [config['include'].append(a) for a in args] | ||
3396 | 209 | |||
3397 | 210 | sync_options = None | ||
3398 | 211 | if 'options' in config: | ||
3399 | 212 | sync_options = config['options'] | ||
3400 | 213 | tmpd = tempfile.mkdtemp() | ||
3401 | 214 | try: | ||
3402 | 215 | checkout = clone_helpers(tmpd, config['branch']) | ||
3403 | 216 | sync_helpers(config['include'], checkout, config['destination'], | ||
3404 | 217 | options=sync_options) | ||
3405 | 218 | except Exception, e: | ||
3406 | 219 | logging.error("Could not sync: %s" % e) | ||
3407 | 220 | raise e | ||
3408 | 221 | finally: | ||
3409 | 222 | logging.debug('Cleaning up %s' % tmpd) | ||
3410 | 223 | shutil.rmtree(tmpd) | ||
3411 | 0 | 224 | ||
3412 | === added file 'tests/10-deploy-and-upgrade' | |||
3413 | --- tests/10-deploy-and-upgrade 1970-01-01 00:00:00 +0000 | |||
3414 | +++ tests/10-deploy-and-upgrade 2014-12-15 18:28:33 +0000 | |||
3415 | @@ -0,0 +1,78 @@ | |||
3416 | 1 | #!/usr/bin/env python3 | ||
3417 | 2 | |||
3418 | 3 | import amulet | ||
3419 | 4 | import requests | ||
3420 | 5 | import unittest | ||
3421 | 6 | |||
3422 | 7 | |||
3423 | 8 | class TestDeployment(unittest.TestCase): | ||
3424 | 9 | @classmethod | ||
3425 | 10 | def setUpClass(cls): | ||
3426 | 11 | cls.deployment = amulet.Deployment(series='trusty') | ||
3427 | 12 | |||
3428 | 13 | mw_config = { 'name': 'MariaDB Test'} | ||
3429 | 14 | |||
3430 | 15 | cls.deployment.add('mariadb') | ||
3431 | 16 | cls.deployment.add('mediawiki') | ||
3432 | 17 | cls.deployment.configure('mediawiki', mw_config) | ||
3433 | 18 | cls.deployment.relate('mediawiki:db', 'mariadb:db') | ||
3434 | 19 | cls.deployment.expose('mediawiki') | ||
3435 | 20 | |||
3436 | 21 | |||
3437 | 22 | try: | ||
3438 | 23 | cls.deployment.setup(timeout=1200) | ||
3439 | 24 | cls.deployment.sentry.wait() | ||
3440 | 25 | except amulet.helpers.TimeoutError: | ||
3441 | 26 | amulet.raise_status(amulet.SKIP, msg="Environment wasn't stood up in time") | ||
3442 | 27 | except: | ||
3443 | 28 | raise | ||
3444 | 29 | |||
3445 | 30 | ''' | ||
3446 | 31 | test_relation: Verify the credentials being sent over the wire were valid | ||
3447 | 32 | when attempting to verify the MariaDB Service Status | ||
3448 | 33 | ''' | ||
3449 | 34 | def test_credentials(self): | ||
3450 | 35 | dbunit = self.deployment.sentry.unit['mariadb/0'] | ||
3451 | 36 | db_relation = dbunit.relation('db', 'mediawiki:db') | ||
3452 | 37 | db_ip = db_relation['host'] | ||
3453 | 38 | db_user = db_relation['user'] | ||
3454 | 39 | db_pass = db_relation['password'] | ||
3455 | 40 | ctmp = 'mysqladmin status -h {0} -u {1} --password={2}' | ||
3456 | 41 | cmd = ctmp.format(db_ip, db_user, db_pass) | ||
3457 | 42 | |||
3458 | 43 | output, code = dbunit.run(cmd) | ||
3459 | 44 | if code != 0: | ||
3460 | 45 | message = 'Unable to get status of the mariadb serverat %s' % db_ip | ||
3461 | 46 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3462 | 47 | |||
3463 | 48 | ''' | ||
3464 | 49 | test_wiki: Verify Mediawiki setup was successful with MariaDB. No page will | ||
3465 | 50 | be available if setup did not complete | ||
3466 | 51 | ''' | ||
3467 | 52 | def test_wiki(self): | ||
3468 | 53 | wikiunit = self.deployment.sentry.unit['mediawiki/0'] | ||
3469 | 54 | wiki_url = "http://{}".format(wikiunit.info['public-address']) | ||
3470 | 55 | response = requests.get(wiki_url) | ||
3471 | 56 | response.raise_for_status() | ||
3472 | 57 | |||
3473 | 58 | |||
3474 | 59 | def test_enterprise_eval(self): | ||
3475 | 60 | self.deployment.configure('mariadb', {'enterprise-eula': True, | ||
3476 | 61 | 'source': 'deb https://charlesbutler:foobarbaz@code.mariadb.com/mariadb-enterprise/10.0/repo/ubuntu trusty main'}) | ||
3477 | 62 | |||
3478 | 63 | # Ensure the bintar was relocated | ||
3479 | 64 | dbunit = self.deployment.sentry.unit['mariadb/0'] | ||
3480 | 65 | |||
3481 | 66 | try: | ||
3482 | 67 | dbunit.directory_stat('/usr/local/mysql') | ||
3483 | 68 | amulet.raise_status(amulet.SKIP, 'bintar directory found, uncertain results ahead') | ||
3484 | 69 | except: | ||
3485 | 70 | # this is what we want to happen | ||
3486 | 71 | pass | ||
3487 | 72 | |||
3488 | 73 | # re-run the test after in-place upgrade | ||
3489 | 74 | self.test_credentials() | ||
3490 | 75 | |||
3491 | 76 | |||
3492 | 77 | if __name__ == '__main__': | ||
3493 | 78 | unittest.main() | ||
3494 | 0 | 79 | ||
3495 | === removed file 'tests/10-deploy-test.py' | |||
3496 | --- tests/10-deploy-test.py 2014-11-12 23:12:00 +0000 | |||
3497 | +++ tests/10-deploy-test.py 1970-01-01 00:00:00 +0000 | |||
3498 | @@ -1,90 +0,0 @@ | |||
3499 | 1 | #!/usr/bin/python3 | ||
3500 | 2 | |||
3501 | 3 | # This amulet code is to test the mariadb charm. | ||
3502 | 4 | |||
3503 | 5 | import amulet | ||
3504 | 6 | import requests | ||
3505 | 7 | |||
3506 | 8 | # The number of seconds to wait for Juju to set up the environment. | ||
3507 | 9 | seconds = 1200 | ||
3508 | 10 | |||
3509 | 11 | # The mediawiki configuration to test. | ||
3510 | 12 | mediawiki_configuration = { | ||
3511 | 13 | 'name': 'MariaDB test' | ||
3512 | 14 | } | ||
3513 | 15 | |||
3514 | 16 | d = amulet.Deployment() | ||
3515 | 17 | |||
3516 | 18 | # Add the mediawiki charm to the deployment. | ||
3517 | 19 | d.add('mediawiki') | ||
3518 | 20 | # Add the MariaDB charm to the deployment. | ||
3519 | 21 | d.add('mariadb', charm='lp:~dbart/charms/trusty/mariadb/trunk') | ||
3520 | 22 | # Configure the mediawiki charm. | ||
3521 | 23 | d.configure('mediawiki', mediawiki_configuration) | ||
3522 | 24 | # Relate the mediawiki and mariadb charms. | ||
3523 | 25 | d.relate('mediawiki:db', 'mariadb:db') | ||
3524 | 26 | # Expose the open ports on mediawiki. | ||
3525 | 27 | d.expose('mediawiki') | ||
3526 | 28 | |||
3527 | 29 | # Deploy the environment and wait for it to setup. | ||
3528 | 30 | try: | ||
3529 | 31 | d.setup(timeout=seconds) | ||
3530 | 32 | d.sentry.wait(seconds) | ||
3531 | 33 | except amulet.helpers.TimeoutError: | ||
3532 | 34 | message = 'The environment did not setup in %d seconds.' % seconds | ||
3533 | 35 | # The SKIP status enables skip or fail the test based on configuration. | ||
3534 | 36 | amulet.raise_status(amulet.SKIP, msg=message) | ||
3535 | 37 | except: | ||
3536 | 38 | raise | ||
3537 | 39 | |||
3538 | 40 | # Get the sentry unit for mariadb. | ||
3539 | 41 | mariadb_unit = d.sentry.unit['mariadb/0'] | ||
3540 | 42 | |||
3541 | 43 | # Get the sentry unit for mediawiki. | ||
3542 | 44 | mediawiki_unit = d.sentry.unit['mediawiki/0'] | ||
3543 | 45 | |||
3544 | 46 | # Get the public address for the system running the mediawiki charm. | ||
3545 | 47 | mediawiki_address = mediawiki_unit.info['public-address'] | ||
3546 | 48 | |||
3547 | 49 | ############################################################################### | ||
3548 | 50 | ## Verify MariaDB | ||
3549 | 51 | ############################################################################### | ||
3550 | 52 | # Verify that mediawiki was related to mariadb | ||
3551 | 53 | mediawiki_relation = mediawiki_unit.relation('db', 'mariadb:db') | ||
3552 | 54 | print('mediawiki relation to mariadb') | ||
3553 | 55 | for key, value in mediawiki_relation.items(): | ||
3554 | 56 | print(key, value) | ||
3555 | 57 | # Verify that mariadb was related to mediawiki | ||
3556 | 58 | mariadb_relation = mariadb_unit.relation('db', 'mediawiki:db') | ||
3557 | 59 | print('mariadb relation to mediawiki') | ||
3558 | 60 | for key, value in mariadb_relation.items(): | ||
3559 | 61 | print(key, value) | ||
3560 | 62 | # Get the db_host from the mediawiki relation to mariadb | ||
3561 | 63 | mariadb_ip = mariadb_relation['host'] | ||
3562 | 64 | # Get the user from the mediawiki relation to mariadb | ||
3563 | 65 | mariadb_user = mariadb_relation['user'] | ||
3564 | 66 | # Get the password from the mediawiki relation to mariadb | ||
3565 | 67 | mariadb_password = mariadb_relation['password'] | ||
3566 | 68 | # Create the command to get the mariadb status with username and password. | ||
3567 | 69 | command = '/usr/local/mysql/bin/mysqladmin status -h {0} -u {1} --password={2}'.format(mariadb_ip, | ||
3568 | 70 | mariadb_user, mariadb_password) | ||
3569 | 71 | print(command) | ||
3570 | 72 | output, code = mariadb_unit.run(command) | ||
3571 | 73 | print(output) | ||
3572 | 74 | if code != 0: | ||
3573 | 75 | message = 'Unable to get the status of mariadb server at %s' % mariadb_ip | ||
3574 | 76 | amulet.raise_status(amulet.FAIL, msg=message) | ||
3575 | 77 | |||
3576 | 78 | ############################################################################### | ||
3577 | 79 | ## Verify mediawiki | ||
3578 | 80 | ############################################################################### | ||
3579 | 81 | # Create a URL string to the mediawiki server. | ||
3580 | 82 | mediawiki_url = 'http://%s' % mediawiki_address | ||
3581 | 83 | print(mediawiki_url) | ||
3582 | 84 | # Get the mediawiki url with the authentication for guest. | ||
3583 | 85 | response = requests.get(mediawiki_url) | ||
3584 | 86 | # Raise an exception if response is not 200 OK. | ||
3585 | 87 | response.raise_for_status() | ||
3586 | 88 | |||
3587 | 89 | print('The MariaDB deploy test completed successfully.') | ||
3588 | 90 |
This looks good and works