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
|
#!/usr/bin/perl
# POD {{{
=head1 NAME
vwm - Manage VMware virtual machines
=head1 SYNOPSIS
vwm <command> [options]
=over
=item B<Global syntax:>
vwm <command> [-f] [-v+] [-w seconds] [@profile]
=item B<Command specific syntax:>
vwm clone [-o pool] [-c count] [-a datastore...] [-l folder] <source vm> <new vm name>
vwm deploy [synonym of 'clone']
vwm df [-h] [datastore...]
vwm host [maintenance|restore|restart|shutdown|disconnect|reconnect] <hosts...>
vwm list [-d col1,col2... | perl string] [-t title] [vm|datastore|host|pool|template][s] [patterns...]
vwm migrate [-p low|normal|high] [-o pool] <vms...> <host>
vwm move [-o pool] <vms...> <datastore>
vwm setpool <low|normal|high> <cpu|mem|all> <pools...>
vwm show [vm|datastore|host|pool] [items...]
vwm snapshot [-t title] <vms...>
vwm state <on|off|suspend|reboot|shutdown|restart|standby> <vms...>
vwm version
=back
=head1 COMMANDS
=over 8
=item B<clone>
Clone a given VM or template to another VM name.
If -c is specified multiple copies are made. Each VM name will be incremented in the usual Perlish way. e.g.: DB1, DB2, DB3 etc.
If -a is unspcified the datastore of the source VM is copied as the new clones datastore.
If -a is specified the data store will be set during cloning. If -a contains a comma denoted list the datastores will be alternated during cloning. e.g. -a 1,2 copies to datastore 1 then 2 then starts again at 1. Patterns of repeating datastores can be specified - e.g. '-a 1,2,3,2,1'.
=item B<deploy>
Synonym of 'clone'.
=item B<df>
Display disk usage information about datastores.
If a list of matches is provided, the data store list is filtered for those items.
=item B<list>
Display a list of the given items matching a pattern.
Possible lists include (selection can be plural or singular):
vms (default if unspecified)
datastores
hosts
pools
If '-d' is specified without any containing '$' marks the string is evaluated as a CSV with each line extracting the requisite information that would be shown with the 'show' command. See the EXAMPLES section for further information.
If '-d' is specified and contains a '$' it is evaluated as a perl expression with $_ being set to the currently active item.
If '-t' is spcified the titles header for the table is set.
=item B<migrate>
Migrate a given list of VMs to another host.
=item B<move>
Move a given list of VMs to another datastore.
=item B<setpool>
Set the share level on the given resource pools.
=item B<show>
Show information about a given object. If no specific object type is specified 'vm' is assumed.
If no specific matching pattern is specified all objects of that type are listed.
=item B<snapshot>
Take a snapshot of the matching VM's.
If '-t' is specified, it is used as the title of the snapshot. Otherwise the current time is used.
=item B<state>
Set the state of a list of VMs.
This can be any of the following choices:
on - Power up the specified VMs
off - Power down the specified VMs. This is a hard power state so data loss could occur.
suspend - Power the machine into standby mode. This is a hard power state which does not rely on VMware tools.
restart - Hard power cycle the VMs. Like 'off' this is a forced power state so data loss could occur.
shutdown - Try shutting down the machine via VMware tools.
standby - Try to put the machine into the soft standby state.
reboot - Try shutting down the machine via VMware tools.
=item B<version>
Display various version informaiton about the connected vServer and local API.
This command is the default if no actual command is specified (i.e. just running 'vwm' with nothing else specified).
=back
=head1 OPTIONS
=over 8
=item B<[@profile]>
=over
=item B<Used during:>
All operations
=item B<Default:>
First specified profile in config
=item B<Type:>
Profile name or URL
=back
Specifies which profile to use when addressing the vServer.
This can be an entry within the config file or the URL (with optional login details) e.g.
vwm version @cluster1
vwm version @cluster2
vwm version @https://cluster1.acme.edu
vwm version @https://username@cluster1.acme.edu
vwm version @https://username:password@cluster1.acme.edu
Examples 1 and two assume 'custer1' and 'customer2' have been defined in the examples file (see EXAMPLES). The further examples specify the connection information on the command line.
Specifying the password from the command line is exceptionally silly and should be avoided.
If username and/or password is omitted (such as in examples 3 and 4 above) they will be prompted for when vwm is run.
=item B<-c>
=over
=item B<Used during:>
migrate
=item B<Default:>
1
=item B<Type:>
Number
=back
Specifies how many VMs should be created during a clone operation.
The name of the target VM is incremented in the usual Perlish way.
e.g.
DBS1, DBS2, DBS3... DBS10
DB00, DB01, DB02... DB99
DBAA, DBAB, DBAC... DBZZ
=item B<--display [col1,col2...]>
=item B<-d [col1,col2...]>
=over
=item B<Used during:>
list
=item B<Default:>
Name
=item B<Type:>
Command seperated list of columns to display in tabular output when using the 'list' command.
See also: -s to specify the seperation character to use between the columns.
=back
Specify a data store for operations that require it.
=item B<--datastore [datastore]>
=item B<--ds [datastore]>
=item B<-a [datastore]>
=over
=item B<Used during:>
migrate
=item B<Default:>
Same as source VM
=item B<Type:>
Datastore name
=back
Specify a data store for operations that require it.
=item B<--force>
=item B<-f>
=over
=item B<Used during:>
All operations
=item B<Default:>
off
=item B<Type:>
Switch
=back
Force continue if an error occurs.
Normaly if an error occurs vwm will stop processing any operations specified on the command line.
If this flag is enabled vwm will continue operation as if no error occured.
=item B<--human>
=item B<-h>
=over
=item B<Used during:>
df
=item B<Default:>
off
=item B<Type:>
Switch
=back
Display the numbers of the 'df' command in a human readable format.
=item B<--dryrun>
=item B<-n>
=over
=item B<Used during:>
All operations
=item B<Default:>
off
=item B<Type:>
Switch
=back
Dry run mode.
When enabled vwm will continue as normal but no actual call to the VMware VServer is made.
=item B<--folder>
=item B<-l>
=over
=item B<Used during:>
clone
=item B<Default:>
Source VM / templates folder
=item B<Type:>
String
=back
Specifies the folder that the cloned machine should be moved into. If unspecified the source VM's folder is used instead.
=item B<--pool [pool]>
=item B<-o [pool]>
=over
=item B<Used during:>
clone, migrate, move
=item B<Default:>
Same as the source VM
=item B<Type:>
Pool name
=back
Specifies the alternate pool name to use when migrating or cloning machines. If unspecified the source VM's pool is used instead.
=item B<--priority [priority]>
=item B<-p [priority]>
=over
=item B<Used during:>
migrate
=item B<Default:>
low
=item B<Type:>
Choice of: low, normal, high
=back
Specifies the priority when migrating VMs.
=item B<--seperator [character]>
=item B<-s [character]>
=over
=item B<Used during:>
list
=item B<Default:>
\t (tab)
=item B<Type:>
String
=back
Specifies the string to display between columns when outputing a list.
=item B<--title [title]>
=item B<-t [title]>
=over
=item B<Used during:>
list, snapshot
=item B<Default:>
The Unix EPOC (for VMs)
=item B<Type:>
String
=back
The title of the snapshot to create or the title row of the list table.
=item B<-v>
=item B<--verbose>
=over
=item B<Used during:>
All operations
=item B<Default:>
0
=item B<Type:>
Accumulating switch
=back
Be more verbose when outputting information to STDERR.
Specify multiple times to increase verbosity.
=item B<-w [seconds]>
=item B<-wait [seconds]>
=over
=item B<Used during:>
clone, host, migrate, setpool, state
=item B<Default:>
0
=item B<Type:>
Number of seconds
=back
Force a wait for the specified number of seconds between operations.
=back
=head1 DESCRIPTION
A command line tool for the manipulation of VMware Virtual Machines (VM).
=head1 EXAMPLES
=over
=item B<vwm clone VM01 VM02>
Clone VM01 to VM02.
Since neither the datasource (-d) or pool (-o) is specified these details are copied from VM01.
=item B<vwm clone DB00 DB01 -c 30>
Clone DB01 to DB02 creating 30 copies. This will actually make the machines DB01 to DB30.
Since neither the datasource (-d) or pool (-o) is specified these details are copied from VM01.
=item B<vwm clone DB00 DB01 -c 30 -d SAN1,SAN2 -o Active>
Same as the above example but spread the datastores across SAN1 and SAN2 and move the machine to the 'Active' pool.
=item B<vwm deploy Template-DBServer DB05 -l Databases>
Deploys the template Template-DBServer into DB05, moving the destination into the Databases folder.
=item B<vwm clone Template-DBServer DB05 -l Databases>
This is exactly the same as above. A clone and deploy operations will automatically figure out if the source is a template and act accordingly.
=item B<vwm df *2>
Display a datastore usage sheet (similar to the Unix 'df' command) for all datastores ending in '2'.
=item B<vwm host maintenance Moe Homer>
Put the hosts 'Moe' and 'Homer' into maintenance mode (use 'restore' to recover from this).
=item B<vwm list vms>
List all VMs.
=item B<vwm list vms -d name,host,ip>
List all VMs - showing their name, currently allocated host and IP address.
=item B<vwm migrate DBS* Carl>
Migrate all virtual machines matching 'DBS*' to the 'Carl' host.
=item B<vwm migrate DBS* Lenny -w 60 -o Active -p high>
Migrate all virtual machines matching 'DBS*' with high priority to the 'Active' pool on the 'Lenny' host waiting 60 seconds between machine.
=item B<vwm move DB00 DB01 SAN2 @cluster2>
Move VMs DB00 and DB01 to the SAN2 datastore within profile 'cluster2'.
=item B<vwm show host Lisa>
Show information on host 'Lisa'.
=item B<vwm snapshot DB04 DB05 -t 'Todays backup'>
Take a snapshot of VMs 'DB04' and 'DB05' using the title 'Todays backup'
=item B<vwm state on DB00 DB01 -w 30>
Turn DB00 and DB01 on waiting 30 seconds between machines.
=item B<vwm state on DB00 DB01 -w 30 -f>
Turn DB* VMs on.
-f ensures that even if any of the machines fail to turn on for any reason the remaining machines will still be sent the 'on' command.
=back
=head1 FILES
=over 8
=item B</etc/vmmrc>
VMM config file for all users.
=item B<.vmmrc>
VMM config file for the local user.
=back
=head1 CONFIG
The /etc/vmmrc and .vmmrc files will be processed to determine VMM's configuration, the latter file taking precedence.
The layout of the config file spcifies which profiles to use.
[GLOBAL]
rewrite host = s/^(.+?)\./\1/
verbose = 2
profile = Cluster1
dryrun = 0
human = 1
force = 0
seperator = \t
http_proxy = http://myproxy.example.com:8080
https_proxy = http://myproxy.example.com:8080
[Cluster1]
url = https://cluster1.acme.edu
username = admin
password = password
[Cluster2]
url = https://cluster2.acme.edu
username = administrator
password = changeme
=over 8
=item B<[GLOBAL]>
The meta global section. Any option specified here will be automatically carried into each profiles config.
In the main example Cluster1 will have a 'verbose' option of 2. Cluster2 will have a 'verbose' option of 1 since it overrides the global setting.
=item B<[profile]>
The name (case-insensitive) of the profile to define.
=item B<url>
The connection URL of the vServer system within the profile
=item B<username> and B<password>
The authentication information when connecting to the vServer.
=item B<dryrun>
Specify a default dry run value. See B<-n> for further information.
=item B<force>
If an error is encounted during a multiple VM operation the default behaviour is to stop execution. If this setting is set to '1' this behaviour will be overridden and operations will continue even if an error is encounted.
=item B<http_proxy>
=item B<https_proxy>
Forceably set the HTTP(s)_PROXY environment variable to the provided value before connecting.
This is included to assist basic login shells where these variables are not imported correctly.
=item B<human>
Always output numbers in a human readable format rather than the raw form.
=item B<priority>
Specify a default priority when using any command that is '-p' compatible.
=item B<profile>
Specify the default profile to use if none is explicitally set. If not specified the first found profile in the config file is used.
=item B<rewrite host>
Specify a substitution regular expression to use when correcting host names.
The value given in the above example will remove any trailing DNS name correcting 'host1.a.very.long.dns.com' to 'host1'.
=item B<seperator>
Specify the seperator character used when outputting tabular data with the 'list' command.
=item B<verbose>
Specify a default verbosity level. See B<-v> for further information.
=back
=head1 INSTALLATION
VMM requires a few external modules before it can work correctly. Follow the following stages to get everything working.
* Install the VMware Perl SDK from http://www.vmware.com/support/developer/viperltoolkit/
This requires the packages libclass-methodmaker-perl libcrypt-ssleay-perl
libsoap-lite-perl libuuid-perl libxml-libxml-perl.
* Setup the config file. See either the CONFIG section above or use the sample file from /usr/share/doc/vmware-manager.
* Run VMM with a simple command to make sure everything is setup right.
vwm version
* Enjoy
=head1 BUGS
Quite probably.
Please report to https://github.com/hash-bang/VMM when found.
=head1 AUTHOR
Matt Carter <m@ttcarter.com>
=cut
# }}} POD
package vmm;
our $VERSION = '0.2.0';
# Header {{{
use Config::IniFiles;
use IO::Handle;
use Getopt::Long;
use Number::Format qw/format_bytes/;
use Term::ReadKey;
use Text::Glob qw/match_glob glob_to_regex/;
my $mod="VMware::VIRuntime";
die "Couldn't load the VMware SDK: maybe you haven't installed it yet?\nPlease check the README file in /usr/share/doc/vmware-manager/ for details.\n"
if (!eval "require $mod");
$mod->import();
Getopt::Long::Configure('bundling', 'ignorecase_always', 'pass_through');
STDERR->autoflush(1); # } Flush the output DIRECTLY to the output buffer without caching
STDOUT->autoflush(1); # }
use Data::Dump; # FIXME: Debugging modules
# }}} Header
# Functions {{{
# Flow control {{{
sub fatal {
# Print an error message and fatally die
print STDERR @_, "\n";
exit 1;
}
sub say {
# Print a message to STDERR based on the verbosity level
our $verbose;
my $verbosity = shift;
print STDERR @_, "\n" if ($verbose >= $verbosity);
}
sub pause {
# Wait a number of seconds (specified by the -w [seconds]) between VM operations
# This function purposely ignores the first vm (thus not bothering to wait for the last vm to finish)
our $wait;
if ($wait > 0) {
say(0, "Waiting $wait seconds...");
sleep($wait);
}
}
sub error {
my $action = shift;
my $subject = shift;
if (ref($@) eq 'SoapFault') {
say(0, "ERROR: " . $@->detail);
} else {
say(0, "ERROR: General fault!");
}
fatal("Stopping execution. Use -f to force continue.") unless $force;
}
# }}} Flow control
# Filters {{{
sub list {
my $type = shift;
my @out;
return grep {
if ($type eq 'VirtualMachine' and !$_->resourcePool) {
undef;
} else {
$_ = $_->name;
}
} @{Vim::find_entity_views (
view_type => ($type eq 'Template' ? 'VirtualMachine' : $type), # Template is really just VirtualMachine with the above extra work
begin_entity => Vim::get_service_content()->rootFolder,
filter => {},
)};
return @out;
}
sub multiglob {
# Perform multiple greps and return all matching list items
# e.g. multiglob(qw/apple pear orange tomatoe carrot/, qw/*pp* *ar *zz/) = qw/apple pear/
# If the list of matches is empty, all are returned
my ($list, $globs) = @_;
return @$list unless @$globs;
@globs = map { $_ = glob_to_regex($_) } @$globs;
#print "LIST [" . Dumper($list) . "]";
#print "GLOBS [" . Dumper($globs) . "]";
return grep {
my $found = 0;
foreach $glob (@$globs) {
if ($_ =~ $glob) {
$found = 1;
last;
}
}
$found;
} @$list;
}
# }}} Filters
# Info grabbers {{{
sub translate {
my $type = shift;
$type =~ s/s$//; # Translate plurals in singulars
my %translate = qw/
vm VirtualMachine
template Template
host HostSystem
datastore Datastore
d Datastore
pool ResourcePool
/;
return $translate{$type} ? $translate{$type} : undef;
}
sub getview {
# Return a VMware view object from its type and reference
# This function also supports the meta type 'Mor' which looks up the view by the managed object reference
my $type = shift; # HostSystem, VirtualMachine, ResourcePool, Folder
my $ref = shift;
if ($type eq 'Mor') {
return Vim::get_view(
mo_ref => $ref,
);
} else {
return Vim::find_entity_view(
view_type => $type,
filter => { name => $ref },
);
}
}
sub getinfo {
# Generic function to return information from one of the below get<type>info functions
my $type = shift;
my $name = shift;
if ($type =~ /^VirtualMachine|Template$/) {
return getvminfo($name);
} elsif ($type eq 'Datastore') {
return getdsinfo($name);
} elsif ($type eq 'HostSystem') {
return gethostinfo($name);
} elsif ($type eq 'ResourcePool') {
return getpoolinfo($name);
}
}
sub istemplate {
# This view is a template machine ?
my $view = shift;
return $view->summary->config->template eq '0' ? 0 : 1;
}
sub getvminfo {
my $vm = shift;
my $view = getview('VirtualMachine', $vm) or fatal("Unknown VM: '$vm'");
my $template = istemplate($view);
my %info = (
name => $view->name,
template => $template,
os => $view->summary->guest->guestFullName,
datastore => Vim::get_view(mo_ref => ${$view->datastore}[0])->name,
alloccpu => $view->summary->config->numCpu,
allocmem => $view->summary->config->memorySizeMB,
allocdisks => $view->summary->config->numVirtualDisks,
maxcpu => $view->runtime->maxCpuUsage,
maxmem => $view->runtime->maxMemoryUsage,
host => Vim::get_view(mo_ref => $view->runtime->host)->name,
state => $view->runtime->powerState->val eq 'poweredOn' ? 'on' : 'off',
tools => $view->guest->toolsStatus->val eq 'toolsOk' ? 'yes' : 'no',
folder => Vim::get_view(mo_ref => $view->parent)->name,
ip => 'UNKNOWN',
mac => 'UNKNOWN',
);
if (!$template) { # Only grab the following if its not a template machine
$info{pool} = Vim::get_view(mo_ref => $view->resourcePool)->name;
$info{booted} => $view->runtime->bootTime;
}
if ($view->guest->disk) {
foreach (@{$view->guest->disk}) {
my $no;
$info{'disk_' . $no++} = $_->diskPath . ' ' . $_->capacity . ' ' . $_->freeSpace;
}
}
if ($view->guest->net) {
foreach $net (@{$view->guest->net}) {
my $no;
$info{'net_' . $no++} = $net->network . ' ' . $net->macAddress . ' ' . join(',', @{$net->ipAddress});
$info{ip} = join(',', @{$net->ipAddress}) if $info{ip} eq 'UNKNOWN'; # Lazy accessor for 'ip'
$info{mac} = $net->macAddress if $info{mac} eq 'UNKNOWN'; # Lazy accessor for 'mac'
}
}
return %info;
}
sub getdsinfo {
my $ds = shift;
our $human;
my $view = getview('Datastore', $ds) or fatal("Unknown datastore: '$ds'");
my %info = (
name => $view->name,
size => ($human ? format_bytes($view->info->vmfs->capacity) : $view->info->vmfs->capacity),
used => ($human ? format_bytes($view->info->vmfs->capacity - $view->info->freeSpace) : $view->info->vmfs->capacity - $view->info->freeSpace),
free => ($human ? format_bytes($view->info->freeSpace) : $view->info->freeSpace),
percent => sprintf('%d', (($view->info->vmfs->capacity - $view->info->freeSpace) / $view->info->vmfs->capacity * 100)),
);
return %info;
}
sub gethostinfo {
my $host = shift;
my $view = getview('HostSystem', $host) or fatal("Unknown host: '$ds'");
my %info = (
name => $view->name,
cpuuse => $view->summary->quickStats->overallCpuUsage,
memuse => $view->summary->quickStats->overallMemoryUsage,
mem => $view->hardware->memorySize,
cpu => $view->hardware->cpuInfo->hz,
);
if ($view->datastore) {
foreach $dsmor (@{$view->datastore}) {
my $no;
my $dsref = getview('Mor', $dsmor);
$info{'datastore_' . $no++} = $dsref->name;
}
}
return %info;
}
sub getpoolinfo {
my $pool = shift;
my $view = getview('ResourcePool', $pool) or fatal("Unknown pool: '$pool'");
my %info = (
name => $view->name,
maxmem => $view->runtime->memory->maxUsage,
maxcpu => $view->runtime->cpu->maxUsage,
mem => $view->runtime->memory->overallUsage,
cpu => $view->runtime->cpu->overallUsage,
memshare => $view->config->memoryAllocation->shares->level->val,
cpushare => $view->config->cpuAllocation->shares->level->val,
);
return %info;
}
# }}} Info grabbers
# }}} Functions
# Config loading {{{
my $cfgfile;
if (-e "/etc/vmmrc") {
$cfgfile = "/etc/vmmrc";
} elsif (-e "$ENV{HOME}/.vmmrc") {
$cfgfile = "$ENV{HOME}/.vmmrc";
} else {
say(1, "No VMMRC file could be found at either /etc/vmmrc or \$HOME/.vmmrc");
}
our $verbose = 0;
my $cfg = Config::IniFiles->new(
-file => ($cfgfile ? $cfgfile : \*DATA), # Read defaults from __DATA__ section if we cant find a default file.
-default => 'global',
-nocase => 1,
-allowempty => 1,
);
my $profile; # The active profile to use
@ARGV = grep { # Scan for '@profile' strings in @ARGV
if (/^@(.+)$/) {
fatal("Only one profile may be set per invocation. Profile was originally '$profile' when you tried to override with '$_'") if $profile;
if (my($cproto, $clogin, $curl) = (m/^\@(https?):\/\/(?:(.*?)@)?(.*)$/)) { # User is specifying user:pass@url, user@url or url
my($cuser, $cpass) = ($clogin,undef) unless (($cuser, $cpass) = ($clogin =~ m/^(.*?):(.*)$/));
say(2, "Using custom URL: $curl");
$cfg->newval('CUSTOM', 'url', "$cproto://$curl");
$cfg->newval('CUSTOM', 'username', $cuser) if $cuser;
$cfg->newval('CUSTOM', 'password', $cpass) if $cpass;
$profile = 'CUSTOM';
} else { # Standard profile alias
$profile = $1;
}
undef;
} else {
$_;
}
} @ARGV;
$verbose = $cfg->val('global', 'verbose', 0); # Early import from global so 'say' works correctly in the following profile options
if ($profile) { # User wants to select a specific profile
fatal("Profile not valid: $profile") unless $cfg->exists($profile, 'url');
say(2, "Using user set profile '$profile'");
} elsif ($cfg->exists('global', 'profile')) { # Default profile option set in config
$profile = $cfg->val('global', 'profile');
say(2, "Using config file default profile '$profile'");
} elsif ($cfg->val('global', 'profile')) { # Config file specifies default fallback profile
$profile = $cfg->val('global', 'profile', $profile);
} else { # Use first section found that isn't 'global'
$profile = [grep { $_ ne 'global' } $cfg->Sections]->[0];
say(2, "Using first found profile '$profile'");
}
fatal("No vServer URL specified for profile $profile") unless $cfg->exists($profile, 'url');
unless ($cfg->val($profile, 'username')) {
print "Username: ";
my $cuser = ReadLine(0);
chomp($cuser);
$cfg->newval($profile, 'username', $cuser);
}
unless ($cfg->val($profile, 'password')) {
print "Password: ";
ReadMode('noecho');
my $cpass = ReadLine(0);
chomp($cpass);
print "\n";
$cfg->newval($profile, 'password', $cpass);
}
# Import various options from the config file. These can be overriden in the GetOptions call below.
$verbose = $cfg->val($profile, 'verbose', 0); # Late import which overrides the 'global/verbose' setting now we know what profile to use
our $cycleno = 0; # Offset of the object we are operating on
our $dryrun = $cfg->val($profile, 'dryrun', 0);
our $wait = $cfg->val($profile, 'wait', 0);
our $human = $cfg->val($profile, 'human', '0');
our $force = $cfg->val($profile, 'force', '0');
my $priority = $cfg->val($profile, 'priority', 'low');
my $seperator = $cfg->val($profile, 'seperator', "\t");
my $title, $display, $pool, $datastore, $folder;
my $count = 1;
if (my $x = $cfg->val($profile, 'http_proxy')) {
say(2, "Forceably importing HTTP_PROXY as '$x'");
$ENV{HTTP_PROXY} = $x;
}
if (my $x = $cfg->val($profile, 'https_proxy')) {
say(2, "Forceably importing HTTPS_PROXY as '$x'");
$ENV{HTTPS_PROXY} = $x;
}
Opts::set_option('url', $cfg->val($profile, 'url'));
Opts::set_option('username', $cfg->val($profile, 'username'));
Opts::set_option('password', $cfg->val($profile, 'password'));
say(3, "Connecting to " . $cfg->val($profile, 'username') . '@' . $cfg->val($profile, 'url'));
Util::connect();
# }}} Config loading
# Command line options loading {{{
GetOptions(
# Global options
'dryrun|n' => \$dryrun,
'force|f' => \$force,
'verbose|v+' => \$verbose,
'wait|w=i' => \$wait,
# Specific command options
'count|c=i' => \$count,
'priority|p=s' => \$priority,
'pool|o=s' => \$pool,
'human|h' => \$human,
'display|d=s' => \$display,
'seperator|s=s' => \$seperator,
'title|t=s' => \$title,
'datastore|ds|a=s' => \$datastore,
'folder|l=s' => \$folder,
);
my $cmd = shift; # Extract what command we should work with
# }}} Command line options loading
if ($cmd eq 'df') { # DF {{{
# DF is really just a lazy way of configuring the 'list' command
$cmd = 'list';
$display = '$_{name}\t$_{size}\t$_{used}\t$_{free}\t$_{percent}%';
$title = 'Name,Size,Used,Free,%';
unshift @ARGV, 'datastore';
} # }}}
if ($cmd =~ /^clone|deploy$/) { # CLONE / DEPLOY {{{
my $poolref;
my $folderref;
my $source = shift;
my $target = shift;
my $sourceref = getview('VirtualMachine', $source) or fatal("Invalid source VM / template: '$source'");
my $sourcehost = getview('Mor', $sourceref->runtime->host) or fatal("Invalid host for VM '$source'");
my @dsrefs;
if ($pool) { # Requesting a specific pool
say(2, "Using pool '$pool'");
$poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool");
} else { # Copy pool from source
fatal("Cannot determine pool when deploying from a template. You must specify the pool with -o") if istemplate($sourceref);
$poolref = getview('Mor', $sourceref->resourcePool);
}
if ($folder) { # Requesting a specific folder
say(2, "Using folder '$folder'");
$folderref = getview('Folder', $folder) or fatal("Invalid destination folder: $folder");
} else { # Copy folder from source
$folderref = $sourceref->parent;
}
if ($datastore) { # User is specifying pattern of datastores
foreach (split('\s*,\s*', $datastore)) {
say(2, "Loading datastore '$_'");
my $dsref = getview('Datastore', $_) or fatal("Unknown datastore: '$_'");
push @dsrefs, $dsref;
}
} else { # No DS preferences set - use default clone DS
push @dsrefs, getview('Mor', $sourceref->datastore->[0]);
}
say(1, "Clone source $source ($count clones, across " . scalar(@dsrefs) ." datastores)") if $count > 1;
while ($cycleno < $count) {
pause() if $cycleno++;
while (getview('VirtualMachine', $target)) {
say(1, "VM '$target' already exists. Trying next slot");
$target++;
}
say(1, "Cloning $source -> $target (clone #$cycleno, Pool = " . $poolref->name . ", DS = " . $dsrefs[$dsno]->name . ", Folder = " . $folderref->name . ")");
eval {
$sourceref->CloneVM(
folder => $folderref,
name => $target,
spec => VirtualMachineCloneSpec->new(
powerOn => 0,
template => 0,
location => VirtualMachineRelocateSpec->new(
datastore => $dsrefs[$dsno],
host => $sourcehost,
pool => $poolref,
)
)
) unless $dryrun;
};
error('clone', $source, @_) if @_;
$dsno = 0 if ++$dsno > scalar(@dsrefs)-1; # Move though selected datastores
$target++;
}
# }}} CLONE
} elsif ($cmd eq 'list') { # LIST {{{
my $type = shift || 'vm';
my $type = translate($type) or fatal("Unknown list type: '$type'");
my @displaylist;
my $displaytype = 0; # 0 - Plain list, 1 - CSV list, 2 - Perl string eval
if ($display =~ /\$/) { # Contains a '$' - assume Perl eval
$displaytype = 2;
} elsif ($display) { # Treat as CSV
@displaylist = split(',',$display);
$displaytype = 1;
}
if ($title) { # Output a title
$title =~ s/\s*,\s*/$seperator/g;
say(0, $title);
}
my @list = multiglob([list($type)], \@ARGV);
if ($displaytype == 0) { # No custom format - just dump list
print join "\n", @list;
} elsif ($displaytype == 1) { # CSV style extract
unless ($title) {
foreach $type (@displaylist) { # Print headers
print "$type$seperator";
}
}
print "\n";
foreach $item (@list) {
my %info = getinfo($type, $item) or fatal("Dont know how to retrieve info for type '$type'");
my $line = '';
foreach $type (@displaylist) {
$line .= ($info{$type} ? $info{$type} : 'UNKNOWN') . $seperator;
}
$line = substr($line, 0, 0 - length($seperator)); # Strip last $seperator
print "$line\n";
}
} elsif ($displaytype == 2) { # Perl eval
foreach $name (@list) {
%_ = getinfo($type, $name) or fatal("Dont know how to retrieve info for type '$type'");
print eval("return \"$display\"") . "\n";
}
}
print "\n" if @list; # Insert final \n
# }}} LIST
} elsif ($cmd eq 'host') { # HOST {{{
my $operation = shift;
fatal('No operation specified. Choose: maintenance, restore, restart, shutdown, disconnect, reconnect') unless $state;
fatal('Invalid power state specified. Choose: maintenance, restore, restart, shutdown, disconnect, reconnect') unless $state =~ /^maintenance|restore|restart|shutdown|disconnect|reconnect$/;
my @hosts = multiglob([list('HostSystem')], \@ARGV);
fatal('No Hosts\'s match the given pattern') unless scalar(@hosts);
foreach $host (@hosts) {
pause() if $cycleno++;
my $hostref = getview('HostSystem', $host) or fatal("Invalid host: $host");
if ($operation eq 'disconnect') {
say(1, "Disconnecting host '$host'");
eval {
$hostref->DisconnectHost() unless $dryrun;
}
} elsif ($operation eq 'reconnect') {
say(1, "Reconnecting host '$host'");
eval {
$hostref->ReconnectHost() unless $dryrun;
}
} elsif ($operation eq 'maintenance') {
say(1, "Entering maintenance mode for host '$host'");
eval {
$hostref->EnterMaintenanceMode(timeout => 0) unless $dryrun;
}
} elsif ($operation eq 'restore') {
say(1, "Leaving maintenance mode for host '$host'");
eval {
$hostref->ExitMaintenanceMode(timeout => 0) unless $dryrun;
}
} elsif ($operation eq 'restart') {
say(1, "Restarting host '$host'");
eval {
$hostref->RebootHost(force => 1) unless $dryrun;
}
} elsif ($operation eq 'shutdown') {
say(1, "Shutdown host '$host'");
eval {
$hostref->ShutdownHost(force => 1) unless $dryrun;
}
}
error("host->$operation", $host, @_) if @_;
}
# }}} HOST
} elsif ($cmd eq 'migrate') { # MIGRATE {{{
fatal("Invalid priority: '$priority'. Choose from: low, normal, high") unless $priority =~ /^low|normal|high$/;
my $priorityref = VirtualMachineMovePriority->new($priority) or fatal('Invalid internal priority state. Probably an issue with the VMware libraries');
my $targethost = pop;
fatal('No destination host specified') unless $targethost;
my $poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool") if ($pool);
my $targethostref = getview('HostSystem', $targethost) or fatal("Invalid destination host: $targethost");
my @vms = multiglob([list('VirtualMachine')], \@ARGV);
fatal('No VM\'s match the given pattern') unless scalar(@vms);
say(2, "Migrating to $targethost with $priority priority");
my $success; # Last operation worked
foreach $vm (@vms) {
pause() if $cycleno++ and $success;
$success = 0;
say(1, "Migrate $vm -> $targethost");
my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid VM: $vm");
my $vmpoolref = $pool ? $poolref : getview('Mor', $vmref->resourcePool); # User either user specified pool or import from source VM
eval {
$vmref->MigrateVM(
host => $targethostref,
pool => $vmpoolref,
priority => $priorityref,
state => $vm->runtime->powerState->val,
) unless $dryrun;
};
if (@_) { # Had errors
error('migrate', $vm, @_) ;
last unless $force;
} else {
$success = 1;
}
}
# }}} MIGRATE
} elsif ($cmd eq 'move') { # MOVE {{{
my $targetds = pop;
fatal('No destination datasore specified') unless $targetds;
my $targetdsref = getview('Datastore', $targetds) or fatal("Invalid destination datastore: $targetds");
my $poolref;
if ($pool) {
$poolref = getview('ResourcePool', $pool) or fatal("Invalid destination pool: $pool");
}
my @vms = multiglob([list('VirtualMachine')], \@ARGV);
fatal('No VM\'s match the given pattern') unless scalar(@vms);
say(2, "Moving " . scalar(@vms) . " VM's to datastore '$targetds'");
my $success; # Last operation worked
foreach $vm (@vms) {
pause() if $cycleno++ and $success;
$success = 0;
say(1, "Move $vm -> $targetds");
my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid VM: $vm");
if (getview('Mor', $vmref->datastore->[0])->name eq $targetdsref->name) {
say(0, "$vm is already located in datastore '$targetds'");
next;
}
my $vmhostref = getview('Mor', $vmref->runtime->host) or fatal("Cannot determine VM host for $vm");
my $vmpoolref = $pool ? $poolref : getview('Mor', $vmref->resourcePool); # User either user specified pool or import from source VM
eval {
$vmref->RelocateVM(spec => VirtualMachineRelocateSpec->new(
datastore => $targetdsref,
host => $vmhostref,
pool => $vmpoolref,
)) unless $dryrun;
};
if (@_) { # Had errors
error('move', $vm, @_);
last unless $force;
} else {
$success = 1;
}
}
# }}} MOVE
} elsif ($cmd eq 'state') { # STATE {{{
my $state = shift;
fatal('No state specified. Choose: on, off, suspend, reboot, shutdown, restart, standby') unless $state;
fatal('Invalid power state specified. Choose: on, off, suspend, reboot, shutdown, restart, standby') unless $state =~ /^on|off|reboot|shutdown|suspend|standby|restart$/;
my @vms = multiglob([list('VirtualMachine')], \@ARGV);
fatal('No VM\'s match the given pattern') unless scalar(@vms);
my $success;
foreach $vm (@vms) {
pause() if $cycleno++ and $success;
$success = 0;
my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid virtual machine: $vm");
if ($state eq 'on') {
if ($vmref->runtime->powerState->val eq 'poweredOff') {
say(1, "Powering on $vm");
$vmref->PowerOnVM() unless $dryrun;
$success = 1;
} else {
say(0, "$vm needs to be powered off before it can be turned on (VMware recognises the power state as '" . $vm->runtime->powerState->val . "')!");
}
} elsif ($state =~ /^reboot|off|shutdown|suspend|standby|restart$/) {
if ($vmref->runtime->powerState->val ne 'poweredOn') {
say(0, "Cannot change VM state to '$state' for '$vm' from the current state '" . $vm->runtime->powerState->val . "'");
} elsif ($state eq 'reboot') {
say(1, "Rebooting $vm");
$vmref->ResetVM() unless $dryrun;
$success = 1;
} elsif ($state eq 'suspend') {
say(1, "Suspending $vm");
$vmref->SuspendVM() unless $dryrun;
$success = 1;
} elsif ($state eq 'off') {
say(1, "Powering off $vm");
$vmref->PowerOffVM() unless $dryrun;
$success = 1;
} elsif ($state eq 'standby') {
say(1, "Standby $vm");
$vmref->StandbyGuest() unless $dryrun;
$success = 1;
} elsif ($state eq 'shutdown') {
say(1, "Shutting down $vm");
$vmref->ShutdownGuest() unless $dryrun;
$success = 1;
} elsif ($state eq 'restart') {
say(1, "Restarting $vm");
$vmref->RebootGuest() unless $dryrun;
$success = 1;
}
}
}
# }}} STATE
} elsif ($cmd eq 'setpool') { # SETPOOL {{{
my $level = shift;
fatal('You must specify a level to set. Choose from: low, normal, high') unless $level;
fatal('Invalid level. Choose from: low, normal, high') unless $level =~ /^low|normal|high$/;
my $item = shift;
fatal('You must specify what item to set. Choose from: cpu, mem, all') unless $item;
fatal('Invalid item selection. Choose from: cpu, mem, all') unless $item =~ /^cpu|mem|all$/;
my @pools = multiglob([list('ResourcePool')], \@ARGV) or fatal('No pools match the given pattern');
my $success;
foreach $pool (@pools) {
pause() if $cycleno++ and $success;
$success = 0;
my $poolref = getview('ResourcePool', $pool);
fatal("Invalid resource pool: $pool") unless $poolref;
my $newshare = SharesInfo->new(shares => 0, level => SharesLevel->new($level));
my $cpualloc, $memalloc;
if ($item eq 'cpu') { # Set CPU, import RAM
$cpualloc = ResourceAllocationInfo->new(shares=>$newshare);
$memalloc = $poolref->config->memoryAllocation;
} elsif ($item eq 'mem') { # Set RAM, import CPU
$cpualloc = $poolref->config->cpuAllocation;
$memalloc = ResourceAllocationInfo->new(shares=>$newshare);
} else { # Set both to the same value
$cpualloc = ResourceAllocationInfo->new(shares=>$newshare);
$memalloc = ResourceAllocationInfo->new(shares=>$newshare);
}
my $config = ResourceConfigSpec->new(cpuAllocation=>$cpualloc, memoryAllocation=>$memalloc);
$poolref->UpdateConfig(config => $config) unless $dryrun;
$success = 1;
}
# }}} SETPOOL
} elsif ($cmd eq 'show') { # SHOW {{{
my $rawtype = $type = shift;
unless ($type = translate($type)) { # First arg is not a recognised type - assume the user ommitted the prefix 'vm'
unshift @ARGV, $rawtype; # Add the incorrect type back to pattern list
$type = 'VirtualMachine';
say(1, "No specific type requested. Assuming: 'vm'");
}
my @items = multiglob([list($type)], \@ARGV);
fatal("No matching items found") unless @items;
foreach $item (@items) {
my %info = getinfo($type, $item);
print "$key = $val\n" while (($key, $val) = each %info);
print "\n";
}
# }}} SHOW
} elsif ($cmd eq 'snapshot') { # SNAPSHOT {{{
my @vms = multiglob([list('VirtualMachine')], \@ARGV) or fatal('No VM\'s match the given pattern');
$title = $title || time;
my $success;
foreach $vm (@vms) {
say(1, "Snapshot '$vm'");
pause() if $cycleno++ and $success;
$success = 0;
my $vmref = getview('VirtualMachine', $vm) or fatal("Invalid virtual machine: $vm");
eval {
$vmref->CreateSnapshot(
name => $title,
description => 'VMM created snapshot',
memory => 0,
quiesce => 1,
) unless $dryrun;
};
if (@_) {
error('snapshot', $vm, @_);
} else {
$success = 1;
}
}
# }}} SNAPSHOT
} elsif ($cmd eq 'version' or !$cmd) { # VERSION {{{
my $service = Vim::get_service_content();
print "vServer name: " . $service->about->fullName, "\n";
print "vServer OS: " . $service->about->osType . "\n";
print "API version: " . $service->about->apiVersion . " (build " . $service->about->build, ")\n";
print "Perl toolkit version: " . VMware::VIRuntime->VERSION . "\n";
# }}} VERSION
} else { # OTHER {{{
fatal("Unknown command: '$cmd'");
# }}}
}
# Default config file
__DATA__
[GLOBAL]
verbose = 1
dryrun = 0
force = 0
|