This file is indexed.

/usr/lib/python3/dist-packages/plainbox/impl/secure/providers/v1.py is in python3-plainbox 0.25-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
# This file is part of Checkbox.
#
# Copyright 2013-2015 Canonical Ltd.
# Written by:
#   Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3,
# as published by the Free Software Foundation.
#
# Checkbox is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Checkbox.  If not, see <http://www.gnu.org/licenses/>.
"""
:mod:`plainbox.impl.secure.providers.v1` -- Implementation of V1 provider
=========================================================================
"""
import collections
import gettext
import logging
import os

from plainbox.abc import IProvider1
from plainbox.i18n import gettext as _
from plainbox.impl.secure.config import Config, Variable
from plainbox.impl.secure.config import (
    ValidationError as ConfigValidationError)
from plainbox.impl.secure.config import IValidator
from plainbox.impl.secure.config import NotEmptyValidator
from plainbox.impl.secure.config import NotUnsetValidator
from plainbox.impl.secure.config import PatternValidator
from plainbox.impl.secure.config import Unset
from plainbox.impl.secure.origin import Origin
from plainbox.impl.secure.plugins import FsPlugInCollection
from plainbox.impl.secure.plugins import LazyFsPlugInCollection
from plainbox.impl.secure.plugins import PlugIn
from plainbox.impl.secure.plugins import PlugInError
from plainbox.impl.secure.plugins import now
from plainbox.impl.secure.qualifiers import WhiteList
from plainbox.impl.secure.rfc822 import FileTextSource
from plainbox.impl.secure.rfc822 import RFC822SyntaxError
from plainbox.impl.secure.rfc822 import load_rfc822_records
from plainbox.impl.unit import all_units
from plainbox.impl.unit.file import FileRole
from plainbox.impl.unit.file import FileUnit
from plainbox.impl.unit.testplan import TestPlanUnit
from plainbox.impl.validation import Severity
from plainbox.impl.validation import ValidationError


logger = logging.getLogger("plainbox.secure.providers.v1")


class ProviderContentPlugIn(PlugIn):
    """
    PlugIn class for loading provider content.

    Provider content comes in two shapes and sizes:
        - units (of any kind)
        - whitelists

    The actual logic on how to load everything is encapsulated in
    :meth:`wrap()` though its return value is not so useful.

    :attr unit_list:
        The list of loaded units
    :attr whitelist_list:
        The list of loaded whitelists
    """

    def __init__(self, filename, text, load_time, provider, *,
                 validate=False, validation_kwargs=None,
                 check=True, context=None):
        start_time = now()
        try:
            # Inspect the file
            inspect_result = self.inspect(
                filename, text, provider,
                validate, validation_kwargs or {},  # legacy validation
                check, context  # modern validation
            )
        except PlugInError as exc:
            raise exc
        except Exception as exc:
            raise PlugInError(_("Cannot load {!r}: {}").format(filename, exc))
        wrap_time = now() - start_time
        super().__init__(filename, inspect_result, load_time, wrap_time)
        self.unit_list = []
        self.whitelist_list = []
        # And load all of the content from that file
        self.unit_list.extend(self.discover_units(
            inspect_result, filename, text, provider))
        self.whitelist_list.extend(self.discover_whitelists(
            inspect_result, filename, text, provider))

    def inspect(self, filename: str, text: str, provider: "Provider1",
                validate: bool, validation_kwargs: "Dict[str, Any]", check:
                bool, context: "???") -> "Any":
        """
        Interpret and wrap the content of the filename as whatever is
        appropriate. The return value of this class becomes the
        :meth:`plugin_object`

        .. note::
            This method must *not* access neither :attr:`unit_list` nor
            :attr:`whitelist_list`. If needed, it can collect its own state in
            private instance attributes.
        """

    def discover_units(
        self, inspect_result: "Any", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[Unit]":
        """
        Discover all units that were loaded by this plug-in

        :param wrap_result:
            whatever was returned on the call to :meth:`wrap()`.
        :returns:
            an iterable of units.

        .. note::
            this method is always called *after* :meth:`wrap()`.
        """
        yield self.make_file_unit(filename, provider)

    def discover_whitelists(
        self, inspect_result: "Any", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[WhiteList]":
        """
        Discover all whitelists that were loaded by this plug-in

        :param wrap_result:
            whatever was returned on the call to :meth:`wrap()`.
        :returns:
            an iterable of whitelists.

        .. note::
            this method is always called *after* :meth:`wrap()`.
        """
        return ()

    def make_file_unit(self, filename, provider, role=None, base=None):
        if role is None or base is None:
            role, base, plugin_cls = provider.classify(filename)
        return FileUnit({
            'unit': FileUnit.Meta.name,
            'path': filename,
            'base': base,
            'role': role,
        }, origin=Origin(FileTextSource(filename)), provider=provider,
            virtual=True)


class WhiteListPlugIn(ProviderContentPlugIn):
    """
    A specialized :class:`plainbox.impl.secure.plugins.IPlugIn` that loads
    :class:`plainbox.impl.secure.qualifiers.WhiteList` instances from a file.
    """

    def inspect(self, filename: str, text: str, provider: "Provider1",
                validate: bool, validation_kwargs: "Dict[str, Any]", check:
                bool, context: "???") -> "WhiteList":
        if provider is not None:
            implicit_namespace = provider.namespace
        else:
            implicit_namespace = None
        origin = Origin(FileTextSource(filename), 1, text.count('\n'))
        return WhiteList.from_string(
            text, filename=filename, origin=origin,
            implicit_namespace=implicit_namespace)

    def discover_units(
        self, inspect_result: "WhiteList", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[Unit]":
        if provider is not None:
            yield self.make_file_unit(
                filename, provider,
                # NOTE: don't guess what this file is for
                role=FileRole.legacy_whitelist, base=provider.whitelists_dir)
            yield self.make_test_plan_unit(filename, text, provider)

    def discover_whitelists(
        self, inspect_result: "WhiteList", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[WhiteList]":
        yield inspect_result

    def make_test_plan_unit(self, filename, text, provider):
        name = os.path.basename(os.path.splitext(filename)[0])
        origin = Origin(FileTextSource(filename), 1, text.count('\n'))
        field_offset_map = {'include': 0}
        return TestPlanUnit({
            'unit': TestPlanUnit.Meta.name,
            'id': name,
            'name': name,
            'include': str(text),  # delazify content
        }, origin=origin, provider=provider, field_offset_map=field_offset_map,
            virtual=True)

    # NOTE: This version of __init__() exists solely so that provider can
    # default to None. This is still used in some places and must be supported.
    def __init__(self, filename, text, load_time, provider=None, *,
                 validate=False, validation_kwargs=None,
                 check=True, context=None):
        super().__init__(
            filename, text, load_time, provider, validate=validate,
            validation_kwargs=validation_kwargs, check=check, context=context)

    # NOTE: this version of plugin_name() is just for legacy code support
    @property
    def plugin_name(self):
        """
        plugin name, the name of the WhiteList
        """
        return self.plugin_object.name


class UnitPlugIn(ProviderContentPlugIn):
    """
    A specialized :class:`plainbox.impl.secure.plugins.IPlugIn` that loads a
    list of :class:`plainbox.impl.unit.Unit` instances from a file.
    """

    def inspect(
        self, filename: str, text: str, provider: "Provider1", validate: bool,
        validation_kwargs: "Dict[str, Any]", check: bool, context: "???"
    ) -> "Any":
        """
        Load all units from their PXU representation.

        :param filename:
            Name of the file with unit definitions
        :param text:
            Full text of the file with unit definitions (lazy)
        :param provider:
            A provider object to which those units belong to
        :param validate:
            Enable unit validation. Incorrect unit definitions will not be
            loaded and will abort the process of loading of the remainder of
            the jobs.  This is ON by default to prevent broken units from being
            used. This is a keyword-only argument.
        :param validation_kwargs:
            Keyword arguments to pass to the Unit.validate().  Note, this is a
            single argument. This is a keyword-only argument.
        :param check:
            Enable unit checking. Incorrect unit definitions will not be loaded
            and will abort the process of loading of the remainder of the jobs.
            This is OFF by default to prevent broken units from being used.
            This is a keyword-only argument.
        :param context:
            If checking, use this validation context.
        """
        logger.debug(_("Loading units from %r..."), filename)
        try:
            records = load_rfc822_records(
                text, source=FileTextSource(filename))
        except RFC822SyntaxError as exc:
            raise PlugInError(
                _("Cannot load job definitions from {!r}: {}").format(
                    filename, exc))
        unit_list = []
        for record in records:
            unit_name = record.data.get('unit', 'job')
            try:
                unit_cls = self._get_unit_cls(unit_name)
            except KeyError:
                raise PlugInError(
                    _("Unknown unit type: {!r}").format(unit_name))
            try:
                unit = unit_cls.from_rfc822_record(record, provider)
            except ValueError as exc:
                raise PlugInError(
                    _("Cannot define unit from record {!r}: {}").format(
                        record, exc))
            if check:
                for issue in unit.check(context=context, live=True):
                    if issue.severity is Severity.error:
                        raise PlugInError(
                            _("Problem in unit definition, {}").format(issue))
            if validate:
                try:
                    unit.validate(**validation_kwargs)
                except ValidationError as exc:
                    raise PlugInError(
                        _("Problem in unit definition, field {}: {}").format(
                            exc.field, exc.problem))
            unit_list.append(unit)
            logger.debug(_("Loaded %r"), unit)
        return unit_list

    def discover_units(
        self, inspect_result: "List[Unit]", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[Unit]":
        for unit in inspect_result:
            yield unit
        yield self.make_file_unit(filename, provider)

    def discover_whitelists(
        self, inspect_result: "List[Unit]", filename: str, text: str,
        provider: "Provider1"
    ) -> "Iterable[WhiteList]":
        for unit in (unit for unit in inspect_result
                     if unit.Meta.name == 'test plan'):
            if unit.include is not None:
                yield WhiteList(
                    unit.include, name=unit.partial_id, origin=unit.origin,
                    implicit_namespace=unit.provider.namespace)

    # NOTE: this version of plugin_object() is just for legacy code support
    @property
    def plugin_object(self):
        return self.unit_list

    @staticmethod
    def _get_unit_cls(unit_name):
        """
        Get a class that implements the specified unit
        """
        # TODO: transition to lazy plugin collection
        all_units.load()
        return all_units.get_by_name(unit_name).plugin_object


class ProviderContentEnumerator:
    """
    Support class for enumerating provider content.

    The only role of this class is to expose a plug in collection that can
    enumerate all of the files reachable from a provider. This collection
    is consumed by other parts of provider loading machinery.

    Since it is a stock plug in collection it can be easily "mocked" to provide
    alternate content without involving modifications of the real file system.

    .. note::
        This class is automatically instantiated by :class:`Provider1`. The
        :meth:`content_collection` property is exposed as
        :meth:`Provider1.content_collection`.
    """

    def __init__(self, provider: "Provider1"):
        """
        Initialize a new provider content enumerator

        :param provider:
            The associated provider
        """
        # NOTE: This code tries to account for two possible layouts. In one
        # layout we don't have the base directory and everything is spread
        # across the filesystem. This is how a packaged provider looks like.
        # The second layout is the old flat layout that is not being used
        # anymore. The only modern exception is when working with a provider
        # from source. To take that into account, the src_dir and build_bin_dir
        # are optional.
        if provider.base_dir:
            dir_list = [provider.base_dir]
            if provider.src_dir:
                dir_list.append(provider.src_dir)
                # NOTE: in source layout we may also see virtual executables
                # that are not loaded yet. Those are listed by
                # "$src_dir/EXECUTABLES"
            if provider.build_bin_dir:
                dir_list.append(provider.build_bin_dir)
            if provider.build_mo_dir:
                dir_list.append(provider.build_mo_dir)
        else:
            dir_list = []
            if provider.units_dir:
                dir_list.append(provider.units_dir)
            if provider.jobs_dir:
                dir_list.append(provider.jobs_dir)
            if provider.data_dir:
                dir_list.append(provider.data_dir)
            if provider.bin_dir:
                dir_list.append(provider.bin_dir)
            if provider.locale_dir:
                dir_list.append(provider.locale_dir)
            if provider.whitelists_dir:
                dir_list.append(provider.whitelists_dir)
        # Find all the files that belong to a provider
        self._content_collection = LazyFsPlugInCollection(
            dir_list, ext=None, recursive=True)

    @property
    def content_collection(self) -> "IPlugInCollection":
        """
        An plugin collection that enumerates all of the files in the provider.

        This collections exposes all of the files in a provider. It can also be
        mocked for easier testing. It is the only part of the provider codebase
        that tries to discover data in a file system.

        .. note::
            By default the collection is **not** loaded. Make sure to call
            ``.load()`` to see the actual data. This is, again, a way to
            simplify testing and to de-couple it from file-system activity.
        """
        return self._content_collection


class ProviderContentClassifier:
    """
    Support class for classifying content inside a provider.

    The primary role of this class is to come up with the role of each file
    inside the provider. That includes all files reachable from any of the
    directories that constitute a provider definition. In addition, each file
    is associated with a *base directory*. This directory can be used to
    re-construct the same provider at a different location or in a different
    layout.

    The secondary role is to provide a hint on what PlugIn to use to load such
    content (as units). In practice the majority of files are loaded with the
    :class:`UnitPlugIn` class. Legacy ``.whitelist`` files are loaded with the
    :class:`WhiteListPlugIn` class instead. All other files are handled by the
    :class:`ProviderContentPlugIn`.

    .. note::
        This class is automatically instantiated by :class:`Provider1`. The
        :meth:`classify` method is exposed as :meth:`Provider1.classify()`.
    """
    LEGAL_SET = frozenset(['COPYING', 'COPYING.LESSER', 'LICENSE'])
    DOC_SET = frozenset(['README', 'README.md', 'README.rst', 'README.txt'])

    def __init__(self, provider: "Provider1"):
        """
        Initialize a new provider content classifier

        :param provider:
            The associated provider
        """
        self.provider = provider
        self._classify_fn_list = None
        self._EXECUTABLES = None

    def classify(self, filename: str) -> "Tuple[Symbol, str, type]":
        """
        Classify a file belonging to the provider

        :param filename:
            Full pathname of the file to classify
        :returns:
            A tuple of information about the file. The first element is the
            :class:`FileRole` symbol that describes the role of the file. The
            second element is the base path of the file. It can be subtracted
            from the actual filename to obtain a relative directory where the
            file needs to be located in case of provider re-location. The last,
            third element is the plug-in class that can be used to load units
            from that file.
        :raises ValueError:
            If the file cannot be classified. This can only happen if the file
            is not in any way related to the provider. All (including random
            junk) files can be classified correctly, as long as they are inside
            one of the well-known directories.
        """
        for fn in self.classify_fn_list:
            result = fn(filename)
            if result is not None:
                return result
        else:
            raise ValueError("Unable to classify: {!r}".format(filename))

    @property
    def classify_fn_list(
        self
    ) -> "List[Callable[[str], Tuple[Symbol, str, type]]]":
        """
        List of functions that aid in the classification process.
        """
        if self._classify_fn_list is None:
            self._classify_fn_list = self._get_classify_fn_list()
        return self._classify_fn_list

    def _get_classify_fn_list(
        self
    ) -> "List[Callable[[str], Tuple[Symbol, str, type]]]":
        """
        Get a list of function that can classify any file reachable from our
        provider. The returned function list depends on which directories are
        present.

        :returns:
            A list of functions ``fn(filename) -> (Symbol, str, plugin_cls)``
            where the return value is a tuple (file_role, base_dir, type).
            The plugin_cls can be used to find all of the units stored in that
            file.
        """
        classify_fn_list = []
        if self.provider.jobs_dir:
            classify_fn_list.append(self._classify_pxu_jobs)
        if self.provider.units_dir:
            classify_fn_list.append(self._classify_pxu_units)
        if self.provider.whitelists_dir:
            classify_fn_list.append(self._classify_whitelist)
        if self.provider.data_dir:
            classify_fn_list.append(self._classify_data)
        if self.provider.bin_dir:
            classify_fn_list.append(self._classify_exec)
        if self.provider.build_bin_dir:
            classify_fn_list.append(self._classify_built_exec)
        if self.provider.build_mo_dir:
            classify_fn_list.append(self._classify_built_i18n)
        if self.provider.build_dir:
            classify_fn_list.append(self._classify_build)
        if self.provider.po_dir:
            classify_fn_list.append(self._classify_po)
        if self.provider.src_dir:
            classify_fn_list.append(self._classify_src)
        if self.provider.base_dir:
            classify_fn_list.append(self._classify_legal)
            classify_fn_list.append(self._classify_docs)
            classify_fn_list.append(self._classify_manage_py)
            classify_fn_list.append(self._classify_vcs)
        # NOTE: this one always has to be last
        classify_fn_list.append(self._classify_unknown)
        return classify_fn_list

    def _get_EXECUTABLES(self):
        assert self.provider.src_dir is not None
        hint_file = os.path.join(self.provider.src_dir, 'EXECUTABLES')
        if os.path.isfile(hint_file):
            with open(hint_file, "rt", encoding='UTF-8') as stream:
                return frozenset(line.strip() for line in stream)
        else:
            return frozenset()

    @property
    def EXECUTABLES(self) -> "Set[str]":
        """
        A set of executables that are expected to be built from source.
        """
        if self._EXECUTABLES is None:
            self._EXECUTABLES = self._get_EXECUTABLES()
        return self._EXECUTABLES

    def _classify_pxu_jobs(self, filename: str):
        """ classify certain files in jobs_dir as unit source"""
        if filename.startswith(self.provider.jobs_dir):
            ext = os.path.splitext(filename)[1]
            if ext in (".txt", ".in", ".pxu"):
                return (FileRole.unit_source, self.provider.jobs_dir,
                        UnitPlugIn)

    def _classify_pxu_units(self, filename: str):
        """ classify certain files in units_dir as unit source"""
        if filename.startswith(self.provider.units_dir):
            ext = os.path.splitext(filename)[1]
            # TODO: later on just let .pxu files in the units_dir
            if ext in (".txt", ".txt.in", ".pxu"):
                return (FileRole.unit_source, self.provider.units_dir,
                        UnitPlugIn)

    def _classify_whitelist(self, filename: str):
        """ classify .whitelist files in whitelist_dir as whitelist """
        if (filename.startswith(self.provider.whitelists_dir) and
                filename.endswith(".whitelist")):
            return (FileRole.legacy_whitelist, self.provider.whitelists_dir,
                    WhiteListPlugIn)

    def _classify_data(self, filename: str):
        """ classify files in data_dir as data """
        if filename.startswith(self.provider.data_dir):
            return (FileRole.data, self.provider.data_dir,
                    ProviderContentPlugIn)

    def _classify_exec(self, filename: str):
        """ classify files in bin_dir as scripts/executables """
        if (filename.startswith(self.provider.bin_dir) and
                os.access(filename, os.F_OK | os.X_OK)):
            with open(filename, 'rb') as stream:
                chunk = stream.read(2)
            role = FileRole.script if chunk == b'#!' else FileRole.binary
            return (role, self.provider.bin_dir, ProviderContentPlugIn)

    def _classify_built_exec(self, filename: str):
        """ classify files in build_bin_dir as scripts/executables """
        if (filename.startswith(self.provider.build_bin_dir) and
                os.access(filename, os.F_OK | os.X_OK) and
                os.path.basename(filename) in self.EXECUTABLES):
            with open(filename, 'rb') as stream:
                chunk = stream.read(2)
            role = FileRole.script if chunk == b'#!' else FileRole.binary
            return (role, self.provider.build_bin_dir, ProviderContentPlugIn)

    def _classify_built_i18n(self, filename: str):
        """ classify files in build_mo_dir as i18n """
        if (filename.startswith(self.provider.build_mo_dir) and
                os.path.splitext(filename)[1] == '.mo'):
            return (FileRole.i18n, self.provider.build_bin_dir,
                    ProviderContentPlugIn)

    def _classify_build(self, filename: str):
        """ classify anything in build_dir as a build artefact """
        if filename.startswith(self.provider.build_dir):
            return (FileRole.build, self.provider.build_dir, None)

    def _classify_legal(self, filename: str):
        """ classify file as a legal document """
        if os.path.basename(filename) in self.LEGAL_SET:
            return (FileRole.legal, self.provider.base_dir,
                    ProviderContentPlugIn)

    def _classify_docs(self, filename: str):
        """ classify certain files as documentation """
        if os.path.basename(filename) in self.DOC_SET:
            return (FileRole.docs, self.provider.base_dir,
                    ProviderContentPlugIn)

    def _classify_manage_py(self, filename: str):
        """ classify the manage.py file """
        if os.path.join(self.provider.base_dir, 'manage.py') == filename:
            return (FileRole.manage_py, self.provider.base_dir, None)

    def _classify_po(self, filename: str):
        if (os.path.dirname(filename) == self.provider.po_dir and
                (os.path.splitext(filename)[1] in ('.po', '.pot') or
                 os.path.basename(filename) == 'POTFILES.in')):
            return (FileRole.src, self.provider.base_dir, None)

    def _classify_src(self, filename: str):
        if filename.startswith(self.provider.src_dir):
            return (FileRole.src, self.provider.base_dir, None)

    def _classify_vcs(self, filename: str):
        if os.path.basename(filename) in ('.gitignore', '.bzrignore'):
            return (FileRole.vcs, self.provider.base_dir, None)
        head = filename
        # NOTE: first condition is for correct cases, the rest are for broken
        # cases that may be caused if we get passed some garbage argument.
        while head != self.provider.base_dir and head != '' and head != '/':
            head, tail = os.path.split(head)
            if tail in ('.git', '.bzr'):
                return (FileRole.vcs, self.provider.base_dir, None)

    def _classify_unknown(self, filename: str):
        """ classify anything as an unknown file """
        return (FileRole.unknown, self.provider.base_dir, None)


class ProviderContentLoader:
    """
    Support class for enumerating provider content.

    The only role of this class is to expose a plug in collection that can
    enumerate all of the files reachable from a provider. This collection
    is consumed by other parts of provider loading machinery.

    Since it is a stock plug in collection it can be easily "mocked" to provide
    alternate content without involving modifications of the real file system.

    .. note::
        This class is automatically instantiated by :class:`Provider1`. All
        four attributes of this class are directly exposed as properties on the
        provider object.

    :attr provider:
        The provider back-reference
    :attr is_loaded:
        Flag indicating if the content loader has loaded all of the content
    :attr unit_list:
        A list of loaded whitelist objects
    :attr problem_list:
        A list of problems experienced while loading any of the content
    :attr path_map:
        A dictionary mapping from the path of each file to the list of units
        stored there.
    :attr id_map:
        A dictionary mapping from the identifier of each unit to the list of
        units that have that identifier.
    """

    def __init__(self, provider):
        self.provider = provider
        self.is_loaded = False
        self.unit_list = []
        self.whitelist_list = []
        self.problem_list = []
        self.path_map = collections.defaultdict(list)  # path -> list(unit)
        self.id_map = collections.defaultdict(list)  # id -> list(unit)

    def load(self, plugin_kwargs):
        logger.info("Loading content for provider %s", self.provider)
        self.provider.content_collection.load()
        for file_plugin in self.provider.content_collection.get_all_plugins():
            filename = file_plugin.plugin_name
            text = file_plugin.plugin_object
            self._load_file(filename, text, plugin_kwargs)
        self.problem_list.extend(self.provider.content_collection.problem_list)
        self.is_loaded = True

    def _load_file(self, filename, text, plugin_kwargs):
        # NOTE: text is lazy, call str() or iter() to see the real content This
        # prevents us from trying to read binary blobs.
        classification = self.provider.classify(filename)
        role, base_dir, plugin_cls = classification
        if plugin_cls is None:
            return
        try:
            plugin = plugin_cls(
                filename, text, 0, self.provider, **plugin_kwargs)
        except PlugInError as exc:
            self.problem_list.append(exc)
        else:
            self.unit_list.extend(plugin.unit_list)
            self.whitelist_list.extend(plugin.whitelist_list)
            for unit in plugin.unit_list:
                if hasattr(unit.Meta.fields, 'id'):
                    self.id_map[unit.id].append(unit)
                if hasattr(unit.Meta.fields, 'path'):
                    self.path_map[unit.path].append(unit)


class Provider1(IProvider1):
    """
    A v1 provider implementation.

    A provider is a container of jobs and whitelists. It provides additional
    meta-data and knows about location of essential directories to both load
    structured data and provide runtime information for job execution.

    Providers are normally loaded with :class:`Provider1PlugIn`, due to the
    number of fields involved in basic initialization.
    """

    def __init__(self, name, namespace, version, description, secure,
                 gettext_domain, units_dir, jobs_dir, whitelists_dir, data_dir,
                 bin_dir, locale_dir, base_dir, *, validate=False,
                 validation_kwargs=None, check=True, context=None):
        """
        Initialize a provider with a set of meta-data and directories.

        :param name:
            provider name / ID

        :param namespace:
            provider namespace

        :param version:
            provider version

        :param description:
            provider version

            This is the untranslated version of this field. Implementations may
            obtain the localized version based on the gettext_domain property.

        :param secure:
            secure bit

            When True jobs from this provider should be available via the
            trusted launcher mechanism. It should be set to True for
            system-wide installed providers.

        :param gettext_domain:
            gettext domain that contains translations for this provider

        :param units_dir:
            path of the directory with unit definitions

        :param jobs_dir:
            path of the directory with job definitions

        :param whitelists_dir:
            path of the directory with whitelists definitions (aka test-plans)

        :param data_dir:
            path of the directory with files used by jobs at runtime

        :param bin_dir:
            path of the directory with additional executables

        :param locale_dir:
            path of the directory with locale database (translation catalogs)

        :param base_dir:
            path of the directory with (perhaps) all of jobs_dir,
            whitelists_dir, data_dir, bin_dir, locale_dir. This may be None.
            This is also the effective value of $CHECKBOX_SHARE

        :param validate:
            Enable job validation. Incorrect job definitions will not be loaded
            and will abort the process of loading of the remainder of the jobs.
            This is ON by default to prevent broken job definitions from being
            used. This is a keyword-only argument.

        :param validation_kwargs:
            Keyword arguments to pass to the JobDefinition.validate().  Note,
            this is a single argument. This is a keyword-only argument.
        """
        # Meta-data
        if namespace is None:
            namespace = name.split(':', 1)[0]
            self._has_dedicated_namespace = False
        else:
            self._has_dedicated_namespace = True
        self._name = name
        self._namespace = namespace
        self._version = version
        self._description = description
        self._secure = secure
        self._gettext_domain = gettext_domain
        # Directories
        self._units_dir = units_dir
        self._jobs_dir = jobs_dir
        self._whitelists_dir = whitelists_dir
        self._data_dir = data_dir
        self._bin_dir = bin_dir
        self._locale_dir = locale_dir
        self._base_dir = base_dir
        # Create support classes
        self._enumerator = ProviderContentEnumerator(self)
        self._classifier = ProviderContentClassifier(self)
        self._loader = ProviderContentLoader(self)
        self._load_kwargs = {
            'validate': validate,
            'validation_kwargs': validation_kwargs,
            'check': check,
            'context': context,
        }
        # Setup provider specific i18n
        self._setup_translations()
        logger.info("Provider initialized %s", self)

    def _ensure_loaded(self):
        if not self._loader.is_loaded:
            self._loader.load(self._load_kwargs)

    def _load_whitelists(self):
        self._ensure_loaded()

    def _load_units(self, validate, validation_kwargs, check, context):
        self._ensure_loaded()

    def _setup_translations(self):
        if self._gettext_domain and self._locale_dir:
            gettext.bindtextdomain(self._gettext_domain, self._locale_dir)

    @classmethod
    def from_definition(cls, definition, secure, *,
                        validate=False, validation_kwargs=None, check=True,
                        context=None):
        """
        Initialize a provider from Provider1Definition object

        :param definition:
            A Provider1Definition object to use as reference
        :param secure:
            Value of the secure flag. This cannot be expressed by a definition
            object.
        :param validate:
            Enable job validation. Incorrect job definitions will not be loaded
            and will abort the process of loading of the remainder of the jobs.
            This is ON by default to prevent broken job definitions from being
            used. This is a keyword-only argument.
        :param validation_kwargs:
            Keyword arguments to pass to the JobDefinition.validate().  Note,
            this is a single argument. This is a keyword-only argument.

        This method simplifies initialization of a Provider1 object where the
        caller already has a Provider1Definition object. Depending on the value
        of ``definition.location`` all of the directories are either None or
        initialized to a *good* (typical) value relative to *location*

        The only value that you may want to adjust, for working with source
        providers, is *locale_dir*, by default it would be ``location/locale``
        but ``manage.py i18n`` creates ``location/build/mo``
        """
        logger.debug("Loading provider from definition %r", definition)
        # Initialize the provider object
        return cls(
            definition.name, definition.namespace or None, definition.version,
            definition.description, secure,
            definition.effective_gettext_domain,
            definition.effective_units_dir, definition.effective_jobs_dir,
            definition.effective_whitelists_dir, definition.effective_data_dir,
            definition.effective_bin_dir, definition.effective_locale_dir,
            definition.location or None, validate=validate,
            validation_kwargs=validation_kwargs, check=check, context=context)

    def __repr__(self):
        return "<{} name:{!r}>".format(self.__class__.__name__, self.name)

    def __str__(self):
        return "{}, version {}".format(self.name, self.version)

    @property
    def name(self):
        """
        name of this provider
        """
        return self._name

    @property
    def namespace(self):
        """
        namespace component of the provider name

        This property defines the namespace in which all provider jobs are
        defined in. Jobs within one namespace do not need to be fully qualified
        by prefixing their partial identifier with provider namespace (so all
        stays 'as-is'). Jobs that need to interact with other provider
        namespaces need to use the fully qualified job identifier instead.

        The identifier is defined as the part of the provider name, up to the
        colon. This effectively gives organizations flat namespace within one
        year-domain pair and allows to create private namespaces by using
        sub-domains.
        """
        return self._namespace

    @property
    def has_dedicated_namespace(self):
        """Flag set if namespace was defined by a dedicated field."""
        return self._has_dedicated_namespace

    @property
    def version(self):
        """
        version of this provider
        """
        return self._version

    @property
    def description(self):
        """
        description of this provider
        """
        return self._description

    def tr_description(self):
        """
        Get the translated version of :meth:`description`
        """
        return self.get_translated_data(self.description)

    @property
    def units_dir(self):
        """
        absolute path of the units directory
        """
        return self._units_dir

    @property
    def jobs_dir(self):
        """
        absolute path of the jobs directory
        """
        return self._jobs_dir

    @property
    def whitelists_dir(self):
        """
        absolute path of the whitelist directory
        """
        return self._whitelists_dir

    @property
    def data_dir(self):
        """
        absolute path of the data directory
        """
        return self._data_dir

    @property
    def bin_dir(self):
        """
        absolute path of the bin directory

        .. note::
            The programs in that directory may not work without setting
            PYTHONPATH and CHECKBOX_SHARE.
        """
        return self._bin_dir

    @property
    def locale_dir(self):
        """
        absolute path of the directory with locale data

        The value is applicable as argument bindtextdomain()
        """
        return self._locale_dir

    @property
    def base_dir(self):
        """
        path of the directory with (perhaps) all of jobs_dir, whitelists_dir,
        data_dir, bin_dir, locale_dir. This may be None
        """
        return self._base_dir

    @property
    def build_dir(self):
        """
        absolute path of the build directory

        This value may be None. It depends on location/base_dir being set.
        """
        if self.base_dir is not None:
            return os.path.join(self.base_dir, 'build')

    @property
    def build_bin_dir(self):
        """
        absolute path of the build/bin directory

        This value may be None. It depends on location/base_dir being set.
        """
        if self.base_dir is not None:
            return os.path.join(self.base_dir, 'build', 'bin')

    @property
    def build_mo_dir(self):
        """
        absolute path of the build/mo directory

        This value may be None. It depends on location/base_dir being set.
        """
        if self.base_dir is not None:
            return os.path.join(self.base_dir, 'build', 'mo')

    @property
    def src_dir(self):
        """
        absolute path of the src/ directory

        This value may be None. It depends on location/base_dir set.
        """
        if self.base_dir is not None:
            return os.path.join(self.base_dir, 'src')

    @property
    def po_dir(self):
        """
        absolute path of the po/ directory

        This value may be None. It depends on location/base_dir set.
        """
        if self.base_dir is not None:
            return os.path.join(self.base_dir, 'po')

    @property
    def CHECKBOX_SHARE(self):
        """
        required value of CHECKBOX_SHARE environment variable.

        .. note::
            This variable is only required by one script.
            It would be nice to remove this later on.
        """
        return self.base_dir

    @property
    def extra_PYTHONPATH(self):
        """
        additional entry for PYTHONPATH, if needed.

        This entry is required for CheckBox scripts to import the correct
        CheckBox python libraries.

        .. note::
            The result may be None
        """
        return None

    @property
    def secure(self):
        """
        flag indicating that this provider was loaded from the secure portion
        of PROVIDERPATH and thus can be used with the
        plainbox-trusted-launcher-1.
        """
        return self._secure

    @property
    def gettext_domain(self):
        """
        the name of the gettext domain associated with this provider

        This value may be empty, in such case provider data cannot be localized
        for the user environment.
        """
        return self._gettext_domain

    @property
    def unit_list(self):
        """
        List of loaded units.

        This list may contain units of various types. You should not assume all
        of them are :class:`JobDefinition` instances. You may use filtering to
        obtain units of a given type.

            >>> [unit for unit in provider.unit_list
            ...  if unit.Meta.name == 'job']
            [...]
        """
        self._ensure_loaded()
        return self._loader.unit_list

    @property
    def job_list(self):
        """
        A sorted list of loaded job definition units.
        """
        return sorted(
            (unit for unit in self.unit_list if unit.Meta.name == 'job'),
            key=lambda unit: unit.id)

    @property
    def executable_list(self):
        """
        List of all the executables
        """
        return sorted(
            unit.path for unit in self.unit_list
            if unit.Meta.name == 'file' and
            unit.role in (FileRole.script, FileRole.binary))

    @property
    def whitelist_list(self):
        """
        List of loaded whitelists.

        .. warning::
            :class:`WhiteList` is currently deprecated. You should never need
            to access them in any new code.  They are entirely replaced by
            :class:`TestPlan`. This property is provided for completeness and
            it will be **removed** once whitelists classes are no longer used.
        """
        self._ensure_loaded()
        return self._loader.whitelist_list

    @property
    def problem_list(self):
        """
        list of problems encountered by the loading process
        """
        self._ensure_loaded()
        return self._loader.problem_list

    @property
    def id_map(self):
        """
        A mapping from unit identifier to list of units with that identifier.

        .. note::
            Typically the list will be one element long but invalid providers
            may break that guarantee. Code defensively if you can.
        """
        self._ensure_loaded()
        return self._loader.id_map

    @property
    def path_map(self):
        """
        A mapping from filename path to a list of units stored in that file.

        .. note::
            For ``.pxu`` files this will enumerate all units stored there. For
            other things it will typically be just the FileUnit.
        """
        self._ensure_loaded()
        return self._loader.path_map

    def get_translated_data(self, msgid):
        """
        Get a localized piece of data

        :param msgid:
            data to translate
        :returns:
            translated data obtained from the provider if msgid is not False
            (empty string and None both are) and this provider has a
            gettext_domain defined for it, msgid itself otherwise.
        """
        if msgid and self._gettext_domain:
            return gettext.dgettext(self._gettext_domain, msgid)
        else:
            return msgid

    @property
    def classify(self):
        """
        Exposed :meth:`ProviderContentClassifier.classify()`
        """
        return self._classifier.classify

    @property
    def content_collection(self) -> "IPlugInCollection":
        """
        Exposed :meth:`ProviderContentEnumerator.content_collection`
        """
        return self._enumerator.content_collection

    @property
    def fake(self):
        """
        Bridge to ``.content_collection.fake_plugins`` that's shorter to type.
        """
        return self._enumerator.content_collection.fake_plugins


class IQNValidator(PatternValidator):
    """
    A validator for provider name.

    Provider names use a RFC3720 IQN-like identifiers composed of the follwing
    parts:

    * year
    * (dot separating the next section)
    * domain name
    * (colon separating the next section)
    * identifier

    Each of the fields has an informal definition below:

        year:
            four digit number
        domain name:
            identifiers separated by dots, at least one dot has to be present
        identifier:
            `[a-z][a-z0-9-]*`
    """

    def __init__(self):
        super(IQNValidator, self).__init__(
            "^[0-9]{4}\.[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+:[a-z][a-z0-9-]*$")

    def __call__(self, variable, new_value):
        if super(IQNValidator, self).__call__(variable, new_value):
            return _("must look like RFC3720 IQN")


class ProviderNameValidator(PatternValidator):

    """
    Validator for the provider name.

    Two forms are allowed:

        - short form (requires a separate namespace definition)
        - verbose form (based on RFC3720 IQN-like strings)

    The short form is supposed to look like Debian package name.
    """

    _PATTERN = (
        "^"
        "([0-9]{4}\.[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+:[a-z][a-z0-9-]*)"
        "|"
        "([a-z0-9-]+)"
        "$"
    )

    def __init__(self):
        super().__init__(self._PATTERN)

    def __call__(self, variable, new_value):
        if super().__call__(variable, new_value):
            return _("must look like RFC3720 IQN")


class VersionValidator(PatternValidator):
    """
    A validator for provider provider version.

    Provider version must be a sequence of non-negative numbers separated by
    dots. At most one version number must be present, which may be followed by
    any sub-versions.
    """

    def __init__(self):
        super().__init__("^[0-9]+(\.[0-9]+)*$")

    def __call__(self, variable, new_value):
        if super().__call__(variable, new_value):
            return _("must be a sequence of digits separated by dots")


class ExistingDirectoryValidator(IValidator):
    """
    A validator that checks that the value points to an existing directory
    """

    def __call__(self, variable, new_value):
        if not os.path.isdir(new_value):
            return _("no such directory")


class AbsolutePathValidator(IValidator):
    """
    A validator that checks that the value is an absolute path
    """

    def __call__(self, variable, new_value):
        if not os.path.isabs(new_value):
            return _("cannot be relative")


class Provider1Definition(Config):
    """
    A Config-like class for parsing plainbox provider definition files

    .. note::

        The location attribute is special, if set, it defines the base
        directory of *all* the other directory attributes. If location is
        unset, then all the directory attributes default to None (that is,
        there is no directory of that type). This is actually a convention that
        is implemented in :class:`Provider1PlugIn`. Here, all the attributes
        can be Unset and their validators only check values other than Unset.
    """

    # NOTE: See the implementation note in :class:`Provider1PluginIn` to
    # understand the effect of this flag.
    relocatable = Variable(
        section='PlainBox Provider',
        help_text=_("Flag indicating if the provider is relocatable"),
        kind=bool,
    )

    location = Variable(
        section='PlainBox Provider',
        help_text=_("Base directory with provider data"),
        validator_list=[
            # NOTE: it *can* be unset!
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    name = Variable(
        section='PlainBox Provider',
        help_text=_("Name of the provider"),
        validator_list=[
            NotUnsetValidator(),
            NotEmptyValidator(),
            ProviderNameValidator(),
        ])

    namespace = Variable(
        section='PlainBox Provider',
        help_text=_("Namespace of the provider"),
        validator_list=[
            # NOTE: it *can* be unset, then name must be IQN
            NotEmptyValidator(),
        ])

    @property
    def name_without_colon(self):
        if ':' in self.name:
            return self.name.replace(':', '.')
        else:
            return self.name

    version = Variable(
        section='PlainBox Provider',
        help_text=_("Version of the provider"),
        validator_list=[
            NotUnsetValidator(),
            NotEmptyValidator(),
            VersionValidator(),
        ])

    description = Variable(
        section='PlainBox Provider',
        help_text=_("Description of the provider"))

    gettext_domain = Variable(
        section='PlainBox Provider',
        help_text=_("Name of the gettext domain for translations"),
        validator_list=[
            # NOTE: it *can* be unset!
            PatternValidator("[a-z0-9_-]+"),
        ])

    @property
    def effective_gettext_domain(self):
        """
        effective value of gettext_domian

        The effective value is :meth:`gettex_domain` itself, unless it is
        Unset. If it is Unset the effective value None.
        """
        if self.gettext_domain is not Unset:
            return self.gettext_domain

    units_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with unit definitions"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_units_dir(self):
        """
        implicit value of units_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'units' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "units")

    @property
    def effective_units_dir(self):
        """
        effective value of units_dir

        The effective value is :meth:`units_dir` itself, unless it is Unset. If
        it is Unset the effective value is the :meth:`implicit_units_dir`, if
        that value would be valid. The effective value may be None.
        """
        if self.units_dir is not Unset:
            return self.units_dir
        implicit = self.implicit_units_dir
        if implicit is not None and os.path.isdir(implicit):
            return implicit

    jobs_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with job definitions"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_jobs_dir(self):
        """
        implicit value of jobs_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'jobs' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "jobs")

    @property
    def effective_jobs_dir(self):
        """
        effective value of jobs_dir

        The effective value is :meth:`jobs_dir` itself, unless it is Unset. If
        it is Unset the effective value is the :meth:`implicit_jobs_dir`, if
        that value would be valid. The effective value may be None.
        """
        if self.jobs_dir is not Unset:
            return self.jobs_dir
        implicit = self.implicit_jobs_dir
        if implicit is not None and os.path.isdir(implicit):
            return implicit

    whitelists_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with whitelists definitions"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_whitelists_dir(self):
        """
        implicit value of whitelists_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'whitelists' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "whitelists")

    @property
    def effective_whitelists_dir(self):
        """
        effective value of whitelists_dir

        The effective value is :meth:`whitelists_dir` itself, unless it is
        Unset. If it is Unset the effective value is the
        :meth:`implicit_whitelists_dir`, if that value would be valid. The
        effective value may be None.
        """
        if self.whitelists_dir is not Unset:
            return self.whitelists_dir
        implicit = self.implicit_whitelists_dir
        if implicit is not None and os.path.isdir(implicit):
            return implicit

    data_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with provider data"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_data_dir(self):
        """
        implicit value of data_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'data' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "data")

    @property
    def effective_data_dir(self):
        """
        effective value of data_dir

        The effective value is :meth:`data_dir` itself, unless it is Unset. If
        it is Unset the effective value is the :meth:`implicit_data_dir`, if
        that value would be valid. The effective value may be None.
        """
        if self.data_dir is not Unset:
            return self.data_dir
        implicit = self.implicit_data_dir
        if implicit is not None and os.path.isdir(implicit):
            return implicit

    bin_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with provider executables"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_bin_dir(self):
        """
        implicit value of bin_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'bin' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "bin")

    @property
    def effective_bin_dir(self):
        """
        effective value of bin_dir

        The effective value is :meth:`bin_dir` itself, unless it is Unset. If
        it is Unset the effective value is the :meth:`implicit_bin_dir`, if
        that value would be valid. The effective value may be None.
        """
        if self.bin_dir is not Unset:
            return self.bin_dir
        implicit = self.implicit_bin_dir
        if implicit is not None and os.path.isdir(implicit):
            return implicit

    locale_dir = Variable(
        section='PlainBox Provider',
        help_text=_("Pathname of the directory with locale data"),
        validator_list=[
            # NOTE: it *can* be unset
            NotEmptyValidator(),
            AbsolutePathValidator(),
            ExistingDirectoryValidator(),
        ])

    @property
    def implicit_locale_dir(self):
        """
        implicit value of locale_dir (if Unset)

        The implicit value is only defined if location is not Unset. It is the
        'locale' subdirectory of the directory that location points to.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "locale")

    @property
    def implicit_build_locale_dir(self):
        """
        implicit value of locale_dir (if Unset) as laid out in the source tree

        This value is only applicable to source layouts, where the built
        translation catalogs are in the build/mo directory.
        """
        if self.location is not Unset:
            return os.path.join(self.location, "build", "mo")

    @property
    def effective_locale_dir(self):
        """
        effective value of locale_dir

        The effective value is :meth:`locale_dir` itself, unless it is Unset.
        If it is Unset the effective value is the :meth:`implicit_locale_dir`,
        if that value would be valid. The effective value may be None.
        """
        if self.locale_dir is not Unset:
            return self.locale_dir
        implicit1 = self.implicit_locale_dir
        if implicit1 is not None and os.path.isdir(implicit1):
            return implicit1
        implicit2 = self.implicit_build_locale_dir
        if implicit2 is not None and os.path.isdir(implicit2):
            return implicit2

    def validate_whole(self):
        """
        Validate the provider definition object.

        :raises ValidationError:
            If the namespace is not defined and name is using a simplified
            format that doesn't contain an embedded namespace part.
        """
        super().validate_whole()
        if not self.namespace:
            variable = self.__class__.name
            value = self.name
            validator = IQNValidator()
            message = validator(variable, value)
            if message is not None:
                raise ConfigValidationError(variable, value, message)


class Provider1PlugIn(PlugIn):
    """
    A specialized IPlugIn that loads Provider1 instances from their definition
    files
    """

    def __init__(self, filename, definition_text, load_time, *, validate=None,
                 validation_kwargs=None, check=None, context=None):
        """
        Initialize the plug-in with the specified name and external object
        """
        start = now()
        self._load_time = load_time
        definition = Provider1Definition()
        # Load the provider definition
        definition.read_string(definition_text)
        # If the relocatable flag is set, set location to the base directory of
        # the filename and reset all the other directories (to Unset). This is
        # to allow creation of .provider files that can be moved entirely, and
        # as long as they follow the implicit source layout, they will work
        # okay.
        if definition.relocatable:
            definition.location = os.path.dirname(filename)
            definition.units_dir = Unset
            definition.jobs_dir = Unset
            definition.whitelists_dir = Unset
            definition.data_dir = Unset
            definition.bin_dir = Unset
            definition.locale_dir = Unset
        # any validation issues prevent plugin from being used
        if definition.problem_list:
            # take the earliest problem and report it
            exc = definition.problem_list[0]
            raise PlugInError(
                _("Problem in provider definition, field {!a}: {}").format(
                    exc.variable.name, exc.message))
        # Get the secure flag
        secure = os.path.dirname(filename) in get_secure_PROVIDERPATH_list()
        # Initialize the provider object
        provider = Provider1.from_definition(
            definition, secure, validate=validate,
            validation_kwargs=validation_kwargs, check=check, context=context)
        wrap_time = now() - start
        super().__init__(provider.name, provider, load_time, wrap_time)

    def __repr__(self):
        return "<{!s} plugin_name:{!r}>".format(
            type(self).__name__, self.plugin_name)


def get_secure_PROVIDERPATH_list():
    """
    Computes the secure value of PROVIDERPATH

    This value is used by `plainbox-trusted-launcher-1` executable to discover
    all secure providers.

    :returns:
        A list of two strings:
        * `/usr/local/share/plainbox-providers-1`
        * `/usr/share/plainbox-providers-1`
    """
    return ["/usr/local/share/plainbox-providers-1",
            "/usr/share/plainbox-providers-1"]


class SecureProvider1PlugInCollection(FsPlugInCollection):
    """
    A collection of v1 provider plugins.

    This FsPlugInCollection subclass carries proper, built-in defaults, that
    make loading providers easier.

    This particular class loads providers from the system-wide managed
    locations. This defines the security boundary, as if someone can compromise
    those locations then they already own the corresponding system. In
    consequence this plug in collection does not respect ``PROVIDERPATH``, it
    cannot be customized to load provider definitions from any other location.
    This feature is supported by the
    :class:`plainbox.impl.providers.v1.InsecureProvider1PlugInCollection`
    """

    def __init__(self, **kwargs):
        dir_list = get_secure_PROVIDERPATH_list()
        super().__init__(dir_list, '.provider', wrapper=Provider1PlugIn,
                         **kwargs)


# Collection of all providers
all_providers = SecureProvider1PlugInCollection()