Ubuntu Pastebin

Paste from ubuntu at Fri, 20 May 2016 17:41:59 +0000

Download as text
   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
#!/bin/sh
#
# This script carries inside it multiple files.  When executed, it creates
# the files into a temporary directory, downloads and extracts commissioning
# scripts from the metadata service, and then processes the scripts.
#
# The commissioning scripts get run by a close equivalent of run-parts.
# For each, the main script calls home to maas with maas-signal, posting
# the script's output as a separate file.
#
####  IPMI setup  ######
# If IPMI network settings have been configured statically, you can
# make them DHCP. If 'true', the IPMI network source will be changed
# to DHCP.
IPMI_CHANGE_STATIC_TO_DHCP="false"

# In certain hardware, the parameters for the ipmi_si kernel module
# might need to be specified. If you wish to send parameters, uncomment
# the following line.
#IPMI_SI_PARAMS="type=kcs ports=0xca2"

#### script setup ######
TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX")
SCRIPTS_D="${TEMP_D}/commissioning.d"
IPMI_CONFIG_D="${TEMP_D}/ipmi.d"
BIN_D="${TEMP_D}/bin"
OUT_D="${TEMP_D}/out"
PATH="$BIN_D:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
trap cleanup EXIT

mkdir -p "$BIN_D" "$OUT_D" "$SCRIPTS_D" "$IPMI_CONFIG_D"

# Ensure that invocations of apt-get are not interactive by default,
# here and in all subprocesses.
export DEBIAN_FRONTEND=noninteractive

### some utility functions ####
aptget() {
   apt-get --assume-yes -q "$@" </dev/null
}

add_bin() {
   cat > "${BIN_D}/$1"
   chmod "${2:-755}" "${BIN_D}/$1"
}
add_ipmi_config() {
   cat > "${IPMI_CONFIG_D}/$1"
   chmod "${2:-644}" "${IPMI_CONFIG_D}/$1"
}
cleanup() {
   [ -n "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}

find_creds_cfg() {
   local config="" file="" found=""

   # If the config location is set in environment variable, trust it.
   [ -n "${COMMISSIONING_CREDENTIALS_URL}" ] &&
      _RET="${COMMISSIONING_CREDENTIALS_URL}" && return

   # Go looking for local files written by cloud-init.
   for file in /etc/cloud/cloud.cfg.d/*cmdline*.cfg; do
      [ -f "$file" ] && _RET="$file" && return
   done

   local opt="" cmdline=""
   if [ -f /proc/cmdline ] && read cmdline < /proc/cmdline; then
      # Search through /proc/cmdline arguments:
      # cloud-config-url trumps url=
      for opt in $cmdline; do
         case "$opt" in
            url=*)
               found=${opt#url=};;
            cloud-config-url=*)
               _RET="${opt#*=}"
               return 0;;
         esac
      done
      [ -n "$found" ] && _RET="$found" && return 0
   fi
   return 1
}

# Invoke the "signal()" API call to report progress.
# Usage: signal <status> <message>
signal() {
   maas-signal "--config=${CRED_CFG}" "$@"
}

# Report result of a commissioning script: output file, error output
# file if there was any error output, and return code.
# Usage: signal <return-value> <message> <stdout-file> <stderr-file>
signal_result() {
   local result=$1 message="$2" stdout="$3" stderr="$4"
   local files="--file=$stdout"
   if [ -f "$stderr" -a -s "$stderr" ]
   then
      files="$files --file=$stderr"
   fi
   maas-signal \
      "--config=${CRED_CFG}" \
      "--script-result=$result" \
      $files \
      WORKING "$message"
}

fail() {
   [ -z "$CRED_CFG" ] || signal FAILED "$1"
   echo "FAILED: $1" 1>&2;
   exit 1
}

write_block_poweroff() {
   touch /tmp/block-poweroff
}

main() {
   write_block_poweroff

   # Install tools and load modules.
   aptget update
   aptget install python3-yaml python3-oauthlib freeipmi-tools openipmi ipmitool
   load_modules

   # The main function, actually execute stuff that is written below.
   local script total=0 creds=""

   find_creds_cfg ||
      fail "failed to find credential config"
   creds="$_RET"

   # Get remote credentials into a local file.
   case "$creds" in
      http://*|https://*)
         wget "$creds" -O "${TEMP_D}/my.creds" ||
            fail "failed to get credentials from $cred_cfg"
         creds="${TEMP_D}/my.creds"
         ;;
   esac

   # Use global name read by signal() and fail.
   CRED_CFG="$creds"

   # Power settings.
   local pargs=""
   if $IPMI_CHANGE_STATIC_TO_DHCP; then
      pargs="--dhcp-if-static"
   fi
   power_type=$(maas-ipmi-autodetect-tool)
   case "$power_type" in
       ipmi)
           power_settings=$(maas-ipmi-autodetect --configdir "$IPMI_CONFIG_D" ${pargs})
           ;;
       moonshot)
           power_settings=$(maas-moonshot-autodetect)
           ;;
   esac
   if [ ! -z "$power_settings" ]; then
      signal "--power-type=${power_type}" "--power-parameters=${power_settings}" WORKING "finished [maas-ipmi-autodetect]"
   fi

   # Download and extract commissioning scripts.  It will contain a
   # commissioning.d directory, so this is how $SCRIPTS_D is created.
   maas-get --config="${CRED_CFG}" maas-commissioning-scripts | tar -C "${TEMP_D}" -x

   # Just get a count of how many scripts there are for progress reporting.
   for script in "${SCRIPTS_D}/"*; do
      [ -x "$script" -a -f "$script" ] || continue
      total=$(($total+1))
   done

   local cur=1 numfailed=0 name="" failed="" separator=""
   for script in "${SCRIPTS_D}/"*; do
      [ -f "$script" -a -f "$script" ] || continue
      name=${script##*/}
      signal WORKING "starting ${name} [$cur/$total]"
      "$script" > "${OUT_D}/${name}.out" 2> "${OUT_D}/${name}.err"
      ret=$?
      signal_result \
         "$ret" "finished $name [$cur/$total]: $ret" \
         "${OUT_D}/${name}.out" \
         "${OUT_D}/${name}.err"
      if [ $ret -ne 0 ]; then
          numfailed=$(($numfailed+1))
          failed="${failed}${separator}${name}"
          separator=", "
      fi
      cur=$(($cur+1))
   done

   if [ $numfailed -eq 0 ]; then
      ( cd "${OUT_D}" &&
         signal OK "finished [$total/$total]" )
      return 0
   else
      ( cd "${OUT_D}" &&
         signal FAILED "failed [$numfailed/$total] ($failed)" )
      return $numfailed
   fi

}

load_modules() {
   modprobe ipmi_msghandler
   modprobe ipmi_devintf
   modprobe ipmi_si ${IPMI_SI_PARAMS}
   udevadm settle
}

### begin writing files ###

# Example config: enable BMC remote access (on some systems.)
#add_ipmi_config "02-global-config.ipmi" <<"END_IPMI_CONFIG"
#Section Lan_Channel
#	Volatile_Access_Mode			Always_Available
#	Volatile_Enable_User_Level_Auth		Yes
#	Volatile_Channel_Privilege_Limit	Administrator
#	Non_Volatile_Access_Mode		Always_Available
#	Non_Volatile_Enable_User_Level_Auth	Yes
#	Non_Volatile_Channel_Privilege_Limit	Administrator
#EndSection
#END_IPMI_CONFIG

add_bin "maas-ipmi-autodetect-tool" <<"END_MAAS_IPMI_AUTODETECT_TOOL"
#!/usr/bin/python3

import glob
import re
import subprocess


def detect_ipmi():
    # XXX: andreserl 2013-04-09 bug=1064527: Try to detect if node
    # is a Virtual Machine. If it is, do not try to detect IPMI.
    with open('/proc/cpuinfo', 'r') as cpuinfo:
        for line in cpuinfo:
            if line.startswith('model name') and 'QEMU' in line:
                return (False, None)

    (status, output) = subprocess.getstatusoutput('ipmi-locate')
    show_re = re.compile('(IPMI\ Version:) (\d\.\d)')
    res = show_re.search(output)
    if res is None:
        found = glob.glob("/dev/ipmi[0-9]")
        if len(found):
            return (True, "UNKNOWN: %s" % " ".join(found))
        return (False, "")
    return (True, res.group(2))


def is_host_moonshot():
    output = subprocess.check_output(['ipmitool', 'raw', '06', '01'])
    # 14 is the code that identifies a machine as a moonshot
    if output.split()[0] == "14":
        return True
    return False


def main():
    # Check whether IPMI exists or not.
    (status, ipmi_version) = detect_ipmi()
    if not status:
        # if False, then failed to detect ipmi
        exit(1)

    if is_host_moonshot():
        print("moonshot")
    else:
        print("ipmi")


if __name__ == '__main__':
    main()

END_MAAS_IPMI_AUTODETECT_TOOL

add_bin "maas-ipmi-autodetect" <<"END_MAAS_IPMI_AUTODETECT"
#!/usr/bin/python3
#
# maas-ipmi-autodetect - autodetect and autoconfigure IPMI.
#
# Copyright (C) 2013-2016 Canonical
#
# Authors:
#    Andres Rodriguez <andres.rodriguez@canonical.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3 of the License.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from collections import OrderedDict
import json
import os
import random
import re
import string
import subprocess
import time


class IPMIError(Exception):
    """An error related to IPMI."""


def run_command(command_args):
    """Run a command. Return output if successful or raise exception if not."""
    output = subprocess.check_output(command_args, stderr=subprocess.STDOUT)
    return output.decode('utf-8')


def bmc_get(key):
    """Fetch the output of a key via bmc-config checkout."""
    command = ('bmc-config', '--checkout', '--key-pair=%s' % key)
    output = run_command(command)
    return output


def bmc_set(key, value):
    """Set the value of a key via bmc-config commit."""
    command = ('bmc-config', '--commit', '--key-pair=%s=%s' % (key, value))
    run_command(command)


def format_user_key(user_number, parameter):
    """Format a user key string."""
    return '%s:%s' % (user_number, parameter)


def bmc_user_get(user_number, parameter):
    """Get a user parameter via bmc-config commit."""
    key = format_user_key(user_number, parameter)
    raw = bmc_get(key)
    pattern = r'^\s*%s(?:[ \t])+([^#\s]+[^\n]*)$' % (re.escape(parameter))
    match = re.search(pattern, raw, re.MULTILINE)
    if match is None:
        return None
    return match.group(1)


def bmc_user_set(user_number, parameter, value):
    """Set a user parameter via bmc-config commit."""
    key = format_user_key(user_number, parameter)
    bmc_set(key, value)


def bmc_list_sections():
    """Retrieve the names of config sections from the BMC."""
    command = ('bmc-config', '-L')
    output = run_command(command)
    return output


def list_user_numbers():
    """List the user numbers on the BMC."""
    output = bmc_list_sections()
    pattern = r'^(User\d+)$'
    users = re.findall(pattern, output, re.MULTILINE)

    return users


def pick_user_number_from_list(search_username, user_numbers):
    """Pick the best user number for a user from a list of user numbers.

    If any any existing user's username matches the search username, pick
    that user.

    Otherwise, pick the first user that has no username set.

    If no users match those criteria, raise an IPMIError.
    """
    first_unused = None

    for user_number in user_numbers:
        # The IPMI spec reserves User1 as anonymous.
        if user_number == 'User1':
            continue

        username = bmc_user_get(user_number, 'Username')

        if username == search_username:
            return user_number

        # Usually a BMC won't include a Username value if the user is unused.
        # Some HP BMCs use "(Empty User)" to indicate a user in unused.
        if username in [None, '(Empty User)'] and first_unused is None:
            first_unused = user_number

    return first_unused


def pick_user_number(search_username):
    """Pick the best user number for a username."""
    user_numbers = list_user_numbers()
    user_number = pick_user_number_from_list(search_username, user_numbers)

    if not user_number:
        raise IPMIError('No IPMI user slots available.')

    return user_number


def is_ipmi_dhcp():
    output = bmc_get('Lan_Conf:IP_Address_Source')
    show_re = re.compile('IP_Address_Source\s+Use_DHCP')
    return show_re.search(output) is not None


def set_ipmi_network_source(source):
    bmc_set('Lan_Conf:IP_Address_Source', source)


def get_ipmi_ip_address():
    output = bmc_get('Lan_Conf:IP_Address')
    show_re = re.compile('([0-9]{1,3}[.]?){4}')
    res = show_re.search(output)
    return res.group()


def verify_ipmi_user_settings(user_number, user_settings):
    """Verify user settings were applied correctly."""

    bad_values = {}

    for key, expected_value in user_settings.items():
        # Password isn't included in checkout. Plus,
        # some older BMCs may not support Enable_User.
        if key not in ['Enable_User', 'Password']:
            value = bmc_user_get(user_number, key)
            if value != expected_value:
                bad_values[key] = value

    if len(bad_values) == 0:
        return

    errors_string = ' '.join([
        "for '%s', expected '%s', actual '%s';" % (
            key, user_settings[key], actual_value)
        for key, actual_value in bad_values.items()
        ]).rstrip(';')
    message = "IPMI user setting verification failures: %s." % (errors_string)
    raise IPMIError(message)


def apply_ipmi_user_settings(user_settings):
    """Commit and verify IPMI user settings."""
    username = user_settings['Username']
    ipmi_user_number = pick_user_number(username)

    for key, value in user_settings.items():
        bmc_user_set(ipmi_user_number, key, value)

    verify_ipmi_user_settings(ipmi_user_number, user_settings)


def make_ipmi_user_settings(username, password):
    """Factory for IPMI user settings."""
    # Some BMCs care about the order these settings are applied in.
    #
    # - Dell Poweredge R420 Systems require the username and password to
    # be set prior to the user being enabled.
    #
    # - Supermicro systems require the LAN Privilege Limit to be set
    # prior to enabling LAN IPMI msgs for the user.
    user_settings = OrderedDict((
        ('Username', username),
        ('Password', password),
        ('Enable_User', 'Yes'),
        ('Lan_Privilege_Limit', 'Administrator'),
        ('Lan_Enable_IPMI_Msgs', 'Yes'),
    ))
    return user_settings


def configure_ipmi_user(username, password):
    """Create or configure an IPMI user for remote use."""
    user_settings = make_ipmi_user_settings(username, password)
    apply_ipmi_user_settings(user_settings)


def commit_ipmi_settings(config):
    run_command(('bmc-config', '--commit', '--filename', config))


def get_maas_power_settings(user, password, ipaddress, version):
    return "%s,%s,%s,%s" % (user, password, ipaddress, version)


def get_maas_power_settings_json(user, password, ipaddress, version):
    power_params = {
        "power_address": ipaddress,
        "power_pass": password,
        "power_user": user,
        "power_driver": version,
    }
    return json.dumps(power_params)


def generate_random_password(min_length=8, max_length=15):
    length = random.randint(min_length, max_length)
    letters = string.ascii_letters + string.digits
    return ''.join([random.choice(letters) for _ in range(length)])


def bmc_supports_lan2_0():
    """Detect if BMC supports LAN 2.0."""
    output = run_command(('ipmi-locate'))
    return 'IPMI Version: 2.0' in output


def main():
    import argparse

    parser = argparse.ArgumentParser(
        description='send config file to modify IPMI settings with')
    parser.add_argument(
        "--configdir", metavar="folder", help="specify config file directory",
        default=None)
    parser.add_argument(
        "--dhcp-if-static", action="store_true", dest="dhcp",
        help="set network source to DHCP if Static", default=False)
    parser.add_argument(
        "--commission-creds", action="store_true", dest="commission_creds",
        help="Create IPMI temporary credentials", default=False)

    args = parser.parse_args()

    # Check whether IPMI is being set to DHCP. If it is not, and
    # '--dhcp-if-static' has been passed,  Set it to IPMI to DHCP.
    if not is_ipmi_dhcp() and args.dhcp:
        set_ipmi_network_source("Use_DHCP")
        # allow IPMI 120 seconds to obtain an IP address
        time.sleep(120)
    # create user/pass
    IPMI_MAAS_USER = "maas"
    IPMI_MAAS_PASSWORD = generate_random_password()

    configure_ipmi_user(IPMI_MAAS_USER, IPMI_MAAS_PASSWORD)

    # Commit other IPMI settings
    if args.configdir:
        for file in os.listdir(args.configdir):
            commit_ipmi_settings(os.path.join(args.configdir, file))

    # get the IP address
    IPMI_IP_ADDRESS = get_ipmi_ip_address()
    if IPMI_IP_ADDRESS == "0.0.0.0":
        # if IPMI_IP_ADDRESS is 0.0.0.0, wait 60 seconds and retry.
        set_ipmi_network_source("Static")
        time.sleep(2)
        set_ipmi_network_source("Use_DHCP")
        time.sleep(60)
        IPMI_IP_ADDRESS = get_ipmi_ip_address()

    if IPMI_IP_ADDRESS is None or IPMI_IP_ADDRESS == "0.0.0.0":
        # Exit (to not set power params in MAAS) if no IPMI_IP_ADDRESS
        # has been detected
        exit(1)

    if bmc_supports_lan2_0():
        IPMI_VERSION = "LAN_2_0"
    else:
        IPMI_VERSION = "LAN"
    if args.commission_creds:
        print(get_maas_power_settings_json(
            IPMI_MAAS_USER, IPMI_MAAS_PASSWORD, IPMI_IP_ADDRESS, IPMI_VERSION))
    else:
        print(get_maas_power_settings(
            IPMI_MAAS_USER, IPMI_MAAS_PASSWORD, IPMI_IP_ADDRESS, IPMI_VERSION))

if __name__ == '__main__':
    main()

END_MAAS_IPMI_AUTODETECT

add_bin "maas-moonshot-autodetect" <<"END_MAAS_MOONSHOT_AUTODETECT"
#!/usr/bin/python3

import argparse
import json
import re
import subprocess


IPMI_MAAS_USER = 'Administrator'
IPMI_MAAS_PASSWORD = 'password'


def get_local_address():
    output = subprocess.getoutput('ipmitool raw 0x2c 1 0')
    return "0x%s" % output.split()[2]


def get_cartridge_address(local_address):
    # obtain address of Cartridge Controller (parent of the system node):
    output = subprocess.getoutput(
        'ipmitool -t 0x20 -b 0 -m %s raw 0x2c 1 0' % local_address)
    return "0x%s" % output.split()[2]


def get_channel_number(address, output):
    # channel number (routing to this system node)
    show = re.compile(
        r'Device Slave Address\s+:\s+%sh(.*?)Channel Number\s+:\s+\d+'
        % address.replace('0x', '').upper(),
        re.DOTALL)
    res = show.search(output)
    return res.group(0).split()[-1]


def get_ipmi_ip_address(local_address):
    output = subprocess.getoutput(
        'ipmitool -B 0 -T 0x20 -b 0 -t 0x20 -m %s lan print 2' % local_address)
    show_re = re.compile('IP Address\s+:\s+([0-9]{1,3}[.]?){4}')
    res = show_re.search(output)
    return res.group().split()[-1]


def get_maas_power_settings(user, password, ipaddress, hwaddress):
    return "%s,%s,%s,%s" % (user, password, ipaddress, hwaddress)


def get_maas_power_settings_json(user, password, ipaddress, hwaddress):
    power_params = {
        "power_address": ipaddress,
        "power_pass": password,
        "power_user": user,
        "power_hwaddress": hwaddress,
    }
    return json.dumps(power_params)


def main():
    parser = argparse.ArgumentParser(
        description='send config file to modify IPMI settings with')
    parser.add_argument(
        "--commission-creds", action="store_true", dest="commission_creds",
        help="Create IPMI temporary credentials", default=False)

    args = parser.parse_args()

    local_address = get_local_address()
    node_address = get_cartridge_address(local_address)

    # Obtaining channel numbers:
    output = subprocess.getoutput(
        'ipmitool -b 0 -t 0x20 -m %s sdr list mcloc -v' % local_address)

    local_chan = get_channel_number(local_address, output)
    cartridge_chan = get_channel_number(node_address, output)

    # ipmitool -I lanplus -H 10.16.1.11 -U Administrator -P password -B 0
    #     -T 0x88 -b 7 -t 0x72 -m 0x20 power status
    IPMI_HW_ADDRESS = "-B %s -T %s -b %s -t %s -m 0x20" % (
        cartridge_chan,
        node_address,
        local_chan,
        local_address,
        )

    IPMI_IP_ADDRESS = get_ipmi_ip_address(local_address)

    if args.commission_creds:
        print(get_maas_power_settings_json(
            IPMI_MAAS_USER, IPMI_MAAS_PASSWORD, IPMI_IP_ADDRESS,
            IPMI_HW_ADDRESS))
    else:
        print(get_maas_power_settings(
            IPMI_MAAS_USER, IPMI_MAAS_PASSWORD, IPMI_IP_ADDRESS,
            IPMI_HW_ADDRESS))


if __name__ == '__main__':
    main()

END_MAAS_MOONSHOT_AUTODETECT

add_bin "maas_api_helper.py" <<"END_MAAS_API_HELPER"
from email.utils import parsedate
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

import oauthlib.oauth1 as oauth
import yaml


__all__ = [
    'geturl',
    'read_config',
    ]


def read_config(url, creds):
    """Read cloud-init config from given `url` into `creds` dict.

    Updates any keys in `creds` that are None with their corresponding
    values in the config.

    Important keys include `metadata_url`, and the actual OAuth
    credentials.
    """
    if url.startswith("http://") or url.startswith("https://"):
        cfg_str = urllib.request.urlopen(urllib.request.Request(url=url))
    else:
        if url.startswith("file://"):
            url = url[7:]
        cfg_str = open(url, "r").read()

    cfg = yaml.safe_load(cfg_str)

    # Support reading cloud-init config for MAAS datasource.
    if 'datasource' in cfg:
        cfg = cfg['datasource']['MAAS']

    for key in creds.keys():
        if key in cfg and creds[key] is None:
            creds[key] = cfg[key]


def oauth_headers(url, consumer_key, token_key, token_secret, consumer_secret,
                  clockskew=0):
    """Build OAuth headers using given credentials."""
    timestamp = int(time.time()) + clockskew
    client = oauth.Client(
        consumer_key,
        client_secret=consumer_secret,
        resource_owner_key=token_key,
        resource_owner_secret=token_secret,
        signature_method=oauth.SIGNATURE_PLAINTEXT,
        timestamp=str(timestamp))
    uri, signed_headers, body = client.sign(url)
    return signed_headers


def authenticate_headers(url, headers, creds, clockskew):
    """Update and sign a dict of request headers."""
    if creds.get('consumer_key', None) is not None:
        headers.update(oauth_headers(
            url,
            consumer_key=creds['consumer_key'],
            token_key=creds['token_key'],
            token_secret=creds['token_secret'],
            consumer_secret=creds['consumer_secret'],
            clockskew=clockskew))


def warn(msg):
    sys.stderr.write(msg + "\n")


def geturl(url, creds, headers=None, data=None):
    # Takes a dict of creds to be passed through to oauth_headers,
    #   so it should have consumer_key, token_key, ...
    if headers is None:
        headers = {}
    else:
        headers = dict(headers)

    clockskew = 0

    error = Exception("Unexpected Error")
    for naptime in (1, 1, 2, 4, 8, 16, 32):
        authenticate_headers(url, headers, creds, clockskew)
        try:
            req = urllib.request.Request(url=url, data=data, headers=headers)
            return urllib.request.urlopen(req).read()
        except urllib.error.HTTPError as exc:
            error = exc
            if 'date' not in exc.headers:
                warn("date field not in %d headers" % exc.code)
                pass
            elif exc.code in (401, 403):
                date = exc.headers['date']
                try:
                    ret_time = time.mktime(parsedate(date))
                    clockskew = int(ret_time - time.time())
                    warn("updated clock skew to %d" % clockskew)
                except:
                    warn("failed to convert date '%s'" % date)
        except Exception as exc:
            error = exc

        warn("request to %s failed. sleeping %d.: %s" % (url, naptime, error))
        time.sleep(naptime)

    raise error

END_MAAS_API_HELPER

add_bin "maas-signal" <<"END_MAAS_SIGNAL"
#!/usr/bin/python3

import json
import mimetypes
import os.path
import random
import socket
import string
import sys
import urllib.error
import urllib.parse
import urllib.request

from maas_api_helper import (
    geturl,
    read_config,
)


MD_VERSION = "2012-03-01"
VALID_STATUS = ("OK", "FAILED", "WORKING")
POWER_TYPES = ("ipmi", "virsh", "manual", "moonshot")


def _encode_field(field_name, data, boundary):
    assert isinstance(field_name, bytes)
    assert isinstance(data, bytes)
    assert isinstance(boundary, bytes)
    return (
        b'--' + boundary,
        b'Content-Disposition: form-data; name=\"' + field_name + b'\"',
        b'', data,
        )


def _encode_file(name, fileObj, boundary):
    assert isinstance(name, str)
    assert isinstance(boundary, bytes)
    byte_name = name.encode("utf-8")
    return (
        b'--' + boundary,
        (
            b'Content-Disposition: form-data; name=\"' + byte_name + b'\"; ' +
            b'filename=\"' + byte_name + b'\"'
        ),
        b'Content-Type: ' + _get_content_type(name).encode("utf-8"),
        b'',
        fileObj.read(),
        )


def _random_string(length):
    return b''.join(
        random.choice(string.ascii_letters).encode("ascii")
        for ii in range(length + 1)
    )


def _get_content_type(filename):
    return mimetypes.guess_type(filename)[0] or 'application/octet-stream'


def encode_multipart_data(data, files):
    """Create a MIME multipart payload from L{data} and L{files}.

    @param data: A mapping of names (ASCII strings) to data (byte string).
    @param files: A mapping of names (ASCII strings) to file objects ready to
        be read.
    @return: A 2-tuple of C{(body, headers)}, where C{body} is a a byte string
        and C{headers} is a dict of headers to add to the enclosing request in
        which this payload will travel.
    """
    boundary = _random_string(30)

    lines = []
    for name in data:
        lines.extend(_encode_field(name, data[name], boundary))
    for name in files:
        lines.extend(_encode_file(name, files[name], boundary))
    lines.extend((b'--' + boundary + b'--', b''))
    body = b'\r\n'.join(lines)

    headers = {
        'Content-Type': (
            'multipart/form-data; boundary=' + boundary.decode("ascii")),
        'Content-Length': str(len(body)),
    }

    return body, headers


def fail(msg):
    sys.stderr.write("FAIL: %s" % msg)
    sys.exit(1)


def main():
    """
    Call with single argument of directory or http or https url.
    If url is given additional arguments are allowed, which will be
    interpreted as consumer_key, token_key, token_secret, consumer_secret.
    """
    import argparse

    parser = argparse.ArgumentParser(
        description='Send signal operation and optionally post files to MAAS')
    parser.add_argument(
        "--config", metavar="file", help="Specify config file", default=None)
    parser.add_argument(
        "--ckey", metavar="key", help="The consumer key to auth with",
        default=None)
    parser.add_argument(
        "--tkey", metavar="key", help="The token key to auth with",
        default=None)
    parser.add_argument(
        "--csec", metavar="secret", help="The consumer secret (likely '')",
        default="")
    parser.add_argument(
        "--tsec", metavar="secret", help="The token secret to auth with",
        default=None)
    parser.add_argument(
        "--apiver", metavar="version",
        help="The apiver to use (\"\" can be used)", default=MD_VERSION)
    parser.add_argument(
        "--url", metavar="url", help="The data source to query", default=None)
    parser.add_argument(
        "--file", dest='files', help="File to post", action='append',
        default=[])
    parser.add_argument(
        "--post", dest='posts', help="name=value pairs to post",
        action='append', default=[])
    parser.add_argument(
        "--power-type", dest='power_type', help="Power type.",
        choices=POWER_TYPES, default=None)
    parser.add_argument(
        "--power-parameters", dest='power_parms', help="Power parameters.",
        default=None)
    parser.add_argument(
        "--script-result", metavar="retval", type=int, dest='script_result',
        help="Return code of a commissioning script.")

    parser.add_argument(
        "status", help="Status", choices=VALID_STATUS, action='store')
    parser.add_argument(
        "message", help="Optional message", default="", nargs='?')

    args = parser.parse_args()

    creds = {
        'consumer_key': args.ckey,
        'token_key': args.tkey,
        'token_secret': args.tsec,
        'consumer_secret': args.csec,
        'metadata_url': args.url,
        }

    if args.config:
        read_config(args.config, creds)

    url = creds.get('metadata_url', None)
    if not url:
        fail("URL must be provided either in --url or in config\n")
    url = "%s/%s/" % (url, args.apiver)

    params = {
        b"op": b"signal",
        b"status": args.status.encode("utf-8"),
        b"error": args.message.encode("utf-8"),
        }

    if args.script_result is not None:
        params[b'script_result'] = str(args.script_result).encode("utf-8")

    for ent in args.posts:
        try:
            (key, val) = ent.split("=", 2)
        except ValueError:
            sys.stderr.write("'%s' had no '='" % ent)
            sys.exit(1)
        params[key.encode("utf-8")] = val.encode("utf-8")

    if args.power_parms is not None:
        params[b"power_type"] = args.power_type.encode("utf-8")
        if params[b"power_type"] == b"moonshot":
            user, passwd, address, hwaddress = args.power_parms.split(",")
            power_parms = dict(
                power_user=user,
                power_pass=passwd,
                power_address=address,
                power_hwaddress=hwaddress
                )
        else:
            user, passwd, address, driver = args.power_parms.split(",")
            power_parms = dict(
                power_user=user,
                power_pass=passwd,
                power_address=address,
                power_driver=driver
                )
        params[b"power_parameters"] = json.dumps(power_parms).encode()

    files = {}
    for fpath in args.files:
        files[os.path.basename(fpath)] = open(fpath, "rb")

    data, headers = encode_multipart_data(params, files)

    error = None
    msg = ""

    try:
        payload = geturl(url, creds=creds, headers=headers, data=data)
        if payload != b"OK":
            raise TypeError("Unexpected result from call: %s" % payload)
        else:
            msg = "Success"
    except urllib.error.HTTPError as exc:
        error = exc
        msg = "http error [%s]" % exc.code
    except urllib.error.URLError as exc:
        error = exc
        msg = "url error [%s]" % exc.reason
    except socket.timeout as exc:
        error = exc
        msg = "socket timeout [%s]" % exc
    except TypeError as exc:
        error = exc
        msg = str(exc)
    except Exception as exc:
        error = exc
        msg = "unexpected error [%s]" % exc

    sys.stderr.write("%s\n" % msg)
    sys.exit((error is None))

if __name__ == '__main__':
    main()

END_MAAS_SIGNAL

add_bin "maas-get" <<END_MAAS_GET
#!/usr/bin/python3

import sys

from maas_api_helper import (
    geturl,
    read_config,
)


MD_VERSION = "2012-03-01"


def main():
    """Authenticate, and download file from MAAS metadata API."""
    import argparse

    parser = argparse.ArgumentParser(
        description="GET file from MAAS metadata API.")
    parser.add_argument(
        "--config", metavar="file",
        help="Config file containing MAAS API credentials", default=None)
    parser.add_argument(
        "--apiver", metavar="version", help="Use given API version",
        default=MD_VERSION)
    parser.add_argument('path')

    args = parser.parse_args()

    creds = {
        'consumer_key': None,
        'token_key': None,
        'token_secret': None,
        'consumer_secret': '',
        'metadata_url': None,
    }
    read_config(args.config, creds)
    url = "%s/%s/%s" % (
        creds['metadata_url'],
        args.apiver,
        args.path,
        )

    sys.stdout.buffer.write(geturl(url, creds))

if __name__ == '__main__':
    main()

END_MAAS_GET


main
exit
Download as text