#!/usr/bin/perl

use strict;
use warnings;

# Sample script showing how to retreive information from the XtremIO REST API
#
# Uses 2 different methods to get details for all volumes on the array
# See https://blog.docbert.org/using-the-xtremio-rest-api-part-5/ for more info
#
# Scott Howard, scott.howard@emc.com
#

my $username="admin";
my $password="Xtrem10";
my $xms="xms.example.com";

#
# If your XMS does not have a valid SSL certificate then uncomment the below
# line to avoid failing due to a cert error
#
#$ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #

use REST::Client;
use MIME::Base64;
use JSON;
use Data::Dumper;

#
# Check the response from all API calls, and exit if they fail
#
sub checkerr($) {
	my ($cl) = @_;

	my $respcode=$cl->responseCode();
	return 0 if ($respcode>=200 && $respcode <300);

	# Error message is normally JSON, but sometimes it isnt...
	my $msg = $cl->responseContent();
	if ($msg =~ /^{/) {
		$msg = from_json($msg)->{message};
	}
	print STDERR "Error - $msg (response code $respcode)\n";
	exit(2);
}


my $client = REST::Client->new();
my $headers = {Authorization => "Basic ".encode_base64($username.":".$password), "Content-Type" => 'application/json'};

#
# First, do things the hard way - get a list of all volumes and their URLs,
# and then iterate through to get the details of each one
#

print "Getting list of all volumes\n";
$client->GET("https://$xms/api/json/v2/types/volumes", $headers);
checkerr($client);
my $resp = from_json($client->responseContent());

my @Volumes;

foreach my $v (@{$resp->{volumes}}) {
	push @Volumes, $v->{href};
}

foreach my $v (@Volumes) {
	print "Getting URL $v\n";
	$client->GET($v, $headers);
	checkerr($client);
	my $resp = from_json($client->responseContent());

	# For debugging/learning purposes, uncomment the following
	# line to see the full details returned and the JSON structure
	# print Dumper($resp);

	print << "EOT"
Volume name : $resp->{content}->{name}
Volume size : $resp->{content}->{"vol-size"}
Volume used : $resp->{content}->{"logical-space-in-use"}

EOT
}


#
# Now do the same thing the easier way - using ?full=1 to get the details
# for all vols in one request
#

print "\nGetting details of all volumes\n";
$client->GET("https://$xms/api/json/v2/types/volumes?full=1&prop=vol-size&prop=logical-space-in-use", $headers);
checkerr($client);
$resp = from_json($client->responseContent());

foreach my $v (@{$resp->{volumes}}) {
	print << "EOT"
Volume name : $v->{name}
Volume size : $v->{"vol-size"}
Volume used : $v->{"logical-space-in-use"}

EOT
}

exit(0);

