File: package.py

package info (click to toggle)
python-dcos 0.2.0-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,440 kB
  • sloc: python: 8,196; sh: 194; makefile: 36
file content (1575 lines) | stat: -rw-r--r-- 46,851 bytes parent folder | download
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
import abc
import base64
import collections
import copy
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import zipfile
from distutils.version import LooseVersion

import git
import portalocker
import pystache
import six
from dcos import (constants, emitting, errors, http, marathon, mesos,
                  subcommand, util)
from dcos.errors import DCOSException, DefaultError

from six.moves import urllib

logger = util.get_logger(__name__)

emitter = emitting.FlatEmitter()


PACKAGE_METADATA_KEY = 'DCOS_PACKAGE_METADATA'
PACKAGE_NAME_KEY = 'DCOS_PACKAGE_NAME'
PACKAGE_VERSION_KEY = 'DCOS_PACKAGE_VERSION'
PACKAGE_SOURCE_KEY = 'DCOS_PACKAGE_SOURCE'
PACKAGE_FRAMEWORK_KEY = 'DCOS_PACKAGE_IS_FRAMEWORK'
PACKAGE_RELEASE_KEY = 'DCOS_PACKAGE_RELEASE'
PACKAGE_COMMAND_KEY = 'DCOS_PACKAGE_COMMAND'
PACKAGE_REGISTRY_VERSION_KEY = 'DCOS_PACKAGE_REGISTRY_VERSION'
PACKAGE_FRAMEWORK_NAME_KEY = 'DCOS_PACKAGE_FRAMEWORK_NAME'


def install_app(pkg, revision, init_client, options, app_id):
    """Installs a package's application

    :param pkg: the package to install
    :type pkg: Package
    :param revision: the package revision to install
    :type revision: str
    :param init_client: the program to use to run the package
    :type init_client: object
    :param options: package parameters
    :type options: dict
    :param app_id: app ID for installation of this package
    :type app_id: str
    :rtype: None
    """

    # Insert option parameters into the init template
    init_desc = pkg.marathon_json(revision, options)

    if app_id is not None:
        logger.debug('Setting app ID to "%s" (was "%s")',
                     app_id,
                     init_desc['id'])
        init_desc['id'] = app_id

    # Send the descriptor to init
    init_client.add_app(init_desc)


def _make_package_labels(pkg, revision, options):
    """Returns Marathon app labels for a package.

    :param pkg: The package to install
    :type pkg: Package
    :param revision: The package revision to install
    :type revision: str
    :param options: package parameters
    :type options: dict
    :returns: Marathon app labels
    :rtype: dict
    """

    metadata = pkg.package_json(revision)

    encoded_metadata = _base64_encode(metadata)

    is_framework = metadata.get('framework')
    if not is_framework:
        is_framework = False

    package_registry_version = pkg.registry.get_version()

    package_labels = {
        PACKAGE_METADATA_KEY: encoded_metadata,
        PACKAGE_NAME_KEY: metadata['name'],
        PACKAGE_VERSION_KEY: metadata['version'],
        PACKAGE_SOURCE_KEY: pkg.registry.source.url,
        PACKAGE_FRAMEWORK_KEY: json.dumps(is_framework),
        PACKAGE_REGISTRY_VERSION_KEY: package_registry_version,
        PACKAGE_RELEASE_KEY: revision
    }

    if pkg.has_command_definition(revision):
        command = pkg.command_json(revision, options)
        package_labels[PACKAGE_COMMAND_KEY] = _base64_encode(command)

    # Run a heuristic that determines the hint for the framework name
    framework_name = _find_framework_name(pkg.name(), options)
    if framework_name:
        package_labels[PACKAGE_FRAMEWORK_NAME_KEY] = framework_name

    return package_labels


def _find_framework_name(package_name, options):
    """
    :param package_name: the name of the package
    :type package_name: str
    :param options: the options object
    :type options: dict
    :returns: the name of framework if found; None otherwise
    :rtype: str
    """

    return options.get(package_name, {}).get('framework-name', None)


def _base64_encode(dictionary):
    """Returns base64(json(dictionary)).

    :param dictionary: dict to encode
    :type dictionary: dict
    :returns: base64 encoding
    :rtype: str
    """

    json_str = json.dumps(dictionary, sort_keys=True)
    str_bytes = six.b(json_str)
    return base64.b64encode(str_bytes).decode('utf-8')


def uninstall(package_name, remove_all, app_id, cli, app):
    """Uninstalls a package.

    :param package_name: The package to uninstall
    :type package_name: str
    :param remove_all: Whether to remove all instances of the named app
    :type remove_all: boolean
    :param app_id: App ID of the app instance to uninstall
    :type app_id: str
    :param init_client: The program to use to run the app
    :type init_client: object
    :rtype: None
    """

    if cli is False and app is False:
        cli = app = True

    uninstalled = False
    if cli:
        if subcommand.uninstall(package_name):
            uninstalled = True

    if app:
        num_apps = uninstall_app(
            package_name,
            remove_all,
            app_id,
            marathon.create_client(),
            mesos.DCOSClient())

        if num_apps > 0:
            uninstalled = True

    if uninstalled:
        return None
    else:
        msg = 'Package [{}]'.format(package_name)
        if app_id is not None:
            msg += " with id [{}]".format(app_id)
        msg += " is not installed."
        raise DCOSException(msg)


def uninstall_subcommand(distribution_name):
    """Uninstalls a subcommand.

    :param distribution_name: the name of the package
    :type distribution_name: str
    :returns: True if the subcommand was uninstalled
    :rtype: bool
    """

    return subcommand.uninstall(distribution_name)


def uninstall_app(app_name, remove_all, app_id, init_client, dcos_client):
    """Uninstalls an app.

    :param app_name: The app to uninstall
    :type app_name: str
    :param remove_all: Whether to remove all instances of the named app
    :type remove_all: boolean
    :param app_id: App ID of the app instance to uninstall
    :type app_id: str
    :param init_client: The program to use to run the app
    :type init_client: object
    :param dcos_client: the DCOS client
    :type dcos_client: dcos.mesos.DCOSClient
    :returns: number of apps uninstalled
    :rtype: int
    """

    apps = init_client.get_apps()

    def is_match(app):
        encoding = 'utf-8'  # We normalize encoding for byte-wise comparison
        name_label = app.get('labels', {}).get(PACKAGE_NAME_KEY, u'')
        name_label_enc = name_label.encode(encoding)
        app_name_enc = app_name.encode(encoding)
        name_matches = name_label_enc == app_name_enc

        if app_id is not None:
            pkg_app_id = app.get('id', '')
            normalized_app_id = init_client.normalize_app_id(app_id)
            return name_matches and pkg_app_id == normalized_app_id
        else:
            return name_matches

    matching_apps = [a for a in apps if is_match(a)]

    if not remove_all and len(matching_apps) > 1:
        app_ids = [a.get('id') for a in matching_apps]
        raise DCOSException(
            ("Multiple apps named [{}] are installed: [{}].\n" +
             "Please use --app-id to specify the ID of the app to uninstall," +
             " or use --all to uninstall all apps.").format(
                 app_name,
                 ', '.join(app_ids)))

    for app in matching_apps:
        package_json = _decode_and_add_context(
            app['id'],
            app.get('labels', {}))
        # First, remove the app from Marathon
        init_client.remove_app(app['id'], force=True)

        # Second, shutdown the framework with Mesos
        framework_name = app.get('labels', {}).get(PACKAGE_FRAMEWORK_NAME_KEY)
        if framework_name is not None:
            logger.info(
                'Trying to shutdown framework {}'.format(framework_name))
            frameworks = mesos.Master(dcos_client.get_master_state()) \
                              .frameworks(inactive=True)

            # Look up all the framework names
            framework_ids = [
                framework['id']
                for framework in frameworks
                if framework['name'] == framework_name
            ]

            logger.info(
                'Found the following frameworks: {}'.format(framework_ids))

            # Emit post uninstall notes
            emitter.publish(
                DefaultError(
                    'Uninstalled package [{}] version [{}]'.format(
                        package_json['name'],
                        package_json['version'])))

            if 'postUninstallNotes' in package_json:
                emitter.publish(
                    DefaultError(package_json['postUninstallNotes']))

            if len(framework_ids) == 1:
                dcos_client.shutdown_framework(framework_ids[0])
            elif len(framework_ids) > 1:
                raise DCOSException(
                    "Unable to shutdown the framework for [{}] because there "
                    "are multiple frameworks with the same name: [{}]. "
                    "Manually shut them down using 'dcos service "
                    "shutdown'.".format(
                        framework_name,
                        ', '.join(framework_ids)))

    return len(matching_apps)


class InstalledPackage(object):
    """Represents an intalled DCOS package.  One of `app` and
    `subcommand` must be supplied.

    :param apps: A dictionary representing a marathon app. Of the
                format returned by `installed_apps()`
    :type apps: [dict]
    :param subcommand: Installed subcommand
    :type subcommand: subcommand.InstalledSubcommand
    """

    def __init__(self, apps=[], subcommand=None):
        assert apps or subcommand
        self.apps = apps
        self.subcommand = subcommand

    def name(self):
        """
        :returns: The name of the package
        :rtype: str
        """
        if self.subcommand:
            return self.subcommand.name
        else:
            return self.apps[0]['name']

    def dict(self):
        """ A dictionary representation of the package.  Used by `dcos package
        list`.

        :returns: A dictionary representation of the package.
        :rtype: dict
        """
        ret = {}

        if self.subcommand:
            ret['command'] = {'name': self.subcommand.name}

        if self.apps:
            ret['apps'] = [app['appId'] for app in self.apps]

        if self.subcommand:
            package_json = self.subcommand.package_json()
            ret.update(package_json)

            ret['packageSource'] = self.subcommand.package_source()
            ret['releaseVersion'] = self.subcommand.package_revision()
        else:
            ret.update(self.apps[0])
            ret.pop('appId')

        return ret


def installed_packages(init_client, endpoints):
    """Returns all installed packages in the format:

    [{
       'apps': [<id>],
       'command': {
         'name': <name>
       }
       ...<metadata>...
    }]

    :param init_client: The program to use to list packages
    :type init_client: object
    :param endpoints: Whether to include a list of
                      endpoints as port-host pairs
    :type endpoints: boolean
    :returns: A list of installed packages
    :rtype: [InstalledPackage]
    """

    apps = installed_apps(init_client, endpoints)
    subcommands = installed_subcommands()

    dicts = collections.defaultdict(lambda: {'apps': [], 'command': None})

    for app in apps:
        key = (app['name'], app['releaseVersion'], app['packageSource'])
        dicts[key]['apps'].append(app)

    for subcmd in subcommands:
        package_revision = subcmd.package_revision()
        package_source = subcmd.package_source()
        key = (subcmd.name, package_revision, package_source)
        dicts[key]['command'] = subcmd

    return [
        InstalledPackage(pkg['apps'], pkg['command']) for pkg in dicts.values()
    ]


def installed_subcommands():
    """Returns all installed subcommands.

    :returns: all installed subcommands
    :rtype: [InstalledSubcommand]
    """

    return [subcommand.InstalledSubcommand(name) for name in
            subcommand.distributions()]


def installed_apps(init_client, endpoints=False):
    """
    Returns all installed apps.  An app is of the format:

    {
      'appId': <appId>,
      'packageSource': <source>,
      'registryVersion': <app_version>,
      'releaseVersion': <release_version>
      'endpoints' (optional): [{
        'host': <host>,
        'ports': <ports>,
      }]
      ..<package.json properties>..
    }

    :param init_client: The program to use to list packages
    :type init_client: object
    :param endpoints: Whether to include a list of
                      endpoints as port-host pairs
    :type endpoints: boolean
    :returns: all installed apps
    :rtype: [dict]
    """

    apps = init_client.get_apps()

    encoded_apps = [(a['id'], a['labels'])
                    for a in apps
                    if a.get('labels', {}).get(PACKAGE_METADATA_KEY)]

    # Filter elements that failed to parse correctly as JSON
    valid_apps = []
    for app_id, labels in encoded_apps:
        try:
            decoded = _decode_and_add_context(app_id, labels)
        except Exception:
            logger.exception(
                'Unable to decode package metadata during install: %s',
                app_id)

        valid_apps.append(decoded)

    if endpoints:
        for app in valid_apps:
            tasks = init_client.get_tasks(app["appId"])
            app['endpoints'] = [{"host": t["host"], "ports": t["ports"]}
                                for t in tasks]

    return valid_apps


def _decode_and_add_context(app_id, labels):
    """ Create an enhanced package JSON from Marathon labels

    {
      'appId': <appId>,
      'packageSource': <source>,
      'registryVersion': <app_version>,
      'releaseVersion': <release_version>,
      ..<package.json properties>..
    }

    :param app_id: Marathon application id
    :type app_id: str
    :param labels: Marathon label dictionary
    :type labels: dict
    :rtype: dict
    """

    encoded = labels.get(PACKAGE_METADATA_KEY, {})
    decoded = base64.b64decode(six.b(encoded)).decode()

    decoded_json = util.load_jsons(decoded)
    decoded_json['appId'] = app_id
    decoded_json['packageSource'] = labels.get(PACKAGE_SOURCE_KEY)
    decoded_json['releaseVersion'] = labels.get(PACKAGE_RELEASE_KEY)

    return decoded_json


def search(query, cfg):
    """Returns a list of index entry collections, one for each registry in
    the supplied config.

    :param query: The search term
    :type query: str
    :param cfg: Configuration dictionary
    :type cfg: dcos.config.Toml
    :rtype: [IndexEntries]
    """

    threshold = 0.5  # Minimum rank required to appear in results
    results = []

    def clean_package_entry(entry):
        result = entry.copy()
        result.update({
            'versions': list(entry['versions'].keys())
        })
        return result

    for registry in registries(cfg):
        source_results = []
        index = registry.get_index()

        for pkg in index['packages']:
            rank = _search_rank(pkg, query)
            if rank >= threshold:
                source_results.append(clean_package_entry(pkg))

        entries = IndexEntries(registry.source, source_results)
        results.append(entries)

    return results


def _search_rank(pkg, query):
    """
    :param pkg: Index entry to rank for affinity with the search term
    :type pkg: object
    :param query: Search term
    :type query: str
    :rtype: float
    """
    result = 0.0

    wildcard_symbol = '*'
    regex_pattern = '.*'

    q = query.lower()
    if wildcard_symbol in q:
        q = q.replace(wildcard_symbol, regex_pattern)
        if q.endswith(wildcard_symbol):
            q = '^{}'.format(q)
        else:
            q = '{}$'.format(q)

        if re.match(q, pkg['name'].lower()):
            result += 2.0
        return result

    if q in pkg['name'].lower():
        result += 2.0
    for tag in pkg['tags']:
        if q in tag.lower():
            result += 1.0

    if q in pkg['description'].lower():
        result += 0.5

    return result


def _extract_default_values(config_schema):
    """
    :param config_schema: A json-schema describing configuration options.
    :type config_schema: dict
    :returns: a dictionary with the default specified by the schema
    :rtype: dict | None
    """

    defaults = {}
    if 'properties' not in config_schema:
        return None

    for key, value in config_schema['properties'].items():
        if isinstance(value, dict) and 'default' in value:
            defaults[key] = value['default']
        elif isinstance(value, dict) and value.get('type', '') == 'object':
            # Generate the default value from the embedded schema
            defaults[key] = _extract_default_values(value)

    return defaults


def _merge_options(first, second):
    """Merges the :code:`second` dictionary into the :code:`first` dictionary.
    If both dictionaries have the same key and both values are dictionaries
    then it recursively merges those two dictionaries.

    :param first: first dictionary
    :type first: dict
    :param second: second dictionary
    :type second: dict
    :returns: merged dictionary
    :rtype: dict
    """

    result = copy.deepcopy(first)
    for key, second_value in second.items():
        if key in first:
            first_value = first[key]

            if (isinstance(first_value, collections.abc.Mapping) and
               isinstance(second_value, collections.abc.Mapping)):
                result[key] = _merge_options(first_value, second_value)
            else:
                result[key] = second_value
        else:
            result[key] = second_value

    return result


def resolve_package(package_name, config=None):
    """Returns the first package with the supplied name found by looking at
    the configured sources in the order they are defined.

    :param package_name: The name of the package to resolve
    :type package_name: str
    :param config: dcos config
    :type config: dcos.config.Toml | None
    :returns: The named package, if found
    :rtype: Package
    """

    if not config:
        config = util.get_config()

    for registry in registries(config):
        package = registry.get_package(package_name)
        if package:
            return package

    return None


def registries(config):
    """Returns configured cached package registries.

    :param config: Configuration dictionary
    :type config: dcos.config.Toml
    :returns: The list of registries, in resolution order
    :rtype: [Registry]
    """

    sources = list_sources(config)
    return [Registry(source, source.local_cache(config)) for source in sources]


def list_sources(config):
    """List configured package sources.

    :param config: Configuration dictionary
    :type config: dcos.config.Toml
    :returns: The list of sources, in resolution order
    :rtype: [Source]
    """

    source_uris = util.get_config_vals(['package.sources'], config)[0]

    sources = [url_to_source(s) for s in source_uris]

    errs = [source for source in sources if isinstance(source, Error)]
    if errs:
        raise DCOSException('\n'.join(err.error() for err in errs))

    return sources


def url_to_source(url):
    """Creates a package source from the supplied URL.

    :param url: Location of the package source
    :type url: str
    :returns: A Source backed by the supplied URL
    :rtype: Source | Error
    """

    parse_result = urllib.parse.urlparse(url)
    scheme = parse_result.scheme

    if scheme == 'file':
        return FileSource(url)
    elif scheme == 'http' or scheme == 'https':
        return HttpSource(url)
    elif scheme == 'git':
        return GitSource(url)
    else:
        return Error("Source URL uses unsupported protocol [{}]".format(url))


def _acquire_file_lock(lock_file_path):
    """Acquires an exclusive lock on the supplied file.

    :param lock_file_path: Path to the lock file
    :type lock_file_path: str
    :returns: Lock file
    :rtype: File
    """

    try:
        lock_file = open(lock_file_path, 'w')
    except IOError as e:
        logger.exception('Failed to open lock file: %s', lock_file_path)

        raise util.io_exception(lock_file_path, e.errno)

    acquire_mode = portalocker.LOCK_EX | portalocker.LOCK_NB

    try:
        portalocker.lock(lock_file, acquire_mode)
        return lock_file
    except portalocker.LockException:
        logger.exception(
            'Failure while tring to aquire file lock: %s',
            lock_file_path)

        lock_file.close()
        raise DCOSException('Unable to acquire the package cache lock')


def update_sources(config, validate=False):
    """Overwrites the local package cache with the latest source data.

    :param config: Configuration dictionary
    :type config: dcos.config.Toml
    :rtype: None
    """

    errors = []

    # ensure the cache directory is properly configured
    cache_dir = os.path.expanduser(
        util.get_config_vals(['package.cache'], config)[0])

    # ensure the cache directory exists
    if not os.path.exists(cache_dir):
        os.makedirs(cache_dir)

    if not os.path.isdir(cache_dir):
        raise DCOSException(
            'Cache directory does not exist! [{}]'.format(cache_dir))

    # obtain an exclusive file lock on $CACHE/.lock
    lock_path = os.path.join(cache_dir, '.lock')

    with _acquire_file_lock(lock_path):

        # list sources
        sources = list_sources(config)

        for source in sources:

            emitter.publish('Updating source [{}]'.format(source))

            # create a temporary staging directory
            with util.tempdir() as tmp_dir:

                stage_dir = os.path.join(tmp_dir, source.hash())

                # copy to the staging directory
                try:
                    source.copy_to_cache(stage_dir)
                except DCOSException as e:
                    logger.exception(
                        'Failed to copy universe source %s to cache %s',
                        source.url,
                        stage_dir)

                    errors.append(str(e))
                    continue

                # check version
                # TODO(jsancio): move this to the validation when it is forced
                Registry(source, stage_dir).check_version(
                    LooseVersion('1.0'),
                    LooseVersion('2.0'))

                # validate content
                if validate:
                    validation_errors = Registry(source, stage_dir).validate()
                    if len(validation_errors) > 0:
                        errors += validation_errors
                        continue  # keep updating the other sources

                # remove the $CACHE/source.hash() directory
                target_dir = os.path.join(cache_dir, source.hash())
                try:
                    if os.path.exists(target_dir):
                        shutil.rmtree(target_dir,
                                      onerror=_rmtree_on_error,
                                      ignore_errors=False)
                except OSError:
                    logger.exception(
                        'Error removing target directory before move: %s',
                        target_dir)

                    err = "Could not remove directory [{}]".format(target_dir)
                    errors.append(err)
                    continue  # keep updating the other sources

                # move the staging directory to $CACHE/source.hash()
                shutil.move(stage_dir, target_dir)

    if errors:
        raise DCOSException(util.list_to_err(errors))


class Source:
    """A source of DCOS packages."""

    @property
    @abc.abstractmethod
    def url(self):
        """
        :returns: Location of the package source
        :rtype: str
        """

        raise NotImplementedError

    def hash(self):
        """Returns a cryptographically secure hash derived from this source.

        :returns: a hexadecimal string
        :rtype: str
        """

        return hashlib.sha1(self.url.encode('utf-8')).hexdigest()

    def local_cache(self, config):
        """Returns the file system path to this source's local cache.

        :param config: Configuration dictionary
        :type config: dcos.config.Toml
        :returns: Path to this source's local cache on disk
        :rtype: str or None
        """

        cache_dir = os.path.expanduser(
            util.get_config_vals(['package.cache'], config)[0])
        return os.path.join(cache_dir, self.hash())

    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :rtype: None
        """

        raise NotImplementedError

    def __repr__(self):

        return self.url


class FileSource(Source):
    """A registry of DCOS packages.

    :param url: Location of the package source
    :type url: str
    """

    def __init__(self, url):
        self._url = url

    @property
    def url(self):
        """
        :returns: Location of the package source
        :rtype: str
        """

        return self._url

    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :rtype: None
        """

        # copy the source to the target_directory
        parse_result = urllib.parse.urlparse(self._url)
        source_dir = parse_result.path
        try:
            shutil.copytree(source_dir, target_dir)
            return None
        except OSError:
            logger.exception(
                'Error copying source director [%s] to target directory [%s].',
                source_dir,
                target_dir)

            raise DCOSException(
                'Unable to fetch packages from [{}]'.format(self.url))


class HttpSource(Source):
    """A registry of DCOS packages.

    :param url: Location of the package source
    :type url: str
    """

    def __init__(self, url):
        self._url = url

    @property
    def url(self):
        """
        :returns: Location of the package source
        :rtype: str
        """

        return self._url

    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :returns: The error, if one occurred
        :rtype: None
        """

        try:
            with util.tempdir() as tmp_dir:

                tmp_file = os.path.join(tmp_dir, 'packages.zip')
                # Download the zip file.
                req = http.get(self.url)
                if req.status_code == 200:
                    with open(tmp_file, 'wb') as f:
                        for chunk in req.iter_content(1024):
                            f.write(chunk)
                else:
                    raise Exception(
                        'HTTP GET for {} did not return 200: {}'.format(
                            self.url,
                            req.status_code))

                # Unzip the downloaded file.
                packages_zip = zipfile.ZipFile(tmp_file, 'r')
                packages_zip.extractall(tmp_dir)

                # Move the enclosing directory to the target directory
                enclosing_dirs = [item
                                  for item in os.listdir(tmp_dir)
                                  if os.path.isdir(
                                      os.path.join(tmp_dir, item))]

                # There should only be one directory present after extracting.
                assert(len(enclosing_dirs) == 1)

                enclosing_dir = os.path.join(tmp_dir, enclosing_dirs[0])

                shutil.copytree(enclosing_dir, target_dir)

                # Set appropriate file permissions on the scripts.
                x_mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR |
                          stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP)

                scripts_dir = os.path.join(target_dir, 'scripts')
                scripts = os.listdir(scripts_dir)

                for script in scripts:
                    script_path = os.path.join(scripts_dir, script)
                    if os.path.isfile(script_path):
                        os.chmod(script_path, x_mode)

                return None

        except Exception:
            logger.exception('Unable to fetch packages from URL: %s', self.url)

            raise DCOSException(
                'Unable to fetch packages from [{}]'.format(self.url))


class GitSource(Source):
    """A registry of DCOS packages.

    :param url: Location of the package source
    :type url: str
    """

    def __init__(self, url):
        self._url = url

    @property
    def url(self):
        """
        :returns: Location of the package source
        :rtype: str
        """

        return self._url

    def copy_to_cache(self, target_dir):
        """Copies the source content to the supplied local directory.

        :param target_dir: Path to the destination directory.
        :type target_dir: str
        :returns: The error, if one occurred
        :rtype: None
        """

        try:
            # TODO(SS): add better url parsing

            # Ensure git is installed properly.
            git_program = util.which('git')
            if git_program is None:
                raise DCOSException("""Could not locate the git program.  Make sure \
it is installed and on the system search path.
PATH = {}""".format(os.environ[constants.PATH_ENV]))

            # Clone git repo into the supplied target directory.
            git.Repo.clone_from(self._url,
                                to_path=target_dir,
                                progress=None,
                                branch='master')

            # Remove .git directory to save space.
            shutil.rmtree(os.path.join(target_dir, ".git"),
                          onerror=_rmtree_on_error)
            return None

        except git.exc.GitCommandError:
            logger.exception('Unable to fetch packages from git: %s', self.url)

            raise DCOSException(
                'Unable to fetch packages from [{}]'.format(self.url))


def _rmtree_on_error(func, path, exc_info):
    """Error handler for ``shutil.rmtree``.
    If the error is due to an access error (read only file)
    it attempts to add write permission and then retries.
    If the error is for another reason it re-raises the error.

    Usage : ``shutil.rmtree(path, onerror=onerror)``.

    :param func: Function which raised the exception.
    :type func: function
    :param path: The path name passed to ``shutil.rmtree`` function.
    :type path: str
    :param exc_info: Information about the last raised exception.
    :type exc_info: tuple
    :rtype: None
    """
    import stat
    if not os.access(path, os.W_OK):
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        func(path)
    else:
        raise


class Error(errors.Error):
    """Class for describing errors during packaging operations.

    :param message: Error message
    :type message: str
    """

    def __init__(self, message):
        self._message = message

    def error(self):
        """Return error message

        :returns: The error message
        :rtype: str
        """

        return self._message


class Registry():
    """Represents a package registry on disk.

    :param base_path: Path to the registry
    :type base_path: str
    :param source: The associated package source
    :type source: Source
    """

    def __init__(self, source, base_path):
        self._base_path = base_path
        self._source = source

    def validate(self):
        """Validates a package registry.

        :returns: Validation errors
        :rtype: [str]
        """

        # TODO(CD): implement these checks in pure Python?
        scripts_dir = os.path.join(self._base_path, 'scripts')
        if util.is_windows_platform():
            validate_script = os.path.join(scripts_dir,
                                           '1-validate-packages.ps1')
            cmd = ['powershell', '-ExecutionPolicy',
                   'ByPass', '-File', validate_script]
            result = subprocess.call(cmd)
        else:
            validate_script = os.path.join(scripts_dir,
                                           '1-validate-packages.sh')
            result = subprocess.call(validate_script)
        if result != 0:
            return ["Source tree is not valid [{}]".format(self._base_path)]
        else:
            return []

    @property
    def source(self):
        """Returns the associated upstream package source for this registry.

        :rtype: Source
        """

        return self._source

    def check_version(self, min_version, max_version):
        """Checks that the version is [min_version, max_version)

        :param min_version: the min version inclusive
        :type min_version: LooseVersion
        :param max_version: the max version exclusive
        :type max_version: LooseVersion
        :returns: None
        """

        version = LooseVersion(self.get_version())
        if not (version >= min_version and
                version < max_version):
            raise DCOSException((
                'Unable to update source [{}] because version {} is '
                'not supported. Supported versions are between {} and '
                '{}. Please update your DCOS CLI.').format(
                    self._source.url,
                    version,
                    min_version,
                    max_version))

    def get_version(self):
        """Returns the version of this registry.

        :rtype: str
        """

        # The package version is found in $BASE/repo/meta/version.json
        index_path = os.path.join(
            self._base_path,
            'repo',
            'meta',
            'version.json')

        if not os.path.isfile(index_path):
            raise DCOSException('Path [{}] is not a file'.format(index_path))

        try:
            with util.open_file(index_path) as fd:
                version_json = json.load(fd)
                return version_json.get('version')
        except ValueError:
            logger.exception('Unable to parse JSON: %s', index_path)

            raise DCOSException('Unable to parse [{}]'.format(index_path))

    def get_index(self):
        """Retuprns the index of packages in this registry.

        :rtype: dict
        """

        # The package index is found in $BASE/repo/meta/index.json
        index_path = os.path.join(
            self._base_path,
            'repo',
            'meta',
            'index.json')

        if not os.path.isfile(index_path):
            raise DCOSException('Path [{}] is not a file'.format(index_path))

        try:
            with util.open_file(index_path) as fd:
                return json.load(fd)
        except ValueError:
            logger.exception('Unable to parse JSON: %s', index_path)

            raise DCOSException('Unable to parse [{}]'.format(index_path))

    def get_package(self, package_name):
        """Returns the named package, if it exists.

        :param package_name: The name of the package to fetch
        :type package_name: str
        :returns: The requested package
        :rtype: Package
        """

        if len(package_name) != 0:
            raise DCOSException('Package name must not be empty.')

        # Packages are found in $BASE/repo/package/<first_character>/<pkg_name>
        first_character = package_name[0].title()

        package_path = os.path.join(
            self._base_path,
            'repo',
            'packages',
            first_character,
            package_name)

        if not os.path.isdir(package_path):
            return None

        try:
            return Package(self, package_path)
        except:
            logger.exception('Unable to read package: %s', package_path)

            raise DCOSException(
                'Could not read package [{}]'.format(package_name))


class Package():
    """Interface to a package on disk.

    :param registry: The containing registry for this package.
    :type registry: Registry
    :param path: Path to the package description on disk
    :type path: str
    """

    def __init__(self, registry, path):
        assert os.path.isdir(path)
        self._registry = registry
        self.path = path

    def name(self):
        """Returns the package name.

        :returns: The name of this package
        :rtype: str
        """

        return os.path.basename(self.path)

    def options(self, revision, user_options):
        """Merges package options with user supplied options, validates, and
        returns the result.

        :param revision: the package revision to install
        :type revision: str
        :param user_options: package parameters
        :type user_options: dict
        :returns: a dictionary with the user supplied options
        :rtype: dict
        """

        if user_options is None:
            user_options = {}

        config_schema = self.config_json(revision)
        default_options = _extract_default_values(config_schema)
        if default_options is None:
            pkg = self.package_json(revision)
            msg = ("An object in the package's config.json is missing the "
                   "required 'properties' feature:\n {}".format(config_schema))
            if 'maintainer' in pkg:
                msg += "\nPlease contact the project maintainer: {}".format(
                       pkg['maintainer'])
            raise DCOSException(msg)

        logger.info('Generated default options: %r', default_options)

        # Merge option overrides
        options = _merge_options(default_options, user_options)

        logger.info('Merged options: %r', options)

        # Validate options with the config schema
        errs = util.validate_json(options, config_schema)
        if len(errs) != 0:
            raise DCOSException(
                "{}\n\n{}".format(
                    util.list_to_err(errs),
                    'Please create a JSON file with the appropriate options, '
                    'and pass the /path/to/file as an --options argument.'))

        return options

    @property
    def registry(self):
        """Returns the containing registry for this package.

        :rtype: Registry
        """

        return self._registry

    def has_definition(self, revision, filename):
        """Returns true if the package defines filename; false otherwise.

        :param revision: package revision
        :type revision: str
        :param filename: file in package definition
        :type filename: str
        :returns: whether filename is defined
        :rtype: bool
        """

        return os.path.isfile(
            os.path.join(
                self.path,
                os.path.join(revision, filename)))

    def has_command_definition(self, revision):
        """Returns true if the package defines a command; false otherwise.

        :param revision: package revision
        :type revision: str
        :rtype: bool
        """

        return self.has_definition(revision, 'command.json')

    def has_marathon_definition(self, revision):
        """Returns true if the package defines a Marathon json. false otherwise.

        :param revision: package revision
        :type revision: str
        :rtype: bool
        """

        return self.has_definition(revision, 'marathon.json')

    def config_json(self, revision):
        """Returns the JSON content of the config.json file.

        :param revision: package revision
        :type revision: str
        :returns: Package config schema
        :rtype: dict
        """

        return self._json(revision, 'config.json')

    def package_json(self, revision):
        """Returns the JSON content of the package.json file.

        :param revision: the package revision
        :type revision: str
        :returns: Package data
        :rtype: dict
        """

        return self._json(revision, 'package.json')

    def marathon_json(self, revision, options):
        """Returns the JSON content of the marathon.json template, after
        rendering it with options.

        :param revision: the package revision
        :type revision: str
        :param options: the template options to use in rendering
        :type options: dict
        :rtype: dict
        """

        init_desc = self._render_template(
            'marathon.json',
            revision,
            options)

        # Add package metadata
        package_labels = _make_package_labels(self, revision, options)

        # Preserve existing labels
        labels = init_desc.get('labels', {})

        labels.update(package_labels)
        init_desc['labels'] = labels

        return init_desc

    def command_json(self, revision, options):
        """Returns the JSON content of the comand.json template, after
        rendering it with options.

        :param revision: the package revision
        :type revision: str
        :param options: the template options to use in rendering
        :type options: dict
        :returns: Package data
        :rtype: dict
        """

        template = self._data(revision, 'command.json')
        rendered = pystache.render(template, options)
        return json.loads(rendered)

    def marathon_template(self, revision):
        """ Returns raw data from marathon.json

        :param revision: the package revision
        :type revision: str
        :returns: raw data from marathon.json
        :rtype: str
        """
        return self._data(revision, 'marathon.json')

    def command_template(self, revision):
        """ Returns raw data from command.json

        :param revision: the package revision
        :type revision: str
        :returns: raw data from command.json
        :rtype: str
        """
        return self._data(revision, 'command.json')

    def _render_template(self, name, revision, options):
        """Render a template.

        :param name: the file name of the template
        :type name: str
        :param revision: the package revision
        :type revision: str
        :param options: the template options to use in rendering
        :type options: dict
        :rtype: dict
        """

        template = self._data(revision, name)
        return util.render_mustache_json(template, options)

    def _json(self, revision, name):
        """Returns the json content of the file named `name` in the directory
           named `revision`

        :param revision: the package revision
        :type revision: str
        :param name: file name
        :type name: str
        :rtype: dict
        """

        data = self._data(revision, name)
        return util.load_jsons(data)

    def _data(self, revision, name):
        """Returns the content of the file named `name` in the directory named
        `revision`

        :param revision: the package revision
        :type revision: str
        :param name: file name
        :type name: str
        :returns: File content of the supplied path
        :rtype: str
        """

        path = os.path.join(revision, name)
        full_path = os.path.join(self.path, path)
        return util.read_file(full_path)

    def package_revisions(self):
        """Returns all of the available package revisions, most recent first.

        :returns: Available revisions of this package
        :rtype: [str]
        """

        vs = sorted((f for f in os.listdir(self.path)
                     if not f.startswith('.')), key=int, reverse=True)
        return vs

    def package_revisions_map(self):
        """Returns an ordered mapping from the package revision to the package
           version, sorted by package revision.

        :returns: Map from package revision to package version
        :rtype: OrderedDict

        """

        package_version_map = collections.OrderedDict()
        for rev in self.package_revisions():
            pkg_json = self.package_json(rev)
            package_version_map[rev] = pkg_json['version']
        return package_version_map

    def latest_package_revision(self, package_version=None):
        """Returns the most recent package revision, for a
        given package version if specified.

        :param package_version: a given package version
        :type package_version: str
        :returns: package revision
        :rtype: str | None
        """

        if package_version:
            pkg_rev_map = self.package_revisions_map()
            # depends on package_revisions() returning an OrderedDict
            if package_version in pkg_rev_map.values():
                return next(pkg_rev for pkg_rev in reversed(pkg_rev_map)
                            if pkg_rev_map[pkg_rev] == package_version)
            else:
                return None
        else:
            pkg_revisions = self.package_revisions()
            revision = pkg_revisions[0]

        return revision

    def __repr__(self):

        rev = self.latest_package_revision()
        pkg_json = self.package_json(rev)

        return json.dumps(pkg_json)


class IndexEntries():
    """A collection of package index entries from a single source.
    Each entry is a dict as described by the JSON schema for the package index:
    https://github.com/mesosphere/universe/blob/master/repo/meta/schema/index-schema.json

    :param source: The source of these index entries
    :type source: Source
    :param packages: The index entries
    :type packages: [dict]
    """

    def __init__(self, source, packages):
        self._source = source
        self._packages = packages

    @property
    def source(self):
        """Returns the source of these index entries.

        :rtype: Source
        """

        return self._source

    @property
    def packages(self):
        """Returns the package index entries.

        :rtype: list of dict
        """

        return self._packages

    def as_dict(self):
        """
        :rtype: dict
        """

        return {'source': self.source.url, 'packages': self.packages}


def get_apps_for_framework(framework_name, client):
    """ Return all apps running the given framework.

    :param framework_name: framework name
    :type framework_name: str
    :param client: marathon client
    :type client: marathon.Client
    :rtype: [dict]
    """

    return [app for app in client.get_apps()
            if app.get('labels', {}).get(
                PACKAGE_FRAMEWORK_NAME_KEY) == framework_name]