Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
// Copyright 2012 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in the
//   documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
//   may be used to endorse or promote products derived from this software
//   without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "engine/metadata.hpp"

#include <memory>

#include "engine/exceptions.hpp"
#include "utils/config/exceptions.hpp"
#include "utils/config/nodes.ipp"
#include "utils/config/tree.ipp"
#include "utils/datetime.hpp"
#include "utils/defs.hpp"
#include "utils/format/macros.hpp"
#include "utils/fs/exceptions.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/memory.hpp"
#include "utils/passwd.hpp"
#include "utils/sanity.hpp"
#include "utils/text/exceptions.hpp"
#include "utils/text/operations.hpp"
#include "utils/units.hpp"

namespace config = utils::config;
namespace datetime = utils::datetime;
namespace fs = utils::fs;
namespace passwd = utils::passwd;
namespace text = utils::text;
namespace units = utils::units;


/// The default timeout value for test cases that do not provide one.
/// TODO(jmmv): We should not be doing this; see issue 5 for details.
datetime::delta engine::default_timeout(300, 0);


namespace {


/// A leaf node that holds a bytes quantity.
class bytes_node : public config::native_leaf_node< units::bytes > {
public:
    /// Copies the node.
    ///
    /// \return A dynamically-allocated node.
    virtual base_node*
    deep_copy(void) const
    {
        std::auto_ptr< bytes_node > new_node(new bytes_node());
        new_node->_value = _value;
        return new_node.release();
    }

    /// Pushes the node's value onto the Lua stack.
    ///
    /// \param unused_state The Lua state onto which to push the value.
    void
    push_lua(lutok::state& UTILS_UNUSED_PARAM(state)) const
    {
        UNREACHABLE;
    }

    /// Sets the value of the node from an entry in the Lua stack.
    ///
    /// \param unused_state The Lua state from which to get the value.
    /// \param unused_index The stack index in which the value resides.
    void
    set_lua(lutok::state& UTILS_UNUSED_PARAM(state),
            const int UTILS_UNUSED_PARAM(index))
    {
        UNREACHABLE;
    }
};


/// A leaf node that holds a time delta.
class delta_node : public config::typed_leaf_node< datetime::delta > {
public:
    /// Copies the node.
    ///
    /// \return A dynamically-allocated node.
    virtual base_node*
    deep_copy(void) const
    {
        std::auto_ptr< delta_node > new_node(new delta_node());
        new_node->_value = _value;
        return new_node.release();
    }

    /// Sets the value of the node from a raw string representation.
    ///
    /// \param raw_value The value to set the node to.
    ///
    /// \throw value_error If the value is invalid.
    void
    set_string(const std::string& raw_value)
    {
        unsigned int seconds;
        try {
            seconds = text::to_type< unsigned int >(raw_value);
        } catch (const text::error& e) {
            throw config::value_error(F("Invalid time delta %s") % raw_value);
        }
        set(datetime::delta(seconds, 0));
    }

    /// Converts the contents of the node to a string.
    ///
    /// \pre The node must have a value.
    ///
    /// \return A string representation of the value held by the node.
    std::string
    to_string(void) const
    {
        return F("%s") % value().seconds;
    }

    /// Pushes the node's value onto the Lua stack.
    ///
    /// \param unused_state The Lua state onto which to push the value.
    void
    push_lua(lutok::state& UTILS_UNUSED_PARAM(state)) const
    {
        UNREACHABLE;
    }

    /// Sets the value of the node from an entry in the Lua stack.
    ///
    /// \param unused_state The Lua state from which to get the value.
    /// \param unused_index The stack index in which the value resides.
    void
    set_lua(lutok::state& UTILS_UNUSED_PARAM(state),
            const int UTILS_UNUSED_PARAM(index))
    {
        UNREACHABLE;
    }
};


/// A leaf node that holds a "required user" property.
///
/// This node is just a string, but it provides validation of the only allowed
/// values.
class user_node : public config::string_node {
    /// Copies the node.
    ///
    /// \return A dynamically-allocated node.
    virtual base_node*
    deep_copy(void) const
    {
        std::auto_ptr< user_node > new_node(new user_node());
        new_node->_value = _value;
        return new_node.release();
    }

    /// Checks a given user textual representation for validity.
    ///
    /// \param user The value to validate.
    ///
    /// \throw config::value_error If the value is not valid.
    void
    validate(const value_type& user) const
    {
        if (!user.empty() && user != "root" && user != "unprivileged")
            throw config::value_error("Invalid required user value");
    }
};


/// A leaf node that holds a set of paths.
///
/// This node type is used to represent the value of the required files and
/// required programs, for example, and these do not allow relative paths.  We
/// check this here.
class paths_set_node : public config::base_set_node< fs::path > {
    /// Copies the node.
    ///
    /// \return A dynamically-allocated node.
    virtual base_node*
    deep_copy(void) const
    {
        std::auto_ptr< paths_set_node > new_node(new paths_set_node());
        new_node->_value = _value;
        return new_node.release();
    }

    /// Converts a single path to the native type.
    ///
    /// \param raw_value The value to parse.
    ///
    /// \return The parsed value.
    ///
    /// \throw config::value_error If the value is invalid.
    fs::path
    parse_one(const std::string& raw_value) const
    {
        try {
            return fs::path(raw_value);
        } catch (const fs::error& e) {
            throw config::value_error(e.what());
        }
    }

    /// Checks a collection of paths for validity.
    ///
    /// \param paths The value to validate.
    ///
    /// \throw config::value_error If the value is not valid.
    void
    validate(const value_type& paths) const
    {
        for (value_type::const_iterator iter = paths.begin();
             iter != paths.end(); ++iter) {
            const fs::path& path = *iter;
            if (!path.is_absolute() && path.ncomponents() > 1)
                throw config::value_error(F("Relative path '%s' not allowed") %
                                          *iter);
        }
    }
};


/// Initializes a tree to hold test case requirements.
///
/// \param [in,out] tree The tree to initialize.
static void
init_tree(config::tree& tree)
{
    tree.define< config::strings_set_node >("allowed_architectures");
    tree.set< config::strings_set_node >("allowed_architectures",
                                         engine::strings_set());

    tree.define< config::strings_set_node >("allowed_platforms");
    tree.set< config::strings_set_node >("allowed_platforms",
                                         engine::strings_set());

    tree.define_dynamic("custom");

    tree.define< config::string_node >("description");
    tree.set< config::string_node >("description", "");

    tree.define< config::bool_node >("has_cleanup");
    tree.set< config::bool_node >("has_cleanup", false);

    tree.define< config::strings_set_node >("required_configs");
    tree.set< config::strings_set_node >("required_configs",
                                         engine::strings_set());

    tree.define< paths_set_node >("required_files");
    tree.set< paths_set_node >("required_files", engine::paths_set());

    tree.define< bytes_node >("required_memory");
    tree.set< bytes_node >("required_memory", units::bytes(0));

    tree.define< paths_set_node >("required_programs");
    tree.set< paths_set_node >("required_programs", engine::paths_set());

    tree.define< user_node >("required_user");
    tree.set< user_node >("required_user", "");

    tree.define< delta_node >("timeout");
    tree.set< delta_node >("timeout", engine::default_timeout);
}


/// Looks up a value in a tree with error rewriting.
///
/// \tparam NodeType The type of the node.
/// \param tree The tree in which to insert the value.
/// \param key The key to set.
///
/// \return A read-write reference to the value in the node.
///
/// \throw engine::error If the key is not known or if the value is not valid.
template< class NodeType >
typename NodeType::value_type&
lookup_rw(config::tree& tree, const std::string& key)
{
    try {
        return tree.lookup_rw< NodeType >(key);
    } catch (const config::unknown_key_error& e) {
        throw engine::error(F("Unknown metadata property %s") % key);
    } catch (const config::value_error& e) {
        throw engine::error(F("Invalid value for metadata property %s: %s") %
                            key % e.what());
    }
}


/// Sets a value in a tree with error rewriting.
///
/// \tparam NodeType The type of the node.
/// \param tree The tree in which to insert the value.
/// \param key The key to set.
/// \param value The value to set the node to.
///
/// \throw engine::error If the key is not known or if the value is not valid.
template< class NodeType >
void
set(config::tree& tree, const std::string& key,
    const typename NodeType::value_type& value)
{
    try {
        tree.set< NodeType >(key, value);
    } catch (const config::unknown_key_error& e) {
        throw engine::error(F("Unknown metadata property %s") % key);
    } catch (const config::value_error& e) {
        throw engine::error(F("Invalid value for metadata property %s: %s") %
                            key % e.what());
    }
}


/// Checks if all required configuration variables are present.
///
/// \param required_configs Set of required variable names.
/// \param user_config Runtime user configuration.
/// \param test_suite_name Name of the test suite the test belongs to.
///
/// \return Empty if all variables are present or an error message otherwise.
static std::string
check_required_configs(const engine::strings_set& required_configs,
                       const config::tree& user_config,
                       const std::string& test_suite_name)
{
    for (engine::strings_set::const_iterator iter = required_configs.begin();
         iter != required_configs.end(); iter++) {
        std::string property;
        // TODO(jmmv): All this rewrite logic belongs in the ATF interface.
        if ((*iter) == "unprivileged-user" || (*iter) == "unprivileged_user")
            property = "unprivileged_user";
        else
            property = F("test_suites.%s.%s") % test_suite_name % (*iter);

        if (!user_config.is_set(property))
            return F("Required configuration property '%s' not defined") %
                (*iter);
    }
    return "";
}


/// Checks if the allowed architectures match the current architecture.
///
/// \param allowed_architectures Set of allowed architectures.
/// \param user_config Runtime user configuration.
///
/// \return Empty if the current architecture is in the list or an error
/// message otherwise.
static std::string
check_allowed_architectures(const engine::strings_set& allowed_architectures,
                            const config::tree& user_config)
{
    if (!allowed_architectures.empty()) {
        const std::string architecture =
            user_config.lookup< config::string_node >("architecture");
        if (allowed_architectures.find(architecture) ==
            allowed_architectures.end())
            return F("Current architecture '%s' not supported") % architecture;
    }
    return "";
}


/// Checks if the allowed platforms match the current architecture.
///
/// \param allowed_platforms Set of allowed platforms.
/// \param user_config Runtime user configuration.
///
/// \return Empty if the current platform is in the list or an error message
/// otherwise.
static std::string
check_allowed_platforms(const engine::strings_set& allowed_platforms,
                        const config::tree& user_config)
{
    if (!allowed_platforms.empty()) {
        const std::string platform =
            user_config.lookup< config::string_node >("platform");
        if (allowed_platforms.find(platform) == allowed_platforms.end())
            return F("Current platform '%s' not supported") % platform;
    }
    return "";
}


/// Checks if the current user matches the required user.
///
/// \param required_user Name of the required user category.
/// \param user_config Runtime user configuration.
///
/// \return Empty if the current user fits the required user characteristics or
/// an error message otherwise.
static std::string
check_required_user(const std::string& required_user,
                    const config::tree& user_config)
{
    if (!required_user.empty()) {
        const passwd::user user = passwd::current_user();
        if (required_user == "root") {
            if (!user.is_root())
                return "Requires root privileges";
        } else if (required_user == "unprivileged") {
            if (user.is_root())
                if (!user_config.is_set("unprivileged_user"))
                    return "Requires an unprivileged user but the "
                        "unprivileged-user configuration variable is not "
                        "defined";
        } else
            UNREACHABLE_MSG("Value of require.user not properly validated");
    }
    return "";
}


/// Checks if all required files exist.
///
/// \param required_files Set of paths.
///
/// \return Empty if the required files all exist or an error message otherwise.
static std::string
check_required_files(const engine::paths_set& required_files)
{
    for (engine::paths_set::const_iterator iter = required_files.begin();
         iter != required_files.end(); iter++) {
        INV((*iter).is_absolute());
        if (!fs::exists(*iter))
            return F("Required file '%s' not found") % *iter;
    }
    return "";
}


/// Checks if all required programs exist.
///
/// \param required_programs Set of paths.
///
/// \return Empty if the required programs all exist or an error message
/// otherwise.
static std::string
check_required_programs(const engine::paths_set& required_programs)
{
    for (engine::paths_set::const_iterator iter = required_programs.begin();
         iter != required_programs.end(); iter++) {
        if ((*iter).is_absolute()) {
            if (!fs::exists(*iter))
                return F("Required program '%s' not found") % *iter;
        } else {
            if (!fs::find_in_path((*iter).c_str()))
                return F("Required program '%s' not found in PATH") % *iter;
        }
    }
    return "";
}


/// Checks if the current system has the specified amount of memory.
///
/// \param required_memory Amount of required physical memory, or zero if not
///     applicable.
///
/// \return Empty if the current system has the required amount of memory or an
/// error message otherwise.
static std::string
check_required_memory(const units::bytes& required_memory)
{
    if (required_memory > 0) {
        const units::bytes physical_memory = utils::physical_memory();
        if (physical_memory > 0 && physical_memory < required_memory)
            return F("Requires %s bytes of physical memory but only %s "
                     "available") %
                required_memory.format() % physical_memory.format();
    }
    return "";
}


}  // anonymous namespace


/// Internal implementation of the metadata class.
struct engine::metadata::impl {
    /// Metadata properties.
    config::tree props;

    /// Constructor.
    ///
    /// \param props_ Metadata properties of the test.
    impl(const utils::config::tree& props_) :
        props(props_)
    {
    }

    /// Equality comparator.
    ///
    /// \param other The other object to compare this one to.
    ///
    /// \return True if this object and other are equal; false otherwise.
    bool
    operator==(const impl& other) const
    {
        return props == other.props;
    }
};


/// Constructor.
///
/// \param props Metadata properties of the test.
engine::metadata::metadata(const utils::config::tree& props) :
    _pimpl(new impl(props))
{
}


/// Destructor.
engine::metadata::~metadata(void)
{
}


/// Returns the architectures allowed by the test.
///
/// \return Set of architectures, or empty if this does not apply.
const engine::strings_set&
engine::metadata::allowed_architectures(void) const
{
    return _pimpl->props.lookup< config::strings_set_node >(
        "allowed_architectures");
}


/// Returns the platforms allowed by the test.
///
/// \return Set of platforms, or empty if this does not apply.
const engine::strings_set&
engine::metadata::allowed_platforms(void) const
{
    return _pimpl->props.lookup< config::strings_set_node >("allowed_platforms");
}


/// Returns all the user-defined metadata properties.
///
/// \return A key/value map of properties.
engine::properties_map
engine::metadata::custom(void) const
{
    return _pimpl->props.all_properties("custom", true);
}


/// Returns the description of the test.
///
/// \return Textual description; may be empty.
const std::string&
engine::metadata::description(void) const
{
    return _pimpl->props.lookup< config::string_node >("description");
}


/// Returns whether the test has a cleanup part or not.
///
/// \return True if there is a cleanup part; false otherwise.
bool
engine::metadata::has_cleanup(void) const
{
    return _pimpl->props.lookup< config::bool_node >("has_cleanup");
}


/// Returns the list of configuration variables needed by the test.
///
/// \return Set of configuration variables.
const engine::strings_set&
engine::metadata::required_configs(void) const
{
    return _pimpl->props.lookup< config::strings_set_node >("required_configs");
}


/// Returns the list of files needed by the test.
///
/// \return Set of paths.
const engine::paths_set&
engine::metadata::required_files(void) const
{
    return _pimpl->props.lookup< paths_set_node >("required_files");
}


/// Returns the amount of memory required by the test.
///
/// \return Number of bytes, or 0 if this does not apply.
const units::bytes&
engine::metadata::required_memory(void) const
{
    return _pimpl->props.lookup< bytes_node >("required_memory");
}


/// Returns the list of programs needed by the test.
///
/// \return Set of paths.
const engine::paths_set&
engine::metadata::required_programs(void) const
{
    return _pimpl->props.lookup< paths_set_node >("required_programs");
}


/// Returns the user required by the test.
///
/// \return One of unprivileged, root or empty.
const std::string&
engine::metadata::required_user(void) const
{
    return _pimpl->props.lookup< user_node >("required_user");
}


/// Returns the timeout of the test.
///
/// \return A time delta; should be compared to default_timeout to see if it has
/// been overriden.
const datetime::delta&
engine::metadata::timeout(void) const
{
    return _pimpl->props.lookup< delta_node >("timeout");
}


/// Externalizes the metadata to a set of key/value textual pairs.
///
/// \return A key/value representation of the metadata.
engine::properties_map
engine::metadata::to_properties(void) const
{
    return _pimpl->props.all_properties();
}


/// Equality comparator.
///
/// \param other The other object to compare this one to.
///
/// \return True if this object and other are equal; false otherwise.
bool
engine::metadata::operator==(const metadata& other) const
{
    return _pimpl == other._pimpl || *_pimpl == *other._pimpl;
}


/// Inequality comparator.
///
/// \param other The other object to compare this one to.
///
/// \return True if this object and other are different; false otherwise.
bool
engine::metadata::operator!=(const metadata& other) const
{
    return !(*this == other);
}


/// Injects the object into a stream.
///
/// \param output The stream into which to inject the object.
/// \param object The object to format.
///
/// \return The output stream.
std::ostream&
engine::operator<<(std::ostream& output, const metadata& object)
{
    output << "metadata{";

    bool first = true;
    const engine::properties_map props = object.to_properties();
    for (engine::properties_map::const_iterator iter = props.begin();
         iter != props.end(); ++iter) {
        if (!first)
            output << ", ";
        output << F("%s=%s") % (*iter).first %
            text::quote((*iter).second, '\'');
        first = false;
    }

    output << "}";
    return output;
}


/// Internal implementation of the metadata_builder class.
struct engine::metadata_builder::impl {
    /// Collection of requirements.
    config::tree props;

    /// Whether we have created a metadata object or not.
    bool built;

    /// Constructor.
    impl(void) :
        built(false)
    {
        init_tree(props);
    }

    /// Constructor.
    impl(const engine::metadata& base) :
        props(base._pimpl->props.deep_copy()),
        built(false)
    {
    }
};


/// Constructor.
engine::metadata_builder::metadata_builder(void) :
    _pimpl(new impl())
{
}


/// Constructor.
engine::metadata_builder::metadata_builder(const engine::metadata& base) :
    _pimpl(new impl(base))
{
}


/// Destructor.
engine::metadata_builder::~metadata_builder(void)
{
}


/// Accumulates an additional allowed architecture.
///
/// \param arch The architecture.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_allowed_architecture(const std::string& arch)
{
    lookup_rw< config::strings_set_node >(
        _pimpl->props, "allowed_architectures").insert(arch);
    return *this;
}


/// Accumulates an additional allowed platform.
///
/// \param platform The platform.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_allowed_platform(const std::string& platform)
{
    lookup_rw< config::strings_set_node >(
        _pimpl->props, "allowed_platforms").insert(platform);
    return *this;
}


/// Accumulates a single user-defined property.
///
/// \param key Name of the property to define.
/// \param value Value of the property.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_custom(const std::string& key,
                                     const std::string& value)
{
    _pimpl->props.set_string(F("custom.%s") % key, value);
    return *this;
}


/// Accumulates an additional required configuration variable.
///
/// \param var The name of the configuration variable.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_required_config(const std::string& var)
{
    lookup_rw< config::strings_set_node >(
        _pimpl->props, "required_configs").insert(var);
    return *this;
}


/// Accumulates an additional required file.
///
/// \param path The path to the file.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_required_file(const fs::path& path)
{
    lookup_rw< paths_set_node >(_pimpl->props, "required_files").insert(path);
    return *this;
}


/// Accumulates an additional required program.
///
/// \param path The path to the program.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::add_required_program(const fs::path& path)
{
    lookup_rw< paths_set_node >(_pimpl->props,
                                "required_programs").insert(path);
    return *this;
}


/// Sets the architectures allowed by the test.
///
/// \param as Set of architectures.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_allowed_architectures(const strings_set& as)
{
    set< config::strings_set_node >(_pimpl->props, "allowed_architectures", as);
    return *this;
}


/// Sets the platforms allowed by the test.
///
/// \return ps Set of platforms.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_allowed_platforms(const strings_set& ps)
{
    set< config::strings_set_node >(_pimpl->props, "allowed_platforms", ps);
    return *this;
}


/// Sets the user-defined properties.
///
/// \param props The custom properties to set.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_custom(const properties_map& props)
{
    for (properties_map::const_iterator iter = props.begin();
         iter != props.end(); ++iter)
        _pimpl->props.set_string(F("custom.%s") % (*iter).first,
                                 (*iter).second);
    return *this;
}


/// Sets the description of the test.
///
/// \param description Textual description of the test.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_description(const std::string& description)
{
    set< config::string_node >(_pimpl->props, "description", description);
    return *this;
}


/// Sets whether the test has a cleanup part or not.
///
/// \param cleanup True if the test has a cleanup part; false otherwise.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_has_cleanup(const bool cleanup)
{
    set< config::bool_node >(_pimpl->props, "has_cleanup", cleanup);
    return *this;
}


/// Sets the list of configuration variables needed by the test.
///
/// \param vars Set of configuration variables.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_required_configs(const strings_set& vars)
{
    set< config::strings_set_node >(_pimpl->props, "required_configs", vars);
    return *this;
}


/// Sets the list of files needed by the test.
///
/// \param files Set of paths.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_required_files(const paths_set& files)
{
    set< paths_set_node >(_pimpl->props, "required_files", files);
    return *this;
}


/// Sets the amount of memory required by the test.
///
/// \param bytes Number of bytes.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_required_memory(const units::bytes& bytes)
{
    set< bytes_node >(_pimpl->props, "required_memory", bytes);
    return *this;
}


/// Sets the list of programs needed by the test.
///
/// \param progs Set of paths.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_required_programs(const paths_set& progs)
{
    set< paths_set_node >(_pimpl->props, "required_programs", progs);
    return *this;
}


/// Sets the user required by the test.
///
/// \param user One of unprivileged, root or empty.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_required_user(const std::string& user)
{
    set< user_node >(_pimpl->props, "required_user", user);
    return *this;
}


/// Sets a metadata property by name from its textual representation.
///
/// \param key The property to set.
/// \param value The value to set the property to.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid or the key does not exist.
engine::metadata_builder&
engine::metadata_builder::set_string(const std::string& key,
                                     const std::string& value)
{
    try {
        _pimpl->props.set_string(key, value);
    } catch (const config::unknown_key_error& e) {
        throw engine::format_error(F("Unknown metadata property %s") % key);
    } catch (const config::value_error& e) {
        throw engine::format_error(
            F("Invalid value for metadata property %s: %s") % key % e.what());
    }
    return *this;
}


/// Sets the timeout of the test.
///
/// \param timeout The timeout to set.
///
/// \return A reference to this builder.
///
/// \throw engine::error If the value is invalid.
engine::metadata_builder&
engine::metadata_builder::set_timeout(const datetime::delta& timeout)
{
    set< delta_node >(_pimpl->props, "timeout", timeout);
    return *this;
}


/// Creates a new metadata object.
///
/// \pre This has not yet been called.  We only support calling this function
/// once due to the way the internal tree works: we pass around references, not
/// deep copies, so if we allowed a second build, we'd encourage reusing the
/// same builder to construct different metadata objects, and this could have
/// unintended consequences.
///
/// \return The constructed metadata object.
engine::metadata
engine::metadata_builder::build(void) const
{
    PRE(!_pimpl->built);
    _pimpl->built = true;

    return metadata(_pimpl->props);
}


/// Checks if all the requirements specified by the test case are met.
///
/// \param md The test metadata.
/// \param cfg The engine configuration.
/// \param test_suite Name of the test suite the test belongs to.
///
/// \return A string describing the reason for skipping the test, or empty if
/// the test should be executed.
std::string
engine::check_reqs(const engine::metadata& md, const config::tree& cfg,
                   const std::string& test_suite)
{
    std::string reason;

    reason = check_required_configs(md.required_configs(), cfg, test_suite);
    if (!reason.empty())
        return reason;

    reason = check_allowed_architectures(md.allowed_architectures(), cfg);
    if (!reason.empty())
        return reason;

    reason = check_allowed_platforms(md.allowed_platforms(), cfg);
    if (!reason.empty())
        return reason;

    reason = check_required_user(md.required_user(), cfg);
    if (!reason.empty())
        return reason;

    reason = check_required_files(md.required_files());
    if (!reason.empty())
        return reason;

    reason = check_required_programs(md.required_programs());
    if (!reason.empty())
        return reason;

    reason = check_required_memory(md.required_memory());
    if (!reason.empty())
        return reason;

    INV(reason.empty());
    return reason;
}