This file is indexed.

/usr/share/pyshared/lsm/cmdline.py is in python-libstoragemgmt 0.0.20-2.

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

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
# Copyright (C) 2012 Red Hat, Inc.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
#
# Author: tasleson
from optparse import OptionParser, OptionGroup
import optparse
import os
import re
import string
import textwrap
import sys
import getpass
import time

import common
import client
import data
from version import VERSION
from data import Capabilities

##@package lsm.cmdline


## Users are reporting errors with broken pipe when piping output
# to another program.  This appears to be related to this issue:
# http://bugs.python.org/issue11380
# Unable to reproduce, but hopefully this will address it.
# @param msg    The message to be written to stdout
def out(msg):
    try:
        sys.stdout.write(str(msg))
        sys.stdout.write("\n")
        sys.stdout.flush()
    except IOError:
        sys.exit(1)


## Wraps the invocation to the command line
# @param    client  Object to invoke calls on (optional)
def cmd_line_wrapper(client=None):
    """
    Common command line code, called.
    """
    try:
        cli = CmdLine()
        cli.process(client)
    except ArgError as ae:
        sys.stderr.write(str(ae))
        sys.stderr.flush()
        sys.exit(2)
    except common.LsmError as le:
        sys.stderr.write(str(le) + "\n")
        sys.stderr.flush()
        sys.exit(4)
    except KeyboardInterrupt:
        sys.exit(1)


## Simple class used to handle \n in optparse output
class MyWrapper:
    """
    Handle \n in text for the command line help etc.
    """

    @staticmethod
    def wrap(text, width=70, **kw):
        rc = []
        for line in text.split("\n"):
            rc.extend(textwrap.wrap(line, width, **kw))
        return rc

    @staticmethod
    def fill(text, width=70, **kw):
        rc = []
        for line in text.split("\n"):
            rc.append(textwrap.fill(line, width, **kw))
        return "\n".join(rc)


## This class represents a command line argument error
class ArgError(Exception):
    def __init__(self, message, *args, **kwargs):
        """
        Class represents an error.
        """
        Exception.__init__(self, *args, **kwargs)
        self.msg = message

    def __str__(self):
        return "%s: error: %s\n" % (os.path.basename(sys.argv[0]), self.msg)


## Prefixes cmd with "cmd_"
# @param    cmd     The command to prefix with cmd_"
# @return   The cmd string prefixed with "cmd_"
def _c(cmd):
    return "cmd_" + cmd


## Prefixes option with "opt_"
# @param    option  The option to prefix with "opt_"
# @return   The option string prefixed with "opt_"
def _o(option):
    return "opt_" + option


## Class that encapsulates the command line arguments for lsmcli
# Note: This class is used by lsmcli and any python plug-ins.
class CmdLine:
    """
    Command line interface class.
    """

    ##
    # Warn of imminent data loss
    # @param    deleting    Indicate data will be lost vs. may be lost (re-size)
    # @return True if operation confirmed, else False
    def confirm_prompt(self, deleting):
        """
        Give the user a chance to bail.
        """
        if not self.options.force:
            msg = "will" if deleting else "may"
            out("Warning: You are about to do an operation that %s cause data "
                "to be lost!\nPress [Y|y] to continue, any other key to abort"
                % msg)

            pressed = common.getch()
            if pressed.upper() == 'Y':
                return True
            else:
                out('Operation aborted!')
                return False
        else:
            return True

    ##
    # Tries to make the output better when it varies considerably from
    # plug-in to plug-in.
    # @param    rows    Data, first row is header all other data.
    def display_table(self, rows):
        """
        Creates a nicer text dump of tabular data.  First row should be the
        column headers.
        """
        #If any of the table cells is another list, lets flatten using the sep
        for i in range(len(rows)):
            for j in range(len(rows[i])):
                if isinstance(rows[i][j], list):
                    rows[i][j] = self._list(rows[i][j])

        if self.options.sep is not None:
            s = self.options.sep

            #See if we want to display the header or not!
            start = 1
            if self.options.header:
                start = 0

            for i in range(start, len(rows)):
                out(s.join([str(x) for x in rows[i]]))

        else:
            if len(rows) >= 2:
                #Get the max length of each column
                lens = []
                for l in zip(*rows):
                    lens.append(max(len(str(x)) for x in l))
                data_formats = []
                header_formats = []

                #Build the needed format
                for i in range(len(rows[0])):
                    header_formats.append("%%-%ds" % lens[i])

                    #If the row contains numerical data we will right justify.
                    if isinstance(rows[1][i], int):
                        data_formats.append("%%%dd" % lens[i])
                    else:
                        data_formats.append("%%-%ds" % lens[i])

                #Print the header, header separator and then row data.
                header_pattern = " | ".join(header_formats)
                out(header_pattern % tuple(rows[0]))
                out("-+-".join(['-' * n for n in lens]))
                data_pattern = " | ".join(data_formats)

                for i in range(1, len(rows)):
                    out(data_pattern % tuple(rows[i]))

    def display_data(self, d):

        if d and len(d):

            rows = d[0].column_headers()

            for r in d:
                rows.extend(
                    r.column_data(self.options.human, self.options.enum))

            self.display_table(rows)

    ## All the command line arguments and options are created in this method
    # @param    self    The this object pointer
    def cli(self):
        """
        Command line interface parameters
        """
        usage = "usage: %prog [options]... [command]... [command options]..."
        optparse.textwrap = MyWrapper
        parser = OptionParser(usage=usage, version="%prog " + VERSION)
        parser.description = 'libStorageMgmt command line interface. \n'

        parser.epilog = ('Copyright 2012-2013 Red Hat, Inc.\n'
                         'Please report bugs to '
                         '<libstoragemgmt-devel@lists.sourceforge.net>\n')

        parser.add_option('-u', '--uri', action="store", type="string",
                          dest="uri",
                          help='uniform resource identifier (env LSMCLI_URI)')
        parser.add_option('-P', '--prompt', action="store_true", dest="prompt",
                          help='prompt for password (env LSMCLI_PASSWORD)')
        parser.add_option('-H', '--human', action="store_true", dest="human",
                          help='print sizes in human readable format\n'
                               '(e.g., MiB, GiB, TiB)')
        parser.add_option('-t', '--terse', action="store", dest="sep",
                          help='print output in terse form with "SEP" '
                               'as a record separator')

        parser.add_option('-e', '--enum', action="store_true", dest="enum",
                          default=False,
                          help='display enumerated types as numbers '
                               'instead of text')

        parser.add_option('-f', '--force', action="store_true", dest="force",
                          default=False,
                          help='bypass confirmation prompt for data '
                               'loss operations')

        parser.add_option('-w', '--wait', action="store", type="int",
                          dest="wait", default=30000,
                          help="command timeout value in ms (default = 30s)")

        parser.add_option('', '--header', action="store_true", dest="header",
                          help='include the header with terse')

        parser.add_option('-b', '', action="store_true", dest="async",
                          default=False,
                          help='run the command async. instead of waiting '
                               'for completion\n'
                               'command will exit(7) and job id written '
                               'to stdout.')

        #What action we want to take
        commands = OptionGroup(parser, 'Commands')

        list_choices = ['VOLUMES', 'INITIATORS', 'POOLS', 'FS', 'SNAPSHOTS',
                        'EXPORTS', "NFS_CLIENT_AUTH", 'ACCESS_GROUPS',
                        'SYSTEMS']

        commands.add_option('-l', '--list', action="store", type="choice",
                            dest="cmd_list",
                            #metavar='<'+ ",".join(list_choices) + '>',
                            metavar='<type>',
                            choices=list_choices,
                            help='List records of type: ' + ",".join(
                                list_choices) + '\n'
                                                'Note: SNAPSHOTS requires '
                                                '--fs <fs id>')

        commands.add_option('', '--capabilities', action="store", type="string",
                            dest=_c("capabilities"),
                            metavar='<system id>',
                            help='Retrieves array capabilities')

        commands.add_option('', '--plugin-info', action="store_true",
                            dest=_c("plugin-info"),
                            help='Retrieves plugin description and version')

        commands.add_option('', '--delete-fs', action="store", type="string",
                            dest=_c("delete-fs"),
                            metavar='<fs id>',
                            help='Delete a filesystem')

        commands.add_option('', '--delete-access-group', action="store",
                            type="string",
                            dest=_c("delete-access-group"),
                            metavar='<group id>',
                            help='Deletes an access group')

        commands.add_option('', '--access-group-add', action="store",
                            type="string",
                            dest=_c("access-group-add"),
                            metavar='<access group id>',
                            help='Adds an initiator to an access group, '
                                 'requires:\n'
                                 '--id <initiator id\n'
                                 '--type <initiator type>')

        commands.add_option('', '--access-group-remove', action="store",
                            type="string",
                            dest=_c("access-group-remove"),
                            metavar='<access group id>',
                            help='Removes an initiator from an access group, '
                                 'requires:\n'
                                 '--id <initiator id>')

        commands.add_option('', '--create-volume', action="store",
                            type="string",
                            dest=_c("create-volume"),
                            metavar='<volume name>',
                            help="Creates a volume (logical unit) requires:\n"
                                 "--size <volume size>\n"
                                 "--pool <pool id>\n"
                                 "--provisioning (optional) "
                                 "[DEFAULT|THIN|FULL]\n")

        commands.add_option('', '--create-fs', action="store", type="string",
                            dest=_c("create-fs"),
                            metavar='<fs name>',
                            help="Creates a file system requires:\n"
                                 "--size <fs size>\n"
                                 "--pool <pool id>")

        commands.add_option('', '--create-ss', action="store", type="string",
                            dest=_c("create-ss"),
                            metavar='<snapshot name>',
                            help="Creates a snapshot, requires:\n"
                                 "--file <repeat for each file>(default "
                                 "is all files)\n"
                                 "--fs <file system id>")

        commands.add_option('', '--create-access-group', action="store",
                            type="string",
                            dest=_c("create-access-group"),
                            metavar='<Access group name>',
                            help="Creates an access group, requires:\n"
                                 "--id <initiator id>\n"
                                 '--type [WWPN|WWNN|ISCSI|HOSTNAME]\n'
                                 '--system <system id>')

        commands.add_option('', '--access-group-volumes', action="store",
                            type="string",
                            dest=_c("access-group-volumes"),
                            metavar='<access group id>',
                            help='Lists the volumes that the access group has'
                                 ' been granted access to')

        commands.add_option('', '--volume-access-group', action="store",
                            type="string",
                            dest=_c("volume-access-group"),
                            metavar='<volume id>',
                            help='Lists the access group(s) that have access'
                                 ' to volume')

        commands.add_option('', '--volumes-accessible-initiator',
                            action="store", type="string",
                            dest=_c("volumes-accessible-initiator"),
                            metavar='<initiator id>',
                            help='Lists the volumes that are accessible '
                                 'by the initiator')

        commands.add_option('', '--initiators-granted-volume', action="store",
                            type="string",
                            dest=_c("initiators-granted-volume"),
                            metavar='<volume id>',
                            help='Lists the initiators that have been '
                                 'granted access to specified volume')

        commands.add_option('', '--restore-ss', action="store", type="string",
                            dest=_c("restore-ss"),
                            metavar='<snapshot id>',
                            help="Restores a FS or specified files to "
                                 "previous snapshot state, requires:\n"
                                 "--fs <file system>\n"
                                 "--file <repeat for each file (optional)>\n"
                                 "--fileas <restore file name (optional)>\n"
                                 "--all (optional, exclusive option, "
                                 "restores all files in snapshot other "
                                 "options must be absent)")

        commands.add_option('', '--clone-fs', action="store", type="string",
                            dest=_c("clone-fs"),
                            metavar='<source file system id>',
                            help="Creates a file system clone requires:\n"
                                 "--name <file system clone name>\n"
                                 "--backing-snapshot <backing snapshot id> "
                                 "(optional)")

        commands.add_option('', '--clone-file', action="store", type="string",
                            dest=_c("clone-file"),
                            metavar='<file system>',
                            help="Creates a clone of a file (thin "
                                 "provisioned):\n"
                                 "--src  <source file to clone "
                                 "(relative path)>\n"
                                 "--dest <destination file (relative path)>\n"
                                 "--backing-snapshot <backing snapshot id> "
                                 "(optional)")

        commands.add_option('', '--delete-volume', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("delete-volume"),
                            help='Deletes a volume given its id')

        commands.add_option('', '--delete-ss', action="store", type="string",
                            metavar='<snapshot id>',
                            dest=_c("delete-ss"),
                            help='Deletes a snapshot requires --fs')

        commands.add_option('-r', '--replicate-volume', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("replicate-volume"),
                            help='replicates a volume, requires:\n'
                                 "--type [SNAPSHOT|CLONE|COPY|MIRROR_ASYNC|"
                                 "MIRROR_SYNC]\n"
                                 "--name <human name>\n"
                                 "Optional:\n"
                                 "--pool <pool id>\n")

        commands.add_option('', '--replicate-volume-range-block-size',
                            action="store", type="string",
                            metavar='<system id>',
                            dest=_c("replicate-volume-range-block-size"),
                            help='size of each replicated block in bytes')

        commands.add_option('', '--replicate-volume-range', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("replicate-volume-range"),
                            help='replicates a portion of a volume, requires:\n'
                                 "--type [SNAPSHOT|CLONE|COPY|MIRROR]\n"
                                 "--dest <destination volume>\n"
                                 "--src_start <source block start number>\n"
                                 "--dest_start <destination block start>\n"
                                 "--count <number of blocks to replicate>")

        commands.add_option('', '--iscsi-chap', action="store", type="string",
                            metavar='<initiator id>',
                            dest=_c("iscsi-chap"),
                            help='configures ISCSI inbound/outbound CHAP '
                                 'authentication\n'
                                 'Optional:\n'
                                 '--in-user <inbound chap user name>\n'
                                 '--in-password <inbound chap password>\n'
                                 '--out-user <outbound chap user name>\n'
                                 '--out-password <inbound chap user password\n')

        commands.add_option('', '--access-grant', action="store", type="string",
                            metavar='<initiator id>',
                            dest=_c("access-grant"),
                            help='grants access to an initiator to a volume\n'
                                 'requires:\n'
                                 '--type <initiator id type>\n'
                                 '--volume <volume id>\n'
                                 '--access [RO|RW], read-only or read-write')

        commands.add_option('', '--access-grant-group', action="store",
                            type="string",
                            metavar='<access group id>',
                            dest=_c("access-grant-group"),
                            help='grants access to an access group to a '
                                 'volume\n'
                                 'requires:\n'
                                 '--volume <volume id>\n'
                                 '--access [RO|RW], read-only or read-write')

        commands.add_option('', '--access-revoke', action="store",
                            type="string",
                            metavar='<initiator id>',
                            dest=_c("access-revoke"),
                            help='removes access for an initiator to a volume\n'
                                 'requires:\n'
                                 '--volume <volume id>')

        commands.add_option('', '--access-revoke-group', action="store",
                            type="string",
                            metavar='<access group id>',
                            dest=_c("access-revoke-group"),
                            help='removes access for access group to a volume\n'
                                 'requires:\n'
                                 '--volume <volume id>')

        commands.add_option('', '--resize-volume', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("resize-volume"),
                            help='re-sizes a volume, requires:\n'
                                 '--size <new size>')

        commands.add_option('', '--resize-fs', action="store", type="string",
                            metavar='<fs id>',
                            dest=_c("resize-fs"),
                            help='re-sizes a file system, requires:\n'
                                 '--size <new size>')

        commands.add_option('', '--nfs-export-remove', action="store",
                            type="string",
                            metavar='<nfs export id>',
                            dest=_c("nfs-export-remove"),
                            help='removes a nfs export')

        commands.add_option('', '--nfs-export-fs', action="store",
                            type="string",
                            metavar='<file system id>',
                            dest=_c("nfs-export-fs"),
                            help='creates a nfs export\n'
                                 'Optional:\n'
                                 '--exportpath e.g. /foo/bar\n'
                                 'Note: root, ro, rw are to be repeated for '
                                 'each host\n'
                                 '--root <no_root_squash host>\n'
                                 '--ro <read only host>\n'
                                 '--rw <read/write host>\n'
                                 '--anonuid <uid to map to anonymous>\n'
                                 '--anongid <gid to map to anonymous>\n'
                                 '--auth-type <NFS client authentication '
                                 'type>\n')

        commands.add_option('', '--job-status', action="store", type="string",
                            metavar='<job status id>',
                            dest=_c("job-status"),
                            help='retrieve information about job')

        commands.add_option('', '--volume-dependants', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("volume-dependants"),
                            help='Returns True if volume has a dependant child')

        commands.add_option('', '--volume-dependants-rm', action="store",
                            type="string",
                            metavar='<volume id>',
                            dest=_c("volume-dependants-rm"),
                            help='Removes dependencies')

        commands.add_option('', '--fs-dependants', action="store",
                            type="string",
                            metavar='<fs id>',
                            dest=_c("fs-dependants"),
                            help='Returns true if a child dependency exists.\n'
                                 'Optional:\n'
                                 '--file <file> for File check')

        commands.add_option('', '--fs-dependants-rm', action="store",
                            type="string",
                            metavar='<fs id>',
                            dest=_c("fs-dependants-rm"),
                            help='Removes dependencies\n'
                                 'Optional:\n'
                                 '--file <file> for File check')

        parser.add_option_group(commands)

        #Options to the actions
        #We could hide these with help = optparse.SUPPRESS_HELP
        #Should we?
        command_args = OptionGroup(parser, 'Command options')
        command_args.add_option('', '--size', action="store", type="string",
                                metavar='size',
                                dest=_o("size"),
                                help='size (Can use B, K, M, G, T, P postfix '
                                     '(IEC sizing)')
        command_args.add_option('', '--pool', action="store", type="string",
                                metavar='pool id',
                                dest=_o("pool"), help='pool ID')
        command_args.add_option('', '--provisioning', action="store",
                                type="choice",
                                default='DEFAULT',
                                choices=['DEFAULT', 'THIN', 'FULL'],
                                dest="provisioning", help='[DEFAULT|THIN|FULL]')

        command_args.add_option('', '--type', action="store", type="choice",
                                choices=['WWPN', 'WWNN', 'ISCSI', 'HOSTNAME',
                                         'SNAPSHOT', 'CLONE', 'COPY',
                                         'MIRROR_SYNC', 'MIRROR_ASYNC'],
                                metavar="type",
                                dest=_o("type"), help='type specifier')

        command_args.add_option('', '--name', action="store", type="string",
                                metavar="name",
                                dest=_o("name"),
                                help='human readable name')

        command_args.add_option('', '--volume', action="store", type="string",
                                metavar="volume",
                                dest=_o("volume"), help='volume ID')

        command_args.add_option('', '--access', action="store", type="choice",
                                metavar="access",
                                dest=_o("access"), choices=['RO', 'RW'],
                                help='[RO|RW], read-only or read-write access')

        command_args.add_option('', '--id', action="store", type="string",
                                metavar="initiator id",
                                dest=_o("id"), help="initiator id")

        command_args.add_option('', '--system', action="store", type="string",
                                metavar="system id",
                                dest=_o("system"), help="system id")

        command_args.add_option('', '--backing-snapshot', action="store",
                                type="string",
                                metavar="<backing snapshot>", default=None,
                                dest="backing_snapshot",
                                help="backing snap shot name for operation")

        command_args.add_option('', '--src', action="store", type="string",
                                metavar="<source file>", default=None,
                                dest=_o("src"), help="source of operation")

        command_args.add_option('', '--dest', action="store", type="string",
                                metavar="<source file>", default=None,
                                dest=_o("dest"),
                                help="destination of operation")

        command_args.add_option('', '--file', action="append", type="string",
                                metavar="<file>", default=[],
                                dest="file",
                                help="file to include in operation, option "
                                     "can be repeated")

        command_args.add_option('', '--fileas', action="append", type="string",
                                metavar="<fileas>", default=[],
                                dest="fileas",
                                help="file to be renamed as, option can "
                                     "be repeated")

        command_args.add_option('', '--fs', action="store", type="string",
                                metavar="<file system>", default=None,
                                dest=_o("fs"), help="file system of interest")

        command_args.add_option('', '--exportpath', action="store",
                                type="string",
                                metavar="<path for export>", default=None,
                                dest=_o("exportpath"),
                                help="desired export path on array")

        command_args.add_option('', '--root', action="append", type="string",
                                metavar="<no_root_squash_host>", default=[],
                                dest="nfs_root",
                                help="list of hosts with no_root_squash")

        command_args.add_option('', '--ro', action="append", type="string",
                                metavar="<read only host>", default=[],
                                dest="nfs_ro",
                                help="list of hosts with read/only access")

        command_args.add_option('', '--rw', action="append", type="string",
                                metavar="<read/write host>", default=[],
                                dest="nfs_rw",
                                help="list of hosts with read/write access")

        command_args.add_option('', '--anonuid', action="store", type="string",
                                metavar="<anonymous uid>", default=None,
                                dest="anonuid", help="uid to map to anonymous")

        command_args.add_option('', '--anongid', action="store", type="string",
                                metavar="<anonymous uid>", default=None,
                                dest="anongid", help="gid to map to anonymous")

        command_args.add_option('', '--authtype', action="store", type="string",
                                metavar="<type>", default=None,
                                dest="authtype",
                                help="NFS client authentication type")

        command_args.add_option('', '--all', action="store_true", dest="all",
                                default=False,
                                help='specify all in an operation')

        command_args.add_option('', '--src_start', action="append", type="int",
                                metavar="<source block start>", default=None,
                                dest=_o("src_start"),
                                help="source block address to replicate")

        command_args.add_option('', '--dest_start', action="append", type="int",
                                metavar="<dest. block start>", default=None,
                                dest=_o("dest_start"),
                                help="destination block address to replicate")

        command_args.add_option('', '--count', action="append", type="int",
                                metavar="<block count>", default=None,
                                dest=_o("count"),
                                help="number of blocks to replicate")

        command_args.add_option('', '--in-user', action="store", type="string",
                                metavar="<username>", default=None,
                                dest=_o("username"),
                                help="CHAP inbound user name")

        command_args.add_option('', '--in-password', action="store", type="string",
                                metavar="<password>", default=None,
                                dest=_o("password"),
                                help="CHAP inbound password")

        command_args.add_option('', '--out-user', action="store", type="string",
                                metavar="<out_user>", default=None,
                                dest=_o("out_user"),
                                help="CHAP outbound user name")

        command_args.add_option('', '--out-password', action="store",
                                type="string",
                                metavar="<out_password>", default=None,
                                dest=_o("out_password"),
                                help="CHAP outbound password")

        parser.add_option_group(command_args)

        (self.options, self.args) = parser.parse_args()

    ## Checks to make sure only one command was specified on the command line
    # @param    self    The this pointer
    # @return   tuple of command to execute and the value of the command
    #           argument
    def _cmd(self):
        cmds = [e[4:] for e in dir(self.options)
                if e[0:4] == "cmd_" and self.options.__dict__[e] is not None]
        if len(cmds) > 1:
            raise ArgError(
                "More than one command operation specified (" + ",".join(
                    cmds) + ")")

        if len(cmds) == 1:
            return cmds[0], self.options.__dict__['cmd_' + cmds[0]]
        else:
            return None, None

    ## Validates that the required options for a given command are present.
    # @param    self    The this pointer
    # @return   None
    def _validate(self):
        optional_opts = 0
        expected_opts = self.verify[self.cmd]['options']
        actual_ops = [e[4:] for e in dir(self.options)
                      if
                      e[0:4] == "opt_" and self.options.__dict__[e] is not None]

        if 'optional' in self.verify[self.cmd]:
            optional_opts = len(self.verify[self.cmd]['optional'])

        if len(expected_opts):
            if (optional_opts + len(expected_opts)) >= len(actual_ops):
                for e in expected_opts:
                    if e not in actual_ops:
                        out("expected=" + ":".join(expected_opts))
                        out("actual=" + ":".join(actual_ops))
                        raise ArgError("missing option " + e)

            else:
                raise ArgError("expected options = (" +
                               ",".join(expected_opts) + ") actual = (" +
                               ",".join(actual_ops) + ")")

        #Check size
        if self.options.opt_size:
            self._size(self.options.opt_size)

    def _list(self, l):
        if l and len(l):
            if self.options.sep:
                return self.options.sep.join(l)
            else:
                return ", ".join(l)
        else:
            return "None"

    ## Display the types of nfs client authentication that are supported.
    # @param    self    The this pointer
    # @return None
    def display_nfs_client_authentication(self):
        """
        Dump the supported nfs client authentication types
        """
        if self.options.sep:
            out(self.options.sep.join(self.c.export_auth()))
        else:
            out(", ".join(self.c.export_auth()))

    ## Method that calls the appropriate method based on what the cmd_value is
    # @param    self    The this pointer
    def list(self):
        if self.cmd_value == 'VOLUMES':
            self.display_data(self.c.volumes())
        elif self.cmd_value == 'POOLS':
            self.display_data(self.c.pools())
        elif self.cmd_value == 'FS':
            self.display_data(self.c.fs())
        elif self.cmd_value == 'SNAPSHOTS':
            if self.options.opt_fs is None:
                raise ArgError("--fs <file system id> required")

            fs = self._get_item(self.c.fs(), self.options.opt_fs)
            if fs:
                self.display_data(self.c.fs_snapshots(fs))
            else:
                raise ArgError(
                    "filesystem %s not found!" % self.options.opt_volume)
        elif self.cmd_value == 'INITIATORS':
            self.display_data(self.c.initiators())
        elif self.cmd_value == 'EXPORTS':
            self.display_data(self.c.exports())
        elif self.cmd_value == 'NFS_CLIENT_AUTH':
            self.display_nfs_client_authentication()
        elif self.cmd_value == 'ACCESS_GROUPS':
            self.display_data(self.c.access_group_list())
        elif self.cmd_value == 'SYSTEMS':
            self.display_data(self.c.systems())
        else:
            raise ArgError(" unsupported listing type=%s", self.cmd_value)

    ## Converts type initiator type to enumeration type.
    # @param    type    String representation of type
    # @returns  Enumerated value
    @staticmethod
    def _init_type_to_enum(init_type):
        if init_type == 'WWPN':
            i = data.Initiator.TYPE_PORT_WWN
        elif init_type == 'WWNN':
            i = data.Initiator.TYPE_NODE_WWN
        elif init_type == 'ISCSI':
            i = data.Initiator.TYPE_ISCSI
        elif init_type == 'HOSTNAME':
            i = data.Initiator.TYPE_HOSTNAME
        else:
            raise ArgError("invalid initiator type " + init_type)
        return i

    ## Creates an access group.
    # @param    self    The this pointer
    def create_access_group(self):
        name = self.cmd_value
        initiator = self.options.opt_id
        i = CmdLine._init_type_to_enum(self.options.opt_type)
        access_group = self.c.access_group_create(name, initiator, i,
                                                  self.options.opt_system)
        self.display_data([access_group])

    def _add_rm_access_grp_init(self, op):
        agl = self.c.access_group_list()
        group = self._get_item(agl, self.cmd_value)

        if group:
            if op:
                i = CmdLine._init_type_to_enum(self.options.opt_type)
                self.c.access_group_add_initiator(group, self.options.opt_id, i)
            else:
                i = self._get_item(self.c.initiators(), self.options.opt_id)
                if i:
                    self.c.access_group_del_initiator(group, i.id)
                else:
                    raise ArgError(
                        "initiator with id %s not found!" % self.options.opt_id)
        else:
            if not group:
                raise ArgError(
                    'access group with id %s not found!' % self.cmd_value)

    ## Adds an initiator from an access group
    def access_group_add(self):
        self._add_rm_access_grp_init(True)

    ## Removes an initiator from an access group
    def access_group_remove(self):
        self._add_rm_access_grp_init(False)

    def access_group_volumes(self):
        agl = self.c.access_group_list()
        group = self._get_item(agl, self.cmd_value)

        if group:
            vols = self.c.volumes_accessible_by_access_group(group)
            self.display_data(vols)
        else:
            raise ArgError(
                'access group with id %s not found!' % self.cmd_value)

    def volume_accessible_init(self):
        i = self._get_item(self.c.initiators(), self.cmd_value)

        if i:
            volumes = self.c.volumes_accessible_by_initiator(i)
            self.display_data(volumes)
        else:
            raise ArgError("initiator with id= %s not found!" % self.cmd_value)

    def init_granted_volume(self):
        vol = self._get_item(self.c.volumes(), self.cmd_value)

        if vol:
            initiators = self.c.initiators_granted_to_volume(vol)
            self.display_data(initiators)
        else:
            raise ArgError("volume with id= %s not found!" % self.cmd_value)

    def iscsi_chap(self):
        init = self._get_item(self.c.initiators(), self.cmd_value)
        if init:
            self.c.iscsi_chap_auth(init, self.options.opt_username,
                                   self.options.opt_password,
                                   self.options.opt_out_user,
                                   self.options.opt_out_password)
        else:
            raise ArgError("initiator with id= %s not found" % self.cmd_value)

    def volume_access_group(self):
        vol = self._get_item(self.c.volumes(), self.cmd_value)

        if vol:
            groups = self.c.access_groups_granted_to_volume(vol)
            self.display_data(groups)
        else:
            raise ArgError("volume with id= %s not found!" % self.cmd_value)

    ## Used to delete access group
    # @param    self    The this pointer
    def delete_access_group(self):
        agl = self.c.access_group_list()

        group = self._get_item(agl, self.cmd_value)
        if group:
            return self.c.access_group_del(group)
        else:
            raise ArgError(
                "access group with id = %s not found!" % self.cmd_value)

    ## Used to delete a file system
    # @param    self    The this pointer
    def fs_delete(self):

        fs = self._get_item(self.c.fs(), self.cmd_value)
        if fs:
            if self.confirm_prompt(True):
                self._wait_for_it("delete-fs", self.c.fs_delete(fs), None)
        else:
            raise ArgError("fs with id = %s not found!" % self.cmd_value)

    ## Used to create a file system
    # @param    self    The this pointer
    def fs_create(self):
        #Need a name, size and pool
        size = self._size(self.options.opt_size)
        p = self._get_item(self.c.pools(), self.options.opt_pool)
        name = self.cmd_value
        if p:
            fs = self._wait_for_it("create-fs",
                                   *self.c.fs_create(p, name, size))
            self.display_data([fs])
        else:
            raise ArgError(
                "pool with id = %s not found!" % self.options.opt_pool)

    ## Used to resize a file system
    # @param    self    The this pointer
    def fs_resize(self):
        fs = self._get_item(self.c.fs(), self.cmd_value)
        size = self._size(self.options.opt_size)

        if fs and size:
            if self.confirm_prompt(False):
                fs = self._wait_for_it("resize-fs", *self.c.fs_resize(fs, size))
                self.display_data([fs])
        else:
            if not fs:
                raise ArgError(
                    " filesystem with id= %s not found!" % self.cmd_value)

    ## Used to clone a file system
    # @param    self    The this pointer
    def fs_clone(self):
        src_fs = self._get_item(self.c.fs(), self.cmd_value)
        name = self.options.opt_name

        if not src_fs:
            raise ArgError(
                " source file system with id=%s not found!" % self.cmd_value)

        if self.options.backing_snapshot:
            #go get the snapsnot
            ss = self._get_item(self.c.fs_snapshots(src_fs),
                                self.options.backing_snapshot)
            if not ss:
                raise ArgError(
                    " snapshot with id= %s not found!" %
                    self.options.backing_snapshot)
        else:
            ss = None

        fs = self._wait_for_it("fs_clone", *self.c.fs_clone(src_fs, name, ss))
        self.display_data([fs])

    ## Used to clone a file(s)
    # @param    self    The this pointer
    def file_clone(self):
        fs = self._get_item(self.c.fs(), self.cmd_value)
        src = self.options.opt_src
        dest = self.options.opt_dest

        if self.options.backing_snapshot:
            #go get the snapsnot
            ss = self._get_item(self.c.fs_snapshots(fs),
                                self.options.backing_snapshot)
        else:
            ss = None

        self._wait_for_it("file_clone", self.c.file_clone(fs, src, dest, ss),
                          None)

    def _get_item(self, l, the_id):
        for i in l:
            if i.id == the_id:
                return i
        return None

    ##Converts a size parameter into the appropriate number of bytes
    # @param    s   Size to convert to bytes handles B, K, M, G, T, P postfix
    # @return Size in bytes
    @staticmethod
    def _size(s):
        s = string.upper(s)
        m = re.match('^([0-9]+(\.[0-9]+)?)([BKMGTP]?)$', s)
        if m:
            unit = m.group(3)
            rc = float(m.group(1))

            if unit == 'K':
                rc *= common.KiB
            elif unit == 'M':
                rc *= common.MiB
            elif unit == 'G':
                rc *= common.GiB
            elif unit == 'T':
                rc *= common.TiB
            elif unit == 'P':
                rc *= common.PiB
            else:
                if m.group(2) is None:
                    rc = m.group(1)
                else:
                    raise ArgError(" unable to specify fractional parts "
                                   "of a byte")
        else:
            raise ArgError(" size is not in form <number>|<number"
                           "[B|K|M|G|T|P] (IEC)> No postfix indicates bytes")

        if int(rc) > ((2 ** 64) - 1):
            raise ArgError(" specified size too large")

        return int(rc)

    def _cp(self, cap, val):
        if self.options.sep is not None:
            s = self.options.sep
        else:
            s = ':'

        if val == data.Capabilities.SUPPORTED:
            v = "SUPPORTED"
        elif val == data.Capabilities.UNSUPPORTED:
            v = "UNSUPPORTED"
        elif val == data.Capabilities.SUPPORTED_OFFLINE:
            v = "SUPPORTED_OFFLINE"
        elif val == data.Capabilities.NOT_IMPLEMENTED:
            v = "NOT_IMPLEMENTED"
        else:
            v = "UNKNOWN"

        out("%s%s%s" % (cap, s, v))

    def capabilities(self):
        s = self._get_item(self.c.systems(), self.cmd_value)

        if s:
            cap = self.c.capabilities(s)
            self._cp("BLOCK_SUPPORT", cap.get(Capabilities.BLOCK_SUPPORT))
            self._cp("FS_SUPPORT", cap.get(Capabilities.FS_SUPPORT))
            self._cp("INITIATORS", cap.get(Capabilities.INITIATORS))
            self._cp("INITIATORS_GRANTED_TO_VOLUME",
                     cap.get(Capabilities.INITIATORS_GRANTED_TO_VOLUME))
            self._cp("VOLUMES", cap.get(Capabilities.VOLUMES))
            self._cp("VOLUME_CREATE", cap.get(Capabilities.VOLUME_CREATE))
            self._cp("VOLUME_RESIZE", cap.get(Capabilities.VOLUME_RESIZE))
            self._cp("VOLUME_REPLICATE", cap.get(Capabilities.VOLUME_REPLICATE))
            self._cp("VOLUME_REPLICATE_CLONE",
                     cap.get(Capabilities.VOLUME_REPLICATE_CLONE))
            self._cp("VOLUME_REPLICATE_COPY",
                     cap.get(Capabilities.VOLUME_REPLICATE_COPY))
            self._cp("VOLUME_REPLICATE_MIRROR_ASYNC",
                     cap.get(Capabilities.VOLUME_REPLICATE_MIRROR_ASYNC))
            self._cp("VOLUME_REPLICATE_MIRROR_SYNC",
                     cap.get(Capabilities.VOLUME_REPLICATE_MIRROR_SYNC))
            self._cp("VOLUME_COPY_RANGE_BLOCK_SIZE",
                     cap.get(Capabilities.VOLUME_COPY_RANGE_BLOCK_SIZE))
            self._cp("VOLUME_COPY_RANGE",
                     cap.get(Capabilities.VOLUME_COPY_RANGE))
            self._cp("VOLUME_COPY_RANGE_CLONE",
                     cap.get(Capabilities.VOLUME_COPY_RANGE_CLONE))
            self._cp("VOLUME_COPY_RANGE_COPY",
                     cap.get(Capabilities.VOLUME_COPY_RANGE_COPY))
            self._cp("VOLUME_DELETE", cap.get(Capabilities.VOLUME_DELETE))
            self._cp("VOLUME_ONLINE", cap.get(Capabilities.VOLUME_ONLINE))
            self._cp("VOLUME_OFFLINE", cap.get(Capabilities.VOLUME_OFFLINE))
            self._cp("VOLUME_INITIATOR_GRANT",
                     cap.get(Capabilities.VOLUME_INITIATOR_GRANT))
            self._cp("VOLUME_INITIATOR_REVOKE",
                     cap.get(Capabilities.VOLUME_INITIATOR_REVOKE))
            self._cp("VOLUME_THIN",
                     cap.get(Capabilities.VOLUME_THIN))
            self._cp("VOLUME_ISCSI_CHAP_AUTHENTICATION",
                     cap.get(Capabilities.VOLUME_ISCSI_CHAP_AUTHENTICATION))
            self._cp("ACCESS_GROUP_GRANT",
                     cap.get(Capabilities.ACCESS_GROUP_GRANT))
            self._cp("ACCESS_GROUP_REVOKE",
                     cap.get(Capabilities.ACCESS_GROUP_REVOKE))
            self._cp("ACCESS_GROUP_LIST",
                     cap.get(Capabilities.ACCESS_GROUP_LIST))
            self._cp("ACCESS_GROUP_CREATE",
                     cap.get(Capabilities.ACCESS_GROUP_CREATE))
            self._cp("ACCESS_GROUP_DELETE",
                     cap.get(Capabilities.ACCESS_GROUP_DELETE))
            self._cp("ACCESS_GROUP_ADD_INITIATOR",
                     cap.get(Capabilities.ACCESS_GROUP_ADD_INITIATOR))
            self._cp("ACCESS_GROUP_DEL_INITIATOR",
                     cap.get(Capabilities.ACCESS_GROUP_DEL_INITIATOR))
            self._cp("VOLUMES_ACCESSIBLE_BY_ACCESS_GROUP",
                     cap.get(Capabilities.VOLUMES_ACCESSIBLE_BY_ACCESS_GROUP))
            self._cp("VOLUME_ACCESSIBLE_BY_INITIATOR",
                     cap.get(Capabilities.VOLUME_ACCESSIBLE_BY_INITIATOR))
            self._cp("ACCESS_GROUPS_GRANTED_TO_VOLUME",
                     cap.get(Capabilities.ACCESS_GROUPS_GRANTED_TO_VOLUME))
            self._cp("VOLUME_CHILD_DEPENDENCY",
                     cap.get(Capabilities.VOLUME_CHILD_DEPENDENCY))
            self._cp("VOLUME_CHILD_DEPENDENCY_RM",
                     cap.get(Capabilities.VOLUME_CHILD_DEPENDENCY_RM))
            self._cp("FS", cap.get(Capabilities.FS))
            self._cp("FS_DELETE", cap.get(Capabilities.FS_DELETE))
            self._cp("FS_RESIZE", cap.get(Capabilities.FS_RESIZE))
            self._cp("FS_CREATE", cap.get(Capabilities.FS_CREATE))
            self._cp("FS_CLONE", cap.get(Capabilities.FS_CLONE))
            self._cp("FILE_CLONE", cap.get(Capabilities.FILE_CLONE))
            self._cp("FS_SNAPSHOTS", cap.get(Capabilities.FS_SNAPSHOTS))
            self._cp("FS_SNAPSHOT_CREATE",
                     cap.get(Capabilities.FS_SNAPSHOT_CREATE))
            self._cp("FS_SNAPSHOT_CREATE_SPECIFIC_FILES",
                     cap.get(Capabilities.FS_SNAPSHOT_CREATE_SPECIFIC_FILES))
            self._cp("FS_SNAPSHOT_DELETE",
                     cap.get(Capabilities.FS_SNAPSHOT_DELETE))
            self._cp("FS_SNAPSHOT_REVERT",
                     cap.get(Capabilities.FS_SNAPSHOT_REVERT))
            self._cp("FS_SNAPSHOT_REVERT_SPECIFIC_FILES",
                     cap.get(Capabilities.FS_SNAPSHOT_REVERT_SPECIFIC_FILES))
            self._cp("FS_CHILD_DEPENDENCY",
                     cap.get(Capabilities.FS_CHILD_DEPENDENCY))
            self._cp("FS_CHILD_DEPENDENCY_RM",
                     cap.get(Capabilities.FS_CHILD_DEPENDENCY_RM))
            self._cp("FS_CHILD_DEPENDENCY_RM_SPECIFIC_FILES", cap.get(
                Capabilities.FS_CHILD_DEPENDENCY_RM_SPECIFIC_FILES))
            self._cp("EXPORT_AUTH", cap.get(Capabilities.EXPORT_AUTH))
            self._cp("EXPORTS", cap.get(Capabilities.EXPORTS))
            self._cp("EXPORT_FS", cap.get(Capabilities.EXPORT_FS))
            self._cp("EXPORT_REMOVE", cap.get(Capabilities.EXPORT_REMOVE))
            self._cp("EXPORT_CUSTOM_PATH",
                     cap.get(Capabilities.EXPORT_CUSTOM_PATH))
        else:
            raise ArgError("system with id= %s not found!" % self.cmd_value)

    def plugin_info(self):
        desc, version = self.c.plugin_info()

        if self.options.sep:
            out("%s%s%s" % (desc, self.options.sep, version))
        else:
            out("Description: %s Version: %s" % (desc, version))

    ## Creates a volume
    # @param    self    The this pointer
    def create_volume(self):
        #Get pool
        p = self._get_item(self.c.pools(), self.options.opt_pool)
        if p:
            vol = self._wait_for_it("create-volume",
                                    *self.c.volume_create(
                                        p,
                                        self.cmd_value,
                                        self._size(self.options.opt_size),
                                        data.Volume.prov_string_to_type(
                                            self.options.provisioning)))

            self.display_data([vol])
        else:
            raise ArgError(
                " pool with id= %s not found!" % self.options.opt_pool)

    ## Creates a snapshot
    # @param    self    The this pointer
    def create_ss(self):
        #Get fs
        fs = self._get_item(self.c.fs(), self.options.opt_fs)
        if fs:
            ss = self._wait_for_it("snapshot-create",
                                   *self.c.fs_snapshot_create(
                                       fs,
                                       self.cmd_value,
                                       self.options.file))

            self.display_data([ss])
        else:
            raise ArgError("fs with id= %s not found!" % self.options.opt_fs)

    ## Restores a snap shot
    # @param    self    The this pointer
    def restore_ss(self):
        #Get snapshot
        fs = self._get_item(self.c.fs(), self.options.opt_fs)
        ss = self._get_item(self.c.fs_snapshots(fs), self.cmd_value)

        if ss and fs:

            if self.options.file:
                if self.options.fileas:
                    if len(self.options.file) != len(self.options.fileas):
                        raise ArgError(
                            "number of --files not equal to --fileas")

            if self.options.all:
                if self.options.file or self.options.fileas:
                    raise ArgError(
                        "Unable to specify --all and --files or --fileas")

            if self.options.all is False and self.options.file is None:
                raise ArgError("Need to specify --all or at least one --file")

            if self.confirm_prompt(True):
                self._wait_for_it('restore-ss',
                                  self.c.fs_snapshot_revert(fs, ss,
                                                            self.options.file,
                                                            self.options.fileas,
                                                            self.options.all),
                                  None)
        else:
            if not ss:
                raise ArgError("ss with id= %s not found!" % self.cmd_value)
            if not fs:
                raise ArgError(
                    "fs with id= %s not found!" % self.options.opt_fs)

    ## Deletes a volume
    # @param    self    The this pointer
    def delete_volume(self):
        v = self._get_item(self.c.volumes(), self.cmd_value)

        if v:
            if self.confirm_prompt(True):
                self._wait_for_it("delete-volume", self.c.volume_delete(v),
                                  None)
        else:
            raise ArgError(" volume with id= %s not found!" % self.cmd_value)

    ## Deletes a snap shot
    # @param    self    The this pointer
    def delete_ss(self):
        fs = self._get_item(self.c.fs(), self.options.opt_fs)
        if fs:
            ss = self._get_item(self.c.fs_snapshots(fs), self.cmd_value)
            if ss:
                if self.confirm_prompt(True):
                    self._wait_for_it("delete-snapshot",
                                      self.c.fs_snapshot_delete(fs, ss), None)
            else:
                raise ArgError(
                    " snapshot with id= %s not found!" % self.cmd_value)
        else:
            raise ArgError(
                " file system with id= %s not found!" % self.options.opt_fs)

    ## Waits for an operation to complete by polling for the status of the
    # operations.
    # @param    self    The this pointer
    # @param    msg     Message to display if this job fails
    # @param    job     The job id to wait on
    # @param    item    The item that could be available now if there is no job
    def _wait_for_it(self, msg, job, item):
        if not job:
            return item
        else:
            #If a user doesn't want to wait, return the job id to stdout
            #and exit with job in progress
            if self.options.async:
                out(job)
                self.shutdown(common.ErrorNumber.JOB_STARTED)

            while True:
                (s, percent, i) = self.c.job_status(job)

                if s == common.JobStatus.INPROGRESS:
                    #Add an option to spit out progress?
                    #print "%s - Percent %s complete" % (job, percent)
                    time.sleep(0.25)
                elif s == common.JobStatus.COMPLETE:
                    self.c.job_free(job)
                    return i
                else:
                    #Something better to do here?
                    raise ArgError(msg + " job error code= " + str(s))

    ## Retrieves the status of the specified job
    # @param    self    The this pointer
    def job_status(self):
        (s, percent, i) = self.c.job_status(self.cmd_value)

        if s == common.JobStatus.COMPLETE:
            if i:
                self.display_data([i])

            self.c.job_free(self.cmd_value)
        else:
            out(str(percent))
            self.shutdown(common.ErrorNumber.JOB_STARTED)

    ## Replicates a volume
    # @param    self    The this pointer
    def replicate_volume(self):
        p = None

        if self.options.opt_pool:
            p = self._get_item(self.c.pools(), self.options.opt_pool)

        v = self._get_item(self.c.volumes(), self.cmd_value)

        if v:

            rep_type = data.Volume.rep_String_to_type(self.options.opt_type)
            if rep_type == data.Volume.REPLICATE_UNKNOWN:
                raise ArgError("invalid replication type= %s" % rep_type)

            vol = self._wait_for_it("replicate volume",
                                    *self.c.volume_replicate(
                                        p, rep_type, v, self.options.opt_name))
            self.display_data([vol])
        else:
            if not p:
                raise ArgError(
                    "pool with id= %s not found!" % self.options.opt_pool)
            if not v:
                raise ArgError("Volume with id= %s not found!" % self.cmd_value)

    ## Replicates a range of a volume
    # @param    self    The this pointer
    def replicate_vol_range(self):
        src = self._get_item(self.c.volumes(), self.cmd_value)
        dest = self._get_item(self.c.volumes(), self.options.opt_dest)

        if src and dest:
            rep_type = data.Volume.rep_String_to_type(self.options.opt_type)
            if rep_type == data.Volume.REPLICATE_UNKNOWN:
                raise ArgError("invalid replication type= %s" % rep_type)

            src_starts = self.options.opt_src_start
            dest_starts = self.options.opt_dest_start
            counts = self.options.opt_count

            if (0 < len(src_starts) == len(dest_starts)
                    and len(dest_starts) == len(counts)):
                ranges = []

                for i in range(len(src_starts)):
                    ranges.append(data.BlockRange(src_starts[i], dest_starts[i],
                                                  counts[i]))

                if self.confirm_prompt(False):
                    self.c.volume_replicate_range(rep_type, src, dest, ranges)
        else:
            if not src:
                raise ArgError(
                    "src volume with id= %s not found!" % self.cmd_value)
            if not dest:
                raise ArgError(
                    "dest volume with id= %s not found!" %
                    self.options.opt_dest)

    ##
    # Returns the block size in bytes for each block represented in
    # volume_replicate_range
    # @param    self    The this pointer
    def replicate_vol_range_bs(self):
        s = self._get_item(self.c.systems(), self.cmd_value)
        if s:
            out(self.c.volume_replicate_range_block_size(s))
        else:
            raise ArgError("system with id= %s not found" % self.cmd_value)

    ## Used to grant or revoke access to a volume to an initiator.
    # @param    self    The this pointer
    # @param    grant   bool, if True we grant, else we un-grant.
    def _access(self, grant):
        v = self._get_item(self.c.volumes(), self.options.opt_volume)
        if not v:
            raise ArgError(
                "volume with id= %s not found" % self.options.opt_volume)

        initiator_id = self.cmd_value

        if grant:
            i_type = CmdLine._init_type_to_enum(self.options.opt_type)
            access = data.Volume.access_string_to_type(self.options.opt_access)

            self.c.initiator_grant(initiator_id, i_type, v, access)
        else:
            initiator = self._get_item(self.c.initiators(), initiator_id)
            if not initiator:
                raise ArgError("initiator with id= %s not found" % initiator_id)

            self.c.initiator_revoke(initiator, v)

    ## Grant access to volume to an initiator
    # @param    self    The this pointer
    def access_grant(self):
        return self._access(True)

    ## Revoke access to volume to an initiator
    # @param    self    The this pointer
    def access_revoke(self):
        return self._access(False)

    def _access_group(self, grant=True):
        agl = self.c.access_group_list()
        group = self._get_item(agl, self.cmd_value)
        v = self._get_item(self.c.volumes(), self.options.opt_volume)

        if group and v:
            if grant:
                access = data.Volume.access_string_to_type(
                    self.options.opt_access)
                self.c.access_group_grant(group, v, access)
            else:
                self.c.access_group_revoke(group, v)
        else:
            if not group:
                raise ArgError(
                    "access group with id= %s not found!" % self.cmd_value)
            if not v:
                raise ArgError(
                    "volume with id= %s not found!" % self.options.opt_volume)

    def access_grant_group(self):
        return self._access_group(True)

    def access_revoke_group(self):
        return self._access_group(False)

    ## Re-sizes a volume
    # @param    self    The this pointer
    def resize_volume(self):
        v = self._get_item(self.c.volumes(), self.cmd_value)
        if v:
            size = self._size(self.options.opt_size)

            if self.confirm_prompt(False):
                vol = self._wait_for_it("resize",
                                        *self.c.volume_resize(v, size))
                self.display_data([vol])
        else:
            raise ArgError("volume with id= %s not found!" % self.cmd_value)

    ## Removes a nfs export
    # @param    self    The this pointer
    def nfs_export_remove(self):
        export = self._get_item(self.c.exports(), self.cmd_value)
        if export:
            self.c.export_remove(export)
        else:
            raise ArgError("nfs export with id= %s not found!" % self.cmd_value)

    ## Exports a file system as a NFS export
    # @param    self    The this pointer
    def nfs_export_fs(self):
        fs = self._get_item(self.c.fs(), self.cmd_value)

        if fs:
            #Check to see if we have some type of access specified
            if len(self.options.nfs_root) == 0 \
                    and len(self.options.nfs_rw) == 0 \
                    and len(self.options.nfs_ro) == 0:
                raise ArgError(" please specify --root, --ro or --rw access")

            export = self.c.export_fs(
                fs.id,
                self.options.opt_exportpath,
                self.options.nfs_root,
                self.options.nfs_rw, self.options.nfs_ro,
                self.options.anonuid,
                self.options.anongid,
                self.options.authtype, None)
            self.display_data([export])
        else:
            raise ArgError(
                " file system with id=%s not found!" % self.cmd_value)

    ## Displays volume dependants.
    # @param    self    The this pointer
    def vol_dependants(self):
        v = self._get_item(self.c.volumes(), self.cmd_value)

        if v:
            rc = self.c.volume_child_dependency(v)
            out(rc)
        else:
            raise ArgError("volume with id= %s not found!" % self.cmd_value)

    ## Removes volume dependants.
    # @param    self    The this pointer
    def vol_dependants_rm(self):
        v = self._get_item(self.c.volumes(), self.cmd_value)

        if v:
            self._wait_for_it("volume-dependant-rm",
                              self.c.volume_child_dependency_rm(v), None)
        else:
            raise ArgError("volume with id= %s not found!" % self.cmd_value)

    ## Displays file system dependants
    # @param    self    The this pointer
    def fs_dependants(self):
        fs = self._get_item(self.c.fs(), self.cmd_value)

        if fs:
            rc = self.c.fs_child_dependency(fs, self.options.file)
            out(rc)
        else:
            raise ArgError(
                "File system with id= %s not found!" % self.cmd_value)

    ## Removes file system dependants
    # @param    self    The this pointer
    def fs_dependants_rm(self):
        fs = self._get_item(self.c.fs(), self.cmd_value)

        if fs:
            self._wait_for_it("fs-dependants-rm",
                              self.c.fs_child_dependency_rm(fs,
                                                            self.options.file),
                              None)
        else:
            raise ArgError(
                "File system with id= %s not found!" % self.cmd_value)

    def _read_configfile(self):
        """
        Set uri from config file. Will be overridden by cmdline option or
        env var if present.
        """

        allowed_config_options = ("uri",)

        config_path = os.path.expanduser("~") + "/.lsmcli"
        if not os.path.exists(config_path):
            return

        with open(config_path) as f:
            for line in f:

                if line.lstrip().startswith("#"):
                    continue

                try:
                    name, val = [x.strip() for x in line.split("=", 1)]
                    if name in allowed_config_options:
                        setattr(self, name, val)
                except ValueError:
                    pass

    ## Class constructor.
    # @param    self    The this pointer
    def __init__(self):
        self.uri = None
        self.c = None
        self.cli()

        self.cleanup = None

        #Get and set the command and command value we will be executing
        (self.cmd, self.cmd_value) = self._cmd()

        if self.cmd is None:
            raise ArgError("no command specified, try --help")

        #Check for extras
        if len(self.args):
            raise ArgError(
                "Extra command line arguments (" + ",".join(self.args) + ")")

        #Data driven validation
        self.verify = {'list': {'options': [], 'method': self.list},
                       'delete-fs': {'options': [],
                                     'method': self.fs_delete},
                       'delete-access-group':
                       {'options': [], 'method': self.delete_access_group},
                       'capabilities': {'options': [],
                                        'method': self.capabilities},

                       'plugin-info': {'options': [],
                                       'method': self.plugin_info},

                       'create-volume': {'options': ['size', 'pool'],
                                         'method': self.create_volume},
                       'create-fs': {'options': ['size', 'pool'],
                                     'method': self.fs_create},
                       'clone-fs': {'options': ['name'],
                                    'method': self.fs_clone},
                       'create-access-group': {
                       'options': ['id', 'type', 'system'],
                       'method': self.create_access_group},
                       'access-group-add': {'options': ['id', 'type'],
                                            'method': self.access_group_add},
                       'access-group-remove':
                       {'options': ['id'], 'method': self.access_group_remove},
                       'access-group-volumes':
                       {'options': [], 'method': self.access_group_volumes},
                       'volume-access-group':
                       {'options': [],
                       'method': self.volume_access_group},
                       'volumes-accessible-initiator':
                       {'options': [], 'method': self.volume_accessible_init},

                       'initiators-granted-volume':
                       {'options': [], 'method': self.init_granted_volume},

                       'iscsi-chap': {'options': [],
                                      'method': self.iscsi_chap},

                       'create-ss': {'options': ['fs'],
                                     'method': self.create_ss},
                       'clone-file': {'options': ['src', 'dest'],
                                      'method': self.file_clone},
                       'delete-volume': {'options': [],
                                         'method': self.delete_volume},
                       'delete-ss': {'options': ['fs'],
                                     'method': self.delete_ss},
                       'replicate-volume': {'options': ['type', 'name'],
                                            'optional': ['pool'],
                                            'method': self.replicate_volume},
                       'access-grant': {'options': ['volume', 'access', 'type'],
                                        'method': self.access_grant},
                       'access-grant-group':
                       {'options': ['volume', 'access'],
                       'method': self.access_grant_group},
                       'access-revoke': {'options': ['volume'],
                                         'method': self.access_revoke},
                       'access-revoke-group':
                       {'options': ['volume'],
                       'method': self.access_revoke_group},
                       'resize-volume': {'options': ['size'],
                                         'method': self.resize_volume},
                       'resize-fs': {'options': ['size'],
                                     'method': self.fs_resize},
                       'nfs-export-remove': {'options': [],
                                             'method': self.nfs_export_remove},
                       'nfs-export-fs': {'options': [],
                                         'method': self.nfs_export_fs},
                       'restore-ss': {'options': ['fs'],
                                      'method': self.restore_ss},
                       'job-status': {'options': [],
                                      'method': self.job_status},
                       'replicate-volume-range':
                       {'options':
                       ['type', 'dest', 'src_start', 'dest_start', 'count'],
                       'method': self.replicate_vol_range},
                       'replicate-volume-range-block-size':
                       {'options': [],
                       'method': self.replicate_vol_range_bs},
                       'volume-dependants': {'options': [],
                                             'method': self.vol_dependants},
                       'volume-dependants-rm':
                       {'options': [], 'method': self.vol_dependants_rm},
                       'fs-dependants': {'options': [],
                                         'method': self.fs_dependants},
                       'fs-dependants-rm': {'options': [],
                                            'method': self.fs_dependants_rm}}
        self._validate()

        self.tmo = int(self.options.wait)
        if not self.tmo or self.tmo < 0:
            raise ArgError("[-w|--wait] reguires a non-zero positive integer")

        self._read_configfile()
        if os.getenv('LSMCLI_URI') is not None:
            self.uri = os.getenv('LSMCLI_URI')
        self.password = os.getenv('LSMCLI_PASSWORD')
        if self.options.uri is not None:
            self.uri = self.options.uri

        if self.uri is None:
            raise ArgError("--uri missing or export LSMCLI_URI")

        #Lastly get the password if requested.
        if self.options.prompt is not None:
            self.password = getpass.getpass()

        if self.password is not None:
            #Check for username
            u = common.uri_parse(self.uri)
            if u['username'] is None:
                raise ArgError("password specified with no user name in uri")

    ## Does appropriate clean-up
    # @param    self    The this pointer
    # @param    ec      The exit code
    def shutdown(self, ec=None):
        if self.cleanup:
            self.cleanup()

        if ec:
            sys.exit(ec)

    ## Process the specified command
    # @param    self    The this pointer
    # @param    cli     The object instance to invoke methods on.
    def process(self, cli=None):
        """
        Process the parsed command.
        """
        if cli:
            #Directly invoking code though a wrapper to catch unsupported
            #operations.
            self.c = common.Proxy(cli())
            self.c.startup(self.uri, self.password, self.tmo)
            self.cleanup = self.c.shutdown
        else:
            #Going across the ipc pipe
            self.c = client.Client(self.uri, self.password, self.tmo)

            if os.getenv('LSM_DEBUG_PLUGIN'):
                raw_input(
                    "Attach debugger to plug-in, press <return> when ready...")

            self.cleanup = self.c.close

        self.verify[self.cmd]['method']()
        self.shutdown()