4. ECP Service Provider Edition API

4.1. Scope

It must be noted that all of the API calls in this document are designed to deal with ONLY machines in the customer interface. The admin interface is designed to be outside of the scope of customer machine management, therefore most commands will not work against machines created on the admin side, and their behaviors when targeting an admin object are undefined.

4.2. Authentication

4.2.1. Introduction

The ECP API uses basic HTTP authorization in order to establish a connection with clients. To establish a connection, the client needs to send an initial HTTP request containing the username and password. If authentication succeeded, the client will receive a non-error HTTP response code and response message. The initial HTTP login request can be either a GET request or a POST request.

Note

ECP authentication for rest calls HAS CHANGED in 3.5.1. While we always had fairly strict checks against a variety of XSS/XSRF attacks, we have improved this system with a far more explicit XSRF prevention check, which can break remote compatibility for remote scripts.

All of these examples assume that there is an exemption set in the xsrf.exempt_ip configuration variable. If you wish to expose your api to OUTSIDE (ie: customer) scripting, then you will need to instruct them to do the following: 1) Check for the value of the Set-Cookie http header from your login request. This should contain a cookie named ecp-csrf-token, which has a value of a 160bit (20 character) hex number. 2) Return an http header containing this hex string , named X-XSRFToken.

Received from login:

Set-Cookie:ecp-csrf-token=a49bc976ee7c221925bd62c3528d702deed000df; expires=Wed, 13 Apr 2011 18:24:46;

Send back to server on rest call:

X-XSRFToken: a49bc976ee7c221925bd62c3528d702deed000df

See also

XSRF referer checking, XSRF exempt_ip

4.2.2. Examples

4.2.2.1. PHP

This is the basic authentication function. It is used throughout the documentation to simplify the examples. It is included with require(‘authentication.php’).

 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
<?php
//Returns true if log in was sucessful, otherwise false.
function authenticate($base_url, $username, $password, $cookies_file, $method='')
{
    //Initialize the client object.
    $client = curl_init();

    //Do some basic client configuration.  We need to be able to read and write 
    //cookies from and to a file.
    curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);
    curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
    
    if(strtolower($method) == 'get'){
    
        //Initialize the authentication GET URL including authentication 
        //parmeters.
        curl_setopt($client, CURLOPT_HTTPGET, 1);
        curl_setopt($client, CURLOPT_URL, $base_url.
        "/modules/hosting/?login=Login&user_name=$username&password=$password");
    } else {
    
        //Set up the client to use POST
        curl_setopt($client, CURLOPT_POST, true);
        //Initialize the authentication URL
        curl_setopt($client, CURLOPT_URL, $base_url.'/modules/hosting/');
        
        //Initialize the authentication POST parameters.
        curl_setopt($client, CURLOPT_POSTFIELDS,
        "user_name=$username&password=$password&login=Login");
    }
    
    //Send the request and read the response code. 
    $response = curl_exec($client);
    $httpcode = curl_getinfo($client, CURLINFO_HTTP_CODE);
    
    //Test the result of the authentication attempt.
    if ($httpcode!=401 && $httpcode!=0)
        $is_sucess = true;
    else $is_sucess = false;
    
    //Close the connection.
    curl_close($client);
    
    return $is_sucess;
}
?>

Here is an example of how to establish a connection by sending a GET request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
require('authentication.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file, 'get')){
    echo "Authentication sucessful.";
    
    //Use use the same cookie file for other API calls

}
else{
    echo "Authentication failed.";
}
?>

Here is an example of how to establish a connection by sending a POST request.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
require('authentication.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    echo "Authentication sucessful.";
    
    //Use use the same cookie file for other API calls

}
else{
    echo "Authentication failed.";
}
?>

4.2.2.2. Python

Here is an example of how to establish a connection by sending a GET request. It also shows in detail the installation of a cookie handler.

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError

#Create a cookie jar
my_cookie_jar = CookieJar()
#Create a URL opener that processes cookies using my_cookie_jar
my_opener = build_opener(HTTPCookieProcessor(my_cookie_jar))
#Make my_opener the default opener. This way cookies are handled automatically 
#by urllib2 and will be sent with every urlopen() call and extracted from every 
#response.
install_opener(my_opener)

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Set up the log in API request. The method is GET by default.
    req = Request(host + '/modules/hosting/?login=Login&user_name=' + \
                  username + '&password=' + password)
    
    #Send the log in request and get a response
    response = urlopen(req)
    
    #Note that this API call can be shortened like this:
    
    #urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
    #        username + '&password=' + password)
    
    #However, doing so would make it impossible to explicitly access information 
    #about the cookies or response later. It is done in other examples because
    #as long as there is no HTTP error, the log in request was sucessful.

except (HTTPError, URLError) as exception:

    #Handle errors
    print "Authentication failed."
    print exception

else:

    print "Authenticaiton sucessful."
    
    #Show the cookies to prove that the request was successful
    for cookie in my_cookie_jar.make_cookies(response, req):
        print cookie

Here is an example of how to establish a connection by sending a POST request. It also shows in detail the installation of a cookie handler.

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError

#Create a cookie jar
my_cookie_jar = CookieJar()
#Create a URL opener that processes cookies using my_cookie_jar
my_opener = build_opener(HTTPCookieProcessor(my_cookie_jar))
#Make my_opener the default opener. This way cookies are handled automatically 
#by urllib2 and will be sent with every urlopen() call and extracted from every 
#response.
install_opener(my_opener)

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Set up the log in API request. The method is POST if data is provided.
    req = Request(host + '/modules/hosting/', data = 'login=Login&user_name='+ \
                  username + '&password=' + password)
    
    #Send the log in request and get a response
    response = urlopen(req)
    
    #Note that this API call can be shortened like this:
    
    #urlopen(host + '/modules/hosting/', data = 'login=Login&user_name='+ \
    #        username + '&password=' + password)
    
    #However, doing so would make it impossible to explicitly access information 
    #about the cookies or response later. It is done in other examples because
    #as long as there is no HTTP error, the log in request was sucessful.

except (HTTPError, URLError) as exception:

    #Handle errors
    print "Authentication failed."
    print exception

else:

    print "Authenticaiton sucessful."
    
    #Show the cookies to prove that the request was successful
    for cookie in my_cookie_jar.make_cookies(response, req):
        print cookie

4.2.2.3. Java

Here is an example of how to establish a connection by sending a GET request.

 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
import java.net.*;

public class authentication_get {

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "customer";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/network/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            System.out.println("Connected Successfully");
            System.out.println(" ");
            do {
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }
}

Here is an example of how to establish a connection by sending a POST request.

 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
import java.io.IOException;
import java.net.*;

public class authentication_post {
    // Following method will output all information in proper format

    public static void ControlVM(Client user, String uri, CookieManager cm)
            throws IOException {
        String trans_info_Line = "";
        int count = 0;
        error_Handling errorCheck = new error_Handling();
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            trans_info_Line = (user.connectURI(url, cm, count));
            errorCheck.api_error(trans_info_Line);
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("POST");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "customer";
        String password = "password";
        String uri = "rest/hosting/network/list";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            System.out.println("Connected Successfully");
            System.out.println(" ");
            ControlVM(user, uri, cm);
        }

    }
}

4.3. billing – Billing

Billing functionality.

4.3.1. Resources

4.3.1.1. Billing

class billing.Billing

This resource represents a query into the available billing data for users and the virtual machine resources used by those users.

Resource URI:

/modules/billingreports/
GET(start_date, end_date)

Retrieve the virtual machine resource usage data in CSV format by submitting an HTTP GET request.

Note

This resource requires read permission on both the virtual machine and the elastic_hosting extension module when using the HTTP GET method.

Parameters:
  • start_date – The starting date of the resource usage data (YYYY:MM:DD:HH:mm:ss).
  • end_data – The ending data of the resource usage data (YYYY:MM:DD:HH:mm:ss).
Return type:

billing.RepBillingSummary

4.3.1.2. BillingUser

class billing.BillingUser

This resource provides granular details on the machines being billed for a particular user.

Resource URI:

modules/billingreports/user_summary
GET(user_uuid, start_date, end_date)
Retrieve the individual VM utilization records for a given user during the requested time frame via an HTTP GET request.

Note

This resource requires read permission on both the virtual machine and the elastic_hosting extension module when using the HTTP GET method.
param user_uuid:
 The uuid of the user to limit the report to
param start_date:
 The starting date of the resource usage data (YYYY:MM:DD:HH:mm:ss).
param end_date:The ending data of the resource usage data (YYYY:MM:DD:HH:mm:ss).
rtype:billing.RepUserBilling

4.3.1.3. BillingTraffic

class billing.BillingTraffic

This resource represents a query into the bandwidth utilization for a user and their virtual machines. Bandwidth utilization is broken down by virtual network, allowing for different billing rates depending on the target network, ie: public/private networking.

Resource URI

/modules/billingtrafficreports/
GET(start_date, end_date)

Retrieve the virtual machine bandwidth usage data in CSV format by submitting a HTTP GET request.

Note

This resource requires read permission on both the virtual machine and the elastic_hosting_billing extension module when using the HTTP GET method.

Parameters:
  • start_date – The starting date of the resource usage data (YYYY:MM:DD:HH:mm:ss).
  • end_data – The ending data of the resource usage data (YYYY:MM:DD:HH:mm:ss).
  • user_uuid – The uuid of the user to limit the report to
  • machine_uuid – The uuid of the machine to limit the report to
Return type:

billing.RepBillingTraffic

4.3.2. Representations

4.3.2.1. RepBillingSummary

class billing.RepBillingSummary

This is a representation of virtual machine resource usage for the cluster as a whole, by user.

The first row in this representation is a set of headers describing each column of data. There are a variable number of hardware profile columns, so it is important to have a flexible parser to handle them. The first columns represent the user name, and user uuid respectively, followed by one column for hours of runtime for each of the available hardware profiles, then terminated with a single column that gives the amount of disk space used, in GB for that user.

Representation:

user,user_uuid,tiny,medium,CUSTOMERPROFILE1,CUSTOMERPROFILE2,ARBITRARYPROFILENAME,256M_x86_64_1cpu,ANOTHERPROFILE,PW,PX,PY,PZ,totalMBytes
admin,7eabba12-12fe-11dd-8fd0-0019d2b28af0,0,0,0,0,0,0,0,0,0,0,0,0
customer,7b906438-debb-11de-b902-0022fa5e0f34,164,0,0,0,0,1363,0,0,0,0,0,6654
userX,cf45745c-eb84-11df-b903-90e6ba09c256,0,0,0,0,0,0,0,0,0,0,0,0
user1,d31fcc86-2e2c-11e0-b903-90e6ba09c256,0,0,0,0,0,0,0,0,0,0,0,0
user2,3cec3f24-43ad-11e0-b903-90e6ba09c256,0,0,0,0,0,0,0,0,0,0,0,0
user3,609a21ae-025b-11e0-b903-90e6ba09c256,0,0,0,0,0,0,0,0,0,0,0,0
user4,b17c2d12-ff43-11df-b903-90e6ba09c256,0,0,0,0,0,0,0,0,0,0,0,0

4.3.2.2. RepUserBilling

class billing.RepUserBilling

This is a representation of the virtual machine resource usage for a given user of the system.

Note

The first row in this representation is descriptive of the following rows. The columns show the user uuid (none if the machine is created by elastic valet), the start date and end date of the machine action, hardware profile size as a string and as a uuid, machine uuid, cpu count, the memory usage in MB and the disk usage in GB.

Representation:

user_uuid, start_date, end_date, profile_name, profile_uuid, machine_uuid, package_uuid, cpu_count, memory_usage_mb, disk_usage_gb
c029122c-afb5-11df-83a4-000acd19024f, 2010-08-24 15:47:41, 2010-08-24 16:47:32, 'Small', bcaff710-2914-11de-836c-001a929face2, c8f86644-afb7-11df-9156-526rgb13370t, c020f1a0-afb5-11df-83a4-000acd19024f, 1, 512, 20
c029122c-afb5-11df-83a4-000acd19024f, 2010-08-24 16:48:03, 2010-08-24 16:49:04, 'Small', bcaff710-2914-11de-836c-001a929face2, c8f86644-afb7-11df-9156-000acd19024f, c020f1a0-afb5-11df-83a4-000acd19024f, 1, 512, 20

4.3.2.3. RepBillingTraffic

class billing.RepBillingTraffic

This is a representation of the virtual machine bandwidth usage for all users of the system.

Note

The first row in this representation is descriptive of the following rows. The columns show the user uuid (none if the machine is created by elastic valet), the start date and end date of the machine action, hardware profile size as a string and as a uuid, machine uuid, cpu count, the memory usage in MB and the disk usage in GB.

Representation:

user.name, user.uuid, machine.name, machine.uuid, interface, in(Mb), out(Mb)
customer, 7b906438-debb-11de-b902-0022fa5e0f34, testiso, abba1520-00fa-11e0-b903-90e6ba09c256, eth0, 0, 44
customer, 7b906438-debb-11de-b902-0022fa5e0f34, testiso, abba1520-00fa-11e0-b903-90e6ba09c256, ***, 32, 97

4.3.3. Examples

4.3.3.1. PHP

Here is an example of how to display all billing data.

  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
<html>
<head>
    <title>Billing</title>
</head>
<body>
    <h1>Billing Summary:</h1>
    <?php
    require('authentication.php');

    //Basic connection parameters.
    //IP address or host name of the primary ECP node (no trailing slash)
    $base_url = '127.0.0.1';
    //login info
    $username = 'admin';
    $password = 'password';
    
    //The cookie file used to store the session cookie.
    $cookies_file = 'cookies.txt';
    
    //Initialize and configure the client to make a custom call because the 
    //response for this API is not a json object, but in CSV format.
    $client = curl_init();
    curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);
    curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
    curl_setopt($client, CURLOPT_URL, $base_url.'/modules/billingreports/');

    
    //Authenticate and check for success
    if (authenticate($base_url, $username, $password, $cookies_file)){
        
        //Initialize the sample cost dictionary.
        $cost = array('Small'=>0.029, 'Medium'=>0.119, 'Large'=>0.239, 'totalMBytes'=>0.001);


        //Make the API call.
        $http_response = curl_exec($client);

        //Make sure the request was successful.
        $http_response_code = curl_getinfo($client, CURLINFO_HTTP_CODE);
    
        if($http_response_code==200){
    
            //Initialize the CSV response into a usable array.
            $billing_array = array_filter(explode("\n", $http_response));
            $billing_titles = explode(',', array_shift($billing_array));
        
            foreach($billing_array as $row_num=>$row_data){
                $billing_info_line = explode(',', $row_data);
                foreach($billing_info_line as $col_num=>$col_data){
                    $billing_info[$row_num][$billing_titles[$col_num]] = $col_data;
                }
            }

            //Format and display all billing data.
            foreach($billing_info as $statement){

                $small_total=$statement['Small']*$cost['Small'];
                $medium_total=$statement['Medium']*$cost['Medium'];
                $large_total=$statement['Large']*$cost['Large'];
                $storage_total=$statement['totalMBytes']*$cost['totalMBytes'];

                echo '<div style="font-family:sans-serif">';
                echo '<h1>Billing statement for '.$statement['user'].'</h1>';
                echo '<p style="color:#666; font-size:10px">UUID: '.$statement['user_uuid'].'</p>';
                echo '<h2>Usage:</h2>';
                echo '<table cellpadding="10px" cellspacing="0" border="1px">';

                echo '<tr>';
                echo '<td>Small Template</td>';
                echo '<td>$'.$cost['Small'].' per hour</td>';
                echo '<td>'.$statement['Small'].' hours</td>';
                echo '<td>$'.$small_total.'</td>';
                echo '</tr>';

                echo '<tr>';
                echo '<td>Medium Template</td>';
                echo '<td>$'.$cost['Medium'].'</td>';
                echo '<td>'.$statement['Medium'].' hours</td>';
                echo '<td>$'.$medium_total.'</td>';
                echo '</tr>';

                echo '<tr>';
                echo '<td>Large Template</td>';
                echo '<td>$'.$cost['Large'].' per hour</td>';
                echo '<td>'.$statement['Large'].' hours</td>';
                echo '<td>$'.$large_total.'</td>';
                echo '</tr>';

                echo '<tr>';
                echo '<td>Storage Monthly Max</td>';
                echo '<td>$'.$cost['totalMBytes'].' per MB</td>';
                echo '<td>'.round($statement['totalMBytes']/1024, 2).' GB</td>';
                echo '<td>$'.$storage_total.'</td>';
                echo '</tr>';

                echo '<tr>';
                echo '<td colspan="3">Total: </td>';
                echo '<td>$'.($small_total + $medium_total + $large_total + $storage_total).'</td>';
                echo '</tr>';

                echo '</table></div>';
        
            }
        }
        else{
            echo '<p>Error: Request failed. HTTP response code: '.$http_response_code.'</p>';
        }
    }
    else{
        echo '<p>Error: Authentication failed.</p>';
    }

    //Close the client.        
    curl_close($client);

    ?>
</body>
</html>

4.3.3.2. Python

Here is an example of how to display all billing data.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from csv import reader

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'https://127.0.0.1'
username = 'admin'
password = 'password'

#Dollars per hour per machine
cost = {
'Small': 0.029,
'Medium': 0.119,
'Large': 0.239
}
#Dollars per MB
storage_cost = 0.0001

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/modules/billingreports/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    if response_body:
        
        #Format the output nicely
        
        #This is a way to use the CSV reader for strings even though it is 
        #intended for files
        report = reader(response_body.split("\n"), delimiter=',')
        
        #The first line contains the names of the various hardware templates 
        #that exist along with some special fields.
        first_row = report.next()
        
        #These are shorthand for finding the first element with a given name in 
        #the list. We basically get the indices of the fields that are special. 
        #All other fields are the total number of hours a hardware template was 
        #used.
        #Remove the fields we know and what's left is the hardware template 
        #names.
        user_field = (i for i, field in enumerate(first_row) if \
                      field == 'user').next() 
        
        user_uuid_field = (i for i, field in enumerate(first_row) if \
                      field == 'user_uuid').next()
        
        totalMBytes_field = (i for i, field in enumerate(first_row) if \
                      field == 'totalMBytes').next()
        
        #Create a dictionary of the hardware template names so they retain their 
        #keys when information is removed.
        first_row_dict = dict(zip(xrange(len(first_row)), first_row))
        del(first_row_dict[user_field])
        del(first_row_dict[user_uuid_field])
        del(first_row_dict[totalMBytes_field])
        htemplate_names = first_row_dict
        
        for user in report:
            if user:
            
                #Start summing the users's bill
                total_bill = 0
                #Convert user to a dictionary so we can manipulate the elements 
                #more easily
                user = dict(zip(xrange(len(user)), user))
                
                storage_total = storage_cost * int(user[totalMBytes_field])
                total_bill = total_bill + storage_total
                print '===== ' + user[user_field] + ' ====='
                print 'UUID: ' + user[user_uuid_field]
                print '%20s: %-5s hours x $%-6s = $%s' % \
                       ('Peak storage used', user[totalMBytes_field], \
                        storage_cost, storage_total)
                print
                
                #Remove special fields so that only hardware templates are left
                del(user[user_field])
                del(user[user_uuid_field])
                del(user[totalMBytes_field])
                
                #Display information about each hardware template's usage
                for key, used in user.items():
                
                    #Get the price. If it's unknown make it free.
                    try:
                        price = cost[htemplate_names[key]]
                    except KeyError:
                        price = 0
                        
                    htemplate = htemplate_names[key]
                    total = price * int(used)
                    
                    #Add the expense to the bill
                    total_bill = total_bill + total
                    
                    print '%20s: %-5s hours x $%-6s = $%s' % \
                           (str(htemplate), str(used), str(price), str(total))
                print
                print 'Total bill: $' + str(total_bill)
                print
        
    else:
        #Output the error
        print "There has been an error getting the billing reports."

4.3.3.3. Java

Here is an example of how to display all billing data.

 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
import java.net.*;
import java.text.*;

public class modules_billingreports {
    // Method will be used to display data for each customer in unique format
    public static void DisplayData(String[] values) {
        String Customer;
        String UUID;
        String small_hours;
        String med_hours;
        String large_hours;
        Customer = values[0];
        UUID = values[1];
        small_hours = values[2];
        med_hours = values[3];
        large_hours = values[4];
        // Calculations done to calculate various costs
        double totalGB = ((Double.parseDouble(values[5])) / 1024);
        double usage_cost = ((totalGB * 1024) * 0.001);
        double sml_cost = (Double.parseDouble(small_hours)) * 0.029;
        double med_cost = (Double.parseDouble(med_hours)) * 0.119;
        double large_cost = (Double.parseDouble(large_hours)) * 0.239;
        double total_cost = usage_cost + sml_cost + med_cost + large_cost;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println("Billing Statement for:" + Customer);
        System.out.println("UUID:" + UUID);
        System.out.println("Small Template:      $0.029/hour  Usage: "
                + small_hours + " Hours   Cost:$" + df.format(sml_cost));
        System.out.println("Medium Template:     $0.119/hour  Usage: "
                + med_hours + " Hours    Cost:$" + df.format(med_cost));
        System.out.println("Large Template:      $0.239/hour  Usage: "
                + large_hours + " Hours   Cost:$" + df.format(large_cost));
        System.out
                .println("Storage Monthly Max: $0.001/MB    Amount:"
                        + Math.round(totalGB) + " GB    Cost:$"
                        + df.format(usage_cost));
        System.out.println("Total Cost:  $" + df.format(total_cost));
        System.out.println(" ");
        System.out.println(" ");

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String billing_Line = "";
        String[] split_billing_line = null;
        int count = 1;
        URL url = new URL(
                "https://127.0.0.1/modules/billingreports/");
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                billing_Line = (user.connectURI(url, cm, count));
                if (billing_Line != null) {
                    split_billing_line = billing_Line.split(",");
                    DisplayData(split_billing_line);
                }
                count++;
            } while (billing_Line != null);
        }
    }
}

4.4. cdmount – Mounting CDs/DVDs

Mounting virtual CDs/DVDs on the virtual machines.

4.4.1. Resources

4.4.1.1. CDMount

class cdmount.CDMount

This resource represents a method in which to mount CDs/DVDs to a specific VM.

Resource URI::

/rest/hosting/cdmount/
PUT(vm, file_name)

Mount a hard drive on a virtual machine by submitting an HTTP PUT request. The vm parameter represents the UUID of the virtual machine. The file_name parameter represents the name of the iso file on the server to be mounted.

Parameters:
  • vm – UUID of the VM
  • file_name – Name of the ISO file that exists on the server
Return type:

cdmount.RepCDMount

See also

vm, isofile

4.4.1.2. CDMountUUID

class cdmount.CDMountUUID

This resource represents a specific CD/DVD mounted on a virtual machine.

Resource URI::

/rest/hosting/cdmount/<UUID>/
GET()

Get information about the mounted CD/DVD with that UUID. The UUID in the resource URI should be the UUID of the CD/DVD to get information about.

Return type:cdmount.RepCDMount

See also

vm

DELETE()
Unmount the specified CD/DVD. The UUID in the resource URI should be the UUID of the CD/DVD to delete. Note: To find the CD/DVD you want to unmount, you may want to use /rest/hosting/vm/list or /rest/hosting/vm/<UUID>/.

See also

vm

4.4.2. Representations

4.4.2.1. RepCDMount

class cdmount.RepCDMount

This is a representation of a mounted CD/DVD.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
cdrom_mount
This attribute represents the CDROM that is mounted.

Representation:

{"errno":response.errno,
 "message":response.message,
 "cdrom_mount": {"created_time": cdmount.created
                 "uuid": cdmount.uuid
                 "file_name": cdmount.file}}

4.5. clone – Clone virtual machines.

Virtual machine cloning functionality.

4.5.1. Resources

4.5.1.1. Clone

class clone.Clone

This resource represents a method in which to clone a virtual machine.

Resource URI:

/rest/hosting/clone/<UUID>
POST()

Clone the specified virtual machine by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target virtual machine.

Note

This resource requires create permission on the elastic_hosting extension module.

Return type:vm.RepClone

See also

vm

4.5.2. Representations

4.5.2.1. RepClone

class clone.RepClone

This is a representation of a virtual machine being cloned.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
machine_id
This attribute represents the UUID of the virtual machine being cloned.

Representation:

{"errno": response.errno,
 "message": response.message,
 "machine_id": vm.uuid}

4.5.3. Examples

4.5.3.1. PHP

Here is an example of how to clone powered off virtual machines.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Machine to clone. (It needs to be turned off)
$uuid = 'aab3caa6-0f48-11df-9193-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/clone/'.$uuid.'/', 
        'post', NULL, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){
    
        echo "<p>Cloning $response[machine_id].</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.5.3.2. Python

Here is an example of how to clone powered off virtual machines.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

#VM to be cloned
uuid = '2c8b1b05-1356-11df-938b-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a POST by default when providing data.
    req = Request(host + '/rest/hosting/clone/'+uuid+'/', data = '')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)

        #Output the appropriate message with the appropriate ID upon a 
        #Successful Cloning
        print 'Cloning started.'
        print 'UUID of clone: ' + json['machine_id']
    else:
        #Output the error
        print error

4.5.3.3. Java

Here is an example of how to clone powered off virtual machines.

 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_clone_uuid_post {
    // Following method will output all information in proper format
    public static void DisplayData(String clone_Line) {
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(clone_Line);
            System.out.println(" ");
            System.out.println(json.get("message"));
            System.out.println("Machine id: " + json.get("machine_id"));
            System.out.println(" ");
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void ControlVM(Client user, String uri, String query,
            String uuid, CookieManager cm) throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/"
                    + uuid + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                httpURLConnection.setRequestMethod("POST");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    DisplayData(nextline);
                }
                dis.close();
            }
        } catch (RuntimeException exception) {
            System.out.println("Failed");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "customer";
        String password = "password";
        String uuid = "5fd137a3-129b-11df-a61d-000acd1901c5";
        String uri = "rest/hosting/clone";
        String query = " ";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            ControlVM(user, uri, query, uuid, cm);
        }

    }
}

4.6. disk – Additional Storage

Adding storage with additional virtual hard drives.

4.6.1. Resources

4.6.1.1. VMDisk

class disk.VMDisk

This resource represents a method in which to add additional disks to a specific VM.

Resource URI::

/rest/hosting/vmdisk/
PUT(vm, size, disk_template)

Add an additional virtual disk to a virtual machine by submitting an HTTP PUT request. The vm parameter represents the UUID of the virtual machine. The size parameter represents the size of the disk to be added in MB. The disk_template parameter is the disk template used to create the new disk.

Parameters:
  • vm – UUID of the VM
  • size – Size of disk in MB
  • disk_template – The disk template.
Return type:

disk.RepDisk

Note

The size parameter is deprecated and will be removed in the future. Use the disk_template parameter instead.

See also

vm dtemplate

4.6.1.2. VMDiskUUID

class disk.VMDiskUUID

This resource represents a specific disk.

Resource URI::

/rest/hosting/vmdisk/<UUID>/
GET()

Get information about the disk with that UUID. The UUID in the resource URI should be the UUID of the disk to get information about.

Return type:disk.RepDisk

See also

vm

DELETE()
Delete the specified disk. The UUID in the resource URI should be the UUID of the disk to delete. Note: To find the disk you want to delete, you may want to use /rest/hosting/vm/list or /rest/hosting/vm/<UUID>/.

See also

vm

4.6.2. Representations

4.6.2.1. RepDisk

class disk.RepDisk

This is a representation of a VM disk.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
vmdisk
This attribute represents the VM disk.

Representation:

{"errno":response.errno,
 "message":response.message,
 "vmdisk": {"created_time": disk.created
            "target_dev": disk.dev
            "file_path": disk.path
            "uuid": disk.uuid
            "size": disk.size}}

4.7. dtemplate – Disk Template

Disk template functionality.

4.7.1. Resources

4.7.1.1. DtemplateUUID

class dtemplate.DtemplateUUID

This resource represens a specific disk template.

Resource URI:

/rest/hosting/dtemplate/<UUID>/
GET()

Retrieve the specified disk template by submitting an HTTP GET request. The UUID in the resource uri should be the uuid of the target disk template.

Note

This resource requires read permission on both the disk template and the elastic_hosting extension module when using the HTTP GET method.

Return type:dtemplate.RepDtemplateUUID

4.7.1.2. DtemplateList

class dtemplate.DtemplateList

This resource represents a list of disk templates.

Resource URI:

/rest/hosting/dtemplate/list/
GET()

Retrieve a list of disk templates by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:dtemplate.RepDtemplateList

4.7.2. Representations

4.7.2.1. RepDtemplateUUID

class dtemplate.RepDtemplateUUID

This is a representation of a disk template resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
uuid
This attribute represents the ID of the disk template resource.
size
This attribute represents the size of the disk template resource. This attribute is measured in MB.

Representation:

{"errno": response.errno,
 "message": response.message,
 "dtemplate": {"uuid": dtemplate.uuid,
               "size": dtemplate.size}}

4.7.2.2. RepDtemplateList

class dtemplate.RepDtemplateList

This is a representation of a list of disk templates. This is a list of dtemplate.RepDtemplateUUID representations.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general error message generated by the resource.
templates
This attribute represents the list of template representations.

Representation:

{"errno": response.errno,
 "message": response.message,
 "templates": [dtemplate1, dtemplate2]}

4.7.3. Examples

4.7.3.1. PHP

Here is an example of how to list all available disk templates.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $disks = api_request($base_url.'/rest/hosting/dtemplate/list/', 'get', null, 
        $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($disks)){
    
        if($disks['templates']){
        
            //Display all returned disk data.
            echo '<h1>Disk templates:</h1>';
            echo '<ol>';
            foreach ($disks['templates'] as $disk){
                 echo "<li>($disk[uuid]) ".($disk['size']/1024)." GB</li>";
            }
            echo '</ol>';
        }
        else{
            echo '<p>No disks available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$disks.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to get information about a specific disk template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Disk template to get details of
$uuid = 'f1648fba-29ce-11de-84a2-001a929face2';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/dtemplate/'.$uuid.'/', 'get', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for disk with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['dtemplate'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.7.3.2. Python

Here is an example of how to list all available disk templates.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/dtemplate/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the disk templates
        for template in json['templates']:
        
            #Output and remove the name from the dictionary
            print
            print '=========== ' + str(round(template['size']/1024, 2)) + \
                  'GB ==========='
            del(template['size'])
            
            #Output all information
            for key in template.keys():
                print key + ' = ' + str(template[key])
    else:
        #Output the error
        print error

Here is an example of how to get information about a specific disk template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

#Disk template to get information about
uuid = 'f1648fba-29ce-11de-84a2-001a929face2'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/dtemplate/f1648fba-29ce-11de-84a2-001a929face2/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Show information about this template
        template = json['dtemplate']
        
        #Output and remove the name from the dictionary
        print 'Information for Disk Drive with UUID: '+ template['uuid'] 
        del(template['uuid'])
        
        #Output all information
        for key in template.keys():
            print key + ' = ' + str(template[key])
        
    else:
        #Output the error
        	print error

4.7.3.3. Java

Here is an example of how to list all available disk templates.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_dtemplate_list {

    public static void DisplayData(String hd_Line) {
        boolean check = true;
        int count = 0;
        JSONObject harddrive_json;
        System.out.println(" ");
        System.out.println("Disk Templates)");
        System.out.println(" ");
        while (check) {
            try {
                harddrive_json = (JSONObject) new JSONParser().parse(hd_Line);
                JSONArray harddrive_obj = (JSONArray) harddrive_json
                        .get("templates");
                JSONObject harddrive_name = (JSONObject) harddrive_obj
                        .get(count);
                // information will be displayed accordingly
                System.out.print((count + 1) + ".");
                int Size = ((Number) harddrive_name.get("size")).intValue();
                System.out.println(Size / 1024 + " GB");
                System.out.println("UUID: " + harddrive_name.get("uuid"));
                System.out.println(" ");
                count++;
            } catch (Exception e) {
                check = false;
                break;
            }

        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String disk_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/dtemplate/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                disk_Line = (user.connectURI(url, cm, count));
                if (disk_Line != null) {
                    errorCheck.api_error(disk_Line);
                    DisplayData(disk_Line);
                    count++;
                }
            } while (disk_Line != null);
        }
    }

}

Here is an example of how to get information about a specific disk template.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_dtemplate_uuid_get {

    public static void DisplayData(String hd_Line, String uuid) {
        JSONObject harddrive_json;
        System.out.println(" ");
        System.out.println("Info for Disk Template with UUID: " + uuid);
        System.out.println(" ");
        try {
            harddrive_json = (JSONObject) new JSONParser().parse(hd_Line);
            JSONObject harddrive_temp = (JSONObject) harddrive_json
                    .get("dtemplate");
            // information will be displayed accordingly
            System.out.println("Disk Size: " + harddrive_temp.get("size"));
        } catch (Exception e) {
            System.out.println("Display Error");
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String disk_Line = "";
        String username = "admin";
        String password = "password";
        String uuid = "5eff7b34-29cf-11de-867d-001a929face2";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/dtemplate/"
                        + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                disk_Line = (user.connectURI(url, cm, count));
                if (disk_Line != null) {
                    errorCheck.api_error(disk_Line);
                    DisplayData(disk_Line, uuid);
                    count++;
                }
            } while (disk_Line != null);
        }
    }

}

4.8. Error Handling

4.8.1. Introduction

There are two modes of failure that can occur when using the ECP API. The first mode of failure is at the HTTP level. If an HTTP standard error code is returned, such as an authentication or a permission error, this means that the client must be able to act accordingly.

The second mode of failure is an internal mode of failure in which the HTTP response is successfully returned to the client, but there is an error code inside the JSON response. These error codes are ECP-specific and the client using the API must be prepared to handle them.

4.8.2. Examples

4.8.2.1. PHP

Here is an example of how to test a given HTTP response string for errors. It is included with require(‘error_handling.php’). It is used by the API request function.

 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
<?php

//Initialize the ECP error code definitions.
define('ECP_SUCCESS'                 , 0);
define('ECP_NO_SUCH_MACHINE'         , 1);
define('ECP_INVALID_COMMAND'         , 2);
define('ECP_MISSING_PARAMETER'       , 3);
define('ECP_COULD_NOT_CONNECT'       , 4);
define('ECP_COULD_NOT_RETRIEVE'      , 5);
define('ECP_COMMAND_FAILED'          , 6);
define('ECP_RESOURCE_LOCKED'         , 7);
define('ECP_INTERNAL_ERROR'          , 8);
define('ECP_UNKNOWN_PARAMETER'       , 9);
define('ECP_RESOURCE_BUSY'           , 10);
define('ECP_NAMING_CONFLICT'         , 11);
define('ECP_RECURSION_ERROR'         , 12);

//This function will determine if the specified HTTP response string contains an 
//error and $error = an error message if it does.
function api_error($http_response){

    //Make sure a response was provided.
    if(!$http_response){
        $error = 'No response.';
    }
    
    //Initialize the JSON response.
    $arr_response = json_decode($http_response, true);
    
    //Make sure the JSON response was initialized.
    if(!$arr_response){
        $error = 'Response cannot be parsed.';
    }
    else {
    
        //Handle the error code.  This function will $error = false on success.
        switch($arr_response['errno']){
            case ECP_SUCCESS:
                $error = false;
                break;
            case ECP_NO_SUCH_MACHINE:
                $error = 'No such machine exists.';
                break;
            case ECP_INVALID_COMMAND:
                $error = 'Invalid command.';
                break;
            case ECP_MISSING_PARAMETER:
                $error = 'Missing parameter.';
                break;
            case ECP_COULD_NOT_CONNECT:
                $error = 'Could not connect.';
                break;
            case ECP_COULD_NOT_RETRIEVE:
                $error = 'Could not retrieve the requested information.';
                break;
            case ECP_COMMAND_FAILED:
                $error = 'Command failed.';
                break;
            case ECP_RESOURCE_LOCKED:
                $error = 'Resource locked.';
                break;
            case ECP_INTERNAL_ERROR:
                $error = 'Internal error.';
                break;
            case ECP_UNKNOWN_PARAMETER:
                $error = 'Unknown parameter.';
                break;
            case ECP_RESOURCE_BUSY:
                $error = 'Resource busy.';
                break;
            case ECP_NAMING_CONFLICT:
                $error = 'Naming conflict.';
                break;
            case ECP_RECURSION_ERROR:
                $error = 'Recursion error.';
                break;
            default:
                $error = 'Unknown error.';
                break;
        }
        if($error)
            $error .= ' '. $arr_response['message'];
    }
    return $error;
}

4.8.2.2. Python

Here is an example of how to test a given HTTP response string for errors.

 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
#errcodes={
#    'SUCCESS'                   : 0,
#    'NO_SUCH_MACHINE'           : 1,
#    'INVALID_COMMAND'           : 2,
#    'MISSING_PARAMETER'         : 3,
#    'COULD_NOT_CONNECT'         : 4,
#    'COULD_NOT_RETRIEVE'        : 5,
#    'COMMAND_FAILED'            : 6,
#    'RESOURCE_LOCKED'           : 7,
#    'INTERNAL_ERROR'            : 8,
#    'UNKNOWN_PARAMETER'         : 9,
#    'RESOURCE_BUSY'             : 10,
#    'NAMING_CONFLICT'           : 11,
#    'RECURSION_ERROR'           : 12
#}

from json import loads

errcodes=[
 'Sucess.',
 'No such machine.',
 'Invalid command.',
 'Missing paramter.',
 'Could not connect.',
 'Could not retrieve.',
 'Command failed.',
 'Resource locked.',
 'Internal error.',
 'Unknown paramter.',
 'Resource busy.',
 'Naming conflic.',
 'Recursion error.'
]

#Returns the error or False on no error.
def ecp_check_error(body):
    try:
        #Make sure that the json object can be loaded
        json = loads(body)
    except:
        return 'Response could not be parsed.'
    else:
        #If there is no error, return False.
        if json['errno'] == 0:
            return False
        #If not then return the information from errno and the message
        else:
            return errcodes[json['errno']] + ' ' + json['message']

4.8.2.3. Java

Here is an example of how to test a given HTTP response string for errors. It is used in all examples

 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
import org.json.simple.JSONObject;
import org.json.simple.parser.*;

//Class will contain all error codes from "errno" fields
public class error_Handling {
    // constant values assigned to final integers accordingly
    public static final int SUCCESS = 0;
    public static final int NO_SUCH_MACHINE = 1;
    public static final int INVALID_COMMAND = 2;
    public static final int MISSING_PARAMETER = 3;
    public static final int COULD_NOT_CONNECT = 4;
    public static final int COULD_NOT_RETRIEVE = 5;
    public static final int COMMAND_FAILED = 6;
    public static final int RESOURCE_LOCKED = 7;
    public static final int INTERNAL_ERROR = 8;
    public static final int UNKNOWN_PARAMETER = 9;
    public static final int RESOURCE_BUSY = 10;
    public static final int NAMING_CONFLICT = 11;
    public static final int RECURSION_ERROR = 12;

    public void api_error(String nextLine) {
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(nextLine);
            int errObj = ((Number) json.get("errno")).intValue();
            switch (errObj) {
            case error_Handling.SUCCESS:
                System.out.println("Successful Connection Established");
                break;
            case error_Handling.NO_SUCH_MACHINE:
                System.out.println("Machine does not Exist");
                break;
            case error_Handling.INVALID_COMMAND:
                System.out.println("Invalid Command Entered");
                break;
            case error_Handling.MISSING_PARAMETER:
                System.out.println("A Parameter is Missing");
                break;
            case error_Handling.COULD_NOT_CONNECT:
                System.out.println("Could not Connect");
                break;
            case error_Handling.COULD_NOT_RETRIEVE:
                System.out.println("Could not Retrieve Information");
                break;
            case error_Handling.COMMAND_FAILED:
                System.out.println("Command Failed");
                break;
            case error_Handling.RESOURCE_LOCKED:
                System.out.println("the Resource is Locked");
                break;
            case error_Handling.INTERNAL_ERROR:
                System.out.println("Internal Error");
                break;
            case error_Handling.UNKNOWN_PARAMETER:
                System.out.println("Unknown Parameter Entered");
                break;
            case error_Handling.RESOURCE_BUSY:
                System.out.println("The Resource is Busy");
                break;
            case error_Handling.NAMING_CONFLICT:
                System.out.println("There is a Naming Conflict");
                break;
            case error_Handling.RECURSION_ERROR:
                System.out.println("There is a Naming Conflict");
                break;
            default:
                System.out.println("Unknown Error");
                break;
            }

        } catch (ParseException e) {

            e.printStackTrace();
        }
    }
}

4.9. About the Code examples

4.9.1. PHP

4.9.1.1. General Information

The examples in this manual work in PHP 4 and above because they use functions and not classes. They also use the cURL library. There are other methods to do the same thing, but this is the easiest to demonstrate the functionality of our API. The functions required for each example to work are linked to in the descriptions of the examples.

It is important to note that these examples use cookies stored in files, which may or may not be the desired behaviour. Please refer to the PHP documentation to find out how to store the cookies in memory instead if multiple users need to run the scripts at the same time.

4.9.1.2. Generic API Request Function

Throughout this manual, the following generic API request function is used to make the API requests.It is included with require(‘api_request.php’). Note that it uses the error handling function therefore both must be included for this function to work.

 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
<?php
//Basic function to make an API request. Returns an array if sucessful.
//Otherwise returns a string with an error message.
function api_request($url, $method, $data, $cookies_file){

    //Initialize the client object.
    $client = curl_init();

    //Do some basic client configuration.
    curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
    curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);

    //Specify the URL for the HTTP request
    curl_setopt($client, CURLOPT_URL, $url);
    
    //Set up the data to be sent depending on the method
    switch(strtolower($method)){
     
        case 'get':
        
            //Set up the GET request.
            curl_setopt($client, CURLOPT_HTTPGET, 1);
            //Add GET parameters if there are any
            if($data)
                curl_setopt($client, CURLOPT_URL, $url.'?'.$data);
            break;
            
        case 'post':
        
            //Set up the POST request
            curl_setopt($client, CURLOPT_POST, 1);
            curl_setopt($client, CURLOPT_POSTFIELDS, $data);
            break;
            
        case 'delete':
        
            //Set up the DELETE request
            curl_setopt($client, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
            
        case 'put':
        
            //The data has to be written to a file because CURL needs a file to 
            //"PUT"
            $tmp_file = tmpfile();
            fwrite($tmp_file, $data);
            //Move the pointer to the beginning of the file so that CURL can 
            //read it from the beginning
            fseek($tmp_file, 0);
        
            //Set up the request so the temp file will be read and uploaded
            curl_setopt($client, CURLOPT_PUT, 1);
            curl_setopt($client, CURLOPT_INFILE, $tmp_file);
            curl_setopt($client, CURLOPT_INFILESIZE, strlen($data));
            curl_setopt($client, CURLOPT_HTTPHEADER,
                array("Content-Type: application/x-www-form-urlencoded"));
            break;
    }
    
    //Execute the request
    $http_response = curl_exec($client);
    
    //Clean up the temp file if PUT was used
    if(strtolower($method) == 'put')
        fclose($tmp_file);
    
    //Verify that the call was sucessful.
    $http_error_code = curl_getinfo($client, CURLINFO_HTTP_CODE);
    if($http_error_code == 200){
    
        //Check if there was an internal error and get the error message
        $error = api_error($http_response);
        
        //Verify that the operation was sucessful
        if(!$error){
    
            //Return the json response parsed into an array
            $json_response = json_decode($http_response, true);
            
            curl_close($client);
            return $json_response;
        }
        else {
            curl_close($client);
            return $error;
        }
    }
    else{
        return "HTTP error code ".$http_error_code;
    }
}
?>

4.9.2. Python

4.9.2.1. General Information

The python examples use urllib2 and cookielib and work for Python 2. Other alternatives to urllib2 are urllib, httplib, httplib2, PycURL (good for those already familiar with cURL).

Please see the authentication examples first because it explains how cookies are handled in other examples.

4.9.3. Java

4.9.3.1. General Information

The examples in this manual work with built in Java libraries, and a downloaded library that can be downloaded from: http://code.google.com/p/json-simple/downloads/detail?name=json_simple-1.1.jar The functions that will be required for each example to work are linked to in the description of the examples.

4.9.3.2. Generic Client Class

The following class contains two functions that are used throughout all the examples. This class uses Cookie Manager Class Therefore it is important that both are included within the package for the examples to compile.

 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Client {

    public boolean initial_Login(CookieManager cm, String user_name,
            String pass_word) {
        boolean check = true;
        try {
            URL url = new URL(
                    "https://127.0.0.1/modules/hosting?user_name="
                            + user_name + "&password=" + pass_word
                            + "&login=Login");
            URLConnection conn = url.openConnection();
            conn.connect();
            HttpURLConnection httpConn = (HttpURLConnection) conn;

            int response_code = httpConn.getResponseCode();
            // will check for authentication by user
            if (response_code == 401) {
                // response = "Authentication Failed";
                check = false;
            } else if (response_code == 200) {
                // response = "Connected Successfully";
                System.out.println(" ");
                cm.storeCookies(conn);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return check;
    }

    public String connectURI(URL url, CookieManager cm, int count) {
        String info_Line = "";
        try {
            URLConnection conn2 = url.openConnection();
            // cookies are set for resource uri
            cm.setCookies(conn2);
            conn2.connect();
            // buffered reader that will read in the lines from the resource uri
            BufferedReader stream_in = new BufferedReader(
                    new InputStreamReader(conn2.getInputStream()));
            count++;
            for (int i = 0; i < count; i++) {
                info_Line = stream_in.readLine();
            }
            stream_in.close();
        } catch (IOException ioe) {
            System.out.println("URL entered is not correct");
            return null;
        }
        return info_Line;
    }

}

4.10. group – Group

Group functionality.

4.10.1. Resources

4.10.1.1. Group

class group.Group

This resource represents a method in which to create a new group.

Resource URI:

/rest/hosting/group/
PUT(groupname, displayname)

Create a new group by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • groupname – New group name.
  • displayname – New group display name.
  • quota – UUID of the quota that will be associated with the group.
Return type:

group.RepGroup

4.10.1.2. GroupUUID

class group.GroupUUID

This resource represens a specific group.

Resource URI:

/rest/hosting/group/<UUID>/
GET()

Retrieve the specified group by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target group.

Note

This resource requires read permission on both the group and the elastic_hosting extension module when using the HTTP GET method.

Return type:group.RepGroupUUID
POST(groupname, displayname, quota)

Update the specified group by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target group.

Note

This resource requires update permission on both the group and the elastic_hosting extension module when using the HTTP POST method.

Parameters:
  • groupname – The groupname to update the group with.
  • displayname – The display name to update the group with.
  • displayname – The quota (UUID) to update the group with.
Return type:

group.RepGroupUUID

4.10.1.3. GroupList

class group.GroupList

This resource represents a list of groups.

Resource URI:

/rest/hosting/group/list/
GET()

Retrieve a list of groups by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module and on each group that is found.

Return type:group.RepGroupList

4.10.2. Representations

4.10.2.1. RepGroup

class group.RepGroup

This is a representation of a group resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
group
This attribute represents the newly created group object and is a group.RepGroupUUID representation.

Representation:

{"errno":response.errno,
 "message":response.message,
 "group": group_obj}

4.10.2.2. RepGroupUUID

class group.RepGroupUUID

This is a representation of a group resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
group.uuid
This attribute represents the UUID of the group.
group.group_name
This attribute represents the groupname of the group.
group.display_name
This attribute represents the display name of the group.
group.created
This attribute represents the date and time the gropu was created in the format YYYY-MM-DD HH:MM:SS.
group.users
This attribute represents a list of the users who belong to this group listed by username.
group.quota
This attribute represents the quota for the group as a quota.RepQuotaUUID representation. Note that it is only returned using /rest/hosting/groups/list/ and not /rest/hosting/groups/<UUID>/

Representation:

{"errno": response.errno,
 "message": response.message,
 "group": {"uuid": group.uuid,
          "group_name": group.group_name,
          "display_name": group.display_name,
          "created": group.created,
          "users": group.users,
          "quota": quota}}

4.10.2.3. RepGroupList

class group.RepGroupList

This is a representation of a list of groups. This is a list of user.RepGroupUUID representations.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
groups
This attribute represents the list of group representations.

Representation

{"errno": response.errno,
 "message": response.message,
 "groups": [group1, group2]}

4.10.3. Examples

4.10.3.1. PHP

Here is an example of how to list all existing groups.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_groups = api_request($base_url.'/rest/hosting/group/list/', 'get',
        null, $cookies_file);
        
    //Make sure there was no error returned
    if(is_array($arr_groups)){
    
        if($arr_groups['groups']){
        
            //Display the groups
            echo "
            <h1>Groups:</h1><table>
            <tr>
            <td>UUID</td>
            <td>Name</td>
            <td>Display Name</td>
            <td>Created</td>
            <td>Users</td>
            <td>Quota UUID</td>
            </tr>";
            foreach ($arr_groups['groups'] as $group)
            {
                echo "
                <tr>
                <td>$group[uuid]</td>
                <td>$group[group_name]</td>
                <td>$group[display_name]</td>
                <td>$group[created]</td>
                <td>".implode(', ',$group['users'])."</td>
                <td>{$group['quota']['uuid']}</td>
                </tr>";
            }
            echo '</table>';
        }
        else{
            echo '<p>No groups available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_groups.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
?>

Here is an example of how to get information about a specific group.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Group to get details of
$uuid = '2a0041e3-d655-11de-ae3d-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/group/'.$uuid.'/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for group with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['group'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to udpate a group.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request_debug.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Group to update:
$uuid = '2181b142-217b-11df-bba9-000acd1901c5';
//New information:
$groupname = 'updated';
$displayname = 'The Updated Group';
$quota = 'f9b526de-1bf4-11df-b68b-000acd1901c5';

//Combine the data to create the POST string
$data = "groupname=$groupname&displayname=$displayname&quota=$quota";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/group/'.$uuid.'/', 
        'post', $data, $cookies_file, 'group');
    
    //Make sure there was no error returned
    if(is_array($response)){

        //Display the new information
        echo "<p>Updated group with UUID: $uuid</p>";
        echo '<ul>';
        foreach ($response['group'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.10.3.2. Python

Here is an example of how to list all existing groups.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/group/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the groups
        for group in json['groups']:
        
            #Output and remove the name from the dictionary
            print
            print '=========== ' + group['group_name'] + ' ==========='
            del(group['group_name'])
            
            #Output all information
            for key in group.keys():
                print key + ' = ' + str(group[key])
    else:
        #Output the error
        print error

4.10.3.3. Java

Here is an example of how to list all existing groups.

 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
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_group_list {
    // Following method will output all information in proper format
    public static void DisplayData(String group_List) {
        boolean check = true;
        int count = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(group_List);
            JSONArray group_obj = (JSONArray) json.get("groups");
            System.out.println(" ");
            System.out.println("Groups:");
            while (check) {
                try {
                    JSONObject group_items = (JSONObject) group_obj.get(count);
                    System.out.println(" ");
                    System.out.println((count + 1) + ")");
                    System.out.println("Display Name: "
                            + group_items.get("display_name"));
                    System.out.println("Group Name: "
                            + group_items.get("group_name"));
                    System.out.println("Date Created: "
                            + group_items.get("created"));
                    System.out.println("uuid: " + group_items.get("uuid"));
                    System.out.println("Users: " + group_items.get("users"));
                    JSONObject quota_info = (JSONObject) group_items
                            .get("quota");
                    if (quota_info != null) {
                        System.out.println("Quota: \"" + quota_info.get("name")
                                + "\"");
                    } else {
                        System.out.println("Quota: No quota exists");
                    }
                    count++;
                } catch (Exception e) {
                    check = false;
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/group/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to get information about a specific group.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_group_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String group_List) {
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(group_List);
            System.out.println(" ");
            System.out.println("Group:");
            try {
                JSONObject group_info = (JSONObject) json.get("group");
                System.out.println(" ");
                System.out.println("Display Name: "
                        + group_info.get("display_name"));
                System.out.println("Group Name: "
                        + group_info.get("group_name"));
                System.out
                        .println("Date Created: " + group_info.get("created"));
                System.out.println("uuid: " + group_info.get("uuid"));
                System.out.println("Users: " + group_info.get("users"));
            } catch (Exception e) {

                System.out.println("Group with specified uuid does not exist");
            }

        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "2a0041e3-d655-11de-ae3d-000acd1901c5";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/group/"
                + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }
}

4.11. htemplate – Hardware Template

Hardware template functionality.

4.11.1. Resources

4.11.1.1. Htemplate

class htemplate.Htemplate

This resource represents a method in which to create a new hardware template.

Resource URI:

/rest/hosting/htemplate/
PUT()

Create a new hardware template by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • name – New hardware template name.
  • arch – New hardware template architecture.
  • hypervisor – New hardware template hypervisor.
  • memory – New hardware template memory.
  • cpus – New hardware template cpus.
Return type:

htemplate.RepHtemplate

4.11.1.2. HtemplateUUID

class htemplate.HtemplateUUID

This resource represents a specific hardware template.

Resource URI:

/rest/hosting/htemplate/<UUID>/
GET()

Retrieve the specified hardware template by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target hardware template.

Note

This resource requires read permission on both the hardware template and the elastic_hosting extension module when using the HTTP GET method.

Return type:htemplate.RepHtemplateUUID
POST()

Update the specified hardware template by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target hardware template.

Note

This resource requires update permission on both the hardware template and the elastic_hosting extension module when using the HTTP POST method.

Parameters:
  • name – The name of the hardware template.
  • arch – The cpu architecture of the hardware template.
  • hypervisor – The hypervisor of the hardware template.
  • memory – The memory of the hardware template..
  • cpus – The number of cpus for the hardware template.
Return type:

htemplate.RepHtemplateUUID

DELETE()
Delete the specified hardware template by submitting an HTTP DELETE request. The UUID in the resource URI should be the UUID of the target hardware template.

4.11.1.3. HtemplateList

class htemplate.HtemplateList

This resource represents a list of hardware templates.

Resource URI:

/rest/hosting/htemplate/list/
GET()

Retrieve a list of hardware templates by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:htemplate.RepHtemplateList

4.11.2. Representations

4.11.2.1. RepHtemplate

class htemplate.RepHtemplate

This is a representation of a new hardware template that has been created.

Representation:

{"errno": response.errno,
 "message": response.message,
 "hardware": hardware}

4.11.2.2. RepHtemplateUUID

class htemplate.RepHtemplateUUID

This is a representation of a specific hardware template.

Representation:

{"errno": response.errno,
 "message": response.message,
 "hardware": {"uuid": hardware.uuid,
              "name": hardware.name,
              "arch": hardware.arch,
              "hypervisor_name": hardware.hvm,
              "memory": hardware.memory,
              "cpus": hardware.cpus}}

4.11.2.3. RepHtemplateList

class htemplate.RepHtemplateList

This is a representation of a list of hardware templates.

Representation:

{"errno": response.errno,
 "message": response.message,
 "templates": [htemplate1, htemplate2]}

4.11.3. Examples

4.11.3.1. PHP

Here is an example of how to list all available hardware templates.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $hardware = api_request($base_url.'/rest/hosting/htemplate/list/', 'get',
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($hardware)){
    
        if($hardware['templates']){
        
            //Display all returned hardware data.
            echo '<h1>Hardware templates:</h1>';
            echo '<ol>';
            foreach ($hardware['templates'] as $_hardware){
                 echo "<li>($_hardware[uuid]) ";
                 echo "$_hardware[name]: $_hardware[arch], ";
                 echo "$_hardware[memory] MB, $_hardware[cpus] CPU(s)</li>";
            }
            echo '</ol>';
        }
        else{
            echo '<p>No hardware templates available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$hardware.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get information for a specific hardware template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Hardware template to get details of
$uuid = 'bcaff710-2914-11de-836c-001a929face2';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/htemplate/'.$uuid.'/', 
        'get', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for hardware template with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['hardware'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to update a specific hardware template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Hardware template to update:
$uuid = '14c34419-0c34-11df-91fa-000acd1901c5';
//New information:
$name        = 'Really Small';
$arch        = 'i686';
$hypervisor  = 'kvm-hvm';
$memory      = '256';
$cpus        = '2';

//Combine the data to create the POST string
$data = "name=$name&arch=$arch&hypervisor=$hypervisor".
        "&memory=$memory&cpus=$cpus";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/htemplate/'.$uuid.'/', 
        'post', $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        //Display the new information
        echo "<p>Updated hardware template with UUID: $uuid</p>";
        echo '<ul>';
        foreach ($response['hardware'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to delete a specific hardware template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Hardware template to delete
$uuid = '110cccf0-0c79-11df-ba93-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $result = api_request($base_url.'/rest/hosting/htemplate/'.$uuid.'/', 
        'delete', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($result)){
    
        //The delete was sucessful.
        echo '<p>Sucessfully deleted hardware template with UUID: '.
            $uuid.'</p>';
    } 
    else{
         echo '<p>Error: '.$result.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to create a new hardware template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Information about the new hardware tamplate
$name        = 'Really Really Small';
$arch        = 'i686';
$hypervisor  = 'kvm-hvm';
$memory      = '128';
$cpus        = '1';

//Combine the data to create the PUT string
$data = "name=$name&arch=$arch&hypervisor=$hypervisor".
        "&memory=$memory&cpus=$cpus";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/htemplate/', 'put',
        $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        echo "<p>New hardware template created with UUID:".
             "{$response['hardware']['uuid']}</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.11.3.2. Python

Here is an example of how to list all available hardware templates.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/htemplate/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the hardware templates
        for template in json['templates']:
        
            #Output and remove the name from the dictionary
            print
            print '=========== ' + template['name'] + ' ==========='
            del(template['name'])
            
            #Output all information
            for key in template.keys():
                print key + ' = ' + str(template[key])
    else:
        #Output the error
        print error

Here is an example of how to get information for a specific hardware template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Hardware template to get information about
uuid = 'c2325bcf-14c1-11df-be3e-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
    
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/htemplate/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Show information about this template
        template = json['hardware']
        
        #Output and remove the name from the dictionary
        print '=========== ' + template['name'] + ' ==========='
        del(template['name'])
        
        #Output all information
        for key in template.keys():
            print key + ' = ' + str(template[key])
        
    else:
        #Output the error
        print error

Here is an example of how to update a specific hardware template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Hardware template to update
uuid = '3bb17342-11b1-11df-951e-000acd1901c5'
#New information about the hardware template
name = 'Python is Awesome!'
arch = 'i686'
cpus = '2'
hypervisor = 'xen-hvm'
memory = '513'
data = 'name='+name+'&arch='+arch+'&cpus='+cpus+\
       '&hypervisor='+hypervisor+'&memory='+memory

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a POST by default when providing data.
    req = Request(host + '/rest/hosting/htemplate/'+uuid+'/', data = data)
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Format the output nicely
        print 'Hardware template sucessfuly updated!'
        print
        
        #Show information about this template
        template = json['hardware']
        
        #Output and remove the name from the dictionary
        print '=========== ' + template['name'] + ' ==========='
        del(template['name'])
        
        #Output all information
        for key in template.keys():
            print key + ' = ' + str(template[key])
        
    else:
        #Output the error
        print error

Here is an example of how to delete a specific hardware template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Hardware template to delete
uuid = 'c4422c35-11c7-11df-86d7-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
    
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/htemplate/'+uuid+'/')
    req.get_method = lambda: 'DELETE'
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        print 'Hardware template sucessfuly deleted!'

    else:
        #Output the error
        print error

Here is an example of how to create a new hardware template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Information about the hardware template to be created
name = 'Custom Hardware Template'
arch = 'i686'
cpus = '1'
hypervisor = 'xen-hvm'
memory = '512'
data = 'name=' + name + '&arch=' + arch + '&cpus=' + cpus + \
       '&hypervisor=' + hypervisor + '&memory=' + memory

try:
    
    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a POST by default when providing data.
    req = Request(host + '/rest/hosting/htemplate/', data = data)
    req.get_method = lambda: 'PUT'
    #Send the request
    response = urlopen(req)
    
except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        print 'Hardware template sucessfuly created!'
        print
        
        #Show information about this template
        template = json['hardware']
        
        #Output and remove the name from the dictionary
        print '=========== ' + template['name'] + ' ==========='
        del(template['name'])
        
        #Output all information
        for key in template.keys():
            print key + ' = ' + str(template[key])
        
    else:
        #Output the error
        print error

4.11.3.3. Java

Here is an example of how to list all available hardware templates.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_htemplate_list {

    public static void DisplayData(String hdware_Line) {
        boolean check = true;
        int count = 0;
        JSONObject hardware_json;
        System.out.println(" ");
        System.out.println("Hardware Templates)");
        System.out.println(" ");
        while (check) {
            try {
                hardware_json = (JSONObject) new JSONParser()
                        .parse(hdware_Line);

                JSONArray hardware_obj = (JSONArray) hardware_json
                        .get("templates");
                JSONObject hardware_name = (JSONObject) hardware_obj.get(count);
                // Information will be displayed accordingly
                System.out.println(" ");
                System.out.print((count + 1) + ".");
                System.out.print("Size:" + hardware_name.get("name") + " ");
                System.out.println(":" + hardware_name.get("memory") + " Mb");
                System.out.println(hardware_name.get("uuid"));
                count++;
            } catch (Exception e) {
                check = false;
                break;
            }

        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String hardware_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/htemplate/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                hardware_Line = (user.connectURI(url, cm, count));
                if (hardware_Line != null) {
                    errorCheck.api_error(hardware_Line);
                    DisplayData(hardware_Line);
                    count++;
                }
            } while (hardware_Line != null);
        }

    }
}

Here is an example of how to get information for a specific hardware template.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_htemplate_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String hardware_Line, String uuid) {
        JSONObject hardware_json;
        System.out.println(" ");
        System.out.println("Hardware Template with UUID \"" + uuid + "\":");
        System.out.println(" ");
        try {
            hardware_json = (JSONObject) new JSONParser().parse(hardware_Line);
            // information will be displayed accordingly
            JSONObject hardware_info = (JSONObject) hardware_json
                    .get("hardware");
            System.out.println("Name: " + hardware_info.get("name"));
            System.out
                    .println("Memory: " + hardware_info.get("memory") + " MB");
            System.out.println("# of CPUS: " + hardware_info.get("cpus"));
        } catch (Exception e) {
            System.out.println("Display Error");
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "14c34419-0c34-11df-91fa-000acd1901c5";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/htemplate/"
                        + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line, uuid);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to update a specific hardware template.

 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_htemplate_uuid_post {
    // Following method will output all information in proper format

    public static void DisplayData(String hardware_Line, String uuid) {
        JSONObject hardware_json;
        System.out.println(" ");
        System.out.println("Changes made to Hardware Template with UUID \""
                + uuid + "\":");
        System.out.println(" ");
        try {
            hardware_json = (JSONObject) new JSONParser().parse(hardware_Line);
            // information will be displayed accordingly
            JSONObject hardware_info = (JSONObject) hardware_json
                    .get("hardware");
            System.out.println("Name: " + hardware_info.get("name"));
            System.out
                    .println("Memory: " + hardware_info.get("memory") + " MB");
            System.out.println("# of CPUS: " + hardware_info.get("cpus"));
        } catch (Exception e) {
            System.out.println("Display Error");
        }

    }

    public static void ControlVM(Client user, String uri, String query,
            String uuid, CookieManager cm) throws IOException {
        String trans_info_Line = "";
        int count = 0;
        error_Handling errorCheck = new error_Handling();
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/"
                    + uuid + "/");
            trans_info_Line = (user.connectURI(url, cm, count));
            errorCheck.api_error(trans_info_Line);
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                httpURLConnection.setRequestMethod("POST");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    DisplayData(nextline, uuid);
                }
                dis.close();
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorcheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String uuid = "7de343d7-1282-11df-973b-000acd1901c5";
        String uri = "rest/hosting/htemplate";
        String query = "name=admin_CHECK&arch=i686&hypervisor=kvm-hvm"
                + "&memory=128000&cpus=1";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            ControlVM(user, uri, query, uuid, cm);
        }

    }
}

Here is an example of how to delete a specific hardware template.

 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
import java.io.IOException;
import java.net.*;

public class rest_hosting_htemplate_uuid_delete {
    // Following method will output all information in proper format

    public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("DELETE Failed due to a " + responseCode
                            + " HTTP error");
                } else {
                    System.out
                            .println("Successfully Deleted Hardware Template with UUID: "
                                    + uuid);
                }
            } else {
                throw new IOException("Delete is not supported for ");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uuid = "01770f7a-1281-11df-802c-000acd1901c5";
        String uri = "rest/hosting/htemplate/" + uuid;
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            DeleteNetwork(uuid, uri, cm);
        }

    }
}
// }

Here is an example of how to create a new hardware template.

 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_htemplate_put {
    // Following method will output all information in proper format
    public static void DisplayData(String hdware_Line) {
        JSONObject hardware_json;
        System.out.println(" ");
        System.out.println("Hardware Template )");
        System.out.println(" ");
        try {
            System.out.println("CREATED");
            hardware_json = (JSONObject) new JSONParser().parse(hdware_Line);
            JSONObject hardware_name = (JSONObject) hardware_json
                    .get("hardware");
            // Information will be displayed accordingly
            System.out.print("Name: " + hardware_name.get("name") + " ");
            System.out
                    .println("Memory: " + hardware_name.get("memory") + " Mb");
            System.out.println("# of CPUS: " + hardware_name.get("cpus"));
            System.out.println("UUID: " + hardware_name.get("uuid"));
        } catch (Exception e) {
            System.out.println("Display Error");
        }

    }

    public static void CreateHTemp(String uri, String query, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            error_Handling errorCheck = new error_Handling();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                httpURLConnection.setRequestMethod("PUT");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    System.out.println(nextline);
                    errorCheck.api_error(nextline);
                    DisplayData(nextline);
                }
                dis.close();
            }
        } catch (RuntimeException exception) {
            System.out.println("Failed to Create Hardware Template");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorcheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String uri = "rest/hosting/htemplate";
        String query = "name=apii4_htemp&arch=i686&hypervisor=kvm-hvm"
                + "&memory=128&cpus=2";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            CreateHTemp(uri, query, cm);
        }

    }
}

4.12. interface – Interface

Network interface functionality.

4.12.1. Resources

4.12.1.1. Interface

class interface.Interface

This resource is for the creation of network interfaces.

Resource URI:

/rest/hosting/interface/
PUT(vm_uuid, network_uuid)
Add a network interface to a VM.

4.12.1.2. InterfaceUUID

class interface.InterfaceUUID

This resource represens a specific network interface.

Resource URI:

/rest/hosting/interface/<UUID>/
GET()

Retrieve the specified network interface by submitting an HTTP GET request. The UUID in the resource uri should be the uuid of the target interface.

Return type:interface.RepInterfaceUUID
POST(network_uuid)

Change the network that an interface is on with an HTTP POST request.

Return type:interface.RepInterfaceUUID
DELETE()
Remove a network interface.

4.12.1.3. InterfaceList

class interface.InterfaceList

This resource represents a list of network interfaces.

Resource URI:

/rest/hosting/interface/list/
GET()

Retrieve a list of network interfaces by submitting an HTTP GET request.

Return type:interface.RepInterfaceList

4.12.2. Representations

4.12.2.1. InterfaceUUID

class interface.RepInterfaceUUID

This is a representation of a network interface resource.

Representation:

{"uuid": interface.uuid,
 "network": network.uuid,
 "network_name": network.name,
 "mac": interface.mac,
 "ip": interface.ip}

4.12.2.2. RepInterfaceList

class interface.RepInterfaceList

This is a representation of a list of network interfaces. This is a list of network.RepInterfaceUUID representations.

Representation:

[interface1, interface2]

4.13. isofile – ISO Files

Viewing the available ISO files.

4.13.1. Resources

4.13.1.1. ISOFileList

class isofile.ISOFileList

This resource represents a list of all ISO files on the server.

Resource URI:

/rest/hosting/isofile/list/
GET()

Get a list of all ISO files available on the server.

Return type:isofile.RepISOFile

See also

vm

4.13.2. Representations

4.13.2.1. RepISOFile

class isofile.RepISOFile

This is a representation of an ISO file.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
file_names
This attribute represents the file names of the ISO files available.

Representation:

{"errno":response.errno,
 "message":response.message,
 "file_names": [file1, file2]}

4.14. log – Logs and Transactions

Logging and transactional functionality.

4.14.1. Resources

4.14.1.1. LogUUID

class log.LogUUID

This resource represents a specific action log.

Resource URI:

/rest/hosting/log/<UUID>/
DELETE()

Delete the specified action log by submitting an HTTP DELETE request. The UUID in the resource URI should be the uuid of the target action log.

Note

This resource requires delete permission on the elastic_hosting extension module.

Return type:log.RepLogUUID

4.14.1.2. LogList

class log.LogList

This resource represents a list of action logs and running transactions.

Resource URI:

/rest/hosting/log/list/
GET()

Retrieve a list of action logs and running transactions by submitting an HTTP GET request.

..note

This resource requires *read* permission on the *elastic_hosting* extension module.
Return type:log.RepLogList

4.14.2. Representations

4.14.2.1. RepLogUUID

class log.RepLogUUID

This is a representation of an action log.

date
This attribute represents the date of the log in a human readable format.
timestamp
This attribute represents the timestamp attribute of the log. This is the time at which the log was created.
error
This attribute represents the error attribute of the log. The value of this attribute will be true if the log is an error message.
message
This attribute represents the message attribute of the log. This message is the main content of the log.
uuid
This attribute represents the uuid attribute of the log.

Representation:

{"date": log.date,
 "timestamp": log.timestamp,
 "error": log.error,
 "uuid": log.uuid,
 "message": log.message}

4.14.2.2. RepLogList

class log.RepLogList

This is a representation of a list of action logs and running transactions.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
logs
This attribute represents the list of action log representations.
transactions
This attribute represents the list of transaction representations.

Representation:

{"errno": response.errno,
 "message": response.message,
 "logs": [log1, log2],
 "transactions": [transaction1, transaction2]}

4.14.3. Examples

4.14.3.1. PHP

Here is an example of how to monitor running transactions.

 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
<html>
<head>
    <title>Running Transactions</title>
    <meta http-equiv="refresh" content="5">
</head>
<body>
    <h1>Running Transactions:</h1>
     
    <?php
    require('authentication.php');
    require('error_handling.php');
    require('api_request.php');

    //Basic connection parameters.
    //IP address or host name of the primary ECP node (no trailing slash)
    $base_url = '127.0.0.1';
    //login info
    $username = 'customer';
    $password = 'password';
    
    //The cookie file used to store the session cookie.
    $cookies_file = 'cookies.txt';
    
    //Authenticate and check for success
    if (authenticate($base_url, $username, $password, $cookies_file)){
        
        //Use use the same cookie file for other API calls
        $transactions = api_request($base_url.'/rest/hosting/log/list/', 'get',
            null, $cookies_file);
        
        //Make sure there was no error returned
        if(is_array($transactions)){
        
            //Make sure there are transactions to display and display them.
            if($transactions['transactions']){
                echo '<h1>Running Transcations:</h1>';
                echo '<ul>';
                foreach ($transactions['transactions'] as $transaction){
                    echo '<li>'.$transaction['completion'].
                        '% '.$transaction['message'].'</li>';
                }
                echo '</ul>';
            }
            else{
                echo '<p>No pending transactions.</p>';
            }
        } 
        else{
             echo '<p>Error: '.$transactions.'</p>';
        }
    
    }
    else{
        echo "<p>Authentication failed.</p>";
    }
    ?>

</body>
</html>

Here is an example of how to list all logs for the current user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $logs = api_request($base_url.'/rest/hosting/log/list/', 'get',
        null, $cookies_file);
        
    //Make sure there was no error returned
    if(is_array($logs)){
    
        if($logs['logs']){
            
            //Display the logs
            echo '<h1>Logs:</h1>';
            echo '<ul>';
            foreach ($logs['logs'] as $log){
                echo '<li>('.$log['uuid'].') '.$log['date'].
                    ' -- '.$log['message'].'</li>';
            }
            echo '</ul>';
        }
        else{
            echo '<p>No logs available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$logs.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
?>

Here is an example of how to delete a specific log entry.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Log entry to delete
$uuid = 'c9127fc0-0bd9-11df-86c0-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $result = api_request($base_url.'/rest/hosting/log/'.$uuid.'/', 
        'delete', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($result)){
    
        //The delete was sucessful.
        echo '<p>Sucessfully deleted log with UUID: '.
            $uuid.'</p>';
    } 
    else{
         echo '<p>Error: '.$result.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.14.3.2. Python

Here is an example of how to monitor running transactions.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error
from time import sleep

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:

    #Monitor transactions until there are none left
    while True:
    
        #Clear the screen
        print '\n'*24,
    
        try:
            #Set up the request. It is a GET by default when not providing data.
            req = Request(host+'/rest/hosting/log/list/')
            #Send the request
            response = urlopen(req)
            
        except (HTTPError, URLError) as exception:
    
            #Handle http error codes and errors with the connection
            print exception
    
        else:
        
            #Read the response
            response_body = response.read()
            
            #Verify that there was no error
            error = ecp_check_error(response_body)
        
            if not error:
                
                #Format the output nicely
                #Parse the response into a dictionary
                json = loads(response_body)
                if json['transactions']:
                    
                    #Loop through the transactions
                    for transaction in json['transactions']:
                    
                        #Output info - consult the documentation for what other 
                        #information is available to be displayed
                        print str(transaction['completion']) + '% ' + \
                              str(transaction['message'])
                    
                else:
                
                    print 'No pending transactions.'
                    #Stop moinitoring transactions
                    break
                
                #Wait 20 seconds before checking again to not put stress on 
                #the server
                sleep(20)
                
            else:
                #Output the error
                print error
                #Stop moinitoring transactions
                break

Here is an example of how to list all logs for the current user.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/log/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the logs
        for log in json['logs']:
        
            #Somehow distinguish between errors and messages
            if log['error']:
                log['message'] = "!!! "+log['message']+" !!!"
            del(log['error'])
            #Output and remove the message from the dictionary.
            print
            print log['message']
            print '---'
            del(log['message'])
            
            #Output all information
            for key in log.keys():
                print key + ' = ' + str(log[key])
    else:
        #Output the error
        print error

Here is an example of how to delete a specific log entry.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Log to delete
uuid = 'c3e1055e-159a-11df-9349-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
    
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/log/'+uuid+'/')
    req.get_method = lambda: 'DELETE'
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        print 'Log sucessfuly deleted!'

    else:
        #Output the error
        print error

4.14.3.3. Java

Here is an example of how to monitor running transactions.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_log_list_transactions {
    // Function will display all the information accordingly
    public static boolean DisplayData(String transaction_Line) {
        JSONObject json;
        boolean trans_Check = true;
        try {

            json = (JSONObject) new JSONParser().parse(transaction_Line);
            JSONArray trans_obj = (JSONArray) json.get("transactions");
            if (trans_obj.size() > 0) {
                for (int i = 0; i < trans_obj.size(); i++) {
                    JSONObject transObjItem = (JSONObject) trans_obj.get(i);
                    // will output which machines are in transaction if any
                    // exist
                    System.out.println(" ");
                    System.out.println("Machine in queue " + (i + 1) + ")");
                    System.out.println("completion:"
                            + transObjItem.get("completion") + "%");
                    // Following will delay the output screen
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException ex) {

                    }

                }
            } else {
                System.out.println(" ");
                System.out.println("No Running Transactions");
                trans_Check = false;
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return trans_Check;
    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        boolean trans_Check = true;
        String authentication_message = "";
        String trans_info_Line = "";
        String username = "customer";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/log/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        // will connect to resource URI and retrieve information
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            trans_info_Line = (user.connectURI(url, cm, count));
            errorCheck.api_error(trans_info_Line);
            count = 0;
            do {
                trans_info_Line = (user.connectURI(url, cm, count));
                if (trans_info_Line != null) {
                    trans_Check = DisplayData(trans_info_Line);
                    count = 0;
                }
            } while (trans_info_Line != null && trans_Check != false);
        }
    }
}

Here is an example of how to delete a specific log entry.

 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
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class rest_hosting_log_uuid_delete {
    // Following method will output all information in proper format

    public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("DELETE Failed due to a " + responseCode
                            + " HTTP error");
                } else {
                    System.out.println("Successfully Deleted log with UUID: "
                            + uuid);
                }
            } else {
                throw new IOException("Delete is not supported for ");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uuid = "0f695e75-1297-11df-8b9f-000acd1901c5";
        String uri = "rest/hosting/log/" + uuid;
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            DeleteNetwork(uuid, uri, cm);
        }

    }
}

4.15. network – Network

Network functionality.

4.15.1. Resources

4.15.1.1. Network

class network.Network

This resource represents a method in which to create a new virtual network.

Resource URI:

/rest/hosting/network/
PUT(name, vlan_id)

Create a new virtual network by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • name – New virtual network name.
  • vlan_id – The vlan ID this network is associated with.
Return type:

network.RepNetwork

4.15.1.2. NetworkUUID

class network.NetworkUUID

This resource represents a specific virtual network.

Resource URI:

/rest/hosting/network/<UUID>/
GET()

Retrieve the specified virtual network by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target virtual network.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:network.RepNetworkUUID
POST(name, vlan_id)

Update the specified virtual network by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target virtual network.

Note

This resource requires read permission on the elastic_hosting extension module.

Parameters:
  • name – The virtual network name.
  • vlan_id – The vlan ID this network is associated with.
Return type:

network.RepNetworkUUID

DELETE()
Delete the specified virtual network by submitting an HTTP DELETE request. The UUID in the resource URI should be the UUID of the target virtual network.

4.15.1.3. NetworkList

class network.NetworkList

This resource represents a list of virtual networks.

Resource URI:

/rest/hosting/network/list/
GET()

Retrieve a list of virtual networks.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:RepNetworkList

4.15.2. Representations

4.15.2.1. RepNetwork

class network.RepNetwork
This is a representation of a newly created virtual network.
errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
network
This attribute represents the newly created network.

Representation:

{"errno": response.errno,
 "message": response.message,
 "network": network_obj}

4.15.2.2. RepNetworkUUID

class network.RepNetworkUUID
This is a representation of a specific virtual network.
errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
network.uuid
This attribute represents the UUID of the virtual network.
network.name
This attribute represents the name of the virtual network.
network.vlan_id
This attribute represents the vlan ID of the virtual network.

Representation:

{"errno": response.errno,
 "message": response.message,
 "network":{"uuid": network.uuid,
            "name": network.name,
            "vlan_id": network.vlan_id}}

4.15.2.3. RepNetworkList

class network.RepNetworkList

This is a representation of a list of virtual networks.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
networks
This attribute represents the list of virtual network representations.

Representation:

{"errno": response.errno,
 "message": response.message,
 "networks": [network_obj1, network_obj2]}

4.15.3. Examples

4.15.3.1. PHP

Here is an example of how to list all available virtual networks.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $networks = api_request($base_url.'/rest/hosting/network/list/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($networks)){
    
        if($networks['networks']){
        
            //Display all returned network data.
            echo '<h1>Networks:</h1>';
            echo '<ol>';
            foreach ($networks['networks'] as $network){
                 echo "<li>($network[uuid]) $network[name] (id: $network[vlan_id])</li>";
            }
            echo '</ol>';
        }
        else{
            echo '<p>No networks available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$networks.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get information about a specific virtual network.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Network to get details of
$uuid = 'ff5770a3-e136-11de-a1a2-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/network/'.$uuid.'/', 'get', 
        null, $cookies_file, 'network');
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for network with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to delete a specific virtual network.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Network to delete
$uuid = 'de796154-0c78-11df-9edd-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $result = api_request($base_url.'/rest/hosting/network/'.$uuid.'/', 
        'delete', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($result)){
    
        //The delete was sucessful.
        echo '<p>Sucessfully deleted network with UUID: '.
            $uuid.'</p>';
    } 
    else{
         echo '<p>Error: '.$result.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to create a new virtual network.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Information about the new network
$name = 'New Network';
//Used to identify packets on the network. It is important that the network 
//hardware is configured to allow traffic tagged with this VLAN ID
$vlan_id = 6;

//Combine the data to create the PUT string
$data = "name=$name&vlan_id=$vlan_id";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/network/', 'put',
        $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        echo "<p>New virtual network created with UUID: ". 
             "{$response['network']['uuid']}</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.15.3.2. Python

Here is an example of how to list all available virtual networks.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/network/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the networks
        for network in json['networks']:
        
            #Output and remove the name from the dictionary.
            print
            print "=========== " + network['name'] + " ==========="
            del(network['name'])
            
            #Output all information
            for key in network.keys():
                print key + ' = ' + str(network[key])
    else:
        #Output the error
        print error

Here is an example of how to get information about a specific virtual network.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Network to get information about
uuid = 'ff5770a3-e136-11de-a1a2-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/network/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Show information about this template
        network = json['network']
        
        #Output and remove the name from the dictionary
        print 
        print'Information about Network with UUID: ' + network['uuid'] 
        del(network['uuid'])
        
        #Output all information
        for key in network.keys():
            print key + ' = ' + str(network[key])
        
    else:
        #Output the error
        	print error

Here is an example of how to delete a specific virtual network.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Network to delete
uuid = '54903a70-11c2-11df-917f-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
    
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/network/'+uuid+'/')
    req.get_method = lambda: 'DELETE'
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        print 'Network sucessfuly deleted!'

    else:
        #Output the error
        print error

Here is an example of how to create a new virtual network.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Information about the virtual network to be created
name = 'New Network'
#Used to identify packets on the network. It is important that the network 
#hardware is configured to allow traffic tagged with this VLAN ID
vlan_id = '1'

data = 'name=' + name + '&vlan_id=' + vlan_id

try:
    
    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a POST by default when providing data.
    req = Request(host + '/rest/hosting/network/', data = data)
    req.get_method = lambda: 'PUT'
    #Send the request
    response = urlopen(req)
    
except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        print 'Virtual network sucessfuly created!'
        print
        
        #Show information about this network
        network = json['network']
        
        #Output and remove the name from the dictionary
        print '=========== ' + network['name'] + ' ==========='
        del(network['name'])
        
        #Output all information
        for key in network.keys():
            print key + ' = ' + str(network[key])
        
    else:
        #Output the error
        print error

4.15.3.3. Java

Here is an example of how to list all available virtual networks.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_network_list {

    public static void DisplayData(String network_Line) {
        boolean check = true;
        int count = 0;
        JSONObject network_json;
        System.out.println(" ");
        System.out.println("Networks)");
        System.out.println(" ");
        while (check) {
            try {
                network_json = (JSONObject) new JSONParser()
                        .parse(network_Line);
                // information will be displayed accordingly
                JSONArray network_obj = (JSONArray) network_json
                        .get("networks");
                JSONObject network_name = (JSONObject) network_obj.get(count);
                System.out.print((count + 1) + ".");
                System.out.println(network_name.get("name"));
                System.out.println(network_name.get("uuid"));
                count++;
            } catch (Exception e) {
                check = false;
                break;
            }

        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String network_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/network/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                network_Line = (user.connectURI(url, cm, count));
                if (network_Line != null) {
                    errorCheck.api_error(network_Line);
                    System.out.println(network_Line);
                    DisplayData(network_Line);
                    count++;
                }
            } while (network_Line != null);
        }
    }

}

Here is an example of how to get information about a specific virtual network.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_network_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String network_Line, String uuid) {
        JSONObject network_json;
        System.out.println(" ");
        System.out.println("Network with UUID \"" + uuid + "\":");
        System.out.println(" ");
        try {
            network_json = (JSONObject) new JSONParser().parse(network_Line);
            // information will be displayed accordingly
            JSONObject network_info = (JSONObject) network_json.get("network");
            System.out.println("Name: " + network_info.get("name"));
            System.out.println("UUID: " + network_info.get("uuid"));
            System.out.println("VLan ID: " + network_info.get("vlan_id"));
        } catch (Exception e) {
            System.out.println("Display Error");
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "4e9d7ba3-11c2-11df-9234-000acd1901c5";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/network/" + uuid
                        + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line, uuid);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to delete a specific virtual network.

 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
import java.io.IOException;
import java.net.*;

public class rest_hosting_network_uuid_delete {
    // Following method will output all information in proper format

    public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("DELETE Failed due to a " + responseCode
                            + " HTTP error");
                } else {
                    System.out
                            .println("Successfully Deleted network with UUID: "
                                    + uuid);
                }
            } else {
                throw new IOException("Delete is not supported for ");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uuid = "66f822d9-176-11df-8849-000acd1901c5";
        String uri = "rest/hosting/network/" + uuid;
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            DeleteNetwork(uuid, uri, cm);
        }

    }
}
// }

Here is an example of how to create a new virtual network.

 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_network_put {
    // Following method will output all information in proper format
    public static void DisplayData(String network_Line) {
        JSONObject network_json;
        boolean exists = true;
        try {
            network_json = (JSONObject) new JSONParser().parse(network_Line);
            System.out.println(" ");
            int errObj = ((Number) network_json.get("errno")).intValue();
            if (errObj != 0) {
                System.out.println("Failed to Create Network");
                System.out.println(network_json.get("message"));
                exists = false;
            }
            while (exists) {
                try {
                    System.out.println("Network )");
                    System.out.println(" ");
                    System.out.println("CREATED");
                    JSONObject network_name = (JSONObject) network_json
                            .get("hardware");
                    // Information will be displayed accordingly
                    System.out.print("Name: " + network_name.get("name"));
                    System.out.println("vlan_id: "
                            + network_name.get("vlan_id"));
                    System.out.println("UUID: " + network_name.get("uuid"));
                } catch (Exception e) {
                    System.out.println("Display Error");
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void CreateVM(String uri, String query, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                httpURLConnection.setRequestMethod("PUT");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    System.out.println(nextline);
                    DisplayData(nextline);
                }
                dis.close();
                // System.out.println("Great Success");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uri = "rest/hosting/network";
        String query = "name=test6&vlan_id=5";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            CreateVM(uri, query, cm);
        }

    }
}

4.16. ptemplate – Package Template

Package template functionality.

4.16.1. Resources

4.16.1.1. PtemplateUUID

class ptemplate.PtemplateUUID

This resource represens a specific package template.

Resource URI:

/rest/hosting/ptemplate/<UUID>/
GET()

Retrieve the specified package template by submitting an HTTP GET request. The UUID in the resource uri should be the uuid of the target package template.

Note

This resource requires read permission on both the package template and the elastic_hosting extension module when using the HTTP GET method.

Return type:ptemplate.RepPtemplateUUID

4.16.1.2. PtemplateList

class ptemplate.PtemplateList

This resource represents a list of package templates.

Resource URI:

/rest/hosting/ptemplate/list/
GET()

Retrieve a list of package templates by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:ptemplate.RepPtemplateList

4.16.2. Representations

4.16.2.1. RepPtemplateUUID

class ptemplate.RepPtemplateUUID

This is a representation of a package template resource.

Representation:

{"uuid": ptemplate.uuid,
 "name": ptemplate.name,
 "storage": ptemplate.storage,
 "description": ptemplate.description,
 "os": ptemplate.os}

4.16.2.2. RepPtemplateList

class ptemplate.RepPtemplateList

This is a representation of a list of package templates. This is a list of ptemplate.RepPtemplateUUID representations.

Representation:

[ptemplate1, ptemplate2]

4.16.3. Examples

4.16.3.1. PHP

Here is an example of how to list all available package templates.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $packages = api_request($base_url.'/rest/hosting/ptemplate/list/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($packages)){
    
        if($packages['packages']){
        
            //Display all returned package (appliance) data.
            echo '<h1>Appliances:</h1>';
            echo '<ol>';
            foreach ($packages['packages'] as $package){
                echo "<li>($package[uuid]) $package[name]: $package[description]</li>";
            }
            echo '</ol>';
        }
        else{
            echo '<p>No networks available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$packages.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get the details for a specific package template.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Appliance (package template) to get details of
$uuid = '5d407a68-c76c-11de-86e5-000475cb7577';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/ptemplate/'.$uuid.'/', 
        'get', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for appliance with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['package'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.16.3.2. Python

Here is an example of how to list all available package templates.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/ptemplate/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the package templates
        for template in json['packages']:
        
            #Output and remove the name from the dictionary
            print
            print '=========== ' + template['name'] + ' ==========='
            del(template['name'])
            
            #Output all information
            for key in template.keys():
                print key + ' = ' + str(template[key])
    else:
        #Output the error
        print error

Here is an example of how to get the details for a specific package template.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Appliance (package template) to get information about
uuid = 'ea64e966-e13f-11de-9843-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/ptemplate/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Show information about this template
        template = json['package']
        
        #Output and remove the name from the dictionary
        print 
        print 'Information about Appliance with UUID: ' + template['uuid'] 
        del(template['uuid'])
        
        #Output all information
        for key in template.keys():
            print key + ' = ' + str(template[key])
        
    else:
        #Output the error
        	print error

4.16.3.3. Java

Here is an example of how to list all available package templates.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_ptemplate_list {

    public static void DisplayData(String package_Line) {
        boolean check = true;
        int count = 0;
        JSONObject package_json;
        System.out.println(" ");
        System.out.println("Appliances)");
        System.out.println(" ");
        while (check) {
            try {
                package_json = (JSONObject) new JSONParser()
                        .parse(package_Line);
                JSONArray package_obj = (JSONArray) package_json
                        .get("packages");
                JSONObject pack_name = (JSONObject) package_obj.get(count);
                // Information will be displayed accordingly
                System.out.print((count + 1) + ".");
                System.out.print("Name:" + pack_name.get("name") + " ");
                System.out.print("....OS:" + pack_name.get("os") + " ");
                System.out.print("....Description:"
                        + ((String) pack_name.get("description")).replaceAll(
                                "\n", " ") + " ");
                System.out.print("....Storage:" + pack_name.get("storage")
                        + " ");
                System.out.print("....UUID:" + pack_name.get("uuid") + " ");
                System.out.println(" ");
                count++;

            } catch (Exception e) {
                check = false;
                break;
            }

        }
    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String package_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/ptemplate/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                package_Line = (user.connectURI(url, cm, count));
                if (package_Line != null) {
                    errorCheck.api_error(package_Line);
                    DisplayData(package_Line);
                    count++;
                }
            } while (package_Line != null);
        }

    }
}

Here is an example of how to get the details for a specific package template.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class rest_hosting_ptemplate_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String package_Line, String uuid) {
        JSONObject package_json;
        System.out.println(" ");
        System.out.println("Appliance with UUID \"" + uuid + "\":");
        System.out.println(" ");
        try {
            package_json = (JSONObject) new JSONParser().parse(package_Line);
            JSONObject pack_name = (JSONObject) package_json.get("package");
            // Information will be displayed accordingly
            System.out.print("Name:" + pack_name.get("name") + " ");
            System.out.print("....OS:" + pack_name.get("os") + " ");
            System.out.print("....Description:"
                    + ((String) pack_name.get("description")).replaceAll("\n",
                            " ") + " ");
            System.out.print("....Storage:" + pack_name.get("storage") + " ");
            System.out.print("....UUID:" + pack_name.get("uuid") + " ");
            System.out.println(" ");
        } catch (Exception e) {
            System.out.println("Display Error");
        }
    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "74e70ff3-0124-11df-8483-000acd1901c5";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/ptemplate/"
                        + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line, uuid);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

4.17. quota – Resource Quota

Virtual machine resource quota functionality.

4.17.1. Resources

4.17.1.1. Quota

class quota.Quota

This resource represents a method in which to create a new quota.

Resource URI:

/rest/hosting/quota/
PUT(name, max_vms, max_cpus, max_memory, max_storage)

Create a new quota by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • name – The name of the new quota.
  • max_vms – The maximum number of virtual machines allowed by the quota.
  • max_cpus – The maximum number of virtual cpus allowed by the quota.
  • max_memory – The maximum amount of memory allowed by the quota.
  • max_storage – The maximum amount storage allowed by the quota.
Return type:

quota.RepQuota

4.17.1.2. QuotaUUID

class quota.QuotaUUID

This resource represens a specific virtual machine resource quota.

Resource URI:

/rest/hosting/quota/<UUID>/
GET()

Retrieve the specified virtual machine resource quota by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target quota.

Note

This resource requires read permission on both the quota and the elastic_hosting extension module when using the HTTP GET method.

Return type:quota.RepQuotaUUID
POST(name, max_vms, max_cpus, max_memory, max_storage)

Update the specified virtual machine resource quota by submitting an HTTP POST request. The UUID in the resource uri should be the uuid of the target quota.

Note

This resource requires update permission on both the quota and the elastic_hosting extension module when using the HTTP POST method.

Parameters:
  • name – The name of the new quota.
  • max_vms – The maximum number of virtual machines allowed by the quota.
  • max_cpus – The maximum number of virtual cpus allowed by the quota.
  • max_memory – The maximum amount of memory allowed by the quota.
  • max_storage – The maximum amount storage allowed by the quota.
Return type:

quota.RepQuotaUUID

DELETE()

Delete the specified virtual machine resource quota by submitting an HTTP DELETE request. The UUID in the resource URI should be the UUID of the target quota.

Note

This resource requires delete permission on both the quota and the elastic_hosting extension module when using the HTTP DELETE method.

4.17.1.3. QuotaGroupUUID

class quota.QuotaGroupUUID

This resource represents a specific group quota.

Resource URI:

/rest/hosting/quota/group/<UUID>/
GET()

Retrieve the specified virtual machine resource quota by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target group.

Note

This resource requires read permission on both the quota and the elastic_hosting extension module when using the HTTP GET method.

Return type:quota.RepQuotaUUID
POST(quota)

Update the specified group by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target group.

Note

This resource requires update permission on both the quota and the elastic_hosting extension module when using the HTTP POST method.

Parameter:quota – The new quota for the target group.
Return type:quota.RepQuotaUUID

4.17.1.4. QuotaList

class quota.QuotaList

This resource represents a list of virtual machine resource quotas.

Resource URI:

/rest/hosting/quota/list/
GET()

Retrieve a list of virtual machine resource quotas by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module and on each virtual machine resource quota that is found.

Return type:quota.RepQuotaList

4.17.2. Representations

4.17.2.1. RepQuota

class quota.RepQuota

This is a representation of a new quota that is been created.

Representation:

{"errno" response.errno,
 "message": response.message,
 "quota": quota}

4.17.2.2. RepQuotaUUID

class quota.RepQuotaUUID

This is a representation of a quota resource.

Representation:

{"errno": response.errno,
 "message": response.message,
 "quota": {"uuid": quota.uuid,
           "name": quota.name,
           "max_vms": quota.vms,
           "max_cpus": quota.cpus,
           "max_memory": quota.max_memory,
           "max_storage": quota.max_storage}}

4.17.2.3. RepQuotaList

class quota.RepQuotaList

This is a representation of a list of virtual machine resource quotas. This is a list of quota.RepQuotaUUID representations.

Representation

{"errno": response.errno,
 "message": response.message,
 "quotas": [quota1, quota2]}

4.17.3. Examples

4.17.3.1. PHP

Here is an example of how to list all available quotas.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_quotas = api_request($base_url.'/rest/hosting/quota/list/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_quotas)){
    
        if($arr_quotas['quotas']){
        
            //Display all returned quotas.
            echo "
            <h1>Quotas:</h1><table>
            <tr>
            <td>UUID</td>
            <td>Name</td>
            <td>VMs</td>
            <td>CPUs</td>
            <td>Memory</td>
            <td>Storage</td>
            </tr>";
            foreach ($arr_quotas['quotas'] as $quota){
                echo "
                <tr>
                <td>$quota[uuid]</td>
                <td>$quota[name]</td>
                <td>$quota[max_vms]</td>
                <td>$quota[max_cpus]</td>
                <td>$quota[max_memory]</td>
                <td>$quota[max_storage]</td>
                </tr>";
            }
            echo '</table>';
        }
        else{
            echo '<p>No quotas available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_quotas.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get information about a specific quota.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Quota to get details of
$uuid = '29ff6978-d655-11de-8904-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/quota/'.$uuid.'/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for quota with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['quota'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to delete a specific quota.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Quota to delete
$uuid = 'fd91ba6b-0b85-11df-bd65-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $result = api_request($base_url.'/rest/hosting/quota/'.$uuid.'/', 
        'delete', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($result)){
    
        //The delete was sucessful.
        echo '<p>Sucessfully deleted quota with UUID: '.
            $uuid.'</p>';
    } 
    else{
         echo '<p>Error: '.$result.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to create a new quota.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Information about the new quota
$name = 'Custom Quota';
$max_vms = 10;
$max_cpus = 15;
$max_memory = 25*1024;//MB
$max_storage = 300*1024;//MB

//Combine the data to create the PUT string
$data = "name=$name&max_vms=$max_vms&max_cpus=$max_cpus".
    "&max_memory=$max_memory&max_storage=$max_storage";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/quota/', 'put',
        $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        echo "<p>New quota created with UUID: {$response['quota']['uuid']}</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to check what the quota for a group is.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Find out the quota for group with this uuid:
$uuid = '28ce4a1c-0088-11df-a8ef-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/quota/group/'.$uuid.'/', 
        'get', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details of the quota for group with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['quota'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to change the quota for a group.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Group to update:
$uuid = '28ce4a1c-0088-11df-a8ef-000acd1901c5';
//Set this quota:
$quota = 'bb8baec5-0087-11df-95a3-000acd1901c5';

//Combine the data to create the POST string
$data = "quota=$quota";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/quota/group/'.$uuid.'/', 
        'post', $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        //Display the new information
        echo "<p>Changed quota of group with UUID: $uuid</p>";
        echo '<ul>';
        foreach ($response['quota'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.17.3.2. Python

Here is an example of how to list all available quotas.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/quota/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the quotas
        for quota in json['quotas']:
        
            #Output and remove the name from the dictionary.
            print
            print "=========== " + quota['name'] + " ==========="
            del(quota['name'])
            
            #Output all information
            for key in quota.keys():
                print key + ' = ' + str(quota[key])
    else:
        #Output the error
        print error

Here is an example of how to get information about a specific quota.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#UUID of Quota to get information about
uuid = 'bb8baec5-0087-11df-95a3-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/quota/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Show information about this template
        quota = json['quota']
        
        #Output and remove the name from the dictionary
        print 
        print 'Information about Quota with UUID: '+ quota['uuid'] 
        del(quota['uuid'])
		
        #Output all information
        for key in quota.keys():
            print key + ' = ' + str(quota[key])
        
    else:
        #Output the error
        	print error

Here is an example of how to delete a specific quota.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#Quota to delete
uuid = '7fce172b-172b-11df-ae5f-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
    
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/quota/'+uuid+'/')
    req.get_method = lambda: 'DELETE'
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        print 'Quota sucessfuly deleted!'

    else:
        #Output the error
        print error

Here is an example of how to create a new quota.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/quota/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the quotas
        for quota in json['quotas']:
        
            #Output and remove the name from the dictionary.
            print
            print "=========== " + quota['name'] + " ==========="
            del(quota['name'])
            
            #Output all information
            for key in quota.keys():
                print key + ' = ' + str(quota[key])
    else:
        #Output the error
        print error

4.17.3.3. Java

Here is an example of how to list all available quotas.

 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
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_quota_list {
    // Following method will output all information in proper format
    public static void DisplayData(String quota_List) {
        boolean check = true;
        int count = 0;
        int storage_GB = 0;
        int memory_GB = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(quota_List);
            JSONArray quota_obj = (JSONArray) json.get("quotas");
            System.out.println(" ");
            System.out.println("Quotas:");
            while (check) {
                try {
                    JSONObject quota_items = (JSONObject) quota_obj.get(count);
                    storage_GB = (((Number) quota_items.get("max_storage"))
                            .intValue()) / 1000;
                    memory_GB = (((Number) quota_items.get("max_memory"))
                            .intValue()) / 1000;
                    System.out.println(" ");
                    System.out.println((count + 1) + ")");
                    System.out.println("Name: " + quota_items.get("name"));
                    System.out.println("Maximum # of Virtual Machines: "
                            + quota_items.get("max_vms"));
                    System.out.println("Maximum Amount of Storage: "
                            + storage_GB + " GB");
                    System.out.println("uuid: " + quota_items.get("uuid"));
                    System.out.println("Maximum Amount of memory: " + memory_GB
                            + " GB");
                    System.out.println("Maximum # of CPUs: "
                            + quota_items.get("max_cpus"));
                    count++;
                } catch (Exception e) {
                    check = false;
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/quota/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to get information about a specific quota.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_quota_uuid_get {
	// Following method will output all information in proper format
	public static void DisplayData(String quota_Called) {
		int storage_GB = 0;
		int memory_GB = 0;
		JSONObject json;
		try {
			json = (JSONObject) new JSONParser().parse(quota_Called);
			System.out.println(" ");
			System.out.println("Quota:");
			try {
				JSONObject quota_info = (JSONObject) json.get("quota");
				storage_GB = (((Number) quota_info.get("max_storage"))
						.intValue()) / 1000;
				memory_GB = (((Number) quota_info.get("max_memory")).intValue()) / 1000;
				System.out.println("	Name: " + quota_info.get("name"));
				System.out.println("	Maximum # of Virtual Machines: "
						+ quota_info.get("max_vms"));
				System.out.println("	Maximum Amount of Storage: " + storage_GB
						+ " GB");
				System.out.println("	Maximum Amount of memory: " + memory_GB
						+ " GB");
				System.out.println("	Maximum # of CPUs: "
						+ quota_info.get("max_cpus"));
			} catch (Exception e) {

				System.out
						.println("A field that was called does not exist or the "
								+ "quota with the specified uuid does not exist");
			}

		} catch (ParseException e) {

			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws MalformedURLException {
		Client user = new Client();
		CookieManager cm = new CookieManager();
		error_Handling errorCheck = new error_Handling();
		boolean check;
		String username = "admin";
		String password = "password";
		String authentication_message = "";
		String info_Line = "";
		String uuid = "29ff6978-d655-11de-8904-000acd1901c5";
		int count = 0;
		URL url = new URL("https://127.0.0.1/rest/hosting/quota/"
				+ uuid + "/");
		check = user.initial_Login(cm, username, password);
		System.out.println(authentication_message);
		if (check == false) {
			System.out.println("Authentication Failed");
		} else {
			do {
				// will connect to URL and call display method to output all the
				// info
				info_Line = (user.connectURI(url, cm, count));
				if (info_Line != null) {
					errorCheck.api_error(info_Line);
					DisplayData(info_Line);
					count++;
				}
			} while (info_Line != null);
		}
	}
}

Here is an example of how to delete a specific quota.

 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
import java.io.IOException;
import java.net.*;

public class rest_hosting_quota_uuid_delete {
    // Following method will output all information in proper format

    public static void DeleteQuota(String uuid, String uri, CookieManager cm)
            throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/"
                    + uuid + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("DELETE Failed due to a " + responseCode
                            + " HTTP error");
                } else {
                    System.out.println("Successfully Deleted quota with UUID: "
                            + uuid);
                }
            } else {
                throw new IOException("Delete is not supported for ");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uuid = "dfe93166-11b1-11df-bfef-000acd1901c5";
        String uri = "rest/hosting/quota";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            DeleteQuota(uuid, uri, cm);
        }

    }
}

Here is an example of how to create a new quota.

  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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_quota_uuid_put {
    // Following method will output all information in proper format
    public static void DisplayData(String quota_Called) {
        int storage_GB = 0;
        int memory_GB = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(quota_Called);
            System.out.println(" ");
            System.out.println("Quota:");
            try {
                JSONObject quota_info = (JSONObject) json.get("quota");
                storage_GB = (((Number) quota_info.get("max_storage"))
                        .intValue()) / 1000;
                memory_GB = (((Number) quota_info.get("max_memory")).intValue()) / 1000;
                System.out.println("    Name: " + quota_info.get("name"));
                System.out.println("    Maximum # of Virtual Machines: "
                        + quota_info.get("max_vms"));
                System.out.println("    Maximum Amount of Storage: " + storage_GB
                        + " GB");
                System.out.println("    Maximum Amount of memory: " + memory_GB
                        + " GB");
                System.out.println("    Maximum # of CPUs: "
                        + quota_info.get("max_cpus"));
            } catch (Exception e) {

                System.out
                        .println("A field that was called does not exist or the "
                                + "quota with the specified uuid does not exist");
            }

        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void CreateQuota(String uri, String query, CookieManager cm)
            throws IOException {
        error_Handling errorCheck = new error_Handling();
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestMethod("PUT");
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    errorCheck.api_error(nextline);
                    DisplayData(nextline);
                }
                dis.close();
                System.out.println(" ");
                System.out.println("Quota Successfully Created");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "admin";
        String password = "password";
        String uri = "rest/hosting/quota";
        String query = "name=TestQuota4&max_vms=10&max_cpus=30&max_memory=160000&max_storage=120000";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            CreateQuota(uri, query, cm);
        }

    }
}

4.18. tag – Tagging

Virtual machine tagging functionality.

4.18.1. Resources

4.18.1.1. Tag

class tag.Tag

This resource represents a method in which to create a new set of tags for a specific VM.

Resource URI::

/rest/hosting/vm/<UUID>/tag/
PUT(tag)

Create a new set of tags for a virtual machine by submitting an HTTP PUT request. The tag parameter is a comma-separated list of tag names. The UUID in the resource URI should be the UUID of the target virtual machine.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameter:tag – The comma-separated list of tags to create.
Return type:tag.RepTag

See also

vm

4.18.1.2. TagName

class tag.TagName

This resource represents a specific tag for a target virtual machine referenced by tag name.

Resource URI::

/rest/hosting/vm/<UUID>/tag/<NAME>/
DELETE()

Delete the specified tag from the target virtual machine. The NAME in the resource URI should be the name of the tag to delete. The UUID in the resource URI should be the UUID of the target virtual machine.

Note

This resource requires create permission on the elastic_hosting extension module.

Return type:tag.RepTagList

See also

vm

4.18.1.3. TagList

class tag.TagList

This class represents a list of tags. Repending on the resource URI, this can either be a list of all VM tags, or a list of tags belonging to a particular virtual machine.

Resource URI::

/rest/hosting/vm/tag/list/
/rest/hosting/vm/<UUID>/tag/list/
GET()

Retrieve a list of virtual machine tags.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:tag.RepTagList

4.18.2. Representations

4.18.2.1. RepTag

class tag.RepTag

This is a representation of a set of tags that have just been created.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
tags
This attribute represents the list of tags that have been created.

Representation:

{"errno":response.errno,
 "message":response.message,
 "tags": [tag1, tag2]}

4.18.2.2. RepTagList

class tag.RepTagList

This is a representation of a set of tags.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
tags
This attribute represents the list of tag name strings.

Representation:

{"errno":response.errno,
 "message":response.message,
 "tags": [tag1, tag2]}

4.18.3. Examples

4.18.3.1. PHP

Here is an example of how to view all tags for the current user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request_debug.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_tags = api_request($base_url.'/rest/hosting/vm/tag/list/', 'get', null, 
        $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_tags)){

        if($arr_tags['tags']){
        
            echo "Tags: ".implode(', ', $arr_tags['tags']);
            
        }
        else{
            echo '<p>No tags created.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_tags.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to view all tags for a specific VM.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Virtual machine UUID
$uuid = 'd3ee2bfa-0dd1-11df-890f-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_tags = api_request($base_url.'/rest/hosting/vm/'.$uuid.'/tag/list/', 
        'get', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_tags)){

        if($arr_tags['tags']){
        
            echo "Tags: ".implode(', ', $arr_tags['tags']);
            
        }
        else{
            echo '<p>No tags for this VM.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_tags.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to add a tag or a comma separated list of tags to a virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request_debug.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Virtual machine UUID
$uuid = '519851ee-1038-11df-94e4-000acd1901c5';
$tag = 'test2'; //can be a comma separated list

$data = "tag=$tag";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_tags = api_request($base_url.'/rest/hosting/vm/'.$uuid.'/tag/', 'put', 
        $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_tags)){

        if($arr_tags['tags']){
        
            echo "Tags added sucessfully. Current tags: ".
                implode(', ', $arr_tags['tags']);
            
        }
        else{
            echo '<p>No tags for this VM.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_tags.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to remove a tag from a virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request_debug.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//VM for which to delete a tag
$uuid = 'cf5827f0-10ea-11df-a7ad-000acd1901c5';
//The name of the tag
$tag = 'new';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $result = api_request($base_url.'/rest/hosting/vm/'.$uuid.'/tag/'.$tag.'/', 
        'delete', null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($result)){
    
        //The delete was sucessful.
        echo '<p>Sucessfully deleted tag for virtual machine with UUID: '.
            $uuid.'Current tags: '.implode(', ', $result['tags']);
    } 
    else{
         echo '<p>Error: '.$result.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.18.3.2. Python

Here is an example of how to view all tags for the current user.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/vm/tag/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the tags
        for tag in json['tags']:
        
            #Output each tag on a new line
            print "- "+tag
    else:
        #Output the error
        print error

Here is an example of how to view all tags for a specific VM.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

#The VM for which we're checking the tags
uuid = 'fa87dc66-1353-11df-840e-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/vm/'+ uuid +'/tag/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        
        #Loop through the tags
        for tag in json['tags']:
        
            #Output each tag on a new line
            print "- "+tag
    else:
        #Output the error
        print error

Here is an example of how to add a tag or a comma separated list of tags to a virtual machine.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

#Information about the virtual machine to be tagged
uuid = 'fa87dc66-1353-11df-840e-000acd1901c5'
tag = 'tag'; #can be a comma separated list

data = 'tag=' + tag
       
try:
    
    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a POST by default when providing data.
    req = Request(host + '/rest/hosting/vm/' + uuid + '/tag/', data = data)
    req.get_method = lambda: 'PUT'
    #Send the request
    response = urlopen(req)
    
except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        print 'Virtual Machine sucessfuly tagged!'
        print
        print 'Current tags: '
        
        #Loop through the tags
        for tag in json['tags']:
        
            #Output each tag on a new line
            print "- "+tag
        
    else:
        #Output the error
        print error

4.18.3.3. Java

Here is an example of how to view all tags for the current user.

 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
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_vm_tag_list {
    // Following method will output all information in proper format
    public static void DisplayData(String tag_List) {
        boolean check = true;
        int count = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(tag_List);
            JSONArray tag_obj = (JSONArray) json.get("tags");
            System.out.println(" ");
            System.out.println("Tags:");
            while (check) {
                try {
                    if (tag_obj != null) {
                        System.out.println(" -" + tag_obj.get(count));
                    }
                    count++;
                } catch (Exception e) {
                    check = false;
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "customer";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/vm/tag/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to view all tags for a specific VM.

 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
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_vm_uuid_tag_list {
    // Following method will output all information in proper format
    public static void DisplayData(String tag_List, String uuid) {
        boolean check = true;
        int count = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(tag_List);
            JSONArray tag_obj = (JSONArray) json.get("tags");
            System.out.println(" ");
            System.out.println("Tags for Machine with UUID \"" + uuid + "\":");
            while (check) {
                try {
                    if (tag_obj != null) {
                        System.out.println(" -" + tag_obj.get(count));
                    }
                    count++;
                } catch (Exception e) {
                    check = false;
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "customer";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "1809404a-12cf-11df-8e89-000acd1901c5";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/vm/"
                + uuid + "/tag/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line, uuid);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to add a tag or a comma separated list of tags to a virtual machine.

 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
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_vm_uuid_tag_put {
    // Following method will output all information in proper format
    public static void DisplayData(String vm_tag, String uuid) {
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(vm_tag);
            int errObj = ((Number) json.get("errno")).intValue();
            if (errObj != 0) {
                System.out.println(json.get("message"));
            } else {
                System.out
                        .println("Successfully added tags to machine with UUID \""
                                + uuid + "\"");
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }
    }

    public static void CreateQuota(String uri, String uuid, String query,
            CookieManager cm) throws IOException {
        try {
            error_Handling errorCheck = new error_Handling();
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                httpURLConnection.setRequestMethod("PUT");
                DataOutputStream stream = new DataOutputStream(
                        httpURLConnection.getOutputStream());
                stream.writeBytes(query);
                stream.flush();
                stream.close();
                DataInputStream dis = new DataInputStream(httpURLConnection
                        .getInputStream());
                String nextline;
                while ((nextline = dis.readLine()) != null) {
                    errorCheck.api_error(nextline);
                    System.out.println(" ");
                    DisplayData(nextline, uuid);
                }
                dis.close();
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "customer";
        String password = "password";
        String uuid = "1809404a-12cf-11df-8e89-000acd1901c5";
        String uri = "rest/hosting/vm/" + uuid + "/tag";
        String query = "tag=ne,tet,nt";
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            CreateQuota(uri, uuid, query, cm);
        }

    }
}

Here is an example of how to remove a tag from a virtual machine.

 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
import java.io.IOException;
import java.net.*;

public class rest_hosting_vm_uuid_tag_name_delete {
    // Following method will output all information in proper format

    public static void DeleteQuota(String uuid, String uri, String tag,
            CookieManager cm) throws IOException {
        try {
            URL url = new URL("https://127.0.0.1/" + uri + "/");
            URLConnection urlConnection = url.openConnection();
            cm.setCookies(urlConnection);
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode != 200) {
                    System.out.println("DELETE Failed due to a " + responseCode
                            + " HTTP error");
                } else {
                    System.out.println("Successfully Deleted tag \"" + tag
                            + "\" for UUID: " + uuid);
                }
            } else {
                throw new IOException("Delete is not supported for ");
            }
        } catch (RuntimeException exception) {
            System.out.println("FAIL");
        }
    }

    public static void main(String[] args) throws IOException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        boolean check;
        String username = "customer";
        String password = "password";
        String uuid = "1809404a-12cf-11df-8e89-000acd1901c5";
        String tag = "new";
        String uri = "rest/hosting/vm/" + uuid + "/tag/" + tag;
        check = user.initial_Login(cm, username, password);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            DeleteQuota(uuid, uri, tag, cm);
        }

    }
}

4.19. usage – Virtual Machine Resource Usage

Virtual machine resource usage functionality.

4.19.1. Resources

4.19.1.1. Usage

class usage.Usage

This resource represens virtual machine resource usage data.

Resource URI:

/rest/hosting/usage/
GET()

Retrieve the usage data by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module.

Return type:usage.RepUsage

4.19.1.2. UsageUUID

class usage.UsageUUID

This resource represens virtual machine resource usage data for a particular virtual machine.

Resource URI:

/rest/hosting/usage/<UUID>/
GET()

Retrieve the usage data by submitting an HTTP GET request. The UUID in the resource path should be the uuid of the target virtual machine.

Note

This resource requires read permission both on the elastic_hosting extension module and on the target virtual machine.

Return type:usage.RepUsage

4.19.2. Representations

4.19.2.1. RepUsage

class usage.RepUsage

This is a representation of the virtual machine resource usage data.

Representation:

{"vms": {"used": usage.used_vms, "available": usage.available_cpus},
 "cpus": {"used": usage.used_cpus, "available": usage.available_cpus},
 "memory": {"used": usage.used_memory, "available": usage.available_memory},\
 "storage": {"used": usage.used_storage, "available": usage.available_storage}}

4.19.3. Examples

4.19.3.1. PHP

Here is an example of how to check the usage for the current user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_usage = api_request($base_url.'/rest/hosting/usage/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_usage)){
    
        if($arr_usage){
        
            //Display all usage info
            echo "
            <h1>Usage:</h1><table>
            <tr>
            <td>Usage</td>
            <td>Used</td>
            <td>Total</td>
            </tr>";
            foreach ($arr_usage['usage'] as $usage=>$info){
                echo "
                <tr>
                <td>$usage</td>
                <td>$info[used]</td>
                <td>$info[available]</td>
                </tr>";
            }
            echo '</table>';
        }
        else{
            echo '<p>No quotas available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_usage.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to check the usage for a specific virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Check usage the this Virtual Machine
$uuid = 'd8895fc5-0dd1-11df-ab9f-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_usage = api_request($base_url.'/rest/hosting/usage/'.$uuid.'/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_usage)){
    
        if($arr_usage){
        
            //Display all usage info
            echo "
            <h1>Usage:</h1><table>
            <tr>
            <td>Usage</td>
            <td>Used</td>
            <td>Total</td>
            </tr>";
            foreach ($arr_usage['usage'] as $usage=>$info){
                echo "
                <tr>
                <td>$usage</td>
                <td>$info[used]</td>
                <td>$info[available]</td>
                </tr>";
            }
            echo '</table>';
        }
        else{
            echo '<p>No quotas available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_usage.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

4.19.3.2. Python

Here is an example of how to check the usage for the current user.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/usage/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        
        #Output the usage in a nice format
        usage = json['usage']
        
        print 'VMs:     %i/%i' % (usage['vms']['used'], usage['vms']['available'])
        
        print 'CPUs:    %i/%i' % (usage['cpus']['used'], usage['cpus']['available'])
                            
        print 'Memory:  %i/%i MB' % (usage['memory']['used'],
        usage['memory']['available'])
               
        print 'Storage: %.2f/%.2f GB' % (float(usage['storage']['used'])/1024, 
        float(usage['storage']['available'])/1024)
        
    else:
        #Output the error
        print error

Here is an example of how to check the usage for a specific virtual machine.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

#UUID of machine to get usage information about
uuid = '04a0a538-129e-11df-a880-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/usage/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        
        #Show information about this VM's usage
        usage = json['usage']
        
        print 'CPUs:    %i/%i' % (usage['cpus']['used'], usage['cpus']['available'])
                            
        print 'Memory:  %i/%i MB' % (usage['memory']['used'],
        usage['memory']['available'])
               
        print 'Storage: %.2f/%.2f GB' % (float(usage['storage']['used'])/1024, 
        float(usage['storage']['available'])/1024)
        
    else:
        #Output the error
        	print error

4.19.3.3. Java

Here is an example of how to check the usage for the current user.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_usage_get {
    // Following method will output all information in proper format
    public static void DisplayData(String usage_List, String field, String unit) {

        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(usage_List);
            try {
                JSONObject usage_info = (JSONObject) json.get("usage");
                JSONObject info_item = (JSONObject) usage_info.get(field);
                System.out.println(" ");
                System.out.println(field.toUpperCase());
                System.out.println("   Available: "
                        + info_item.get("available") + " " + unit);
                System.out.println("   Used: " + info_item.get("used") + " "
                        + unit);

            } catch (Exception e) {
                System.out.println("Display Error");
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "customer";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/usage/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line, "memory", "MB");
                    DisplayData(info_Line, "storage", "MB");
                    DisplayData(info_Line, "vms", "");
                    DisplayData(info_Line, "cpus", "");
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to check the usage for a specific virtual machine.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_usage_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String usage_List, String field, String unit) {
        boolean exists = true;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(usage_List);
            int errObj = ((Number) json.get("errno")).intValue();
            if (errObj != 0) {
                System.out.println(json.get("message"));
                System.out.println(" ");
                exists = false;
            }
            while (exists) {
                try {
                    JSONObject usage_info = (JSONObject) json.get("usage");
                    JSONObject info_item = (JSONObject) usage_info.get(field);
                    System.out.println(" ");
                    System.out.println(field.toUpperCase());
                    System.out.println("   Available: "
                            + info_item.get("available") + " " + unit);
                    System.out.println("   Used: " + info_item.get("used")
                            + " " + unit);

                } catch (Exception e) {
                    System.out.println("Display Error");
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "customer";
        String password = "password";
        String uuid = "e4ed8a9e-11c1-11df-b782-000acd1901c5";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/usage/"
                + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    System.out.println(" ");
                    DisplayData(info_Line, "memory", "MB");
                    DisplayData(info_Line, "storage", "MB");
                    DisplayData(info_Line, "cpus", "");
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

4.20. user – User

User functionality.

4.20.1. Resources

4.20.1.1. User

class user.User

This resource represents a method in which to create a new user.

Resource URI:

/rest/hosting/user/
PUT(username, displayname, password, password_confirm, group, email)

Create a new user by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • username – New user name. (no spaces)
  • displayname – New user display name.
  • password – New user password.
  • password_confirm – New user password again.
  • group – New user’s group. (UUID)
  • email – New user email.
Return type:

user.RepUser

4.20.1.2. UserUUID

class user.UserUUID

This resource represens a specific user.

Resource URI:

/rest/hosting/user/<UUID>/
GET()

Retrieve the specified user by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target user.

Note

This resource requires read permission on both the user and the elastic_hosting extension module when using the HTTP GET method.

Return type:user.RepUserUUID
POST(username, displayname, email)

Update the specified user by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target user.

Note

This resource requires update permission on both the user and the elastic_hosting extension module when using the HTTP POST method.

Parameters:
  • username – The username to update the user with.
  • displayname – The display name to update the user with.
  • email – The email address to update the user with.
  • limit_to_ip – The ip address/network to update the user with.
Return type:

user.RepUserUUID

DELETE()

Delete the specified user by submitting an HTTP DELETE request. The UUID in the resource URI should be the UUID of the target user. Will only work if their VMs have all been stopped and deleted.

Return type:util.RepErrCodes

4.20.1.3. UserList

class user.UserList

This resource represents a list of users.

Resource URI:

/rest/hosting/user/list/
GET()

Retrieve a list of users by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module and on each user that is found.

Return type:user.RepUserList

4.20.2. Representations

4.20.2.1. RepUser

class user.RepUser

This is a representation of a user resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
user
This attribute represents the newly created user object and is a user.RepUserUUID representation.

Representation:

{"errno":response.errno,
 "message":response.message,
 "user": user_obj}

4.20.2.2. RepUserUUID

class user.RepUserUUID

This is a representation of a user resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
user.uuid
This attribute represents the UUID of the user.
user.user_name
This attribute represents the username of the user.
user.display_name
This attribute represents the display name of the user.
user.password
This attribute represents the password of the user.
user.email
This attribute represents the email address of the user.
user.created
This is the date stamp (variable output format) of the user creation.
user.groups
This is an array of strings, representing the user’s group memberships
user.perms
This is a reserved attribute, subject to change without notice.
user.childName
This is a reserved attribute, subject to change without notice.
user.lang_pref
The i18n identifier for the user’s language preference. This is a reserved attribute, subject to change without notice.
user.limit_to_ip
This is a reserved attribute, subject to change without notice.
user.data
Additional user metadata. This is a reserved attribute, subject to change without notice.
user.id
This is a reserved attribute, subject to change without notice.
user.permissions
This is a reserved attribute, subject to change without notice.

Representation:

{"errno": response.errno,
 "message": response.message,
 "user": {"uuid": user.uuid,
          "groups": user.groups,
          "created": user.created,
          "perms": user.perms,
          "user_name": user.user_name,
          "childName": user.childName,
          "lang_pref": user.lang_pref,
          "limit_to_ip": user.limit_to_ip,
          "data": user.data,
          "id": user.id,
          "permissions": user.permissions,
          "display_name": user.display_name,
          "password": user.password,
          "email": user.email}}

4.20.2.3. RepUserList

class user.RepUserList

This is a representation of a list of users. This is a list of user.RepUserUUID representations.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
users
This attribute represents the list of user representations.

Representation

{"errno": response.errno,
 "message": response.message,
 "users": [user1, user2]}

4.20.3. Examples

4.20.3.1. PHP

Here is an example of how to list all users.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_users = api_request($base_url.'/rest/hosting/user/list/', 'get', null, 
        $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_users)){
    
        if($arr_users['users']){
        
            //Display the users in a table
            echo '<h1>Users:</h1><table>';
            echo '<tr>';
            echo '<td>UUID</td>';
            echo '<td>Display name</td>';
            echo '<td>Username</td>';
            echo '<td>Groups</td>';
            echo '</tr>';
            foreach ($arr_users['users'] as $user)
            {
                echo '<tr>';
                echo "<td>$user[uuid]</td>";
                echo "<td>$user[display_name]</td>";
                echo "<td>$user[user_name]</td>";
                echo '<td>';
                //If the user belongs to at least one group, show a comma 
                //separated list of the groups
                if(is_array($user['groups']) && $user['groups']){
                    echo implode(', ',$user['groups']);
                }
                else{ //otherwise show "None!"
                    echo 'None!</td>';
                }
                echo '</tr>';
            }
            echo '</table>';
        }
        else{
            echo '<p>No users available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_users.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get information about a specific user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//User to get details of
$uuid = '74f27594-fa86-11de-9e2d-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/user/'.$uuid.'/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for user with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['user'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to create a new user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Information about the new user
$username         = 'API_user4';
$displayname      = 'A user of the API';
$password         = 'password';
$password_confirm = 'password';
$group            = 'f9b5fc11-1bf4-11df-9c93-000acd1901c5';
$email            = 'person4@example.com';


//Combine the data to create the PUT string
$data = "username=$username&displayname=$displayname&password=$password".
        "&password_confirm=$password_confirm&group=$group&email=$email";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/user/', 'put',
        $data, $cookies_file, 'user');
    
    //Make sure there was no error returned
    if(is_array($response)){
    
        echo "<p>New user created with UUID: ".$response['user']['uuid']."</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.20.3.2. Python

Here is an example of how to list all users.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/user/list/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        #Loop through the users
        for user in json['users']:
        
            #Output and remove the name from the dictionary.
            print
            print "=========== " + user['user_name'] + " ==========="
            del(user['user_name'])
            
            #Output all information
            for key in user.keys():
                print key + ' = ' + str(user[key])
    else:
        #Output the error
        print error

Here is an example of how to get information about a specific user.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'admin'
password = 'password'

#User for which to get information
uuid = 'ee5d91f0-0055-11df-8ecf-000acd1901c5'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/user/'+uuid+'/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
        
        #Format the output nicely
        #Parse the response into a dictionary
        json = loads(response_body)
        
        #Show information about this user
        user = json['user']
        
        #Output and remove the name from the dictionary
        print 
        print '=========== ' + user['user_name'] + ' ==========='
        del(user['user_name'])
		
        #Output all information
        for key in user.keys():
            print key + ' = ' + str(user[key])
        
    else:
        #Output the error
        	print error

4.20.3.3. Java

Here is an example of how to list all existing users.

 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
import java.net.*;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_user_list {
    // Following method will output all information in proper format
    public static void DisplayData(String user_List) {
        boolean check = true;
        int count = 0;
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(user_List);
            JSONArray user_obj = (JSONArray) json.get("users");
            System.out.println(" ");
            System.out.println("Users:");
            while (check) {
                try {
                    JSONObject user_items = (JSONObject) user_obj.get(count);
                    System.out.println(" ");
                    System.out.println((count + 1) + ")");
                    System.out.println("Display Name: "
                            + user_items.get("display_name"));
                    System.out.println("User Name: "
                            + user_items.get("user_name"));
                    System.out.println("Date Created: "
                            + user_items.get("created"));
                    System.out.println("Email Address: "
                            + user_items.get("email_address"));
                    System.out.println("uuid: " + user_items.get("uuid"));
                    System.out.println("Groups: " + user_items.get("groups"));
                    count++;
                } catch (Exception e) {
                    check = false;
                }
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/user/list/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                // will connect to URL and call display method to output all the
                // info
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to get information about a specific user.

 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
import java.net.*;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_user_uuid_get {
    // Following method will output all information in proper format
    public static void DisplayData(String user_List) {
        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(user_List);
            System.out.println(" ");
            System.out.println("User:");
            try {
                JSONObject user_info = (JSONObject) json.get("user");
                System.out.println(" ");
                System.out.println("Display Name: "
                        + user_info.get("display_name"));
                System.out.println("Groups: " + user_info.get("groups"));
                System.out.println("Date Created: " + user_info.get("created"));
                System.out.println("uuid: " + user_info.get("uuid"));
                System.out.println("Email Address: "
                        + user_info.get("email_address"));
            } catch (Exception e) {

                System.out.println("User with specified uuid does not exist");
            }

        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String username = "admin";
        String password = "password";
        String authentication_message = "";
        String info_Line = "";
        String uuid = "ee5d91f0-0055-11df-8ecf-000acd1901c5";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/user/"
                + uuid + "/");
        check = user.initial_Login(cm, username, password);
        System.out.println(authentication_message);
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            // will connect to URL and call display method to output all the
            // info
            do {
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }
}

4.21. util – Utilities

Utility functionality.

4.21.1. Resources

4.21.1.1. ErrCodes

class util.ErrCodes

This resources represents the potential error codes that may be returned by any given resource.

Resource URI:

/rest/hosting/errcodes/
GET()

Return the available error codes.

Note

This resource requires read permission on the elastic_hosting extension module when using the HTTP GET method.

Return type:util.RepErrCodes

4.21.1.2. I18N

class util.I18N

This resource represents the language labels used in the user interface.

Resource URI:

/rest/hosting/i18n/
GET(locale)

Return the language labels used in the user interface by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module when using the HTTP GET method.

Parameter:locale – The locale of the translations to return.
Return type:util.RepI18N

4.21.1.3. IconMap

class util.IconMap

This resource represents the icons for operation systems and applications used in the user interface.

Resource URI:

/rest/hosting/iconmap/
GET()

Return the icons used in the user interface.

Note

This resource requires read permission on the elastic_hosting extension module when using the HTTP GET method.

Return type:util.RepIconMap

4.21.2. Representations

4.21.2.1. RepErrCodes

class util.RepErrCodes

This is a representation of the available API error codes.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general error message generated by the resource.
errcodes
This attribute represents the errcode dictionary.

Representation:

{"errno": response.errno,
 "message": response.message,
 "errcodes": {"err_label": err.number}}

4.21.2.2. RepI18N

class util.RepI18N

This is a representation of language labels used in the user interface.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general error message generated by the resource.
i18n

This attribute represents the dictionary of language translations.

i18n_label is a label with the prefix I18N such as I18N_PENDING_VM.

lang is an array containing two elements: The first one is the locale code and the second is the human readable language name.

Representation:

{"errno": response.errno,
 "message": response.message,
 "i18n": {"current": i18n.current,
          "supported": [lang1, lang2],
          i18n_label: i18n.translation}}

4.21.2.3. RepIconMap

class util.RepIconMap

This is a representation of the icons used in the user interface.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general error message generated by the resource.
icons
This attribute represents the dictionary of operating system icons.

Representation:

{"errno": response.errno,
 "message": response.message,
 "icons": {"base_path": "/path/",
           "os_label": {"small": os.small,
                        "medium": os.medium}}}

4.21.3. Examples

4.21.3.1. PHP

Here is an example of how to get the current language’s translation of all messages.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_i18n = api_request($base_url.'/rest/hosting/i18n/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_i18n)){
    
        //Display the info.
		echo '<p>Current language: '.$arr_i18n['i18n']['current'].'</p>';
		echo '<p>Supported languages: ';
		$buff = '';
		foreach($arr_i18n['i18n']['supported'] as $lang)
		{
			$buff .= ', '.$lang[1].'('.$lang[0].')';
		}
		echo substr ($buff,2).'</p>';
		
		//Ignore the unnedded info for the next section
		unset($arr_i18n['i18n']['supported']);
		unset($arr_i18n['i18n']['current']);
		
		//Display the translations in a table
		echo "
		<h1>Current transaltion:</h1><table>
		<tr>
		<td><b>Label</b></td>
		<td><b>Translation</b></td>
		</tr>";
		foreach ($arr_i18n['i18n'] as $label=>$translation)
		{
			echo "
			<tr>
			<td>$label</td>
			<td>$translation</td>
			</tr>";
		}
		echo '</table>';
    } 
    else{
         echo '<p>Error: '.$arr_i18n.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to get the paths of all VM icons.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_icons = api_request($base_url.'/rest/hosting/iconmap/', 'get', 
        null, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_icons)){
    
        echo "<p>Base path: {$arr_icons['icons']['base_path']}</p>";
        unset($arr_icons['icons']['base_path']);
        foreach($arr_icons['icons'] as $key=>$value){
            echo "<p><b>$key</b> -- Small:$value[small] Medium:$value[medium]</p>";
        }
    } 
    else{
         echo '<p>Error: '.$arr_i18n.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

4.21.3.2. Python

Here is an example of how to get the current language’s translation of all messages.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/i18n/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
    
        #Parse the response
        json = loads(response_body)
        dictionary = json['i18n']
        
        #Display and remove special elements form the list
        print 'Current language: ' + dictionary['current']
        del(dictionary['current'])
        
        print 'Supported languages: '
        for lang in dictionary['supported']:
            print '- %s(%s)' % (lang[1], lang[0])
        del(dictionary['supported'])
        
        print
        print 'Current dictionary:'
        for label, translation in dictionary.items():
            print label + ': ' + translation
        
    else:
        #Output the error
        print error

Here is an example of how to get the paths of all VM icons.

See also

Cookies

from cookielib import CookieJar
from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
from urllib2 import build_opener, install_opener, URLError
from json import loads
from error import ecp_check_error

#Quickly assign an anonymous cookie jar to handle the cookies
install_opener(build_opener(HTTPCookieProcessor(CookieJar())))

#Domain or ip of primary ECP node (also specify port if not 80)
#Include protocol prefix http:// and do not include a trailing slash
host = 'http://127.0.0.1'
username = 'customer'
password = 'password'

try:

    #Log in. More information about this in the authentication example.
    urlopen(host + '/modules/hosting/?login=Login&user_name=' + \
            username + '&password=' + password)
            
    #Set up the request. It is a GET by default when not providing data.
    req = Request(host+'/rest/hosting/iconmap/')
    #Send the request
    response = urlopen(req)

except (HTTPError, URLError) as exception:

    #Handle http error codes and errors with the connection
    print exception

else:
    
    #Read the response
    response_body = response.read()
    
    #Verify that there was no error
    error = ecp_check_error(response_body)
    if not error:
    
        #Parse the response
        json = loads(response_body)
        icons = json['icons']
        
        print 'Base path: ' + icons['base_path']
        print
        del(icons['base_path'])
        
        for label, info in icons.items():
            print '--- ' + label + ' ---'
            print 'Small: ' + info['small']
            print 'Medium: ' + info['medium']
            print
        
    else:
        #Output the error
        print error

4.21.3.3. Java

Here is an example of how to get the current language’s translation of all messages.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_i18n_get {

    public static void DisplayData(String i18n_List) {
        String key_Line = "";
        String key_Data = "";
        String[] split_key_line = null;
        String[] split_key_data = null;

        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(i18n_List);
            try {
                JSONObject i18n_name = (JSONObject) json.get("i18n");
                System.out.println(" ");
                System.out.println("Langauges Supported: "
                        + i18n_name.get("supported"));
                System.out.println("Current Language: \""
                        + i18n_name.get("current") + "\"");
                System.out.println(" ");
                key_Line = i18n_name.keySet().toString();
                // Following will replace unnecessary character and strings with
                // empty
                // values
                key_Line = key_Line.replace("[", "");
                key_Line = key_Line.replace("]", "");
                key_Line = key_Line.replaceAll(" supported, current,", "");
                // Split items in string at commas
                split_key_line = key_Line.split(",");

                key_Data = i18n_name.values().toString();
                // Following will replace unnecessary character and strings with
                // empty
                // values
                key_Data = key_Data.replace("[", "");
                key_Data = key_Data.replace("]", "");
                key_Data = key_Data.replaceAll(
                        " \"en\",\"English\",\"sv\",\"svenska\", en,", "");
                // Split items in string at commas
                split_key_data = key_Data.split(",");

                for (int i = 0; i < split_key_line.length; i++) {
                    System.out.println(" ");
                    System.out.println((i + 1) + ")");
                    System.out.println("Label: " + split_key_line[i]);
                    System.out.println("Message: " + split_key_data[i]);
                }

            } catch (Exception e) {
                System.out.println("Display Error");
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String info_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL("https://127.0.0.1/rest/hosting/i18n/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

Here is an example of how to get the paths of all VM icons.

 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
import java.net.MalformedURLException;
import java.net.URL;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class rest_hosting_iconmap_get {

    public static void DisplayData(String icon_List) {
        String key_Line = "";
        String key_Data = "";
        String[] split_key_line = null;
        String[] split_key_data = null;

        JSONObject json;
        try {
            json = (JSONObject) new JSONParser().parse(icon_List);
            try {
                JSONObject icon_types = (JSONObject) json.get("icons");
                System.out.println(" ");
                System.out.println("Base Path for Icons: "
                        + icon_types.get("base_path"));
                key_Line = icon_types.keySet().toString();
                // Following will replace unnecessary character and strings with
                // empty
                // values
                key_Line = key_Line.replace("[", "");
                key_Line = key_Line.replace("]", "");
                key_Line = key_Line.replaceAll(" base_path,", "");
                split_key_line = key_Line.split(",");

                key_Data = icon_types.values().toString();
                // Following will replace unnecessary character and strings with
                // empty
                // values
                key_Data = key_Data.replace("[", "");
                key_Data = key_Data.replace("]", "");
                key_Data = key_Data.replace("\"", "");
                key_Data = key_Data.replace("{", "");
                key_Data = key_Data.replaceAll(
                        " /modules/hosting/static/img/,", "");
                split_key_data = key_Data.split("},");
                // following will create a counted loop to display all labels
                // with paths
                // Max size could also be replaced with data array length as
                // they both
                // have the same amount of elements
                for (int i = 0; i < split_key_line.length; i++) {
                    System.out.println(" ");
                    System.out.println((i + 1) + ")");
                    System.out.println("OS Label: " + split_key_line[i]);
                    split_key_data[i] = split_key_data[i].replace(",", "   ");
                    System.out.println("Icon Paths: "
                            + split_key_data[i].replace("}", ""));
                }

            } catch (Exception e) {
                System.out.println("Display Error");
            }
        } catch (ParseException e) {

            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws MalformedURLException {
        Client user = new Client();
        CookieManager cm = new CookieManager();
        error_Handling errorCheck = new error_Handling();
        boolean check;
        String info_Line = "";
        String username = "admin";
        String password = "password";
        int count = 0;
        URL url = new URL(
                "https://127.0.0.1/rest/hosting/iconmap/");
        check = user.initial_Login(cm, username, password);
        System.out.println(" ");
        if (check == false) {
            System.out.println("Authentication Failed");
        } else {
            do {
                info_Line = (user.connectURI(url, cm, count));
                if (info_Line != null) {
                    errorCheck.api_error(info_Line);
                    DisplayData(info_Line);
                    count++;
                }
            } while (info_Line != null);
        }
    }

}

4.22. vm – Virtual Machine

Virtual machine functionality.

4.22.1. Resources

4.22.1.1. Vm

class vm.Vm

This resource represents a method in which to provision a new virtual machine.

Resource URI:

/rest/hosting/vm/
PUT(name, package, hardware, disk, network_uuid)

Provision a new virtual machine by submitting an HTTP PUT request.

Note

This resource requires create permission on the elastic_hosting extension module.

Parameters:
  • name – New virtual machine name.
  • package – New virtual machine package.
  • hardware – New virtual machine hardware profile.
  • disk – Additional hard disk for the virtual machine.
  • network_uuid – Network associated with the new virtual machine.
Return type:

vm.RepVm

See also

ptemplate htemplate dtemplate network

4.22.1.2. VmUUID

class vm.VmUUID

This resource represens a specific virtual machine.

Resource URI:

/rest/hosting/vm/<UUID>/
GET()

Retrieve the specified virtual machine by submitting an HTTP GET request. The UUID in the resource URI should be the UUID of the target virtual machine.

Note

This resource requires read permission on both the virtual machine and the elastic_hosting extension module when using the HTTP GET method.

Return type:vm.RepVmUUID
POST(action, name, hardware_profile_uuid, flags, notes, is_cd_boot)

Update the specified virtual machine by submitting an HTTP POST request. The UUID in the resource URI should be the UUID of the target virtual machine.

Note

This resource requires update permission on both the virtual machine and the elastic_hosting extension module when using the HTTP POST method.

Parameters:
  • action – The action to perform on the virtual machine. The following actions are supported - start, stop, pause, resume, delete, and save.
  • name – The name to update the virtual machine with.
  • enable_vnc – Enable or disable VNC with “True” or “False”.
  • harware_profile_uuid – The hardware profile to associate with the virtual machine.
  • flags – The advanced virtualization VM flags to set. “-” turns the flag off. All flags are required and are comma-separated. Valid flags are “acpi”, “apic”, “pae”, “virtio” (not with e1000), “virtblk”, “e1000” (not with virtio), “rtcfix”.
  • notes – Plain text notes to associate with the VM.
  • is_cd_boot – A value of 1 means boot from CD ROM.
Return type:

vm.RepVmUUID

4.22.1.3. VmList

class vm.VmList

This resource represents a list of virtual machines.

Resource URI:

/rest/hosting/vm/list/
GET()

Retrieve a list of virtual machines by submitting an HTTP GET request.

Note

This resource requires read permission on the elastic_hosting extension module and on each virtual machine that is found.

Return type:vm.RepVmList
4.22.1.3.1. List by IP
class vm.VmList

This resource represents a list of virtual machines specified by an ip address.

Resource URI:

/rest/hosting/vm/list/ip?=<some ip>
GET()

Retrieve a list of virtual machines by submitting an HTTP GET request. If <some ip> field is left blank, all vas will be listed.

Note

This resource requires read permission on the elastic_hosting extension module and on each virtual machine that is found.

Return type:vm.RepVmList
4.22.1.3.2. List by MAC
class vm.VmList

This resource represents a list of virtual machines specified by a mac address.

Resource URI:

/rest/hosting/vm/list/mac?=<some mac>
GET()

Retrieve a list of virtual machines by submitting an HTTP GET request. If <some mac> field is left blank, all vas will be listed.

Note

This resource requires read permission on the elastic_hosting extension module and on each virtual machine that is found.

Return type:vm.RepVmList

4.22.2. Representations

4.22.2.1. RepVm

class vm.RepVm

This is a representation of a virtual machine currently being provisioned.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
txid
This attribute represents the UUID of the transaction that is executing the provision job.
machine_id
This attribute represents the UUID of the new VM.

Representation:

{"errno":response.errno,
 "message":response.message,
 "txid": transaction.uuid,
 "machine_id": machine.uuid}

4.22.2.2. RepVmUUID

class vm.RepVmUUID

This is a representation of a virtual machine resource.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
vm.uuid
This attribute represents the UUID of the virtual machine.
vm.name
This attribute represents the name of the virtual machine.
vm.state
This attribute represents the current state of the virtual machine.
vm.os
This attribute represents the operating system of the virtual machine.
vm.hardware_profile_uuid
This attribute represents the UUID of the hardware profile this virtual machine is using.
vm.vnc_ip_address
This attribute represents the VNC IP address of the virtual machine.
vm.vnc_port
This attribute represents the VNC port of the virtual machine.
vm.vnc_password
This attribute represents the VNC password of the virtual machine.
vm.vnc_enabled
This attribute represents whether or not VNC is enabled for this virtual machine.
vm.interfaces
This attribute represents the list of network interfacs belonging to this virtual machine.
vm.flags
This attribute represents the list of advanced VM flags.
vm.owner
This attribute represents user that owns this VM.
vm.is_cd_boot
This attribute is true is the current boot device is the CD ROM.

Representation:

{"errno": response.errno,
 "message": response.message,
 "vm": {"uuid": vm.uuid,
        "name": vm.name,
        "state": vm.state,
        "os": vm.os,
        "hardware_profile_uuid": vm.hardware_profile,
        "vnc_ip_address": vm.vnc_ip,
        "vnc_port": vm.vnc_port,
        "vnc_password": vm.vnc_password,
        "vnc_enabled": vm.vnc_enabled,
        "interfaces": [{"uuid": interface.uuid,
                        "ip": interface.ip,
                        "mac": interface.mac,
                        "network_name": interface.network_name,
                        "network": interface.network}],
        "flags": vm.flags,
        "owner": vm.user_obj,
        "is_cd_boot": vm.is_cd_boot}}

4.22.2.3. RepVmList

class vm.RepVmList

This is a representation of a list of virtual machines. This is a list of vm.RepVmUUID representations.

errno
This attribute represents the general error number generated by the resource.
message
This attribute represents the general message generated by the resource.
vms
This attribute represents the list of virtual machine representations.

Representation

{"errno": response.errno,
 "message": response.message,
 "vms": [vm1, vm2]}

See also

vm.RepVmUUID

4.22.3. Examples

4.22.3.1. PHP

Here is an example of how to list all virtual machines owned by the current user.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $arr_vms = api_request($base_url.'/rest/hosting/vm/list/', 'get', null, 
        $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($arr_vms)){
    
        if($arr_vms['vms']){
        
            //Display VMs in a table
            echo "
            <h1>Virtual Machines:</h1><table>
            <tr>
            <td>UUID</td>
            <td>Name</td>
            <td>State</td>
            <td>Operating System</td>
            <td>Hardware UUID</td>
            <td>VNC IP</td>
            <td>VNC port</td>
            <td>VNC password</td>
            <td>VNC enabled</td>
            <td>Interfaces</td>
            </tr>";
            foreach ($arr_vms['vms'] as $vms)
            {
                echo "
                <tr>
                <td>$vms[uuid]</td>
                <td>$vms[name]</td>
                <td>$vms[state]</td>
                <td>$vms[os]</td>
                <td>$vms[hardware_profile_uuid]</td>
                <td>$vms[vnc_ip_address]</td>
                <td>$vms[vnc_port]</td>
                <td>$vms[vnc_password]</td>
                <td>".($vms['vnc_enabled']?'Yes':'No')."</td>
                <td>";
                
                //The logic for putting together a list of the network 
                //interfaces:
                $list='';
                foreach($vms['interfaces'] as $interface)
                {
                    $list .= ', '.$interface['network_name'].'('.$interface['ip'].')';
                }
                echo substr($list,2);
                
                echo "
                </td>
                </tr>";
            }
            echo '</table>';
        }
        else{
            echo '<p>No VMs available.</p>';
        }
    } 
    else{
         echo '<p>Error: '.$arr_vms.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>

Here is an example of how to get information about a specific virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//VM to get details of
$uuid = 'cfd4df9c-0b11-11df-bc8a-000acd1901c5';

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $details = api_request($base_url.'/rest/hosting/vm/'.$uuid.'/', 'get', null, 
        $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($details)){
    
        //Display the details.
        echo '<h1>Details for virtual machine with UUID:'.$uuid.'</h1>';
        echo '<ul>';
        foreach ($details['vm'] as $key=>$value){
             echo "<li>$key=$value</li>";
        }
        echo '</ul>';
    } 
    else{
         echo '<p>Error: '.$details.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to provision a new virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'customer';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Information about the new VM
$name           = "Machine Created by API";
$package        = '5d407a68-c76c-11de-86e5-000475cb7577';
$hardware       = 'bcaff710-2914-11de-836c-001a929face2';
$disk           = 'f1648fba-29ce-11de-84a2-001a929face2';
$network_uuid   = 'fc38963c-a9fa-11de-8c4b-001b63a56c51';

//Combine the data to create the PUT string
$data = "name=$name&package=$package&hardware=$hardware".
        "&disk=$disk&network_uuid=$network_uuid";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response = api_request($base_url.'/rest/hosting/vm/', 'put',
        $data, $cookies_file);
    
    //Make sure there was no error returned
    if(is_array($response)){

        echo "<p>New vm provisioned with UUID: $response[machine_id].".
             "Transaction UUID: $response[txid]</p>";

    } 
    else{
         echo '<p>Error: '.$response.'</p>';
    }

}
else{
    echo "<p>Authentication failed.</p>";
}
 
?>         

Here is an example of how to control a virtual machine.

 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
<?php
require('authentication.php');
require('error_handling.php');
require('api_request.php');

//Basic connection parameters.
//IP address or host name of the primary ECP node (no trailing slash)
$base_url = '127.0.0.1';
//login info
$username = 'admin';
$password = 'password';

//The cookie file used to store the session cookie.
$cookies_file = 'cookies.txt';

//Virtual Machine UUID
$uuid = 'f3178ef5-0f48-11df-9387-000acd1901c5';
//Command to send
$action = 'start';
//The action has to be set to 'save' to rename or change hardware template
$rename = 'new name';
//hardware changes will be made only upon restart
$hardware = 'bcaff710-2914-11de-836c-001a929face2';

//Combine the data to create the POST string
$data = "action=$action";
//add the additional information if we are using "save"
if ($action == 'save')
    $data .= "&name=$rename&hardware_profile_uuid=$hardware";

//Authenticate and check for success
if (authenticate($base_url, $username, $password, $cookies_file)){
    
    //Use use the same cookie file for other API calls
    $response