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
|
# Copyright 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
from contextlib import contextmanager
import hashlib
import json
import logging
import os.path
import shutil
import subprocess
from textwrap import dedent
import bzrlib
from bzrlib.bzrdir import BzrDir
from httmock import (
HTTMock,
urlmatch,
)
from mock import patch
import yaml
from charmworld.charmstore import (
CharmStore,
)
from charmworld.jobs.config import CHARM_DIR
from charmworld.jobs.ingest import (
IngestError,
IngestJob,
run_job,
slurp_files,
update_branch,
update_charm,
update_hash,
UpdateCharmJob,
UpdateBundleJob,
update_date_created,
)
from charmworld.jobs.tests.test_bzr import bzr_isolation
from charmworld.models import (
CharmSource,
getfs,
)
from charmworld.testing import (
factory,
force_index_client,
MongoTestBase,
response404,
TestCase,
)
from charmworld.utils import (
quote_key,
)
class TestUpdateDateCreated(TestCase):
def test_update_date_created(self):
result = json.dumps(
{'date_created': '2012-03-06T17:59:55.818912+00:00'})
charm = {'branch_spec': 'steve'}
with HTTMock(lambda x, y: result):
update_date_created(charm, logging.getLogger('foo'))
self.assertEqual({
'date_created': '2012-03-06T17:59:55Z',
'branch_spec': 'steve',
}, charm)
def test_update_date_created_ignores_existing(self):
charm = {'date_created': None, 'branch_spec': 'steve'}
update_date_created(charm, logging.getLogger('foo'))
self.assertEqual({'date_created': None, 'branch_spec': 'steve'}, charm)
def test_update_date_created_no_branch(self):
with HTTMock(response404):
charm = {'branch_spec': 'steve'}
update_date_created(charm, logging.getLogger('foo'))
self.assertNotIn('date_created', charm)
@contextmanager
def charm_update_environment(real_charm_data, index_client):
"""Mock many things that are used when updating charms."""
def checkout_branch(charm_data, branch_dir, log):
wt = BzrDir.create_standalone_workingtree(branch_dir)
wt.bzrdir.root_transport.mkdir('hooks')
wt.bzrdir.root_transport.put_bytes('metadata.yaml', json.dumps({
'name': charm_data['name'],
'summary': real_charm_data['summary'],
}))
wt.add(['hooks', 'metadata.yaml'])
charm_data['store_data']['digest'] = wt.commit('commit 1')
checkout_patch = patch(
'charmworld.jobs.ingest.checkout_branch', checkout_branch)
@urlmatch(path='/stats/counter/charm-bundle:.*')
def mock_counts(url, request):
return json.dumps([[0]])
@urlmatch(netloc='api.launchpad.net')
def mock_date_created(url, request):
return json.dumps({'date_created': '2005-06-07T12:13:14.15+00:00'})
test_results = urlmatch(netloc='jenkins.qa.ubuntu.com')(response404)
httmock = HTTMock(mock_counts, test_results, mock_date_created)
with bzr_isolation() as cwd, checkout_patch:
root_dir = os.path.join(cwd, 'root_dir')
dir_patch = patch('charmworld.jobs.ingest.CHARM_DIR', root_dir)
with dir_patch, httmock, force_index_client(index_client):
yield
class TestUpdateCharmJob(MongoTestBase):
@staticmethod
def payload(charm_data):
return {
'series': charm_data['series'],
'owner': charm_data['owner'],
'name': charm_data['name'],
'bname': charm_data['bname'],
'branch_spec': charm_data['branch_spec'],
'branch_deleted': charm_data['branch_deleted'],
'promulgated': charm_data['promulgated'],
'store_data': charm_data['store_data'],
'store_url': charm_data['store_url'],
}
def test_run_indexes(self):
charm_data = factory.get_charm_json()
with charm_update_environment(charm_data, self.use_index_client()):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
self.assertIsNot(None, self.index_client.get(charm_data['_id']))
def test_run_updates_mongo(self):
charm_data = factory.get_charm_json()
with charm_update_environment(charm_data, self.use_index_client()):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
self.assertIsNot(None, self.db.charms.find_one(charm_data['_id']))
def test_run_includes_old_mongo_data_in_index(self):
charm_data = factory.get_charm_json()
charm_data['foo'] = 'bar'
self.db.charms.save(charm_data)
del charm_data['foo']
with charm_update_environment(charm_data, self.use_index_client()):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
indexed_charm = self.index_client.get(charm_data['_id'])
self.assertEqual('bar', indexed_charm.get('foo'))
def test_mongo_and_index_store_identical_charm(self):
charm_data = factory.get_charm_json()
charm_data['foo'] = 'bar'
self.db.charms.save(charm_data)
del charm_data['foo']
with charm_update_environment(charm_data, self.use_index_client()):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
indexed_charm = self.index_client.get(charm_data['_id'])
mongo_charm = self.db.charms.find_one(charm_data['_id'])
self.assertEqual(indexed_charm, mongo_charm)
def test_saves_early_error(self):
charm_data = factory.get_charm_json()
# Induce improbable error -- bname must be a string.
charm_data['bname'] = None
update_handler = self.get_handler('charm.update')
update_charm_handler = self.get_handler('charm.update_charm')
with patch('charmworld.jobs.ingest.update_from_store'):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
self.assertIsNot(
None, self.db.charms.find_one(charm_data['_id']))
logs = ''.join(r.getMessage() for r in update_handler.buffer)
update_charm_logs = ''.join(r.getMessage()
for r in update_charm_handler.buffer)
self.assertEqual('Saving %s' % charm_data['_id'], logs)
self.assertIn("'NoneType' object has no attribute 'startswith'",
update_charm_logs)
def test_updates_promulgated(self):
charm_data = factory.get_charm_json(promulgated=False)
self.use_index_client()
CharmSource.from_request(self).save(charm_data)
charm_data['promulgated'] = True
with charm_update_environment(charm_data, self.index_client):
run_job(UpdateCharmJob(), self.payload(charm_data), db=self.db)
self.assertTrue(
self.db.charms.find_one(charm_data['_id'])['promulgated'])
def test_setting_charm_id(self):
payload = factory.get_payload_json(owner='baz', series='bar',
name='foo')
factory.add_store_data(payload, revision=42)
self.assertNotIn('_id', payload)
payload['summary'] = 'foo'
with charm_update_environment(payload, self.use_index_client()):
run_job(UpdateCharmJob(), payload, db=self.db)
self.assertEqual('~baz/charms/bar/foo/trunk', payload['_id'])
class TestUpdateBranch(TestCase):
def setUp(self):
self.use_context(bzr_isolation())
def test_update_branch_passes_on_subprocess_errors_if_not_retrying(self):
def check_output(command, *args, **kws):
self.assertEqual(command[:2], ['/usr/bin/bzr', 'update'])
raise subprocess.CalledProcessError('foo', 'bar')
with patch('subprocess.check_output', check_output):
with self.assertRaises(subprocess.CalledProcessError):
update_branch(
'', {'branch_spec': ''}, '', logging.getLogger('foo'))
def test_update_branch_passes_retries(self):
# If the bzr update fails, the branch is deleted and checked out anew.
first_time = [True]
def check_output(command, *args, **kws):
if first_time:
del first_time[0]
self.assertEqual(command[:2], ['/usr/bin/bzr', 'update'])
raise subprocess.CalledProcessError('foo', 'bar')
else:
self.assertEqual(command[:2], ['/usr/bin/bzr', 'checkout'])
with patch('subprocess.check_output', check_output):
with patch('shutil.rmtree') as rmtree:
update_branch(
'', {'branch_spec': ''}, '', logging.getLogger('foo'),
retry=True)
self.assertTrue(rmtree.called)
@contextmanager
def bundle_update_environment(source_branch_dir=None):
def checkout_charm_mock(charm_data, branch_dir, log):
if source_branch_dir is None:
wt = BzrDir.create_standalone_workingtree(branch_dir)
wt.commit('commit message', rev_id=charm_data['commit'])
else:
shutil.copytree(source_branch_dir, branch_dir)
with patch(
'charmworld.jobs.ingest.checkout_branch',
side_effect=checkout_charm_mock
) as checkout_branch:
with bzr_isolation() as working_dir:
with patch('charmworld.jobs.ingest.UpdateBundleJob.store_bundles'):
try:
yield checkout_branch, working_dir
finally:
# Clean up despite exceptions raised by the context
# manager client.
shutil.rmtree(CHARM_DIR, ignore_errors=True)
class TestUpdateBundleJob(MongoTestBase):
def test_run_updates_mongo(self):
# Running a bundle job creates a bundle document in mongo.
NAME = 'our-source-package'
bundle_data = factory.get_payload_json(name=NAME)
with bundle_update_environment():
run_job(UpdateBundleJob(), bundle_data, db=self.db)
self.assertIsNotNone(self.db.baskets.find_one(bundle_data['_id']))
def test_run_creates_branch(self):
# The ingest job fetches the target branch.
NAME = 'our-source-package'
bundle_data = factory.get_payload_json(name=NAME)
with bundle_update_environment() as (checkout_branch, working_dir):
run_job(
UpdateBundleJob(working_dir=working_dir), bundle_data,
db=self.db)
self.assertTrue(checkout_branch.called)
def test_slurp_files_puts_files_in_gridfs(self):
with bundle_update_environment() as (checkout_branch, working_dir):
job = UpdateBundleJob()
job.setup(self.db)
with factory.bzr_branch() as (cwd, _, tree):
bytes = factory.random_string()
tree.bzrdir.root_transport.put_bytes('foo', bytes)
tree.add(['foo'])
tree.commit(message='add the file')
hashes = slurp_files(getfs(self.db, 'hashed-files'), tree)
expected_hash = hashlib.sha256(bytes).hexdigest()
self.assertEqual(hashes, {'foo': expected_hash})
fs = getfs(self.db, 'hashed-files')
self.assertEqual(fs.get(expected_hash).read(), bytes)
def test_dots_in_file_paths_do_not_break_things(self):
# Since mongodb doesn't like keys with dots in them and we want to
# store a mapping from file name (potentially with dots) to file hash,
# we need to quote the file patth.
job = UpdateBundleJob()
job.setup(self.db)
with patch.object(job, 'get_deployer_config'):
with bundle_update_environment():
with patch(
'charmworld.jobs.ingest.slurp_files',
side_effect=lambda *_: {'a.b': 'X'}) as slurp_files:
bundle_data = factory.get_payload_json()
job.run(bundle_data)
self.assertTrue(slurp_files.called)
def test_file_paths_with_dots_can_be_retrieved(self):
# Since we have to escape file paths for mongodb, it is important that
# we check that file paths containing dots can be retrieved.
job = UpdateBundleJob()
basket_data = {'file_hashes': {quote_key('bundles.yaml'): 'HASH'}}
class FauxFS:
@staticmethod
def get(hash):
self.assertEqual(hash, 'HASH')
self.get_called = True
return ''
job.get_deployer_config(FauxFS(), basket_data)
self.assertTrue(self.get_called)
def test_run_pulls_in_all_branch_files(self):
# The ingest job puts all files in the branch into the database.
NAME = 'our-source-package'
bundle_data = factory.get_payload_json(name=NAME)
with bundle_update_environment() as (checkout_branch, working_dir):
run_job(
UpdateBundleJob(working_dir=working_dir), bundle_data,
db=self.db)
self.assertTrue(checkout_branch.called)
def test_run_slurps(self):
# The run method calls slurp_files to actually read the files into the
# database.
job = UpdateBundleJob()
job.setup(self.db)
with patch.object(job, 'get_deployer_config'):
with bundle_update_environment():
with patch(
'charmworld.jobs.ingest.slurp_files',
side_effect=lambda *_: {}) as slurp_files:
bundle_data = factory.get_payload_json()
job.run(bundle_data)
self.assertTrue(slurp_files.called)
def test_bundle_knows_where_its_files_are(self):
# The mapping of bundle file paths to hashes (keys in gridfs) is
# stored in the bundle document.
job = UpdateBundleJob()
job.setup(self.db)
with patch.object(job, 'get_deployer_config'):
with bundle_update_environment():
def slurp_files_side_effect(*args):
return {'path1': 'hash1', 'path2': 'hash2'}
with patch(
'charmworld.jobs.ingest.slurp_files',
side_effect=slurp_files_side_effect):
bundle_data = factory.get_payload_json()
job.run(bundle_data)
self.assertEqual(
bundle_data['file_hashes'],
{'path1': 'hash1', 'path2': 'hash2'})
def test_bundle_ids_include_their_revno(self):
job = UpdateBundleJob()
job.setup(self.db)
bundle_data = factory.get_payload_json()
# We use multiple commits to show that the latest revno is used.
with bzr_isolation() as source_branch_dir:
wt = BzrDir.create_standalone_workingtree(source_branch_dir)
for x in range(7):
wt.commit('commit %d' % x)
wt.commit('commit message', rev_id=bundle_data['commit'])
with bundle_update_environment(source_branch_dir):
job.decorate_basket(bundle_data, None)
self.assertTrue(bundle_data['_id'].endswith('/8'))
def test_decorate_basket_stores_files(self):
job = UpdateBundleJob()
fs = getfs(self.db, collection='hashed-files')
bundle_data = factory.get_payload_json()
with bzr_isolation() as source_branch_dir:
wt = BzrDir.create_standalone_workingtree(source_branch_dir)
wt.bzrdir.root_transport.put_bytes(
'bundles.yaml', '{foo: {}}')
wt.add('bundles.yaml')
bundle_data['commit'] = wt.commit('commit message')
with bundle_update_environment(source_branch_dir):
job.decorate_basket(bundle_data, fs)
bundles_hash = bundle_data['file_hashes'].get('bundles%2Eyaml')
self.assertIsNot(None, bundles_hash)
self.assertEqual('{foo: {}}', fs.get(bundles_hash).read())
def test_decorate_bundles(self):
basket_contents = {'foo': {}}
UpdateBundleJob.decorate_bundles(basket_contents, '~bar/baz')
self.assertEqual({'foo': {'_id': '~bar/baz/foo'}}, basket_contents)
def test_missing_revisions_generate_errors(self):
job = UpdateBundleJob()
job.setup(self.db)
bundle_data = factory.get_payload_json()
# We use multiple commits to show that the latest revno is used.
with bzr_isolation() as source_branch_dir:
wt = BzrDir.create_standalone_workingtree(source_branch_dir)
base = wt.commit('commit message')
wt.commit('commit message', rev_id=bundle_data['commit'])
wt.pull(wt.branch, stop_revision=base, overwrite=True)
wt.merge_from_branch(wt.branch, to_revision=bundle_data['commit'])
wt.commit('do a merge which hides the second commit')
with bundle_update_environment(source_branch_dir):
with self.assertRaises(bzrlib.errors.NoSuchRevision):
job.decorate_basket(bundle_data, None)
def test_set_basket_info_includes_owner_if_promulgated(self):
payload = factory.get_payload_json(name='mysql', promulgated=True)
UpdateBundleJob.set_basket_info(payload, 5)
self.assertEqual('mysql/5', payload['name_revno'])
self.assertEqual('~charmers/mysql/5', payload['_id'])
def test_set_basket_info_includes_owner_if_not_promulgated(self):
payload = factory.get_payload_json(name='mysql', promulgated=False)
UpdateBundleJob.set_basket_info(payload, 5)
self.assertEqual('mysql/5', payload['name_revno'])
self.assertEqual('~charmers/mysql/5', payload['_id'])
def test_job_can_store_bundles_in_the_db(self):
basket_data = factory.get_payload_json(name='wordpress')
UpdateBundleJob.set_basket_info(basket_data, 5)
bundle_id = '%s/%s' % (basket_data['_id'], 'stage')
job = UpdateBundleJob()
job.setup(self.db)
DEPLOYER_CONFIG_HASH = '31337'
basket_data['file_hashes'] = {
'bundles.yaml': DEPLOYER_CONFIG_HASH,
}
fs = getfs(self.db)
deployer_config = dedent("""\
stage:
series: precise
services:
blog:
charm: cs:precise/wordpress
constraints: mem=2
options:
tuning: optimized
engine: apache
""")
fs.put(deployer_config, _id=DEPLOYER_CONFIG_HASH)
job.store_bundles(
yaml.safe_load(deployer_config),
basket_data['owner'], basket_data['name_revno'])
self.assertIsNotNone(self.db.bundles.find_one(bundle_id))
def test_job_run_stores_bundles_in_the_db(self):
basket_data = factory.get_payload_json(name='wordpress')
basket_data['name_revno'] = 'dummy'
job = UpdateBundleJob()
job.setup(self.db)
with patch.object(job, 'get_deployer_config'):
with patch.object(job, 'decorate_basket'):
with patch.object(job, 'store_bundles') as store_bundles:
job.run(basket_data)
self.assertTrue(store_bundles.called)
class TestUpdateCharm(MongoTestBase):
def test_update_charm_does_not_index(self):
charm_data = factory.get_charm_json()
with charm_update_environment(charm_data, self.use_index_client()):
update_charm(charm_data, self.db, CharmStore())
self.index_client.wait_for_startup()
self.assertIs(None, self.index_client.get(charm_data['_id']))
def test_update_charm_does_not_update_mongo(self):
charm_data = factory.get_charm_json()
with charm_update_environment(charm_data, self.use_index_client()):
update_charm(charm_data, self.db, CharmStore())
self.assertIs(None, self.db.charms.find_one(charm_data['_id']))
def test_forgets_past_error(self):
charm_data = factory.get_charm_json(promulgated=True)
charm_data['error'] = {'error_stage': 'foo', 'error': 'bar'}
with charm_update_environment(charm_data, self.use_index_client()):
update_charm(charm_data, self.db, CharmStore())
self.assertNotIn('error', charm_data)
def test_updates_download_info(self):
charm_data = factory.get_charm_json()
del charm_data['downloads']
class FakeCharmStore:
@staticmethod
def count_downloads_in_days(charm, days, end):
return 0
@staticmethod
def get_download_counts(charm, start=None, end=None):
return [[5]]
with charm_update_environment(charm_data, self.use_index_client()):
update_charm(charm_data, self.db, FakeCharmStore)
self.assertEqual(5, charm_data['downloads'])
class TestJob(IngestJob):
name = 'test'
def __init__(self, exc=None):
super(TestJob, self).setup()
self.setup_called = False
self.run_called = False
self.exc = exc
self.charm_data = None
def setup(self, db=None):
self.setup_called = True
self.db = db
def run(self, charm_data):
self.charm_data = charm_data
if self.exc is not None:
raise self.exc('test error')
self.run_called = True
class TestRunJob(TestCase):
def test_run_job_defaults(self):
job = TestJob()
result = run_job(job, charm_data='foo')
self.assertTrue(result)
self.assertTrue(job.setup_called)
self.assertTrue(job.run_called)
self.assertEqual('foo', job.charm_data)
self.assertIs(None, job.db)
def test_run_job_no_setup(self):
job = TestJob()
run_job(job, 'foo', needs_setup=False)
self.assertFalse(job.setup_called)
def test_run_job_db_specified(self):
job = TestJob()
run_job(job, 'foo', db='db')
self.assertEqual('db', job.db)
job = TestJob()
run_job(job, 'foo', needs_setup=False, db='db')
self.assertIs(None, getattr(job, 'db', None))
def test_run_job_general_exception(self):
handler = self.get_handler('charm.test')
job = TestJob(ValueError)
charm_data = {'foo': 'bar'}
result = run_job(job, charm_data)
self.assertFalse(result)
expected_error = {
'error': 'test error',
'error_stage': 'test',
}
self.assertEqual(expected_error, charm_data['error'])
log_messages = [record.getMessage() for record in handler.buffer]
expected = "test error on {'foo': 'bar'}: test error\nTraceback"
self.assertEqual(1, len(log_messages))
self.assertTrue(log_messages[0].startswith(expected))
log_level = handler.buffer[0].levelname
self.assertEqual('ERROR', log_level)
def test_run_job_IngestError(self):
handler = self.get_handler('charm.test')
job = TestJob(IngestError)
charm_data = {'foo': 'bar'}
result = run_job(job, charm_data)
self.assertFalse(result)
expected_error = {
'error': 'test error',
'error_stage': 'test',
}
self.assertEqual(expected_error, charm_data['error'])
log_messages = [record.getMessage() for record in handler.buffer]
expected = ["test error on {'foo': 'bar'}: test error"]
self.assertEqual(expected, log_messages)
log_level = handler.buffer[0].levelname
self.assertEqual('INFO', log_level)
class TestUpdateHash(TestCase):
def test_update_hash(self):
# update_hash() adds a hash to a charm.
charm_data = factory.get_charm_json()
self.assertFalse('hash' in charm_data)
update_hash(charm_data)
old_hash = charm_data['hash']
# Changing any value of the charm changes the hash.
charm_data['name'] = charm_data['name'] + 'changed'
update_hash(charm_data)
self.assertNotEqual(old_hash, charm_data['hash'])
def test_hash_value_not_included_in_calculation(self):
# The hash value itself is not included in a new calculation of the
# hash.
charm_data = factory.get_charm_json()
update_hash(charm_data)
old_hash = charm_data['hash']
charm_data['hash'] = 'some other value'
update_hash(charm_data)
self.assertEqual(old_hash, charm_data['hash'])
|