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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
|
# Copyright 2012, 2013 Marco Ceppi, Canonical Ltd. This software is
# licensed under the GNU Affero General Public License version 3 (see
# the file LICENSE).
__metaclass__ = type
from calendar import timegm
import hashlib
import itertools
import logging
from mimetypes import guess_type
import os
from os.path import (
dirname,
join,
normpath,
split,
)
import random
import re
from xml.etree import ElementTree
from bzrlib.branch import Branch
from bzrlib.errors import NoSuchRevision
from deployer import get_flattened_deployment
import gridfs
import magic
import pymongo
from charmworld.utils import (
configure_logging,
get_ini,
read_locked,
quote_key,
)
from charmworld.search import (
CHARM,
ElasticSearchClient,
)
from charmworld.jobs.config import settings
OBSOLETE_SERIES = set(['oneiric'])
def getconnection(settings, fsync=False, safe=False):
"""Initialize the PyMongo database Connection object.
:param settings: dict of application settings including the mongo.X info.
"""
url_or_host = os.environ.get('TEST_MONGODB', settings.get('mongo.url'))
if not url_or_host:
url_or_host = settings.get('mongo.host')
port = int(settings.get('mongo.port'))
else:
port = None
connection = pymongo.Connection(
url_or_host, port,
fsync=fsync,
safe=safe,
)
return connection
def getdb(connection, database_name):
"""Helper to access the db instance.
This is needed because the test runner nose loads views which tried to
import db directly, before the main() is run and initialize_db is run with
the connection information.
:param connection: pymongo connection object.
:param database_name: mongo db name to connect to.
"""
return getattr(connection, database_name)
def getfs(database, collection='fs'):
"""Helper to get the gridfs handle used to store files."""
return gridfs.GridFS(database, collection)
def parse_sso_fields(payload):
"""Process the data form a sso request to a normal clean dict."""
user_sso_data = set([
'openid.sreg.nickname',
'openid.sreg.fullname',
'openid.sreg.email',
'openid.sreg.timezone',
])
common = user_sso_data.intersection(payload)
# We're using the last bit of the key in our User object.
user_data = dict((key.split('.')[2], payload[key]) for key in common)
groups = []
if payload['openid.lp.is_member'] != '':
groups = payload['openid.lp.is_member'].split(',')
user_data['groups'] = groups
return user_data
class UserMgr:
"""Handle non-instance user actions."""
@staticmethod
def auth_principalfinder(userid, request):
"""Pyramid wants to know what principals are associated with a user.
This is a helper provided for the RequestWithUser factory.
"""
user = request.user
if user is None:
return None
group_principals = ['group %s' % group for group in user.groups]
return ['user %s' % user.userid] + group_principals
@staticmethod
def find_one(db, userid):
found = db.users.find_one({'userid': userid})
if not found:
return None
else:
# Make sure we return a instantiated object vs the raw dictionary
# from mongo.
userid = found['userid']
del(found['userid'])
return User(userid, **found)
@staticmethod
def from_sso(payload):
"""Generate a User object instance from the SSO payload.
We take the SSO dict and turn it into something that a User object,
without being SSO aware, can easily handle and process.
"""
user_data = parse_sso_fields(payload)
user_id = payload['openid.claimed_id']
return User(user_id, **user_data)
class User:
"""A user in our system."""
# Attributes are defined as a list so we can easily create a
# dict(someuser) helper to dump to mongodb.
attributes = [
'_id',
'userid',
'nickname',
'fullname',
'email',
'groups',
'timezone',
]
def __init__(self, userid, **kwargs):
self.userid = userid
# Set some sane defaults since this depends on the users providing us
# with the data.
self.nickname = kwargs.get('nickname', 'Not Provided')
self.fullname = kwargs.get('fullname', 'Not Provided')
self.email = kwargs.get('email', None)
self.groups = kwargs['groups']
self.timezone = kwargs.get('timezone', 'GMT')
# We need to worry about if this is a mongodb record or just a new
# user object. A new object has no mongo id.
if '_id' in kwargs:
self._id = kwargs['_id']
else:
self._id = None
def __iter__(self):
"""Allow the User to be dumped to a dict for mongo."""
for key in self.attributes:
yield(key, getattr(self, key))
def in_group(self, group):
return True if group in self.groups else False
def save(self, db):
"""Actual storing of the instance into mongodb."""
mongo_data = dict(self)
if not self._id:
db.users.save(mongo_data)
else:
self._id = db.users.insert(mongo_data)
def update_from_sso(self, payload):
"""Update the stored user data from a fresh sso payload dump."""
user_data = parse_sso_fields(payload)
for key, val in user_data.items():
setattr(self, key, val)
def construct_charm_id(charm_data, use_revision=True):
elements = [charm_data['owner'], charm_data['series'], charm_data['name']]
if use_revision:
elements.append('%d' % charm_data['store_data']['revision'])
return '~' + '/'.join(elements)
class FeaturedSource:
"""Charms and Bundles can be featured; that state is represented here."""
def __init__(self, collection):
# The collection that stores the featured state.
self.collection = collection
@classmethod
def from_db(cls, db):
"""Create a source of charm feature data from a database."""
return cls(db.featured)
@staticmethod
def _make_query(item_data, doctype):
"""Create a query that finds a featured item."""
result = {
'name': item_data['name'],
'owner': item_data['owner'],
}
if doctype != 'bundle':
# Bundles do not have a series.
result['series'] = item_data['series']
return result
@classmethod
def _make_document(cls, item_data, doctype):
"""Create a document that describes a featured item."""
result = cls._make_query(item_data, doctype)
result['doctype'] = doctype
return result
def set_featured(self, item_data, doctype):
"""Add an item from the featured collection."""
featured_document = self._make_document(item_data, doctype)
self.collection.update(
featured_document, featured_document, upsert=True)
def clear_featured(self, item_data, doctype):
"""Remove an item from the featured collection."""
self.collection.remove(self._make_document(item_data, doctype))
def is_featured(self, item_data, doctype):
return bool(self.collection.find_one(
self._make_document(item_data, doctype)))
def _make_featured_query(self, doctype):
"""Construct a query that will search a collection for featured items.
"""
ors = []
for featured in self.collection.find({'doctype': doctype}):
ors.append(self._make_query(featured, doctype))
# If there are no featured items, then there can be no query to find
# them.
if not ors:
return None
return {'$or': ors}
def get_featured(self, collection, doctype):
# TODO Add support for fetching featured bundles when bundles become
# featurable.
assert doctype == 'charm', 'only charms can be featured at the moment'
query = self._make_featured_query(doctype)
# There is no query, so there are no featured items.
if query is None:
return []
return [
dict(doctype=CHARM, data=featured)
for featured in _find_charms(collection, query)]
class Charm:
"""A model to access a charm representation.
A charm representation is constructed from several processes which
add keys and values to the charm dict. This model represents the
the properties that all charms will possess when they are processed
without error.
"""
_COMMON_REPRESENTATION = {
# Provided by Lp charms queue.
'address': '',
'branch_spec': '',
'bzr_branch': '',
'branch_deleted': False,
'bname': '',
'commit': '',
'distro_series': [],
'name': '',
'owner': '',
'promulgated': False,
'series': '',
# Provided by the update charm job.
'date_created': None,
'error': '',
'_id': '',
# Provided from the bazaar job.
'branch_dir': '',
'files': {},
# Provided by the charm store job.
'downloads': 0,
'downloads_in_past_7_days': 0,
'downloads_in_past_30_days': 0,
'downloads_in_past_half_year': 0,
'store_data': {},
'store_url': '',
# Provided by the proof job.
'proof': {},
# Provided by the Jenkins job.
'test_results': {},
'tests': {},
# Provided by the changelog job.
'changes': [],
'first_change': None,
'last_change': None,
# Provided by the scan ingest job.
'categories': [],
'config': {'options': {}},
'config_raw': '',
'description': '',
'hooks': [],
'i_provides': [],
'i_requires': [],
'label': '',
'maintainer': '',
'provides': {},
'requires': {},
'revision': 0,
'short_url': '',
'subordinate': False,
'summary': '',
# Provided by update_hash()
'hash': None,
}
OFFICIAL_CATEGORIES = [
'applications',
'app-servers',
'cache-proxy',
'databases',
'file-servers',
'misc',
]
def __init__(self, charm_data):
"""Init the charm from a charm representation.
:param charm_data: A dict that represents the properties of a charm.
"""
self._raw_representation = charm_data
self._representation = dict(self._COMMON_REPRESENTATION)
self._representation.update(charm_data)
def __eq__(self, other):
if (isinstance(other, self.__class__)
and self.owner == other.owner
and self.series == other.series
and self.name == other.name):
# The store thinks these two charms are the same.
return True
return False
@property
def address(self):
"""The charm's cs: URL without a charm revision ID."""
return self._representation['address']
@property
def branch_spec(self):
"""The location of the charm's branch.
This is based on the Launchpad URI. It is used to locate the branch
Locally as well as on Lp. For example, ~owner/charms/series/name/trunk.
"""
return self._representation['branch_spec']
@property
def bzr_branch(self):
"""The Lp location of the charm's branch."""
return "lp:%s" % self.branch_spec
@property
def branch_deleted(self):
"""True if the Launchpad branch of this charm is deleted, else False.
"""
return self._representation['branch_deleted']
@property
def owner(self):
"""The owner of the charm's branch.'
The branch owner is not the maintainer from the charm metadata. The
branch owner is the person who published the charm.
"""
return self._representation['owner']
@property
def series(self):
"""The series the charm is intended to deploy on.
The series corresponds to the charms series in Launchpad, which mirrors
the Ubuntu series names in Launchpad.
"""
return self._representation['series']
@property
def name(self):
"""The charm name.
The name corresponds to the charms distribution source package in
Launchpad. For example, 'apache2' is the name cs:precise/apache2-33.
"""
return self._representation['name']
@property
def bname(self):
"""The charm's branch name.
Only branches named trunk are ingested from Launchpad.
"""
return self._representation['bname']
@property
def commit(self):
"""The revid of the charm branch's last commit.
The string can be empty if the branch is not found or it is empty.
"""
return self._representation['commit']
@property
def distro_series(self):
"""The official series the branch is linked to.
A branch linked to a series package is synonymous with
promulgated to a series charm after review.
"""
return self._representation['distro_series']
@property
def promulgated(self):
"""Is the charm promulgated?
Is the charm reviewed and recommended to be the default charm
for a series? The charm's URI will not include the owner so
that it can be deployed by specifying just the charm's series
and name.
"""
return self._representation['promulgated']
@property
def _id(self):
"""The _id used to find the charm in the database.
The value comes from the branch_spec. The database _id for a charm
looks like ~owner/series/name/store-revision
"""
return self._representation['_id']
@property
def date_created(self):
"""The ISO timestamp the charm was created.
This value is created from the date the branch was created, which
can disagree with the intent to show the age of the charm. For example,
when the source branch for a charm is changed, the date_created value
will change to the value from the new branch. The value can be an
empty string if the branch can not be found.
"""
return self._representation['date_created']
@property
def error(self):
"""The error seen during ingest, or an empty string when successful."""
return self._representation['error']
@property
def branch_dir(self):
"""The path to the charm's branch directory in the local repository.
The path takes the form of /var/charms/<series>/<owner>/<name>/<bname>.
"""
return self._representation['branch_dir']
@property
def files(self):
"""The dict `CharmFile` dicts representing the files in the charm."""
return self._representation['files']
@property
def store_url(self):
"""The charm's deployment URL, including the Charm revision ID."""
return self._representation['store_url']
@property
def store_revision(self):
"""The charm's revision in the store."""
revision = self.store_data.get("revision")
if revision is None:
revision = 1
return revision
@property
def store_data(self):
"""The charm data provided by the store.
A dict of information including address, store_checked, digest,
revision, and sha256. The error key may replace the digest, revision,
and sha256 keys if the store found errors. The dict will be empty
if there were ingest errors"""
return self._representation['store_data']
@property
def downloads(self):
"""The number of times the charm was downloaded.
The number comes from the store. It does not equate to deploys."""
return self._representation['downloads']
@property
def downloads_in_past_7_days(self):
"""The number of times the charm was downloaded in the past 7 days.
The number comes from the store. It does not equate to deploys."""
return self._representation['downloads_in_past_7_days']
@property
def downloads_in_past_30_days(self):
"""The number of times the charm was downloaded in the past 30 days.
The number comes from the store. It does not equate to deploys."""
return self._representation['downloads_in_past_30_days']
@property
def downloads_in_past_half_year(self):
"""The number of times the charm was downloaded in the past half year.
The number comes from the store. It does not equate to deploys."""
return self._representation['downloads_in_past_half_year']
@property
def proof(self):
"""The dict charm's proof warnings and errors."""
return self._representation['proof']
@property
def tests(self):
"""The dict charm's status of tested providers."""
return self._representation['tests']
@property
def test_results(self):
"""The dict charm's test results for each provider."""
return self._representation['test_results']
@property
def changes(self):
"""The list of revision info dicts from the charm's branch."""
return self._representation['changes']
def _get_change(self, name):
# Some view functions assume that last_change and first_change
# always exist, but this is not true for empty branches. Return
# some default data in this case.
change = self._representation[name]
if change is None:
return {
'authors': [],
'revno': 0,
'committer': '',
'created': None,
'message': '',
}
return change
@property
def first_change(self):
"""The revision dict of the first change to the charm's branch."""
return self._get_change('first_change')
@property
def last_change(self):
"""The revision dict of the last change to the charm's branch."""
return self._get_change('last_change')
@property
def revision(self):
"""The charm revision number.
The charm revision comes from the revision file in the charm's branch.
It is a manually incremented version number that is independent of
the charm's branch revisions.
"""
return self._representation['revision']
@property
def summary(self):
"""The charms summary.
The summary comes from the charm's metadata.
"""
return self._representation['summary']
@property
def description(self):
"""The charms description.
The description comes from the charm's metadata.
"""
return self._representation['description']
@property
def categories(self):
"""The list of categories the charm relates to.
The categories come from the charm's metadata.
"""
return [
category for category in self._representation['categories']
if category in self.OFFICIAL_CATEGORIES
]
@property
def maintainer(self):
"""The maintainer of this charm.
The maintainer is a string or a list of strings in the RFC2822 format.
"""
return self._representation['maintainer']
@property
def subordinate(self):
"""Is this charm a subordinate of another charm?"""
return self._representation['subordinate']
@property
def provides(self):
"""The dict of interfaces that the charm provides.
The provides interfaces comes from the charm's metadata.
"""
return self._representation['provides']
@property
def i_provides(self):
"""The list of interfaces that the charm provides.
The list is a flattened representation of the provides property.
"""
return self._representation['i_provides']
@property
def requires(self):
"""The dict of interfaces that the charm requires.
The requires interfaces comes from the charm's metadata.
"""
return self._representation['requires']
@property
def i_requires(self):
"""The list of interfaces that the charm requires.
The list is a flattened representation of the requires property.
"""
return self._representation['i_requires']
@property
def config(self):
"""The dict of the charm's configuration options.
The dict is parsed from the config_raw property's YAML.
"""
config = self._representation['config']
if config is not None and 'options' in config:
config = dict(config)
config['options'] = storage_to_options(config['options'])
return config
@property
def config_raw(self):
"""The charm's configuration YAML.
The unparsed content of the charm's config.yaml file.
"""
return self._representation['config_raw']
@property
def options(self):
"""The charm's configuration options."""
config = self.config
if config is not None and 'options' in config:
return config['options']
else:
return {}
@property
def hooks(self):
"""The list of life cycle and relation hooks the charm supports.
The list is created from the filenames found in the hooks directory.
"""
return self._representation['hooks']
@property
def label(self):
"""The charm name qualified by series and owner.
XXX sinzui 2013-06-04 bug=1118351:
Nb. This property overlaps with branch_spec and short_url.
It is the cause of ambiguous paths that users misconstrue to
be cs: urls. In general, users believe cs:urls to be a proper
label.
"""
return self._representation['label']
@property
def short_url(self):
"""The short URL the path to the charm within charmworld's routing.
The short_url property is based on the branch_spec. It is either
~owner/series/name or charms/series/name for promulgated charms.
"""
return self._representation['short_url']
def changes_since(self, date):
"""The changes that have been introduced since a given datetime."""
date = timegm(date.timetuple())
return [change for change in self.changes if change['created'] >= date]
@property
def hash(self):
"""A sum over the charm's data."""
return self._representation['hash']
class QADataSource:
def __init__(self, questions, answers):
self.questions = questions
self.answers = answers
@classmethod
def from_db(cls, db):
return cls(db.qa, db.charm_qa_answers)
def load_question_set(self):
"""Load the qa questions we want to have data about."""
stored_questions = self.questions.find()
# We index them for easy fetching of each categories data later.
return dict([(q['name'], q) for q in stored_questions])
def save_qa_data(self, charm, qa_data):
charm_id = construct_charm_id(charm._representation)
document = {
'_id': charm_id,
'owner': charm.owner,
'series': charm.series,
'name': charm.name,
'revision': charm.store_data['revision'],
'answers': qa_data,
}
self.answers.save(document)
def get_qa_data(self, charm):
"""Return the QA data that appplies to this charm.
The newest QA that is not newer than this charm is considered to
apply. Basically, this assumes no regressions. "newer" is determined
by the store revision.
"""
documents = self.answers.find({
'name': charm.name,
'series': charm.series,
'owner': charm.owner,
'revision': {'$lte': charm.store_data['revision']},
}).sort('revision', pymongo.DESCENDING).limit(1)
if documents.count() == 0:
answers = None
else:
answers = documents[0]['answers']
return QAData(self, answers)
class QAData:
"""Build a usable object out of the QA questions and instance data."""
def __init__(self, qa_data_source, charm_data=None):
self.qa_categories = qa_data_source.load_question_set()
self.charm_data = charm_data
@property
def categories(self):
return sorted(self.qa_categories)
@property
def score(self):
"""Calculate the score for whole qa set across categories."""
# If we have no qa data then we need to respond with not available
if not self.charm_data:
return None
score = 0
for category in self.categories:
category_score = self.category_score(category)
if category_score is not None:
score = score + category_score
return score
def category_score(self, category):
"""Given a category retrieve the scores for it."""
score = 0
if self.charm_data is None or category not in self.charm_data:
return None
category_questions = self.qa_categories[category]['questions']
charm_category_scores = self.charm_data[category]
for qnum, question in enumerate(category_questions):
score_key = "{0}_{1}".format(category, qnum)
q_score = charm_category_scores.get(score_key, 0)
# The score could be '' if it's unknown vs yes/no
if q_score:
score = score + int(q_score)
return score
def category_max_score(self, category):
"""How many possible points does the category have?"""
return len(self.qa_categories[category]['questions'])
def filtered_scores(self):
"""Return only scores that match the categories."""
if self.charm_data is None:
return None
score_categories = {}
for category in self.qa_categories:
if category not in self.charm_data:
continue
score_categories[category] = {}
for question in self.qa_categories[category]['questions']:
qid = question['id']
score = self.charm_data[category].get(qid)
if score is not None:
score_categories[category][qid] = score
return score_categories
class CharmFileSet:
"""Handle Charm file storage and access.
Charm key - series/owner/name/bname [branch name: trunk]
"""
store_files = [
'^config.yaml$',
'^metadata.yaml$',
'^readme.*$',
'^revision$',
'^icon.svg$',
]
store_directories = [
'hooks/',
]
@classmethod
def make_charm_file(cls, fs, charm_data, file_path, filename):
charmid = cls.gen_charmid(charm_data)
fileid = cls.gen_fileid(charm_data, file_path)
content_type = guess_type(filename)[0]
return CharmFile(
fs,
fileid,
charmid,
filename=filename,
contentType=content_type,
)
@classmethod
def save_file(cls, fs, logger, charm_data, file_path, file_id, tree):
"""Do the actual storage of the file contents.
:param fs: The mongo fs connection to use.
:param logger: A logger
:param charm_data: The charm's representation in charmworld
:param file_info: The file's data as returned by tree.list_files().
:tree: The working tree of the branch.
"""
plain_file_name = split(file_path)[1]
charm_file = cls.make_charm_file(
fs, charm_data, file_path, plain_file_name)
file_content = tree.get_file_text(file_id)
if file_path == 'icon.svg':
if magic.from_buffer(file_content, mime=True) != 'image/svg+xml':
logger.warn("File is not an SVG: %s" % file_path)
return
# Check if the icon has viewBox set.
root = ElementTree.fromstring(file_content)
if root.get('viewBox') is None:
width = root.get('width')
height = root.get('height')
if width is None or height is None:
logger.warn("SVG is malformed: "
+ "width or height attributes not set")
return
if int(width) <= 0 or int(height) <= 0:
logger.warn("SVG is malformed: "
+ "width or height must be greater than 0")
return
# If we have reasonable values for width and height, generate
# a viewBox attribute spanning the entire image. This will
# allow for it to be scaled when embedded in a webpage or
# another SVG.
logger.info("Generating a viewBox attribute for icon.svg")
root.attrib['viewBox'] = "0 0 {0} {1}".format(width, height)
file_content = ElementTree.tostring(root, encoding='UTF-8')
charm_file.save(file_content)
return charm_file
@classmethod
def gen_fileid(cls, charm_data, filename):
"""Generate our own mongo _id for the files.
In keeping with the bzr structure files are stored:
series-owner-name-bname-filename
"""
return quote_key("/".join([
cls.gen_charmid(charm_data),
filename
]))
@staticmethod
def gen_charmid(charm_data):
"""Generate the charm id to aid in searching."""
return "/".join([
charm_data['owner'],
charm_data['series'],
charm_data['name'],
charm_data['bname'],
])
@staticmethod
def get_by_id(fs, fileid):
"""Fetch the contents of the file
:param fileid: The stored _id of the file.
"""
if '.' in fileid:
fileid = quote_key(fileid)
found = fs.get(fileid)
cf = CharmFile(fs, fileid, found.charmid, instance=found)
return cf
@classmethod
def get_tree(cls, charm_data, charm_bzr_path, logger):
bzr_revision = charm_data['store_data']['digest']
branch = Branch.open(charm_bzr_path)
try:
return branch.repository.revision_tree(bzr_revision)
except NoSuchRevision:
logger.warn('Revision %s not found' % bzr_revision)
return None
@classmethod
def find_files(cls, tree, logger):
"""Yield file_path, file_id of relevant charm files.
Irrelevant files and directories are ignored. Symlinks outside
of the charm are ignored.
"""
for file_path, entry in tree.iter_entries_by_dir():
if entry.kind == 'directory':
continue
found = False
for pattern in cls.store_files:
if re.match(pattern, file_path, flags=re.I):
found = True
break
if not found:
for directory in cls.store_directories:
if file_path.startswith(directory):
found = True
break
if not found:
continue
if entry.kind == 'symlink':
target = tree.get_symlink_target(entry.file_id)
if target.startswith('/'):
logger.warn(
"Invalid file path: symlink %s points to the absolute "
"path %s." % (
file_path, target))
continue
directory = dirname(file_path)
resolved = normpath(join(directory, target))
if resolved.startswith('../'):
logger.warn(
"Invalid file path: Path %s points to %s, which is "
"not inside the charm's root directory" % (
file_path, resolved))
continue
file_id = tree.path2id(resolved)
if file_id is None:
logger.warn(
"File does not exist: %s (resolving to %s)." % (
file_path, resolved))
continue
else:
file_id = entry.file_id
yield file_path, file_id
@classmethod
def save_files(cls, fs, charm_data, charm_bzr_path, logger):
"""Given a bzr branch, load the files we care about."""
tree = cls.get_tree(charm_data, charm_bzr_path, logger)
if tree is None:
return []
with read_locked(tree):
stored = []
for file_path, file_id in cls.find_files(tree, logger):
charm_file = cls.save_file(
fs,
logger,
charm_data,
file_path,
file_id,
tree)
if charm_file is not None:
stored.append(charm_file)
return stored
@classmethod
def save_revision_files(cls, fs, charm_data, charm_bzr_path, logger):
"""Store relevant files from a charm revision"""
tree = cls.get_tree(charm_data, charm_bzr_path, logger)
if tree is None:
charm_data['files'] = {}
return
with read_locked(tree):
charm_data['files'] = slurp_files(
fs, tree, cls.find_files(tree, logger))
class CharmFile:
"""Representation of the GridFS stored document.
Wraps a PyMongo GridOut object instance.
"""
# Attributes are defined as a list so we can easily create a
# dict(charmfile) helper to dump to mongodb.
attributes = [
'fileid',
'charmid',
'contentType',
'subdir',
'filename',
'length',
'md5',
]
def __iter__(self):
"""Allow the Object to be dumped to a dict for mongo."""
for key in self.attributes:
if hasattr(self, key):
yield(key, getattr(self, key))
else:
yield(key, getattr(self._gridout, key))
@property
def subdir(self):
"""From a file id drop the file and return a charmid"""
filename = self.fileid.replace(quote_key(self.charmid), '').lstrip('/')
# If there's no subdir in the filename, there's no subdir to return.
return dirname(filename)
@property
def fileid(self):
"""fileid is more clear in code, but we're mapping this to mongo _id
fileid cannot have . characters; it's used as a key in mongo.
"""
if '.' in self._id:
return quote_key(self._id)
else:
return self._id
@property
def filename(self):
"""The filename is in the fileid so auto pull it out."""
if self._filename:
return self._filename
elif self._gridout:
return self._gridout.filename
else:
return self._id.split('/')[-1]
@property
def md5(self):
if self._gridout is None:
return None
return self._gridout.md5
# value to use as default to distinguish between None/null and unset.
undefined = object()
def __init__(self, fs, fileid, charmid, filename=None,
instance=None, metadata=None, contentType=undefined):
"""Get a file object started.
:param fs: the gridfs client to use.
:param fileid: The full mongo fileid to use for this file.
:param charmid: The path of the charm identification through branch
name.
:param filename: Override the name of the file from being determined
by the fileid.
:param instance: The GridOut instance to be associated with the file.
:param metadata: dict of extra data to store with the file in GridFS.
"""
self.fs = fs
self._id = fileid
self.charmid = charmid
self._filename = None
if contentType is not self.undefined:
self.contentType = contentType
elif instance is not None:
self.contentType = getattr(instance, 'contentType', None)
else:
self.contentType = None
if instance:
self._gridout = instance
# The filename might have been written out previously.
self._filename = instance.filename
else:
self._gridout = None
if filename:
self._filename = filename
if metadata:
self.metadata = metadata
else:
self.metadata = {}
def read(self):
"""Provide a read interface for the file."""
if not self._gridout:
self._gridout = self.fs.get(self.fileid)
return self._gridout.read()
def save(self, contents, data=None):
"""Store the contents of the file.
:param contents: String/readable value of file content.
:param data: dict of metadata to override defaults. See GridOut
"""
if data:
self.metadata.update(data)
# Delete any existing charm file with this id, including orphaned
# chunks.
self.fs.delete(self.fileid)
self.metadata['_id'] = self.fileid
self.metadata['charmid'] = self.charmid
self.fs.put(
contents,
filename=self.filename,
contentType=self.contentType,
**self.metadata
)
# We then have to pull the file we just saved back out so that we can
# load the instance data into our object.
self._gridout = self.fs.get(self.fileid)
return self.fileid
class CharmSource:
def __init__(self, db, index_client, collection=None):
if collection is None:
collection = db.charms
self.collection = collection
self.index_client = index_client
@classmethod
def from_settings(cls, settings):
db = getdb(getconnection(settings), settings['mongo.database'])
index_client = ElasticSearchClient.from_settings(settings)
return cls(db, index_client)
@classmethod
def from_request(cls, request):
return cls(request.db, request.index_client)
def sync_index(self):
for charm in _find_charms(self.collection):
yield charm['_id']
self.index_client.index_charm(charm)
def save(self, charm):
self.collection.save(charm)
try:
self.index_client.index_charm(charm)
except:
self.index_client.delete_charm(charm)
raise
def get_store_charms(self):
return self.collection.find({'store_url': {'$exists': True}})
@staticmethod
def exclude_obsolete(query):
return {'$and': [query, {'series': {'$nin': list(OBSOLETE_SERIES)}}]}
def find_mia_charms(self):
query = self.exclude_obsolete(
{"store_data.errors": {"$exists": True}})
return (Charm(data) for data in self.collection.find(query))
def find_proof_error_charms(self, sub_only):
query = {"proof.e": {"$exists": True}, "promulgated": True}
if sub_only:
query['subordinate'] = True
query = self.exclude_obsolete(query)
sort = [("series", pymongo.DESCENDING), ("name", pymongo.ASCENDING)]
return (Charm(data) for data in self.collection.find(query, sort=sort))
def _get_all(self, charm_id):
""""Return all stored values for a given charm."""
yield self.collection.find_one({'_id': charm_id})
yield self.index_client.get(charm_id)
def create_collection(self):
self.collection.database.create_collection(self.collection.name)
def get_basket_info(revno, **data):
owner_segment = '~%s' % data['owner']
name_revno = "%s/%d" % (data['name'], revno)
return {
'name_revno': name_revno,
'_id': '%s/%s' % (owner_segment, name_revno),
}
class Bundle:
"""A model to represent bundles of charms."""
_COMMON_REPRESENTATION = {
'owner': '',
'basket_name': None,
'basket_revision': None,
'name': '',
'title': '',
'description': '',
'data': dict(),
'promulgated': False,
'branch_deleted': False,
}
def __init__(self, data):
assert 'inherits' not in data, (
'inheriting from other bundles is not supported, the bundle '
'must be preprocessed to incorporate any inheritance')
self._raw_representation = data
self._representation = dict(self._COMMON_REPRESENTATION)
self._representation.update(data)
@classmethod
def from_query(cls, query, db=None, collection=None):
"""Given a query and a database or collection, find a bundle.
If the query doesn't match any bundles, None is returned. If the
query matches more than one bundle, an exception is raised.
"""
assert db is not None or collection is not None, (
'either "db" or "collection" must be provided')
assert db is None or collection is None, (
'only one of "db" or "collection" can be provided')
if collection is None:
collection = db.bundles
cursor = collection.find(query).sort(
'basket_revision', pymongo.DESCENDING).limit(1)
if cursor.count() == 0:
# No bundles match the query.
return None
return cls(cursor.next())
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.permanent_url == other.permanent_url)
def __getattr__(self, name):
if name in self._COMMON_REPRESENTATION:
return self._representation[name]
else:
raise AttributeError
@staticmethod
def construct_id(owner, basket, name, revision=None):
if revision is not None:
basket = '/'.join([basket, str(revision)])
return "~%s/%s/%s" % (owner, basket, name)
@property
def id(self):
return self.construct_id(
self.owner, self.basket_name, self.name, self.basket_revision)
@property
def search_id(self):
"""Return the (revisionless) ID used to index the bundle for searches.
"""
return self.construct_id(
self.owner, self.basket_name, self.name)
@property
def short_url(self):
"""Return the short URL for this bundle.
The URL is the permanent path portion of the charmworld URL, e.g.
~sinzui/bundles/mysql/tiny to support a full URL of
http://manage.jujucharms.com/~sinzui/bundles/mysql/tiny
"""
if not all([self.owner, self.basket_name, self.name]):
return ''
url = '~{owner}/bundles/{basket_name}/{name}'.format(
owner=self.owner,
basket_name=self.basket_name,
name=self.name,
)
return url
@property
def permanent_url(self):
"""The permanent url for the bundle."""
return "jc:{}".format(self.id)
def __iter__(self):
"""Iterate over the keys and values of this bundle.
Among other uses, this makes it easy to get a dictionary
representation of a bundle by "casting" with dict(bundle).
"""
yield 'id', self.id
yield 'permanent_url', self.permanent_url
for key in self._COMMON_REPRESENTATION:
yield key, self.__getattr__(key)
def acquire_session_secret(database):
"""Return a secret to use for AuthTkt sessions.
If a secret is already in the database, use that. Otherwise, generate a
new secret.
"""
secret = str(random.getrandbits(32))
try:
database.app_config.insert({'_id': 'session-secret', 'secret': secret})
except pymongo.errors.DuplicateKeyError:
# If there was a secret already, just use the existing one.
pass
unicode_secret = database.app_config.find_one('session-secret')['secret']
return unicode_secret.encode('ascii')
def unversioned_key(charm):
return (charm['owner'], charm['series'], charm['name'])
def find_charms(db, spec=None, fields=None, skip=0, limit=0, timeout=True,
snapshot=False, tailable=False, sort=None, max_scan=None,
as_class=None, valid_charms_only=True, only_promulgated=False,
all_revisions=False, **kwargs):
"""Return items from the charms collection.
If the parameter valid_charms_only is True, a filter is added to spec
so that only those charms are returned where the field store_data.errors
does not exist.
By default, the latest revision is returned. If all_revisions is True,
all revisions are returned.
"""
collection = db.charms
if valid_charms_only:
if spec is None:
spec = {}
spec['store_data.errors'] = {'$exists': False}
if only_promulgated:
if spec is None:
spec = {}
spec['promulgated'] = True
return list(_find_charms(
collection, spec, fields, skip, limit, timeout, snapshot, tailable,
sort, max_scan, as_class, all_revisions, **kwargs))
def _find_charms(collection, spec=None, fields=None, skip=0, limit=0,
timeout=True, snapshot=False, tailable=False, sort=None,
max_scan=None, as_class=None, all_revisions=False, **kwargs):
if not all_revisions:
id_fields = ('owner', 'series', 'name')
initial_sort = [(f, pymongo.DESCENDING) for f in
id_fields + ('store_data.revision',)]
if fields is not None:
# Ensure required fields for groupby are present.
final_fields = set(fields).union({'_id'})
fields = final_fields.union(id_fields)
else:
initial_sort = sort
results = collection.find(
spec, fields, skip, limit, timeout, snapshot, tailable, initial_sort,
max_scan, as_class, **kwargs)
if not all_revisions:
results = (group.next() for key, group in
itertools.groupby(results, key=unversioned_key))
if fields is not None:
# Strip fields that were added for groupby.
results = (
dict(
(k, v) for k, v in result.items() if k in final_fields
) for result in results)
if sort is not None:
results = _local_sort(results, sort)
return results
def _local_sort(results, sort):
results = list(results)
for field, order in reversed(sort):
reverse = bool(order == pymongo.DESCENDING)
results.sort(key=lambda x: x.get(field), reverse=reverse)
return results
def sync_index():
""""Entry point for sync-index script."""
configure_logging()
logger = logging.getLogger('sync-index')
charm_source = CharmSource.from_settings(get_ini())
charm_ids = charm_source.sync_index()
while True:
try:
charm_id = next(charm_ids)
except StopIteration:
break
except Exception:
logger.exception('Unable to index charm.')
else:
logger.info('Syncing %s to Elasticsearch' % charm_id)
def options_to_storage(options):
"""Convert options, as retrieved from config.yaml, into a list.
This format avoids user-defined keys, which are problematic in
elasticsearch.
"""
storage = []
if options is None:
return storage
for key, value in options.items():
option = {'name': key}
option.update(value)
storage.append(option)
return storage
def storage_to_options(storage):
"""Convert options, as retrieved from mongodb, into a dict.
This format has the same structure as config.yaml.
"""
options = {}
for option in storage:
new_option = dict(option)
del new_option['name']
value = options.setdefault(option['name'], new_option)
if value is not new_option:
raise ValueError('Option name "%s" occurs multiple times.' %
option['name'])
return options
def make_bundle_doc(data, owner, basket_id, bundle_name):
basket_name, basket_revision = basket_id.split('/')
_id = Bundle.construct_id(owner, basket_name, bundle_name, basket_revision)
return {
'_id': _id,
'name': bundle_name,
'owner': owner,
'basket_name': basket_name,
'basket_revision': int(basket_revision),
'data': data,
}
def store_bundles(collection, deployer_config, owner, basket_id,
index_client=None):
"""Store a basket of bundles into MongoDB and/or ElasticSearch.
:param: collection: A db bundles collection. If None the bundles are not
stored to Mongo.
:param: deployer_config: A dictionary representing the basket of bundles.
:param: owner: A string representing the owner. No leading ~.
:param: basket_id: A slash-joined string of name and revision for the
basket. Does not include the owner name.
:param: index_client: The elastic search client. If None it will be
retrieved. Useful for Mongo-only tests where the indexing is not
needed.
"""
if index_client is None:
index_client = ElasticSearchClient.from_settings(settings)
# Augment the deployer_config with additional information for indexing.
index_data = {}
for bundle_name in deployer_config:
# Set up indexing.
data = get_flattened_deployment(deployer_config, bundle_name)
index_data[bundle_name] = make_bundle_doc(data, owner, basket_id,
bundle_name)
if collection is not None:
collection.save(index_data[bundle_name])
index_client.index_bundles(index_data.values())
def slurp_files(fs, tree, entry_source=None):
"""Store files in a gridFS, returning a mapping of paths to content hashes.
:param fs: A gridFS.
:param tree: A bazaar tree.
:param entry_source: A generator of (file_path, file_id) tuples to
be slurped. The default entry_source only finds files.
"""
if entry_source is None:
def entry_source():
for path, entry in tree.iter_entries_by_dir():
if entry.kind != 'file':
continue
yield path, entry.file_id
entry_source = entry_source()
hashes = {}
for path, file_id in entry_source:
bytes = tree.get_file_text(file_id)
content_type = magic.from_buffer(bytes, mime=True)
_id = hashlib.sha256(bytes).hexdigest()
if not fs.exists(_id):
fs.put(bytes, contentType=content_type, _id=_id)
hashes[path] = _id
return hashes
|