1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
|
# Copyright 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import calendar
import contextlib
from datetime import (
date,
datetime,
timedelta,
)
import hashlib
import json
import logging
import os
import shutil
import subprocess
import sys
import traceback
from types import StringTypes
import urllib2
from bzrlib.branch import Branch
from bzrlib.revision import NULL_REVISION
from bzrlib.transport import get_transport
import requests
import yaml
from charmworld.charmstore import (
CharmStore,
get_address,
make_store_url,
)
from charmworld.lp import (
get_branch_info,
parse_date,
)
from charmworld.models import (
CharmFileSet,
CharmSource,
construct_charm_id,
getconnection,
getdb,
getfs,
get_basket_info,
options_to_storage,
slurp_files,
store_bundles,
)
from charmworld.search import (
ElasticSearchClient,
SearchServiceNotAvailable,
)
from charmworld.utils import (
quote_key,
quote_yaml,
read_locked,
timestamp,
unquote_yaml,
)
# XXX Why not "from charmworld.jobs.config import..."? (Benji)
from config import CHARM_DIR
from config import CHARM_PROOF_PATH
from config import settings
ICON_FILENAME = 'icon.svg'
JENKINS_PROVIDERS = ['ec2', 'openstack', 'local']
JENKINS_ARTIFACT_URL = (
"https://jenkins.qa.ubuntu.com/job/"
"%(series)s-%(provider)s-charm-%(charm)s/%(build)d/artifact/%(artifact)s")
JENKINS_QA_URL = (
"https://jenkins.qa.ubuntu.com/job/"
"%(series)s-%(provider)s-charm-%(charm)s/lastBuild/api/json")
class IngestError(Exception):
pass
class IngestJob(object):
name = 'default'
def __init__(self):
self.log = logging.getLogger("charm.%s" % self.name)
def setup(self):
pass
def run(self, charm_data):
raise NotImplementedError
class DBIngestJob(IngestJob):
def setup(self, db=None):
if not db:
connection = getconnection(settings)
db = getdb(connection, settings.get('mongo.database'))
self.db = db
def do_bzr_update(charm_data, db, fs, log, root_dir=None):
"""Fetch a branch from bzr, and augment charm data."""
if not root_dir:
root_dir = CHARM_DIR
root_dir = root_dir
if not os.path.exists(root_dir):
os.makedirs(root_dir)
update_charm_files(root_dir, fs, charm_data, log)
def update_branch(root_dir, branch_data, branch_dir, log, retry=False):
log.debug('Updating branch lp:%s', branch_data['branch_spec'])
try:
subprocess.check_output(
['/usr/bin/bzr', 'update', '-q'],
cwd=branch_dir,
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
# Update failed for some reason; destroy it and start over.
if retry:
shutil.rmtree(branch_dir)
return checkout_branch(branch_data, branch_dir, log)
raise
def branch_is_current(branch_data, branch_dir, log):
# It exists and check if it's the latest revision already.
log.debug(
"Existing checkout from lp:%s", branch_data["branch_spec"])
transport = get_transport(branch_dir)
branch = Branch.open_from_transport(transport)
cur_rev_id = branch.last_revision()
return cur_rev_id == branch_data['commit']
def checkout_branch(branch_data, branch_dir, log):
# The branch has never been seen before. Original branch.
log.info("Checking out lp:%s", branch_data["branch_spec"])
subprocess.check_output(
["/usr/bin/bzr", "checkout", "-q",
"lp:%s" % branch_data["branch_spec"], branch_dir])
def store_charm_files(fs, branch_dir, charm_data, log):
"""Process the bzr branch for files that need to be stored in gridfs.
"""
log.info('Storing files of branch into gridfs')
filestore = CharmFileSet.save_files(
fs, charm_data, branch_dir, log)
log.info('Completed gridfs storage.')
return filestore
def add_files(fs, branch_dir, charm_data, log):
charm_data['files'] = dict([
(quote_key(cfile.filename), dict(cfile)) for cfile in
store_charm_files(fs, branch_dir, charm_data, log)
])
return charm_data
def construct_branch_dir(root_dir, branch_data):
return os.path.abspath(
str(os.path.join(root_dir,
branch_data["series"],
branch_data["owner"],
branch_data["name"],
branch_data["bname"])))
def fetch_branch(root_dir, branch_data, log, retry=True):
branch_dir = construct_branch_dir(root_dir, branch_data)
if not os.path.exists(os.path.dirname(branch_dir)):
os.makedirs(os.path.dirname(branch_dir))
if not os.path.exists(branch_dir):
# Branch doesn't exist; check it out.
checkout_branch(branch_data, branch_dir, log)
elif branch_is_current(branch_data, branch_dir, log):
# Branch exists, and is current; log and finish.
log.debug(
"Already up to date lp:%s", branch_data["branch_spec"])
else:
# Branch exists, but needs updating; update it.
update_branch(root_dir, branch_data, branch_dir, log, retry)
return branch_dir
def update_charm_files(root_dir, fs, charm_data, log, retry=True):
if charm_data['branch_deleted']:
return
# Store the branch directory
branch_dir = fetch_branch(root_dir, charm_data, log, retry)
charm_data["branch_dir"] = branch_dir
charm_data = add_files(fs, branch_dir, charm_data, log)
def log(stage, level, exc, charm_data, tb=None):
logger = logging.getLogger("charm.%s" % stage)
err_msg = "%s error on %s: %s" % (
stage, charm_data, str(exc))
if tb is not None:
err_msg = '%s\n%s' % (err_msg, tb)
logger.log(level, err_msg)
charm_error = {'error_stage': stage, 'error': str(exc)}
if hasattr(exc, 'output'):
charm_error['output'] = str(exc.output)
charm_data['error'] = charm_error
def run_job(job, charm_data, needs_setup=True, db=None):
if needs_setup:
if db is not None:
job.setup(db=db)
else:
job.setup()
stage = job.name
try:
job.run(charm_data)
except IngestError as e:
log(stage, logging.INFO, e, charm_data)
return False
except SearchServiceNotAvailable:
raise
except Exception as e:
tb = traceback.format_exc()
log(stage, logging.ERROR, e, charm_data, tb)
return False
return True
def update_hash(charm_data):
hashable_data = charm_data.copy()
hashable_data.pop('hash', None)
h = hashlib.sha256()
h.update(json.dumps(hashable_data, sort_keys=True))
charm_data['hash'] = h.hexdigest()
def update_charm(charm_data, db, store):
# Drop existing error data so that charms can lose their error status.
charm_data.pop('error', None)
if 'errors' in charm_data.get('store_data', {}):
return
log = logging.getLogger("charm.update_charm")
fs = getfs(db)
try:
do_bzr_update(charm_data, db, fs, log)
update_download_count(store, charm_data)
update_proof_data(charm_data, log)
update_jenkins_data(db, charm_data, log)
update_from_revisions(charm_data)
update_date_created(charm_data, log)
scan_charm(charm_data, db, fs, log)
update_hash(charm_data)
except Exception as e:
err_msg = "%s error: %s" % (charm_data, str(e))
log.exception(err_msg)
charm_error = {'error': str(e)}
if hasattr(e, 'output'):
charm_error['output'] = str(e.output)
charm_data['error'] = charm_error
class UpdateCharmJob(DBIngestJob):
name = 'update'
def run(self, payload):
payload['_id'] = construct_charm_id(payload)
charm_data = self.db.charms.find_one(payload['_id'])
if charm_data is None:
charm_data = {}
charm_data.update(payload)
update_charm(charm_data, self.db, CharmStore())
index_client = ElasticSearchClient.from_settings(settings)
self.log.info('Saving %s' % charm_data['_id'])
CharmSource(self.db, index_client).save(charm_data)
class UpdateBundleJob(DBIngestJob):
name = 'update-bundle'
def __init__(self, working_dir=None):
if working_dir is None:
working_dir = CHARM_DIR
self.working_dir = working_dir
super(UpdateBundleJob, self).__init__()
def store_bundles(self, deployer_config, owner, basket_id):
store_bundles(self.db.bundles, deployer_config, owner, basket_id)
@staticmethod
def set_basket_info(data, revno):
data.update(get_basket_info(revno, **data))
def decorate_basket(self, basket_data, fs):
branch_dir = fetch_branch(self.working_dir, basket_data, self.log)
branch = Branch.open(branch_dir)
revno = branch.revision_id_to_revno(basket_data['commit'])
self.set_basket_info(basket_data, revno)
with read_locked(branch):
tree = branch.repository.revision_tree(basket_data['commit'])
basket_data['file_hashes'] = quote_yaml(slurp_files(fs, tree))
@staticmethod
def get_deployer_config(fs, basket_data):
hashes = unquote_yaml(basket_data['file_hashes'])
deployer_config_bytes = fs.get(hashes['bundles.yaml'])
return yaml.safe_load(deployer_config_bytes)
def run(self, basket_data):
self.log.info('Saving %s' % basket_data['branch_spec'])
fs = getfs(self.db, collection='hashed-files')
self.decorate_basket(basket_data, fs)
self.db.baskets.save(basket_data)
deployer_config = self.get_deployer_config(fs, basket_data)
self.store_bundles(
deployer_config, basket_data['owner'], basket_data['name_revno'])
def _rev_info(r, branch):
d = {
'authors': r.get_apparent_authors(),
"revno": branch.revision_id_to_revno(r.revision_id),
"committer": r.committer,
"created": r.timestamp,
"message": r.message,
}
return d
def update_from_revisions(charm_data, limit=10, since=None):
if charm_data['branch_deleted']:
return
if since is None:
days_of_revisions = settings.get('days_of_revisions')
if days_of_revisions is not None:
cutoff = datetime.utcnow() - timedelta(int(days_of_revisions))
since = calendar.timegm(cutoff.timetuple())
branch_dir = charm_data["branch_dir"]
charm_data.update(get_changes(branch_dir, limit, since))
def get_changes(branch_dir, limit, since):
charm_data = {}
branch = Branch.open(branch_dir)
branch.lock_read()
try:
revisions = get_revisions(branch, limit, since)
charm_data["changes"] = changes = []
for r in revisions:
changes.append(_rev_info(r, branch))
if len(revisions) == 0:
last_change = None
first_change = None
else:
last_change = changes[0]
first = branch.repository.get_revision(branch.get_rev_id(1))
first_change = _rev_info(first, branch)
charm_data.update({
'last_change': last_change,
'first_change': first_change,
})
return charm_data
finally:
branch.unlock()
def get_revisions(branch, limit, since):
# We only want the last 10 changes, in descending order.
graph = branch.repository.get_graph()
cur_rev_id = branch.last_revision()
ancestry_iter = graph.iter_lefthand_ancestry(cur_rev_id)
revs = []
for num, revision_id in enumerate(ancestry_iter):
if revision_id == NULL_REVISION:
break
revision = branch.repository.get_revision(revision_id)
if num >= limit:
if since is None or revision.timestamp < since:
break
revs.append(revision)
return revs
def update_jenkins_data(db, charm, log):
if not charm['promulgated']:
return
charm.setdefault('tests', {})
charm.setdefault('test_results', {})
for p in JENKINS_PROVIDERS:
try:
result_id, status = store_provider_results(db, p, charm, log)
if result_id is None:
continue
charm['tests'][p] = status
charm['test_results'][p] = result_id
except:
log.exception("Unknown error while processing %s %s",
charm['branch_spec'], p)
def scan_artifacts(provider, charm, result):
artifacts = []
for artifact in result['artifacts']:
a_url = JENKINS_ARTIFACT_URL % (dict(
series=charm['series'],
provider=provider,
charm=charm['name'],
build=result['number'],
artifact=artifact['relativePath']))
# Load up the charm revision as a result property.
if artifact['displayPath'] == 'charm-revision':
charm_revision = urllib2.urlopen(a_url).read().strip()
if not charm_revision:
continue
revision_info = charm_revision.split(' ', 1)
result['revno'] = int(revision_info[0])
if len(revision_info) > 1:
result['revision-id'] = revision_info[1].rstrip('\n')
continue
# Mark the test result as graph runner enabled.
if "graph-tests" in artifact['displayPath']:
result['charmrunner'] = True
return artifacts
def store_provider_results(db, provider, charm, log):
charm_result_url = JENKINS_QA_URL % (
dict(series=charm['series'],
provider=provider,
charm=charm['name']))
log.debug("Loading %s from %s", charm['name'], charm_result_url)
response = requests.get(charm_result_url)
if response.status_code is not None and response.status_code != 200:
log.info(
"No test result for %s @ %s", charm['branch_spec'], provider)
return None, None
result = response.json()
# If we already have results no pointing in refetching.
result_id = "%s::%s-%s" % (
charm['branch_spec'], provider, result['number'])
db_result = db.jenkins.find_one({'_id': result_id})
if db_result is not None:
return result_id, db_result['result']
# Fetch test artifacts.
artifacts = scan_artifacts(provider, charm, result)
# Inject test metadata.
result['branch_spec'] = charm['branch_spec']
result['provider'] = provider
result['artifacts'] = artifacts
result['_id'] = result_id
db.jenkins.insert(result)
return (result_id, result['result'])
@contextlib.contextmanager
def get_proof_lib(new_path):
if new_path not in sys.path:
sys.path.append(new_path)
try:
import lib.proof as prooflib
yield prooflib
except ImportError:
yield None
finally:
if new_path in sys.path:
sys.path.remove(new_path)
def get_proofer(log, proof_path=None):
proofer = None
if not proof_path:
proof_path = CHARM_PROOF_PATH
# Use config.CHARM_PROOF_PATH for testing. Monkeypatching is scary.
if not os.path.isdir(proof_path):
err_msg = ("proof error before processing began: could not find "
"charm proof path.")
log.exception(err_msg)
log.exception("CHARM_PROOF_PATH: %s", proof_path)
with get_proof_lib(proof_path) as prooflib:
if not prooflib:
err_msg = ("proof error before processing began: could not "
"import charm proof lib.")
log.exception(err_msg)
log.exception(
"CHARM_PROOF_PATH: %s", proof_path)
else:
proofer = prooflib.run
return proofer
def update_proof_data(charm, log, _proofer=None):
proofer = _proofer
if proofer is None:
proofer = get_proofer(log)
if not proofer:
log.exception("proof aborted.")
raise Exception("No proofer")
if charm['branch_deleted']:
return
proof = {}
lint, exit_code = proofer(charm['branch_dir'])
for line in lint:
if not ':' in line:
continue
level, msg = line.split(':', 1)
if level == "W" and 'name' in msg:
continue
proof.setdefault(level.lower(), []).append(msg)
charm['proof'] = proof
def scan_charm(charm_data, db, fs, log):
# Note: charm_data is modified in-place. IndexIngestJob requires
# these modifications.
files = charm_data['files']
# Some files have bad characters in them since they are used as mongo
# keys. Use their escaped forms instead.
metadata_file = quote_key('metadata.yaml')
config_file = quote_key('config.yaml')
if metadata_file not in files:
log.info(
"Charm has no metadata: %s", charm_data["branch_spec"])
return
else:
cfile = CharmFileSet.get_by_id(
fs, files[metadata_file]['fileid'])
try:
metadata = quote_yaml(yaml.safe_load(cfile.read()))
except Exception, exc:
raise IngestError(
'Invalid charm metadata %s: %s' % (
charm_data['branch_spec'],
exc)
)
if config_file in files:
cfile = CharmFileSet.get_by_id(
fs, files[config_file]['fileid'])
config_raw = cfile.read()
try:
config_yaml = yaml.safe_load(config_raw)
if 'options' in config_yaml:
config_yaml['options'] = options_to_storage(
config_yaml['options'])
config = quote_yaml(config_yaml)
except Exception, exc:
raise IngestError(
'Invalid charm config yaml. %s: %s' % (
charm_data['branch_spec'],
exc)
)
metadata["config"] = config
metadata["config_raw"] = config_raw
if 'revision' in files:
cfile = CharmFileSet.get_by_id(
fs, files['revision']['fileid'])
rev_raw = cfile.read()
rev_id = int(rev_raw.strip())
metadata["revision"] = rev_id
elif not "revision" in metadata:
log.info("Invalid revision %s", charm_data["branch_spec"])
metadata["revision"] = 0
hooks = []
for filedata in files.values():
if filedata['subdir'] == 'hooks':
hooks.append(filedata['filename'])
hooks.sort()
metadata["hooks"] = hooks
# The charm name specified in the metadta may differ fromo the
# LP source package name and the name used by the main charm store.
# Using the name from the metadata can cause problems like described
# in bug 1202665.
if 'name' in metadata:
del metadata['name']
# Update the historic or incomplete charm_data with the new metadata.
# Stuff into the db.
charm_data.update(metadata)
complete_charm_data = process_charm(charm_data)
# Modify charm_data itself.
charm_data.clear()
charm_data.update(complete_charm_data)
def normalize_interfaces(interfaces):
# Transform the short defintion of relations into the
# long form. Quoted from
# https://juju.ubuntu.com/docs/charm.html#the-metadata-file :
#
# As a shortcut, if these properties are not defined, and
# instead a single string value is provided next to the
# relation name, the string is taken as the interface
# value, as seen in this example:
#
# requires:
# db: mysql
for relation_name, relation_data in interfaces.items():
if isinstance(relation_data, StringTypes):
interfaces[relation_name] = {'interface': relation_data}
def process_charm(base_charm):
# Enrich charm metadata for webapp.
charm = dict(base_charm)
# Charm url
if charm["promulgated"]:
charm["short_url"] = "/charms/%s/%s" % (
charm["series"], charm["name"])
else:
charm["short_url"] = "/~%s/%s/%s" % (charm["owner"],
charm["series"],
charm["name"])
# Charm label
if charm["promulgated"]:
charm["label"] = "%s/%s" % (charm["series"], charm["name"])
else:
charm["label"] = "~%s:%s/%s" % (charm["owner"],
charm["series"],
charm["name"])
# Flatten the interfaces provided
i_provides = []
provides = charm.get("provides")
if provides:
normalize_interfaces(provides)
for v in provides.values():
if not isinstance(v, dict):
continue
i = v.get("interface")
if not i:
continue
i_provides.append(i)
charm["i_provides"] = i_provides
# Flatten the interfaces required
i_requires = []
requires = charm.get("requires")
if requires:
normalize_interfaces(requires)
for v in requires.values():
i = v.get("interface")
if not i:
continue
i_requires.append(i)
charm["i_requires"] = i_requires
return charm
def addresses(charm):
"""Return an iterator of potential store addresses."""
if charm['promulgated']:
yield get_address(charm, short=True)
yield get_address(charm, short=False)
def update_download_count(store, charm):
count = store.count_downloads_in_days(charm, 30, date.today())
charm['downloads_in_past_30_days'] = count
count = store.get_download_counts(charm)
charm['downloads'] = count[0][0] if count else 0
count = store.count_downloads_in_days(charm, 7, date.today())
charm['downloads_in_past_7_days'] = count
count = store.count_downloads_in_days(charm, 182, date.today())
charm['downloads_in_past_half_year'] = count
def update_date_created(charm, log):
"""Use Launchpad to update the charm's date_created field.
Field will only be set if it is missing AND a branch with the correct
branch_spec exists in Launchpad.
"""
if 'date_created' in charm:
log.debug('Skipping %s which already has date_created',
charm['branch_spec'])
return
log.info('Retrieving date_created for %s', charm['branch_spec'])
info = get_branch_info(charm['branch_spec'])
if info is None:
log.warning('No branch for %s', charm['branch_spec'])
return
date_created = parse_date(info['date_created'])
charm['date_created'] = timestamp(date_created.replace(microsecond=0))
def update_from_store(charm, address, data, check_time, log):
if 'errors' in data or 'warnings' in data:
log.warning("store error on %s %s" % (address, data))
data["store_checked"] = check_time
charm['address'] = address
charm['store_data'] = data
charm['store_url'] = make_store_url(data['revision'], address)
|