Merge lp:~brad-marshall/charms/trusty/ntp/add-nrpe-checks into lp:charms/trusty/ntp
- Trusty Tahr (14.04)
- add-nrpe-checks
- Merge into trunk
Proposed by
Brad Marshall
Status: | Merged |
---|---|
Merged at revision: | 18 |
Proposed branch: | lp:~brad-marshall/charms/trusty/ntp/add-nrpe-checks |
Merge into: | lp:charms/trusty/ntp |
Diff against target: |
3925 lines (+3087/-116) 29 files modified
charm-helpers-sync.yaml (+1/-0) config.yaml (+23/-1) files/nagios/check_ntpd.pl (+154/-0) files/nagios/check_ntpmon.py (+361/-0) hooks/charmhelpers/__init__.py (+38/-0) hooks/charmhelpers/contrib/__init__.py (+15/-0) hooks/charmhelpers/contrib/charmsupport/__init__.py (+15/-0) hooks/charmhelpers/contrib/charmsupport/nrpe.py (+358/-0) hooks/charmhelpers/contrib/charmsupport/volumes.py (+175/-0) hooks/charmhelpers/contrib/templating/__init__.py (+15/-0) hooks/charmhelpers/contrib/templating/jinja.py (+25/-9) hooks/charmhelpers/core/__init__.py (+15/-0) hooks/charmhelpers/core/decorators.py (+57/-0) hooks/charmhelpers/core/fstab.py (+30/-12) hooks/charmhelpers/core/hookenv.py (+100/-19) hooks/charmhelpers/core/host.py (+127/-37) hooks/charmhelpers/core/services/__init__.py (+18/-0) hooks/charmhelpers/core/services/base.py (+329/-0) hooks/charmhelpers/core/services/helpers.py (+267/-0) hooks/charmhelpers/core/strutils.py (+42/-0) hooks/charmhelpers/core/sysctl.py (+56/-0) hooks/charmhelpers/core/templating.py (+68/-0) hooks/charmhelpers/core/unitdata.py (+477/-0) hooks/charmhelpers/fetch/__init__.py (+61/-18) hooks/charmhelpers/fetch/archiveurl.py (+115/-17) hooks/charmhelpers/fetch/bzrurl.py (+30/-2) hooks/charmhelpers/fetch/giturl.py (+71/-0) hooks/ntp_hooks.py (+39/-0) metadata.yaml (+5/-1) |
To merge this branch: | bzr merge lp:~brad-marshall/charms/trusty/ntp/add-nrpe-checks |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Marco Ceppi (community) | Approve | ||
Review via email: mp+253156@code.launchpad.net |
Commit message
Description of the change
Adds some basic nrpe checks for ntp.
To post a comment you must log in.
- 24. By Brad Marshall
-
[bradm] Add ntpmon checks from paulgear
- 25. By Brad Marshall
-
[bradm] Adding missed string
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === modified file 'charm-helpers-sync.yaml' | |||
2 | --- charm-helpers-sync.yaml 2014-08-05 05:12:15 +0000 | |||
3 | +++ charm-helpers-sync.yaml 2015-03-23 00:51:45 +0000 | |||
4 | @@ -4,3 +4,4 @@ | |||
5 | 4 | - core | 4 | - core |
6 | 5 | - fetch | 5 | - fetch |
7 | 6 | - contrib.templating.jinja | 6 | - contrib.templating.jinja |
8 | 7 | - contrib.charmsupport | ||
9 | 7 | 8 | ||
10 | === modified file 'config.yaml' | |||
11 | --- config.yaml 2014-06-20 14:08:13 +0000 | |||
12 | +++ config.yaml 2015-03-23 00:51:45 +0000 | |||
13 | @@ -1,5 +1,27 @@ | |||
14 | 1 | options: | 1 | options: |
15 | 2 | source: | 2 | source: |
17 | 3 | default: | 3 | default: "" |
18 | 4 | type: string | 4 | type: string |
19 | 5 | description: Space separated list of NTP servers to use as source for time. | 5 | description: Space separated list of NTP servers to use as source for time. |
20 | 6 | nagios_context: | ||
21 | 7 | default: "juju" | ||
22 | 8 | type: string | ||
23 | 9 | description: | | ||
24 | 10 | Used by the nrpe-external-master subordinate charm. | ||
25 | 11 | A string that will be prepended to instance name to set the host name | ||
26 | 12 | in nagios. So for instance the hostname would be something like: | ||
27 | 13 | juju-myservice-0 | ||
28 | 14 | If you're running multiple environments with the same services in them | ||
29 | 15 | this allows you to differentiate between them. | ||
30 | 16 | nagios_servicegroups: | ||
31 | 17 | default: "" | ||
32 | 18 | type: string | ||
33 | 19 | description: | | ||
34 | 20 | A comma-separated list of nagios servicegroups. | ||
35 | 21 | If left empty, the nagios_context will be used as the servicegroup | ||
36 | 22 | nagios_ntpmon_checks: | ||
37 | 23 | default: "offset peers reachability sync" | ||
38 | 24 | type: string | ||
39 | 25 | description: | | ||
40 | 26 | A space-seperated list of nagios ntpmon checks to enable. | ||
41 | 27 | If left empty, no ntpmon checks will be used. | ||
42 | 6 | 28 | ||
43 | === added directory 'files' | |||
44 | === added directory 'files/nagios' | |||
45 | === added file 'files/nagios/check_ntpd.pl' | |||
46 | --- files/nagios/check_ntpd.pl 1970-01-01 00:00:00 +0000 | |||
47 | +++ files/nagios/check_ntpd.pl 2015-03-23 00:51:45 +0000 | |||
48 | @@ -0,0 +1,154 @@ | |||
49 | 1 | #!/usr/bin/perl -w | ||
50 | 2 | # Script from http://exchange.nagios.org/directory/Plugins/Network-Protocols/NTP-and-Time/check_ntpd/details | ||
51 | 3 | |||
52 | 4 | use Getopt::Long; | ||
53 | 5 | use strict; | ||
54 | 6 | |||
55 | 7 | GetOptions( | ||
56 | 8 | "critical=i" => \(my $critical_threshold = '50'), | ||
57 | 9 | "warning=i" => \(my $warning_threshold = '75'), | ||
58 | 10 | "peer_critical=i" => \(my $peer_critical_threshold = '1'), | ||
59 | 11 | "peer_warning=i" => \(my $peer_warning_threshold = '2'), | ||
60 | 12 | "help" => \&display_help, | ||
61 | 13 | ); | ||
62 | 14 | |||
63 | 15 | my $ntpq_path = `/usr/bin/which ntpq`; | ||
64 | 16 | $ntpq_path =~ s/\n//g; | ||
65 | 17 | my @server_list = `$ntpq_path -pn`; | ||
66 | 18 | my %server_health; | ||
67 | 19 | my $peer_count; | ||
68 | 20 | my $overall_health = 0; | ||
69 | 21 | my $good_count; | ||
70 | 22 | my $selected_primary; | ||
71 | 23 | my $selected_backup = 0; | ||
72 | 24 | |||
73 | 25 | # Cleanup server list | ||
74 | 26 | for(my $i = 0; $i < @server_list; $i++) { | ||
75 | 27 | if($server_list[$i] =~ /LOCAL/) { | ||
76 | 28 | splice(@server_list, $i, 1); | ||
77 | 29 | $i--; | ||
78 | 30 | } elsif($server_list[$i] =~ /^===/) { | ||
79 | 31 | splice(@server_list, $i, 1); | ||
80 | 32 | $i--; | ||
81 | 33 | } elsif($server_list[$i] =~ /jitter$/) { | ||
82 | 34 | splice(@server_list, $i, 1); | ||
83 | 35 | $i--; | ||
84 | 36 | } elsif($server_list[$i] =~ /^No association/) { | ||
85 | 37 | splice(@server_list, $i, 1); | ||
86 | 38 | $i--; | ||
87 | 39 | } | ||
88 | 40 | } | ||
89 | 41 | |||
90 | 42 | # Get number of peers | ||
91 | 43 | $peer_count = @server_list; | ||
92 | 44 | |||
93 | 45 | # Cycle through peers | ||
94 | 46 | for(my $i = 0; $i < @server_list; $i++) { | ||
95 | 47 | #split each element of the peer line | ||
96 | 48 | my @tmp_array = split(" ", $server_list[$i]); | ||
97 | 49 | |||
98 | 50 | # Check for first character of peer | ||
99 | 51 | # space = Discarded due to high stratum and/or failed sanity checks. | ||
100 | 52 | # x = Designated falseticker by the intersection algorithm. | ||
101 | 53 | # . = Culled from the end of the candidate list. | ||
102 | 54 | # - = Discarded by the clustering algorithm. | ||
103 | 55 | # + = Included in the final selection set. | ||
104 | 56 | # # = Selected for synchronization but distance exceeds maximum. | ||
105 | 57 | # * = Selected for synchronization. | ||
106 | 58 | # o = Selected for synchronization, pps signal in use. | ||
107 | 59 | if(substr($tmp_array[0], 0, 1) eq '*') { | ||
108 | 60 | $selected_primary = "true"; | ||
109 | 61 | } elsif(substr($tmp_array[0], 0, 1) eq '+') { | ||
110 | 62 | $selected_backup++; | ||
111 | 63 | } | ||
112 | 64 | |||
113 | 65 | $good_count = 0; | ||
114 | 66 | # Read in the octal number in column 6 | ||
115 | 67 | my $rearch = oct($tmp_array[6]); | ||
116 | 68 | |||
117 | 69 | # while $rearch is not 0 | ||
118 | 70 | while($rearch) { | ||
119 | 71 | # 1s place 0 or 1? | ||
120 | 72 | $good_count += $rearch % 2; | ||
121 | 73 | # Bit shift to the right | ||
122 | 74 | $rearch = $rearch >> 1; | ||
123 | 75 | } | ||
124 | 76 | |||
125 | 77 | # Calculate good packets received | ||
126 | 78 | $rearch = int(($good_count / 8) * 100); | ||
127 | 79 | |||
128 | 80 | # Set percentage in hash | ||
129 | 81 | $server_health{$tmp_array[0]} = $rearch; | ||
130 | 82 | } | ||
131 | 83 | |||
132 | 84 | # Cycle through hash and tally weighted average of peer health | ||
133 | 85 | while(my($key, $val) = each(%server_health)) { | ||
134 | 86 | $overall_health += $val * (1 / $peer_count); | ||
135 | 87 | } | ||
136 | 88 | |||
137 | 89 | ########################### Nagios Status checks ########################### | ||
138 | 90 | #if overall health is below critical threshold, crit | ||
139 | 91 | if($overall_health <= $critical_threshold) { | ||
140 | 92 | print_overall_health("Critical"); | ||
141 | 93 | print_server_list(); | ||
142 | 94 | exit 2; | ||
143 | 95 | } | ||
144 | 96 | |||
145 | 97 | #if overall health is below warning and above critical threshold, warn | ||
146 | 98 | if(($overall_health <= $warning_threshold) && ($overall_health > $critical_threshold)) { | ||
147 | 99 | print_overall_health("Warning"); | ||
148 | 100 | print_server_list(); | ||
149 | 101 | exit 1; | ||
150 | 102 | } | ||
151 | 103 | |||
152 | 104 | #if the number of peers is below the critical threshold, crit | ||
153 | 105 | if($peer_count <= $peer_critical_threshold) { | ||
154 | 106 | print_overall_health("Critical"); | ||
155 | 107 | print_server_list(); | ||
156 | 108 | exit 2; | ||
157 | 109 | #if the number of peers is below the warning threshold, warn | ||
158 | 110 | } elsif($peer_count <= $peer_warning_threshold) { | ||
159 | 111 | print_overall_health("Warning"); | ||
160 | 112 | print_server_list(); | ||
161 | 113 | exit 1; | ||
162 | 114 | } | ||
163 | 115 | |||
164 | 116 | #check to make sure we have one backup and one selected ntp server | ||
165 | 117 | #if there is no primary ntp server selected, crit | ||
166 | 118 | if($selected_primary ne "true") { | ||
167 | 119 | print_overall_health("Critical"); | ||
168 | 120 | print_server_list(); | ||
169 | 121 | exit 2; | ||
170 | 122 | #if there is no backup ntp server selected, warn | ||
171 | 123 | } elsif($selected_backup < 1) { | ||
172 | 124 | print_overall_health("Warning"); | ||
173 | 125 | print_server_list(); | ||
174 | 126 | exit 1; | ||
175 | 127 | } | ||
176 | 128 | |||
177 | 129 | print_overall_health("OK"); | ||
178 | 130 | print_server_list(); | ||
179 | 131 | exit 0; | ||
180 | 132 | |||
181 | 133 | sub print_server_list { | ||
182 | 134 | print "---------------------------\n"; | ||
183 | 135 | while(my($key, $val) = each(%server_health)) { | ||
184 | 136 | print "Received " . $val . "% of the traffic from " . $key . "\n"; | ||
185 | 137 | } | ||
186 | 138 | } | ||
187 | 139 | |||
188 | 140 | sub print_overall_health { | ||
189 | 141 | print $_[0] . " - NTPd Health is " . $overall_health . "% with " . $peer_count . " peers.\n"; | ||
190 | 142 | } | ||
191 | 143 | |||
192 | 144 | sub display_help { | ||
193 | 145 | print "This nagios check is to determine the health of the NTPd client on the local system. It uses the reach attribute from 'ntpq -pn' to determine the health of each listed peer, and determines the average health based on the number of peers. For example, if there are 3 peers, and one peer has dropped 2 of the last 8 packets, it's health will be 75%. This will result in an overall health of about 92% ((100+100+75) / 3).\n"; | ||
194 | 146 | print "\n"; | ||
195 | 147 | print "Available Options:\n"; | ||
196 | 148 | print "\t--critical|-c <num>\t-Set the critical threshold for overall health (default:50)\n"; | ||
197 | 149 | print "\t--warning|-w <num>\t-Set the warning threshold for overall health (default:75)\n"; | ||
198 | 150 | print "\t--peer_critical <num>\t-Set the critical threshold for number of peers (default:1)\n"; | ||
199 | 151 | print "\t--peer_warning <num>\t-Set the warning threshold for number of peers (default:2)\n"; | ||
200 | 152 | print "\t--help|-h\t\t-display this help\n"; | ||
201 | 153 | exit 0; | ||
202 | 154 | } | ||
203 | 0 | 155 | ||
204 | === added file 'files/nagios/check_ntpmon.py' | |||
205 | --- files/nagios/check_ntpmon.py 1970-01-01 00:00:00 +0000 | |||
206 | +++ files/nagios/check_ntpmon.py 2015-03-23 00:51:45 +0000 | |||
207 | @@ -0,0 +1,361 @@ | |||
208 | 1 | #!/usr/bin/python | ||
209 | 2 | # | ||
210 | 3 | # Author: Paul Gear | ||
211 | 4 | # Copyright: (c) 2015 Gear Consulting Pty Ltd <http://libertysys.com.au/> | ||
212 | 5 | # License: GPLv3 <http://www.gnu.org/licenses/gpl.html> | ||
213 | 6 | # Description: NTP metrics as a Nagios check. | ||
214 | 7 | # | ||
215 | 8 | # This program is free software: you can redistribute it and/or modify it under | ||
216 | 9 | # the terms of the GNU General Public License as published by the Free Software | ||
217 | 10 | # Foundation, either version 3 of the License, or (at your option) any later | ||
218 | 11 | # version. | ||
219 | 12 | # | ||
220 | 13 | # This program is distributed in the hope that it will be useful, but WITHOUT | ||
221 | 14 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | ||
222 | 15 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more | ||
223 | 16 | # details. | ||
224 | 17 | # | ||
225 | 18 | # You should have received a copy of the GNU General Public License along with | ||
226 | 19 | # this program. If not, see <http://www.gnu.org/licenses/>. | ||
227 | 20 | # | ||
228 | 21 | |||
229 | 22 | import argparse | ||
230 | 23 | import re | ||
231 | 24 | import subprocess | ||
232 | 25 | import sys | ||
233 | 26 | import traceback | ||
234 | 27 | import warnings | ||
235 | 28 | |||
236 | 29 | |||
237 | 30 | def ishostnamey(name): | ||
238 | 31 | """Return true if the passed name is roughly hostnamey. NTP is rather casual about how it | ||
239 | 32 | reports hostnames and IP addresses, so we can't be too strict. This function simply tests | ||
240 | 33 | that all of the characters in the string are letters, digits, dash, or period.""" | ||
241 | 34 | return re.search(r'^[\w.-]*$', name) is not None and name.find('_') == -1 | ||
242 | 35 | |||
243 | 36 | |||
244 | 37 | def isipaddressy(name): | ||
245 | 38 | """Return true if the passed name is roughly IP addressy. NTP is rather casual about how it | ||
246 | 39 | reports hostnames and IP addresses, so we can't be too strict. This function simply tests | ||
247 | 40 | that all of the characters in the string are hexadecimal digits, period, or colon.""" | ||
248 | 41 | return re.search(r'^[0-9a-f.:]*$', name) is not None | ||
249 | 42 | |||
250 | 43 | |||
251 | 44 | class CheckNTPMon(object): | ||
252 | 45 | |||
253 | 46 | def __init__(self, | ||
254 | 47 | warnpeers=2, | ||
255 | 48 | okpeers=4, | ||
256 | 49 | warnoffset=10, | ||
257 | 50 | critoffset=50, | ||
258 | 51 | warnreach=75, | ||
259 | 52 | critreach=50): | ||
260 | 53 | |||
261 | 54 | self.warnpeers = warnpeers | ||
262 | 55 | self.okpeers = okpeers | ||
263 | 56 | self.warnoffset = warnoffset | ||
264 | 57 | self.critoffset = critoffset | ||
265 | 58 | self.warnreach = warnreach | ||
266 | 59 | self.critreach = critreach | ||
267 | 60 | |||
268 | 61 | def peers(self, n): | ||
269 | 62 | """Return 0 if the number of peers is OK | ||
270 | 63 | Return 1 if the number of peers is WARNING | ||
271 | 64 | Return 2 if the number of peers is CRITICAL""" | ||
272 | 65 | if n >= self.okpeers: | ||
273 | 66 | print "OK: %d usable peers" % n | ||
274 | 67 | return 0 | ||
275 | 68 | elif n < self.warnpeers: | ||
276 | 69 | print "CRITICAL: Too few peers (%d) - must be at least %d" % (n, self.warnpeers) | ||
277 | 70 | return 2 | ||
278 | 71 | else: | ||
279 | 72 | print "WARNING: Too few peers (%d) - should be at least %d" % (n, self.okpeers) | ||
280 | 73 | return 1 | ||
281 | 74 | |||
282 | 75 | def offset(self, offset): | ||
283 | 76 | """Return 0 if the offset is OK | ||
284 | 77 | Return 1 if the offset is WARNING | ||
285 | 78 | Return 2 if the offset is CRITICAL""" | ||
286 | 79 | if abs(offset) > self.critoffset: | ||
287 | 80 | print "CRITICAL: Offset too high (%g) - must be less than %g" % \ | ||
288 | 81 | (offset, self.critoffset) | ||
289 | 82 | return 2 | ||
290 | 83 | if abs(offset) > self.warnoffset: | ||
291 | 84 | print "WARNING: Offset too high (%g) - should be less than %g" % \ | ||
292 | 85 | (offset, self.warnoffset) | ||
293 | 86 | return 1 | ||
294 | 87 | else: | ||
295 | 88 | print "OK: Offset normal (%g)" % (offset) | ||
296 | 89 | return 0 | ||
297 | 90 | |||
298 | 91 | def reachability(self, percent): | ||
299 | 92 | """Return 0 if the reachability percentage is OK | ||
300 | 93 | Return 1 if the reachability percentage is warning | ||
301 | 94 | Return 2 if the reachability percentage is critical | ||
302 | 95 | Raise a ValueError if reachability is not a percentage""" | ||
303 | 96 | if percent < 0 or percent > 100: | ||
304 | 97 | raise ValueError('Value must be a percentage') | ||
305 | 98 | if percent <= self.critreach: | ||
306 | 99 | print "CRITICAL: Reachability too low (%g%%) - must be more than %g%%" % \ | ||
307 | 100 | (percent, self.critreach) | ||
308 | 101 | return 2 | ||
309 | 102 | elif percent <= self.warnreach: | ||
310 | 103 | print "WARNING: Reachability too low (%g%%) - should be more than %g%%" % \ | ||
311 | 104 | (percent, self.warnreach) | ||
312 | 105 | return 1 | ||
313 | 106 | else: | ||
314 | 107 | print "OK: Reachability normal (%g%%)" % (percent) | ||
315 | 108 | return 0 | ||
316 | 109 | |||
317 | 110 | def sync(self, synchost): | ||
318 | 111 | """Return 0 if the synchost is non-zero in length and is a roughly valid host identifier, return 2 otherwise.""" | ||
319 | 112 | synced = len(synchost) > 0 and (ishostnamey(synchost) or isipaddressy(synchost)) | ||
320 | 113 | if synced: | ||
321 | 114 | print "OK: time is in sync with %s" % (synchost) | ||
322 | 115 | else: | ||
323 | 116 | print "CRITICAL: no sync host selected" | ||
324 | 117 | return 0 if synced else 2 | ||
325 | 118 | |||
326 | 119 | |||
327 | 120 | class NTPPeers(object): | ||
328 | 121 | """Turn the peer lines returned by 'ntpq -pn' into a data structure usable for checks.""" | ||
329 | 122 | |||
330 | 123 | noiselines = [ | ||
331 | 124 | r'remote\s+refid\s+st\s+t\s+when\s+poll\s+reach\s+', | ||
332 | 125 | r'^=*$', | ||
333 | 126 | r'No association ID.s returned', | ||
334 | 127 | ] | ||
335 | 128 | ignorepeers = [".LOCL.", ".INIT.", ".XFAC."] | ||
336 | 129 | |||
337 | 130 | def isnoiseline(self, line): | ||
338 | 131 | for regex in self.noiselines: | ||
339 | 132 | if re.search(regex, line) is not None: | ||
340 | 133 | return True | ||
341 | 134 | return False | ||
342 | 135 | |||
343 | 136 | def shouldignore(self, fields, l): | ||
344 | 137 | if len(fields) != 10: | ||
345 | 138 | warnings.warn('Invalid ntpq peer line - there are %d fields: %s' % (len(fields), l)) | ||
346 | 139 | return True | ||
347 | 140 | if fields[1] in self.ignorepeers: | ||
348 | 141 | return True | ||
349 | 142 | if int(fields[2]) > 15: | ||
350 | 143 | return True | ||
351 | 144 | return False | ||
352 | 145 | |||
353 | 146 | def parsetally(self, tally, peerdata, offset): | ||
354 | 147 | """Parse the tally code and add the appropriate items to the peer data based on that code. | ||
355 | 148 | See the explanation of tally codes in the ntpq documentation for how these work: | ||
356 | 149 | - http://www.eecis.udel.edu/~mills/ntp/html/decode.html#peer | ||
357 | 150 | - http://www.eecis.udel.edu/~mills/ntp/html/ntpq.html | ||
358 | 151 | - http://psp2.ntp.org/bin/view/Support/TroubleshootingNTP | ||
359 | 152 | """ | ||
360 | 153 | if tally in ['*', 'o'] and 'syncpeer' not in self.ntpdata: | ||
361 | 154 | # this is our sync peer | ||
362 | 155 | self.ntpdata['syncpeer'] = peerdata['peer'] | ||
363 | 156 | self.ntpdata['offsetsyncpeer'] = offset | ||
364 | 157 | self.ntpdata['survivors'] += 1 | ||
365 | 158 | self.ntpdata['offsetsurvivors'] += offset | ||
366 | 159 | elif tally in ['+', '#']: | ||
367 | 160 | # valid peer | ||
368 | 161 | self.ntpdata['survivors'] += 1 | ||
369 | 162 | self.ntpdata['offsetsurvivors'] += offset | ||
370 | 163 | elif tally in [' ', 'x', '.', '-']: | ||
371 | 164 | # discarded peer | ||
372 | 165 | self.ntpdata['discards'] += 1 | ||
373 | 166 | self.ntpdata['offsetdiscards'] += offset | ||
374 | 167 | else: | ||
375 | 168 | self.ntpdata['unknown'] += 1 | ||
376 | 169 | return False | ||
377 | 170 | return True | ||
378 | 171 | |||
379 | 172 | def __init__(self, peerlines, check=None): | ||
380 | 173 | self.ntpdata = { | ||
381 | 174 | 'survivors': 0, | ||
382 | 175 | 'offsetsurvivors': 0, | ||
383 | 176 | 'discards': 0, | ||
384 | 177 | 'offsetdiscards': 0, | ||
385 | 178 | 'unknown': 0, | ||
386 | 179 | 'peers': 0, | ||
387 | 180 | 'offsetall': 0, | ||
388 | 181 | 'totalreach': 0, | ||
389 | 182 | } | ||
390 | 183 | self.check = check | ||
391 | 184 | |||
392 | 185 | for l in peerlines: | ||
393 | 186 | if self.isnoiseline(l): | ||
394 | 187 | continue | ||
395 | 188 | |||
396 | 189 | # first column is the tally field, the rest are whitespace-separated fields | ||
397 | 190 | tally = l[0] | ||
398 | 191 | fields = l[1:-1].split() | ||
399 | 192 | |||
400 | 193 | if self.shouldignore(fields, l): | ||
401 | 194 | continue | ||
402 | 195 | |||
403 | 196 | fieldnames = ['peer', 'refid', 'stratum', 'type', 'lastpoll', 'interval', 'reach', | ||
404 | 197 | 'delay', 'offset', 'jitter'] | ||
405 | 198 | peerdata = dict(zip(fieldnames, fields)) | ||
406 | 199 | |||
407 | 200 | offset = abs(float(peerdata['offset'])) | ||
408 | 201 | if not self.parsetally(tally, peerdata, offset): | ||
409 | 202 | warnings.warn('Unknown tally code detected - please report a bug: %s' % (l)) | ||
410 | 203 | continue | ||
411 | 204 | |||
412 | 205 | self.ntpdata['peers'] += 1 | ||
413 | 206 | self.ntpdata['offsetall'] += offset | ||
414 | 207 | |||
415 | 208 | # reachability - this counts the number of bits set in the reachability field | ||
416 | 209 | # (which is displayed in octal in the ntpq output) | ||
417 | 210 | # http://stackoverflow.com/questions/9829578/fast-way-of-counting-bits-in-python | ||
418 | 211 | self.ntpdata['totalreach'] += bin(int(peerdata['reach'], 8)).count("1") | ||
419 | 212 | |||
420 | 213 | # reachability as a percentage of the last 8 polls, across all peers | ||
421 | 214 | self.ntpdata['reachability'] = float(self.ntpdata['totalreach']) * 100 / self.ntpdata['peers'] / 8 | ||
422 | 215 | |||
423 | 216 | # average offsets | ||
424 | 217 | if self.ntpdata['survivors'] > 0: | ||
425 | 218 | self.ntpdata['averageoffsetsurvivors'] = \ | ||
426 | 219 | self.ntpdata['offsetsurvivors'] / self.ntpdata['survivors'] | ||
427 | 220 | if self.ntpdata['discards'] > 0: | ||
428 | 221 | self.ntpdata['averageoffsetdiscards'] = \ | ||
429 | 222 | self.ntpdata['offsetdiscards'] / self.ntpdata['discards'] | ||
430 | 223 | self.ntpdata['averageoffset'] = self.ntpdata['offsetall'] / self.ntpdata['peers'] | ||
431 | 224 | |||
432 | 225 | def dump(self): | ||
433 | 226 | if self.ntpdata.get('syncpeer'): | ||
434 | 227 | print "Synced to: %s, offset %g ms" % \ | ||
435 | 228 | (self.ntpdata['syncpeer'], self.ntpdata['offsetsyncpeer']) | ||
436 | 229 | else: | ||
437 | 230 | print "No remote sync peer" | ||
438 | 231 | print "%d total peers, average offset %g ms" % \ | ||
439 | 232 | (self.ntpdata['peers'], self.ntpdata['averageoffset']) | ||
440 | 233 | if self.ntpdata['survivors'] > 0: | ||
441 | 234 | print "%d good peers, average offset %g ms" % \ | ||
442 | 235 | (self.ntpdata['survivors'], self.ntpdata['averageoffsetsurvivors']) | ||
443 | 236 | if self.ntpdata['discards'] > 0: | ||
444 | 237 | print "%d discarded peers, average offset %g ms" % \ | ||
445 | 238 | (self.ntpdata['discards'], self.ntpdata['averageoffsetdiscards']) | ||
446 | 239 | print "Average reachability of all peers: %d%%" % (self.ntpdata['reachability']) | ||
447 | 240 | |||
448 | 241 | def check_peers(self, check=None): | ||
449 | 242 | """Check the number of usable peers""" | ||
450 | 243 | if check is None: | ||
451 | 244 | check = self.check if self.check else CheckNTPMon() | ||
452 | 245 | return check.peers(self.ntpdata['peers']) | ||
453 | 246 | |||
454 | 247 | def check_offset(self, check=None): | ||
455 | 248 | """Check the offset from the sync peer, returning critical, warning, | ||
456 | 249 | or OK based on the CheckNTPMon results. | ||
457 | 250 | If there is no sync peer, use the average offset of survivors instead. | ||
458 | 251 | If there are no survivors, use the average offset of discards instead, and return warning as a minimum. | ||
459 | 252 | If there are no discards, return critical. | ||
460 | 253 | """ | ||
461 | 254 | if check is None: | ||
462 | 255 | check = self.check if self.check else CheckNTPMon() | ||
463 | 256 | if 'offsetsyncpeer' in self.ntpdata: | ||
464 | 257 | return check.offset(self.ntpdata['offsetsyncpeer']) | ||
465 | 258 | if 'averageoffsetsurvivors' in self.ntpdata: | ||
466 | 259 | return check.offset(self.ntpdata['averageoffsetsurvivors']) | ||
467 | 260 | if 'averageoffsetdiscards' in self.ntpdata: | ||
468 | 261 | result = check.offset(self.ntpdata['averageoffsetdiscards']) | ||
469 | 262 | return 1 if result < 1 else result | ||
470 | 263 | else: | ||
471 | 264 | print "CRITICAL: No peers for which to check offset" | ||
472 | 265 | return 2 | ||
473 | 266 | |||
474 | 267 | def check_reachability(self, check=None): | ||
475 | 268 | """Check reachability of all peers""" | ||
476 | 269 | if check is None: | ||
477 | 270 | check = self.check if self.check else CheckNTPMon() | ||
478 | 271 | return check.reachability(self.ntpdata['reachability']) | ||
479 | 272 | |||
480 | 273 | def check_sync(self, check=None): | ||
481 | 274 | """Check whether host is in sync with a peer""" | ||
482 | 275 | if check is None: | ||
483 | 276 | check = self.check if self.check else CheckNTPMon() | ||
484 | 277 | if self.ntpdata.get('syncpeer') is None: | ||
485 | 278 | print "CRITICAL: No sync peer" | ||
486 | 279 | return 2 | ||
487 | 280 | return check.sync(self.ntpdata['syncpeer']) | ||
488 | 281 | |||
489 | 282 | def checks(self, methods=None, check=None): | ||
490 | 283 | ret = 0 | ||
491 | 284 | if not methods: | ||
492 | 285 | methods = [self.check_offset, self.check_peers, self.check_reachability, self.check_sync] | ||
493 | 286 | for method in methods: | ||
494 | 287 | check = method() | ||
495 | 288 | if ret < check: | ||
496 | 289 | ret = check | ||
497 | 290 | return ret | ||
498 | 291 | |||
499 | 292 | @staticmethod | ||
500 | 293 | def query(): | ||
501 | 294 | lines = None | ||
502 | 295 | try: | ||
503 | 296 | output = subprocess.check_output(["ntpq", "-pn"]) | ||
504 | 297 | lines = output.split("\n") | ||
505 | 298 | except: | ||
506 | 299 | traceback.print_exc(file=sys.stdout) | ||
507 | 300 | return lines | ||
508 | 301 | |||
509 | 302 | |||
510 | 303 | def main(): | ||
511 | 304 | methodnames = ['offset', 'peers', 'reachability', 'sync'] | ||
512 | 305 | options = { | ||
513 | 306 | 'warnpeers': [ 2, int, 'Minimum number of peers to be considered non-critical'], | ||
514 | 307 | 'okpeers': [ 4, int, 'Minimum number of peers to be considered OK'], | ||
515 | 308 | 'warnoffset': [ 10, float, 'Minimum offset to be considered warning'], | ||
516 | 309 | 'critoffset': [ 50, float, 'Minimum offset to be considered critical'], | ||
517 | 310 | 'warnreach': [ 75, float, 'Minimum peer reachability percentage to be considered OK'], | ||
518 | 311 | 'critreach': [ 50, float, 'Minimum peer reachability percentage to be considered non-crtical'], | ||
519 | 312 | } | ||
520 | 313 | |||
521 | 314 | # Create check ranges; will be used by parse_args to store options | ||
522 | 315 | checkntpmon = CheckNTPMon() | ||
523 | 316 | |||
524 | 317 | # parse command line | ||
525 | 318 | parser = argparse.ArgumentParser(description='Nagios NTP check incorporating the logic of NTPmon') | ||
526 | 319 | parser.add_argument('--check', choices=methodnames, | ||
527 | 320 | help='Select check to run; if omitted, run all checks and return the worst result.') | ||
528 | 321 | parser.add_argument('--debug', action='store_true', | ||
529 | 322 | help='Include "ntpq -pn" output and internal state dump along with check results.') | ||
530 | 323 | for o in options.keys(): | ||
531 | 324 | helptext = options[o][2] + ' (default: %d)' % (options[o][0]) | ||
532 | 325 | parser.add_argument('--' + o, default=options[o][0], help=helptext, type=options[o][1]) | ||
533 | 326 | args = parser.parse_args(namespace=checkntpmon) | ||
534 | 327 | |||
535 | 328 | # run ntpq | ||
536 | 329 | lines = NTPPeers.query() | ||
537 | 330 | if lines is None: | ||
538 | 331 | # Unknown result | ||
539 | 332 | print "Cannot get peers from ntpq." | ||
540 | 333 | print "Please check that an NTP server is installed and functional." | ||
541 | 334 | sys.exit(3) | ||
542 | 335 | |||
543 | 336 | # initialise our object with the results of ntpq and our preferred check thresholds | ||
544 | 337 | ntp = NTPPeers(lines, checkntpmon) | ||
545 | 338 | |||
546 | 339 | if args.debug: | ||
547 | 340 | print "\n".join(lines) | ||
548 | 341 | ntp.dump() | ||
549 | 342 | |||
550 | 343 | # work out which method to run | ||
551 | 344 | # (methods must be in the same order as methodnames above) | ||
552 | 345 | methods = [ntp.check_offset, ntp.check_peers, ntp.check_reachability, ntp.check_sync] | ||
553 | 346 | checkmethods = dict(zip(methodnames, methods)) | ||
554 | 347 | |||
555 | 348 | # if check argument is specified, run just that check | ||
556 | 349 | ret = 0 | ||
557 | 350 | if checkmethods.get(args.check): | ||
558 | 351 | method = checkmethods[args.check] | ||
559 | 352 | ret = method() | ||
560 | 353 | # else check all the methods | ||
561 | 354 | else: | ||
562 | 355 | ret = ntp.checks(methods) | ||
563 | 356 | |||
564 | 357 | sys.exit(ret) | ||
565 | 358 | |||
566 | 359 | if __name__ == "__main__": | ||
567 | 360 | main() | ||
568 | 361 | |||
569 | 0 | 362 | ||
570 | === modified file 'hooks/charmhelpers/__init__.py' | |||
571 | --- hooks/charmhelpers/__init__.py 2013-07-09 11:17:24 +0000 | |||
572 | +++ hooks/charmhelpers/__init__.py 2015-03-23 00:51:45 +0000 | |||
573 | @@ -0,0 +1,38 @@ | |||
574 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
575 | 2 | # | ||
576 | 3 | # This file is part of charm-helpers. | ||
577 | 4 | # | ||
578 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
579 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
580 | 7 | # published by the Free Software Foundation. | ||
581 | 8 | # | ||
582 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
583 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
584 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
585 | 12 | # GNU Lesser General Public License for more details. | ||
586 | 13 | # | ||
587 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
588 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
589 | 16 | |||
590 | 17 | # Bootstrap charm-helpers, installing its dependencies if necessary using | ||
591 | 18 | # only standard libraries. | ||
592 | 19 | import subprocess | ||
593 | 20 | import sys | ||
594 | 21 | |||
595 | 22 | try: | ||
596 | 23 | import six # flake8: noqa | ||
597 | 24 | except ImportError: | ||
598 | 25 | if sys.version_info.major == 2: | ||
599 | 26 | subprocess.check_call(['apt-get', 'install', '-y', 'python-six']) | ||
600 | 27 | else: | ||
601 | 28 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-six']) | ||
602 | 29 | import six # flake8: noqa | ||
603 | 30 | |||
604 | 31 | try: | ||
605 | 32 | import yaml # flake8: noqa | ||
606 | 33 | except ImportError: | ||
607 | 34 | if sys.version_info.major == 2: | ||
608 | 35 | subprocess.check_call(['apt-get', 'install', '-y', 'python-yaml']) | ||
609 | 36 | else: | ||
610 | 37 | subprocess.check_call(['apt-get', 'install', '-y', 'python3-yaml']) | ||
611 | 38 | import yaml # flake8: noqa | ||
612 | 0 | 39 | ||
613 | === modified file 'hooks/charmhelpers/contrib/__init__.py' | |||
614 | --- hooks/charmhelpers/contrib/__init__.py 2014-09-08 16:38:59 +0000 | |||
615 | +++ hooks/charmhelpers/contrib/__init__.py 2015-03-23 00:51:45 +0000 | |||
616 | @@ -0,0 +1,15 @@ | |||
617 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
618 | 2 | # | ||
619 | 3 | # This file is part of charm-helpers. | ||
620 | 4 | # | ||
621 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
622 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
623 | 7 | # published by the Free Software Foundation. | ||
624 | 8 | # | ||
625 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
626 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
627 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
628 | 12 | # GNU Lesser General Public License for more details. | ||
629 | 13 | # | ||
630 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
631 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
632 | 0 | 16 | ||
633 | === added directory 'hooks/charmhelpers/contrib/charmsupport' | |||
634 | === added file 'hooks/charmhelpers/contrib/charmsupport/__init__.py' | |||
635 | --- hooks/charmhelpers/contrib/charmsupport/__init__.py 1970-01-01 00:00:00 +0000 | |||
636 | +++ hooks/charmhelpers/contrib/charmsupport/__init__.py 2015-03-23 00:51:45 +0000 | |||
637 | @@ -0,0 +1,15 @@ | |||
638 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
639 | 2 | # | ||
640 | 3 | # This file is part of charm-helpers. | ||
641 | 4 | # | ||
642 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
643 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
644 | 7 | # published by the Free Software Foundation. | ||
645 | 8 | # | ||
646 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
647 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
648 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
649 | 12 | # GNU Lesser General Public License for more details. | ||
650 | 13 | # | ||
651 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
652 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
653 | 0 | 16 | ||
654 | === added file 'hooks/charmhelpers/contrib/charmsupport/nrpe.py' | |||
655 | --- hooks/charmhelpers/contrib/charmsupport/nrpe.py 1970-01-01 00:00:00 +0000 | |||
656 | +++ hooks/charmhelpers/contrib/charmsupport/nrpe.py 2015-03-23 00:51:45 +0000 | |||
657 | @@ -0,0 +1,358 @@ | |||
658 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
659 | 2 | # | ||
660 | 3 | # This file is part of charm-helpers. | ||
661 | 4 | # | ||
662 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
663 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
664 | 7 | # published by the Free Software Foundation. | ||
665 | 8 | # | ||
666 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
667 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
668 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
669 | 12 | # GNU Lesser General Public License for more details. | ||
670 | 13 | # | ||
671 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
672 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
673 | 16 | |||
674 | 17 | """Compatibility with the nrpe-external-master charm""" | ||
675 | 18 | # Copyright 2012 Canonical Ltd. | ||
676 | 19 | # | ||
677 | 20 | # Authors: | ||
678 | 21 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | ||
679 | 22 | |||
680 | 23 | import subprocess | ||
681 | 24 | import pwd | ||
682 | 25 | import grp | ||
683 | 26 | import os | ||
684 | 27 | import glob | ||
685 | 28 | import shutil | ||
686 | 29 | import re | ||
687 | 30 | import shlex | ||
688 | 31 | import yaml | ||
689 | 32 | |||
690 | 33 | from charmhelpers.core.hookenv import ( | ||
691 | 34 | config, | ||
692 | 35 | local_unit, | ||
693 | 36 | log, | ||
694 | 37 | relation_ids, | ||
695 | 38 | relation_set, | ||
696 | 39 | relations_of_type, | ||
697 | 40 | ) | ||
698 | 41 | |||
699 | 42 | from charmhelpers.core.host import service | ||
700 | 43 | |||
701 | 44 | # This module adds compatibility with the nrpe-external-master and plain nrpe | ||
702 | 45 | # subordinate charms. To use it in your charm: | ||
703 | 46 | # | ||
704 | 47 | # 1. Update metadata.yaml | ||
705 | 48 | # | ||
706 | 49 | # provides: | ||
707 | 50 | # (...) | ||
708 | 51 | # nrpe-external-master: | ||
709 | 52 | # interface: nrpe-external-master | ||
710 | 53 | # scope: container | ||
711 | 54 | # | ||
712 | 55 | # and/or | ||
713 | 56 | # | ||
714 | 57 | # provides: | ||
715 | 58 | # (...) | ||
716 | 59 | # local-monitors: | ||
717 | 60 | # interface: local-monitors | ||
718 | 61 | # scope: container | ||
719 | 62 | |||
720 | 63 | # | ||
721 | 64 | # 2. Add the following to config.yaml | ||
722 | 65 | # | ||
723 | 66 | # nagios_context: | ||
724 | 67 | # default: "juju" | ||
725 | 68 | # type: string | ||
726 | 69 | # description: | | ||
727 | 70 | # Used by the nrpe subordinate charms. | ||
728 | 71 | # A string that will be prepended to instance name to set the host name | ||
729 | 72 | # in nagios. So for instance the hostname would be something like: | ||
730 | 73 | # juju-myservice-0 | ||
731 | 74 | # If you're running multiple environments with the same services in them | ||
732 | 75 | # this allows you to differentiate between them. | ||
733 | 76 | # nagios_servicegroups: | ||
734 | 77 | # default: "" | ||
735 | 78 | # type: string | ||
736 | 79 | # description: | | ||
737 | 80 | # A comma-separated list of nagios servicegroups. | ||
738 | 81 | # If left empty, the nagios_context will be used as the servicegroup | ||
739 | 82 | # | ||
740 | 83 | # 3. Add custom checks (Nagios plugins) to files/nrpe-external-master | ||
741 | 84 | # | ||
742 | 85 | # 4. Update your hooks.py with something like this: | ||
743 | 86 | # | ||
744 | 87 | # from charmsupport.nrpe import NRPE | ||
745 | 88 | # (...) | ||
746 | 89 | # def update_nrpe_config(): | ||
747 | 90 | # nrpe_compat = NRPE() | ||
748 | 91 | # nrpe_compat.add_check( | ||
749 | 92 | # shortname = "myservice", | ||
750 | 93 | # description = "Check MyService", | ||
751 | 94 | # check_cmd = "check_http -w 2 -c 10 http://localhost" | ||
752 | 95 | # ) | ||
753 | 96 | # nrpe_compat.add_check( | ||
754 | 97 | # "myservice_other", | ||
755 | 98 | # "Check for widget failures", | ||
756 | 99 | # check_cmd = "/srv/myapp/scripts/widget_check" | ||
757 | 100 | # ) | ||
758 | 101 | # nrpe_compat.write() | ||
759 | 102 | # | ||
760 | 103 | # def config_changed(): | ||
761 | 104 | # (...) | ||
762 | 105 | # update_nrpe_config() | ||
763 | 106 | # | ||
764 | 107 | # def nrpe_external_master_relation_changed(): | ||
765 | 108 | # update_nrpe_config() | ||
766 | 109 | # | ||
767 | 110 | # def local_monitors_relation_changed(): | ||
768 | 111 | # update_nrpe_config() | ||
769 | 112 | # | ||
770 | 113 | # 5. ln -s hooks.py nrpe-external-master-relation-changed | ||
771 | 114 | # ln -s hooks.py local-monitors-relation-changed | ||
772 | 115 | |||
773 | 116 | |||
774 | 117 | class CheckException(Exception): | ||
775 | 118 | pass | ||
776 | 119 | |||
777 | 120 | |||
778 | 121 | class Check(object): | ||
779 | 122 | shortname_re = '[A-Za-z0-9-_]+$' | ||
780 | 123 | service_template = (""" | ||
781 | 124 | #--------------------------------------------------- | ||
782 | 125 | # This file is Juju managed | ||
783 | 126 | #--------------------------------------------------- | ||
784 | 127 | define service {{ | ||
785 | 128 | use active-service | ||
786 | 129 | host_name {nagios_hostname} | ||
787 | 130 | service_description {nagios_hostname}[{shortname}] """ | ||
788 | 131 | """{description} | ||
789 | 132 | check_command check_nrpe!{command} | ||
790 | 133 | servicegroups {nagios_servicegroup} | ||
791 | 134 | }} | ||
792 | 135 | """) | ||
793 | 136 | |||
794 | 137 | def __init__(self, shortname, description, check_cmd): | ||
795 | 138 | super(Check, self).__init__() | ||
796 | 139 | # XXX: could be better to calculate this from the service name | ||
797 | 140 | if not re.match(self.shortname_re, shortname): | ||
798 | 141 | raise CheckException("shortname must match {}".format( | ||
799 | 142 | Check.shortname_re)) | ||
800 | 143 | self.shortname = shortname | ||
801 | 144 | self.command = "check_{}".format(shortname) | ||
802 | 145 | # Note: a set of invalid characters is defined by the | ||
803 | 146 | # Nagios server config | ||
804 | 147 | # The default is: illegal_object_name_chars=`~!$%^&*"|'<>?,()= | ||
805 | 148 | self.description = description | ||
806 | 149 | self.check_cmd = self._locate_cmd(check_cmd) | ||
807 | 150 | |||
808 | 151 | def _locate_cmd(self, check_cmd): | ||
809 | 152 | search_path = ( | ||
810 | 153 | '/usr/lib/nagios/plugins', | ||
811 | 154 | '/usr/local/lib/nagios/plugins', | ||
812 | 155 | ) | ||
813 | 156 | parts = shlex.split(check_cmd) | ||
814 | 157 | for path in search_path: | ||
815 | 158 | if os.path.exists(os.path.join(path, parts[0])): | ||
816 | 159 | command = os.path.join(path, parts[0]) | ||
817 | 160 | if len(parts) > 1: | ||
818 | 161 | command += " " + " ".join(parts[1:]) | ||
819 | 162 | return command | ||
820 | 163 | log('Check command not found: {}'.format(parts[0])) | ||
821 | 164 | return '' | ||
822 | 165 | |||
823 | 166 | def write(self, nagios_context, hostname, nagios_servicegroups): | ||
824 | 167 | nrpe_check_file = '/etc/nagios/nrpe.d/{}.cfg'.format( | ||
825 | 168 | self.command) | ||
826 | 169 | with open(nrpe_check_file, 'w') as nrpe_check_config: | ||
827 | 170 | nrpe_check_config.write("# check {}\n".format(self.shortname)) | ||
828 | 171 | nrpe_check_config.write("command[{}]={}\n".format( | ||
829 | 172 | self.command, self.check_cmd)) | ||
830 | 173 | |||
831 | 174 | if not os.path.exists(NRPE.nagios_exportdir): | ||
832 | 175 | log('Not writing service config as {} is not accessible'.format( | ||
833 | 176 | NRPE.nagios_exportdir)) | ||
834 | 177 | else: | ||
835 | 178 | self.write_service_config(nagios_context, hostname, | ||
836 | 179 | nagios_servicegroups) | ||
837 | 180 | |||
838 | 181 | def write_service_config(self, nagios_context, hostname, | ||
839 | 182 | nagios_servicegroups): | ||
840 | 183 | for f in os.listdir(NRPE.nagios_exportdir): | ||
841 | 184 | if re.search('.*{}.cfg'.format(self.command), f): | ||
842 | 185 | os.remove(os.path.join(NRPE.nagios_exportdir, f)) | ||
843 | 186 | |||
844 | 187 | templ_vars = { | ||
845 | 188 | 'nagios_hostname': hostname, | ||
846 | 189 | 'nagios_servicegroup': nagios_servicegroups, | ||
847 | 190 | 'description': self.description, | ||
848 | 191 | 'shortname': self.shortname, | ||
849 | 192 | 'command': self.command, | ||
850 | 193 | } | ||
851 | 194 | nrpe_service_text = Check.service_template.format(**templ_vars) | ||
852 | 195 | nrpe_service_file = '{}/service__{}_{}.cfg'.format( | ||
853 | 196 | NRPE.nagios_exportdir, hostname, self.command) | ||
854 | 197 | with open(nrpe_service_file, 'w') as nrpe_service_config: | ||
855 | 198 | nrpe_service_config.write(str(nrpe_service_text)) | ||
856 | 199 | |||
857 | 200 | def run(self): | ||
858 | 201 | subprocess.call(self.check_cmd) | ||
859 | 202 | |||
860 | 203 | |||
861 | 204 | class NRPE(object): | ||
862 | 205 | nagios_logdir = '/var/log/nagios' | ||
863 | 206 | nagios_exportdir = '/var/lib/nagios/export' | ||
864 | 207 | nrpe_confdir = '/etc/nagios/nrpe.d' | ||
865 | 208 | |||
866 | 209 | def __init__(self, hostname=None): | ||
867 | 210 | super(NRPE, self).__init__() | ||
868 | 211 | self.config = config() | ||
869 | 212 | self.nagios_context = self.config['nagios_context'] | ||
870 | 213 | if 'nagios_servicegroups' in self.config and self.config['nagios_servicegroups']: | ||
871 | 214 | self.nagios_servicegroups = self.config['nagios_servicegroups'] | ||
872 | 215 | else: | ||
873 | 216 | self.nagios_servicegroups = self.nagios_context | ||
874 | 217 | self.unit_name = local_unit().replace('/', '-') | ||
875 | 218 | if hostname: | ||
876 | 219 | self.hostname = hostname | ||
877 | 220 | else: | ||
878 | 221 | self.hostname = "{}-{}".format(self.nagios_context, self.unit_name) | ||
879 | 222 | self.checks = [] | ||
880 | 223 | |||
881 | 224 | def add_check(self, *args, **kwargs): | ||
882 | 225 | self.checks.append(Check(*args, **kwargs)) | ||
883 | 226 | |||
884 | 227 | def write(self): | ||
885 | 228 | try: | ||
886 | 229 | nagios_uid = pwd.getpwnam('nagios').pw_uid | ||
887 | 230 | nagios_gid = grp.getgrnam('nagios').gr_gid | ||
888 | 231 | except: | ||
889 | 232 | log("Nagios user not set up, nrpe checks not updated") | ||
890 | 233 | return | ||
891 | 234 | |||
892 | 235 | if not os.path.exists(NRPE.nagios_logdir): | ||
893 | 236 | os.mkdir(NRPE.nagios_logdir) | ||
894 | 237 | os.chown(NRPE.nagios_logdir, nagios_uid, nagios_gid) | ||
895 | 238 | |||
896 | 239 | nrpe_monitors = {} | ||
897 | 240 | monitors = {"monitors": {"remote": {"nrpe": nrpe_monitors}}} | ||
898 | 241 | for nrpecheck in self.checks: | ||
899 | 242 | nrpecheck.write(self.nagios_context, self.hostname, | ||
900 | 243 | self.nagios_servicegroups) | ||
901 | 244 | nrpe_monitors[nrpecheck.shortname] = { | ||
902 | 245 | "command": nrpecheck.command, | ||
903 | 246 | } | ||
904 | 247 | |||
905 | 248 | service('restart', 'nagios-nrpe-server') | ||
906 | 249 | |||
907 | 250 | for rid in relation_ids("local-monitors"): | ||
908 | 251 | relation_set(relation_id=rid, monitors=yaml.dump(monitors)) | ||
909 | 252 | |||
910 | 253 | |||
911 | 254 | def get_nagios_hostcontext(relation_name='nrpe-external-master'): | ||
912 | 255 | """ | ||
913 | 256 | Query relation with nrpe subordinate, return the nagios_host_context | ||
914 | 257 | |||
915 | 258 | :param str relation_name: Name of relation nrpe sub joined to | ||
916 | 259 | """ | ||
917 | 260 | for rel in relations_of_type(relation_name): | ||
918 | 261 | if 'nagios_hostname' in rel: | ||
919 | 262 | return rel['nagios_host_context'] | ||
920 | 263 | |||
921 | 264 | |||
922 | 265 | def get_nagios_hostname(relation_name='nrpe-external-master'): | ||
923 | 266 | """ | ||
924 | 267 | Query relation with nrpe subordinate, return the nagios_hostname | ||
925 | 268 | |||
926 | 269 | :param str relation_name: Name of relation nrpe sub joined to | ||
927 | 270 | """ | ||
928 | 271 | for rel in relations_of_type(relation_name): | ||
929 | 272 | if 'nagios_hostname' in rel: | ||
930 | 273 | return rel['nagios_hostname'] | ||
931 | 274 | |||
932 | 275 | |||
933 | 276 | def get_nagios_unit_name(relation_name='nrpe-external-master'): | ||
934 | 277 | """ | ||
935 | 278 | Return the nagios unit name prepended with host_context if needed | ||
936 | 279 | |||
937 | 280 | :param str relation_name: Name of relation nrpe sub joined to | ||
938 | 281 | """ | ||
939 | 282 | host_context = get_nagios_hostcontext(relation_name) | ||
940 | 283 | if host_context: | ||
941 | 284 | unit = "%s:%s" % (host_context, local_unit()) | ||
942 | 285 | else: | ||
943 | 286 | unit = local_unit() | ||
944 | 287 | return unit | ||
945 | 288 | |||
946 | 289 | |||
947 | 290 | def add_init_service_checks(nrpe, services, unit_name): | ||
948 | 291 | """ | ||
949 | 292 | Add checks for each service in list | ||
950 | 293 | |||
951 | 294 | :param NRPE nrpe: NRPE object to add check to | ||
952 | 295 | :param list services: List of services to check | ||
953 | 296 | :param str unit_name: Unit name to use in check description | ||
954 | 297 | """ | ||
955 | 298 | for svc in services: | ||
956 | 299 | upstart_init = '/etc/init/%s.conf' % svc | ||
957 | 300 | sysv_init = '/etc/init.d/%s' % svc | ||
958 | 301 | if os.path.exists(upstart_init): | ||
959 | 302 | nrpe.add_check( | ||
960 | 303 | shortname=svc, | ||
961 | 304 | description='process check {%s}' % unit_name, | ||
962 | 305 | check_cmd='check_upstart_job %s' % svc | ||
963 | 306 | ) | ||
964 | 307 | elif os.path.exists(sysv_init): | ||
965 | 308 | cronpath = '/etc/cron.d/nagios-service-check-%s' % svc | ||
966 | 309 | cron_file = ('*/5 * * * * root ' | ||
967 | 310 | '/usr/local/lib/nagios/plugins/check_exit_status.pl ' | ||
968 | 311 | '-s /etc/init.d/%s status > ' | ||
969 | 312 | '/var/lib/nagios/service-check-%s.txt\n' % (svc, | ||
970 | 313 | svc) | ||
971 | 314 | ) | ||
972 | 315 | f = open(cronpath, 'w') | ||
973 | 316 | f.write(cron_file) | ||
974 | 317 | f.close() | ||
975 | 318 | nrpe.add_check( | ||
976 | 319 | shortname=svc, | ||
977 | 320 | description='process check {%s}' % unit_name, | ||
978 | 321 | check_cmd='check_status_file.py -f ' | ||
979 | 322 | '/var/lib/nagios/service-check-%s.txt' % svc, | ||
980 | 323 | ) | ||
981 | 324 | |||
982 | 325 | |||
983 | 326 | def copy_nrpe_checks(): | ||
984 | 327 | """ | ||
985 | 328 | Copy the nrpe checks into place | ||
986 | 329 | |||
987 | 330 | """ | ||
988 | 331 | NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' | ||
989 | 332 | nrpe_files_dir = os.path.join(os.getenv('CHARM_DIR'), 'hooks', | ||
990 | 333 | 'charmhelpers', 'contrib', 'openstack', | ||
991 | 334 | 'files') | ||
992 | 335 | |||
993 | 336 | if not os.path.exists(NAGIOS_PLUGINS): | ||
994 | 337 | os.makedirs(NAGIOS_PLUGINS) | ||
995 | 338 | for fname in glob.glob(os.path.join(nrpe_files_dir, "check_*")): | ||
996 | 339 | if os.path.isfile(fname): | ||
997 | 340 | shutil.copy2(fname, | ||
998 | 341 | os.path.join(NAGIOS_PLUGINS, os.path.basename(fname))) | ||
999 | 342 | |||
1000 | 343 | |||
1001 | 344 | def add_haproxy_checks(nrpe, unit_name): | ||
1002 | 345 | """ | ||
1003 | 346 | Add checks for each service in list | ||
1004 | 347 | |||
1005 | 348 | :param NRPE nrpe: NRPE object to add check to | ||
1006 | 349 | :param str unit_name: Unit name to use in check description | ||
1007 | 350 | """ | ||
1008 | 351 | nrpe.add_check( | ||
1009 | 352 | shortname='haproxy_servers', | ||
1010 | 353 | description='Check HAProxy {%s}' % unit_name, | ||
1011 | 354 | check_cmd='check_haproxy.sh') | ||
1012 | 355 | nrpe.add_check( | ||
1013 | 356 | shortname='haproxy_queue', | ||
1014 | 357 | description='Check HAProxy queue depth {%s}' % unit_name, | ||
1015 | 358 | check_cmd='check_haproxy_queue_depth.sh') | ||
1016 | 0 | 359 | ||
1017 | === added file 'hooks/charmhelpers/contrib/charmsupport/volumes.py' | |||
1018 | --- hooks/charmhelpers/contrib/charmsupport/volumes.py 1970-01-01 00:00:00 +0000 | |||
1019 | +++ hooks/charmhelpers/contrib/charmsupport/volumes.py 2015-03-23 00:51:45 +0000 | |||
1020 | @@ -0,0 +1,175 @@ | |||
1021 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1022 | 2 | # | ||
1023 | 3 | # This file is part of charm-helpers. | ||
1024 | 4 | # | ||
1025 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1026 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1027 | 7 | # published by the Free Software Foundation. | ||
1028 | 8 | # | ||
1029 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1030 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1031 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1032 | 12 | # GNU Lesser General Public License for more details. | ||
1033 | 13 | # | ||
1034 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1035 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1036 | 16 | |||
1037 | 17 | ''' | ||
1038 | 18 | Functions for managing volumes in juju units. One volume is supported per unit. | ||
1039 | 19 | Subordinates may have their own storage, provided it is on its own partition. | ||
1040 | 20 | |||
1041 | 21 | Configuration stanzas:: | ||
1042 | 22 | |||
1043 | 23 | volume-ephemeral: | ||
1044 | 24 | type: boolean | ||
1045 | 25 | default: true | ||
1046 | 26 | description: > | ||
1047 | 27 | If false, a volume is mounted as sepecified in "volume-map" | ||
1048 | 28 | If true, ephemeral storage will be used, meaning that log data | ||
1049 | 29 | will only exist as long as the machine. YOU HAVE BEEN WARNED. | ||
1050 | 30 | volume-map: | ||
1051 | 31 | type: string | ||
1052 | 32 | default: {} | ||
1053 | 33 | description: > | ||
1054 | 34 | YAML map of units to device names, e.g: | ||
1055 | 35 | "{ rsyslog/0: /dev/vdb, rsyslog/1: /dev/vdb }" | ||
1056 | 36 | Service units will raise a configure-error if volume-ephemeral | ||
1057 | 37 | is 'true' and no volume-map value is set. Use 'juju set' to set a | ||
1058 | 38 | value and 'juju resolved' to complete configuration. | ||
1059 | 39 | |||
1060 | 40 | Usage:: | ||
1061 | 41 | |||
1062 | 42 | from charmsupport.volumes import configure_volume, VolumeConfigurationError | ||
1063 | 43 | from charmsupport.hookenv import log, ERROR | ||
1064 | 44 | def post_mount_hook(): | ||
1065 | 45 | stop_service('myservice') | ||
1066 | 46 | def post_mount_hook(): | ||
1067 | 47 | start_service('myservice') | ||
1068 | 48 | |||
1069 | 49 | if __name__ == '__main__': | ||
1070 | 50 | try: | ||
1071 | 51 | configure_volume(before_change=pre_mount_hook, | ||
1072 | 52 | after_change=post_mount_hook) | ||
1073 | 53 | except VolumeConfigurationError: | ||
1074 | 54 | log('Storage could not be configured', ERROR) | ||
1075 | 55 | |||
1076 | 56 | ''' | ||
1077 | 57 | |||
1078 | 58 | # XXX: Known limitations | ||
1079 | 59 | # - fstab is neither consulted nor updated | ||
1080 | 60 | |||
1081 | 61 | import os | ||
1082 | 62 | from charmhelpers.core import hookenv | ||
1083 | 63 | from charmhelpers.core import host | ||
1084 | 64 | import yaml | ||
1085 | 65 | |||
1086 | 66 | |||
1087 | 67 | MOUNT_BASE = '/srv/juju/volumes' | ||
1088 | 68 | |||
1089 | 69 | |||
1090 | 70 | class VolumeConfigurationError(Exception): | ||
1091 | 71 | '''Volume configuration data is missing or invalid''' | ||
1092 | 72 | pass | ||
1093 | 73 | |||
1094 | 74 | |||
1095 | 75 | def get_config(): | ||
1096 | 76 | '''Gather and sanity-check volume configuration data''' | ||
1097 | 77 | volume_config = {} | ||
1098 | 78 | config = hookenv.config() | ||
1099 | 79 | |||
1100 | 80 | errors = False | ||
1101 | 81 | |||
1102 | 82 | if config.get('volume-ephemeral') in (True, 'True', 'true', 'Yes', 'yes'): | ||
1103 | 83 | volume_config['ephemeral'] = True | ||
1104 | 84 | else: | ||
1105 | 85 | volume_config['ephemeral'] = False | ||
1106 | 86 | |||
1107 | 87 | try: | ||
1108 | 88 | volume_map = yaml.safe_load(config.get('volume-map', '{}')) | ||
1109 | 89 | except yaml.YAMLError as e: | ||
1110 | 90 | hookenv.log("Error parsing YAML volume-map: {}".format(e), | ||
1111 | 91 | hookenv.ERROR) | ||
1112 | 92 | errors = True | ||
1113 | 93 | if volume_map is None: | ||
1114 | 94 | # probably an empty string | ||
1115 | 95 | volume_map = {} | ||
1116 | 96 | elif not isinstance(volume_map, dict): | ||
1117 | 97 | hookenv.log("Volume-map should be a dictionary, not {}".format( | ||
1118 | 98 | type(volume_map))) | ||
1119 | 99 | errors = True | ||
1120 | 100 | |||
1121 | 101 | volume_config['device'] = volume_map.get(os.environ['JUJU_UNIT_NAME']) | ||
1122 | 102 | if volume_config['device'] and volume_config['ephemeral']: | ||
1123 | 103 | # asked for ephemeral storage but also defined a volume ID | ||
1124 | 104 | hookenv.log('A volume is defined for this unit, but ephemeral ' | ||
1125 | 105 | 'storage was requested', hookenv.ERROR) | ||
1126 | 106 | errors = True | ||
1127 | 107 | elif not volume_config['device'] and not volume_config['ephemeral']: | ||
1128 | 108 | # asked for permanent storage but did not define volume ID | ||
1129 | 109 | hookenv.log('Ephemeral storage was requested, but there is no volume ' | ||
1130 | 110 | 'defined for this unit.', hookenv.ERROR) | ||
1131 | 111 | errors = True | ||
1132 | 112 | |||
1133 | 113 | unit_mount_name = hookenv.local_unit().replace('/', '-') | ||
1134 | 114 | volume_config['mountpoint'] = os.path.join(MOUNT_BASE, unit_mount_name) | ||
1135 | 115 | |||
1136 | 116 | if errors: | ||
1137 | 117 | return None | ||
1138 | 118 | return volume_config | ||
1139 | 119 | |||
1140 | 120 | |||
1141 | 121 | def mount_volume(config): | ||
1142 | 122 | if os.path.exists(config['mountpoint']): | ||
1143 | 123 | if not os.path.isdir(config['mountpoint']): | ||
1144 | 124 | hookenv.log('Not a directory: {}'.format(config['mountpoint'])) | ||
1145 | 125 | raise VolumeConfigurationError() | ||
1146 | 126 | else: | ||
1147 | 127 | host.mkdir(config['mountpoint']) | ||
1148 | 128 | if os.path.ismount(config['mountpoint']): | ||
1149 | 129 | unmount_volume(config) | ||
1150 | 130 | if not host.mount(config['device'], config['mountpoint'], persist=True): | ||
1151 | 131 | raise VolumeConfigurationError() | ||
1152 | 132 | |||
1153 | 133 | |||
1154 | 134 | def unmount_volume(config): | ||
1155 | 135 | if os.path.ismount(config['mountpoint']): | ||
1156 | 136 | if not host.umount(config['mountpoint'], persist=True): | ||
1157 | 137 | raise VolumeConfigurationError() | ||
1158 | 138 | |||
1159 | 139 | |||
1160 | 140 | def managed_mounts(): | ||
1161 | 141 | '''List of all mounted managed volumes''' | ||
1162 | 142 | return filter(lambda mount: mount[0].startswith(MOUNT_BASE), host.mounts()) | ||
1163 | 143 | |||
1164 | 144 | |||
1165 | 145 | def configure_volume(before_change=lambda: None, after_change=lambda: None): | ||
1166 | 146 | '''Set up storage (or don't) according to the charm's volume configuration. | ||
1167 | 147 | Returns the mount point or "ephemeral". before_change and after_change | ||
1168 | 148 | are optional functions to be called if the volume configuration changes. | ||
1169 | 149 | ''' | ||
1170 | 150 | |||
1171 | 151 | config = get_config() | ||
1172 | 152 | if not config: | ||
1173 | 153 | hookenv.log('Failed to read volume configuration', hookenv.CRITICAL) | ||
1174 | 154 | raise VolumeConfigurationError() | ||
1175 | 155 | |||
1176 | 156 | if config['ephemeral']: | ||
1177 | 157 | if os.path.ismount(config['mountpoint']): | ||
1178 | 158 | before_change() | ||
1179 | 159 | unmount_volume(config) | ||
1180 | 160 | after_change() | ||
1181 | 161 | return 'ephemeral' | ||
1182 | 162 | else: | ||
1183 | 163 | # persistent storage | ||
1184 | 164 | if os.path.ismount(config['mountpoint']): | ||
1185 | 165 | mounts = dict(managed_mounts()) | ||
1186 | 166 | if mounts.get(config['mountpoint']) != config['device']: | ||
1187 | 167 | before_change() | ||
1188 | 168 | unmount_volume(config) | ||
1189 | 169 | mount_volume(config) | ||
1190 | 170 | after_change() | ||
1191 | 171 | else: | ||
1192 | 172 | before_change() | ||
1193 | 173 | mount_volume(config) | ||
1194 | 174 | after_change() | ||
1195 | 175 | return config['mountpoint'] | ||
1196 | 0 | 176 | ||
1197 | === modified file 'hooks/charmhelpers/contrib/templating/__init__.py' | |||
1198 | --- hooks/charmhelpers/contrib/templating/__init__.py 2014-09-08 16:38:59 +0000 | |||
1199 | +++ hooks/charmhelpers/contrib/templating/__init__.py 2015-03-23 00:51:45 +0000 | |||
1200 | @@ -0,0 +1,15 @@ | |||
1201 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1202 | 2 | # | ||
1203 | 3 | # This file is part of charm-helpers. | ||
1204 | 4 | # | ||
1205 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1206 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1207 | 7 | # published by the Free Software Foundation. | ||
1208 | 8 | # | ||
1209 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1210 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1211 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1212 | 12 | # GNU Lesser General Public License for more details. | ||
1213 | 13 | # | ||
1214 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1215 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1216 | 0 | 16 | ||
1217 | === modified file 'hooks/charmhelpers/contrib/templating/jinja.py' | |||
1218 | --- hooks/charmhelpers/contrib/templating/jinja.py 2014-09-08 16:38:59 +0000 | |||
1219 | +++ hooks/charmhelpers/contrib/templating/jinja.py 2015-03-23 00:51:45 +0000 | |||
1220 | @@ -1,21 +1,37 @@ | |||
1221 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1222 | 2 | # | ||
1223 | 3 | # This file is part of charm-helpers. | ||
1224 | 4 | # | ||
1225 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1226 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1227 | 7 | # published by the Free Software Foundation. | ||
1228 | 8 | # | ||
1229 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1230 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1231 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1232 | 12 | # GNU Lesser General Public License for more details. | ||
1233 | 13 | # | ||
1234 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1235 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1236 | 16 | |||
1237 | 1 | """ | 17 | """ |
1238 | 2 | Templating using the python-jinja2 package. | 18 | Templating using the python-jinja2 package. |
1239 | 3 | """ | 19 | """ |
1248 | 4 | from charmhelpers.fetch import ( | 20 | import six |
1249 | 5 | apt_install, | 21 | from charmhelpers.fetch import apt_install |
1242 | 6 | ) | ||
1243 | 7 | |||
1244 | 8 | |||
1245 | 9 | DEFAULT_TEMPLATES_DIR = 'templates' | ||
1246 | 10 | |||
1247 | 11 | |||
1250 | 12 | try: | 22 | try: |
1251 | 13 | import jinja2 | 23 | import jinja2 |
1252 | 14 | except ImportError: | 24 | except ImportError: |
1254 | 15 | apt_install(["python-jinja2"]) | 25 | if six.PY3: |
1255 | 26 | apt_install(["python3-jinja2"]) | ||
1256 | 27 | else: | ||
1257 | 28 | apt_install(["python-jinja2"]) | ||
1258 | 16 | import jinja2 | 29 | import jinja2 |
1259 | 17 | 30 | ||
1260 | 18 | 31 | ||
1261 | 32 | DEFAULT_TEMPLATES_DIR = 'templates' | ||
1262 | 33 | |||
1263 | 34 | |||
1264 | 19 | def render(template_name, context, template_dir=DEFAULT_TEMPLATES_DIR): | 35 | def render(template_name, context, template_dir=DEFAULT_TEMPLATES_DIR): |
1265 | 20 | templates = jinja2.Environment( | 36 | templates = jinja2.Environment( |
1266 | 21 | loader=jinja2.FileSystemLoader(template_dir)) | 37 | loader=jinja2.FileSystemLoader(template_dir)) |
1267 | 22 | 38 | ||
1268 | === modified file 'hooks/charmhelpers/core/__init__.py' | |||
1269 | --- hooks/charmhelpers/core/__init__.py 2013-07-09 11:17:24 +0000 | |||
1270 | +++ hooks/charmhelpers/core/__init__.py 2015-03-23 00:51:45 +0000 | |||
1271 | @@ -0,0 +1,15 @@ | |||
1272 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1273 | 2 | # | ||
1274 | 3 | # This file is part of charm-helpers. | ||
1275 | 4 | # | ||
1276 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1277 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1278 | 7 | # published by the Free Software Foundation. | ||
1279 | 8 | # | ||
1280 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1281 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1282 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1283 | 12 | # GNU Lesser General Public License for more details. | ||
1284 | 13 | # | ||
1285 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1286 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1287 | 0 | 16 | ||
1288 | === added file 'hooks/charmhelpers/core/decorators.py' | |||
1289 | --- hooks/charmhelpers/core/decorators.py 1970-01-01 00:00:00 +0000 | |||
1290 | +++ hooks/charmhelpers/core/decorators.py 2015-03-23 00:51:45 +0000 | |||
1291 | @@ -0,0 +1,57 @@ | |||
1292 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1293 | 2 | # | ||
1294 | 3 | # This file is part of charm-helpers. | ||
1295 | 4 | # | ||
1296 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1297 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1298 | 7 | # published by the Free Software Foundation. | ||
1299 | 8 | # | ||
1300 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1301 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1302 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1303 | 12 | # GNU Lesser General Public License for more details. | ||
1304 | 13 | # | ||
1305 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1306 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1307 | 16 | |||
1308 | 17 | # | ||
1309 | 18 | # Copyright 2014 Canonical Ltd. | ||
1310 | 19 | # | ||
1311 | 20 | # Authors: | ||
1312 | 21 | # Edward Hope-Morley <opentastic@gmail.com> | ||
1313 | 22 | # | ||
1314 | 23 | |||
1315 | 24 | import time | ||
1316 | 25 | |||
1317 | 26 | from charmhelpers.core.hookenv import ( | ||
1318 | 27 | log, | ||
1319 | 28 | INFO, | ||
1320 | 29 | ) | ||
1321 | 30 | |||
1322 | 31 | |||
1323 | 32 | def retry_on_exception(num_retries, base_delay=0, exc_type=Exception): | ||
1324 | 33 | """If the decorated function raises exception exc_type, allow num_retries | ||
1325 | 34 | retry attempts before raise the exception. | ||
1326 | 35 | """ | ||
1327 | 36 | def _retry_on_exception_inner_1(f): | ||
1328 | 37 | def _retry_on_exception_inner_2(*args, **kwargs): | ||
1329 | 38 | retries = num_retries | ||
1330 | 39 | multiplier = 1 | ||
1331 | 40 | while True: | ||
1332 | 41 | try: | ||
1333 | 42 | return f(*args, **kwargs) | ||
1334 | 43 | except exc_type: | ||
1335 | 44 | if not retries: | ||
1336 | 45 | raise | ||
1337 | 46 | |||
1338 | 47 | delay = base_delay * multiplier | ||
1339 | 48 | multiplier += 1 | ||
1340 | 49 | log("Retrying '%s' %d more times (delay=%s)" % | ||
1341 | 50 | (f.__name__, retries, delay), level=INFO) | ||
1342 | 51 | retries -= 1 | ||
1343 | 52 | if delay: | ||
1344 | 53 | time.sleep(delay) | ||
1345 | 54 | |||
1346 | 55 | return _retry_on_exception_inner_2 | ||
1347 | 56 | |||
1348 | 57 | return _retry_on_exception_inner_1 | ||
1349 | 0 | 58 | ||
1350 | === modified file 'hooks/charmhelpers/core/fstab.py' | |||
1351 | --- hooks/charmhelpers/core/fstab.py 2014-07-16 05:40:55 +0000 | |||
1352 | +++ hooks/charmhelpers/core/fstab.py 2015-03-23 00:51:45 +0000 | |||
1353 | @@ -1,12 +1,29 @@ | |||
1354 | 1 | #!/usr/bin/env python | 1 | #!/usr/bin/env python |
1355 | 2 | # -*- coding: utf-8 -*- | 2 | # -*- coding: utf-8 -*- |
1356 | 3 | 3 | ||
1357 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
1358 | 5 | # | ||
1359 | 6 | # This file is part of charm-helpers. | ||
1360 | 7 | # | ||
1361 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1362 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1363 | 10 | # published by the Free Software Foundation. | ||
1364 | 11 | # | ||
1365 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
1366 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1367 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1368 | 15 | # GNU Lesser General Public License for more details. | ||
1369 | 16 | # | ||
1370 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
1371 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1372 | 19 | |||
1373 | 20 | import io | ||
1374 | 21 | import os | ||
1375 | 22 | |||
1376 | 4 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | 23 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' |
1377 | 5 | 24 | ||
1382 | 6 | import os | 25 | |
1383 | 7 | 26 | class Fstab(io.FileIO): | |
1380 | 8 | |||
1381 | 9 | class Fstab(file): | ||
1384 | 10 | """This class extends file in order to implement a file reader/writer | 27 | """This class extends file in order to implement a file reader/writer |
1385 | 11 | for file `/etc/fstab` | 28 | for file `/etc/fstab` |
1386 | 12 | """ | 29 | """ |
1387 | @@ -24,8 +41,8 @@ | |||
1388 | 24 | options = "defaults" | 41 | options = "defaults" |
1389 | 25 | 42 | ||
1390 | 26 | self.options = options | 43 | self.options = options |
1393 | 27 | self.d = d | 44 | self.d = int(d) |
1394 | 28 | self.p = p | 45 | self.p = int(p) |
1395 | 29 | 46 | ||
1396 | 30 | def __eq__(self, o): | 47 | def __eq__(self, o): |
1397 | 31 | return str(self) == str(o) | 48 | return str(self) == str(o) |
1398 | @@ -45,7 +62,7 @@ | |||
1399 | 45 | self._path = path | 62 | self._path = path |
1400 | 46 | else: | 63 | else: |
1401 | 47 | self._path = self.DEFAULT_PATH | 64 | self._path = self.DEFAULT_PATH |
1403 | 48 | file.__init__(self, self._path, 'r+') | 65 | super(Fstab, self).__init__(self._path, 'rb+') |
1404 | 49 | 66 | ||
1405 | 50 | def _hydrate_entry(self, line): | 67 | def _hydrate_entry(self, line): |
1406 | 51 | # NOTE: use split with no arguments to split on any | 68 | # NOTE: use split with no arguments to split on any |
1407 | @@ -58,8 +75,9 @@ | |||
1408 | 58 | def entries(self): | 75 | def entries(self): |
1409 | 59 | self.seek(0) | 76 | self.seek(0) |
1410 | 60 | for line in self.readlines(): | 77 | for line in self.readlines(): |
1411 | 78 | line = line.decode('us-ascii') | ||
1412 | 61 | try: | 79 | try: |
1414 | 62 | if not line.startswith("#"): | 80 | if line.strip() and not line.strip().startswith("#"): |
1415 | 63 | yield self._hydrate_entry(line) | 81 | yield self._hydrate_entry(line) |
1416 | 64 | except ValueError: | 82 | except ValueError: |
1417 | 65 | pass | 83 | pass |
1418 | @@ -75,18 +93,18 @@ | |||
1419 | 75 | if self.get_entry_by_attr('device', entry.device): | 93 | if self.get_entry_by_attr('device', entry.device): |
1420 | 76 | return False | 94 | return False |
1421 | 77 | 95 | ||
1423 | 78 | self.write(str(entry) + '\n') | 96 | self.write((str(entry) + '\n').encode('us-ascii')) |
1424 | 79 | self.truncate() | 97 | self.truncate() |
1425 | 80 | return entry | 98 | return entry |
1426 | 81 | 99 | ||
1427 | 82 | def remove_entry(self, entry): | 100 | def remove_entry(self, entry): |
1428 | 83 | self.seek(0) | 101 | self.seek(0) |
1429 | 84 | 102 | ||
1431 | 85 | lines = self.readlines() | 103 | lines = [l.decode('us-ascii') for l in self.readlines()] |
1432 | 86 | 104 | ||
1433 | 87 | found = False | 105 | found = False |
1434 | 88 | for index, line in enumerate(lines): | 106 | for index, line in enumerate(lines): |
1436 | 89 | if not line.startswith("#"): | 107 | if line.strip() and not line.strip().startswith("#"): |
1437 | 90 | if self._hydrate_entry(line) == entry: | 108 | if self._hydrate_entry(line) == entry: |
1438 | 91 | found = True | 109 | found = True |
1439 | 92 | break | 110 | break |
1440 | @@ -97,7 +115,7 @@ | |||
1441 | 97 | lines.remove(line) | 115 | lines.remove(line) |
1442 | 98 | 116 | ||
1443 | 99 | self.seek(0) | 117 | self.seek(0) |
1445 | 100 | self.write(''.join(lines)) | 118 | self.write(''.join(lines).encode('us-ascii')) |
1446 | 101 | self.truncate() | 119 | self.truncate() |
1447 | 102 | return True | 120 | return True |
1448 | 103 | 121 | ||
1449 | 104 | 122 | ||
1450 | === modified file 'hooks/charmhelpers/core/hookenv.py' | |||
1451 | --- hooks/charmhelpers/core/hookenv.py 2014-09-08 16:38:59 +0000 | |||
1452 | +++ hooks/charmhelpers/core/hookenv.py 2015-03-23 00:51:45 +0000 | |||
1453 | @@ -1,3 +1,19 @@ | |||
1454 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1455 | 2 | # | ||
1456 | 3 | # This file is part of charm-helpers. | ||
1457 | 4 | # | ||
1458 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1459 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1460 | 7 | # published by the Free Software Foundation. | ||
1461 | 8 | # | ||
1462 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1463 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1464 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1465 | 12 | # GNU Lesser General Public License for more details. | ||
1466 | 13 | # | ||
1467 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1468 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1469 | 16 | |||
1470 | 1 | "Interactions with the Juju environment" | 17 | "Interactions with the Juju environment" |
1471 | 2 | # Copyright 2013 Canonical Ltd. | 18 | # Copyright 2013 Canonical Ltd. |
1472 | 3 | # | 19 | # |
1473 | @@ -9,9 +25,14 @@ | |||
1474 | 9 | import yaml | 25 | import yaml |
1475 | 10 | import subprocess | 26 | import subprocess |
1476 | 11 | import sys | 27 | import sys |
1477 | 12 | import UserDict | ||
1478 | 13 | from subprocess import CalledProcessError | 28 | from subprocess import CalledProcessError |
1479 | 14 | 29 | ||
1480 | 30 | import six | ||
1481 | 31 | if not six.PY3: | ||
1482 | 32 | from UserDict import UserDict | ||
1483 | 33 | else: | ||
1484 | 34 | from collections import UserDict | ||
1485 | 35 | |||
1486 | 15 | CRITICAL = "CRITICAL" | 36 | CRITICAL = "CRITICAL" |
1487 | 16 | ERROR = "ERROR" | 37 | ERROR = "ERROR" |
1488 | 17 | WARNING = "WARNING" | 38 | WARNING = "WARNING" |
1489 | @@ -63,16 +84,18 @@ | |||
1490 | 63 | command = ['juju-log'] | 84 | command = ['juju-log'] |
1491 | 64 | if level: | 85 | if level: |
1492 | 65 | command += ['-l', level] | 86 | command += ['-l', level] |
1493 | 87 | if not isinstance(message, six.string_types): | ||
1494 | 88 | message = repr(message) | ||
1495 | 66 | command += [message] | 89 | command += [message] |
1496 | 67 | subprocess.call(command) | 90 | subprocess.call(command) |
1497 | 68 | 91 | ||
1498 | 69 | 92 | ||
1500 | 70 | class Serializable(UserDict.IterableUserDict): | 93 | class Serializable(UserDict): |
1501 | 71 | """Wrapper, an object that can be serialized to yaml or json""" | 94 | """Wrapper, an object that can be serialized to yaml or json""" |
1502 | 72 | 95 | ||
1503 | 73 | def __init__(self, obj): | 96 | def __init__(self, obj): |
1504 | 74 | # wrap the object | 97 | # wrap the object |
1506 | 75 | UserDict.IterableUserDict.__init__(self) | 98 | UserDict.__init__(self) |
1507 | 76 | self.data = obj | 99 | self.data = obj |
1508 | 77 | 100 | ||
1509 | 78 | def __getattr__(self, attr): | 101 | def __getattr__(self, attr): |
1510 | @@ -203,6 +226,23 @@ | |||
1511 | 203 | if os.path.exists(self.path): | 226 | if os.path.exists(self.path): |
1512 | 204 | self.load_previous() | 227 | self.load_previous() |
1513 | 205 | 228 | ||
1514 | 229 | def __getitem__(self, key): | ||
1515 | 230 | """For regular dict lookups, check the current juju config first, | ||
1516 | 231 | then the previous (saved) copy. This ensures that user-saved values | ||
1517 | 232 | will be returned by a dict lookup. | ||
1518 | 233 | |||
1519 | 234 | """ | ||
1520 | 235 | try: | ||
1521 | 236 | return dict.__getitem__(self, key) | ||
1522 | 237 | except KeyError: | ||
1523 | 238 | return (self._prev_dict or {})[key] | ||
1524 | 239 | |||
1525 | 240 | def keys(self): | ||
1526 | 241 | prev_keys = [] | ||
1527 | 242 | if self._prev_dict is not None: | ||
1528 | 243 | prev_keys = self._prev_dict.keys() | ||
1529 | 244 | return list(set(prev_keys + list(dict.keys(self)))) | ||
1530 | 245 | |||
1531 | 206 | def load_previous(self, path=None): | 246 | def load_previous(self, path=None): |
1532 | 207 | """Load previous copy of config from disk. | 247 | """Load previous copy of config from disk. |
1533 | 208 | 248 | ||
1534 | @@ -252,7 +292,7 @@ | |||
1535 | 252 | 292 | ||
1536 | 253 | """ | 293 | """ |
1537 | 254 | if self._prev_dict: | 294 | if self._prev_dict: |
1539 | 255 | for k, v in self._prev_dict.iteritems(): | 295 | for k, v in six.iteritems(self._prev_dict): |
1540 | 256 | if k not in self: | 296 | if k not in self: |
1541 | 257 | self[k] = v | 297 | self[k] = v |
1542 | 258 | with open(self.path, 'w') as f: | 298 | with open(self.path, 'w') as f: |
1543 | @@ -267,7 +307,8 @@ | |||
1544 | 267 | config_cmd_line.append(scope) | 307 | config_cmd_line.append(scope) |
1545 | 268 | config_cmd_line.append('--format=json') | 308 | config_cmd_line.append('--format=json') |
1546 | 269 | try: | 309 | try: |
1548 | 270 | config_data = json.loads(subprocess.check_output(config_cmd_line)) | 310 | config_data = json.loads( |
1549 | 311 | subprocess.check_output(config_cmd_line).decode('UTF-8')) | ||
1550 | 271 | if scope is not None: | 312 | if scope is not None: |
1551 | 272 | return config_data | 313 | return config_data |
1552 | 273 | return Config(config_data) | 314 | return Config(config_data) |
1553 | @@ -286,10 +327,10 @@ | |||
1554 | 286 | if unit: | 327 | if unit: |
1555 | 287 | _args.append(unit) | 328 | _args.append(unit) |
1556 | 288 | try: | 329 | try: |
1558 | 289 | return json.loads(subprocess.check_output(_args)) | 330 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) |
1559 | 290 | except ValueError: | 331 | except ValueError: |
1560 | 291 | return None | 332 | return None |
1562 | 292 | except CalledProcessError, e: | 333 | except CalledProcessError as e: |
1563 | 293 | if e.returncode == 2: | 334 | if e.returncode == 2: |
1564 | 294 | return None | 335 | return None |
1565 | 295 | raise | 336 | raise |
1566 | @@ -301,7 +342,7 @@ | |||
1567 | 301 | relation_cmd_line = ['relation-set'] | 342 | relation_cmd_line = ['relation-set'] |
1568 | 302 | if relation_id is not None: | 343 | if relation_id is not None: |
1569 | 303 | relation_cmd_line.extend(('-r', relation_id)) | 344 | relation_cmd_line.extend(('-r', relation_id)) |
1571 | 304 | for k, v in (relation_settings.items() + kwargs.items()): | 345 | for k, v in (list(relation_settings.items()) + list(kwargs.items())): |
1572 | 305 | if v is None: | 346 | if v is None: |
1573 | 306 | relation_cmd_line.append('{}='.format(k)) | 347 | relation_cmd_line.append('{}='.format(k)) |
1574 | 307 | else: | 348 | else: |
1575 | @@ -318,7 +359,8 @@ | |||
1576 | 318 | relid_cmd_line = ['relation-ids', '--format=json'] | 359 | relid_cmd_line = ['relation-ids', '--format=json'] |
1577 | 319 | if reltype is not None: | 360 | if reltype is not None: |
1578 | 320 | relid_cmd_line.append(reltype) | 361 | relid_cmd_line.append(reltype) |
1580 | 321 | return json.loads(subprocess.check_output(relid_cmd_line)) or [] | 362 | return json.loads( |
1581 | 363 | subprocess.check_output(relid_cmd_line).decode('UTF-8')) or [] | ||
1582 | 322 | return [] | 364 | return [] |
1583 | 323 | 365 | ||
1584 | 324 | 366 | ||
1585 | @@ -329,7 +371,8 @@ | |||
1586 | 329 | units_cmd_line = ['relation-list', '--format=json'] | 371 | units_cmd_line = ['relation-list', '--format=json'] |
1587 | 330 | if relid is not None: | 372 | if relid is not None: |
1588 | 331 | units_cmd_line.extend(('-r', relid)) | 373 | units_cmd_line.extend(('-r', relid)) |
1590 | 332 | return json.loads(subprocess.check_output(units_cmd_line)) or [] | 374 | return json.loads( |
1591 | 375 | subprocess.check_output(units_cmd_line).decode('UTF-8')) or [] | ||
1592 | 333 | 376 | ||
1593 | 334 | 377 | ||
1594 | 335 | @cached | 378 | @cached |
1595 | @@ -369,21 +412,31 @@ | |||
1596 | 369 | 412 | ||
1597 | 370 | 413 | ||
1598 | 371 | @cached | 414 | @cached |
1599 | 415 | def metadata(): | ||
1600 | 416 | """Get the current charm metadata.yaml contents as a python object""" | ||
1601 | 417 | with open(os.path.join(charm_dir(), 'metadata.yaml')) as md: | ||
1602 | 418 | return yaml.safe_load(md) | ||
1603 | 419 | |||
1604 | 420 | |||
1605 | 421 | @cached | ||
1606 | 372 | def relation_types(): | 422 | def relation_types(): |
1607 | 373 | """Get a list of relation types supported by this charm""" | 423 | """Get a list of relation types supported by this charm""" |
1608 | 374 | charmdir = os.environ.get('CHARM_DIR', '') | ||
1609 | 375 | mdf = open(os.path.join(charmdir, 'metadata.yaml')) | ||
1610 | 376 | md = yaml.safe_load(mdf) | ||
1611 | 377 | rel_types = [] | 424 | rel_types = [] |
1612 | 425 | md = metadata() | ||
1613 | 378 | for key in ('provides', 'requires', 'peers'): | 426 | for key in ('provides', 'requires', 'peers'): |
1614 | 379 | section = md.get(key) | 427 | section = md.get(key) |
1615 | 380 | if section: | 428 | if section: |
1616 | 381 | rel_types.extend(section.keys()) | 429 | rel_types.extend(section.keys()) |
1617 | 382 | mdf.close() | ||
1618 | 383 | return rel_types | 430 | return rel_types |
1619 | 384 | 431 | ||
1620 | 385 | 432 | ||
1621 | 386 | @cached | 433 | @cached |
1622 | 434 | def charm_name(): | ||
1623 | 435 | """Get the name of the current charm as is specified on metadata.yaml""" | ||
1624 | 436 | return metadata().get('name') | ||
1625 | 437 | |||
1626 | 438 | |||
1627 | 439 | @cached | ||
1628 | 387 | def relations(): | 440 | def relations(): |
1629 | 388 | """Get a nested dictionary of relation data for all related units""" | 441 | """Get a nested dictionary of relation data for all related units""" |
1630 | 389 | rels = {} | 442 | rels = {} |
1631 | @@ -438,7 +491,7 @@ | |||
1632 | 438 | """Get the unit ID for the remote unit""" | 491 | """Get the unit ID for the remote unit""" |
1633 | 439 | _args = ['unit-get', '--format=json', attribute] | 492 | _args = ['unit-get', '--format=json', attribute] |
1634 | 440 | try: | 493 | try: |
1636 | 441 | return json.loads(subprocess.check_output(_args)) | 494 | return json.loads(subprocess.check_output(_args).decode('UTF-8')) |
1637 | 442 | except ValueError: | 495 | except ValueError: |
1638 | 443 | return None | 496 | return None |
1639 | 444 | 497 | ||
1640 | @@ -475,9 +528,10 @@ | |||
1641 | 475 | hooks.execute(sys.argv) | 528 | hooks.execute(sys.argv) |
1642 | 476 | """ | 529 | """ |
1643 | 477 | 530 | ||
1645 | 478 | def __init__(self): | 531 | def __init__(self, config_save=True): |
1646 | 479 | super(Hooks, self).__init__() | 532 | super(Hooks, self).__init__() |
1647 | 480 | self._hooks = {} | 533 | self._hooks = {} |
1648 | 534 | self._config_save = config_save | ||
1649 | 481 | 535 | ||
1650 | 482 | def register(self, name, function): | 536 | def register(self, name, function): |
1651 | 483 | """Register a hook""" | 537 | """Register a hook""" |
1652 | @@ -488,9 +542,10 @@ | |||
1653 | 488 | hook_name = os.path.basename(args[0]) | 542 | hook_name = os.path.basename(args[0]) |
1654 | 489 | if hook_name in self._hooks: | 543 | if hook_name in self._hooks: |
1655 | 490 | self._hooks[hook_name]() | 544 | self._hooks[hook_name]() |
1659 | 491 | cfg = config() | 545 | if self._config_save: |
1660 | 492 | if cfg.implicit_save: | 546 | cfg = config() |
1661 | 493 | cfg.save() | 547 | if cfg.implicit_save: |
1662 | 548 | cfg.save() | ||
1663 | 494 | else: | 549 | else: |
1664 | 495 | raise UnregisteredHookError(hook_name) | 550 | raise UnregisteredHookError(hook_name) |
1665 | 496 | 551 | ||
1666 | @@ -511,3 +566,29 @@ | |||
1667 | 511 | def charm_dir(): | 566 | def charm_dir(): |
1668 | 512 | """Return the root directory of the current charm""" | 567 | """Return the root directory of the current charm""" |
1669 | 513 | return os.environ.get('CHARM_DIR') | 568 | return os.environ.get('CHARM_DIR') |
1670 | 569 | |||
1671 | 570 | |||
1672 | 571 | @cached | ||
1673 | 572 | def action_get(key=None): | ||
1674 | 573 | """Gets the value of an action parameter, or all key/value param pairs""" | ||
1675 | 574 | cmd = ['action-get'] | ||
1676 | 575 | if key is not None: | ||
1677 | 576 | cmd.append(key) | ||
1678 | 577 | cmd.append('--format=json') | ||
1679 | 578 | action_data = json.loads(subprocess.check_output(cmd).decode('UTF-8')) | ||
1680 | 579 | return action_data | ||
1681 | 580 | |||
1682 | 581 | |||
1683 | 582 | def action_set(values): | ||
1684 | 583 | """Sets the values to be returned after the action finishes""" | ||
1685 | 584 | cmd = ['action-set'] | ||
1686 | 585 | for k, v in list(values.items()): | ||
1687 | 586 | cmd.append('{}={}'.format(k, v)) | ||
1688 | 587 | subprocess.check_call(cmd) | ||
1689 | 588 | |||
1690 | 589 | |||
1691 | 590 | def action_fail(message): | ||
1692 | 591 | """Sets the action status to failed and sets the error message. | ||
1693 | 592 | |||
1694 | 593 | The results set by action_set are preserved.""" | ||
1695 | 594 | subprocess.check_call(['action-fail', message]) | ||
1696 | 514 | 595 | ||
1697 | === modified file 'hooks/charmhelpers/core/host.py' | |||
1698 | --- hooks/charmhelpers/core/host.py 2014-09-08 16:38:59 +0000 | |||
1699 | +++ hooks/charmhelpers/core/host.py 2015-03-23 00:51:45 +0000 | |||
1700 | @@ -1,3 +1,19 @@ | |||
1701 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
1702 | 2 | # | ||
1703 | 3 | # This file is part of charm-helpers. | ||
1704 | 4 | # | ||
1705 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
1706 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
1707 | 7 | # published by the Free Software Foundation. | ||
1708 | 8 | # | ||
1709 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
1710 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1711 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1712 | 12 | # GNU Lesser General Public License for more details. | ||
1713 | 13 | # | ||
1714 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
1715 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
1716 | 16 | |||
1717 | 1 | """Tools for working with the host system""" | 17 | """Tools for working with the host system""" |
1718 | 2 | # Copyright 2012 Canonical Ltd. | 18 | # Copyright 2012 Canonical Ltd. |
1719 | 3 | # | 19 | # |
1720 | @@ -6,19 +22,20 @@ | |||
1721 | 6 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> | 22 | # Matthew Wedgwood <matthew.wedgwood@canonical.com> |
1722 | 7 | 23 | ||
1723 | 8 | import os | 24 | import os |
1724 | 25 | import re | ||
1725 | 9 | import pwd | 26 | import pwd |
1726 | 10 | import grp | 27 | import grp |
1727 | 11 | import random | 28 | import random |
1728 | 12 | import string | 29 | import string |
1729 | 13 | import subprocess | 30 | import subprocess |
1730 | 14 | import hashlib | 31 | import hashlib |
1731 | 15 | import shutil | ||
1732 | 16 | from contextlib import contextmanager | 32 | from contextlib import contextmanager |
1733 | 17 | |||
1734 | 18 | from collections import OrderedDict | 33 | from collections import OrderedDict |
1735 | 19 | 34 | ||
1738 | 20 | from hookenv import log | 35 | import six |
1739 | 21 | from fstab import Fstab | 36 | |
1740 | 37 | from .hookenv import log | ||
1741 | 38 | from .fstab import Fstab | ||
1742 | 22 | 39 | ||
1743 | 23 | 40 | ||
1744 | 24 | def service_start(service_name): | 41 | def service_start(service_name): |
1745 | @@ -54,7 +71,9 @@ | |||
1746 | 54 | def service_running(service): | 71 | def service_running(service): |
1747 | 55 | """Determine whether a system service is running""" | 72 | """Determine whether a system service is running""" |
1748 | 56 | try: | 73 | try: |
1750 | 57 | output = subprocess.check_output(['service', service, 'status'], stderr=subprocess.STDOUT) | 74 | output = subprocess.check_output( |
1751 | 75 | ['service', service, 'status'], | ||
1752 | 76 | stderr=subprocess.STDOUT).decode('UTF-8') | ||
1753 | 58 | except subprocess.CalledProcessError: | 77 | except subprocess.CalledProcessError: |
1754 | 59 | return False | 78 | return False |
1755 | 60 | else: | 79 | else: |
1756 | @@ -67,9 +86,11 @@ | |||
1757 | 67 | def service_available(service_name): | 86 | def service_available(service_name): |
1758 | 68 | """Determine whether a system service is available""" | 87 | """Determine whether a system service is available""" |
1759 | 69 | try: | 88 | try: |
1763 | 70 | subprocess.check_output(['service', service_name, 'status'], stderr=subprocess.STDOUT) | 89 | subprocess.check_output( |
1764 | 71 | except subprocess.CalledProcessError: | 90 | ['service', service_name, 'status'], |
1765 | 72 | return False | 91 | stderr=subprocess.STDOUT).decode('UTF-8') |
1766 | 92 | except subprocess.CalledProcessError as e: | ||
1767 | 93 | return 'unrecognized service' not in e.output | ||
1768 | 73 | else: | 94 | else: |
1769 | 74 | return True | 95 | return True |
1770 | 75 | 96 | ||
1771 | @@ -96,6 +117,26 @@ | |||
1772 | 96 | return user_info | 117 | return user_info |
1773 | 97 | 118 | ||
1774 | 98 | 119 | ||
1775 | 120 | def add_group(group_name, system_group=False): | ||
1776 | 121 | """Add a group to the system""" | ||
1777 | 122 | try: | ||
1778 | 123 | group_info = grp.getgrnam(group_name) | ||
1779 | 124 | log('group {0} already exists!'.format(group_name)) | ||
1780 | 125 | except KeyError: | ||
1781 | 126 | log('creating group {0}'.format(group_name)) | ||
1782 | 127 | cmd = ['addgroup'] | ||
1783 | 128 | if system_group: | ||
1784 | 129 | cmd.append('--system') | ||
1785 | 130 | else: | ||
1786 | 131 | cmd.extend([ | ||
1787 | 132 | '--group', | ||
1788 | 133 | ]) | ||
1789 | 134 | cmd.append(group_name) | ||
1790 | 135 | subprocess.check_call(cmd) | ||
1791 | 136 | group_info = grp.getgrnam(group_name) | ||
1792 | 137 | return group_info | ||
1793 | 138 | |||
1794 | 139 | |||
1795 | 99 | def add_user_to_group(username, group): | 140 | def add_user_to_group(username, group): |
1796 | 100 | """Add a user to a group""" | 141 | """Add a user to a group""" |
1797 | 101 | cmd = [ | 142 | cmd = [ |
1798 | @@ -115,7 +156,7 @@ | |||
1799 | 115 | cmd.append(from_path) | 156 | cmd.append(from_path) |
1800 | 116 | cmd.append(to_path) | 157 | cmd.append(to_path) |
1801 | 117 | log(" ".join(cmd)) | 158 | log(" ".join(cmd)) |
1803 | 118 | return subprocess.check_output(cmd).strip() | 159 | return subprocess.check_output(cmd).decode('UTF-8').strip() |
1804 | 119 | 160 | ||
1805 | 120 | 161 | ||
1806 | 121 | def symlink(source, destination): | 162 | def symlink(source, destination): |
1807 | @@ -130,28 +171,31 @@ | |||
1808 | 130 | subprocess.check_call(cmd) | 171 | subprocess.check_call(cmd) |
1809 | 131 | 172 | ||
1810 | 132 | 173 | ||
1812 | 133 | def mkdir(path, owner='root', group='root', perms=0555, force=False): | 174 | def mkdir(path, owner='root', group='root', perms=0o555, force=False): |
1813 | 134 | """Create a directory""" | 175 | """Create a directory""" |
1814 | 135 | log("Making dir {} {}:{} {:o}".format(path, owner, group, | 176 | log("Making dir {} {}:{} {:o}".format(path, owner, group, |
1815 | 136 | perms)) | 177 | perms)) |
1816 | 137 | uid = pwd.getpwnam(owner).pw_uid | 178 | uid = pwd.getpwnam(owner).pw_uid |
1817 | 138 | gid = grp.getgrnam(group).gr_gid | 179 | gid = grp.getgrnam(group).gr_gid |
1818 | 139 | realpath = os.path.abspath(path) | 180 | realpath = os.path.abspath(path) |
1821 | 140 | if os.path.exists(realpath): | 181 | path_exists = os.path.exists(realpath) |
1822 | 141 | if force and not os.path.isdir(realpath): | 182 | if path_exists and force: |
1823 | 183 | if not os.path.isdir(realpath): | ||
1824 | 142 | log("Removing non-directory file {} prior to mkdir()".format(path)) | 184 | log("Removing non-directory file {} prior to mkdir()".format(path)) |
1825 | 143 | os.unlink(realpath) | 185 | os.unlink(realpath) |
1827 | 144 | else: | 186 | os.makedirs(realpath, perms) |
1828 | 187 | elif not path_exists: | ||
1829 | 145 | os.makedirs(realpath, perms) | 188 | os.makedirs(realpath, perms) |
1830 | 146 | os.chown(realpath, uid, gid) | 189 | os.chown(realpath, uid, gid) |
1835 | 147 | 190 | os.chmod(realpath, perms) | |
1836 | 148 | 191 | ||
1837 | 149 | def write_file(path, content, owner='root', group='root', perms=0444): | 192 | |
1838 | 150 | """Create or overwrite a file with the contents of a string""" | 193 | def write_file(path, content, owner='root', group='root', perms=0o444): |
1839 | 194 | """Create or overwrite a file with the contents of a byte string.""" | ||
1840 | 151 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) | 195 | log("Writing file {} {}:{} {:o}".format(path, owner, group, perms)) |
1841 | 152 | uid = pwd.getpwnam(owner).pw_uid | 196 | uid = pwd.getpwnam(owner).pw_uid |
1842 | 153 | gid = grp.getgrnam(group).gr_gid | 197 | gid = grp.getgrnam(group).gr_gid |
1844 | 154 | with open(path, 'w') as target: | 198 | with open(path, 'wb') as target: |
1845 | 155 | os.fchown(target.fileno(), uid, gid) | 199 | os.fchown(target.fileno(), uid, gid) |
1846 | 156 | os.fchmod(target.fileno(), perms) | 200 | os.fchmod(target.fileno(), perms) |
1847 | 157 | target.write(content) | 201 | target.write(content) |
1848 | @@ -177,7 +221,7 @@ | |||
1849 | 177 | cmd_args.extend([device, mountpoint]) | 221 | cmd_args.extend([device, mountpoint]) |
1850 | 178 | try: | 222 | try: |
1851 | 179 | subprocess.check_output(cmd_args) | 223 | subprocess.check_output(cmd_args) |
1853 | 180 | except subprocess.CalledProcessError, e: | 224 | except subprocess.CalledProcessError as e: |
1854 | 181 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) | 225 | log('Error mounting {} at {}\n{}'.format(device, mountpoint, e.output)) |
1855 | 182 | return False | 226 | return False |
1856 | 183 | 227 | ||
1857 | @@ -191,7 +235,7 @@ | |||
1858 | 191 | cmd_args = ['umount', mountpoint] | 235 | cmd_args = ['umount', mountpoint] |
1859 | 192 | try: | 236 | try: |
1860 | 193 | subprocess.check_output(cmd_args) | 237 | subprocess.check_output(cmd_args) |
1862 | 194 | except subprocess.CalledProcessError, e: | 238 | except subprocess.CalledProcessError as e: |
1863 | 195 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) | 239 | log('Error unmounting {}\n{}'.format(mountpoint, e.output)) |
1864 | 196 | return False | 240 | return False |
1865 | 197 | 241 | ||
1866 | @@ -209,17 +253,42 @@ | |||
1867 | 209 | return system_mounts | 253 | return system_mounts |
1868 | 210 | 254 | ||
1869 | 211 | 255 | ||
1872 | 212 | def file_hash(path): | 256 | def file_hash(path, hash_type='md5'): |
1873 | 213 | """Generate a md5 hash of the contents of 'path' or None if not found """ | 257 | """ |
1874 | 258 | Generate a hash checksum of the contents of 'path' or None if not found. | ||
1875 | 259 | |||
1876 | 260 | :param str hash_type: Any hash alrgorithm supported by :mod:`hashlib`, | ||
1877 | 261 | such as md5, sha1, sha256, sha512, etc. | ||
1878 | 262 | """ | ||
1879 | 214 | if os.path.exists(path): | 263 | if os.path.exists(path): |
1883 | 215 | h = hashlib.md5() | 264 | h = getattr(hashlib, hash_type)() |
1884 | 216 | with open(path, 'r') as source: | 265 | with open(path, 'rb') as source: |
1885 | 217 | h.update(source.read()) # IGNORE:E1101 - it does have update | 266 | h.update(source.read()) |
1886 | 218 | return h.hexdigest() | 267 | return h.hexdigest() |
1887 | 219 | else: | 268 | else: |
1888 | 220 | return None | 269 | return None |
1889 | 221 | 270 | ||
1890 | 222 | 271 | ||
1891 | 272 | def check_hash(path, checksum, hash_type='md5'): | ||
1892 | 273 | """ | ||
1893 | 274 | Validate a file using a cryptographic checksum. | ||
1894 | 275 | |||
1895 | 276 | :param str checksum: Value of the checksum used to validate the file. | ||
1896 | 277 | :param str hash_type: Hash algorithm used to generate `checksum`. | ||
1897 | 278 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
1898 | 279 | such as md5, sha1, sha256, sha512, etc. | ||
1899 | 280 | :raises ChecksumError: If the file fails the checksum | ||
1900 | 281 | |||
1901 | 282 | """ | ||
1902 | 283 | actual_checksum = file_hash(path, hash_type) | ||
1903 | 284 | if checksum != actual_checksum: | ||
1904 | 285 | raise ChecksumError("'%s' != '%s'" % (checksum, actual_checksum)) | ||
1905 | 286 | |||
1906 | 287 | |||
1907 | 288 | class ChecksumError(ValueError): | ||
1908 | 289 | pass | ||
1909 | 290 | |||
1910 | 291 | |||
1911 | 223 | def restart_on_change(restart_map, stopstart=False): | 292 | def restart_on_change(restart_map, stopstart=False): |
1912 | 224 | """Restart services based on configuration files changing | 293 | """Restart services based on configuration files changing |
1913 | 225 | 294 | ||
1914 | @@ -236,11 +305,11 @@ | |||
1915 | 236 | ceph_client_changed function. | 305 | ceph_client_changed function. |
1916 | 237 | """ | 306 | """ |
1917 | 238 | def wrap(f): | 307 | def wrap(f): |
1919 | 239 | def wrapped_f(*args): | 308 | def wrapped_f(*args, **kwargs): |
1920 | 240 | checksums = {} | 309 | checksums = {} |
1921 | 241 | for path in restart_map: | 310 | for path in restart_map: |
1922 | 242 | checksums[path] = file_hash(path) | 311 | checksums[path] = file_hash(path) |
1924 | 243 | f(*args) | 312 | f(*args, **kwargs) |
1925 | 244 | restarts = [] | 313 | restarts = [] |
1926 | 245 | for path in restart_map: | 314 | for path in restart_map: |
1927 | 246 | if checksums[path] != file_hash(path): | 315 | if checksums[path] != file_hash(path): |
1928 | @@ -270,29 +339,39 @@ | |||
1929 | 270 | def pwgen(length=None): | 339 | def pwgen(length=None): |
1930 | 271 | """Generate a random pasword.""" | 340 | """Generate a random pasword.""" |
1931 | 272 | if length is None: | 341 | if length is None: |
1932 | 342 | # A random length is ok to use a weak PRNG | ||
1933 | 273 | length = random.choice(range(35, 45)) | 343 | length = random.choice(range(35, 45)) |
1934 | 274 | alphanumeric_chars = [ | 344 | alphanumeric_chars = [ |
1936 | 275 | l for l in (string.letters + string.digits) | 345 | l for l in (string.ascii_letters + string.digits) |
1937 | 276 | if l not in 'l0QD1vAEIOUaeiou'] | 346 | if l not in 'l0QD1vAEIOUaeiou'] |
1938 | 347 | # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the | ||
1939 | 348 | # actual password | ||
1940 | 349 | random_generator = random.SystemRandom() | ||
1941 | 277 | random_chars = [ | 350 | random_chars = [ |
1943 | 278 | random.choice(alphanumeric_chars) for _ in range(length)] | 351 | random_generator.choice(alphanumeric_chars) for _ in range(length)] |
1944 | 279 | return(''.join(random_chars)) | 352 | return(''.join(random_chars)) |
1945 | 280 | 353 | ||
1946 | 281 | 354 | ||
1947 | 282 | def list_nics(nic_type): | 355 | def list_nics(nic_type): |
1948 | 283 | '''Return a list of nics of given type(s)''' | 356 | '''Return a list of nics of given type(s)''' |
1950 | 284 | if isinstance(nic_type, basestring): | 357 | if isinstance(nic_type, six.string_types): |
1951 | 285 | int_types = [nic_type] | 358 | int_types = [nic_type] |
1952 | 286 | else: | 359 | else: |
1953 | 287 | int_types = nic_type | 360 | int_types = nic_type |
1954 | 288 | interfaces = [] | 361 | interfaces = [] |
1955 | 289 | for int_type in int_types: | 362 | for int_type in int_types: |
1956 | 290 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] | 363 | cmd = ['ip', 'addr', 'show', 'label', int_type + '*'] |
1958 | 291 | ip_output = subprocess.check_output(cmd).split('\n') | 364 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') |
1959 | 292 | ip_output = (line for line in ip_output if line) | 365 | ip_output = (line for line in ip_output if line) |
1960 | 293 | for line in ip_output: | 366 | for line in ip_output: |
1961 | 294 | if line.split()[1].startswith(int_type): | 367 | if line.split()[1].startswith(int_type): |
1963 | 295 | interfaces.append(line.split()[1].replace(":", "")) | 368 | matched = re.search('.*: (' + int_type + r'[0-9]+\.[0-9]+)@.*', line) |
1964 | 369 | if matched: | ||
1965 | 370 | interface = matched.groups()[0] | ||
1966 | 371 | else: | ||
1967 | 372 | interface = line.split()[1].replace(":", "") | ||
1968 | 373 | interfaces.append(interface) | ||
1969 | 374 | |||
1970 | 296 | return interfaces | 375 | return interfaces |
1971 | 297 | 376 | ||
1972 | 298 | 377 | ||
1973 | @@ -304,7 +383,7 @@ | |||
1974 | 304 | 383 | ||
1975 | 305 | def get_nic_mtu(nic): | 384 | def get_nic_mtu(nic): |
1976 | 306 | cmd = ['ip', 'addr', 'show', nic] | 385 | cmd = ['ip', 'addr', 'show', nic] |
1978 | 307 | ip_output = subprocess.check_output(cmd).split('\n') | 386 | ip_output = subprocess.check_output(cmd).decode('UTF-8').split('\n') |
1979 | 308 | mtu = "" | 387 | mtu = "" |
1980 | 309 | for line in ip_output: | 388 | for line in ip_output: |
1981 | 310 | words = line.split() | 389 | words = line.split() |
1982 | @@ -315,7 +394,7 @@ | |||
1983 | 315 | 394 | ||
1984 | 316 | def get_nic_hwaddr(nic): | 395 | def get_nic_hwaddr(nic): |
1985 | 317 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] | 396 | cmd = ['ip', '-o', '-0', 'addr', 'show', nic] |
1987 | 318 | ip_output = subprocess.check_output(cmd) | 397 | ip_output = subprocess.check_output(cmd).decode('UTF-8') |
1988 | 319 | hwaddr = "" | 398 | hwaddr = "" |
1989 | 320 | words = ip_output.split() | 399 | words = ip_output.split() |
1990 | 321 | if 'link/ether' in words: | 400 | if 'link/ether' in words: |
1991 | @@ -330,10 +409,13 @@ | |||
1992 | 330 | * 0 => Installed revno is the same as supplied arg | 409 | * 0 => Installed revno is the same as supplied arg |
1993 | 331 | * -1 => Installed revno is less than supplied arg | 410 | * -1 => Installed revno is less than supplied arg |
1994 | 332 | 411 | ||
1995 | 412 | This function imports apt_cache function from charmhelpers.fetch if | ||
1996 | 413 | the pkgcache argument is None. Be sure to add charmhelpers.fetch if | ||
1997 | 414 | you call this function, or pass an apt_pkg.Cache() instance. | ||
1998 | 333 | ''' | 415 | ''' |
1999 | 334 | import apt_pkg | 416 | import apt_pkg |
2000 | 335 | from charmhelpers.fetch import apt_cache | ||
2001 | 336 | if not pkgcache: | 417 | if not pkgcache: |
2002 | 418 | from charmhelpers.fetch import apt_cache | ||
2003 | 337 | pkgcache = apt_cache() | 419 | pkgcache = apt_cache() |
2004 | 338 | pkg = pkgcache[package] | 420 | pkg = pkgcache[package] |
2005 | 339 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) | 421 | return apt_pkg.version_compare(pkg.current_ver.ver_str, revno) |
2006 | @@ -348,13 +430,21 @@ | |||
2007 | 348 | os.chdir(cur) | 430 | os.chdir(cur) |
2008 | 349 | 431 | ||
2009 | 350 | 432 | ||
2011 | 351 | def chownr(path, owner, group): | 433 | def chownr(path, owner, group, follow_links=True): |
2012 | 352 | uid = pwd.getpwnam(owner).pw_uid | 434 | uid = pwd.getpwnam(owner).pw_uid |
2013 | 353 | gid = grp.getgrnam(group).gr_gid | 435 | gid = grp.getgrnam(group).gr_gid |
2014 | 436 | if follow_links: | ||
2015 | 437 | chown = os.chown | ||
2016 | 438 | else: | ||
2017 | 439 | chown = os.lchown | ||
2018 | 354 | 440 | ||
2019 | 355 | for root, dirs, files in os.walk(path): | 441 | for root, dirs, files in os.walk(path): |
2020 | 356 | for name in dirs + files: | 442 | for name in dirs + files: |
2021 | 357 | full = os.path.join(root, name) | 443 | full = os.path.join(root, name) |
2022 | 358 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) | 444 | broken_symlink = os.path.lexists(full) and not os.path.exists(full) |
2023 | 359 | if not broken_symlink: | 445 | if not broken_symlink: |
2025 | 360 | os.chown(full, uid, gid) | 446 | chown(full, uid, gid) |
2026 | 447 | |||
2027 | 448 | |||
2028 | 449 | def lchownr(path, owner, group): | ||
2029 | 450 | chownr(path, owner, group, follow_links=False) | ||
2030 | 361 | 451 | ||
2031 | === added directory 'hooks/charmhelpers/core/services' | |||
2032 | === added file 'hooks/charmhelpers/core/services/__init__.py' | |||
2033 | --- hooks/charmhelpers/core/services/__init__.py 1970-01-01 00:00:00 +0000 | |||
2034 | +++ hooks/charmhelpers/core/services/__init__.py 2015-03-23 00:51:45 +0000 | |||
2035 | @@ -0,0 +1,18 @@ | |||
2036 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2037 | 2 | # | ||
2038 | 3 | # This file is part of charm-helpers. | ||
2039 | 4 | # | ||
2040 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2041 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2042 | 7 | # published by the Free Software Foundation. | ||
2043 | 8 | # | ||
2044 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2045 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2046 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2047 | 12 | # GNU Lesser General Public License for more details. | ||
2048 | 13 | # | ||
2049 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2050 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2051 | 16 | |||
2052 | 17 | from .base import * # NOQA | ||
2053 | 18 | from .helpers import * # NOQA | ||
2054 | 0 | 19 | ||
2055 | === added file 'hooks/charmhelpers/core/services/base.py' | |||
2056 | --- hooks/charmhelpers/core/services/base.py 1970-01-01 00:00:00 +0000 | |||
2057 | +++ hooks/charmhelpers/core/services/base.py 2015-03-23 00:51:45 +0000 | |||
2058 | @@ -0,0 +1,329 @@ | |||
2059 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2060 | 2 | # | ||
2061 | 3 | # This file is part of charm-helpers. | ||
2062 | 4 | # | ||
2063 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2064 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2065 | 7 | # published by the Free Software Foundation. | ||
2066 | 8 | # | ||
2067 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2068 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2069 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2070 | 12 | # GNU Lesser General Public License for more details. | ||
2071 | 13 | # | ||
2072 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2073 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2074 | 16 | |||
2075 | 17 | import os | ||
2076 | 18 | import re | ||
2077 | 19 | import json | ||
2078 | 20 | from collections import Iterable | ||
2079 | 21 | |||
2080 | 22 | from charmhelpers.core import host | ||
2081 | 23 | from charmhelpers.core import hookenv | ||
2082 | 24 | |||
2083 | 25 | |||
2084 | 26 | __all__ = ['ServiceManager', 'ManagerCallback', | ||
2085 | 27 | 'PortManagerCallback', 'open_ports', 'close_ports', 'manage_ports', | ||
2086 | 28 | 'service_restart', 'service_stop'] | ||
2087 | 29 | |||
2088 | 30 | |||
2089 | 31 | class ServiceManager(object): | ||
2090 | 32 | def __init__(self, services=None): | ||
2091 | 33 | """ | ||
2092 | 34 | Register a list of services, given their definitions. | ||
2093 | 35 | |||
2094 | 36 | Service definitions are dicts in the following formats (all keys except | ||
2095 | 37 | 'service' are optional):: | ||
2096 | 38 | |||
2097 | 39 | { | ||
2098 | 40 | "service": <service name>, | ||
2099 | 41 | "required_data": <list of required data contexts>, | ||
2100 | 42 | "provided_data": <list of provided data contexts>, | ||
2101 | 43 | "data_ready": <one or more callbacks>, | ||
2102 | 44 | "data_lost": <one or more callbacks>, | ||
2103 | 45 | "start": <one or more callbacks>, | ||
2104 | 46 | "stop": <one or more callbacks>, | ||
2105 | 47 | "ports": <list of ports to manage>, | ||
2106 | 48 | } | ||
2107 | 49 | |||
2108 | 50 | The 'required_data' list should contain dicts of required data (or | ||
2109 | 51 | dependency managers that act like dicts and know how to collect the data). | ||
2110 | 52 | Only when all items in the 'required_data' list are populated are the list | ||
2111 | 53 | of 'data_ready' and 'start' callbacks executed. See `is_ready()` for more | ||
2112 | 54 | information. | ||
2113 | 55 | |||
2114 | 56 | The 'provided_data' list should contain relation data providers, most likely | ||
2115 | 57 | a subclass of :class:`charmhelpers.core.services.helpers.RelationContext`, | ||
2116 | 58 | that will indicate a set of data to set on a given relation. | ||
2117 | 59 | |||
2118 | 60 | The 'data_ready' value should be either a single callback, or a list of | ||
2119 | 61 | callbacks, to be called when all items in 'required_data' pass `is_ready()`. | ||
2120 | 62 | Each callback will be called with the service name as the only parameter. | ||
2121 | 63 | After all of the 'data_ready' callbacks are called, the 'start' callbacks | ||
2122 | 64 | are fired. | ||
2123 | 65 | |||
2124 | 66 | The 'data_lost' value should be either a single callback, or a list of | ||
2125 | 67 | callbacks, to be called when a 'required_data' item no longer passes | ||
2126 | 68 | `is_ready()`. Each callback will be called with the service name as the | ||
2127 | 69 | only parameter. After all of the 'data_lost' callbacks are called, | ||
2128 | 70 | the 'stop' callbacks are fired. | ||
2129 | 71 | |||
2130 | 72 | The 'start' value should be either a single callback, or a list of | ||
2131 | 73 | callbacks, to be called when starting the service, after the 'data_ready' | ||
2132 | 74 | callbacks are complete. Each callback will be called with the service | ||
2133 | 75 | name as the only parameter. This defaults to | ||
2134 | 76 | `[host.service_start, services.open_ports]`. | ||
2135 | 77 | |||
2136 | 78 | The 'stop' value should be either a single callback, or a list of | ||
2137 | 79 | callbacks, to be called when stopping the service. If the service is | ||
2138 | 80 | being stopped because it no longer has all of its 'required_data', this | ||
2139 | 81 | will be called after all of the 'data_lost' callbacks are complete. | ||
2140 | 82 | Each callback will be called with the service name as the only parameter. | ||
2141 | 83 | This defaults to `[services.close_ports, host.service_stop]`. | ||
2142 | 84 | |||
2143 | 85 | The 'ports' value should be a list of ports to manage. The default | ||
2144 | 86 | 'start' handler will open the ports after the service is started, | ||
2145 | 87 | and the default 'stop' handler will close the ports prior to stopping | ||
2146 | 88 | the service. | ||
2147 | 89 | |||
2148 | 90 | |||
2149 | 91 | Examples: | ||
2150 | 92 | |||
2151 | 93 | The following registers an Upstart service called bingod that depends on | ||
2152 | 94 | a mongodb relation and which runs a custom `db_migrate` function prior to | ||
2153 | 95 | restarting the service, and a Runit service called spadesd:: | ||
2154 | 96 | |||
2155 | 97 | manager = services.ServiceManager([ | ||
2156 | 98 | { | ||
2157 | 99 | 'service': 'bingod', | ||
2158 | 100 | 'ports': [80, 443], | ||
2159 | 101 | 'required_data': [MongoRelation(), config(), {'my': 'data'}], | ||
2160 | 102 | 'data_ready': [ | ||
2161 | 103 | services.template(source='bingod.conf'), | ||
2162 | 104 | services.template(source='bingod.ini', | ||
2163 | 105 | target='/etc/bingod.ini', | ||
2164 | 106 | owner='bingo', perms=0400), | ||
2165 | 107 | ], | ||
2166 | 108 | }, | ||
2167 | 109 | { | ||
2168 | 110 | 'service': 'spadesd', | ||
2169 | 111 | 'data_ready': services.template(source='spadesd_run.j2', | ||
2170 | 112 | target='/etc/sv/spadesd/run', | ||
2171 | 113 | perms=0555), | ||
2172 | 114 | 'start': runit_start, | ||
2173 | 115 | 'stop': runit_stop, | ||
2174 | 116 | }, | ||
2175 | 117 | ]) | ||
2176 | 118 | manager.manage() | ||
2177 | 119 | """ | ||
2178 | 120 | self._ready_file = os.path.join(hookenv.charm_dir(), 'READY-SERVICES.json') | ||
2179 | 121 | self._ready = None | ||
2180 | 122 | self.services = {} | ||
2181 | 123 | for service in services or []: | ||
2182 | 124 | service_name = service['service'] | ||
2183 | 125 | self.services[service_name] = service | ||
2184 | 126 | |||
2185 | 127 | def manage(self): | ||
2186 | 128 | """ | ||
2187 | 129 | Handle the current hook by doing The Right Thing with the registered services. | ||
2188 | 130 | """ | ||
2189 | 131 | hook_name = hookenv.hook_name() | ||
2190 | 132 | if hook_name == 'stop': | ||
2191 | 133 | self.stop_services() | ||
2192 | 134 | else: | ||
2193 | 135 | self.provide_data() | ||
2194 | 136 | self.reconfigure_services() | ||
2195 | 137 | cfg = hookenv.config() | ||
2196 | 138 | if cfg.implicit_save: | ||
2197 | 139 | cfg.save() | ||
2198 | 140 | |||
2199 | 141 | def provide_data(self): | ||
2200 | 142 | """ | ||
2201 | 143 | Set the relation data for each provider in the ``provided_data`` list. | ||
2202 | 144 | |||
2203 | 145 | A provider must have a `name` attribute, which indicates which relation | ||
2204 | 146 | to set data on, and a `provide_data()` method, which returns a dict of | ||
2205 | 147 | data to set. | ||
2206 | 148 | """ | ||
2207 | 149 | hook_name = hookenv.hook_name() | ||
2208 | 150 | for service in self.services.values(): | ||
2209 | 151 | for provider in service.get('provided_data', []): | ||
2210 | 152 | if re.match(r'{}-relation-(joined|changed)'.format(provider.name), hook_name): | ||
2211 | 153 | data = provider.provide_data() | ||
2212 | 154 | _ready = provider._is_ready(data) if hasattr(provider, '_is_ready') else data | ||
2213 | 155 | if _ready: | ||
2214 | 156 | hookenv.relation_set(None, data) | ||
2215 | 157 | |||
2216 | 158 | def reconfigure_services(self, *service_names): | ||
2217 | 159 | """ | ||
2218 | 160 | Update all files for one or more registered services, and, | ||
2219 | 161 | if ready, optionally restart them. | ||
2220 | 162 | |||
2221 | 163 | If no service names are given, reconfigures all registered services. | ||
2222 | 164 | """ | ||
2223 | 165 | for service_name in service_names or self.services.keys(): | ||
2224 | 166 | if self.is_ready(service_name): | ||
2225 | 167 | self.fire_event('data_ready', service_name) | ||
2226 | 168 | self.fire_event('start', service_name, default=[ | ||
2227 | 169 | service_restart, | ||
2228 | 170 | manage_ports]) | ||
2229 | 171 | self.save_ready(service_name) | ||
2230 | 172 | else: | ||
2231 | 173 | if self.was_ready(service_name): | ||
2232 | 174 | self.fire_event('data_lost', service_name) | ||
2233 | 175 | self.fire_event('stop', service_name, default=[ | ||
2234 | 176 | manage_ports, | ||
2235 | 177 | service_stop]) | ||
2236 | 178 | self.save_lost(service_name) | ||
2237 | 179 | |||
2238 | 180 | def stop_services(self, *service_names): | ||
2239 | 181 | """ | ||
2240 | 182 | Stop one or more registered services, by name. | ||
2241 | 183 | |||
2242 | 184 | If no service names are given, stops all registered services. | ||
2243 | 185 | """ | ||
2244 | 186 | for service_name in service_names or self.services.keys(): | ||
2245 | 187 | self.fire_event('stop', service_name, default=[ | ||
2246 | 188 | manage_ports, | ||
2247 | 189 | service_stop]) | ||
2248 | 190 | |||
2249 | 191 | def get_service(self, service_name): | ||
2250 | 192 | """ | ||
2251 | 193 | Given the name of a registered service, return its service definition. | ||
2252 | 194 | """ | ||
2253 | 195 | service = self.services.get(service_name) | ||
2254 | 196 | if not service: | ||
2255 | 197 | raise KeyError('Service not registered: %s' % service_name) | ||
2256 | 198 | return service | ||
2257 | 199 | |||
2258 | 200 | def fire_event(self, event_name, service_name, default=None): | ||
2259 | 201 | """ | ||
2260 | 202 | Fire a data_ready, data_lost, start, or stop event on a given service. | ||
2261 | 203 | """ | ||
2262 | 204 | service = self.get_service(service_name) | ||
2263 | 205 | callbacks = service.get(event_name, default) | ||
2264 | 206 | if not callbacks: | ||
2265 | 207 | return | ||
2266 | 208 | if not isinstance(callbacks, Iterable): | ||
2267 | 209 | callbacks = [callbacks] | ||
2268 | 210 | for callback in callbacks: | ||
2269 | 211 | if isinstance(callback, ManagerCallback): | ||
2270 | 212 | callback(self, service_name, event_name) | ||
2271 | 213 | else: | ||
2272 | 214 | callback(service_name) | ||
2273 | 215 | |||
2274 | 216 | def is_ready(self, service_name): | ||
2275 | 217 | """ | ||
2276 | 218 | Determine if a registered service is ready, by checking its 'required_data'. | ||
2277 | 219 | |||
2278 | 220 | A 'required_data' item can be any mapping type, and is considered ready | ||
2279 | 221 | if `bool(item)` evaluates as True. | ||
2280 | 222 | """ | ||
2281 | 223 | service = self.get_service(service_name) | ||
2282 | 224 | reqs = service.get('required_data', []) | ||
2283 | 225 | return all(bool(req) for req in reqs) | ||
2284 | 226 | |||
2285 | 227 | def _load_ready_file(self): | ||
2286 | 228 | if self._ready is not None: | ||
2287 | 229 | return | ||
2288 | 230 | if os.path.exists(self._ready_file): | ||
2289 | 231 | with open(self._ready_file) as fp: | ||
2290 | 232 | self._ready = set(json.load(fp)) | ||
2291 | 233 | else: | ||
2292 | 234 | self._ready = set() | ||
2293 | 235 | |||
2294 | 236 | def _save_ready_file(self): | ||
2295 | 237 | if self._ready is None: | ||
2296 | 238 | return | ||
2297 | 239 | with open(self._ready_file, 'w') as fp: | ||
2298 | 240 | json.dump(list(self._ready), fp) | ||
2299 | 241 | |||
2300 | 242 | def save_ready(self, service_name): | ||
2301 | 243 | """ | ||
2302 | 244 | Save an indicator that the given service is now data_ready. | ||
2303 | 245 | """ | ||
2304 | 246 | self._load_ready_file() | ||
2305 | 247 | self._ready.add(service_name) | ||
2306 | 248 | self._save_ready_file() | ||
2307 | 249 | |||
2308 | 250 | def save_lost(self, service_name): | ||
2309 | 251 | """ | ||
2310 | 252 | Save an indicator that the given service is no longer data_ready. | ||
2311 | 253 | """ | ||
2312 | 254 | self._load_ready_file() | ||
2313 | 255 | self._ready.discard(service_name) | ||
2314 | 256 | self._save_ready_file() | ||
2315 | 257 | |||
2316 | 258 | def was_ready(self, service_name): | ||
2317 | 259 | """ | ||
2318 | 260 | Determine if the given service was previously data_ready. | ||
2319 | 261 | """ | ||
2320 | 262 | self._load_ready_file() | ||
2321 | 263 | return service_name in self._ready | ||
2322 | 264 | |||
2323 | 265 | |||
2324 | 266 | class ManagerCallback(object): | ||
2325 | 267 | """ | ||
2326 | 268 | Special case of a callback that takes the `ServiceManager` instance | ||
2327 | 269 | in addition to the service name. | ||
2328 | 270 | |||
2329 | 271 | Subclasses should implement `__call__` which should accept three parameters: | ||
2330 | 272 | |||
2331 | 273 | * `manager` The `ServiceManager` instance | ||
2332 | 274 | * `service_name` The name of the service it's being triggered for | ||
2333 | 275 | * `event_name` The name of the event that this callback is handling | ||
2334 | 276 | """ | ||
2335 | 277 | def __call__(self, manager, service_name, event_name): | ||
2336 | 278 | raise NotImplementedError() | ||
2337 | 279 | |||
2338 | 280 | |||
2339 | 281 | class PortManagerCallback(ManagerCallback): | ||
2340 | 282 | """ | ||
2341 | 283 | Callback class that will open or close ports, for use as either | ||
2342 | 284 | a start or stop action. | ||
2343 | 285 | """ | ||
2344 | 286 | def __call__(self, manager, service_name, event_name): | ||
2345 | 287 | service = manager.get_service(service_name) | ||
2346 | 288 | new_ports = service.get('ports', []) | ||
2347 | 289 | port_file = os.path.join(hookenv.charm_dir(), '.{}.ports'.format(service_name)) | ||
2348 | 290 | if os.path.exists(port_file): | ||
2349 | 291 | with open(port_file) as fp: | ||
2350 | 292 | old_ports = fp.read().split(',') | ||
2351 | 293 | for old_port in old_ports: | ||
2352 | 294 | if bool(old_port): | ||
2353 | 295 | old_port = int(old_port) | ||
2354 | 296 | if old_port not in new_ports: | ||
2355 | 297 | hookenv.close_port(old_port) | ||
2356 | 298 | with open(port_file, 'w') as fp: | ||
2357 | 299 | fp.write(','.join(str(port) for port in new_ports)) | ||
2358 | 300 | for port in new_ports: | ||
2359 | 301 | if event_name == 'start': | ||
2360 | 302 | hookenv.open_port(port) | ||
2361 | 303 | elif event_name == 'stop': | ||
2362 | 304 | hookenv.close_port(port) | ||
2363 | 305 | |||
2364 | 306 | |||
2365 | 307 | def service_stop(service_name): | ||
2366 | 308 | """ | ||
2367 | 309 | Wrapper around host.service_stop to prevent spurious "unknown service" | ||
2368 | 310 | messages in the logs. | ||
2369 | 311 | """ | ||
2370 | 312 | if host.service_running(service_name): | ||
2371 | 313 | host.service_stop(service_name) | ||
2372 | 314 | |||
2373 | 315 | |||
2374 | 316 | def service_restart(service_name): | ||
2375 | 317 | """ | ||
2376 | 318 | Wrapper around host.service_restart to prevent spurious "unknown service" | ||
2377 | 319 | messages in the logs. | ||
2378 | 320 | """ | ||
2379 | 321 | if host.service_available(service_name): | ||
2380 | 322 | if host.service_running(service_name): | ||
2381 | 323 | host.service_restart(service_name) | ||
2382 | 324 | else: | ||
2383 | 325 | host.service_start(service_name) | ||
2384 | 326 | |||
2385 | 327 | |||
2386 | 328 | # Convenience aliases | ||
2387 | 329 | open_ports = close_ports = manage_ports = PortManagerCallback() | ||
2388 | 0 | 330 | ||
2389 | === added file 'hooks/charmhelpers/core/services/helpers.py' | |||
2390 | --- hooks/charmhelpers/core/services/helpers.py 1970-01-01 00:00:00 +0000 | |||
2391 | +++ hooks/charmhelpers/core/services/helpers.py 2015-03-23 00:51:45 +0000 | |||
2392 | @@ -0,0 +1,267 @@ | |||
2393 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2394 | 2 | # | ||
2395 | 3 | # This file is part of charm-helpers. | ||
2396 | 4 | # | ||
2397 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2398 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2399 | 7 | # published by the Free Software Foundation. | ||
2400 | 8 | # | ||
2401 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2402 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2403 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2404 | 12 | # GNU Lesser General Public License for more details. | ||
2405 | 13 | # | ||
2406 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2407 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2408 | 16 | |||
2409 | 17 | import os | ||
2410 | 18 | import yaml | ||
2411 | 19 | from charmhelpers.core import hookenv | ||
2412 | 20 | from charmhelpers.core import templating | ||
2413 | 21 | |||
2414 | 22 | from charmhelpers.core.services.base import ManagerCallback | ||
2415 | 23 | |||
2416 | 24 | |||
2417 | 25 | __all__ = ['RelationContext', 'TemplateCallback', | ||
2418 | 26 | 'render_template', 'template'] | ||
2419 | 27 | |||
2420 | 28 | |||
2421 | 29 | class RelationContext(dict): | ||
2422 | 30 | """ | ||
2423 | 31 | Base class for a context generator that gets relation data from juju. | ||
2424 | 32 | |||
2425 | 33 | Subclasses must provide the attributes `name`, which is the name of the | ||
2426 | 34 | interface of interest, `interface`, which is the type of the interface of | ||
2427 | 35 | interest, and `required_keys`, which is the set of keys required for the | ||
2428 | 36 | relation to be considered complete. The data for all interfaces matching | ||
2429 | 37 | the `name` attribute that are complete will used to populate the dictionary | ||
2430 | 38 | values (see `get_data`, below). | ||
2431 | 39 | |||
2432 | 40 | The generated context will be namespaced under the relation :attr:`name`, | ||
2433 | 41 | to prevent potential naming conflicts. | ||
2434 | 42 | |||
2435 | 43 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2436 | 44 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2437 | 45 | """ | ||
2438 | 46 | name = None | ||
2439 | 47 | interface = None | ||
2440 | 48 | |||
2441 | 49 | def __init__(self, name=None, additional_required_keys=None): | ||
2442 | 50 | if not hasattr(self, 'required_keys'): | ||
2443 | 51 | self.required_keys = [] | ||
2444 | 52 | |||
2445 | 53 | if name is not None: | ||
2446 | 54 | self.name = name | ||
2447 | 55 | if additional_required_keys: | ||
2448 | 56 | self.required_keys.extend(additional_required_keys) | ||
2449 | 57 | self.get_data() | ||
2450 | 58 | |||
2451 | 59 | def __bool__(self): | ||
2452 | 60 | """ | ||
2453 | 61 | Returns True if all of the required_keys are available. | ||
2454 | 62 | """ | ||
2455 | 63 | return self.is_ready() | ||
2456 | 64 | |||
2457 | 65 | __nonzero__ = __bool__ | ||
2458 | 66 | |||
2459 | 67 | def __repr__(self): | ||
2460 | 68 | return super(RelationContext, self).__repr__() | ||
2461 | 69 | |||
2462 | 70 | def is_ready(self): | ||
2463 | 71 | """ | ||
2464 | 72 | Returns True if all of the `required_keys` are available from any units. | ||
2465 | 73 | """ | ||
2466 | 74 | ready = len(self.get(self.name, [])) > 0 | ||
2467 | 75 | if not ready: | ||
2468 | 76 | hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG) | ||
2469 | 77 | return ready | ||
2470 | 78 | |||
2471 | 79 | def _is_ready(self, unit_data): | ||
2472 | 80 | """ | ||
2473 | 81 | Helper method that tests a set of relation data and returns True if | ||
2474 | 82 | all of the `required_keys` are present. | ||
2475 | 83 | """ | ||
2476 | 84 | return set(unit_data.keys()).issuperset(set(self.required_keys)) | ||
2477 | 85 | |||
2478 | 86 | def get_data(self): | ||
2479 | 87 | """ | ||
2480 | 88 | Retrieve the relation data for each unit involved in a relation and, | ||
2481 | 89 | if complete, store it in a list under `self[self.name]`. This | ||
2482 | 90 | is automatically called when the RelationContext is instantiated. | ||
2483 | 91 | |||
2484 | 92 | The units are sorted lexographically first by the service ID, then by | ||
2485 | 93 | the unit ID. Thus, if an interface has two other services, 'db:1' | ||
2486 | 94 | and 'db:2', with 'db:1' having two units, 'wordpress/0' and 'wordpress/1', | ||
2487 | 95 | and 'db:2' having one unit, 'mediawiki/0', all of which have a complete | ||
2488 | 96 | set of data, the relation data for the units will be stored in the | ||
2489 | 97 | order: 'wordpress/0', 'wordpress/1', 'mediawiki/0'. | ||
2490 | 98 | |||
2491 | 99 | If you only care about a single unit on the relation, you can just | ||
2492 | 100 | access it as `{{ interface[0]['key'] }}`. However, if you can at all | ||
2493 | 101 | support multiple units on a relation, you should iterate over the list, | ||
2494 | 102 | like:: | ||
2495 | 103 | |||
2496 | 104 | {% for unit in interface -%} | ||
2497 | 105 | {{ unit['key'] }}{% if not loop.last %},{% endif %} | ||
2498 | 106 | {%- endfor %} | ||
2499 | 107 | |||
2500 | 108 | Note that since all sets of relation data from all related services and | ||
2501 | 109 | units are in a single list, if you need to know which service or unit a | ||
2502 | 110 | set of data came from, you'll need to extend this class to preserve | ||
2503 | 111 | that information. | ||
2504 | 112 | """ | ||
2505 | 113 | if not hookenv.relation_ids(self.name): | ||
2506 | 114 | return | ||
2507 | 115 | |||
2508 | 116 | ns = self.setdefault(self.name, []) | ||
2509 | 117 | for rid in sorted(hookenv.relation_ids(self.name)): | ||
2510 | 118 | for unit in sorted(hookenv.related_units(rid)): | ||
2511 | 119 | reldata = hookenv.relation_get(rid=rid, unit=unit) | ||
2512 | 120 | if self._is_ready(reldata): | ||
2513 | 121 | ns.append(reldata) | ||
2514 | 122 | |||
2515 | 123 | def provide_data(self): | ||
2516 | 124 | """ | ||
2517 | 125 | Return data to be relation_set for this interface. | ||
2518 | 126 | """ | ||
2519 | 127 | return {} | ||
2520 | 128 | |||
2521 | 129 | |||
2522 | 130 | class MysqlRelation(RelationContext): | ||
2523 | 131 | """ | ||
2524 | 132 | Relation context for the `mysql` interface. | ||
2525 | 133 | |||
2526 | 134 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2527 | 135 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2528 | 136 | """ | ||
2529 | 137 | name = 'db' | ||
2530 | 138 | interface = 'mysql' | ||
2531 | 139 | |||
2532 | 140 | def __init__(self, *args, **kwargs): | ||
2533 | 141 | self.required_keys = ['host', 'user', 'password', 'database'] | ||
2534 | 142 | super(HttpRelation).__init__(self, *args, **kwargs) | ||
2535 | 143 | |||
2536 | 144 | |||
2537 | 145 | class HttpRelation(RelationContext): | ||
2538 | 146 | """ | ||
2539 | 147 | Relation context for the `http` interface. | ||
2540 | 148 | |||
2541 | 149 | :param str name: Override the relation :attr:`name`, since it can vary from charm to charm | ||
2542 | 150 | :param list additional_required_keys: Extend the list of :attr:`required_keys` | ||
2543 | 151 | """ | ||
2544 | 152 | name = 'website' | ||
2545 | 153 | interface = 'http' | ||
2546 | 154 | |||
2547 | 155 | def __init__(self, *args, **kwargs): | ||
2548 | 156 | self.required_keys = ['host', 'port'] | ||
2549 | 157 | super(HttpRelation).__init__(self, *args, **kwargs) | ||
2550 | 158 | |||
2551 | 159 | def provide_data(self): | ||
2552 | 160 | return { | ||
2553 | 161 | 'host': hookenv.unit_get('private-address'), | ||
2554 | 162 | 'port': 80, | ||
2555 | 163 | } | ||
2556 | 164 | |||
2557 | 165 | |||
2558 | 166 | class RequiredConfig(dict): | ||
2559 | 167 | """ | ||
2560 | 168 | Data context that loads config options with one or more mandatory options. | ||
2561 | 169 | |||
2562 | 170 | Once the required options have been changed from their default values, all | ||
2563 | 171 | config options will be available, namespaced under `config` to prevent | ||
2564 | 172 | potential naming conflicts (for example, between a config option and a | ||
2565 | 173 | relation property). | ||
2566 | 174 | |||
2567 | 175 | :param list *args: List of options that must be changed from their default values. | ||
2568 | 176 | """ | ||
2569 | 177 | |||
2570 | 178 | def __init__(self, *args): | ||
2571 | 179 | self.required_options = args | ||
2572 | 180 | self['config'] = hookenv.config() | ||
2573 | 181 | with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp: | ||
2574 | 182 | self.config = yaml.load(fp).get('options', {}) | ||
2575 | 183 | |||
2576 | 184 | def __bool__(self): | ||
2577 | 185 | for option in self.required_options: | ||
2578 | 186 | if option not in self['config']: | ||
2579 | 187 | return False | ||
2580 | 188 | current_value = self['config'][option] | ||
2581 | 189 | default_value = self.config[option].get('default') | ||
2582 | 190 | if current_value == default_value: | ||
2583 | 191 | return False | ||
2584 | 192 | if current_value in (None, '') and default_value in (None, ''): | ||
2585 | 193 | return False | ||
2586 | 194 | return True | ||
2587 | 195 | |||
2588 | 196 | def __nonzero__(self): | ||
2589 | 197 | return self.__bool__() | ||
2590 | 198 | |||
2591 | 199 | |||
2592 | 200 | class StoredContext(dict): | ||
2593 | 201 | """ | ||
2594 | 202 | A data context that always returns the data that it was first created with. | ||
2595 | 203 | |||
2596 | 204 | This is useful to do a one-time generation of things like passwords, that | ||
2597 | 205 | will thereafter use the same value that was originally generated, instead | ||
2598 | 206 | of generating a new value each time it is run. | ||
2599 | 207 | """ | ||
2600 | 208 | def __init__(self, file_name, config_data): | ||
2601 | 209 | """ | ||
2602 | 210 | If the file exists, populate `self` with the data from the file. | ||
2603 | 211 | Otherwise, populate with the given data and persist it to the file. | ||
2604 | 212 | """ | ||
2605 | 213 | if os.path.exists(file_name): | ||
2606 | 214 | self.update(self.read_context(file_name)) | ||
2607 | 215 | else: | ||
2608 | 216 | self.store_context(file_name, config_data) | ||
2609 | 217 | self.update(config_data) | ||
2610 | 218 | |||
2611 | 219 | def store_context(self, file_name, config_data): | ||
2612 | 220 | if not os.path.isabs(file_name): | ||
2613 | 221 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2614 | 222 | with open(file_name, 'w') as file_stream: | ||
2615 | 223 | os.fchmod(file_stream.fileno(), 0o600) | ||
2616 | 224 | yaml.dump(config_data, file_stream) | ||
2617 | 225 | |||
2618 | 226 | def read_context(self, file_name): | ||
2619 | 227 | if not os.path.isabs(file_name): | ||
2620 | 228 | file_name = os.path.join(hookenv.charm_dir(), file_name) | ||
2621 | 229 | with open(file_name, 'r') as file_stream: | ||
2622 | 230 | data = yaml.load(file_stream) | ||
2623 | 231 | if not data: | ||
2624 | 232 | raise OSError("%s is empty" % file_name) | ||
2625 | 233 | return data | ||
2626 | 234 | |||
2627 | 235 | |||
2628 | 236 | class TemplateCallback(ManagerCallback): | ||
2629 | 237 | """ | ||
2630 | 238 | Callback class that will render a Jinja2 template, for use as a ready | ||
2631 | 239 | action. | ||
2632 | 240 | |||
2633 | 241 | :param str source: The template source file, relative to | ||
2634 | 242 | `$CHARM_DIR/templates` | ||
2635 | 243 | |||
2636 | 244 | :param str target: The target to write the rendered template to | ||
2637 | 245 | :param str owner: The owner of the rendered file | ||
2638 | 246 | :param str group: The group of the rendered file | ||
2639 | 247 | :param int perms: The permissions of the rendered file | ||
2640 | 248 | """ | ||
2641 | 249 | def __init__(self, source, target, | ||
2642 | 250 | owner='root', group='root', perms=0o444): | ||
2643 | 251 | self.source = source | ||
2644 | 252 | self.target = target | ||
2645 | 253 | self.owner = owner | ||
2646 | 254 | self.group = group | ||
2647 | 255 | self.perms = perms | ||
2648 | 256 | |||
2649 | 257 | def __call__(self, manager, service_name, event_name): | ||
2650 | 258 | service = manager.get_service(service_name) | ||
2651 | 259 | context = {} | ||
2652 | 260 | for ctx in service.get('required_data', []): | ||
2653 | 261 | context.update(ctx) | ||
2654 | 262 | templating.render(self.source, self.target, context, | ||
2655 | 263 | self.owner, self.group, self.perms) | ||
2656 | 264 | |||
2657 | 265 | |||
2658 | 266 | # Convenience aliases for templates | ||
2659 | 267 | render_template = template = TemplateCallback | ||
2660 | 0 | 268 | ||
2661 | === added file 'hooks/charmhelpers/core/strutils.py' | |||
2662 | --- hooks/charmhelpers/core/strutils.py 1970-01-01 00:00:00 +0000 | |||
2663 | +++ hooks/charmhelpers/core/strutils.py 2015-03-23 00:51:45 +0000 | |||
2664 | @@ -0,0 +1,42 @@ | |||
2665 | 1 | #!/usr/bin/env python | ||
2666 | 2 | # -*- coding: utf-8 -*- | ||
2667 | 3 | |||
2668 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2669 | 5 | # | ||
2670 | 6 | # This file is part of charm-helpers. | ||
2671 | 7 | # | ||
2672 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2673 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2674 | 10 | # published by the Free Software Foundation. | ||
2675 | 11 | # | ||
2676 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2677 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2678 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2679 | 15 | # GNU Lesser General Public License for more details. | ||
2680 | 16 | # | ||
2681 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2682 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2683 | 19 | |||
2684 | 20 | import six | ||
2685 | 21 | |||
2686 | 22 | |||
2687 | 23 | def bool_from_string(value): | ||
2688 | 24 | """Interpret string value as boolean. | ||
2689 | 25 | |||
2690 | 26 | Returns True if value translates to True otherwise False. | ||
2691 | 27 | """ | ||
2692 | 28 | if isinstance(value, six.string_types): | ||
2693 | 29 | value = six.text_type(value) | ||
2694 | 30 | else: | ||
2695 | 31 | msg = "Unable to interpret non-string value '%s' as boolean" % (value) | ||
2696 | 32 | raise ValueError(msg) | ||
2697 | 33 | |||
2698 | 34 | value = value.strip().lower() | ||
2699 | 35 | |||
2700 | 36 | if value in ['y', 'yes', 'true', 't']: | ||
2701 | 37 | return True | ||
2702 | 38 | elif value in ['n', 'no', 'false', 'f']: | ||
2703 | 39 | return False | ||
2704 | 40 | |||
2705 | 41 | msg = "Unable to interpret string value '%s' as boolean" % (value) | ||
2706 | 42 | raise ValueError(msg) | ||
2707 | 0 | 43 | ||
2708 | === added file 'hooks/charmhelpers/core/sysctl.py' | |||
2709 | --- hooks/charmhelpers/core/sysctl.py 1970-01-01 00:00:00 +0000 | |||
2710 | +++ hooks/charmhelpers/core/sysctl.py 2015-03-23 00:51:45 +0000 | |||
2711 | @@ -0,0 +1,56 @@ | |||
2712 | 1 | #!/usr/bin/env python | ||
2713 | 2 | # -*- coding: utf-8 -*- | ||
2714 | 3 | |||
2715 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2716 | 5 | # | ||
2717 | 6 | # This file is part of charm-helpers. | ||
2718 | 7 | # | ||
2719 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2720 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2721 | 10 | # published by the Free Software Foundation. | ||
2722 | 11 | # | ||
2723 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2724 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2725 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2726 | 15 | # GNU Lesser General Public License for more details. | ||
2727 | 16 | # | ||
2728 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2729 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2730 | 19 | |||
2731 | 20 | import yaml | ||
2732 | 21 | |||
2733 | 22 | from subprocess import check_call | ||
2734 | 23 | |||
2735 | 24 | from charmhelpers.core.hookenv import ( | ||
2736 | 25 | log, | ||
2737 | 26 | DEBUG, | ||
2738 | 27 | ERROR, | ||
2739 | 28 | ) | ||
2740 | 29 | |||
2741 | 30 | __author__ = 'Jorge Niedbalski R. <jorge.niedbalski@canonical.com>' | ||
2742 | 31 | |||
2743 | 32 | |||
2744 | 33 | def create(sysctl_dict, sysctl_file): | ||
2745 | 34 | """Creates a sysctl.conf file from a YAML associative array | ||
2746 | 35 | |||
2747 | 36 | :param sysctl_dict: a YAML-formatted string of sysctl options eg "{ 'kernel.max_pid': 1337 }" | ||
2748 | 37 | :type sysctl_dict: str | ||
2749 | 38 | :param sysctl_file: path to the sysctl file to be saved | ||
2750 | 39 | :type sysctl_file: str or unicode | ||
2751 | 40 | :returns: None | ||
2752 | 41 | """ | ||
2753 | 42 | try: | ||
2754 | 43 | sysctl_dict_parsed = yaml.safe_load(sysctl_dict) | ||
2755 | 44 | except yaml.YAMLError: | ||
2756 | 45 | log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict), | ||
2757 | 46 | level=ERROR) | ||
2758 | 47 | return | ||
2759 | 48 | |||
2760 | 49 | with open(sysctl_file, "w") as fd: | ||
2761 | 50 | for key, value in sysctl_dict_parsed.items(): | ||
2762 | 51 | fd.write("{}={}\n".format(key, value)) | ||
2763 | 52 | |||
2764 | 53 | log("Updating sysctl_file: %s values: %s" % (sysctl_file, sysctl_dict_parsed), | ||
2765 | 54 | level=DEBUG) | ||
2766 | 55 | |||
2767 | 56 | check_call(["sysctl", "-p", sysctl_file]) | ||
2768 | 0 | 57 | ||
2769 | === added file 'hooks/charmhelpers/core/templating.py' | |||
2770 | --- hooks/charmhelpers/core/templating.py 1970-01-01 00:00:00 +0000 | |||
2771 | +++ hooks/charmhelpers/core/templating.py 2015-03-23 00:51:45 +0000 | |||
2772 | @@ -0,0 +1,68 @@ | |||
2773 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
2774 | 2 | # | ||
2775 | 3 | # This file is part of charm-helpers. | ||
2776 | 4 | # | ||
2777 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2778 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2779 | 7 | # published by the Free Software Foundation. | ||
2780 | 8 | # | ||
2781 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
2782 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2783 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2784 | 12 | # GNU Lesser General Public License for more details. | ||
2785 | 13 | # | ||
2786 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
2787 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2788 | 16 | |||
2789 | 17 | import os | ||
2790 | 18 | |||
2791 | 19 | from charmhelpers.core import host | ||
2792 | 20 | from charmhelpers.core import hookenv | ||
2793 | 21 | |||
2794 | 22 | |||
2795 | 23 | def render(source, target, context, owner='root', group='root', | ||
2796 | 24 | perms=0o444, templates_dir=None, encoding='UTF-8'): | ||
2797 | 25 | """ | ||
2798 | 26 | Render a template. | ||
2799 | 27 | |||
2800 | 28 | The `source` path, if not absolute, is relative to the `templates_dir`. | ||
2801 | 29 | |||
2802 | 30 | The `target` path should be absolute. | ||
2803 | 31 | |||
2804 | 32 | The context should be a dict containing the values to be replaced in the | ||
2805 | 33 | template. | ||
2806 | 34 | |||
2807 | 35 | The `owner`, `group`, and `perms` options will be passed to `write_file`. | ||
2808 | 36 | |||
2809 | 37 | If omitted, `templates_dir` defaults to the `templates` folder in the charm. | ||
2810 | 38 | |||
2811 | 39 | Note: Using this requires python-jinja2; if it is not installed, calling | ||
2812 | 40 | this will attempt to use charmhelpers.fetch.apt_install to install it. | ||
2813 | 41 | """ | ||
2814 | 42 | try: | ||
2815 | 43 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2816 | 44 | except ImportError: | ||
2817 | 45 | try: | ||
2818 | 46 | from charmhelpers.fetch import apt_install | ||
2819 | 47 | except ImportError: | ||
2820 | 48 | hookenv.log('Could not import jinja2, and could not import ' | ||
2821 | 49 | 'charmhelpers.fetch to install it', | ||
2822 | 50 | level=hookenv.ERROR) | ||
2823 | 51 | raise | ||
2824 | 52 | apt_install('python-jinja2', fatal=True) | ||
2825 | 53 | from jinja2 import FileSystemLoader, Environment, exceptions | ||
2826 | 54 | |||
2827 | 55 | if templates_dir is None: | ||
2828 | 56 | templates_dir = os.path.join(hookenv.charm_dir(), 'templates') | ||
2829 | 57 | loader = Environment(loader=FileSystemLoader(templates_dir)) | ||
2830 | 58 | try: | ||
2831 | 59 | source = source | ||
2832 | 60 | template = loader.get_template(source) | ||
2833 | 61 | except exceptions.TemplateNotFound as e: | ||
2834 | 62 | hookenv.log('Could not load template %s from %s.' % | ||
2835 | 63 | (source, templates_dir), | ||
2836 | 64 | level=hookenv.ERROR) | ||
2837 | 65 | raise e | ||
2838 | 66 | content = template.render(context) | ||
2839 | 67 | host.mkdir(os.path.dirname(target), owner, group, perms=0o755) | ||
2840 | 68 | host.write_file(target, content.encode(encoding), owner, group, perms) | ||
2841 | 0 | 69 | ||
2842 | === added file 'hooks/charmhelpers/core/unitdata.py' | |||
2843 | --- hooks/charmhelpers/core/unitdata.py 1970-01-01 00:00:00 +0000 | |||
2844 | +++ hooks/charmhelpers/core/unitdata.py 2015-03-23 00:51:45 +0000 | |||
2845 | @@ -0,0 +1,477 @@ | |||
2846 | 1 | #!/usr/bin/env python | ||
2847 | 2 | # -*- coding: utf-8 -*- | ||
2848 | 3 | # | ||
2849 | 4 | # Copyright 2014-2015 Canonical Limited. | ||
2850 | 5 | # | ||
2851 | 6 | # This file is part of charm-helpers. | ||
2852 | 7 | # | ||
2853 | 8 | # charm-helpers is free software: you can redistribute it and/or modify | ||
2854 | 9 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
2855 | 10 | # published by the Free Software Foundation. | ||
2856 | 11 | # | ||
2857 | 12 | # charm-helpers is distributed in the hope that it will be useful, | ||
2858 | 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
2859 | 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
2860 | 15 | # GNU Lesser General Public License for more details. | ||
2861 | 16 | # | ||
2862 | 17 | # You should have received a copy of the GNU Lesser General Public License | ||
2863 | 18 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
2864 | 19 | # | ||
2865 | 20 | # | ||
2866 | 21 | # Authors: | ||
2867 | 22 | # Kapil Thangavelu <kapil.foss@gmail.com> | ||
2868 | 23 | # | ||
2869 | 24 | """ | ||
2870 | 25 | Intro | ||
2871 | 26 | ----- | ||
2872 | 27 | |||
2873 | 28 | A simple way to store state in units. This provides a key value | ||
2874 | 29 | storage with support for versioned, transactional operation, | ||
2875 | 30 | and can calculate deltas from previous values to simplify unit logic | ||
2876 | 31 | when processing changes. | ||
2877 | 32 | |||
2878 | 33 | |||
2879 | 34 | Hook Integration | ||
2880 | 35 | ---------------- | ||
2881 | 36 | |||
2882 | 37 | There are several extant frameworks for hook execution, including | ||
2883 | 38 | |||
2884 | 39 | - charmhelpers.core.hookenv.Hooks | ||
2885 | 40 | - charmhelpers.core.services.ServiceManager | ||
2886 | 41 | |||
2887 | 42 | The storage classes are framework agnostic, one simple integration is | ||
2888 | 43 | via the HookData contextmanager. It will record the current hook | ||
2889 | 44 | execution environment (including relation data, config data, etc.), | ||
2890 | 45 | setup a transaction and allow easy access to the changes from | ||
2891 | 46 | previously seen values. One consequence of the integration is the | ||
2892 | 47 | reservation of particular keys ('rels', 'unit', 'env', 'config', | ||
2893 | 48 | 'charm_revisions') for their respective values. | ||
2894 | 49 | |||
2895 | 50 | Here's a fully worked integration example using hookenv.Hooks:: | ||
2896 | 51 | |||
2897 | 52 | from charmhelper.core import hookenv, unitdata | ||
2898 | 53 | |||
2899 | 54 | hook_data = unitdata.HookData() | ||
2900 | 55 | db = unitdata.kv() | ||
2901 | 56 | hooks = hookenv.Hooks() | ||
2902 | 57 | |||
2903 | 58 | @hooks.hook | ||
2904 | 59 | def config_changed(): | ||
2905 | 60 | # Print all changes to configuration from previously seen | ||
2906 | 61 | # values. | ||
2907 | 62 | for changed, (prev, cur) in hook_data.conf.items(): | ||
2908 | 63 | print('config changed', changed, | ||
2909 | 64 | 'previous value', prev, | ||
2910 | 65 | 'current value', cur) | ||
2911 | 66 | |||
2912 | 67 | # Get some unit specific bookeeping | ||
2913 | 68 | if not db.get('pkg_key'): | ||
2914 | 69 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
2915 | 70 | db.set('pkg_key', key) | ||
2916 | 71 | |||
2917 | 72 | # Directly access all charm config as a mapping. | ||
2918 | 73 | conf = db.getrange('config', True) | ||
2919 | 74 | |||
2920 | 75 | # Directly access all relation data as a mapping | ||
2921 | 76 | rels = db.getrange('rels', True) | ||
2922 | 77 | |||
2923 | 78 | if __name__ == '__main__': | ||
2924 | 79 | with hook_data(): | ||
2925 | 80 | hook.execute() | ||
2926 | 81 | |||
2927 | 82 | |||
2928 | 83 | A more basic integration is via the hook_scope context manager which simply | ||
2929 | 84 | manages transaction scope (and records hook name, and timestamp):: | ||
2930 | 85 | |||
2931 | 86 | >>> from unitdata import kv | ||
2932 | 87 | >>> db = kv() | ||
2933 | 88 | >>> with db.hook_scope('install'): | ||
2934 | 89 | ... # do work, in transactional scope. | ||
2935 | 90 | ... db.set('x', 1) | ||
2936 | 91 | >>> db.get('x') | ||
2937 | 92 | 1 | ||
2938 | 93 | |||
2939 | 94 | |||
2940 | 95 | Usage | ||
2941 | 96 | ----- | ||
2942 | 97 | |||
2943 | 98 | Values are automatically json de/serialized to preserve basic typing | ||
2944 | 99 | and complex data struct capabilities (dicts, lists, ints, booleans, etc). | ||
2945 | 100 | |||
2946 | 101 | Individual values can be manipulated via get/set:: | ||
2947 | 102 | |||
2948 | 103 | >>> kv.set('y', True) | ||
2949 | 104 | >>> kv.get('y') | ||
2950 | 105 | True | ||
2951 | 106 | |||
2952 | 107 | # We can set complex values (dicts, lists) as a single key. | ||
2953 | 108 | >>> kv.set('config', {'a': 1, 'b': True'}) | ||
2954 | 109 | |||
2955 | 110 | # Also supports returning dictionaries as a record which | ||
2956 | 111 | # provides attribute access. | ||
2957 | 112 | >>> config = kv.get('config', record=True) | ||
2958 | 113 | >>> config.b | ||
2959 | 114 | True | ||
2960 | 115 | |||
2961 | 116 | |||
2962 | 117 | Groups of keys can be manipulated with update/getrange:: | ||
2963 | 118 | |||
2964 | 119 | >>> kv.update({'z': 1, 'y': 2}, prefix="gui.") | ||
2965 | 120 | >>> kv.getrange('gui.', strip=True) | ||
2966 | 121 | {'z': 1, 'y': 2} | ||
2967 | 122 | |||
2968 | 123 | When updating values, its very helpful to understand which values | ||
2969 | 124 | have actually changed and how have they changed. The storage | ||
2970 | 125 | provides a delta method to provide for this:: | ||
2971 | 126 | |||
2972 | 127 | >>> data = {'debug': True, 'option': 2} | ||
2973 | 128 | >>> delta = kv.delta(data, 'config.') | ||
2974 | 129 | >>> delta.debug.previous | ||
2975 | 130 | None | ||
2976 | 131 | >>> delta.debug.current | ||
2977 | 132 | True | ||
2978 | 133 | >>> delta | ||
2979 | 134 | {'debug': (None, True), 'option': (None, 2)} | ||
2980 | 135 | |||
2981 | 136 | Note the delta method does not persist the actual change, it needs to | ||
2982 | 137 | be explicitly saved via 'update' method:: | ||
2983 | 138 | |||
2984 | 139 | >>> kv.update(data, 'config.') | ||
2985 | 140 | |||
2986 | 141 | Values modified in the context of a hook scope retain historical values | ||
2987 | 142 | associated to the hookname. | ||
2988 | 143 | |||
2989 | 144 | >>> with db.hook_scope('config-changed'): | ||
2990 | 145 | ... db.set('x', 42) | ||
2991 | 146 | >>> db.gethistory('x') | ||
2992 | 147 | [(1, u'x', 1, u'install', u'2015-01-21T16:49:30.038372'), | ||
2993 | 148 | (2, u'x', 42, u'config-changed', u'2015-01-21T16:49:30.038786')] | ||
2994 | 149 | |||
2995 | 150 | """ | ||
2996 | 151 | |||
2997 | 152 | import collections | ||
2998 | 153 | import contextlib | ||
2999 | 154 | import datetime | ||
3000 | 155 | import json | ||
3001 | 156 | import os | ||
3002 | 157 | import pprint | ||
3003 | 158 | import sqlite3 | ||
3004 | 159 | import sys | ||
3005 | 160 | |||
3006 | 161 | __author__ = 'Kapil Thangavelu <kapil.foss@gmail.com>' | ||
3007 | 162 | |||
3008 | 163 | |||
3009 | 164 | class Storage(object): | ||
3010 | 165 | """Simple key value database for local unit state within charms. | ||
3011 | 166 | |||
3012 | 167 | Modifications are automatically committed at hook exit. That's | ||
3013 | 168 | currently regardless of exit code. | ||
3014 | 169 | |||
3015 | 170 | To support dicts, lists, integer, floats, and booleans values | ||
3016 | 171 | are automatically json encoded/decoded. | ||
3017 | 172 | """ | ||
3018 | 173 | def __init__(self, path=None): | ||
3019 | 174 | self.db_path = path | ||
3020 | 175 | if path is None: | ||
3021 | 176 | self.db_path = os.path.join( | ||
3022 | 177 | os.environ.get('CHARM_DIR', ''), '.unit-state.db') | ||
3023 | 178 | self.conn = sqlite3.connect('%s' % self.db_path) | ||
3024 | 179 | self.cursor = self.conn.cursor() | ||
3025 | 180 | self.revision = None | ||
3026 | 181 | self._closed = False | ||
3027 | 182 | self._init() | ||
3028 | 183 | |||
3029 | 184 | def close(self): | ||
3030 | 185 | if self._closed: | ||
3031 | 186 | return | ||
3032 | 187 | self.flush(False) | ||
3033 | 188 | self.cursor.close() | ||
3034 | 189 | self.conn.close() | ||
3035 | 190 | self._closed = True | ||
3036 | 191 | |||
3037 | 192 | def _scoped_query(self, stmt, params=None): | ||
3038 | 193 | if params is None: | ||
3039 | 194 | params = [] | ||
3040 | 195 | return stmt, params | ||
3041 | 196 | |||
3042 | 197 | def get(self, key, default=None, record=False): | ||
3043 | 198 | self.cursor.execute( | ||
3044 | 199 | *self._scoped_query( | ||
3045 | 200 | 'select data from kv where key=?', [key])) | ||
3046 | 201 | result = self.cursor.fetchone() | ||
3047 | 202 | if not result: | ||
3048 | 203 | return default | ||
3049 | 204 | if record: | ||
3050 | 205 | return Record(json.loads(result[0])) | ||
3051 | 206 | return json.loads(result[0]) | ||
3052 | 207 | |||
3053 | 208 | def getrange(self, key_prefix, strip=False): | ||
3054 | 209 | stmt = "select key, data from kv where key like '%s%%'" % key_prefix | ||
3055 | 210 | self.cursor.execute(*self._scoped_query(stmt)) | ||
3056 | 211 | result = self.cursor.fetchall() | ||
3057 | 212 | |||
3058 | 213 | if not result: | ||
3059 | 214 | return None | ||
3060 | 215 | if not strip: | ||
3061 | 216 | key_prefix = '' | ||
3062 | 217 | return dict([ | ||
3063 | 218 | (k[len(key_prefix):], json.loads(v)) for k, v in result]) | ||
3064 | 219 | |||
3065 | 220 | def update(self, mapping, prefix=""): | ||
3066 | 221 | for k, v in mapping.items(): | ||
3067 | 222 | self.set("%s%s" % (prefix, k), v) | ||
3068 | 223 | |||
3069 | 224 | def unset(self, key): | ||
3070 | 225 | self.cursor.execute('delete from kv where key=?', [key]) | ||
3071 | 226 | if self.revision and self.cursor.rowcount: | ||
3072 | 227 | self.cursor.execute( | ||
3073 | 228 | 'insert into kv_revisions values (?, ?, ?)', | ||
3074 | 229 | [key, self.revision, json.dumps('DELETED')]) | ||
3075 | 230 | |||
3076 | 231 | def set(self, key, value): | ||
3077 | 232 | serialized = json.dumps(value) | ||
3078 | 233 | |||
3079 | 234 | self.cursor.execute( | ||
3080 | 235 | 'select data from kv where key=?', [key]) | ||
3081 | 236 | exists = self.cursor.fetchone() | ||
3082 | 237 | |||
3083 | 238 | # Skip mutations to the same value | ||
3084 | 239 | if exists: | ||
3085 | 240 | if exists[0] == serialized: | ||
3086 | 241 | return value | ||
3087 | 242 | |||
3088 | 243 | if not exists: | ||
3089 | 244 | self.cursor.execute( | ||
3090 | 245 | 'insert into kv (key, data) values (?, ?)', | ||
3091 | 246 | (key, serialized)) | ||
3092 | 247 | else: | ||
3093 | 248 | self.cursor.execute(''' | ||
3094 | 249 | update kv | ||
3095 | 250 | set data = ? | ||
3096 | 251 | where key = ?''', [serialized, key]) | ||
3097 | 252 | |||
3098 | 253 | # Save | ||
3099 | 254 | if not self.revision: | ||
3100 | 255 | return value | ||
3101 | 256 | |||
3102 | 257 | self.cursor.execute( | ||
3103 | 258 | 'select 1 from kv_revisions where key=? and revision=?', | ||
3104 | 259 | [key, self.revision]) | ||
3105 | 260 | exists = self.cursor.fetchone() | ||
3106 | 261 | |||
3107 | 262 | if not exists: | ||
3108 | 263 | self.cursor.execute( | ||
3109 | 264 | '''insert into kv_revisions ( | ||
3110 | 265 | revision, key, data) values (?, ?, ?)''', | ||
3111 | 266 | (self.revision, key, serialized)) | ||
3112 | 267 | else: | ||
3113 | 268 | self.cursor.execute( | ||
3114 | 269 | ''' | ||
3115 | 270 | update kv_revisions | ||
3116 | 271 | set data = ? | ||
3117 | 272 | where key = ? | ||
3118 | 273 | and revision = ?''', | ||
3119 | 274 | [serialized, key, self.revision]) | ||
3120 | 275 | |||
3121 | 276 | return value | ||
3122 | 277 | |||
3123 | 278 | def delta(self, mapping, prefix): | ||
3124 | 279 | """ | ||
3125 | 280 | return a delta containing values that have changed. | ||
3126 | 281 | """ | ||
3127 | 282 | previous = self.getrange(prefix, strip=True) | ||
3128 | 283 | if not previous: | ||
3129 | 284 | pk = set() | ||
3130 | 285 | else: | ||
3131 | 286 | pk = set(previous.keys()) | ||
3132 | 287 | ck = set(mapping.keys()) | ||
3133 | 288 | delta = DeltaSet() | ||
3134 | 289 | |||
3135 | 290 | # added | ||
3136 | 291 | for k in ck.difference(pk): | ||
3137 | 292 | delta[k] = Delta(None, mapping[k]) | ||
3138 | 293 | |||
3139 | 294 | # removed | ||
3140 | 295 | for k in pk.difference(ck): | ||
3141 | 296 | delta[k] = Delta(previous[k], None) | ||
3142 | 297 | |||
3143 | 298 | # changed | ||
3144 | 299 | for k in pk.intersection(ck): | ||
3145 | 300 | c = mapping[k] | ||
3146 | 301 | p = previous[k] | ||
3147 | 302 | if c != p: | ||
3148 | 303 | delta[k] = Delta(p, c) | ||
3149 | 304 | |||
3150 | 305 | return delta | ||
3151 | 306 | |||
3152 | 307 | @contextlib.contextmanager | ||
3153 | 308 | def hook_scope(self, name=""): | ||
3154 | 309 | """Scope all future interactions to the current hook execution | ||
3155 | 310 | revision.""" | ||
3156 | 311 | assert not self.revision | ||
3157 | 312 | self.cursor.execute( | ||
3158 | 313 | 'insert into hooks (hook, date) values (?, ?)', | ||
3159 | 314 | (name or sys.argv[0], | ||
3160 | 315 | datetime.datetime.utcnow().isoformat())) | ||
3161 | 316 | self.revision = self.cursor.lastrowid | ||
3162 | 317 | try: | ||
3163 | 318 | yield self.revision | ||
3164 | 319 | self.revision = None | ||
3165 | 320 | except: | ||
3166 | 321 | self.flush(False) | ||
3167 | 322 | self.revision = None | ||
3168 | 323 | raise | ||
3169 | 324 | else: | ||
3170 | 325 | self.flush() | ||
3171 | 326 | |||
3172 | 327 | def flush(self, save=True): | ||
3173 | 328 | if save: | ||
3174 | 329 | self.conn.commit() | ||
3175 | 330 | elif self._closed: | ||
3176 | 331 | return | ||
3177 | 332 | else: | ||
3178 | 333 | self.conn.rollback() | ||
3179 | 334 | |||
3180 | 335 | def _init(self): | ||
3181 | 336 | self.cursor.execute(''' | ||
3182 | 337 | create table if not exists kv ( | ||
3183 | 338 | key text, | ||
3184 | 339 | data text, | ||
3185 | 340 | primary key (key) | ||
3186 | 341 | )''') | ||
3187 | 342 | self.cursor.execute(''' | ||
3188 | 343 | create table if not exists kv_revisions ( | ||
3189 | 344 | key text, | ||
3190 | 345 | revision integer, | ||
3191 | 346 | data text, | ||
3192 | 347 | primary key (key, revision) | ||
3193 | 348 | )''') | ||
3194 | 349 | self.cursor.execute(''' | ||
3195 | 350 | create table if not exists hooks ( | ||
3196 | 351 | version integer primary key autoincrement, | ||
3197 | 352 | hook text, | ||
3198 | 353 | date text | ||
3199 | 354 | )''') | ||
3200 | 355 | self.conn.commit() | ||
3201 | 356 | |||
3202 | 357 | def gethistory(self, key, deserialize=False): | ||
3203 | 358 | self.cursor.execute( | ||
3204 | 359 | ''' | ||
3205 | 360 | select kv.revision, kv.key, kv.data, h.hook, h.date | ||
3206 | 361 | from kv_revisions kv, | ||
3207 | 362 | hooks h | ||
3208 | 363 | where kv.key=? | ||
3209 | 364 | and kv.revision = h.version | ||
3210 | 365 | ''', [key]) | ||
3211 | 366 | if deserialize is False: | ||
3212 | 367 | return self.cursor.fetchall() | ||
3213 | 368 | return map(_parse_history, self.cursor.fetchall()) | ||
3214 | 369 | |||
3215 | 370 | def debug(self, fh=sys.stderr): | ||
3216 | 371 | self.cursor.execute('select * from kv') | ||
3217 | 372 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
3218 | 373 | self.cursor.execute('select * from kv_revisions') | ||
3219 | 374 | pprint.pprint(self.cursor.fetchall(), stream=fh) | ||
3220 | 375 | |||
3221 | 376 | |||
3222 | 377 | def _parse_history(d): | ||
3223 | 378 | return (d[0], d[1], json.loads(d[2]), d[3], | ||
3224 | 379 | datetime.datetime.strptime(d[-1], "%Y-%m-%dT%H:%M:%S.%f")) | ||
3225 | 380 | |||
3226 | 381 | |||
3227 | 382 | class HookData(object): | ||
3228 | 383 | """Simple integration for existing hook exec frameworks. | ||
3229 | 384 | |||
3230 | 385 | Records all unit information, and stores deltas for processing | ||
3231 | 386 | by the hook. | ||
3232 | 387 | |||
3233 | 388 | Sample:: | ||
3234 | 389 | |||
3235 | 390 | from charmhelper.core import hookenv, unitdata | ||
3236 | 391 | |||
3237 | 392 | changes = unitdata.HookData() | ||
3238 | 393 | db = unitdata.kv() | ||
3239 | 394 | hooks = hookenv.Hooks() | ||
3240 | 395 | |||
3241 | 396 | @hooks.hook | ||
3242 | 397 | def config_changed(): | ||
3243 | 398 | # View all changes to configuration | ||
3244 | 399 | for changed, (prev, cur) in changes.conf.items(): | ||
3245 | 400 | print('config changed', changed, | ||
3246 | 401 | 'previous value', prev, | ||
3247 | 402 | 'current value', cur) | ||
3248 | 403 | |||
3249 | 404 | # Get some unit specific bookeeping | ||
3250 | 405 | if not db.get('pkg_key'): | ||
3251 | 406 | key = urllib.urlopen('https://example.com/pkg_key').read() | ||
3252 | 407 | db.set('pkg_key', key) | ||
3253 | 408 | |||
3254 | 409 | if __name__ == '__main__': | ||
3255 | 410 | with changes(): | ||
3256 | 411 | hook.execute() | ||
3257 | 412 | |||
3258 | 413 | """ | ||
3259 | 414 | def __init__(self): | ||
3260 | 415 | self.kv = kv() | ||
3261 | 416 | self.conf = None | ||
3262 | 417 | self.rels = None | ||
3263 | 418 | |||
3264 | 419 | @contextlib.contextmanager | ||
3265 | 420 | def __call__(self): | ||
3266 | 421 | from charmhelpers.core import hookenv | ||
3267 | 422 | hook_name = hookenv.hook_name() | ||
3268 | 423 | |||
3269 | 424 | with self.kv.hook_scope(hook_name): | ||
3270 | 425 | self._record_charm_version(hookenv.charm_dir()) | ||
3271 | 426 | delta_config, delta_relation = self._record_hook(hookenv) | ||
3272 | 427 | yield self.kv, delta_config, delta_relation | ||
3273 | 428 | |||
3274 | 429 | def _record_charm_version(self, charm_dir): | ||
3275 | 430 | # Record revisions.. charm revisions are meaningless | ||
3276 | 431 | # to charm authors as they don't control the revision. | ||
3277 | 432 | # so logic dependnent on revision is not particularly | ||
3278 | 433 | # useful, however it is useful for debugging analysis. | ||
3279 | 434 | charm_rev = open( | ||
3280 | 435 | os.path.join(charm_dir, 'revision')).read().strip() | ||
3281 | 436 | charm_rev = charm_rev or '0' | ||
3282 | 437 | revs = self.kv.get('charm_revisions', []) | ||
3283 | 438 | if charm_rev not in revs: | ||
3284 | 439 | revs.append(charm_rev.strip() or '0') | ||
3285 | 440 | self.kv.set('charm_revisions', revs) | ||
3286 | 441 | |||
3287 | 442 | def _record_hook(self, hookenv): | ||
3288 | 443 | data = hookenv.execution_environment() | ||
3289 | 444 | self.conf = conf_delta = self.kv.delta(data['conf'], 'config') | ||
3290 | 445 | self.rels = rels_delta = self.kv.delta(data['rels'], 'rels') | ||
3291 | 446 | self.kv.set('env', data['env']) | ||
3292 | 447 | self.kv.set('unit', data['unit']) | ||
3293 | 448 | self.kv.set('relid', data.get('relid')) | ||
3294 | 449 | return conf_delta, rels_delta | ||
3295 | 450 | |||
3296 | 451 | |||
3297 | 452 | class Record(dict): | ||
3298 | 453 | |||
3299 | 454 | __slots__ = () | ||
3300 | 455 | |||
3301 | 456 | def __getattr__(self, k): | ||
3302 | 457 | if k in self: | ||
3303 | 458 | return self[k] | ||
3304 | 459 | raise AttributeError(k) | ||
3305 | 460 | |||
3306 | 461 | |||
3307 | 462 | class DeltaSet(Record): | ||
3308 | 463 | |||
3309 | 464 | __slots__ = () | ||
3310 | 465 | |||
3311 | 466 | |||
3312 | 467 | Delta = collections.namedtuple('Delta', ['previous', 'current']) | ||
3313 | 468 | |||
3314 | 469 | |||
3315 | 470 | _KV = None | ||
3316 | 471 | |||
3317 | 472 | |||
3318 | 473 | def kv(): | ||
3319 | 474 | global _KV | ||
3320 | 475 | if _KV is None: | ||
3321 | 476 | _KV = Storage() | ||
3322 | 477 | return _KV | ||
3323 | 0 | 478 | ||
3324 | === modified file 'hooks/charmhelpers/fetch/__init__.py' | |||
3325 | --- hooks/charmhelpers/fetch/__init__.py 2014-09-08 16:38:59 +0000 | |||
3326 | +++ hooks/charmhelpers/fetch/__init__.py 2015-03-23 00:51:45 +0000 | |||
3327 | @@ -1,3 +1,19 @@ | |||
3328 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3329 | 2 | # | ||
3330 | 3 | # This file is part of charm-helpers. | ||
3331 | 4 | # | ||
3332 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3333 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3334 | 7 | # published by the Free Software Foundation. | ||
3335 | 8 | # | ||
3336 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3337 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3338 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3339 | 12 | # GNU Lesser General Public License for more details. | ||
3340 | 13 | # | ||
3341 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3342 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3343 | 16 | |||
3344 | 1 | import importlib | 17 | import importlib |
3345 | 2 | from tempfile import NamedTemporaryFile | 18 | from tempfile import NamedTemporaryFile |
3346 | 3 | import time | 19 | import time |
3347 | @@ -5,10 +21,6 @@ | |||
3348 | 5 | from charmhelpers.core.host import ( | 21 | from charmhelpers.core.host import ( |
3349 | 6 | lsb_release | 22 | lsb_release |
3350 | 7 | ) | 23 | ) |
3351 | 8 | from urlparse import ( | ||
3352 | 9 | urlparse, | ||
3353 | 10 | urlunparse, | ||
3354 | 11 | ) | ||
3355 | 12 | import subprocess | 24 | import subprocess |
3356 | 13 | from charmhelpers.core.hookenv import ( | 25 | from charmhelpers.core.hookenv import ( |
3357 | 14 | config, | 26 | config, |
3358 | @@ -16,6 +28,12 @@ | |||
3359 | 16 | ) | 28 | ) |
3360 | 17 | import os | 29 | import os |
3361 | 18 | 30 | ||
3362 | 31 | import six | ||
3363 | 32 | if six.PY3: | ||
3364 | 33 | from urllib.parse import urlparse, urlunparse | ||
3365 | 34 | else: | ||
3366 | 35 | from urlparse import urlparse, urlunparse | ||
3367 | 36 | |||
3368 | 19 | 37 | ||
3369 | 20 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive | 38 | CLOUD_ARCHIVE = """# Ubuntu Cloud Archive |
3370 | 21 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main | 39 | deb http://ubuntu-cloud.archive.canonical.com/ubuntu {} main |
3371 | @@ -62,9 +80,16 @@ | |||
3372 | 62 | 'trusty-juno/updates': 'trusty-updates/juno', | 80 | 'trusty-juno/updates': 'trusty-updates/juno', |
3373 | 63 | 'trusty-updates/juno': 'trusty-updates/juno', | 81 | 'trusty-updates/juno': 'trusty-updates/juno', |
3374 | 64 | 'juno/proposed': 'trusty-proposed/juno', | 82 | 'juno/proposed': 'trusty-proposed/juno', |
3375 | 65 | 'juno/proposed': 'trusty-proposed/juno', | ||
3376 | 66 | 'trusty-juno/proposed': 'trusty-proposed/juno', | 83 | 'trusty-juno/proposed': 'trusty-proposed/juno', |
3377 | 67 | 'trusty-proposed/juno': 'trusty-proposed/juno', | 84 | 'trusty-proposed/juno': 'trusty-proposed/juno', |
3378 | 85 | # Kilo | ||
3379 | 86 | 'kilo': 'trusty-updates/kilo', | ||
3380 | 87 | 'trusty-kilo': 'trusty-updates/kilo', | ||
3381 | 88 | 'trusty-kilo/updates': 'trusty-updates/kilo', | ||
3382 | 89 | 'trusty-updates/kilo': 'trusty-updates/kilo', | ||
3383 | 90 | 'kilo/proposed': 'trusty-proposed/kilo', | ||
3384 | 91 | 'trusty-kilo/proposed': 'trusty-proposed/kilo', | ||
3385 | 92 | 'trusty-proposed/kilo': 'trusty-proposed/kilo', | ||
3386 | 68 | } | 93 | } |
3387 | 69 | 94 | ||
3388 | 70 | # The order of this list is very important. Handlers should be listed in from | 95 | # The order of this list is very important. Handlers should be listed in from |
3389 | @@ -72,6 +97,7 @@ | |||
3390 | 72 | FETCH_HANDLERS = ( | 97 | FETCH_HANDLERS = ( |
3391 | 73 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', | 98 | 'charmhelpers.fetch.archiveurl.ArchiveUrlFetchHandler', |
3392 | 74 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', | 99 | 'charmhelpers.fetch.bzrurl.BzrUrlFetchHandler', |
3393 | 100 | 'charmhelpers.fetch.giturl.GitUrlFetchHandler', | ||
3394 | 75 | ) | 101 | ) |
3395 | 76 | 102 | ||
3396 | 77 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. | 103 | APT_NO_LOCK = 100 # The return code for "couldn't acquire lock" in APT. |
3397 | @@ -148,7 +174,7 @@ | |||
3398 | 148 | cmd = ['apt-get', '--assume-yes'] | 174 | cmd = ['apt-get', '--assume-yes'] |
3399 | 149 | cmd.extend(options) | 175 | cmd.extend(options) |
3400 | 150 | cmd.append('install') | 176 | cmd.append('install') |
3402 | 151 | if isinstance(packages, basestring): | 177 | if isinstance(packages, six.string_types): |
3403 | 152 | cmd.append(packages) | 178 | cmd.append(packages) |
3404 | 153 | else: | 179 | else: |
3405 | 154 | cmd.extend(packages) | 180 | cmd.extend(packages) |
3406 | @@ -181,7 +207,7 @@ | |||
3407 | 181 | def apt_purge(packages, fatal=False): | 207 | def apt_purge(packages, fatal=False): |
3408 | 182 | """Purge one or more packages""" | 208 | """Purge one or more packages""" |
3409 | 183 | cmd = ['apt-get', '--assume-yes', 'purge'] | 209 | cmd = ['apt-get', '--assume-yes', 'purge'] |
3411 | 184 | if isinstance(packages, basestring): | 210 | if isinstance(packages, six.string_types): |
3412 | 185 | cmd.append(packages) | 211 | cmd.append(packages) |
3413 | 186 | else: | 212 | else: |
3414 | 187 | cmd.extend(packages) | 213 | cmd.extend(packages) |
3415 | @@ -192,7 +218,7 @@ | |||
3416 | 192 | def apt_hold(packages, fatal=False): | 218 | def apt_hold(packages, fatal=False): |
3417 | 193 | """Hold one or more packages""" | 219 | """Hold one or more packages""" |
3418 | 194 | cmd = ['apt-mark', 'hold'] | 220 | cmd = ['apt-mark', 'hold'] |
3420 | 195 | if isinstance(packages, basestring): | 221 | if isinstance(packages, six.string_types): |
3421 | 196 | cmd.append(packages) | 222 | cmd.append(packages) |
3422 | 197 | else: | 223 | else: |
3423 | 198 | cmd.extend(packages) | 224 | cmd.extend(packages) |
3424 | @@ -208,7 +234,8 @@ | |||
3425 | 208 | """Add a package source to this system. | 234 | """Add a package source to this system. |
3426 | 209 | 235 | ||
3427 | 210 | @param source: a URL or sources.list entry, as supported by | 236 | @param source: a URL or sources.list entry, as supported by |
3429 | 211 | add-apt-repository(1). Examples: | 237 | add-apt-repository(1). Examples:: |
3430 | 238 | |||
3431 | 212 | ppa:charmers/example | 239 | ppa:charmers/example |
3432 | 213 | deb https://stub:key@private.example.com/ubuntu trusty main | 240 | deb https://stub:key@private.example.com/ubuntu trusty main |
3433 | 214 | 241 | ||
3434 | @@ -217,6 +244,7 @@ | |||
3435 | 217 | pocket for the release. | 244 | pocket for the release. |
3436 | 218 | 'cloud:' may be used to activate official cloud archive pockets, | 245 | 'cloud:' may be used to activate official cloud archive pockets, |
3437 | 219 | such as 'cloud:icehouse' | 246 | such as 'cloud:icehouse' |
3438 | 247 | 'distro' may be used as a noop | ||
3439 | 220 | 248 | ||
3440 | 221 | @param key: A key to be added to the system's APT keyring and used | 249 | @param key: A key to be added to the system's APT keyring and used |
3441 | 222 | to verify the signatures on packages. Ideally, this should be an | 250 | to verify the signatures on packages. Ideally, this should be an |
3442 | @@ -250,12 +278,14 @@ | |||
3443 | 250 | release = lsb_release()['DISTRIB_CODENAME'] | 278 | release = lsb_release()['DISTRIB_CODENAME'] |
3444 | 251 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: | 279 | with open('/etc/apt/sources.list.d/proposed.list', 'w') as apt: |
3445 | 252 | apt.write(PROPOSED_POCKET.format(release)) | 280 | apt.write(PROPOSED_POCKET.format(release)) |
3446 | 281 | elif source == 'distro': | ||
3447 | 282 | pass | ||
3448 | 253 | else: | 283 | else: |
3450 | 254 | raise SourceConfigError("Unknown source: {!r}".format(source)) | 284 | log("Unknown source: {!r}".format(source)) |
3451 | 255 | 285 | ||
3452 | 256 | if key: | 286 | if key: |
3453 | 257 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: | 287 | if '-----BEGIN PGP PUBLIC KEY BLOCK-----' in key: |
3455 | 258 | with NamedTemporaryFile() as key_file: | 288 | with NamedTemporaryFile('w+') as key_file: |
3456 | 259 | key_file.write(key) | 289 | key_file.write(key) |
3457 | 260 | key_file.flush() | 290 | key_file.flush() |
3458 | 261 | key_file.seek(0) | 291 | key_file.seek(0) |
3459 | @@ -292,14 +322,14 @@ | |||
3460 | 292 | sources = safe_load((config(sources_var) or '').strip()) or [] | 322 | sources = safe_load((config(sources_var) or '').strip()) or [] |
3461 | 293 | keys = safe_load((config(keys_var) or '').strip()) or None | 323 | keys = safe_load((config(keys_var) or '').strip()) or None |
3462 | 294 | 324 | ||
3464 | 295 | if isinstance(sources, basestring): | 325 | if isinstance(sources, six.string_types): |
3465 | 296 | sources = [sources] | 326 | sources = [sources] |
3466 | 297 | 327 | ||
3467 | 298 | if keys is None: | 328 | if keys is None: |
3468 | 299 | for source in sources: | 329 | for source in sources: |
3469 | 300 | add_source(source, None) | 330 | add_source(source, None) |
3470 | 301 | else: | 331 | else: |
3472 | 302 | if isinstance(keys, basestring): | 332 | if isinstance(keys, six.string_types): |
3473 | 303 | keys = [keys] | 333 | keys = [keys] |
3474 | 304 | 334 | ||
3475 | 305 | if len(sources) != len(keys): | 335 | if len(sources) != len(keys): |
3476 | @@ -311,22 +341,35 @@ | |||
3477 | 311 | apt_update(fatal=True) | 341 | apt_update(fatal=True) |
3478 | 312 | 342 | ||
3479 | 313 | 343 | ||
3481 | 314 | def install_remote(source): | 344 | def install_remote(source, *args, **kwargs): |
3482 | 315 | """ | 345 | """ |
3483 | 316 | Install a file tree from a remote source | 346 | Install a file tree from a remote source |
3484 | 317 | 347 | ||
3485 | 318 | The specified source should be a url of the form: | 348 | The specified source should be a url of the form: |
3486 | 319 | scheme://[host]/path[#[option=value][&...]] | 349 | scheme://[host]/path[#[option=value][&...]] |
3487 | 320 | 350 | ||
3490 | 321 | Schemes supported are based on this modules submodules | 351 | Schemes supported are based on this modules submodules. |
3491 | 322 | Options supported are submodule-specific""" | 352 | Options supported are submodule-specific. |
3492 | 353 | Additional arguments are passed through to the submodule. | ||
3493 | 354 | |||
3494 | 355 | For example:: | ||
3495 | 356 | |||
3496 | 357 | dest = install_remote('http://example.com/archive.tgz', | ||
3497 | 358 | checksum='deadbeef', | ||
3498 | 359 | hash_type='sha1') | ||
3499 | 360 | |||
3500 | 361 | This will download `archive.tgz`, validate it using SHA1 and, if | ||
3501 | 362 | the file is ok, extract it and return the directory in which it | ||
3502 | 363 | was extracted. If the checksum fails, it will raise | ||
3503 | 364 | :class:`charmhelpers.core.host.ChecksumError`. | ||
3504 | 365 | """ | ||
3505 | 323 | # We ONLY check for True here because can_handle may return a string | 366 | # We ONLY check for True here because can_handle may return a string |
3506 | 324 | # explaining why it can't handle a given source. | 367 | # explaining why it can't handle a given source. |
3507 | 325 | handlers = [h for h in plugins() if h.can_handle(source) is True] | 368 | handlers = [h for h in plugins() if h.can_handle(source) is True] |
3508 | 326 | installed_to = None | 369 | installed_to = None |
3509 | 327 | for handler in handlers: | 370 | for handler in handlers: |
3510 | 328 | try: | 371 | try: |
3512 | 329 | installed_to = handler.install(source) | 372 | installed_to = handler.install(source, *args, **kwargs) |
3513 | 330 | except UnhandledSource: | 373 | except UnhandledSource: |
3514 | 331 | pass | 374 | pass |
3515 | 332 | if not installed_to: | 375 | if not installed_to: |
3516 | @@ -383,7 +426,7 @@ | |||
3517 | 383 | while result is None or result == APT_NO_LOCK: | 426 | while result is None or result == APT_NO_LOCK: |
3518 | 384 | try: | 427 | try: |
3519 | 385 | result = subprocess.check_call(cmd, env=env) | 428 | result = subprocess.check_call(cmd, env=env) |
3521 | 386 | except subprocess.CalledProcessError, e: | 429 | except subprocess.CalledProcessError as e: |
3522 | 387 | retry_count = retry_count + 1 | 430 | retry_count = retry_count + 1 |
3523 | 388 | if retry_count > APT_NO_LOCK_RETRY_COUNT: | 431 | if retry_count > APT_NO_LOCK_RETRY_COUNT: |
3524 | 389 | raise | 432 | raise |
3525 | 390 | 433 | ||
3526 | === modified file 'hooks/charmhelpers/fetch/archiveurl.py' | |||
3527 | --- hooks/charmhelpers/fetch/archiveurl.py 2014-07-16 05:40:55 +0000 | |||
3528 | +++ hooks/charmhelpers/fetch/archiveurl.py 2015-03-23 00:51:45 +0000 | |||
3529 | @@ -1,6 +1,22 @@ | |||
3530 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3531 | 2 | # | ||
3532 | 3 | # This file is part of charm-helpers. | ||
3533 | 4 | # | ||
3534 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3535 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3536 | 7 | # published by the Free Software Foundation. | ||
3537 | 8 | # | ||
3538 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3539 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3540 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3541 | 12 | # GNU Lesser General Public License for more details. | ||
3542 | 13 | # | ||
3543 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3544 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3545 | 16 | |||
3546 | 1 | import os | 17 | import os |
3549 | 2 | import urllib2 | 18 | import hashlib |
3550 | 3 | import urlparse | 19 | import re |
3551 | 4 | 20 | ||
3552 | 5 | from charmhelpers.fetch import ( | 21 | from charmhelpers.fetch import ( |
3553 | 6 | BaseFetchHandler, | 22 | BaseFetchHandler, |
3554 | @@ -10,11 +26,54 @@ | |||
3555 | 10 | get_archive_handler, | 26 | get_archive_handler, |
3556 | 11 | extract, | 27 | extract, |
3557 | 12 | ) | 28 | ) |
3559 | 13 | from charmhelpers.core.host import mkdir | 29 | from charmhelpers.core.host import mkdir, check_hash |
3560 | 30 | |||
3561 | 31 | import six | ||
3562 | 32 | if six.PY3: | ||
3563 | 33 | from urllib.request import ( | ||
3564 | 34 | build_opener, install_opener, urlopen, urlretrieve, | ||
3565 | 35 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
3566 | 36 | ) | ||
3567 | 37 | from urllib.parse import urlparse, urlunparse, parse_qs | ||
3568 | 38 | from urllib.error import URLError | ||
3569 | 39 | else: | ||
3570 | 40 | from urllib import urlretrieve | ||
3571 | 41 | from urllib2 import ( | ||
3572 | 42 | build_opener, install_opener, urlopen, | ||
3573 | 43 | HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, | ||
3574 | 44 | URLError | ||
3575 | 45 | ) | ||
3576 | 46 | from urlparse import urlparse, urlunparse, parse_qs | ||
3577 | 47 | |||
3578 | 48 | |||
3579 | 49 | def splituser(host): | ||
3580 | 50 | '''urllib.splituser(), but six's support of this seems broken''' | ||
3581 | 51 | _userprog = re.compile('^(.*)@(.*)$') | ||
3582 | 52 | match = _userprog.match(host) | ||
3583 | 53 | if match: | ||
3584 | 54 | return match.group(1, 2) | ||
3585 | 55 | return None, host | ||
3586 | 56 | |||
3587 | 57 | |||
3588 | 58 | def splitpasswd(user): | ||
3589 | 59 | '''urllib.splitpasswd(), but six's support of this is missing''' | ||
3590 | 60 | _passwdprog = re.compile('^([^:]*):(.*)$', re.S) | ||
3591 | 61 | match = _passwdprog.match(user) | ||
3592 | 62 | if match: | ||
3593 | 63 | return match.group(1, 2) | ||
3594 | 64 | return user, None | ||
3595 | 14 | 65 | ||
3596 | 15 | 66 | ||
3597 | 16 | class ArchiveUrlFetchHandler(BaseFetchHandler): | 67 | class ArchiveUrlFetchHandler(BaseFetchHandler): |
3599 | 17 | """Handler for archives via generic URLs""" | 68 | """ |
3600 | 69 | Handler to download archive files from arbitrary URLs. | ||
3601 | 70 | |||
3602 | 71 | Can fetch from http, https, ftp, and file URLs. | ||
3603 | 72 | |||
3604 | 73 | Can install either tarballs (.tar, .tgz, .tbz2, etc) or zip files. | ||
3605 | 74 | |||
3606 | 75 | Installs the contents of the archive in $CHARM_DIR/fetched/. | ||
3607 | 76 | """ | ||
3608 | 18 | def can_handle(self, source): | 77 | def can_handle(self, source): |
3609 | 19 | url_parts = self.parse_url(source) | 78 | url_parts = self.parse_url(source) |
3610 | 20 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): | 79 | if url_parts.scheme not in ('http', 'https', 'ftp', 'file'): |
3611 | @@ -24,22 +83,28 @@ | |||
3612 | 24 | return False | 83 | return False |
3613 | 25 | 84 | ||
3614 | 26 | def download(self, source, dest): | 85 | def download(self, source, dest): |
3615 | 86 | """ | ||
3616 | 87 | Download an archive file. | ||
3617 | 88 | |||
3618 | 89 | :param str source: URL pointing to an archive file. | ||
3619 | 90 | :param str dest: Local path location to download archive file to. | ||
3620 | 91 | """ | ||
3621 | 27 | # propogate all exceptions | 92 | # propogate all exceptions |
3622 | 28 | # URLError, OSError, etc | 93 | # URLError, OSError, etc |
3624 | 29 | proto, netloc, path, params, query, fragment = urlparse.urlparse(source) | 94 | proto, netloc, path, params, query, fragment = urlparse(source) |
3625 | 30 | if proto in ('http', 'https'): | 95 | if proto in ('http', 'https'): |
3627 | 31 | auth, barehost = urllib2.splituser(netloc) | 96 | auth, barehost = splituser(netloc) |
3628 | 32 | if auth is not None: | 97 | if auth is not None: |
3632 | 33 | source = urlparse.urlunparse((proto, barehost, path, params, query, fragment)) | 98 | source = urlunparse((proto, barehost, path, params, query, fragment)) |
3633 | 34 | username, password = urllib2.splitpasswd(auth) | 99 | username, password = splitpasswd(auth) |
3634 | 35 | passman = urllib2.HTTPPasswordMgrWithDefaultRealm() | 100 | passman = HTTPPasswordMgrWithDefaultRealm() |
3635 | 36 | # Realm is set to None in add_password to force the username and password | 101 | # Realm is set to None in add_password to force the username and password |
3636 | 37 | # to be used whatever the realm | 102 | # to be used whatever the realm |
3637 | 38 | passman.add_password(None, source, username, password) | 103 | passman.add_password(None, source, username, password) |
3642 | 39 | authhandler = urllib2.HTTPBasicAuthHandler(passman) | 104 | authhandler = HTTPBasicAuthHandler(passman) |
3643 | 40 | opener = urllib2.build_opener(authhandler) | 105 | opener = build_opener(authhandler) |
3644 | 41 | urllib2.install_opener(opener) | 106 | install_opener(opener) |
3645 | 42 | response = urllib2.urlopen(source) | 107 | response = urlopen(source) |
3646 | 43 | try: | 108 | try: |
3647 | 44 | with open(dest, 'w') as dest_file: | 109 | with open(dest, 'w') as dest_file: |
3648 | 45 | dest_file.write(response.read()) | 110 | dest_file.write(response.read()) |
3649 | @@ -48,16 +113,49 @@ | |||
3650 | 48 | os.unlink(dest) | 113 | os.unlink(dest) |
3651 | 49 | raise e | 114 | raise e |
3652 | 50 | 115 | ||
3654 | 51 | def install(self, source): | 116 | # Mandatory file validation via Sha1 or MD5 hashing. |
3655 | 117 | def download_and_validate(self, url, hashsum, validate="sha1"): | ||
3656 | 118 | tempfile, headers = urlretrieve(url) | ||
3657 | 119 | check_hash(tempfile, hashsum, validate) | ||
3658 | 120 | return tempfile | ||
3659 | 121 | |||
3660 | 122 | def install(self, source, dest=None, checksum=None, hash_type='sha1'): | ||
3661 | 123 | """ | ||
3662 | 124 | Download and install an archive file, with optional checksum validation. | ||
3663 | 125 | |||
3664 | 126 | The checksum can also be given on the `source` URL's fragment. | ||
3665 | 127 | For example:: | ||
3666 | 128 | |||
3667 | 129 | handler.install('http://example.com/file.tgz#sha1=deadbeef') | ||
3668 | 130 | |||
3669 | 131 | :param str source: URL pointing to an archive file. | ||
3670 | 132 | :param str dest: Local destination path to install to. If not given, | ||
3671 | 133 | installs to `$CHARM_DIR/archives/archive_file_name`. | ||
3672 | 134 | :param str checksum: If given, validate the archive file after download. | ||
3673 | 135 | :param str hash_type: Algorithm used to generate `checksum`. | ||
3674 | 136 | Can be any hash alrgorithm supported by :mod:`hashlib`, | ||
3675 | 137 | such as md5, sha1, sha256, sha512, etc. | ||
3676 | 138 | |||
3677 | 139 | """ | ||
3678 | 52 | url_parts = self.parse_url(source) | 140 | url_parts = self.parse_url(source) |
3679 | 53 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') | 141 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched') |
3680 | 54 | if not os.path.exists(dest_dir): | 142 | if not os.path.exists(dest_dir): |
3682 | 55 | mkdir(dest_dir, perms=0755) | 143 | mkdir(dest_dir, perms=0o755) |
3683 | 56 | dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path)) | 144 | dld_file = os.path.join(dest_dir, os.path.basename(url_parts.path)) |
3684 | 57 | try: | 145 | try: |
3685 | 58 | self.download(source, dld_file) | 146 | self.download(source, dld_file) |
3687 | 59 | except urllib2.URLError as e: | 147 | except URLError as e: |
3688 | 60 | raise UnhandledSource(e.reason) | 148 | raise UnhandledSource(e.reason) |
3689 | 61 | except OSError as e: | 149 | except OSError as e: |
3690 | 62 | raise UnhandledSource(e.strerror) | 150 | raise UnhandledSource(e.strerror) |
3692 | 63 | return extract(dld_file) | 151 | options = parse_qs(url_parts.fragment) |
3693 | 152 | for key, value in options.items(): | ||
3694 | 153 | if not six.PY3: | ||
3695 | 154 | algorithms = hashlib.algorithms | ||
3696 | 155 | else: | ||
3697 | 156 | algorithms = hashlib.algorithms_available | ||
3698 | 157 | if key in algorithms: | ||
3699 | 158 | check_hash(dld_file, value, key) | ||
3700 | 159 | if checksum: | ||
3701 | 160 | check_hash(dld_file, checksum, hash_type) | ||
3702 | 161 | return extract(dld_file, dest) | ||
3703 | 64 | 162 | ||
3704 | === modified file 'hooks/charmhelpers/fetch/bzrurl.py' | |||
3705 | --- hooks/charmhelpers/fetch/bzrurl.py 2014-07-16 05:40:55 +0000 | |||
3706 | +++ hooks/charmhelpers/fetch/bzrurl.py 2015-03-23 00:51:45 +0000 | |||
3707 | @@ -1,3 +1,19 @@ | |||
3708 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3709 | 2 | # | ||
3710 | 3 | # This file is part of charm-helpers. | ||
3711 | 4 | # | ||
3712 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3713 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3714 | 7 | # published by the Free Software Foundation. | ||
3715 | 8 | # | ||
3716 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3717 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3718 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3719 | 12 | # GNU Lesser General Public License for more details. | ||
3720 | 13 | # | ||
3721 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3722 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3723 | 16 | |||
3724 | 1 | import os | 17 | import os |
3725 | 2 | from charmhelpers.fetch import ( | 18 | from charmhelpers.fetch import ( |
3726 | 3 | BaseFetchHandler, | 19 | BaseFetchHandler, |
3727 | @@ -5,12 +21,18 @@ | |||
3728 | 5 | ) | 21 | ) |
3729 | 6 | from charmhelpers.core.host import mkdir | 22 | from charmhelpers.core.host import mkdir |
3730 | 7 | 23 | ||
3731 | 24 | import six | ||
3732 | 25 | if six.PY3: | ||
3733 | 26 | raise ImportError('bzrlib does not support Python3') | ||
3734 | 27 | |||
3735 | 8 | try: | 28 | try: |
3736 | 9 | from bzrlib.branch import Branch | 29 | from bzrlib.branch import Branch |
3737 | 30 | from bzrlib import bzrdir, workingtree, errors | ||
3738 | 10 | except ImportError: | 31 | except ImportError: |
3739 | 11 | from charmhelpers.fetch import apt_install | 32 | from charmhelpers.fetch import apt_install |
3740 | 12 | apt_install("python-bzrlib") | 33 | apt_install("python-bzrlib") |
3741 | 13 | from bzrlib.branch import Branch | 34 | from bzrlib.branch import Branch |
3742 | 35 | from bzrlib import bzrdir, workingtree, errors | ||
3743 | 14 | 36 | ||
3744 | 15 | 37 | ||
3745 | 16 | class BzrUrlFetchHandler(BaseFetchHandler): | 38 | class BzrUrlFetchHandler(BaseFetchHandler): |
3746 | @@ -31,8 +53,14 @@ | |||
3747 | 31 | from bzrlib.plugin import load_plugins | 53 | from bzrlib.plugin import load_plugins |
3748 | 32 | load_plugins() | 54 | load_plugins() |
3749 | 33 | try: | 55 | try: |
3750 | 56 | local_branch = bzrdir.BzrDir.create_branch_convenience(dest) | ||
3751 | 57 | except errors.AlreadyControlDirError: | ||
3752 | 58 | local_branch = Branch.open(dest) | ||
3753 | 59 | try: | ||
3754 | 34 | remote_branch = Branch.open(source) | 60 | remote_branch = Branch.open(source) |
3756 | 35 | remote_branch.bzrdir.sprout(dest).open_branch() | 61 | remote_branch.push(local_branch) |
3757 | 62 | tree = workingtree.WorkingTree.open(dest) | ||
3758 | 63 | tree.update() | ||
3759 | 36 | except Exception as e: | 64 | except Exception as e: |
3760 | 37 | raise e | 65 | raise e |
3761 | 38 | 66 | ||
3762 | @@ -42,7 +70,7 @@ | |||
3763 | 42 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | 70 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", |
3764 | 43 | branch_name) | 71 | branch_name) |
3765 | 44 | if not os.path.exists(dest_dir): | 72 | if not os.path.exists(dest_dir): |
3767 | 45 | mkdir(dest_dir, perms=0755) | 73 | mkdir(dest_dir, perms=0o755) |
3768 | 46 | try: | 74 | try: |
3769 | 47 | self.branch(source, dest_dir) | 75 | self.branch(source, dest_dir) |
3770 | 48 | except OSError as e: | 76 | except OSError as e: |
3771 | 49 | 77 | ||
3772 | === added file 'hooks/charmhelpers/fetch/giturl.py' | |||
3773 | --- hooks/charmhelpers/fetch/giturl.py 1970-01-01 00:00:00 +0000 | |||
3774 | +++ hooks/charmhelpers/fetch/giturl.py 2015-03-23 00:51:45 +0000 | |||
3775 | @@ -0,0 +1,71 @@ | |||
3776 | 1 | # Copyright 2014-2015 Canonical Limited. | ||
3777 | 2 | # | ||
3778 | 3 | # This file is part of charm-helpers. | ||
3779 | 4 | # | ||
3780 | 5 | # charm-helpers is free software: you can redistribute it and/or modify | ||
3781 | 6 | # it under the terms of the GNU Lesser General Public License version 3 as | ||
3782 | 7 | # published by the Free Software Foundation. | ||
3783 | 8 | # | ||
3784 | 9 | # charm-helpers is distributed in the hope that it will be useful, | ||
3785 | 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
3786 | 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
3787 | 12 | # GNU Lesser General Public License for more details. | ||
3788 | 13 | # | ||
3789 | 14 | # You should have received a copy of the GNU Lesser General Public License | ||
3790 | 15 | # along with charm-helpers. If not, see <http://www.gnu.org/licenses/>. | ||
3791 | 16 | |||
3792 | 17 | import os | ||
3793 | 18 | from charmhelpers.fetch import ( | ||
3794 | 19 | BaseFetchHandler, | ||
3795 | 20 | UnhandledSource | ||
3796 | 21 | ) | ||
3797 | 22 | from charmhelpers.core.host import mkdir | ||
3798 | 23 | |||
3799 | 24 | import six | ||
3800 | 25 | if six.PY3: | ||
3801 | 26 | raise ImportError('GitPython does not support Python 3') | ||
3802 | 27 | |||
3803 | 28 | try: | ||
3804 | 29 | from git import Repo | ||
3805 | 30 | except ImportError: | ||
3806 | 31 | from charmhelpers.fetch import apt_install | ||
3807 | 32 | apt_install("python-git") | ||
3808 | 33 | from git import Repo | ||
3809 | 34 | |||
3810 | 35 | from git.exc import GitCommandError # noqa E402 | ||
3811 | 36 | |||
3812 | 37 | |||
3813 | 38 | class GitUrlFetchHandler(BaseFetchHandler): | ||
3814 | 39 | """Handler for git branches via generic and github URLs""" | ||
3815 | 40 | def can_handle(self, source): | ||
3816 | 41 | url_parts = self.parse_url(source) | ||
3817 | 42 | # TODO (mattyw) no support for ssh git@ yet | ||
3818 | 43 | if url_parts.scheme not in ('http', 'https', 'git'): | ||
3819 | 44 | return False | ||
3820 | 45 | else: | ||
3821 | 46 | return True | ||
3822 | 47 | |||
3823 | 48 | def clone(self, source, dest, branch): | ||
3824 | 49 | if not self.can_handle(source): | ||
3825 | 50 | raise UnhandledSource("Cannot handle {}".format(source)) | ||
3826 | 51 | |||
3827 | 52 | repo = Repo.clone_from(source, dest) | ||
3828 | 53 | repo.git.checkout(branch) | ||
3829 | 54 | |||
3830 | 55 | def install(self, source, branch="master", dest=None): | ||
3831 | 56 | url_parts = self.parse_url(source) | ||
3832 | 57 | branch_name = url_parts.path.strip("/").split("/")[-1] | ||
3833 | 58 | if dest: | ||
3834 | 59 | dest_dir = os.path.join(dest, branch_name) | ||
3835 | 60 | else: | ||
3836 | 61 | dest_dir = os.path.join(os.environ.get('CHARM_DIR'), "fetched", | ||
3837 | 62 | branch_name) | ||
3838 | 63 | if not os.path.exists(dest_dir): | ||
3839 | 64 | mkdir(dest_dir, perms=0o755) | ||
3840 | 65 | try: | ||
3841 | 66 | self.clone(source, dest_dir, branch) | ||
3842 | 67 | except GitCommandError as e: | ||
3843 | 68 | raise UnhandledSource(e.message) | ||
3844 | 69 | except OSError as e: | ||
3845 | 70 | raise UnhandledSource(e.strerror) | ||
3846 | 71 | return dest_dir | ||
3847 | 0 | 72 | ||
3848 | === added symlink 'hooks/nrpe-external-master-relation-changed' | |||
3849 | === target is u'ntp_hooks.py' | |||
3850 | === added symlink 'hooks/nrpe-external-master-relation-joined' | |||
3851 | === target is u'ntp_hooks.py' | |||
3852 | === modified file 'hooks/ntp_hooks.py' | |||
3853 | --- hooks/ntp_hooks.py 2014-08-05 05:12:15 +0000 | |||
3854 | +++ hooks/ntp_hooks.py 2015-03-23 00:51:45 +0000 | |||
3855 | @@ -9,6 +9,9 @@ | |||
3856 | 9 | import shutil | 9 | import shutil |
3857 | 10 | import os | 10 | import os |
3858 | 11 | 11 | ||
3859 | 12 | from charmhelpers.contrib.charmsupport import nrpe | ||
3860 | 13 | |||
3861 | 14 | NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins' | ||
3862 | 12 | 15 | ||
3863 | 13 | NTP_CONF = '/etc/ntp.conf' | 16 | NTP_CONF = '/etc/ntp.conf' |
3864 | 14 | NTP_CONF_ORIG = '{}.orig'.format(NTP_CONF) | 17 | NTP_CONF_ORIG = '{}.orig'.format(NTP_CONF) |
3865 | @@ -48,6 +51,42 @@ | |||
3866 | 48 | ntpconf.write(render(os.path.basename(NTP_CONF), | 51 | ntpconf.write(render(os.path.basename(NTP_CONF), |
3867 | 49 | {'servers': remote_sources})) | 52 | {'servers': remote_sources})) |
3868 | 50 | 53 | ||
3869 | 54 | update_nrpe_config() | ||
3870 | 55 | |||
3871 | 56 | |||
3872 | 57 | @hooks.hook('nrpe-external-master-relation-joined', | ||
3873 | 58 | 'nrpe-external-master-relation-changed') | ||
3874 | 59 | def update_nrpe_config(): | ||
3875 | 60 | # python-dbus is used by check_upstart_job | ||
3876 | 61 | fetch.apt_install('python-dbus') | ||
3877 | 62 | nagios_ntpmon_checks = hookenv.config('nagios_ntpmon_checks') | ||
3878 | 63 | if os.path.isdir(NAGIOS_PLUGINS): | ||
3879 | 64 | host.rsync(os.path.join(os.getenv('CHARM_DIR'), 'files', 'nagios', | ||
3880 | 65 | 'check_ntpd.pl'), | ||
3881 | 66 | os.path.join(NAGIOS_PLUGINS, 'check_ntpd.pl')) | ||
3882 | 67 | if nagios_ntpmon_checks: | ||
3883 | 68 | host.rsync(os.path.join(os.getenv('CHARM_DIR'), 'files', 'nagios', | ||
3884 | 69 | 'check_ntpmon.py'), | ||
3885 | 70 | os.path.join(NAGIOS_PLUGINS, 'check_ntpmon.py')) | ||
3886 | 71 | |||
3887 | 72 | hostname = nrpe.get_nagios_hostname() | ||
3888 | 73 | current_unit = nrpe.get_nagios_unit_name() | ||
3889 | 74 | nrpe_setup = nrpe.NRPE(hostname=hostname) | ||
3890 | 75 | nrpe.add_init_service_checks(nrpe_setup, ['ntp'], current_unit) | ||
3891 | 76 | nrpe_setup.add_check( | ||
3892 | 77 | shortname="ntp_status", | ||
3893 | 78 | description='Check NTP status {%s}' % current_unit, | ||
3894 | 79 | check_cmd='check_ntpd.pl' | ||
3895 | 80 | ) | ||
3896 | 81 | for nc in nagios_ntpmon_checks.split(" "): | ||
3897 | 82 | nrpe_setup.add_check( | ||
3898 | 83 | shortname="ntpmon_%s" % nc, | ||
3899 | 84 | description='Check NTPmon %s {%s}' % (nc, current_unit), | ||
3900 | 85 | check_cmd='check_ntpmon.py --check %s' % nc | ||
3901 | 86 | ) | ||
3902 | 87 | |||
3903 | 88 | nrpe_setup.write() | ||
3904 | 89 | |||
3905 | 51 | 90 | ||
3906 | 52 | if __name__ == '__main__': | 91 | if __name__ == '__main__': |
3907 | 53 | try: | 92 | try: |
3908 | 54 | 93 | ||
3909 | === modified file 'metadata.yaml' | |||
3910 | --- metadata.yaml 2013-09-16 09:14:14 +0000 | |||
3911 | +++ metadata.yaml 2015-03-23 00:51:45 +0000 | |||
3912 | @@ -10,8 +10,12 @@ | |||
3913 | 10 | . | 10 | . |
3914 | 11 | This charm can be deployed alongside principle charms to enable NTP | 11 | This charm can be deployed alongside principle charms to enable NTP |
3915 | 12 | management across deployed services. | 12 | management across deployed services. |
3917 | 13 | categories: | 13 | tags: |
3918 | 14 | - misc | 14 | - misc |
3919 | 15 | provides: | ||
3920 | 16 | nrpe-external-master: | ||
3921 | 17 | interface: nrpe-external-master | ||
3922 | 18 | scope: container | ||
3923 | 15 | requires: | 19 | requires: |
3924 | 16 | juju-info: | 20 | juju-info: |
3925 | 17 | interface: juju-info | 21 | interface: juju-info |
LGTM +1