This file is indexed.

/usr/lib/python3/dist-packages/maascli/snappy.py is in python3-maas-client 2.4.0~beta2-6865-gec43e47e6-0ubuntu1.

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
#!/usr/bin/env python3
# Copyright 2017 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Snap management commands."""

__all__ = [
    'cmd_config',
    'cmd_init',
    'cmd_migrate',
    'cmd_status',
    ]

import argparse
from collections import OrderedDict
from contextlib import contextmanager
import grp
import os
import pwd
import random
import shutil
import signal
import string
import subprocess
import sys
import threading
import time

from maascli.command import Command
from maascli.init import (
    add_create_admin_options,
    add_idm_options,
    init_maas,
    print_msg,
)
import netifaces
import tempita
import yaml


OPERATION_MODES = """\
available modes:
    all         - full MAAS installation includes database, region
                  controller, and rack controller.
    region+rack - region controller connected to external database
                  and rack controller.
    region      - only region controller connected to external
                  database.
    rack        - only rack controller connected to an external
                  region.
    none        - not configured\
"""

DEFAULT_OPERATION_MODE = 'all'

ARGUMENTS = OrderedDict([
    ('mode', {
        'choices': ['all', 'region+rack', 'region', 'rack', 'none'],
        'help': (
            'Set the mode of the MAAS snap (all, region+rack, region, '
            'rack, or none).'),
    }),
    ('maas-url', {
        'help': (
            'URL that MAAS should use for communicate from the nodes to '
            'MAAS and other controllers of MAAS.'),
    }),
    ('database-host', {
        'help': (
            'Hostname or IP address that should be used to communicate to '
            'the database. Only used when in \'region+rack\' or '
            '\'region\' mode.'),
    }),
    ('database-name', {
        'help': (
            'Database name for MAAS to use. Only used when in '
            '\'region+rack\' or \'region\' mode.'),
    }),
    ('database-user', {
        'help': (
            'Database username to authenticate to the database. Only used '
            'when in \'region+rack\' or \'region\' mode.'),
    }),
    ('database-pass', {
        'help': (
            'Database password to authenticate to the database. Only used '
            'when in \'region+rack\' or \'region\' mode.'),
    }),
    ('secret', {
        'help': (
            'Secret token required for the rack controller to talk '
            'to the region controller(s). Only used when in \'rack\' mode.'),
    }),
    ('num-workers', {
        'type': int,
        'help': (
            'Number of regiond worker process to run.'),
    }),
    ('enable-debug', {
        'action': 'store_true',
        'help': (
            'Enable debug mode for detailed error and log reporting.'),
    }),
    ('disable-debug', {
        'action': 'store_true',
        'help': 'Disable debug mode.',
    }),
    ('enable-debug-queries', {
        'action': 'store_true',
        'help': (
            'Enable query debugging. Reports number of queries and time for '
            'all actions performed. Requires debug to also be True. mode for '
            'detailed error and log reporting.'),
    }),
    ('disable-debug-queries', {
        'action': 'store_true',
        'help': 'Disable query debugging.',
    }),
])


def get_default_gateway_ip():
    """Return the default gateway IP."""
    gateways = netifaces.gateways()
    defaults = gateways.get('default')
    if not defaults:
        return

    def default_ip(family):
        gw_info = defaults.get(family)
        if not gw_info:
            return
        addresses = netifaces.ifaddresses(gw_info[1]).get(family)
        if addresses:
            return addresses[0]['addr']

    return default_ip(netifaces.AF_INET) or default_ip(netifaces.AF_INET6)


def get_default_url():
    """Return the best default URL for MAAS."""
    gateway_ip = get_default_gateway_ip()
    if not gateway_ip:
        gateway_ip = 'localhost'
    return 'http://%s:5240/MAAS' % gateway_ip


def get_mode_filepath():
    """Return the path to the 'snap_mode' file."""
    return os.path.join(os.environ['SNAP_COMMON'], 'snap_mode')


def get_current_mode():
    """Gets the current mode of the snap."""
    filepath = get_mode_filepath()
    if os.path.exists(filepath):
        with open(get_mode_filepath(), "r") as fp:
            return fp.read().strip()
    else:
        return "none"


def set_current_mode(mode):
    """Set the current mode of the snap."""
    with open(get_mode_filepath(), "w") as fp:
        fp.write(mode.strip())


def render_supervisord(mode):
    """Render the 'supervisord.conf' based on the mode."""
    conf_vars = {
        'postgresql': False,
        'regiond': False,
        'rackd': False,
    }
    if mode == 'all':
        conf_vars['postgresql'] = True
    if mode in ['all', 'region+rack', 'region']:
        conf_vars['regiond'] = True
    if mode in ['all', 'region+rack', 'rack']:
        conf_vars['rackd'] = True
    template = tempita.Template.from_filename(
        os.path.join(
            os.environ['SNAP'], 'usr', 'share', 'maas',
            'supervisord.conf.template'), encoding="UTF-8")
    rendered = template.substitute(conf_vars)
    conf_path = os.path.join(
        os.environ['SNAP_DATA'], 'supervisord', 'supervisord.conf')
    with open(conf_path, 'w') as fp:
        fp.write(rendered)


def get_supervisord_pid():
    """Get the running supervisord pid."""
    pid_path = os.path.join(
        os.environ['SNAP_DATA'], 'supervisord', 'supervisord.pid')
    if os.path.exists(pid_path):
        with open(pid_path, 'r') as fp:
            return int(fp.read().strip())
    else:
        return None


def sighup_supervisord():
    """Cause supervisord to stop all processes, reload configuration, and
    start all processes."""
    pid = get_supervisord_pid()
    if pid is None:
        return

    os.kill(pid, signal.SIGHUP)
    # Wait for supervisord to be running successfully.
    time.sleep(0.5)
    while True:
        process = subprocess.Popen([
            os.path.join(
                os.environ['SNAP'], 'bin', 'run-supervisorctl'),
            'status'], stdout=subprocess.PIPE)
        process.wait()
        output = process.stdout.read().decode('utf-8')
        # Error message is printed until supervisord is running correctly.
        if 'error:' in output:
            time.sleep(1)
        else:
            break


def get_config_data():
    """Return the configuration data from `regiond.conf`."""
    regiond_conf_path = os.path.join(os.environ['SNAP_DATA'], 'regiond.conf')
    if os.path.exists(regiond_conf_path):
        with open(regiond_conf_path, 'r') as fp:
            data = yaml.safe_load(fp)
        if data is None:
            data = {}
        return data
    else:
        return {}


def get_config_value(config_name):
    """Return the configuration value for `config_name`."""
    # We always read from regiond.conf. As the database options only exists
    # in that file and maas_url will always be the same in rackd.conf.
    config_data = get_config_data()
    return config_data.get(config_name, None)


def print_config_value(config_name, hidden=False):
    """Print the configuration value to stdout."""
    if hidden:
        print_msg("%s=(hidden)" % config_name)
    else:
        config_value = get_config_value(config_name)
        print_msg("%s=%s" % (config_name, config_value))


def write_config_data(config_data, config_file):
    """Write the configuration data to `regiond.conf`."""
    regiond_conf_path = os.path.join(os.environ['SNAP_DATA'], config_file)
    with open(regiond_conf_path, 'w') as fp:
        fp.write(yaml.safe_dump(config_data, default_flow_style=False))


def update_config_value(config_name, config_value):
    """Update the configuration to new value."""
    config_data = get_config_data()
    if config_value is None:
        config_data.pop(config_name, None)
    else:
        config_data[config_name] = config_value
    write_config_data(config_data, 'regiond.conf')
    # maas_url also gets set in rackd.conf.
    if config_name == 'maas_url':
        if config_value is None:
            config_data = {}
        else:
            config_data = {
                'maas_url': config_value
            }
        write_config_data(config_data, 'rackd.conf')


def get_rpc_secret():
    """Get the current RPC secret."""
    secret = None
    secret_path = os.path.join(
        os.environ['SNAP_DATA'], 'var', 'lib', 'maas', 'secret')
    if os.path.exists(secret_path):
        with open(secret_path, 'r') as fp:
            secret = fp.read().strip()
    if secret:
        return secret
    else:
        return None


def set_rpc_secret(secret):
    """Write/delete the RPC secret."""
    secret_path = os.path.join(
        os.environ['SNAP_DATA'], 'var', 'lib', 'maas', 'secret')
    if secret:
        # Write the secret.
        with open(secret_path, 'w') as fp:
            fp.write(secret)
    else:
        # Delete the secret.
        if os.path.exists(secret_path):
            os.remove(secret_path)


def print_config(
        parsable=False, show_database_password=False, show_secret=False):
    """Print the config output."""
    current_mode = get_current_mode()
    if parsable:
        print_msg('mode=%s' % current_mode)
    else:
        print_msg('Mode: %s' % current_mode)
    if current_mode != 'none':
        if not parsable:
            print_msg('Settings:')
        print_config_value('maas_url')
        if current_mode in ['region+rack', 'region']:
            print_config_value('database_host')
            print_config_value('database_name')
            print_config_value('database_user')
            print_config_value(
                'database_pass', hidden=(not show_database_password))
        if current_mode == 'rack':
            secret = "(hidden)"
            if show_secret:
                secret = get_rpc_secret()
            print_msg('secret=%s' % secret)
        if current_mode != 'rack':
            if get_config_value('num_workers'):
                print_config_value('num_workers')
            if get_config_value('debug'):
                print_config_value('debug')
            if get_config_value('debug_queries'):
                print_config_value('debug_queries')


def drop_privileges():
    """Drop privileges to 'nobody:nogroup'."""
    running_uid = pwd.getpwnam('nobody').pw_uid
    running_gid = grp.getgrnam('nogroup').gr_gid
    os.setgroups([])
    os.setgid(running_gid)
    os.setuid(running_uid)


def run_with_drop_privileges(cmd, *args, **kwargs):
    """Runs `cmd` in child process with lower privileges."""
    pid = os.fork()
    if pid == 0:
        drop_privileges()
        cmd(*args, **kwargs)
        sys.exit(0)
    else:
        os.waitpid(pid, 0)


def run_sql(sql):
    """Run sql command through `psql`."""
    subprocess.check_output([
        os.path.join(os.environ['SNAP'], 'bin', 'psql'),
        '-h', os.path.join(os.environ['SNAP_COMMON'], 'db'),
        '-d', 'postgres', '-U', 'postgres', '-c', sql],
        stderr=subprocess.STDOUT)


def wait_for_postgresql(timeout=60):
    """Wait for postgresql to be running."""
    end_time = time.time() + timeout
    while True:
        try:
            run_sql('SELECT now();')
        except subprocess.CalledProcessError:
            if time.time() > end_time:
                raise TimeoutError(
                    "Unable to connect to postgresql after %s seconds." % (
                        timeout))
            else:
                time.sleep(1)
        else:
            break


def start_postgres():
    """Start postgresql."""
    subprocess.check_output([
        os.path.join(os.environ['SNAP'], 'bin', 'pg_ctl'),
        'start', '-w', '-D', os.path.join(os.environ['SNAP_COMMON'], 'db'),
        '-l', os.path.join(os.environ['SNAP_COMMON'], 'log', 'postgresql.log'),
        '-o', '-k "%s" -h ""' % os.path.join(os.environ['SNAP_COMMON'], 'db')],
        stderr=subprocess.STDOUT)
    wait_for_postgresql()


def stop_postgres():
    """Stop postgresql."""
    subprocess.check_output([
        os.path.join(os.environ['SNAP'], 'bin', 'pg_ctl'),
        'stop', '-w', '-D', os.path.join(os.environ['SNAP_COMMON'], 'db')],
        stderr=subprocess.STDOUT)


@contextmanager
def with_postgresql():
    """Start or stop postgresql."""
    start_postgres()
    yield
    stop_postgres()


def create_db(config):
    """Create the database and user."""
    run_sql("CREATE USER %s WITH PASSWORD '%s';" % (
        config['database_user'], config['database_pass']))
    run_sql("CREATE DATABASE %s;" % config['database_name'])
    run_sql("GRANT ALL PRIVILEGES ON DATABASE %s to %s;" % (
        config['database_name'], config['database_user']))


def migrate_db(capture=False):
    """Migrate the database."""
    if capture:
        process = subprocess.Popen([
            os.path.join(os.environ['SNAP'], 'bin', 'maas-region'),
            'dbupgrade'],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
        ret = process.wait()
        output = process.stdout.read().decode('utf-8')
        if ret != 0:
            clear_line()
            print_msg('Failed to perfom migrations:')
            print_msg(output)
            print_msg('')
            sys.exit(ret)
    else:
        subprocess.check_call([
            os.path.join(os.environ['SNAP'], 'bin', 'maas-region'),
            'dbupgrade'])


def init_db():
    """Initialize the database."""
    config_data = get_config_data()
    db_path = os.path.join(os.environ['SNAP_COMMON'], 'db')
    if os.path.exists(db_path):
        shutil.rmtree(db_path)
    os.mkdir(db_path)
    shutil.chown(db_path, user='nobody', group='nogroup')
    log_path = os.path.join(os.environ['SNAP_COMMON'], 'log', 'postgresql.log')
    if not os.path.exists(log_path):
        open(log_path, 'a').close()
    shutil.chown(log_path, user='nobody', group='nogroup')

    def _init_db():
        subprocess.check_output([
            os.path.join(os.environ['SNAP'], 'bin', 'initdb'),
            '-D', os.path.join(os.environ['SNAP_COMMON'], 'db'),
            '-U', 'postgres', '-E', 'UTF8', '--locale=C'],
            stderr=subprocess.STDOUT)
        with with_postgresql():
            create_db(config_data)
    run_with_drop_privileges(_init_db)


def clear_line():
    """Resets the current line when in a terminal."""
    if sys.stdout.isatty():
        print_msg(
            '\r' + ' ' * int(os.environ.get('COLUMNS', 0)), newline=False)


def perform_work(msg, cmd, *args, **kwargs):
    """Perform work.

    Executes the `cmd` and while its running it prints a nice message.
    """
    # When not running in a terminal, just print the message once and perform
    # the operation.
    if not sys.stdout.isatty():
        print_msg(msg)
        return cmd(*args, **kwargs)

    spinner = {
        0: '/',
        1: '-',
        2: '\\',
        3: '|',
        4: '/',
        5: '-',
        6: '\\',
        7: '|',
    }

    def _write_msg(evnt):
        idx = 0
        while not evnt.is_set():
            # Print the message with a spinner until the work is complete.
            print_msg(
                "\r[%s] %s" % (spinner[idx], msg), newline=False)
            idx += 1
            if idx == 8:
                idx = 0
            time.sleep(0.25)
        # Clear the line so previous message is not show if the next message
        # is not as long as this message.
        print_msg('\r' + ' ' * (len(msg) + 4), newline=False)

    # Spawn a thread to print the message, while performing the work in the
    # current execution thread.
    evnt = threading.Event()
    t = threading.Thread(target=_write_msg, args=(evnt,))
    t.start()
    try:
        ret = cmd(*args, **kwargs)
    finally:
        evnt.set()
        t.join()
    return ret


def read_input(prompt):
    """Reads input from stdin."""
    while True:
        try:
            data = input(prompt)
        except EOFError:
            # Ctrl-d was pressed?
            print()
            continue
        except KeyboardInterrupt:
            print()
            raise SystemExit(1)
        else:
            # The assumption is that, since Python 3 return a Unicode string
            # from input(), it has Done The Right Thing with respect to
            # character encoding.
            return data


def required_prompt(prompt, help_text=None):
    """Prompt for required input."""
    value = None
    while not value or value == "help":
        value = read_input(prompt)
        if value == "help":
            if help_text:
                print_msg(help_text)
    return value


def prompt_for_choices(prompt, choices, default=None, help_text=None):
    """Prompt requires specific choice answeres.

    If `help_text` is provided the 'help' is added as a choice.
    """
    invalid_msg = 'Invalid input, try again'
    if help_text:
        invalid_msg += " or type 'help'"
    invalid_msg += '.'
    value = None
    while True:
        value = read_input(prompt)
        if not value:
            if default:
                return default
            else:
                print_msg(invalid_msg)
                print_msg()
        elif value == 'help' and help_text:
            print_msg(help_text)
            print_msg()
        elif value not in choices:
            print_msg(invalid_msg)
            print_msg()
        else:
            return value


def prompt_for_maas_url():
    """Prompt for the MAAS URL."""
    default_url = get_default_url()
    url = None
    while not url or url == "help":
        url = read_input("MAAS URL [default=%s]: " % default_url)
        if not url:
            url = default_url
        if url == "help":
            print_msg(
                'URL that MAAS should use for communicate from the nodes '
                'to MAAS and other controllers of MAAS.')
    return url


class SnappyCommand(Command):
    """
    Command that just prints the exception instead of the overridden
    'maas --help' output.
    """

    def __call__(self, options):
        try:
            self.handle(options)
        except Exception as exc:
            exc.always_show = True
            raise exc


class cmd_init(SnappyCommand):
    """Initialize controller."""

    def __init__(self, parser):
        super(cmd_init, self).__init__(parser)
        for argument, kwargs in ARGUMENTS.items():
            parser.add_argument('--%s' % argument, **kwargs)
        parser.add_argument(
            '--force', action='store_true',
            help=(
                "Skip confirmation questions when initialization has "
                "already been performed."))
        parser.add_argument(
            '--enable-idm', default=False, action="store_true",
            help=("Enable configuring the use of an external IDM server. "
                  "This feature is currently experimental. "
                  "If this isn't enabled, all --idm-* arguments "
                  "will be ignored."))
        add_idm_options(parser)
        parser.add_argument(
            '--skip-admin', action='store_true',
            help=(
                "Skip the admin creation when initializing in 'all' mode."))
        add_create_admin_options(parser)

    def handle(self, options):
        if os.getuid() != 0:
            raise SystemExit("The 'init' command must be run by root.")

        mode = options.mode
        current_mode = get_current_mode()
        if current_mode != 'none':
            if not options.force:
                init_text = 'initialize again'
                if mode == 'none':
                    init_text = 'de-initialize'
                else:
                    print_msg('Controller has already been initialized.')
                initialize = prompt_for_choices(
                    'Are you sure you want to %s '
                    '(yes/no) [default=no]? ' % init_text,
                    ['yes', 'no'], default='no')
                if initialize == 'no':
                    sys.exit(0)

        if not mode:
            mode = prompt_for_choices(
                "Mode ({choices}) [default={default}]? ".format(
                    choices='/'.join(ARGUMENTS['mode']['choices']),
                    default=DEFAULT_OPERATION_MODE),
                ARGUMENTS['mode']['choices'],
                default=DEFAULT_OPERATION_MODE, help_text=OPERATION_MODES)
        if current_mode == 'all' and mode != 'all' and not options.force:
            print_msg(
                'This will disconnect your MAAS from the running database.')
            disconnect = prompt_for_choices(
                'Are you sure you want to disconnect the database '
                '(yes/no) [default=no]? ', ['yes', 'no'], default='no')
            if disconnect == 'no':
                return 0
        elif current_mode == 'all' and mode == 'all' and not options.force:
            print_msg(
                'This will re-initialize your entire database and all '
                'current data will be lost.')
            reinit_db = prompt_for_choices(
                'Are you sure you want to re-initialize the database '
                '(yes/no) [default=no]? ', ['yes', 'no'], default='no')
            if reinit_db == 'no':
                return 0

        maas_url = options.maas_url
        if mode != 'none' and not maas_url:
            maas_url = prompt_for_maas_url()
        database_host = database_name = None
        database_user = database_pass = None
        rpc_secret = None
        if mode == 'all':
            database_host = os.path.join(os.environ['SNAP_COMMON'], 'db')
            database_name = 'maasdb'
            database_user = 'maas'
            database_pass = ''.join(
                random.choice(string.ascii_uppercase + string.digits)
                for _ in range(10))
        if mode in ['region', 'region+rack']:
            database_host = options.database_host
            if not database_host:
                database_host = required_prompt(
                    "Database host: ",
                    help_text=ARGUMENTS['database_host']['help'])
            database_name = options.database_name
            if not database_name:
                database_name = required_prompt(
                    "Database name: ",
                    help_text=ARGUMENTS['database_name']['help'])
            database_user = options.database_user
            if not database_user:
                database_user = required_prompt(
                    "Database user: ",
                    help_text=ARGUMENTS['database_user']['help'])
            database_pass = options.database_pass
            if not database_pass:
                database_pass = required_prompt(
                    "Database password: ",
                    help_text=ARGUMENTS['database_pass']['help'])
        if mode == 'rack':
            rpc_secret = options.secret
            if not rpc_secret:
                rpc_secret = required_prompt(
                    "Secret: ",
                    help_text=ARGUMENTS['secret']['help'])

        # Stop all services if in another mode.
        if current_mode != 'none':
            def stop_services():
                render_supervisord('none')
                sighup_supervisord()
            perform_work('Stopping services', stop_services)

        # Configure the settings.
        update_config_value('maas_url', maas_url)
        for name, value in [
                ('database_host', database_host),
                ('database_name', database_name),
                ('database_user', database_user),
                ('database_pass', database_pass),
                ]:
            update_config_value(name, value)
        set_rpc_secret(rpc_secret)

        # Finalize the Initialization.
        self._finalize_init(mode, options)

    def _finalize_init(self, mode, options):
        # When in 'all' mode configure the database.
        if mode == 'all':
            perform_work('Initializing database', init_db)

        # Configure mode.
        def start_services():
            render_supervisord(mode)
            set_current_mode(mode)
            sighup_supervisord()
        perform_work(
            'Starting services' if mode != 'none' else 'Stopping services',
            start_services)

        if mode == 'all':
            # When in 'all' mode configure the database and create admin user.
            perform_work('Waiting for postgresql', wait_for_postgresql)
            perform_work(
                "Performing database migrations",
                migrate_db, capture=sys.stdout.isatty())
            clear_line()
            init_maas(options)
        elif mode in ['region', 'region+rack']:
            # When in 'region' or 'region+rack' the migrations for the database
            # must be at the same level as this controller.
            perform_work(
                "Performing database migrations",
                migrate_db, capture=sys.stdout.isatty())
        else:
            clear_line()


class cmd_config(SnappyCommand):
    """View or change controller configuration."""

    # Required options based on mode.
    required_options = {
        'all': ['maas_url'],
        'region+rack': [
            'maas_url',
            'database_host',
            'database_name',
            'database_user',
            'database_pass',
            ],
        'region': [
            'maas_url',
            'database_host',
            'database_name',
            'database_user',
            'database_pass',
            ],
        'rack': [
            'maas_url',
            'secret',
            ],
        'none': [],
    }

    # Requried flags that are in .conf.
    setting_flags = (
        'maas_url',
        'database_host', 'database_name',
        'database_user', 'database_pass')

    # Optional flags that are in .conf.
    optional_flags = {
        'num_workers': {
            'type': 'int',
            'config': 'num_workers',
        },
        'enable_debug': {
            'type': 'bool',
            'set_value': True,
            'config': 'debug',
        },
        'disable_debug': {
            'type': 'bool',
            'set_value': False,
            'config': 'debug',
        },
        'enable_debug_queries': {
            'type': 'bool',
            'set_value': True,
            'config': 'debug_queries',
        },
        'disable_debug_queries': {
            'type': 'bool',
            'set_value': False,
            'config': 'debug_queries',
        },
    }

    def __init__(self, parser):
        super(cmd_config, self).__init__(parser)
        parser.add_argument(
            '--show', action='store_true',
            help=(
                "Show the current configuration. Default when no parameters "
                "are provided."))
        parser.add_argument(
            '--show-database-password', action='store_true',
            help="Show the hidden database password.")
        parser.add_argument(
            '--show-secret', action='store_true',
            help="Show the hidden secret.")
        for argument, kwargs in ARGUMENTS.items():
            parser.add_argument('--%s' % argument, **kwargs)
        parser.add_argument(
            '--force', action='store_true',
            help=(
                "Force leaving 'all' mode and cause loss of database."))
        parser.add_argument(
            '--parsable', action='store_true',
            help=(
                "Output the current configuration in a parsable format."))
        parser.add_argument(
            '--render', action='store_true', help=argparse.SUPPRESS)

    def _validate_mode(self, options):
        """Validate the parameters are correct for changing the mode."""
        if options.mode is not None:
            if options.mode != get_current_mode():
                # Changing the mode, ensure that the required parameters
                # are passed for this mode.
                missing_flags = []
                for flag in self.required_options[options.mode]:
                    if not getattr(options, flag):
                        missing_flags.append(
                            '--%s' % flag.replace('_', '-'))
                if len(missing_flags) > 0:
                    print_msg(
                        "Changing mode to '%s' requires parameters: %s" % (
                            options.mode, ', '.join(missing_flags)))
                    sys.exit(1)

    def _validate_flags(self, options, running_mode):
        """
        Validate the flags are correct for the current mode or the new mode.
        """
        invalid_flags = []
        for flag in self.setting_flags + ('secret', ):
            if (flag not in self.required_options[running_mode] and
                    getattr(options, flag)):
                invalid_flags.append('--%s' % flag.replace('_', '-'))
        if len(invalid_flags) > 0:
            print_msg(
                "Following flags are not supported in '%s' mode: %s" % (
                    running_mode, ', '.join(invalid_flags)))
            sys.exit(1)

    def handle(self, options):
        if os.getuid() != 0:
            raise SystemExit("The 'config' command must be run by root.")

        # Hidden option only called by the run-supervisord script. Renders
        # the initial supervisord.conf based on the current mode.
        if options.render:
            render_supervisord(get_current_mode())
            return

        # In config mode if --show is passed or none of the following flags
        # have been passed.
        in_config_mode = options.show
        if not in_config_mode:
            in_config_mode = not any(
                (getattr(options, flag) is not None and
                 getattr(options, flag) is not False)
                for flag in (
                    ('mode', 'secret') + self.setting_flags +
                    tuple(self.optional_flags.keys()))
            )

        # Config mode returns the current config of the snap.
        if in_config_mode:
            return print_config(
                options.parsable,
                options.show_database_password, options.show_secret)
        else:
            restart_required = False
            changed_to_all = False
            current_mode = get_current_mode()
            running_mode = current_mode
            if options.mode is not None:
                running_mode = options.mode

            # Validate the mode and flags.
            self._validate_mode(options)
            self._validate_flags(options, running_mode)

            # Changing the mode to from all requires --force.
            if options.mode is not None:
                if current_mode == 'all' and options.mode != 'all':
                    if not options.force:
                        print_msg(
                            "Changing mode from 'all' to '%s' will "
                            "disconnect the database and all data will "
                            "be lost. Use '--force' if your sure you want "
                            "to do this." % options.mode)
                        sys.exit(1)
                elif current_mode != 'all' and options.mode == 'all':
                    # Changing mode to all requires services to be stopped and
                    # a new database to be initialized.
                    changed_to_all = True

                    def stop_services():
                        render_supervisord('none')
                        sighup_supervisord()
                    perform_work('Stopping services', stop_services)

                    # Configure the new database settings.
                    options.database_host = os.path.join(
                        os.environ['SNAP_COMMON'], 'db')
                    options.database_name = 'maasdb'
                    options.database_user = 'maas'
                    options.database_pass = ''.join(
                        random.choice(
                            string.ascii_uppercase + string.digits)
                        for _ in range(10))
                    write_config_data({
                        'maas_url': options.maas_url,
                        'database_host': options.database_host,
                        'database_name': options.database_name,
                        'database_user': options.database_user,
                        'database_pass': options.database_pass,
                    }, 'regiond.conf')

                    # Initialize the database before starting the services.
                    perform_work('Initializing database', init_db)
                if options.mode != current_mode:
                    render_supervisord(options.mode)
                    set_current_mode(options.mode)
                    restart_required = True

            if current_mode != running_mode:
                # Update all the settings since the mode changed.
                for flag in self.setting_flags:
                    flag_value = getattr(options, flag)
                    if get_config_value(flag) != flag_value:
                        update_config_value(flag, flag_value)
                        restart_required = True
                set_rpc_secret(options.secret)
            else:
                # Only update the passed settings.
                for flag in self.setting_flags:
                    flag_value = getattr(options, flag)
                    if (flag_value is not None and
                            get_config_value(flag) != flag_value):
                        update_config_value(flag, flag_value)
                        restart_required = True
                if options.secret is not None:
                    set_rpc_secret(options.secret)

            # Update any optional settings.
            for flag, flag_info in self.optional_flags.items():
                flag_value = getattr(options, flag)
                if flag_info['type'] != 'store_true':
                    if (flag_value is not None and
                            get_config_value(flag_info['config']) != (
                                flag_value)):
                        update_config_value(flag_info['config'], flag_value)
                        restart_required = True
                elif flag_value:
                    flag_value = flag_info['set_value']
                    if get_config_value(flag_info['config']) != flag_value:
                        update_config_value(flag_info['config'], flag_value)
                        restart_required = True

            # Restart the supervisor as its required.
            if restart_required:
                perform_work(
                    'Restarting services'
                    if running_mode != 'none' else 'Stopping services',
                    sighup_supervisord)
                clear_line()

            # Perform migrations when switching to all.
            if changed_to_all:
                perform_work('Waiting for postgresql', wait_for_postgresql)
                perform_work(
                    "Performing database migrations",
                    migrate_db, capture=sys.stdout.isatty())
                clear_line()


class cmd_status(SnappyCommand):
    """Status of controller services."""

    def handle(self, options):
        if get_current_mode() == 'none':
            print_msg('MAAS is not configured')
            sys.exit(1)
        else:
            process = subprocess.Popen([
                os.path.join(
                    os.environ['SNAP'], 'bin', 'run-supervisorctl'),
                'status'], stdout=subprocess.PIPE)
            ret = process.wait()
            output = process.stdout.read().decode('utf-8')
            if ret == 0:
                print_msg(output, newline=False)
            else:
                if 'error:' in output:
                    print_msg(
                        'MAAS supervisor is currently restarting. '
                        'Please wait and try again.')
                    sys.exit(-1)
                else:
                    print_msg(output, newline=False)
                    sys.exit(ret)


class cmd_migrate(SnappyCommand):
    """Perform migrations on connected database."""

    def __init__(self, parser):
        super(cmd_migrate, self).__init__(parser)
        # '--configure' is only used from the 'hooks/configure' when the snap
        # is in 'all' mode. Postgresql is not running when the migrate is
        # called.
        parser.add_argument(
            '--configure', action='store_true', help=argparse.SUPPRESS)

    def handle(self, options):
        if os.getuid() != 0:
            raise SystemExit("The 'migrate' command must be run by root.")

        # Hidden parameter that is only called from the configure hook. Updates
        # the database when running in all mode.
        if options.configure:
            current_mode = get_current_mode()
            if current_mode == 'all':
                wait_for_postgresql()
                sys.exit(migrate_db())
            elif current_mode in ['region', 'region+rack']:
                sys.exit(migrate_db())
            else:
                # In 'rack' or 'none' mode, nothing to do.
                sys.exit(0)

        mode = get_current_mode()
        if mode == 'none':
            print_msg('MAAS is not configured')
            sys.exit(1)
        elif mode == 'rack':
            print_msg(
                "Mode 'rack' is not connected to a database. "
                "No migrations to perform.")
            sys.exit(1)
        else:
            sys.exit(migrate_db())