ECP Service Provider Edition API Documentation

Document Sample
ECP Service Provider Edition API Documentation Powered By Docstoc
					ECP Service Provider Edition API
                 Documentation
                       Release 3.3.0




                          Enomaly




                          August 12, 2010
                                                                                      CONTENTS



1   About the Code examples                                                                                            3
    1.1 PHP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    3
    1.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     5
    1.3 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .   5

2   Authentication                                                                                                     11
    2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     11
    2.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     11

3   billing – Billing                                                                                                  17
    3.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    17
    3.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    17
    3.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     18

4   clone – Clone virtual machines.                                                                                    25
    4.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    25
    4.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    25
    4.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     26

5   dtemplate – Disk Template                                                                                          31
    5.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    31
    5.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    32
    5.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     33

6   Error Handling                                                                                                     41
    6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     41
    6.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     41

7   group – Group                                                                                                      47
    7.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    47
    7.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    48
    7.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     50

8   htemplate – Hardware Template                                                                                      59
    8.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    59
    8.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    60
    8.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     62

9   log – Logs and Transactions                                                                                        81
    9.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    81


                                                                                                                        i
     9.2   Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    82
     9.3   Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .     83

10 network – Network                                                                                                     93
   10.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      93
   10.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      94
   10.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       95

11 ptemplate – Package Template                                                                                          111
   11.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      111
   11.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      112
   11.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       112

12 quota – Resource Quota                                                                                           121
   12.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
   12.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
   12.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

13 tag – Tagging                                                                                                         141
   13.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      141
   13.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      142
   13.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       143

14 interface – Interface                                                                                            155
   14.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
   14.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

15 isofile – ISO Files                                                                                              157
   15.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
   15.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

16 cdmount – Mounting CDs/DVDs                                                                                      159
   16.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
   16.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

17 disk – Additional Storage                                                                                        161
   17.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
   17.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

18 usage – Virtual Machine Resource Usage                                                                                163
   18.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      163
   18.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      164
   18.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       164

19 user – User                                                                                                           173
   19.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      173
   19.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      174
   19.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       176

20 util – Utilities                                                                                                      185
   20.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      185
   20.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      186
   20.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .       187

21 vm – Virtual Machine                                                                                             197
   21.1 Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197


ii
   21.2 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
   21.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

22 Indices and tables                                                                                              219

Python Module Index                                                                                                221

Index                                                                                                              223




                                                                                                                    iii
iv
                                      ECP Service Provider Edition API Documentation, Release 3.3.0


Welcome to the ECP Service Provider Edition API documentation. Here you will find resources on how to use the
ECP Service Provider Edition RESTful API.




CONTENTS                                                                                                  1
ECP Service Provider Edition API Documentation, Release 3.3.0




2                                                               CONTENTS
                                                                                                               CHAPTER

                                                                                                                    ONE



                               ABOUT THE CODE EXAMPLES

     1.1 PHP

     1.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.


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

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

 9        //Do some basic client configuration.
10        curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
11        curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
12        curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);
13

14        //Specify the URL for the HTTP request
15        curl_setopt($client, CURLOPT_URL, $url);
16

17        //Set up the data to be sent depending on the method
18        switch(strtolower($method)){
19




                                                                                                                          3
     ECP Service Provider Edition API Documentation, Release 3.3.0



20           case ’get’:
21

22                //Set up the GET request.
23                curl_setopt($client, CURLOPT_HTTPGET, 1);
24                //Add GET parameters if there are any
25                if($data)
26                    curl_setopt($client, CURLOPT_URL, $url.’?’.$data);
27                break;
28

29           case ’post’:
30

31                //Set up the POST request
32                curl_setopt($client, CURLOPT_POST, 1);
33                curl_setopt($client, CURLOPT_POSTFIELDS, $data);
34                break;
35

36           case ’delete’:
37

38                //Set up the DELETE request
39                curl_setopt($client, CURLOPT_CUSTOMREQUEST, ’DELETE’);
40                break;
41

42           case ’put’:
43

44                //The data has to be written to a file because CURL needs a file to
45                //"PUT"
46                $tmp_file = tmpfile();
47                fwrite($tmp_file, $data);
48                //Move the pointer to the beginning of the file so that CURL can
49                //read it from the beginning
50                fseek($tmp_file, 0);
51

52                //Set up the request so the temp file will be read and uploaded
53                curl_setopt($client, CURLOPT_PUT, 1);
54                curl_setopt($client, CURLOPT_INFILE, $tmp_file);
55                curl_setopt($client, CURLOPT_INFILESIZE, strlen($data));
56                curl_setopt($client, CURLOPT_HTTPHEADER,
57                    array("Content-Type: application/x-www-form-urlencoded"));
58                break;
59       }
60

61       //Execute the request
62       $http_response = curl_exec($client);
63

64       //Clean up the temp file if PUT was used
65       if(strtolower($method) == ’put’)
66           fclose($tmp_file);
67

68       //Verify that the call was sucessful.
69       $http_error_code = curl_getinfo($client, CURLINFO_HTTP_CODE);
70       if($http_error_code == 200){
71

72           //Check if there was an internal error and get the error message
73           $error = api_error($http_response);
74

75           //Verify that the operation was sucessful
76           if(!$error){
77




     4                                                         Chapter 1. About the Code examples
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



78                   //Return the json response parsed into an array
79                   $json_response = json_decode($http_response, true);
80

81                   curl_close($client);
82                   return $json_response;
83             }
84             else {
85                 curl_close($client);
86                 return $error;
87             }
88        }
89        else{
90            return "HTTP error code ".$http_error_code;
91        }
92   }
93   ?>



     1.2 Python

     1.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.


     1.3 Java

     1.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.


     1.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   import   java.io.BufferedReader;
 2   import   java.io.IOException;
 3   import   java.io.InputStreamReader;
 4   import   java.net.HttpURLConnection;
 5   import   java.net.URL;
 6   import   java.net.URLConnection;
 7

 8   public class Client {
 9

10        public boolean initial_Login(CookieManager cm, String user_name,
11                String pass_word) {
12            boolean check = true;
13            try {


     1.2. Python                                                                                                          5
     ECP Service Provider Edition API Documentation, Release 3.3.0



14                  URL url = new URL(
15                          "https://127.0.0.1/modules/hosting?user_name="
16                                  + user_name + "&password=" + pass_word
17                                  + "&login=Login");
18                  URLConnection conn = url.openConnection();
19                  conn.connect();
20                  HttpURLConnection httpConn = (HttpURLConnection) conn;
21

22                 int response_code = httpConn.getResponseCode();
23                 // will check for authentication by user
24                 if (response_code == 401) {
25                     // response = "Authentication Failed";
26                     check = false;
27                 } else if (response_code == 200) {
28                     // response = "Connected Successfully";
29                     System.out.println(" ");
30                     cm.storeCookies(conn);
31                 }
32             } catch (IOException ioe) {
33                 ioe.printStackTrace();
34             }
35             return check;
36        }
37

38        public String connectURI(URL url, CookieManager cm, int count) {
39            String info_Line = "";
40            try {
41                URLConnection conn2 = url.openConnection();
42                // cookies are set for resource uri
43                cm.setCookies(conn2);
44                conn2.connect();
45                // buffered reader that will read in the lines from the resource uri
46                BufferedReader stream_in = new BufferedReader(
47                         new InputStreamReader(conn2.getInputStream()));
48                count++;
49                for (int i = 0; i < count; i++) {
50                    info_Line = stream_in.readLine();
51                }
52                stream_in.close();
53            } catch (IOException ioe) {
54                System.out.println("URL entered is not correct");
55                return null;
56            }
57            return info_Line;
58        }
59

60   }



     1.3.3 Cookie Manager Class

     The following class was obtained from http://www.hccp.org/java-net-cookie-how-to.html It was written by Ian Brown.
     The present version contains minor bug fixes. This class is required for every example.
1    import   java.io.IOException;
2    import   java.net.URL;
3    import   java.net.URLConnection;
4    import   java.text.DateFormat;


     6                                                                     Chapter 1. About the Code examples
                                          ECP Service Provider Edition API Documentation, Release 3.3.0



 5   import   java.text.SimpleDateFormat;
 6   import   java.util.Date;
 7   import   java.util.HashMap;
 8   import   java.util.Iterator;
 9   import   java.util.Map;
10   import   java.util.StringTokenizer;
11

12   public class CookieManager {
13       private Map store;
14

15       private   static   final   String SET_COOKIE = "Set-Cookie";
16       private   static   final   String COOKIE_VALUE_DELIMITER = ";";
17       private   static   final   String PATH = "path";
18       private   static   final   String EXPIRES = "expires";
19       private   static   final   String DATE_FORMAT = "EEE, dd-MMM-yyyy hh:mm:ss z";
20       private   static   final   String SET_COOKIE_SEPARATOR = "; ";
21       private   static   final   String COOKIE = "Cookie";
22       private   static   final   char NAME_VALUE_SEPARATOR = ’=’;
23       private   static   final   char DOT = ’.’;
24

25       private DateFormat dateFormat;
26

27       // Cookie Manager and all its methods were imported from
28       // http://www.hccp.org/java-net-cookie-how-to.html
29       // Author: Ian Brown
30       public CookieManager() {
31

32            store = new HashMap();
33            dateFormat = new SimpleDateFormat(DATE_FORMAT);
34       }
35

36       /**
37        * Retrieves and stores cookies returned by the host on the other side of
38        * the the open java.net.URLConnection.
39        *
40        * The connection MUST have been opened using the connect() method or a
41        * IOException will be thrown.
42        *
43        * @param conn
44        *            a java.net.URLConnection - must be open, or IOException will
45        *            be thrown
46        * @throws java.io.IOException
47        *             Thrown if conn is not open.
48        */
49       public void storeCookies(URLConnection conn) throws IOException {
50

51            // let’s determine the domain from where these cookies are being sent
52            String domain = getDomainFromHost(conn.getURL().getHost());
53

54            Map domainStore; // this is where we will store cookies for this domain
55

56            // now let’s check the store to see if we have an entry for this domain
57            if (store.containsKey(domain)) {
58                // we do, so lets retrieve it from the store
59                domainStore = (Map) store.get(domain);
60            } else {
61                // we don’t, so let’s create it and put it in the store
62                domainStore = new HashMap();



     1.3. Java                                                                                       7
      ECP Service Provider Edition API Documentation, Release 3.3.0



 63                store.put(domain, domainStore);
 64           }
 65

 66           // OK, now we are ready to get the cookies out of the URLConnection
 67

 68           String headerName = null;
 69           for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
 70               if (headerName.equalsIgnoreCase(SET_COOKIE)) {
 71                   Map cookie = new HashMap();
 72                   StringTokenizer st = new StringTokenizer(
 73                           conn.getHeaderField(i), COOKIE_VALUE_DELIMITER);
 74

 75                    // the specification dictates that the first name/value pair
 76                    // in the string is the cookie name and value, so let’s handle
 77                    // them as a special case:
 78

 79                    if (st.hasMoreTokens()) {
 80                        String token = st.nextToken();
 81                        String name = token.substring(0, token
 82                                .indexOf(NAME_VALUE_SEPARATOR));
 83                        String value = token.substring(token
 84                                .indexOf(NAME_VALUE_SEPARATOR) + 1, token.length());
 85                        domainStore.put(name, cookie);
 86                        cookie.put(name, value);
 87                    }
 88

 89                    while (st.hasMoreTokens()) {
 90                        String token = st.nextToken();
 91                        if (token.indexOf(NAME_VALUE_SEPARATOR) + 1 > token
 92                                .length()) {
 93                            cookie.put(token.substring(0,
 94                                    token.indexOf(NAME_VALUE_SEPARATOR))
 95                                    .toLowerCase(), "");
 96                        } else if (token.indexOf(NAME_VALUE_SEPARATOR) > 0)
 97                            cookie.put(token.substring(0,
 98                                    token.indexOf(NAME_VALUE_SEPARATOR))
 99                                    .toLowerCase(), token.substring(token
100                                    .indexOf(NAME_VALUE_SEPARATOR) + 1, token
101                                    .length()));
102

103                    }
104                }
105           }
106       }
107

108       /**
109        * Prior to opening a URLConnection, calling this method will set all
110        * unexpired cookies that match the path or subpaths for the underlying URL
111        *
112        * The connection MUST NOT have been opened method or an IOException will be
113        * thrown.
114        *
115        * @param conn
116        *            a java.net.URLConnection - must NOT be open, or IOException
117        *            will be thrown
118        * @throws java.io.IOException
119        *             Thrown if conn has already been opened.
120        */



      8                                                         Chapter 1. About the Code examples
                                     ECP Service Provider Edition API Documentation, Release 3.3.0



121       public void setCookies(URLConnection conn) throws IOException {
122

123           // let’s determine the domain and path to retrieve the appropriate
124           // cookies
125           URL url = conn.getURL();
126           String domain = getDomainFromHost(url.getHost());
127           String path = url.getPath();
128

129           Map domainStore = (Map) store.get(domain);
130           if (domainStore == null)
131               return;
132           StringBuffer cookieStringBuffer = new StringBuffer();
133

134           Iterator cookieNames = domainStore.keySet().iterator();
135           while (cookieNames.hasNext()) {
136               String cookieName = (String) cookieNames.next();
137               Map cookie = (Map) domainStore.get(cookieName);
138               // check cookie to ensure path matches and cookie is not expired
139               // if all is cool, add cookie to header string
140               if (comparePaths((String) cookie.get(PATH), path)
141                       && isNotExpired((String) cookie.get(EXPIRES))) {
142                   cookieStringBuffer.append(cookieName);
143                   cookieStringBuffer.append("=");
144                   cookieStringBuffer.append((String) cookie.get(cookieName));
145                   if (cookieNames.hasNext())
146                       cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
147               }
148           }
149           try {
150               conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
151           } catch (java.lang.IllegalStateException ise) {
152               IOException ioe = new IOException(
153                       "Illegal State! Cookies cannot be set on a URLConnection that is already connecte
154                               + "Only call setCookies(java.net.URLConnection) AFTER calling java.net.UR
155               throw ioe;
156           }
157       }
158

159       private String getDomainFromHost(String host) {
160           if (host.indexOf(DOT) != host.lastIndexOf(DOT)) {
161               return host.substring(host.indexOf(DOT) + 1);
162           } else {
163               return host;
164           }
165       }
166

167       private boolean isNotExpired(String cookieExpires) {
168           if (cookieExpires == null)
169               return true;
170           Date now = new Date();
171           try {
172               return (now.compareTo(dateFormat.parse(cookieExpires))) <= 0;
173           } catch (java.text.ParseException pe) {
174               pe.printStackTrace();
175               return false;
176           }
177       }
178




      1.3. Java                                                                                 9
      ECP Service Provider Edition API Documentation, Release 3.3.0



179        private boolean comparePaths(String cookiePath, String targetPath) {
180            if (cookiePath == null) {
181                return true;
182            } else if (cookiePath.equals("/")) {
183                return true;
184            } else if (targetPath.regionMatches(0, cookiePath, 0, cookiePath
185                     .length())) {
186                return true;
187            } else {
188                return false;
189            }
190

191        }
192   }




      10                                                        Chapter 1. About the Code examples
                                                                                                             CHAPTER

                                                                                                                 TWO



                                                                   AUTHENTICATION

     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.


     2.2 Examples

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

 8        //Do some basic client configuration. We need to be able to read and write
 9        //cookies from and to a file.
10        curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
11        curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);
12        curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
13

14        if(strtolower($method) == ’get’){
15

16            //Initialize the authentication GET URL including authentication
17            //parmeters.
18            curl_setopt($client, CURLOPT_HTTPGET, 1);
19            curl_setopt($client, CURLOPT_URL, $base_url.
20            "/modules/hosting/?login=Login&user_name=$username&password=$password");
21        } else {
22

23             //Set up the client to use POST
24             curl_setopt($client, CURLOPT_POST, true);
25             //Initialize the authentication URL



                                                                                                                       11
     ECP Service Provider Edition API Documentation, Release 3.3.0



26             curl_setopt($client, CURLOPT_URL, $base_url.’/modules/hosting/’);
27

28             //Initialize the authentication POST parameters.
29             curl_setopt($client, CURLOPT_POSTFIELDS,
30             "user_name=$username&password=$password&login=Login");
31        }
32

33        //Send the request and read the response code.
34        $response = curl_exec($client);
35        $httpcode = curl_getinfo($client, CURLINFO_HTTP_CODE);
36

37        //Test the result of the authentication attempt.
38        if ($httpcode!=401 && $httpcode!=0)
39            $is_sucess = true;
40        else $is_sucess = false;
41

42        //Close the connection.
43        curl_close($client);
44

45        return $is_sucess;
46   }
47   ?>

     Here is an example of how to establish a connection by sending a GET request.
 1   <?php
 2   require(’authentication.php’);
 3

 4   //Basic connection parameters.
 5   //IP address or host name of the primary ECP node (no trailing slash)
 6   $base_url = ’127.0.0.1’;
 7   //login info
 8   $username = ’customer’;
 9   $password = ’password’;
10

11   //The cookie file used to store the session cookie.
12   $cookies_file = ’cookies.txt’;
13

14   //Authenticate and check for success
15   if (authenticate($base_url, $username, $password, $cookies_file, ’get’)){
16       echo "Authentication sucessful.";
17

18        //Use use the same cookie file for other API calls
19

20   }
21   else{
22       echo "Authentication failed.";
23   }
24   ?>

     Here is an example of how to establish a connection by sending a POST request.
 1   <?php
 2   require(’authentication.php’);
 3

 4   //Basic connection parameters.
 5   //IP address or host name of the primary ECP node (no trailing slash)
 6   $base_url = ’127.0.0.1’;
 7   //login info



     12                                                                               Chapter 2. Authentication
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



 8   $username = ’customer’;
 9   $password = ’password’;
10

11   //The cookie file used to store the session cookie.
12   $cookies_file = ’cookies.txt’;
13

14   //Authenticate and check for success
15   if (authenticate($base_url, $username, $password, $cookies_file)){
16       echo "Authentication sucessful.";
17

18          //Use use the same cookie file for other API calls
19

20   }
21   else{
22       echo "Authentication failed.";
23   }
24   ?>



     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.
 1   from cookielib import CookieJar
 2   from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from urllib2 import build_opener, install_opener, URLError
 4

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

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

20   try:
21

22          #Set up the log in API request. The method is GET by default.
23          req = Request(host + ’/modules/hosting/?login=Login&user_name=’ + \
24                        username + ’&password=’ + password)
25

26          #Send the log in request and get a response
27          response = urlopen(req)
28

29          #Note that this API call can be shortened like this:
30

31          #urlopen(host + ’/modules/hosting/?login=Login&user_name=’ + \
32          #        username + ’&password=’ + password)
33

34          #However, doing so would make it impossible to explicitly access information


     2.2. Examples                                                                                                      13
     ECP Service Provider Edition API Documentation, Release 3.3.0



35          #about the cookies or response later. It is done in other examples because
36          #as long as there is no HTTP error, the log in request was sucessful.
37

38   except (HTTPError, URLError) as exception:
39

40          #Handle errors
41          print "Authentication failed."
42          print exception
43

44   else:
45

46          print "Authenticaiton sucessful."
47

48          #Show the cookies to prove that the request was successful
49          for cookie in my_cookie_jar.make_cookies(response, req):
50              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.
 1   from cookielib import CookieJar
 2   from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from urllib2 import build_opener, install_opener, URLError
 4

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

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

20   try:
21

22          #Set up the log in API request. The method is POST if data is provided.
23          req = Request(host + ’/modules/hosting/’, data = ’login=Login&user_name=’+ \
24                        username + ’&password=’ + password)
25

26          #Send the log in request and get a response
27          response = urlopen(req)
28

29          #Note that this API call can be shortened like this:
30

31          #urlopen(host + ’/modules/hosting/’, data = ’login=Login&user_name=’+ \
32          #        username + ’&password=’ + password)
33

34          #However, doing so would make it impossible to explicitly access information
35          #about the cookies or response later. It is done in other examples because
36          #as long as there is no HTTP error, the log in request was sucessful.
37

38   except (HTTPError, URLError) as exception:



     14                                                                                     Chapter 2. Authentication
                                             ECP Service Provider Edition API Documentation, Release 3.3.0


39

40        #Handle errors
41        print "Authentication failed."
42        print exception
43

44   else:
45

46        print "Authenticaiton sucessful."
47

48        #Show the cookies to prove that the request was successful
49        for cookie in my_cookie_jar.make_cookies(response, req):
50            print cookie



     2.2.3 Java

     Here is an example of how to establish a connection by sending a GET request.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   public class authentication_get {
 4

 5        public static void main(String[] args) throws MalformedURLException {
 6            Client user = new Client();
 7            CookieManager cm = new CookieManager();
 8            error_Handling errorCheck = new error_Handling();
 9            boolean check;
10            String username = "customer";
11            String password = "password";
12            String authentication_message = "";
13            String info_Line = "";
14            int count = 0;
15            URL url = new URL(
16                     "https://127.0.0.1/rest/hosting/network/list/");
17            check = user.initial_Login(cm, username, password);
18            System.out.println(authentication_message);
19            if (check == false) {
20                System.out.println("Authentication Failed");
21            } else {
22                System.out.println("Connected Successfully");
23                System.out.println(" ");
24                do {
25                     info_Line = (user.connectURI(url, cm, count));
26                     if (info_Line != null) {
27                         errorCheck.api_error(info_Line);
28                         count++;
29                     }
30                } while (info_Line != null);
31            }
32        }
33   }

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


     2.2. Examples                                                                                     15
     ECP Service Provider Edition API Documentation, Release 3.3.0


     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.io.IOException;
 2   import java.net.*;
 3

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

 7        public static void ControlVM(Client user, String uri, CookieManager cm)
 8                throws IOException {
 9            String trans_info_Line = "";
10            int count = 0;
11            error_Handling errorCheck = new error_Handling();
12            try {
13                URL url = new URL("https://127.0.0.1/" + uri + "/");
14                trans_info_Line = (user.connectURI(url, cm, count));
15                errorCheck.api_error(trans_info_Line);
16                URLConnection urlConnection = url.openConnection();
17                cm.setCookies(urlConnection);
18                urlConnection.setDoOutput(true);
19                if (urlConnection instanceof HttpURLConnection) {
20                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
21                    httpURLConnection.setRequestMethod("POST");
22                }
23            } catch (RuntimeException exception) {
24                System.out.println("FAIL");
25            }
26        }
27

28        public static void main(String[] args) throws IOException {
29            Client user = new Client();
30            CookieManager cm = new CookieManager();
31            boolean check;
32            String username = "customer";
33            String password = "password";
34            String uri = "rest/hosting/network/list";
35            check = user.initial_Login(cm, username, password);
36            if (check == false) {
37                System.out.println("Authentication Failed");
38            } else {
39                System.out.println("Connected Successfully");
40                System.out.println(" ");
41                ControlVM(user, uri, cm);
42            }
43

44        }
45   }




     16                                                                 Chapter 2. Authentication
                                                                                                          CHAPTER

                                                                                                          THREE



                                                             BILLING – BILLING

Billing functionality.


3.1 Resources

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_data)
          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 exten-
            sion 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.RepBilling


3.2 Representations

3.2.1 RepBilling

class billing.RepBilling
      This is a representation of the virtual machine resource usage for all users of the system.
      Note: The first row in this representation is descriptive of the following rows. In this case, there are three
      hardware profiles. The number corresponding to each hardware profile, for each user row, indicates the number
      of hours that user has consumed the virtual machine resources required by that profile. The last column is disk
      space measured in MB.
      Representation:


                                                                                                                    17
     ECP Service Provider Edition API Documentation, Release 3.3.0



              user,user_uuid,Small,Medium,Large,totalMBytes
              customer1,7eabba12-12fe-11dd-8fd0-0019d2b28af0,0,0,0,0
              customer2,09492bbc-3fd3-11de-82cf-001a929face2,0,3,0,1024



     3.3 Examples

     3.3.1 PHP

     Here is an example of how to display all billing data.
     See Also:
     Authentication function
 1   <html>
 2   <head>
 3       <title>Billing</title>
 4   </head>
 5   <body>
 6       <h1>Billing Summary:</h1>
 7       <?php
 8       require(’authentication.php’);
 9

10        //Basic connection parameters.
11        //IP address or host name of the primary ECP node (no trailing slash)
12        $base_url = ’127.0.0.1’;
13        //login info
14        $username = ’admin’;
15        $password = ’password’;
16

17        //The cookie file used to store the session cookie.
18        $cookies_file = ’cookies.txt’;
19

20        //Initialize and configure the client to make a custom call because the
21        //response for this API is not a json object, but in CSV format.
22        $client = curl_init();
23        curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
24        curl_setopt($client, CURLOPT_COOKIEFILE, $cookies_file);
25        curl_setopt($client, CURLOPT_COOKIEJAR, $cookies_file);
26        curl_setopt($client, CURLOPT_URL, $base_url.’/modules/billingreports/’);
27

28

29        //Authenticate and check for success
30        if (authenticate($base_url, $username, $password, $cookies_file)){
31

32               //Initialize the sample cost dictionary.
33               $cost = array(’Small’=>0.029, ’Medium’=>0.119, ’Large’=>0.239, ’totalMBytes’=>0.001);
34

35

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

39               //Make sure the request was successful.
40               $http_response_code = curl_getinfo($client, CURLINFO_HTTP_CODE);
41

42               if($http_response_code==200){



     18                                                               Chapter 3. billing – Billing
                                       ECP Service Provider Edition API Documentation, Release 3.3.0


 43

 44               //Initialize the CSV response into a usable array.
 45               $billing_array = array_filter(explode("\n", $http_response));
 46               $billing_titles = explode(’,’, array_shift($billing_array));
 47

 48               foreach($billing_array as $row_num=>$row_data){
 49                   $billing_info_line = explode(’,’, $row_data);
 50                   foreach($billing_info_line as $col_num=>$col_data){
 51                       $billing_info[$row_num][$billing_titles[$col_num]] = $col_data;
 52                   }
 53               }
 54

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

 58                   $small_total=$statement[’Small’]*$cost[’Small’];
 59                   $medium_total=$statement[’Medium’]*$cost[’Medium’];
 60                   $large_total=$statement[’Large’]*$cost[’Large’];
 61                   $storage_total=$statement[’totalMBytes’]*$cost[’totalMBytes’];
 62

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

 69                   echo   ’<tr>’;
 70                   echo   ’<td>Small Template</td>’;
 71                   echo   ’<td>$’.$cost[’Small’].’ per hour</td>’;
 72                   echo   ’<td>’.$statement[’Small’].’ hours</td>’;
 73                   echo   ’<td>$’.$small_total.’</td>’;
 74                   echo   ’</tr>’;
 75

 76                   echo   ’<tr>’;
 77                   echo   ’<td>Medium Template</td>’;
 78                   echo   ’<td>$’.$cost[’Medium’].’</td>’;
 79                   echo   ’<td>’.$statement[’Medium’].’ hours</td>’;
 80                   echo   ’<td>$’.$medium_total.’</td>’;
 81                   echo   ’</tr>’;
 82

 83                   echo   ’<tr>’;
 84                   echo   ’<td>Large Template</td>’;
 85                   echo   ’<td>$’.$cost[’Large’].’ per hour</td>’;
 86                   echo   ’<td>’.$statement[’Large’].’ hours</td>’;
 87                   echo   ’<td>$’.$large_total.’</td>’;
 88                   echo   ’</tr>’;
 89

 90                   echo   ’<tr>’;
 91                   echo   ’<td>Storage Monthly Max</td>’;
 92                   echo   ’<td>$’.$cost[’totalMBytes’].’ per MB</td>’;
 93                   echo   ’<td>’.round($statement[’totalMBytes’]/1024, 2).’ GB</td>’;
 94                   echo   ’<td>$’.$storage_total.’</td>’;
 95                   echo   ’</tr>’;
 96

 97                   echo   ’<tr>’;
 98                   echo   ’<td colspan="3">Total: </td>’;
 99                   echo   ’<td>$’.($small_total + $medium_total + $large_total + $storage_total).’</td>’;
100                   echo   ’</tr>’;



      3.3. Examples                                                                              19
      ECP Service Provider Edition API Documentation, Release 3.3.0


101

102                         echo ’</table></div>’;
103

104                   }
105               }
106               else{
107                   echo ’<p>Error: Request failed. HTTP response code: ’.$http_response_code.’</p>’;
108               }
109          }
110          else{
111              echo ’<p>Error: Authentication failed.</p>’;
112          }
113

114          //Close the client.
115          curl_close($client);
116

117       ?>
118   </body>
119   </html>



      3.3.2 Python

      Here is an example of how to display all billing data.
      See Also:
      Cookies
 1    from    cookielib import CookieJar
 2    from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3    from    urllib2 import build_opener, install_opener, URLError
 4    from    csv import reader
 5

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

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

15    #Dollars per hour per machine
16    cost = {
17    ’Small’: 0.029,
18    ’Medium’: 0.119,
19    ’Large’: 0.239
20    }
21    #Dollars per MB
22    storage_cost = 0.0001
23

24    try:
25

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

30           #Set up the request. It is a GET by default when not providing data.


      20                                                               Chapter 3. billing – Billing
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



31       req = Request(host+’/modules/billingreports/’)
32       #Send the request
33       response = urlopen(req)
34

35   except (HTTPError, URLError) as exception:
36

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

40   else:
41

42       #Read the response
43       response_body = response.read()
44

45       #Verify that there was no error
46       if response_body:
47

48           #Format the output nicely
49

50           #This is a way to use the CSV reader for strings even though it is
51           #intended for files
52           report = reader(response_body.split("\n"), delimiter=’,’)
53

54           #The first line contains the names of the various hardware templates
55           #that exist along with some special fields.
56           first_row = report.next()
57

58           #These are shorthand for finding the first element with a given name in
59           #the list. We basically get the indices of the fields that are special.
60           #All other fields are the total number of hours a hardware template was
61           #used.
62           #Remove the fields we know and what’s left is the hardware template
63           #names.
64           user_field = (i for i, field in enumerate(first_row) if \
65                         field == ’user’).next()
66

67           user_uuid_field = (i for i, field in enumerate(first_row) if \
68                         field == ’user_uuid’).next()
69

70           totalMBytes_field = (i for i, field in enumerate(first_row) if \
71                         field == ’totalMBytes’).next()
72

73           #Create a dictionary of the hardware template names so they retain their
74           #keys when information is removed.
75           first_row_dict = dict(zip(xrange(len(first_row)), first_row))
76           del(first_row_dict[user_field])
77           del(first_row_dict[user_uuid_field])
78           del(first_row_dict[totalMBytes_field])
79           htemplate_names = first_row_dict
80

81           for user in report:
82               if user:
83

84                   #Start summing the users’s bill
85                   total_bill = 0
86                   #Convert user to a dictionary so we can manipulate the elements
87                   #more easily
88                   user = dict(zip(xrange(len(user)), user))



     3.3. Examples                                                                            21
      ECP Service Provider Edition API Documentation, Release 3.3.0


 89

 90                         storage_total = storage_cost * int(user[totalMBytes_field])
 91                         total_bill = total_bill + storage_total
 92                         print ’===== ’ + user[user_field] + ’ =====’
 93                         print ’UUID: ’ + user[user_uuid_field]
94                          print ’%20s: %-5s hours x $%-6s = $%s’ % \
 95                                (’Peak storage used’, user[totalMBytes_field], \
 96                                 storage_cost, storage_total)
 97                         print
 98

 99                         #Remove special fields so that only hardware templates are left
100                         del(user[user_field])
101                         del(user[user_uuid_field])
102                         del(user[totalMBytes_field])
103

104                         #Display information about each hardware template’s usage
105                         for key, used in user.items():
106

107                              #Get the price. If it’s unknown make it free.
108                              try:
109                                   price = cost[htemplate_names[key]]
110                              except KeyError:
111                                   price = 0
112

113                              htemplate = htemplate_names[key]
114                              total = price * int(used)
115

116                              #Add the expense to the bill
117                              total_bill = total_bill + total
118

119                             print ’%20s: %-5s hours x $%-6s = $%s’ % \
120                                    (str(htemplate), str(used), str(price), str(total))
121                         print
122                         print ’Total bill: $’ + str(total_bill)
123                         print
124

125        else:
126            #Output the error
127            print "There has been an error getting the billing reports."



      3.3.3 Java

      Here is an example of how to display all billing data.
      See Also:
      Client Class, Cookie Manager Class
 1    import java.net.*;
 2    import java.text.*;
 3

 4    public class modules_billingreports {
 5        // Method will be used to display data for each customer in unique format
 6        public static void DisplayData(String[] values) {
 7            String Customer;
 8            String UUID;
 9            String small_hours;
10            String med_hours;


      22                                                                  Chapter 3. billing – Billing
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



11           String large_hours;
12           Customer = values[0];
13           UUID = values[1];
14           small_hours = values[2];
15           med_hours = values[3];
16           large_hours = values[4];
17           // Calculations done to calculate various costs
18           double totalGB = ((Double.parseDouble(values[5])) / 1024);
19           double usage_cost = ((totalGB * 1024) * 0.001);
20           double sml_cost = (Double.parseDouble(small_hours)) * 0.029;
21           double med_cost = (Double.parseDouble(med_hours)) * 0.119;
22           double large_cost = (Double.parseDouble(large_hours)) * 0.239;
23           double total_cost = usage_cost + sml_cost + med_cost + large_cost;
24           DecimalFormat df = new DecimalFormat("#.##");
25           System.out.println("Billing Statement for:" + Customer);
26           System.out.println("UUID:" + UUID);
27           System.out.println("Small Template:       $0.029/hour Usage: "
28                   + small_hours + " Hours   Cost:$" + df.format(sml_cost));
29           System.out.println("Medium Template:      $0.119/hour Usage: "
30                   + med_hours + " Hours    Cost:$" + df.format(med_cost));
31           System.out.println("Large Template:       $0.239/hour Usage: "
32                   + large_hours + " Hours   Cost:$" + df.format(large_cost));
33           System.out
34                   .println("Storage Monthly Max: $0.001/MB     Amount:"
35                           + Math.round(totalGB) + " GB     Cost:$"
36                           + df.format(usage_cost));
37           System.out.println("Total Cost: $" + df.format(total_cost));
38           System.out.println(" ");
39           System.out.println(" ");
40

41       }
42

43       public static void main(String[] args) throws MalformedURLException {
44           Client user = new Client();
45           CookieManager cm = new CookieManager();
46           boolean check;
47           String username = "admin";
48           String password = "password";
49           String billing_Line = "";
50           String[] split_billing_line = null;
51           int count = 1;
52           URL url = new URL(
53                    "https://127.0.0.1/modules/billingreports/");
54           check = user.initial_Login(cm, username, password);
55           if (check == false) {
56               System.out.println("Authentication Failed");
57           } else {
58               do {
59                    billing_Line = (user.connectURI(url, cm, count));
60                    if (billing_Line != null) {
61                        split_billing_line = billing_Line.split(",");
62                        DisplayData(split_billing_line);
63                    }
64                    count++;
65               } while (billing_Line != null);
66           }
67       }
68   }



     3.3. Examples                                                                            23
ECP Service Provider Edition API Documentation, Release 3.3.0




24                                                              Chapter 3. billing – Billing
                                                                                                      CHAPTER

                                                                                                       FOUR



     CLONE – CLONE VIRTUAL MACHINES.

Virtual machine cloning functionality.


4.1 Resources

4.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.2 Representations

4.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.



                                                                                                           25
     ECP Service Provider Edition API Documentation, Release 3.3.0


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



     4.3 Examples

     4.3.1 PHP

     Here is an example of how to clone powered off virtual machines.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $response = api_request($base_url.’/rest/hosting/clone/’.$uuid.’/’,
24            ’post’, NULL, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($response)){
28

29               echo "<p>Cloning $response[machine_id].</p>";
30

31        }
32        else{
33                echo ’<p>Error: ’.$response.’</p>’;
34        }
35

36   }
37   else{
38       echo "<p>Authentication failed.</p>";
39   }
40

41   ?>


     26                                                              Chapter 4. clone – Clone virtual machines.
                                             ECP Service Provider Edition API Documentation, Release 3.3.0


     4.3.2 Python

     Here is an example of how to clone powered off virtual machines.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #VM to be cloned
17   uuid = ’2c8b1b05-1356-11df-938b-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a POST by default when providing data.
26          req = Request(host + ’/rest/hosting/clone/’+uuid+’/’, data = ’’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47

48               #Output the appropriate message with the appropriate ID upon a
49               #Successful Cloning
50               print ’Cloning started.’
51               print ’UUID of clone: ’ + json[’machine_id’]



     4.3. Examples                                                                                     27
     ECP Service Provider Edition API Documentation, Release 3.3.0



52        else:
53            #Output the error
54            print error



     4.3.3 Java

     Here is an example of how to clone powered off virtual machines.
     See Also:
     Client Class, Cookie Manager Class
 1   import   java.io.DataInputStream;
 2   import   java.io.DataOutputStream;
 3   import   java.io.IOException;
 4   import   java.net.*;
 5

 6   import   org.json.simple.JSONArray;
 7   import   org.json.simple.JSONObject;
 8   import   org.json.simple.parser.JSONParser;
 9   import   org.json.simple.parser.ParseException;
10

11   public class rest_hosting_clone_uuid_post {
12       // Following method will output all information in proper format
13       public static void DisplayData(String clone_Line) {
14           JSONObject json;
15           try {
16               json = (JSONObject) new JSONParser().parse(clone_Line);
17               System.out.println(" ");
18               System.out.println(json.get("message"));
19               System.out.println("Machine id: " + json.get("machine_id"));
20               System.out.println(" ");
21           } catch (ParseException e) {
22

23                   e.printStackTrace();
24               }
25

26        }
27

28        public static void ControlVM(Client user, String uri, String query,
29                String uuid, CookieManager cm) throws IOException {
30            try {
31                URL url = new URL("https://127.0.0.1/" + uri + "/"
32                        + uuid + "/");
33                URLConnection urlConnection = url.openConnection();
34                cm.setCookies(urlConnection);
35                urlConnection.setDoOutput(true);
36                if (urlConnection instanceof HttpURLConnection) {
37                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
38                    httpURLConnection.setUseCaches(false);
39                    httpURLConnection.setDoOutput(true);
40                    httpURLConnection.setDoInput(true);
41                    httpURLConnection.setRequestProperty("Content-Type",
42                            "application/x-www-form-urlencoded");
43                    httpURLConnection.setRequestMethod("POST");
44                    DataOutputStream stream = new DataOutputStream(
45                            httpURLConnection.getOutputStream());
46                    stream.writeBytes(query);


     28                                                             Chapter 4. clone – Clone virtual machines.
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



47                   stream.flush();
48                   stream.close();
49                   DataInputStream dis = new DataInputStream(httpURLConnection
50                           .getInputStream());
51                   String nextline;
52                   while ((nextline = dis.readLine()) != null) {
53                       DisplayData(nextline);
54                   }
55                   dis.close();
56               }
57           } catch (RuntimeException exception) {
58               System.out.println("Failed");
59           }
60       }
61

62       public static void main(String[] args) throws IOException {
63           Client user = new Client();
64           CookieManager cm = new CookieManager();
65           boolean check;
66           String username = "customer";
67           String password = "password";
68           String uuid = "5fd137a3-129b-11df-a61d-000acd1901c5";
69           String uri = "rest/hosting/clone";
70           String query = " ";
71           check = user.initial_Login(cm, username, password);
72           if (check == false) {
73               System.out.println("Authentication Failed");
74           } else {
75               ControlVM(user, uri, query, uuid, cm);
76           }
77

78       }
79   }




     4.3. Examples                                                                            29
ECP Service Provider Edition API Documentation, Release 3.3.0




30                                                  Chapter 4. clone – Clone virtual machines.
                                                                                                        CHAPTER

                                                                                                            FIVE



                            DTEMPLATE – DISK TEMPLATE

Disk template functionality.


5.1 Resources

5.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


5.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




                                                                                                                 31
ECP Service Provider Edition API Documentation, Release 3.3.0



5.2 Representations

5.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}}




32                                                                     Chapter 5. dtemplate – Disk Template
                                               ECP Service Provider Edition API Documentation, Release 3.3.0


    5.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]}



    5.3 Examples

    5.3.1 PHP

    Here is an example of how to list all available disk templates.
    See Also:
    Authentication function, Error handling function, API request function
1   <?php
2   require(’authentication.php’);
3   require(’error_handling.php’);
4   require(’api_request.php’);
5

6   //Basic connection parameters.
7   //IP address or host name of the primary ECP node (no trailing slash)



    5.3. Examples                                                                                        33
     ECP Service Provider Edition API Documentation, Release 3.3.0



 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $disks = api_request($base_url.’/rest/hosting/dtemplate/list/’, ’get’, null,
21            $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($disks)){
25

26               if($disks[’templates’]){
27

28                   //Display all returned disk data.
29                   echo ’<h1>Disk templates:</h1>’;
30                   echo ’<ol>’;
31                   foreach ($disks[’templates’] as $disk){
32                        echo "<li>($disk[uuid]) ".($disk[’size’]/1024)." GB</li>";
33                   }
34                   echo ’</ol>’;
35               }
36               else{
37                   echo ’<p>No disks available.</p>’;
38               }
39        }
40        else{
41             echo ’<p>Error: ’.$disks.’</p>’;
42        }
43

44   }
45   else{
46       echo "<p>Authentication failed.</p>";
47   }
48

49   ?>

     Here is an example of how to get information about a specific disk template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;



     34                                                                       Chapter 5. dtemplate – Disk Template
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/dtemplate/’.$uuid.’/’, ’get’, null, $cookies_file
24

25        //Make sure there was no error returned
26        if(is_array($details)){
27

28               //Display the details.
29               echo ’<h1>Details for disk with UUID:’.$uuid.’</h1>’;
30               echo ’<ul>’;
31               foreach ($details[’dtemplate’] as $key=>$value){
32                    echo "<li>$key=$value</li>";
33               }
34               echo ’</ul>’;
35        }
36        else{
37             echo ’<p>Error: ’.$details.’</p>’;
38        }
39

40   }
41   else{
42       echo "<p>Authentication failed.</p>";
43   }
44

45   ?>



     5.3.2 Python

     Here is an example of how to list all available disk templates.
     See Also:
     Cookies
 1   from   cookielib import CookieJar
 2   from   urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from   urllib2 import build_opener, install_opener, URLError
 4   from   json import loads
 5   from   error import ecp_check_error
 6

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

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


     5.3. Examples                                                                                        35
     ECP Service Provider Edition API Documentation, Release 3.3.0


15

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/dtemplate/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the disk templates
45               for template in json[’templates’]:
46

47                  #Output and remove the name from the dictionary
48                  print
49                  print ’=========== ’ + str(round(template[’size’]/1024, 2)) + \
50                        ’GB ===========’
51                  del(template[’size’])
52

53                  #Output all information
54                  for key in template.keys():
55                      print key + ’ = ’ + str(template[key])
56          else:
57              #Output the error
58              print error

     Here is an example of how to get information about a specific disk template.
     See Also:
     Cookies
1    from    cookielib import CookieJar
2    from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
3    from    urllib2 import build_opener, install_opener, URLError
4    from    json import loads
5    from    error import ecp_check_error
6

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



     36                                                                   Chapter 5. dtemplate – Disk Template
                                                ECP Service Provider Edition API Documentation, Release 3.3.0


 9

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

16   #Disk template to get information about
17   uuid = ’f1648fba-29ce-11de-84a2-001a929face2’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/dtemplate/f1648fba-29ce-11de-84a2-001a929face2/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44              #Format the output nicely
45              #Parse the response into a dictionary
46              json = loads(response_body)
47              #Show information about this template
48              template = json[’dtemplate’]
49

50              #Output and remove the name from the dictionary
51              print ’Information for Disk Drive with UUID: ’+ template[’uuid’]
52              del(template[’uuid’])
53

54              #Output all information
55              for key in template.keys():
56                  print key + ’ = ’ + str(template[key])
57

58          else:
59              #Output the error
60                      print error



     5.3.3 Java

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



     5.3. Examples                                                                                        37
     ECP Service Provider Edition API Documentation, Release 3.3.0


     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.MalformedURLException;
 2   import java.net.URL;
 3

 4   import org.json.simple.JSONArray;
 5   import org.json.simple.JSONObject;
 6   import org.json.simple.parser.JSONParser;
 7

 8   public class rest_hosting_dtemplate_list {
 9

10        public static void DisplayData(String hd_Line) {
11            boolean check = true;
12            int count = 0;
13            JSONObject harddrive_json;
14            System.out.println(" ");
15            System.out.println("Disk Templates)");
16            System.out.println(" ");
17            while (check) {
18                try {
19                    harddrive_json = (JSONObject) new JSONParser().parse(hd_Line);
20                    JSONArray harddrive_obj = (JSONArray) harddrive_json
21                             .get("templates");
22                    JSONObject harddrive_name = (JSONObject) harddrive_obj
23                             .get(count);
24                    // information will be displayed accordingly
25                    System.out.print((count + 1) + ".");
26                    int Size = ((Number) harddrive_name.get("size")).intValue();
27                    System.out.println(Size / 1024 + " GB");
28                    System.out.println("UUID: " + harddrive_name.get("uuid"));
29                    System.out.println(" ");
30                    count++;
31                } catch (Exception e) {
32                    check = false;
33                    break;
34                }
35

36               }
37

38        }
39

40        public static void main(String[] args) throws MalformedURLException {
41            Client user = new Client();
42            CookieManager cm = new CookieManager();
43            error_Handling errorCheck = new error_Handling();
44            boolean check;
45            String disk_Line = "";
46            String username = "admin";
47            String password = "password";
48            int count = 0;
49            URL url = new URL(
50                     "https://127.0.0.1/rest/hosting/dtemplate/list/");
51            check = user.initial_Login(cm, username, password);
52            System.out.println(" ");
53            if (check == false) {
54                System.out.println("Authentication Failed");
55            } else {



     38                                                         Chapter 5. dtemplate – Disk Template
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



56                   do {
57                       disk_Line = (user.connectURI(url, cm, count));
58                       if (disk_Line != null) {
59                           errorCheck.api_error(disk_Line);
60                           DisplayData(disk_Line);
61                           count++;
62                       }
63                   } while (disk_Line != null);
64               }
65        }
66

67   }

     Here is an example of how to get information about a specific disk template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
1    import java.net.MalformedURLException;
2    import java.net.URL;
3

4    import org.json.simple.JSONObject;
5    import org.json.simple.parser.JSONParser;
6

7    public class rest_hosting_dtemplate_uuid_get {
8

9         public static void DisplayData(String hd_Line, String uuid) {
10            JSONObject harddrive_json;
11            System.out.println(" ");
12            System.out.println("Info for Disk Template with UUID: " + uuid);
13            System.out.println(" ");
14            try {
15                harddrive_json = (JSONObject) new JSONParser().parse(hd_Line);
16                JSONObject harddrive_temp = (JSONObject) harddrive_json
17                        .get("dtemplate");
18                // information will be displayed accordingly
19                System.out.println("Disk Size: " + harddrive_temp.get("size"));
20            } catch (Exception e) {
21                System.out.println("Display Error");
22            }
23

24        }
25

26        public static void main(String[] args) throws MalformedURLException {
27            Client user = new Client();
28            CookieManager cm = new CookieManager();
29            error_Handling errorCheck = new error_Handling();
30            boolean check;
31            String disk_Line = "";
32            String username = "admin";
33            String password = "password";
34            String uuid = "5eff7b34-29cf-11de-867d-001a929face2";
35            int count = 0;
36            URL url = new URL(
37                    "https://127.0.0.1/rest/hosting/dtemplate/"
38                            + uuid + "/");
39            check = user.initial_Login(cm, username, password);
40            System.out.println(" ");



     5.3. Examples                                                                                      39
     ECP Service Provider Edition API Documentation, Release 3.3.0



41            if (check == false) {
42                System.out.println("Authentication Failed");
43            } else {
44                do {
45                     disk_Line = (user.connectURI(url, cm, count));
46                     if (disk_Line != null) {
47                         errorCheck.api_error(disk_Line);
48                         DisplayData(disk_Line, uuid);
49                         count++;
50                     }
51                } while (disk_Line != null);
52            }
53        }
54

55   }




     40                                                       Chapter 5. dtemplate – Disk Template
                                                                                                               CHAPTER

                                                                                                                      SIX



                                                                  ERROR HANDLING

     6.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.


     6.2 Examples

     6.2.1 PHP

     Here is an example of how to test a given HTTP response string for errors.                   It is included with re-
     quire(‘error_handling.php’). It is used by the API request function.
     See Also:
     API request function
 1   <?php
 2

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

18   //This function will determine if the specified HTTP response string contains an
19   //error and $error = an error message if it does.



                                                                                                                         41
     ECP Service Provider Edition API Documentation, Release 3.3.0



20   function api_error($http_response){
21

22        //Make sure a response was provided.
23        if(!$http_response){
24            $error = ’No response.’;
25        }
26

27        //Initialize the JSON response.
28        $arr_response = json_decode($http_response, true);
29

30        //Make sure the JSON response was initialized.
31        if(!$arr_response){
32            $error = ’Response cannot be parsed.’;
33        }
34        else {
35

36            //Handle the error code. This function will $error = false on success.
37            switch($arr_response[’errno’]){
38                case ECP_SUCCESS:
39                    $error = false;
40                    break;
41                case ECP_NO_SUCH_MACHINE:
42                    $error = ’No such machine exists.’;
43                    break;
44                case ECP_INVALID_COMMAND:
45                    $error = ’Invalid command.’;
46                    break;
47                case ECP_MISSING_PARAMETER:
48                    $error = ’Missing parameter.’;
49                    break;
50                case ECP_COULD_NOT_CONNECT:
51                    $error = ’Could not connect.’;
52                    break;
53                case ECP_COULD_NOT_RETRIEVE:
54                    $error = ’Could not retrieve the requested information.’;
55                    break;
56                case ECP_COMMAND_FAILED:
57                    $error = ’Command failed.’;
58                    break;
59                case ECP_RESOURCE_LOCKED:
60                    $error = ’Resource locked.’;
61                    break;
62                case ECP_INTERNAL_ERROR:
63                    $error = ’Internal error.’;
64                    break;
65                case ECP_UNKNOWN_PARAMETER:
66                    $error = ’Unknown parameter.’;
67                    break;
68                case ECP_RESOURCE_BUSY:
69                    $error = ’Resource busy.’;
70                    break;
71                case ECP_NAMING_CONFLICT:
72                    $error = ’Naming conflict.’;
73                    break;
74                case ECP_RECURSION_ERROR:
75                    $error = ’Recursion error.’;
76                    break;
77                default:



     42                                                              Chapter 6. Error Handling
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



78                        $error = ’Unknown error.’;
79                        break;
80             }
81             if($error)
82                 $error .= ’ ’. $arr_response[’message’];
83        }
84        return $error;
85   }



     6.2.2 Python

     Here is an example of how to test a given HTTP response string for errors.
 1   #errcodes={
 2   #    ’SUCCESS’                              :   0,
 3   #    ’NO_SUCH_MACHINE’                      :   1,
 4   #    ’INVALID_COMMAND’                      :   2,
 5   #    ’MISSING_PARAMETER’                    :   3,
 6   #    ’COULD_NOT_CONNECT’                    :   4,
 7   #    ’COULD_NOT_RETRIEVE’                   :   5,
 8   #    ’COMMAND_FAILED’                       :   6,
 9   #    ’RESOURCE_LOCKED’                      :   7,
10   #    ’INTERNAL_ERROR’                       :   8,
11   #    ’UNKNOWN_PARAMETER’                    :   9,
12   #    ’RESOURCE_BUSY’                        :   10,
13   #    ’NAMING_CONFLICT’                      :   11,
14   #    ’RECURSION_ERROR’                      :   12
15   #}
16

17   from json import loads
18

19   errcodes=[
20     ’Sucess.’,
21     ’No such machine.’,
22     ’Invalid command.’,
23     ’Missing paramter.’,
24     ’Could not connect.’,
25     ’Could not retrieve.’,
26     ’Command failed.’,
27     ’Resource locked.’,
28     ’Internal error.’,
29     ’Unknown paramter.’,
30     ’Resource busy.’,
31     ’Naming conflic.’,
32     ’Recursion error.’
33   ]
34

35   #Returns the error or False on no error.
36   def ecp_check_error(body):
37       try:
38            #Make sure that the json object can be loaded
39            json = loads(body)
40       except:
41            return ’Response could not be parsed.’
42       else:
43            #If there is no error, return False.
44            if json[’errno’] == 0:


     6.2. Examples                                                                                      43
     ECP Service Provider Edition API Documentation, Release 3.3.0



45                 return False
46             #If not then return the information from errno and the message
47             else:
48                 return errcodes[json[’errno’]] + ’ ’ + json[’message’]



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

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

21        public void api_error(String nextLine) {
22            JSONObject json;
23            try {
24                json = (JSONObject) new JSONParser().parse(nextLine);
25                int errObj = ((Number) json.get("errno")).intValue();
26                switch (errObj) {
27                case error_Handling.SUCCESS:
28                    System.out.println("Successful Connection Established");
29                    break;
30                case error_Handling.NO_SUCH_MACHINE:
31                    System.out.println("Machine does not Exist");
32                    break;
33                case error_Handling.INVALID_COMMAND:
34                    System.out.println("Invalid Command Entered");
35                    break;
36                case error_Handling.MISSING_PARAMETER:
37                    System.out.println("A Parameter is Missing");
38                    break;
39                case error_Handling.COULD_NOT_CONNECT:
40                    System.out.println("Could not Connect");
41                    break;
42                case error_Handling.COULD_NOT_RETRIEVE:
43                    System.out.println("Could not Retrieve Information");
44                    break;
45                case error_Handling.COMMAND_FAILED:
46                    System.out.println("Command Failed");
47                    break;
48                case error_Handling.RESOURCE_LOCKED:


     44                                                                                     Chapter 6. Error Handling
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



49                   System.out.println("the Resource is Locked");
50                   break;
51               case error_Handling.INTERNAL_ERROR:
52                   System.out.println("Internal Error");
53                   break;
54               case error_Handling.UNKNOWN_PARAMETER:
55                   System.out.println("Unknown Parameter Entered");
56                   break;
57               case error_Handling.RESOURCE_BUSY:
58                   System.out.println("The Resource is Busy");
59                   break;
60               case error_Handling.NAMING_CONFLICT:
61                   System.out.println("There is a Naming Conflict");
62                   break;
63               case error_Handling.RECURSION_ERROR:
64                   System.out.println("There is a Naming Conflict");
65                   break;
66               default:
67                   System.out.println("Unknown Error");
68                   break;
69               }
70

71           } catch (ParseException e) {
72

73               e.printStackTrace();
74           }
75       }
76   }




     6.2. Examples                                                                            45
ECP Service Provider Edition API Documentation, Release 3.3.0




46                                                              Chapter 6. Error Handling
                                                                                                      CHAPTER

                                                                                                      SEVEN



                                                                   GROUP – GROUP

Group functionality.


7.1 Resources

7.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.
                Return type group.RepGroup


7.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


                                                                                                               47
ECP Service Provider Edition API Documentation, Release 3.3.0


      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


7.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


7.2 Representations

7.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}




48                                                                                   Chapter 7. group – Group
                                          ECP Service Provider Edition API Documentation, Release 3.3.0


7.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}}



7.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]}


7.2. Representations                                                                                       49
     ECP Service Provider Edition API Documentation, Release 3.3.0



     7.3 Examples

     7.3.1 PHP

     Here is an example of how to list all existing groups.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $arr_groups = api_request($base_url.’/rest/hosting/group/list/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($arr_groups)){
25

26               if($arr_groups[’groups’]){
27

28                   //Display the groups
29                   echo "
30                   <h1>Groups:</h1><table>
31                   <tr>
32                   <td>UUID</td>
33                   <td>Name</td>
34                   <td>Display Name</td>
35                   <td>Created</td>
36                   <td>Users</td>
37                   <td>Quota UUID</td>
38                   </tr>";
39                   foreach ($arr_groups[’groups’] as $group)
40                   {
41                       echo "
42                       <tr>
43                       <td>$group[uuid]</td>
44                       <td>$group[group_name]</td>
45                       <td>$group[display_name]</td>
46                       <td>$group[created]</td>
47                       <td>".implode(’, ’,$group[’users’])."</td>
48                       <td>{$group[’quota’][’uuid’]}</td>



     50                                                                       Chapter 7. group – Group
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



49                       </tr>";
50                   }
51                   echo ’</table>’;
52               }
53               else{
54                   echo ’<p>No groups available.</p>’;
55               }
56        }
57        else{
58             echo ’<p>Error: ’.$arr_groups.’</p>’;
59        }
60

61   }
62   else{
63       echo "<p>Authentication failed.</p>";
64   }
65   ?>

     Here is an example of how to get information about a specific group.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Group to get details of
17   $uuid = ’2a0041e3-d655-11de-ae3d-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/group/’.$uuid.’/’, ’get’,
24            null, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for group with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’group’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;



     7.3. Examples                                                                                      51
     ECP Service Provider Edition API Documentation, Release 3.3.0



36        }
37        else{
38             echo ’<p>Error: ’.$details.’</p>’;
39        }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to udpate a group.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request_debug.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Group to update:
17   $uuid = ’2181b142-217b-11df-bba9-000acd1901c5’;
18   //New information:
19   $groupname = ’updated’;
20   $displayname = ’The Updated Group’;
21   $quota = ’f9b526de-1bf4-11df-b68b-000acd1901c5’;
22

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

26   //Authenticate and check for success
27   if (authenticate($base_url, $username, $password, $cookies_file)){
28

29        //Use use the same cookie file for other API calls
30        $response = api_request($base_url.’/rest/hosting/group/’.$uuid.’/’,
31            ’post’, $data, $cookies_file, ’group’);
32

33        //Make sure there was no error returned
34        if(is_array($response)){
35

36               //Display the new information
37               echo "<p>Updated group with UUID: $uuid</p>";
38               echo ’<ul>’;
39               foreach ($response[’group’] as $key=>$value){
40                    echo "<li>$key=$value</li>";
41               }



     52                                                                       Chapter 7. group – Group
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



42              echo ’</ul>’;
43          }
44          else{
45               echo ’<p>Error: ’.$response.’</p>’;
46          }
47

48   }
49   else{
50       echo "<p>Authentication failed.</p>";
51   }
52

53   ?>



     7.3.2 Python

     Here is an example of how to list all existing groups.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/group/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error


     7.3. Examples                                                                                       53
     ECP Service Provider Edition API Documentation, Release 3.3.0



38        error = ecp_check_error(response_body)
39        if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the groups
45               for group in json[’groups’]:
46

47                   #Output and remove the name from the dictionary
48                   print
49                   print ’=========== ’ + group[’group_name’] + ’ ===========’
50                   del(group[’group_name’])
51

52                   #Output all information
53                   for key in group.keys():
54                       print key + ’ = ’ + str(group[key])
55        else:
56            #Output the error
57            print error



     7.3.3 Java

     Here is an example of how to list all existing groups.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_group_list {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String group_List) {
11           boolean check = true;
12           int count = 0;
13           JSONObject json;
14           try {
15               json = (JSONObject) new JSONParser().parse(group_List);
16               JSONArray group_obj = (JSONArray) json.get("groups");
17               System.out.println(" ");
18               System.out.println("Groups:");
19               while (check) {
20                   try {
21                       JSONObject group_items = (JSONObject) group_obj.get(count);
22                       System.out.println(" ");
23                       System.out.println((count + 1) + ")");
24                       System.out.println("Display Name: "
25                               + group_items.get("display_name"));
26                       System.out.println("Group Name: "
27                               + group_items.get("group_name"));
28                       System.out.println("Date Created: "
29                               + group_items.get("created"));


     54                                                                 Chapter 7. group – Group
                                             ECP Service Provider Edition API Documentation, Release 3.3.0



30                            System.out.println("uuid: " + group_items.get("uuid"));
31                            System.out.println("Users: " + group_items.get("users"));
32                            JSONObject quota_info = (JSONObject) group_items
33                                     .get("quota");
34                            if (quota_info != null) {
35                                System.out.println("Quota: \"" + quota_info.get("name")
36                                         + "\"");
37                            } else {
38                                System.out.println("Quota: No quota exists");
39                            }
40                            count++;
41                        } catch (Exception e) {
42                            check = false;
43                        }
44                   }
45               } catch (ParseException e) {
46

47                   e.printStackTrace();
48               }
49

50        }
51

52        public static void main(String[] args) throws MalformedURLException {
53            Client user = new Client();
54            CookieManager cm = new CookieManager();
55            error_Handling errorCheck = new error_Handling();
56            boolean check;
57            String username = "admin";
58            String password = "password";
59            String authentication_message = "";
60            String info_Line = "";
61            int count = 0;
62            URL url = new URL(
63                    "https://127.0.0.1/rest/hosting/group/list/");
64            check = user.initial_Login(cm, username, password);
65            System.out.println(authentication_message);
66            if (check == false) {
67                System.out.println("Authentication Failed");
68            } else {
69                do {
70                    // will connect to URL and call display method to output all the
71                    // info
72                    info_Line = (user.connectURI(url, cm, count));
73                    if (info_Line != null) {
74                        errorCheck.api_error(info_Line);
75                        DisplayData(info_Line);
76                        count++;
77                    }
78                } while (info_Line != null);
79            }
80        }
81

82   }

     Here is an example of how to get information about a specific group.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class


     7.3. Examples                                                                                     55
     ECP Service Provider Edition API Documentation, Release 3.3.0



 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5   import org.json.simple.parser.ParseException;
 6

 7   public class rest_hosting_group_uuid_get {
 8       // Following method will output all information in proper format
 9       public static void DisplayData(String group_List) {
10           JSONObject json;
11           try {
12               json = (JSONObject) new JSONParser().parse(group_List);
13               System.out.println(" ");
14               System.out.println("Group:");
15               try {
16                   JSONObject group_info = (JSONObject) json.get("group");
17                   System.out.println(" ");
18                   System.out.println("Display Name: "
19                           + group_info.get("display_name"));
20                   System.out.println("Group Name: "
21                           + group_info.get("group_name"));
22                   System.out
23                           .println("Date Created: " + group_info.get("created"));
24                   System.out.println("uuid: " + group_info.get("uuid"));
25                   System.out.println("Users: " + group_info.get("users"));
26               } catch (Exception e) {
27

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

31            } catch (ParseException e) {
32

33                e.printStackTrace();
34            }
35

36        }
37

38        public static void main(String[] args) throws MalformedURLException {
39            Client user = new Client();
40            CookieManager cm = new CookieManager();
41            error_Handling errorCheck = new error_Handling();
42            boolean check;
43            String username = "admin";
44            String password = "password";
45            String authentication_message = "";
46            String info_Line = "";
47            String uuid = "2a0041e3-d655-11de-ae3d-000acd1901c5";
48            int count = 0;
49            URL url = new URL("https://127.0.0.1/rest/hosting/group/"
50                     + uuid + "/");
51            check = user.initial_Login(cm, username, password);
52            System.out.println(authentication_message);
53            if (check == false) {
54                System.out.println("Authentication Failed");
55            } else {
56                do {
57                     // will connect to URL and call display method to output all the
58                     // info



     56                                                               Chapter 7. group – Group
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



59                   info_Line = (user.connectURI(url, cm, count));
60                   if (info_Line != null) {
61                       errorCheck.api_error(info_Line);
62                       DisplayData(info_Line);
63                       count++;
64                   }
65               } while (info_Line != null);
66           }
67       }
68   }




     7.3. Examples                                                                            57
ECP Service Provider Edition API Documentation, Release 3.3.0




58                                                              Chapter 7. group – Group
                                                                                                     CHAPTER

                                                                                                     EIGHT



     HTEMPLATE – HARDWARE TEMPLATE

Hardware template functionality.


8.1 Resources

8.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


8.1.2 HtemplateUUID

class htemplate.HtemplateUUID
      This resource represents a specific hardware template.
      Resource URI:
         /rest/hosting/htemplate/<UUID>/




                                                                                                          59
ECP Service Provider Edition API Documentation, Release 3.3.0


      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 re-
          source URI should be the UUID of the target hardware template.


8.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


8.2 Representations

8.2.1 RepHtemplate

class htemplate.RepHtemplate
      This is a representation of a new hardware template that has been created.
      Representation:




60                                                              Chapter 8. htemplate – Hardware Template
                                         ECP Service Provider Edition API Documentation, Release 3.3.0



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



8.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}}




8.2. Representations                                                                               61
     ECP Service Provider Edition API Documentation, Release 3.3.0


     8.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]}



     8.3 Examples

     8.3.1 PHP

     Here is an example of how to list all available hardware templates.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success


     62                                                                Chapter 8. htemplate – Hardware Template
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $hardware = api_request($base_url.’/rest/hosting/htemplate/list/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($hardware)){
25

26               if($hardware[’templates’]){
27

28                   //Display all returned hardware data.
29                   echo ’<h1>Hardware templates:</h1>’;
30                   echo ’<ol>’;
31                   foreach ($hardware[’templates’] as $_hardware){
32                        echo "<li>($_hardware[uuid]) ";
33                        echo "$_hardware[name]: $_hardware[arch], ";
34                        echo "$_hardware[memory] MB, $_hardware[cpus] CPU(s)</li>";
35                   }
36                   echo ’</ol>’;
37               }
38               else{
39                   echo ’<p>No hardware templates available.</p>’;
40               }
41        }
42        else{
43                echo ’<p>Error: ’.$hardware.’</p>’;
44        }
45

46   }
47   else{
48       echo "<p>Authentication failed.</p>";
49   }
50

51   ?>

     Here is an example of how to get information for a specific hardware template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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



     8.3. Examples                                                                                      63
     ECP Service Provider Edition API Documentation, Release 3.3.0


18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/htemplate/’.$uuid.’/’,
24            ’get’, null, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for hardware template with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’hardware’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;
36        }
37        else{
38                echo ’<p>Error: ’.$details.’</p>’;
39        }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to update a specific hardware template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Hardware template to update:
17   $uuid = ’14c34419-0c34-11df-91fa-000acd1901c5’;
18   //New information:
19   $name        = ’Really Small’;
20   $arch        = ’i686’;
21   $hypervisor = ’kvm-hvm’;
22   $memory      = ’256’;
23   $cpus        = ’2’;
24




     64                                                              Chapter 8. htemplate – Hardware Template
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



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

29   //Authenticate and check for success
30   if (authenticate($base_url, $username, $password, $cookies_file)){
31

32        //Use use the same cookie file for other API calls
33        $response = api_request($base_url.’/rest/hosting/htemplate/’.$uuid.’/’,
34            ’post’, $data, $cookies_file);
35

36        //Make sure there was no error returned
37        if(is_array($response)){
38

39               //Display the new information
40               echo "<p>Updated hardware template with UUID: $uuid</p>";
41               echo ’<ul>’;
42               foreach ($response[’hardware’] as $key=>$value){
43                    echo "<li>$key=$value</li>";
44               }
45               echo ’</ul>’;
46        }
47        else{
48                echo ’<p>Error: ’.$response.’</p>’;
49        }
50

51   }
52   else{
53       echo "<p>Authentication failed.</p>";
54   }
55

56   ?>

     Here is an example of how to delete a specific hardware template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Hardware template to delete
17   $uuid = ’110cccf0-0c79-11df-ba93-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){



     8.3. Examples                                                                                      65
     ECP Service Provider Edition API Documentation, Release 3.3.0


21

22        //Use use the same cookie file for other API calls
23        $result = api_request($base_url.’/rest/hosting/htemplate/’.$uuid.’/’,
24            ’delete’, null, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($result)){
28

29               //The delete was sucessful.
30               echo ’<p>Sucessfully deleted hardware template with UUID: ’.
31                   $uuid.’</p>’;
32        }
33        else{
34             echo ’<p>Error: ’.$result.’</p>’;
35        }
36

37   }
38   else{
39       echo "<p>Authentication failed.</p>";
40   }
41

42   ?>

     Here is an example of how to create a new hardware template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Information about the new hardware tamplate
17   $name        = ’Really Really Small’;
18   $arch        = ’i686’;
19   $hypervisor = ’kvm-hvm’;
20   $memory      = ’128’;
21   $cpus        = ’1’;
22

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

27   //Authenticate and check for success
28   if (authenticate($base_url, $username, $password, $cookies_file)){
29

30        //Use use the same cookie file for other API calls
31        $response = api_request($base_url.’/rest/hosting/htemplate/’, ’put’,


     66                                                              Chapter 8. htemplate – Hardware Template
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



32               $data, $cookies_file);
33

34          //Make sure there was no error returned
35          if(is_array($response)){
36

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

40          }
41          else{
42               echo ’<p>Error: ’.$response.’</p>’;
43          }
44

45   }
46   else{
47       echo "<p>Authentication failed.</p>";
48   }
49

50   ?>



     8.3.2 Python

     Here is an example of how to list all available hardware templates.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/htemplate/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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


     8.3. Examples                                                                                       67
     ECP Service Provider Edition API Documentation, Release 3.3.0


31

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the hardware templates
45               for template in json[’templates’]:
46

47                  #Output and remove the name from the dictionary
48                  print
49                  print ’=========== ’ + template[’name’] + ’ ===========’
50                  del(template[’name’])
51

52                  #Output all information
53                  for key in template.keys():
54                      print key + ’ = ’ + str(template[key])
55          else:
56              #Output the error
57              print error

     Here is an example of how to get information for a specific hardware template.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Hardware template to get information about
17   uuid = ’c2325bcf-14c1-11df-be3e-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.



     68                                                             Chapter 8. htemplate – Hardware Template
                                             ECP Service Provider Edition API Documentation, Release 3.3.0



26        req = Request(host+’/rest/hosting/htemplate/’+uuid+’/’)
27        #Send the request
28        response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37        #Read the response
38        response_body = response.read()
39

40        #Verify that there was no error
41        error = ecp_check_error(response_body)
42        if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47               #Show information about this template
48               template = json[’hardware’]
49

50               #Output and remove the name from the dictionary
51               print ’=========== ’ + template[’name’] + ’ ===========’
52               del(template[’name’])
53

54               #Output all information
55               for key in template.keys():
56                   print key + ’ = ’ + str(template[key])
57

58        else:
59            #Output the error
60            print error

     Here is an example of how to update a specific hardware template.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Hardware template to update
17   uuid = ’3bb17342-11b1-11df-951e-000acd1901c5’



     8.3. Examples                                                                                     69
     ECP Service Provider Edition API Documentation, Release 3.3.0



18   #New information about the hardware template
19   name = ’Python is Awesome!’
20   arch = ’i686’
21   cpus = ’2’
22   hypervisor = ’xen-hvm’
23   memory = ’513’
24   data = ’name=’+name+’&arch=’+arch+’&cpus=’+cpus+\
25          ’&hypervisor=’+hypervisor+’&memory=’+memory
26

27   try:
28

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

33          #Set up the request. It is a POST by default when providing data.
34          req = Request(host + ’/rest/hosting/htemplate/’+uuid+’/’, data = data)
35          #Send the request
36          response = urlopen(req)
37

38   except (HTTPError, URLError) as exception:
39

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

43   else:
44

45          #Read the response
46          response_body = response.read()
47

48          #Verify that there was no error
49          error = ecp_check_error(response_body)
50          if not error:
51

52               #Format the output nicely
53               #Parse the response into a dictionary
54               json = loads(response_body)
55               #Format the output nicely
56               print ’Hardware template sucessfuly updated!’
57               print
58

59               #Show information about this template
60               template = json[’hardware’]
61

62               #Output and remove the name from the dictionary
63               print ’=========== ’ + template[’name’] + ’ ===========’
64               del(template[’name’])
65

66               #Output all information
67               for key in template.keys():
68                   print key + ’ = ’ + str(template[key])
69

70          else:
71              #Output the error
72              print error

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


     70                                                            Chapter 8. htemplate – Hardware Template
                                             ECP Service Provider Edition API Documentation, Release 3.3.0


     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Hardware template to delete
17   uuid = ’c4422c35-11c7-11df-86d7-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/htemplate/’+uuid+’/’)
27          req.get_method = lambda: ’DELETE’
28          #Send the request
29          response = urlopen(req)
30

31   except (HTTPError, URLError) as exception:
32

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

36   else:
37

38          #Read the response
39          response_body = response.read()
40

41          #Verify that there was no error
42          error = ecp_check_error(response_body)
43          if not error:
44

45               print ’Hardware template sucessfuly deleted!’
46

47          else:
48              #Output the error
49              print error

     Here is an example of how to create a new hardware template.
     See Also:
     Cookies
 1   from cookielib import CookieJar
 2   from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor



     8.3. Examples                                                                                     71
     ECP Service Provider Edition API Documentation, Release 3.3.0



 3   from urllib2 import build_opener, install_opener, URLError
 4   from json import loads
 5   from error import ecp_check_error
 6

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

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

16   #Information about the hardware template to be created
17   name = ’Custom Hardware Template’
18   arch = ’i686’
19   cpus = ’1’
20   hypervisor = ’xen-hvm’
21   memory = ’512’
22   data = ’name=’ + name + ’&arch=’ + arch + ’&cpus=’ + cpus + \
23          ’&hypervisor=’ + hypervisor + ’&memory=’ + memory
24

25   try:
26

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

31          #Set up the request. It is a POST by default when providing data.
32          req = Request(host + ’/rest/hosting/htemplate/’, data = data)
33          req.get_method = lambda: ’PUT’
34          #Send the request
35          response = urlopen(req)
36

37   except (HTTPError, URLError) as exception:
38

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

42   else:
43

44          #Read the response
45          response_body = response.read()
46

47          #Verify that there was no error
48          error = ecp_check_error(response_body)
49          if not error:
50

51             #Format the output nicely
52             #Parse the response into a dictionary
53             json = loads(response_body)
54             print ’Hardware template sucessfuly created!’
55             print
56

57             #Show information about this template
58             template = json[’hardware’]
59

60             #Output and remove the name from the dictionary



     72                                                  Chapter 8. htemplate – Hardware Template
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



61               print ’=========== ’ + template[’name’] + ’ ===========’
62               del(template[’name’])
63

64               #Output all information
65               for key in template.keys():
66                   print key + ’ = ’ + str(template[key])
67

68        else:
69            #Output the error
70            print error



     8.3.3 Java

     Here is an example of how to list all available hardware templates.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.MalformedURLException;
 2   import java.net.URL;
 3

 4   import org.json.simple.JSONArray;
 5   import org.json.simple.JSONObject;
 6   import org.json.simple.parser.JSONParser;
 7

 8   public class rest_hosting_htemplate_list {
 9

10        public static void DisplayData(String hdware_Line) {
11            boolean check = true;
12            int count = 0;
13            JSONObject hardware_json;
14            System.out.println(" ");
15            System.out.println("Hardware Templates)");
16            System.out.println(" ");
17            while (check) {
18                try {
19                    hardware_json = (JSONObject) new JSONParser()
20                            .parse(hdware_Line);
21

22                       JSONArray hardware_obj = (JSONArray) hardware_json
23                                .get("templates");
24                       JSONObject hardware_name = (JSONObject) hardware_obj.get(count);
25                       // Information will be displayed accordingly
26                       System.out.println(" ");
27                       System.out.print((count + 1) + ".");
28                       System.out.print("Size:" + hardware_name.get("name") + " ");
29                       System.out.println(":" + hardware_name.get("memory") + " Mb");
30                       System.out.println(hardware_name.get("uuid"));
31                       count++;
32                   } catch (Exception e) {
33                       check = false;
34                       break;
35                   }
36

37               }
38

39        }


     8.3. Examples                                                                                       73
     ECP Service Provider Edition API Documentation, Release 3.3.0


40

41        public static void main(String[] args) throws MalformedURLException {
42            Client user = new Client();
43            CookieManager cm = new CookieManager();
44            error_Handling errorCheck = new error_Handling();
45            boolean check;
46            String hardware_Line = "";
47            String username = "admin";
48            String password = "password";
49            int count = 0;
50            URL url = new URL(
51                     "https://127.0.0.1/rest/hosting/htemplate/list/");
52            check = user.initial_Login(cm, username, password);
53            System.out.println(" ");
54            if (check == false) {
55                System.out.println("Authentication Failed");
56            } else {
57                do {
58                     hardware_Line = (user.connectURI(url, cm, count));
59                     if (hardware_Line != null) {
60                         errorCheck.api_error(hardware_Line);
61                         DisplayData(hardware_Line);
62                         count++;
63                     }
64                } while (hardware_Line != null);
65            }
66

67        }
68   }

     Here is an example of how to get information for a specific hardware template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5

 6   public class rest_hosting_htemplate_uuid_get {
 7       // Following method will output all information in proper format
 8       public static void DisplayData(String hardware_Line, String uuid) {
 9           JSONObject hardware_json;
10           System.out.println(" ");
11           System.out.println("Hardware Template with UUID \"" + uuid + "\":");
12           System.out.println(" ");
13           try {
14               hardware_json = (JSONObject) new JSONParser().parse(hardware_Line);
15               // information will be displayed accordingly
16               JSONObject hardware_info = (JSONObject) hardware_json
17                       .get("hardware");
18               System.out.println("Name: " + hardware_info.get("name"));
19               System.out
20                       .println("Memory: " + hardware_info.get("memory") + " MB");
21               System.out.println("# of CPUS: " + hardware_info.get("cpus"));
22           } catch (Exception e) {
23               System.out.println("Display Error");



     74                                                             Chapter 8. htemplate – Hardware Template
                                             ECP Service Provider Edition API Documentation, Release 3.3.0



24               }
25

26        }
27

28        public static void main(String[] args) throws MalformedURLException {
29            Client user = new Client();
30            CookieManager cm = new CookieManager();
31            error_Handling errorCheck = new error_Handling();
32            boolean check;
33            String username = "admin";
34            String password = "password";
35            String authentication_message = "";
36            String info_Line = "";
37            String uuid = "14c34419-0c34-11df-91fa-000acd1901c5";
38            int count = 0;
39            URL url = new URL(
40                    "https://127.0.0.1/rest/hosting/htemplate/"
41                            + uuid + "/");
42            check = user.initial_Login(cm, username, password);
43            System.out.println(authentication_message);
44            if (check == false) {
45                System.out.println("Authentication Failed");
46            } else {
47                do {
48                    // will connect to URL and call display method to output all the
49                    // info
50                    info_Line = (user.connectURI(url, cm, count));
51                    if (info_Line != null) {
52                        errorCheck.api_error(info_Line);
53                        DisplayData(info_Line, uuid);
54                        count++;
55                    }
56                } while (info_Line != null);
57            }
58        }
59

60   }

     Here is an example of how to update a specific hardware template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import   java.io.DataInputStream;
 2   import   java.io.DataOutputStream;
 3   import   java.io.IOException;
 4   import   java.net.*;
 5

 6   import org.json.simple.JSONObject;
 7   import org.json.simple.parser.JSONParser;
 8

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

12        public static void DisplayData(String hardware_Line, String uuid) {
13            JSONObject hardware_json;
14            System.out.println(" ");
15            System.out.println("Changes made to Hardware Template with UUID \""



     8.3. Examples                                                                                     75
     ECP Service Provider Edition API Documentation, Release 3.3.0



16                    + uuid + "\":");
17            System.out.println(" ");
18            try {
19                hardware_json = (JSONObject) new JSONParser().parse(hardware_Line);
20                // information will be displayed accordingly
21                JSONObject hardware_info = (JSONObject) hardware_json
22                        .get("hardware");
23                System.out.println("Name: " + hardware_info.get("name"));
24                System.out
25                        .println("Memory: " + hardware_info.get("memory") + " MB");
26                System.out.println("# of CPUS: " + hardware_info.get("cpus"));
27            } catch (Exception e) {
28                System.out.println("Display Error");
29            }
30

31        }
32

33        public static void ControlVM(Client user, String uri, String query,
34                String uuid, CookieManager cm) throws IOException {
35            String trans_info_Line = "";
36            int count = 0;
37            error_Handling errorCheck = new error_Handling();
38            try {
39                URL url = new URL("https://127.0.0.1/" + uri + "/"
40                        + uuid + "/");
41                trans_info_Line = (user.connectURI(url, cm, count));
42                errorCheck.api_error(trans_info_Line);
43                URLConnection urlConnection = url.openConnection();
44                cm.setCookies(urlConnection);
45                urlConnection.setDoOutput(true);
46                if (urlConnection instanceof HttpURLConnection) {
47                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
48                    httpURLConnection.setUseCaches(false);
49                    httpURLConnection.setDoOutput(true);
50                    httpURLConnection.setDoInput(true);
51                    httpURLConnection.setRequestProperty("Content-Type",
52                            "application/x-www-form-urlencoded");
53                    httpURLConnection.setRequestMethod("POST");
54                    DataOutputStream stream = new DataOutputStream(
55                            httpURLConnection.getOutputStream());
56                    stream.writeBytes(query);
57                    stream.flush();
58                    stream.close();
59                    DataInputStream dis = new DataInputStream(httpURLConnection
60                            .getInputStream());
61                    String nextline;
62                    while ((nextline = dis.readLine()) != null) {
63                        DisplayData(nextline, uuid);
64                    }
65                    dis.close();
66                }
67            } catch (RuntimeException exception) {
68                System.out.println("FAIL");
69            }
70        }
71

72        public static void main(String[] args) throws IOException {
73            Client user = new Client();



     76                                                  Chapter 8. htemplate – Hardware Template
                                             ECP Service Provider Edition API Documentation, Release 3.3.0



74               CookieManager cm = new CookieManager();
75               error_Handling errorcheck = new error_Handling();
76               boolean check;
77               String username = "admin";
78               String password = "password";
79               String uuid = "7de343d7-1282-11df-973b-000acd1901c5";
80               String uri = "rest/hosting/htemplate";
81               String query = "name=admin_CHECK&arch=i686&hypervisor=kvm-hvm"
82                        + "&memory=128000&cpus=1";
83               check = user.initial_Login(cm, username, password);
84               if (check == false) {
85                   System.out.println("Authentication Failed");
86               } else {
87                   ControlVM(user, uri, query, uuid, cm);
88               }
89

90        }
91   }

     Here is an example of how to delete a specific hardware template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.io.IOException;
 2   import java.net.*;
 3

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

 7        public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
 8                throws IOException {
 9            try {
10                URL url = new URL("https://127.0.0.1/" + uri + "/");
11                URLConnection urlConnection = url.openConnection();
12                cm.setCookies(urlConnection);
13                urlConnection.setDoOutput(true);
14                if (urlConnection instanceof HttpURLConnection) {
15                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
16                    httpURLConnection.setRequestMethod("DELETE");
17                    int responseCode = httpURLConnection.getResponseCode();
18                    if (responseCode != 200) {
19                         System.out.println("DELETE Failed due to a " + responseCode
20                                 + " HTTP error");
21                    } else {
22                         System.out
23                                 .println("Successfully Deleted Hardware Template with UUID: "
24                                         + uuid);
25                    }
26                } else {
27                    throw new IOException("Delete is not supported for ");
28                }
29            } catch (RuntimeException exception) {
30                System.out.println("FAIL");
31            }
32        }
33

34        public static void main(String[] args) throws IOException {



     8.3. Examples                                                                                     77
     ECP Service Provider Edition API Documentation, Release 3.3.0



35               Client user = new Client();
36               CookieManager cm = new CookieManager();
37               boolean check;
38               String username = "admin";
39               String password = "password";
40               String uuid = "01770f7a-1281-11df-802c-000acd1901c5";
41               String uri = "rest/hosting/htemplate/" + uuid;
42               check = user.initial_Login(cm, username, password);
43               if (check == false) {
44                   System.out.println("Authentication Failed");
45               } else {
46                   DeleteNetwork(uuid, uri, cm);
47               }
48

49       }
50   }
51   // }

     Here is an example of how to create a new hardware template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import   java.io.DataInputStream;
 2   import   java.io.DataOutputStream;
 3   import   java.io.IOException;
 4   import   java.net.*;
 5

 6   import org.json.simple.JSONObject;
 7   import org.json.simple.parser.JSONParser;
 8

 9   public class rest_hosting_htemplate_put {
10       // Following method will output all information in proper format
11       public static void DisplayData(String hdware_Line) {
12           JSONObject hardware_json;
13           System.out.println(" ");
14           System.out.println("Hardware Template )");
15           System.out.println(" ");
16           try {
17               System.out.println("CREATED");
18               hardware_json = (JSONObject) new JSONParser().parse(hdware_Line);
19               JSONObject hardware_name = (JSONObject) hardware_json
20                       .get("hardware");
21               // Information will be displayed accordingly
22               System.out.print("Name: " + hardware_name.get("name") + " ");
23               System.out
24                       .println("Memory: " + hardware_name.get("memory") + " Mb");
25               System.out.println("# of CPUS: " + hardware_name.get("cpus"));
26               System.out.println("UUID: " + hardware_name.get("uuid"));
27           } catch (Exception e) {
28               System.out.println("Display Error");
29           }
30

31        }
32

33        public static void CreateHTemp(String uri, String query, CookieManager cm)
34                throws IOException {
35            try {



     78                                                             Chapter 8. htemplate – Hardware Template
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



36               URL url = new URL("https://127.0.0.1/" + uri + "/");
37               URLConnection urlConnection = url.openConnection();
38               error_Handling errorCheck = new error_Handling();
39               cm.setCookies(urlConnection);
40               urlConnection.setDoOutput(true);
41               if (urlConnection instanceof HttpURLConnection) {
42                   final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
43                   httpURLConnection.setUseCaches(false);
44                   httpURLConnection.setDoOutput(true);
45                   httpURLConnection.setDoInput(true);
46                   httpURLConnection.setRequestProperty("Content-Type",
47                           "application/x-www-form-urlencoded");
48                   httpURLConnection.setRequestMethod("PUT");
49                   DataOutputStream stream = new DataOutputStream(
50                           httpURLConnection.getOutputStream());
51                   stream.writeBytes(query);
52                   stream.flush();
53                   stream.close();
54                   DataInputStream dis = new DataInputStream(httpURLConnection
55                           .getInputStream());
56                   String nextline;
57                   while ((nextline = dis.readLine()) != null) {
58                       System.out.println(nextline);
59                       errorCheck.api_error(nextline);
60                       DisplayData(nextline);
61                   }
62                   dis.close();
63               }
64           } catch (RuntimeException exception) {
65               System.out.println("Failed to Create Hardware Template");
66           }
67       }
68

69       public static void main(String[] args) throws IOException {
70           Client user = new Client();
71           CookieManager cm = new CookieManager();
72           error_Handling errorcheck = new error_Handling();
73           boolean check;
74           String username = "admin";
75           String password = "password";
76           String uri = "rest/hosting/htemplate";
77           String query = "name=apii4_htemp&arch=i686&hypervisor=kvm-hvm"
78                   + "&memory=128&cpus=2";
79           check = user.initial_Login(cm, username, password);
80           if (check == false) {
81               System.out.println("Authentication Failed");
82           } else {
83               CreateHTemp(uri, query, cm);
84           }
85

86       }
87   }




     8.3. Examples                                                                            79
ECP Service Provider Edition API Documentation, Release 3.3.0




80                                                  Chapter 8. htemplate – Hardware Template
                                                                                                       CHAPTER

                                                                                                         NINE



                LOG – LOGS AND TRANSACTIONS

Logging and transactional functionality.


9.1 Resources

9.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


9.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




                                                                                                            81
ECP Service Provider Edition API Documentation, Release 3.3.0



9.2 Representations

9.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}



9.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]}




82                                                                      Chapter 9. log – Logs and Transactions
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



     9.3 Examples

     9.3.1 PHP

     Here is an example of how to monitor running transactions.
     See Also:
     Authentication function, Error handling function, API request function
 1   <html>
 2   <head>
 3       <title>Running Transactions</title>
 4       <meta http-equiv="refresh" content="5">
 5   </head>
 6   <body>
 7       <h1>Running Transactions:</h1>
 8

 9        <?php
10        require(’authentication.php’);
11        require(’error_handling.php’);
12        require(’api_request.php’);
13

14        //Basic connection parameters.
15        //IP address or host name of the primary ECP node (no trailing slash)
16        $base_url = ’127.0.0.1’;
17        //login info
18        $username = ’customer’;
19        $password = ’password’;
20

21        //The cookie file used to store the session cookie.
22        $cookies_file = ’cookies.txt’;
23

24        //Authenticate and check for success
25        if (authenticate($base_url, $username, $password, $cookies_file)){
26

27               //Use use the same cookie file for other API calls
28               $transactions = api_request($base_url.’/rest/hosting/log/list/’, ’get’,
29                   null, $cookies_file);
30

31               //Make sure there was no error returned
32               if(is_array($transactions)){
33

34                   //Make sure there are transactions to display and display them.
35                   if($transactions[’transactions’]){
36                       echo ’<h1>Running Transcations:</h1>’;
37                       echo ’<ul>’;
38                       foreach ($transactions[’transactions’] as $transaction){
39                           echo ’<li>’.$transaction[’completion’].
40                               ’% ’.$transaction[’message’].’</li>’;
41                       }
42                       echo ’</ul>’;
43                   }
44                   else{
45                       echo ’<p>No pending transactions.</p>’;
46                   }
47               }
48               else{



     9.3. Examples                                                                                      83
     ECP Service Provider Edition API Documentation, Release 3.3.0



49                     echo ’<p>Error: ’.$transactions.’</p>’;
50               }
51

52        }
53        else{
54            echo "<p>Authentication failed.</p>";
55        }
56        ?>
57

58   </body>
59   </html>

     Here is an example of how to list all logs for the current user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $logs = api_request($base_url.’/rest/hosting/log/list/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($logs)){
25

26               if($logs[’logs’]){
27

28                   //Display the logs
29                   echo ’<h1>Logs:</h1>’;
30                   echo ’<ul>’;
31                   foreach ($logs[’logs’] as $log){
32                       echo ’<li>(’.$log[’uuid’].’) ’.$log[’date’].
33                           ’ -- ’.$log[’message’].’</li>’;
34                   }
35                   echo ’</ul>’;
36               }
37               else{
38                   echo ’<p>No logs available.</p>’;
39               }
40        }
41        else{



     84                                                                  Chapter 9. log – Logs and Transactions
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



42                echo ’<p>Error: ’.$logs.’</p>’;
43        }
44

45   }
46   else{
47       echo "<p>Authentication failed.</p>";
48   }
49   ?>

     Here is an example of how to delete a specific log entry.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Log entry to delete
17   $uuid = ’c9127fc0-0bd9-11df-86c0-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $result = api_request($base_url.’/rest/hosting/log/’.$uuid.’/’,
24            ’delete’, null, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($result)){
28

29               //The delete was sucessful.
30               echo ’<p>Sucessfully deleted log with UUID: ’.
31                   $uuid.’</p>’;
32        }
33        else{
34                echo ’<p>Error: ’.$result.’</p>’;
35        }
36

37   }
38   else{
39       echo "<p>Authentication failed.</p>";
40   }
41

42   ?>




     9.3. Examples                                                                                      85
     ECP Service Provider Edition API Documentation, Release 3.3.0


     9.3.2 Python

     Here is an example of how to monitor running transactions.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6   from    time import sleep
 7

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

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

17   try:
18

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

23   except (HTTPError, URLError) as exception:
24

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

28   else:
29

30          #Monitor transactions until there are none left
31          while True:
32

33               #Clear the screen
34               print ’\n’*24,
35

36               try:
37                      #Set up the request. It is a GET by default when not providing data.
38                      req = Request(host+’/rest/hosting/log/list/’)
39                      #Send the request
40                      response = urlopen(req)
41

42               except (HTTPError, URLError) as exception:
43

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

47               else:
48

49                      #Read the response
50                      response_body = response.read()
51




     86                                                           Chapter 9. log – Logs and Transactions
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



52                   #Verify that there was no error
53                   error = ecp_check_error(response_body)
54

55                   if not error:
56

57                         #Format the output nicely
58                         #Parse the response into a dictionary
59                         json = loads(response_body)
60                         if json[’transactions’]:
61

62                               #Loop through the transactions
63                               for transaction in json[’transactions’]:
64

65                                    #Output info - consult the documentation for what other
66                                    #information is available to be displayed
67                                    print str(transaction[’completion’]) + ’% ’ + \
68                                          str(transaction[’message’])
69

70                         else:
71

72                               print ’No pending transactions.’
73                               #Stop moinitoring transactions
74                               break
75

76                         #Wait 20 seconds before checking again to not put stress on
77                         #the server
78                         sleep(20)
79

80                   else:
81                       #Output the error
82                       print error
83                       #Stop moinitoring transactions
84                       break

     Here is an example of how to list all logs for the current user.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

18          #Log in. More information about this in the authentication example.
19          urlopen(host + ’/modules/hosting/?login=Login&user_name=’ + \



     9.3. Examples                                                                                        87
     ECP Service Provider Edition API Documentation, Release 3.3.0



20                   username + ’&password=’ + password)
21

22        #Set up the request. It is a GET by default when not providing data.
23        req = Request(host+’/rest/hosting/log/list/’)
24        #Send the request
25        response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34        #Read the response
35        response_body = response.read()
36

37        #Verify that there was no error
38        error = ecp_check_error(response_body)
39        if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the logs
45               for log in json[’logs’]:
46

47                   #Somehow distinguish between errors and messages
48                   if log[’error’]:
49                       log[’message’] = "!!! "+log[’message’]+" !!!"
50                   del(log[’error’])
51                   #Output and remove the message from the dictionary.
52                   print
53                   print log[’message’]
54                   print ’---’
55                   del(log[’message’])
56

57                   #Output all information
58                   for key in log.keys():
59                       print key + ’ = ’ + str(log[key])
60        else:
61            #Output the error
62            print error

     Here is an example of how to delete a specific log entry.
     See Also:
     Cookies
1    from    cookielib import CookieJar
2    from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
3    from    urllib2 import build_opener, install_opener, URLError
4    from    json import loads
5    from    error import ecp_check_error
6

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




     88                                                         Chapter 9. log – Logs and Transactions
                                             ECP Service Provider Edition API Documentation, Release 3.3.0



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

16   #Log to delete
17   uuid = ’c3e1055e-159a-11df-9349-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/log/’+uuid+’/’)
27          req.get_method = lambda: ’DELETE’
28          #Send the request
29          response = urlopen(req)
30

31   except (HTTPError, URLError) as exception:
32

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

36   else:
37

38          #Read the response
39          response_body = response.read()
40

41          #Verify that there was no error
42          error = ecp_check_error(response_body)
43          if not error:
44

45               print ’Log sucessfuly deleted!’
46

47          else:
48              #Output the error
49              print error



     9.3.3 Java

     Here is an example of how to monitor running transactions.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
1    import java.net.MalformedURLException;
2    import java.net.URL;
3

4    import    org.json.simple.JSONArray;
5    import    org.json.simple.JSONObject;
6    import    org.json.simple.parser.JSONParser;
7    import    org.json.simple.parser.ParseException;
8

9    public class rest_hosting_log_list_transactions {


     9.3. Examples                                                                                     89
     ECP Service Provider Edition API Documentation, Release 3.3.0



10        // Function will display all the information accordingly
11        public static boolean DisplayData(String transaction_Line) {
12            JSONObject json;
13            boolean trans_Check = true;
14            try {
15

16                json = (JSONObject) new JSONParser().parse(transaction_Line);
17                JSONArray trans_obj = (JSONArray) json.get("transactions");
18                if (trans_obj.size() > 0) {
19                    for (int i = 0; i < trans_obj.size(); i++) {
20                        JSONObject transObjItem = (JSONObject) trans_obj.get(i);
21                        // will output which machines are in transaction if any
22                        // exist
23                        System.out.println(" ");
24                        System.out.println("Machine in queue " + (i + 1) + ")");
25                        System.out.println("completion:"
26                                + transObjItem.get("completion") + "%");
27                        // Following will delay the output screen
28                        try {
29                            Thread.sleep(1500);
30                        } catch (InterruptedException ex) {
31

32                        }
33

34                    }
35                } else {
36                    System.out.println(" ");
37                    System.out.println("No Running Transactions");
38                    trans_Check = false;
39                }
40            } catch (ParseException e) {
41

42                e.printStackTrace();
43            }
44            return trans_Check;
45        }
46

47        public static void main(String[] args) throws MalformedURLException {
48            Client user = new Client();
49            CookieManager cm = new CookieManager();
50            error_Handling errorCheck = new error_Handling();
51            boolean check;
52            boolean trans_Check = true;
53            String authentication_message = "";
54            String trans_info_Line = "";
55            String username = "customer";
56            String password = "password";
57            int count = 0;
58            URL url = new URL(
59                     "https://127.0.0.1/rest/hosting/log/list/");
60            check = user.initial_Login(cm, username, password);
61            System.out.println(authentication_message);
62            // will connect to resource URI and retrieve information
63            if (check == false) {
64                System.out.println("Authentication Failed");
65            } else {
66                trans_info_Line = (user.connectURI(url, cm, count));
67                errorCheck.api_error(trans_info_Line);



     90                                                     Chapter 9. log – Logs and Transactions
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



68                   count = 0;
69                   do {
70                        trans_info_Line = (user.connectURI(url, cm, count));
71                        if (trans_info_Line != null) {
72                            trans_Check = DisplayData(trans_info_Line);
73                            count = 0;
74                        }
75                   } while (trans_info_Line != null && trans_Check != false);
76               }
77        }
78   }

     Here is an example of how to delete a specific log entry.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import   java.io.IOException;
 2   import   java.net.HttpURLConnection;
 3   import   java.net.URL;
 4   import   java.net.URLConnection;
 5

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

 9        public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
10                throws IOException {
11            try {
12                URL url = new URL("https://127.0.0.1/" + uri + "/");
13                URLConnection urlConnection = url.openConnection();
14                cm.setCookies(urlConnection);
15                urlConnection.setDoOutput(true);
16                if (urlConnection instanceof HttpURLConnection) {
17                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
18                    httpURLConnection.setRequestMethod("DELETE");
19                    int responseCode = httpURLConnection.getResponseCode();
20                    if (responseCode != 200) {
21                         System.out.println("DELETE Failed due to a " + responseCode
22                                 + " HTTP error");
23                    } else {
24                         System.out.println("Successfully Deleted log with UUID: "
25                                 + uuid);
26                    }
27                } else {
28                    throw new IOException("Delete is not supported for ");
29                }
30            } catch (RuntimeException exception) {
31                System.out.println("FAIL");
32            }
33        }
34

35        public static void main(String[] args) throws IOException {
36            Client user = new Client();
37            CookieManager cm = new CookieManager();
38            boolean check;
39            String username = "admin";
40            String password = "password";
41            String uuid = "0f695e75-1297-11df-8b9f-000acd1901c5";



     9.3. Examples                                                                                      91
     ECP Service Provider Edition API Documentation, Release 3.3.0



42            String uri = "rest/hosting/log/" + uuid;
43            check = user.initial_Login(cm, username, password);
44            if (check == false) {
45                System.out.println("Authentication Failed");
46            } else {
47                DeleteNetwork(uuid, uri, cm);
48            }
49

50        }
51   }




     92                                                     Chapter 9. log – Logs and Transactions
                                                                                                     CHAPTER

                                                                                                       TEN



                                                    NETWORK – NETWORK

Network functionality.


10.1 Resources

10.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


10.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



                                                                                                          93
ECP Service Provider Edition API Documentation, Release 3.3.0


      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.


10.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


10.2 Representations

10.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}




94                                                                              Chapter 10. network – Network
                                            ECP Service Provider Edition API Documentation, Release 3.3.0


10.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}}



10.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]}



10.3 Examples

10.3.1 PHP

Here is an example of how to list all available virtual networks.
See Also:
Authentication function, Error handling function, API request function


10.3. Examples                                                                                        95
     ECP Service Provider Edition API Documentation, Release 3.3.0



 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $networks = api_request($base_url.’/rest/hosting/network/list/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($networks)){
25

26               if($networks[’networks’]){
27

28                   //Display all returned network data.
29                   echo ’<h1>Networks:</h1>’;
30                   echo ’<ol>’;
31                   foreach ($networks[’networks’] as $network){
32                        echo "<li>($network[uuid]) $network[name] (id: $network[vlan_id])</li>";
33                   }
34                   echo ’</ol>’;
35               }
36               else{
37                   echo ’<p>No networks available.</p>’;
38               }
39        }
40        else{
41             echo ’<p>Error: ’.$networks.’</p>’;
42        }
43

44   }
45   else{
46       echo "<p>Authentication failed.</p>";
47   }
48

49   ?>

     Here is an example of how to get information about a specific virtual network.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);



     96                                                                              Chapter 10. network – Network
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Network to get details of
17   $uuid = ’ff5770a3-e136-11de-a1a2-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/network/’.$uuid.’/’, ’get’,
24            null, $cookies_file, ’network’);
25

26        //Make sure there was no error returned
27        if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for network with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;
36        }
37        else{
38             echo ’<p>Error: ’.$details.’</p>’;
39        }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to delete a specific virtual network.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info



     10.3. Examples                                                                                     97
     ECP Service Provider Edition API Documentation, Release 3.3.0



10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Network to delete
17   $uuid = ’de796154-0c78-11df-9edd-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $result = api_request($base_url.’/rest/hosting/network/’.$uuid.’/’,
24            ’delete’, null, $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($result)){
28

29               //The delete was sucessful.
30               echo ’<p>Sucessfully deleted network with UUID: ’.
31                   $uuid.’</p>’;
32        }
33        else{
34             echo ’<p>Error: ’.$result.’</p>’;
35        }
36

37   }
38   else{
39       echo "<p>Authentication failed.</p>";
40   }
41

42   ?>

     Here is an example of how to create a new virtual network.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Information about the new network
17   $name = ’New Network’;
18   //Used to identify packets on the network. It is important that the network
19   //hardware is configured to allow traffic tagged with this VLAN ID



     98                                                                       Chapter 10. network – Network
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



20   $vlan_id = 6;
21

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

25   //Authenticate and check for success
26   if (authenticate($base_url, $username, $password, $cookies_file)){
27

28          //Use use the same cookie file for other API calls
29          $response = api_request($base_url.’/rest/hosting/network/’, ’put’,
30              $data, $cookies_file);
31

32          //Make sure there was no error returned
33          if(is_array($response)){
34

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

38          }
39          else{
40               echo ’<p>Error: ’.$response.’</p>’;
41          }
42

43   }
44   else{
45       echo "<p>Authentication failed.</p>";
46   }
47

48   ?>



     10.3.2 Python

     Here is an example of how to list all available virtual networks.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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


     10.3. Examples                                                                                       99
     ECP Service Provider Edition API Documentation, Release 3.3.0


21

22         #Set up the request. It is a GET by default when not providing data.
23         req = Request(host+’/rest/hosting/network/list/’)
24         #Send the request
25         response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34         #Read the response
35         response_body = response.read()
36

37         #Verify that there was no error
38         error = ecp_check_error(response_body)
39         if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the networks
45               for network in json[’networks’]:
46

47                  #Output and remove the name from the dictionary.
48                  print
49                  print "=========== " + network[’name’] + " ==========="
50                  del(network[’name’])
51

52                  #Output all information
53                  for key in network.keys():
54                      print key + ’ = ’ + str(network[key])
55         else:
56             #Output the error
57             print error

     Here is an example of how to get information about a specific virtual network.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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




     100                                                                             Chapter 10. network – Network
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



16   #Network to get information about
17   uuid = ’ff5770a3-e136-11de-a1a2-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/network/’+uuid+’/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47               #Show information about this template
48               network = json[’network’]
49

50               #Output and remove the name from the dictionary
51               print
52               print’Information about Network with UUID: ’ + network[’uuid’]
53               del(network[’uuid’])
54

55               #Output all information
56               for key in network.keys():
57                   print key + ’ = ’ + str(network[key])
58

59          else:
60              #Output the error
61                      print error

     Here is an example of how to delete a specific virtual network.
     See Also:
     Cookies
1    from    cookielib import CookieJar
2    from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
3    from    urllib2 import build_opener, install_opener, URLError
4    from    json import loads
5    from    error import ecp_check_error
6




     10.3. Examples                                                                                    101
     ECP Service Provider Edition API Documentation, Release 3.3.0



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

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

16   #Network to delete
17   uuid = ’54903a70-11c2-11df-917f-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/network/’+uuid+’/’)
27          req.get_method = lambda: ’DELETE’
28          #Send the request
29          response = urlopen(req)
30

31   except (HTTPError, URLError) as exception:
32

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

36   else:
37

38          #Read the response
39          response_body = response.read()
40

41          #Verify that there was no error
42          error = ecp_check_error(response_body)
43          if not error:
44

45               print ’Network sucessfuly deleted!’
46

47          else:
48              #Output the error
49              print error

     Here is an example of how to create a new virtual network.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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




     102                                                             Chapter 10. network – Network
                                       ECP Service Provider Edition API Documentation, Release 3.3.0



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

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

22   data = ’name=’ + name + ’&vlan_id=’ + vlan_id
23

24   try:
25

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

30          #Set up the request. It is a POST by default when providing data.
31          req = Request(host + ’/rest/hosting/network/’, data = data)
32          req.get_method = lambda: ’PUT’
33          #Send the request
34          response = urlopen(req)
35

36   except (HTTPError, URLError) as exception:
37

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

41   else:
42

43          #Read the response
44          response_body = response.read()
45

46          #Verify that there was no error
47          error = ecp_check_error(response_body)
48          if not error:
49

50              #Format the output nicely
51              #Parse the response into a dictionary
52              json = loads(response_body)
53              print ’Virtual network sucessfuly created!’
54              print
55

56              #Show information about this network
57              network = json[’network’]
58

59              #Output and remove the name from the dictionary
60              print ’=========== ’ + network[’name’] + ’ ===========’
61              del(network[’name’])
62

63              #Output all information
64              for key in network.keys():
65                  print key + ’ = ’ + str(network[key])
66

67          else:



     10.3. Examples                                                                             103
     ECP Service Provider Edition API Documentation, Release 3.3.0



68               #Output the error
69               print error



     10.3.3 Java

     Here is an example of how to list all available virtual networks.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.MalformedURLException;
 2   import java.net.URL;
 3

 4   import org.json.simple.JSONArray;
 5   import org.json.simple.JSONObject;
 6   import org.json.simple.parser.JSONParser;
 7

 8   public class rest_hosting_network_list {
 9

10         public static void DisplayData(String network_Line) {
11             boolean check = true;
12             int count = 0;
13             JSONObject network_json;
14             System.out.println(" ");
15             System.out.println("Networks)");
16             System.out.println(" ");
17             while (check) {
18                 try {
19                     network_json = (JSONObject) new JSONParser()
20                              .parse(network_Line);
21                     // information will be displayed accordingly
22                     JSONArray network_obj = (JSONArray) network_json
23                              .get("networks");
24                     JSONObject network_name = (JSONObject) network_obj.get(count);
25                     System.out.print((count + 1) + ".");
26                     System.out.println(network_name.get("name"));
27                     System.out.println(network_name.get("uuid"));
28                     count++;
29                 } catch (Exception e) {
30                     check = false;
31                     break;
32                 }
33

34               }
35

36         }
37

38         public static void main(String[] args) throws MalformedURLException {
39             Client user = new Client();
40             CookieManager cm = new CookieManager();
41             error_Handling errorCheck = new error_Handling();
42             boolean check;
43             String network_Line = "";
44             String username = "admin";
45             String password = "password";
46             int count = 0;
47             URL url = new URL(


     104                                                                 Chapter 10. network – Network
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



48                        "https://127.0.0.1/rest/hosting/network/list/");
49               check = user.initial_Login(cm, username, password);
50               System.out.println(" ");
51               if (check == false) {
52                   System.out.println("Authentication Failed");
53               } else {
54                   do {
55                        network_Line = (user.connectURI(url, cm, count));
56                        if (network_Line != null) {
57                            errorCheck.api_error(network_Line);
58                            System.out.println(network_Line);
59                            DisplayData(network_Line);
60                            count++;
61                        }
62                   } while (network_Line != null);
63               }
64        }
65

66   }

     Here is an example of how to get information about a specific virtual network.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5

 6   public class rest_hosting_network_uuid_get {
 7       // Following method will output all information in proper format
 8       public static void DisplayData(String network_Line, String uuid) {
 9           JSONObject network_json;
10           System.out.println(" ");
11           System.out.println("Network with UUID \"" + uuid + "\":");
12           System.out.println(" ");
13           try {
14               network_json = (JSONObject) new JSONParser().parse(network_Line);
15               // information will be displayed accordingly
16               JSONObject network_info = (JSONObject) network_json.get("network");
17               System.out.println("Name: " + network_info.get("name"));
18               System.out.println("UUID: " + network_info.get("uuid"));
19               System.out.println("VLan ID: " + network_info.get("vlan_id"));
20           } catch (Exception e) {
21               System.out.println("Display Error");
22           }
23

24        }
25

26        public static void main(String[] args) throws MalformedURLException {
27            Client user = new Client();
28            CookieManager cm = new CookieManager();
29            error_Handling errorCheck = new error_Handling();
30            boolean check;
31            String username = "admin";
32            String password = "password";
33            String authentication_message = "";



     10.3. Examples                                                                                    105
     ECP Service Provider Edition API Documentation, Release 3.3.0



34               String info_Line = "";
35               String uuid = "4e9d7ba3-11c2-11df-9234-000acd1901c5";
36               int count = 0;
37               URL url = new URL(
38                        "https://127.0.0.1/rest/hosting/network/" + uuid
39                                + "/");
40               check = user.initial_Login(cm, username, password);
41               System.out.println(authentication_message);
42               if (check == false) {
43                   System.out.println("Authentication Failed");
44               } else {
45                   do {
46                        // will connect to URL and call display method to output all the
47                        // info
48                        info_Line = (user.connectURI(url, cm, count));
49                        if (info_Line != null) {
50                            errorCheck.api_error(info_Line);
51                            DisplayData(info_Line, uuid);
52                            count++;
53                        }
54                   } while (info_Line != null);
55               }
56         }
57

58   }

     Here is an example of how to delete a specific virtual network.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.io.IOException;
 2   import java.net.*;
 3

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

 7         public static void DeleteNetwork(String uuid, String uri, CookieManager cm)
 8                 throws IOException {
 9             try {
10                 URL url = new URL("https://127.0.0.1/" + uri + "/");
11                 URLConnection urlConnection = url.openConnection();
12                 cm.setCookies(urlConnection);
13                 urlConnection.setDoOutput(true);
14                 if (urlConnection instanceof HttpURLConnection) {
15                     final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
16                     httpURLConnection.setRequestMethod("DELETE");
17                     int responseCode = httpURLConnection.getResponseCode();
18                     if (responseCode != 200) {
19                          System.out.println("DELETE Failed due to a " + responseCode
20                                  + " HTTP error");
21                     } else {
22                          System.out
23                                  .println("Successfully Deleted network with UUID: "
24                                          + uuid);
25                     }
26                 } else {
27                     throw new IOException("Delete is not supported for ");



     106                                                              Chapter 10. network – Network
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



28                   }
29               } catch (RuntimeException exception) {
30                   System.out.println("FAIL");
31               }
32        }
33

34        public static void main(String[] args) throws IOException {
35            Client user = new Client();
36            CookieManager cm = new CookieManager();
37            boolean check;
38            String username = "admin";
39            String password = "password";
40            String uuid = "66f822d9-176-11df-8849-000acd1901c5";
41            String uri = "rest/hosting/network/" + uuid;
42            check = user.initial_Login(cm, username, password);
43            if (check == false) {
44                System.out.println("Authentication Failed");
45            } else {
46                DeleteNetwork(uuid, uri, cm);
47            }
48

49       }
50   }
51   // }

     Here is an example of how to create a new virtual network.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import   java.io.DataInputStream;
 2   import   java.io.DataOutputStream;
 3   import   java.io.IOException;
 4   import   java.net.*;
 5

 6   import org.json.simple.JSONObject;
 7   import org.json.simple.parser.JSONParser;
 8   import org.json.simple.parser.ParseException;
 9

10   public class rest_hosting_network_put {
11       // Following method will output all information in proper format
12       public static void DisplayData(String network_Line) {
13           JSONObject network_json;
14           boolean exists = true;
15           try {
16               network_json = (JSONObject) new JSONParser().parse(network_Line);
17               System.out.println(" ");
18               int errObj = ((Number) network_json.get("errno")).intValue();
19               if (errObj != 0) {
20                   System.out.println("Failed to Create Network");
21                   System.out.println(network_json.get("message"));
22                   exists = false;
23               }
24               while (exists) {
25                   try {
26                       System.out.println("Network )");
27                       System.out.println(" ");
28                       System.out.println("CREATED");



     10.3. Examples                                                                                    107
     ECP Service Provider Edition API Documentation, Release 3.3.0



29                        JSONObject network_name = (JSONObject) network_json
30                                .get("hardware");
31                        // Information will be displayed accordingly
32                        System.out.print("Name: " + network_name.get("name"));
33                        System.out.println("vlan_id: "
34                                + network_name.get("vlan_id"));
35                        System.out.println("UUID: " + network_name.get("uuid"));
36                    } catch (Exception e) {
37                        System.out.println("Display Error");
38                    }
39                 }
40             } catch (ParseException e) {
41

42                 e.printStackTrace();
43             }
44

45         }
46

47         public static void CreateVM(String uri, String query, CookieManager cm)
48                 throws IOException {
49             try {
50                 URL url = new URL("https://127.0.0.1/" + uri + "/");
51                 URLConnection urlConnection = url.openConnection();
52                 cm.setCookies(urlConnection);
53                 urlConnection.setDoOutput(true);
54                 if (urlConnection instanceof HttpURLConnection) {
55                     final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
56                     httpURLConnection.setUseCaches(false);
57                     httpURLConnection.setDoOutput(true);
58                     httpURLConnection.setDoInput(true);
59                     httpURLConnection.setRequestProperty("Content-Type",
60                             "application/x-www-form-urlencoded");
61                     httpURLConnection.setRequestMethod("PUT");
62                     DataOutputStream stream = new DataOutputStream(
63                             httpURLConnection.getOutputStream());
64                     stream.writeBytes(query);
65                     stream.flush();
66                     stream.close();
67                     DataInputStream dis = new DataInputStream(httpURLConnection
68                             .getInputStream());
69                     String nextline;
70                     while ((nextline = dis.readLine()) != null) {
71                         System.out.println(nextline);
72                         DisplayData(nextline);
73                     }
74                     dis.close();
75                     // System.out.println("Great Success");
76                 }
77             } catch (RuntimeException exception) {
78                 System.out.println("FAIL");
79             }
80         }
81

82         public static void main(String[] args) throws IOException {
83             Client user = new Client();
84             CookieManager cm = new CookieManager();
85             boolean check;
86             String username = "admin";



     108                                                             Chapter 10. network – Network
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



87           String password = "password";
88           String uri = "rest/hosting/network";
89           String query = "name=test6&vlan_id=5";
90           check = user.initial_Login(cm, username, password);
91           if (check == false) {
92               System.out.println("Authentication Failed");
93           } else {
94               CreateVM(uri, query, cm);
95           }
96

97       }
98   }




     10.3. Examples                                                                          109
ECP Service Provider Edition API Documentation, Release 3.3.0




110                                                             Chapter 10. network – Network
                                                                                                   CHAPTER

                                                                                                   ELEVEN



            PTEMPLATE – PACKAGE TEMPLATE

Package template functionality.


11.1 Resources

11.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


11.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




                                                                                                        111
     ECP Service Provider Edition API Documentation, Release 3.3.0



     11.2 Representations

     11.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}



     11.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]



     11.3 Examples

     11.3.1 PHP

     Here is an example of how to list all available package templates.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19         //Use use the same cookie file for other API calls



     112                                                              Chapter 11. ptemplate – Package Template
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



20        $packages = api_request($base_url.’/rest/hosting/ptemplate/list/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($packages)){
25

26               if($packages[’packages’]){
27

28                   //Display all returned package (appliance) data.
29                   echo ’<h1>Appliances:</h1>’;
30                   echo ’<ol>’;
31                   foreach ($packages[’packages’] as $package){
32                       echo "<li>($package[uuid]) $package[name]: $package[description]</li>";
33                   }
34                   echo ’</ol>’;
35               }
36               else{
37                   echo ’<p>No networks available.</p>’;
38               }
39        }
40        else{
41                echo ’<p>Error: ’.$packages.’</p>’;
42        }
43

44   }
45   else{
46       echo "<p>Authentication failed.</p>";
47   }
48

49   ?>

     Here is an example of how to get the details for a specific package template.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls



     11.3. Examples                                                                                    113
     ECP Service Provider Edition API Documentation, Release 3.3.0



23          $details = api_request($base_url.’/rest/hosting/ptemplate/’.$uuid.’/’,
24              ’get’, null, $cookies_file);
25

26          //Make sure there was no error returned
27          if(is_array($details)){
28

29                 //Display the details.
30                 echo ’<h1>Details for appliance with UUID:’.$uuid.’</h1>’;
31                 echo ’<ul>’;
32                 foreach ($details[’package’] as $key=>$value){
33                      echo "<li>$key=$value</li>";
34                 }
35                 echo ’</ul>’;
36          }
37          else{
38                  echo ’<p>Error: ’.$details.’</p>’;
39          }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>



     11.3.2 Python

     Here is an example of how to list all available package templates.
     See Also:
     Cookies
 1   from       cookielib import CookieJar
 2   from       urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from       urllib2 import build_opener, install_opener, URLError
 4   from       json import loads
 5   from       error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/ptemplate/list/’)
24          #Send the request
25          response = urlopen(req)


     114                                                              Chapter 11. ptemplate – Package Template
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the package templates
45               for template in json[’packages’]:
46

47                   #Output and remove the name from the dictionary
48                   print
49                   print ’=========== ’ + template[’name’] + ’ ===========’
50                   del(template[’name’])
51

52                   #Output all information
53                   for key in template.keys():
54                       print key + ’ = ’ + str(template[key])
55          else:
56              #Output the error
57              print error

     Here is an example of how to get the details for a specific package template.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

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

19   try:
20




     11.3. Examples                                                                                    115
     ECP Service Provider Edition API Documentation, Release 3.3.0



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

25         #Set up the request. It is a GET by default when not providing data.
26         req = Request(host+’/rest/hosting/ptemplate/’+uuid+’/’)
27         #Send the request
28         response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37         #Read the response
38         response_body = response.read()
39

40         #Verify that there was no error
41         error = ecp_check_error(response_body)
42         if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47               #Show information about this template
48               template = json[’package’]
49

50               #Output and remove the name from the dictionary
51               print
52               print ’Information about Appliance with UUID: ’ + template[’uuid’]
53               del(template[’uuid’])
54

55               #Output all information
56               for key in template.keys():
57                   print key + ’ = ’ + str(template[key])
58

59         else:
60             #Output the error
61                     print error



     11.3.3 Java

     Here is an example of how to list all available package templates.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
1    import java.net.MalformedURLException;
2    import java.net.URL;
3

4    import org.json.simple.JSONArray;
5    import org.json.simple.JSONObject;
6    import org.json.simple.parser.JSONParser;
7

8    public class rest_hosting_ptemplate_list {


     116                                                              Chapter 11. ptemplate – Package Template
                                    ECP Service Provider Edition API Documentation, Release 3.3.0


 9

10       public static void DisplayData(String package_Line) {
11           boolean check = true;
12           int count = 0;
13           JSONObject package_json;
14           System.out.println(" ");
15           System.out.println("Appliances)");
16           System.out.println(" ");
17           while (check) {
18               try {
19                   package_json = (JSONObject) new JSONParser()
20                            .parse(package_Line);
21                   JSONArray package_obj = (JSONArray) package_json
22                            .get("packages");
23                   JSONObject pack_name = (JSONObject) package_obj.get(count);
24                   // Information will be displayed accordingly
25                   System.out.print((count + 1) + ".");
26                   System.out.print("Name:" + pack_name.get("name") + " ");
27                   System.out.print("....OS:" + pack_name.get("os") + " ");
28                   System.out.print("....Description:"
29                            + ((String) pack_name.get("description")).replaceAll(
30                                    "\n", " ") + " ");
31                   System.out.print("....Storage:" + pack_name.get("storage")
32                            + " ");
33                   System.out.print("....UUID:" + pack_name.get("uuid") + " ");
34                   System.out.println(" ");
35                   count++;
36

37               } catch (Exception e) {
38                   check = false;
39                   break;
40               }
41

42           }
43       }
44

45       public static void main(String[] args) throws MalformedURLException {
46           Client user = new Client();
47           CookieManager cm = new CookieManager();
48           error_Handling errorCheck = new error_Handling();
49           boolean check;
50           String package_Line = "";
51           String username = "admin";
52           String password = "password";
53           int count = 0;
54           URL url = new URL(
55                   "https://127.0.0.1/rest/hosting/ptemplate/list/");
56           check = user.initial_Login(cm, username, password);
57           System.out.println(" ");
58           if (check == false) {
59               System.out.println("Authentication Failed");
60           } else {
61               do {
62                    package_Line = (user.connectURI(url, cm, count));
63                    if (package_Line != null) {
64                        errorCheck.api_error(package_Line);
65                        DisplayData(package_Line);
66                        count++;



     11.3. Examples                                                                          117
     ECP Service Provider Edition API Documentation, Release 3.3.0



67                       }
68                   } while (package_Line != null);
69               }
70

71         }
72   }

     Here is an example of how to get the details for a specific package template.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5

 6   public class rest_hosting_ptemplate_uuid_get {
 7       // Following method will output all information in proper format
 8       public static void DisplayData(String package_Line, String uuid) {
 9           JSONObject package_json;
10           System.out.println(" ");
11           System.out.println("Appliance with UUID \"" + uuid + "\":");
12           System.out.println(" ");
13           try {
14               package_json = (JSONObject) new JSONParser().parse(package_Line);
15               JSONObject pack_name = (JSONObject) package_json.get("package");
16               // Information will be displayed accordingly
17               System.out.print("Name:" + pack_name.get("name") + " ");
18               System.out.print("....OS:" + pack_name.get("os") + " ");
19               System.out.print("....Description:"
20                       + ((String) pack_name.get("description")).replaceAll("\n",
21                               " ") + " ");
22               System.out.print("....Storage:" + pack_name.get("storage") + " ");
23               System.out.print("....UUID:" + pack_name.get("uuid") + " ");
24               System.out.println(" ");
25           } catch (Exception e) {
26               System.out.println("Display Error");
27           }
28       }
29

30         public static void main(String[] args) throws MalformedURLException {
31             Client user = new Client();
32             CookieManager cm = new CookieManager();
33             error_Handling errorCheck = new error_Handling();
34             boolean check;
35             String username = "admin";
36             String password = "password";
37             String authentication_message = "";
38             String info_Line = "";
39             String uuid = "74e70ff3-0124-11df-8483-000acd1901c5";
40             int count = 0;
41             URL url = new URL(
42                     "https://127.0.0.1/rest/hosting/ptemplate/"
43                             + uuid + "/");
44             check = user.initial_Login(cm, username, password);
45             System.out.println(authentication_message);
46             if (check == false) {



     118                                                             Chapter 11. ptemplate – Package Template
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



47               System.out.println("Authentication Failed");
48           } else {
49               do {
50                    // will connect to URL and call display method to output all the
51                    // info
52                    info_Line = (user.connectURI(url, cm, count));
53                    if (info_Line != null) {
54                        errorCheck.api_error(info_Line);
55                        DisplayData(info_Line, uuid);
56                        count++;
57                    }
58               } while (info_Line != null);
59           }
60       }
61

62   }




     11.3. Examples                                                                          119
ECP Service Provider Edition API Documentation, Release 3.3.0




120                                                 Chapter 11. ptemplate – Package Template
                                                                                                      CHAPTER

                                                                                                     TWELVE



                                 QUOTA – RESOURCE QUOTA

Virtual machine resource quota functionality.


12.1 Resources

12.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


12.1.2 QuotaUUID

class quota.QuotaUUID
      This resource represens a specific virtual machine resource quota.
      Resource URI:
         /rest/hosting/quota/<UUID>/




                                                                                                          121
ECP Service Provider Edition API Documentation, Release 3.3.0


      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.


12.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.
                Parameters


122                                                                   Chapter 12. quota – Resource Quota
                                          ECP Service Provider Edition API Documentation, Release 3.3.0


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


12.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


12.2 Representations

12.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}



12.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}}




12.2. Representations                                                                                          123
     ECP Service Provider Edition API Documentation, Release 3.3.0


     12.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]}



     12.3 Examples

     12.3.1 PHP

     Here is an example of how to list all available quotas.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19         //Use use the same cookie file for other API calls
20         $arr_quotas = api_request($base_url.’/rest/hosting/quota/list/’, ’get’,
21             null, $cookies_file);
22

23         //Make sure there was no error returned
24         if(is_array($arr_quotas)){
25

26               if($arr_quotas[’quotas’]){
27

28                   //Display all returned quotas.
29                   echo "
30                   <h1>Quotas:</h1><table>
31                   <tr>
32                   <td>UUID</td>
33                   <td>Name</td>
34                   <td>VMs</td>
35                   <td>CPUs</td>


     124                                                                      Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



36                   <td>Memory</td>
37                   <td>Storage</td>
38                   </tr>";
39                   foreach ($arr_quotas[’quotas’] as $quota){
40                       echo "
41                       <tr>
42                       <td>$quota[uuid]</td>
43                       <td>$quota[name]</td>
44                       <td>$quota[max_vms]</td>
45                       <td>$quota[max_cpus]</td>
46                       <td>$quota[max_memory]</td>
47                       <td>$quota[max_storage]</td>
48                       </tr>";
49                   }
50                   echo ’</table>’;
51               }
52               else{
53                   echo ’<p>No quotas available.</p>’;
54               }
55        }
56        else{
57                echo ’<p>Error: ’.$arr_quotas.’</p>’;
58        }
59

60   }
61   else{
62       echo "<p>Authentication failed.</p>";
63   }
64

65   ?>

     Here is an example of how to get information about a specific quota.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Quota to get details of
17   $uuid = ’29ff6978-d655-11de-8904-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls



     12.3. Examples                                                                                    125
     ECP Service Provider Edition API Documentation, Release 3.3.0



23         $details = api_request($base_url.’/rest/hosting/quota/’.$uuid.’/’, ’get’,
24             null, $cookies_file);
25

26         //Make sure there was no error returned
27         if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for quota with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’quota’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;
36         }
37         else{
38                 echo ’<p>Error: ’.$details.’</p>’;
39         }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to delete a specific quota.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Quota to delete
17   $uuid = ’fd91ba6b-0b85-11df-bd65-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22         //Use use the same cookie file for other API calls
23         $result = api_request($base_url.’/rest/hosting/quota/’.$uuid.’/’,
24             ’delete’, null, $cookies_file);
25

26         //Make sure there was no error returned
27         if(is_array($result)){
28




     126                                                                      Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



29               //The delete was sucessful.
30               echo ’<p>Sucessfully deleted quota with UUID: ’.
31                   $uuid.’</p>’;
32        }
33        else{
34             echo ’<p>Error: ’.$result.’</p>’;
35        }
36

37   }
38   else{
39       echo "<p>Authentication failed.</p>";
40   }
41

42   ?>

     Here is an example of how to create a new quota.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Information about the new quota
17   $name = ’Custom Quota’;
18   $max_vms = 10;
19   $max_cpus = 15;
20   $max_memory = 25*1024;//MB
21   $max_storage = 300*1024;//MB
22

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

27   //Authenticate and check for success
28   if (authenticate($base_url, $username, $password, $cookies_file)){
29

30        //Use use the same cookie file for other API calls
31        $response = api_request($base_url.’/rest/hosting/quota/’, ’put’,
32            $data, $cookies_file);
33

34        //Make sure there was no error returned
35        if(is_array($response)){
36

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




     12.3. Examples                                                                                    127
     ECP Service Provider Edition API Documentation, Release 3.3.0



39         }
40         else{
41              echo ’<p>Error: ’.$response.’</p>’;
42         }
43

44   }
45   else{
46       echo "<p>Authentication failed.</p>";
47   }
48

49   ?>

     Here is an example of how to check what the quota for a group is.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22         //Use use the same cookie file for other API calls
23         $details = api_request($base_url.’/rest/hosting/quota/group/’.$uuid.’/’,
24             ’get’, null, $cookies_file);
25

26         //Make sure there was no error returned
27         if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details of the quota for group with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’quota’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;
36         }
37         else{
38                 echo ’<p>Error: ’.$details.’</p>’;
39         }
40

41   }



     128                                                                      Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to change the quota for a group.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Group to update:
17   $uuid = ’28ce4a1c-0088-11df-a8ef-000acd1901c5’;
18   //Set this quota:
19   $quota = ’bb8baec5-0087-11df-95a3-000acd1901c5’;
20

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

24   //Authenticate and check for success
25   if (authenticate($base_url, $username, $password, $cookies_file)){
26

27        //Use use the same cookie file for other API calls
28        $response = api_request($base_url.’/rest/hosting/quota/group/’.$uuid.’/’,
29            ’post’, $data, $cookies_file);
30

31        //Make sure there was no error returned
32        if(is_array($response)){
33

34               //Display the new information
35               echo "<p>Changed quota of group with UUID: $uuid</p>";
36               echo ’<ul>’;
37               foreach ($response[’quota’] as $key=>$value){
38                    echo "<li>$key=$value</li>";
39               }
40               echo ’</ul>’;
41        }
42        else{
43                echo ’<p>Error: ’.$response.’</p>’;
44        }
45

46   }
47   else{



     12.3. Examples                                                                                    129
     ECP Service Provider Edition API Documentation, Release 3.3.0



48          echo "<p>Authentication failed.</p>";
49   }
50

51   ?>



     12.3.2 Python

     Here is an example of how to list all available quotas.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/quota/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the quotas
45               for quota in json[’quotas’]:


     130                                                       Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


46

47                  #Output and remove the name from the dictionary.
48                  print
49                  print "=========== " + quota[’name’] + " ==========="
50                  del(quota[’name’])
51

52                  #Output all information
53                  for key in quota.keys():
54                      print key + ’ = ’ + str(quota[key])
55          else:
56              #Output the error
57              print error

     Here is an example of how to get information about a specific quota.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #UUID of Quota to get information about
17   uuid = ’bb8baec5-0087-11df-95a3-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/quota/’+uuid+’/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error



     12.3. Examples                                                                                    131
     ECP Service Provider Edition API Documentation, Release 3.3.0



41          error = ecp_check_error(response_body)
42          if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47               #Show information about this template
48               quota = json[’quota’]
49

50               #Output and remove the name from the dictionary
51               print
52               print ’Information about Quota with UUID: ’+ quota[’uuid’]
53               del(quota[’uuid’])
54

55               #Output all information
56               for key in quota.keys():
57                   print key + ’ = ’ + str(quota[key])
58

59          else:
60              #Output the error
61                      print error

     Here is an example of how to delete a specific quota.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Quota to delete
17   uuid = ’7fce172b-172b-11df-ae5f-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/quota/’+uuid+’/’)
27          req.get_method = lambda: ’DELETE’
28          #Send the request
29          response = urlopen(req)
30

31   except (HTTPError, URLError) as exception:



     132                                                       Chapter 12. quota – Resource Quota
                                             ECP Service Provider Edition API Documentation, Release 3.3.0


32

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

36   else:
37

38          #Read the response
39          response_body = response.read()
40

41          #Verify that there was no error
42          error = ecp_check_error(response_body)
43          if not error:
44

45               print ’Quota sucessfuly deleted!’
46

47          else:
48              #Output the error
49              print error

     Here is an example of how to create a new quota.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/quota/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response



     12.3. Examples                                                                                   133
     ECP Service Provider Edition API Documentation, Release 3.3.0



35         response_body = response.read()
36

37         #Verify that there was no error
38         error = ecp_check_error(response_body)
39         if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the quotas
45               for quota in json[’quotas’]:
46

47                   #Output and remove the name from the dictionary.
48                   print
49                   print "=========== " + quota[’name’] + " ==========="
50                   del(quota[’name’])
51

52                   #Output all information
53                   for key in quota.keys():
54                       print key + ’ = ’ + str(quota[key])
55         else:
56             #Output the error
57             print error



     12.3.3 Java

     Here is an example of how to list all available quotas.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_quota_list {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String quota_List) {
11           boolean check = true;
12           int count = 0;
13           int storage_GB = 0;
14           int memory_GB = 0;
15           JSONObject json;
16           try {
17               json = (JSONObject) new JSONParser().parse(quota_List);
18               JSONArray quota_obj = (JSONArray) json.get("quotas");
19               System.out.println(" ");
20               System.out.println("Quotas:");
21               while (check) {
22                   try {
23                       JSONObject quota_items = (JSONObject) quota_obj.get(count);
24                       storage_GB = (((Number) quota_items.get("max_storage"))
25                               .intValue()) / 1000;
26                       memory_GB = (((Number) quota_items.get("max_memory"))


     134                                                        Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



27                                     .intValue()) / 1000;
28                            System.out.println(" ");
29                            System.out.println((count + 1) + ")");
30                            System.out.println("Name: " + quota_items.get("name"));
31                            System.out.println("Maximum # of Virtual Machines: "
32                                     + quota_items.get("max_vms"));
33                            System.out.println("Maximum Amount of Storage: "
34                                     + storage_GB + " GB");
35                            System.out.println("uuid: " + quota_items.get("uuid"));
36                            System.out.println("Maximum Amount of memory: " + memory_GB
37                                     + " GB");
38                            System.out.println("Maximum # of CPUs: "
39                                     + quota_items.get("max_cpus"));
40                            count++;
41                        } catch (Exception e) {
42                            check = false;
43                        }
44                 }
45             } catch (ParseException e) {
46

47                  e.printStackTrace();
48             }
49

50        }
51

52        public static void main(String[] args) throws MalformedURLException {
53            Client user = new Client();
54            CookieManager cm = new CookieManager();
55            error_Handling errorCheck = new error_Handling();
56            boolean check;
57            String username = "admin";
58            String password = "password";
59            String authentication_message = "";
60            String info_Line = "";
61            int count = 0;
62            URL url = new URL(
63                    "https://127.0.0.1/rest/hosting/quota/list/");
64            check = user.initial_Login(cm, username, password);
65            System.out.println(authentication_message);
66            if (check == false) {
67                System.out.println("Authentication Failed");
68            } else {
69                do {
70                    // will connect to URL and call display method to output all the
71                    // info
72                    info_Line = (user.connectURI(url, cm, count));
73                    if (info_Line != null) {
74                        errorCheck.api_error(info_Line);
75                        DisplayData(info_Line);
76                        count++;
77                    }
78                } while (info_Line != null);
79            }
80        }
81

82   }

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


     12.3. Examples                                                                                    135
     ECP Service Provider Edition API Documentation, Release 3.3.0


     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5   import org.json.simple.parser.ParseException;
 6

 7   public class rest_hosting_quota_uuid_get {
 8           // Following method will output all information in proper format
 9           public static void DisplayData(String quota_Called) {
10                   int storage_GB = 0;
11                   int memory_GB = 0;
12                   JSONObject json;
13                   try {
14                           json = (JSONObject) new JSONParser().parse(quota_Called);
15                           System.out.println(" ");
16                           System.out.println("Quota:");
17                           try {
18                                   JSONObject quota_info = (JSONObject) json.get("quota");
19                                   storage_GB = (((Number) quota_info.get("max_storage"))
20                                                   .intValue()) / 1000;
21                                   memory_GB = (((Number) quota_info.get("max_memory")).intValue()) / 10
22                                   System.out.println("        Name: " + quota_info.get("name"));
23                                   System.out.println("        Maximum # of Virtual Machines: "
24                                                   + quota_info.get("max_vms"));
25                                   System.out.println("        Maximum Amount of Storage: " + storage_GB
26                                                   + " GB");
27                                   System.out.println("        Maximum Amount of memory: " + memory_GB
28                                                   + " GB");
29                                   System.out.println("        Maximum # of CPUs: "
30                                                   + quota_info.get("max_cpus"));
31                           } catch (Exception e) {
32

33                                           System.out
34                                                              .println("A field that was called does not exist or t
35                                                                              + "quota with the specified uuid does
36                                 }
37

38                       } catch (ParseException e) {
39

40                                 e.printStackTrace();
41                       }
42

43               }
44

45               public static void main(String[] args) throws MalformedURLException {
46                       Client user = new Client();
47                       CookieManager cm = new CookieManager();
48                       error_Handling errorCheck = new error_Handling();
49                       boolean check;
50                       String username = "admin";
51                       String password = "password";
52                       String authentication_message = "";
53                       String info_Line = "";
54                       String uuid = "29ff6978-d655-11de-8904-000acd1901c5";
55                       int count = 0;



     136                                                             Chapter 12. quota – Resource Quota
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



56                        URL url = new URL("https://127.0.0.1/rest/hosting/quota/"
57                                         + uuid + "/");
58                        check = user.initial_Login(cm, username, password);
59                        System.out.println(authentication_message);
60                        if (check == false) {
61                                 System.out.println("Authentication Failed");
62                        } else {
63                                 do {
64                                         // will connect to URL and call display method to output all the
65                                         // info
66                                         info_Line = (user.connectURI(url, cm, count));
67                                         if (info_Line != null) {
68                                                 errorCheck.api_error(info_Line);
69                                                 DisplayData(info_Line);
70                                                 count++;
71                                         }
72                                 } while (info_Line != null);
73                        }
74               }
75   }

     Here is an example of how to delete a specific quota.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.io.IOException;
 2   import java.net.*;
 3

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

 7        public static void DeleteQuota(String uuid, String uri, CookieManager cm)
 8                throws IOException {
 9            try {
10                URL url = new URL("https://127.0.0.1/" + uri + "/"
11                         + uuid + "/");
12                URLConnection urlConnection = url.openConnection();
13                cm.setCookies(urlConnection);
14                urlConnection.setDoOutput(true);
15                if (urlConnection instanceof HttpURLConnection) {
16                    final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
17                    httpURLConnection.setRequestMethod("DELETE");
18                    int responseCode = httpURLConnection.getResponseCode();
19                    if (responseCode != 200) {
20                         System.out.println("DELETE Failed due to a " + responseCode
21                                 + " HTTP error");
22                    } else {
23                         System.out.println("Successfully Deleted quota with UUID: "
24                                 + uuid);
25                    }
26                } else {
27                    throw new IOException("Delete is not supported for ");
28                }
29            } catch (RuntimeException exception) {
30                System.out.println("FAIL");
31            }
32        }



     12.3. Examples                                                                                    137
     ECP Service Provider Edition API Documentation, Release 3.3.0


33

34         public static void main(String[] args) throws IOException {
35             Client user = new Client();
36             CookieManager cm = new CookieManager();
37             boolean check;
38             String username = "admin";
39             String password = "password";
40             String uuid = "dfe93166-11b1-11df-bfef-000acd1901c5";
41             String uri = "rest/hosting/quota";
42             check = user.initial_Login(cm, username, password);
43             if (check == false) {
44                 System.out.println("Authentication Failed");
45             } else {
46                 DeleteQuota(uuid, uri, cm);
47             }
48

49         }
50   }

     Here is an example of how to create a new quota.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import    java.io.DataInputStream;
 2   import    java.io.DataOutputStream;
 3   import    java.io.IOException;
 4   import    java.net.*;
 5

 6   import org.json.simple.JSONObject;
 7   import org.json.simple.parser.JSONParser;
 8   import org.json.simple.parser.ParseException;
 9

10   public class rest_hosting_quota_uuid_put {
11       // Following method will output all information in proper format
12       public static void DisplayData(String quota_Called) {
13           int storage_GB = 0;
14           int memory_GB = 0;
15           JSONObject json;
16           try {
17               json = (JSONObject) new JSONParser().parse(quota_Called);
18               System.out.println(" ");
19               System.out.println("Quota:");
20               try {
21                   JSONObject quota_info = (JSONObject) json.get("quota");
22                   storage_GB = (((Number) quota_info.get("max_storage"))
23                            .intValue()) / 1000;
24                   memory_GB = (((Number) quota_info.get("max_memory")).intValue()) / 1000;
25                   System.out.println("     Name: " + quota_info.get("name"));
26                   System.out.println("     Maximum # of Virtual Machines: "
27                            + quota_info.get("max_vms"));
28                   System.out.println("     Maximum Amount of Storage: " + storage_GB
29                            + " GB");
30                   System.out.println("     Maximum Amount of memory: " + memory_GB
31                            + " GB");
32                   System.out.println("     Maximum # of CPUs: "
33                            + quota_info.get("max_cpus"));
34               } catch (Exception e) {



     138                                                        Chapter 12. quota – Resource Quota
                                     ECP Service Provider Edition API Documentation, Release 3.3.0


35

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

41           } catch (ParseException e) {
42

43               e.printStackTrace();
44           }
45

46       }
47

48       public static void CreateQuota(String uri, String query, CookieManager cm)
49               throws IOException {
50           error_Handling errorCheck = new error_Handling();
51           try {
52               URL url = new URL("https://127.0.0.1/" + uri + "/");
53               URLConnection urlConnection = url.openConnection();
54               cm.setCookies(urlConnection);
55               urlConnection.setDoOutput(true);
56               if (urlConnection instanceof HttpURLConnection) {
57                   final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
58                   httpURLConnection.setUseCaches(false);
59                   httpURLConnection.setDoOutput(true);
60                   httpURLConnection.setDoInput(true);
61                   httpURLConnection.setRequestMethod("PUT");
62                   httpURLConnection.setRequestProperty("Content-Type",
63                           "application/x-www-form-urlencoded");
64                   DataOutputStream stream = new DataOutputStream(
65                           httpURLConnection.getOutputStream());
66                   stream.writeBytes(query);
67                   stream.flush();
68                   stream.close();
69                   DataInputStream dis = new DataInputStream(httpURLConnection
70                           .getInputStream());
71                   String nextline;
72                   while ((nextline = dis.readLine()) != null) {
73                       errorCheck.api_error(nextline);
74                       DisplayData(nextline);
75                   }
76                   dis.close();
77                   System.out.println(" ");
78                   System.out.println("Quota Successfully Created");
79               }
80           } catch (RuntimeException exception) {
81               System.out.println("FAIL");
82           }
83       }
84

85       public static void main(String[] args) throws IOException {
86           Client user = new Client();
87           CookieManager cm = new CookieManager();
88           boolean check;
89           String username = "admin";
90           String password = "password";
91           String uri = "rest/hosting/quota";
92           String query = "name=TestQuota4&max_vms=10&max_cpus=30&max_memory=160000&max_storage=120000";



     12.3. Examples                                                                           139
      ECP Service Provider Edition API Documentation, Release 3.3.0



 93             check = user.initial_Login(cm, username, password);
 94             if (check == false) {
 95                 System.out.println("Authentication Failed");
 96             } else {
 97                 CreateQuota(uri, query, cm);
 98             }
 99

100         }
101   }




      140                                                       Chapter 12. quota – Resource Quota
                                                                                                      CHAPTER

                                                                                                    THIRTEEN



                                                                       TAG – TAGGING

Virtual machine tagging functionality.


13.1 Resources

13.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.
                  Parameters
                     • tag – The comma-separated list of tags to create.
                  Return type tag.RepTag
      See Also:
      vm


13.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.


                                                                                                             141
ECP Service Provider Edition API Documentation, Release 3.3.0


            Note: This resource requires create permission on the elastic_hosting extension module.
                  Return type tag.RepTagList
      See Also:
      vm


13.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


13.2 Representations

13.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]}



13.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.




142                                                                                     Chapter 13. tag – Tagging
                                               ECP Service Provider Edition API Documentation, Release 3.3.0


           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]}



     13.3 Examples

     13.3.1 PHP

     Here is an example of how to view all tags for the current user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request_debug.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $arr_tags = api_request($base_url.’/rest/hosting/vm/tag/list/’, ’get’, null,
21            $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($arr_tags)){
25

26               if($arr_tags[’tags’]){
27

28                   echo "Tags: ".implode(’, ’, $arr_tags[’tags’]);
29

30               }
31               else{
32                   echo ’<p>No tags created.</p>’;
33               }
34        }
35        else{



     13.3. Examples                                                                                     143
     ECP Service Provider Edition API Documentation, Release 3.3.0



36                 echo ’<p>Error: ’.$arr_tags.’</p>’;
37         }
38

39   }
40   else{
41       echo "<p>Authentication failed.</p>";
42   }
43

44   ?>

     Here is an example of how to view all tags for a specific VM.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Virtual machine UUID
17   $uuid = ’d3ee2bfa-0dd1-11df-890f-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22         //Use use the same cookie file for other API calls
23         $arr_tags = api_request($base_url.’/rest/hosting/vm/’.$uuid.’/tag/list/’,
24             ’get’, null, $cookies_file);
25

26         //Make sure there was no error returned
27         if(is_array($arr_tags)){
28

29               if($arr_tags[’tags’]){
30

31                    echo "Tags: ".implode(’, ’, $arr_tags[’tags’]);
32

33               }
34               else{
35                   echo ’<p>No tags for this VM.</p>’;
36               }
37         }
38         else{
39                 echo ’<p>Error: ’.$arr_tags.’</p>’;
40         }
41

42   }
43   else{



     144                                                                      Chapter 13. tag – Tagging
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



44        echo "<p>Authentication failed.</p>";
45   }
46

47   ?>

     Here is an example of how to add a tag or a comma separated list of tags to a virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request_debug.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

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

20   $data = "tag=$tag";
21

22   //Authenticate and check for success
23   if (authenticate($base_url, $username, $password, $cookies_file)){
24

25        //Use use the same cookie file for other API calls
26        $arr_tags = api_request($base_url.’/rest/hosting/vm/’.$uuid.’/tag/’, ’put’,
27            $data, $cookies_file);
28

29        //Make sure there was no error returned
30        if(is_array($arr_tags)){
31

32               if($arr_tags[’tags’]){
33

34                   echo "Tags added sucessfully. Current tags: ".
35                       implode(’, ’, $arr_tags[’tags’]);
36

37               }
38               else{
39                   echo ’<p>No tags for this VM.</p>’;
40               }
41        }
42        else{
43                echo ’<p>Error: ’.$arr_tags.’</p>’;
44        }
45

46   }
47   else{
48       echo "<p>Authentication failed.</p>";



     13.3. Examples                                                                                     145
     ECP Service Provider Edition API Documentation, Release 3.3.0



49   }
50

51   ?>

     Here is an example of how to remove a tag from a virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request_debug.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //VM for which to delete a tag
17   $uuid = ’cf5827f0-10ea-11df-a7ad-000acd1901c5’;
18   //The name of the tag
19   $tag = ’new’;
20

21   //Authenticate and check for success
22   if (authenticate($base_url, $username, $password, $cookies_file)){
23

24         //Use use the same cookie file for other API calls
25         $result = api_request($base_url.’/rest/hosting/vm/’.$uuid.’/tag/’.$tag.’/’,
26             ’delete’, null, $cookies_file);
27

28         //Make sure there was no error returned
29         if(is_array($result)){
30

31               //The delete was sucessful.
32               echo ’<p>Sucessfully deleted tag for virtual machine with UUID: ’.
33                   $uuid.’Current tags: ’.implode(’, ’, $result[’tags’]);
34         }
35         else{
36                 echo ’<p>Error: ’.$result.’</p>’;
37         }
38

39   }
40   else{
41       echo "<p>Authentication failed.</p>";
42   }
43

44   ?>



     13.3.2 Python

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


     146                                                                      Chapter 13. tag – Tagging
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/vm/tag/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the tags
45               for tag in json[’tags’]:
46

47                   #Output each tag on a new line
48                   print "- "+tag
49          else:
50              #Output the error
51              print error

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



     13.3. Examples                                                                                    147
     ECP Service Provider Edition API Documentation, Release 3.3.0


     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

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

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/vm/’+ uuid +’/tag/list/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44             #Format the output nicely
45             #Parse the response into a dictionary
46             json = loads(response_body)
47

48             #Loop through the tags
49             for tag in json[’tags’]:
50

51                   #Output each tag on a new line
52                   print "- "+tag
53          else:
54              #Output the error
55              print error

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


     148                                                                                  Chapter 13. tag – Tagging
                                          ECP Service Provider Edition API Documentation, Release 3.3.0


     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Information about the virtual machine to be tagged
17   uuid = ’fa87dc66-1353-11df-840e-000acd1901c5’
18   tag = ’tag’; #can be a comma separated list
19

20   data = ’tag=’ + tag
21

22   try:
23

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

28          #Set up the request. It is a POST by default when providing data.
29          req = Request(host + ’/rest/hosting/vm/’ + uuid + ’/tag/’, data = data)
30          req.get_method = lambda: ’PUT’
31          #Send the request
32          response = urlopen(req)
33

34   except (HTTPError, URLError) as exception:
35

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

39   else:
40

41          #Read the response
42          response_body = response.read()
43

44          #Verify that there was no error
45          error = ecp_check_error(response_body)
46          if not error:
47

48               #Format the output nicely
49               #Parse the response into a dictionary
50               json = loads(response_body)
51               print ’Virtual Machine sucessfuly tagged!’
52               print
53               print ’Current tags: ’
54

55               #Loop through the tags



     13.3. Examples                                                                                149
     ECP Service Provider Edition API Documentation, Release 3.3.0



56               for tag in json[’tags’]:
57

58                   #Output each tag on a new line
59                   print "- "+tag
60

61         else:
62             #Output the error
63             print error



     13.3.3 Java

     Here is an example of how to view all tags for the current user.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import    org.json.simple.JSONArray;
 4   import    org.json.simple.JSONObject;
 5   import    org.json.simple.parser.JSONParser;
 6   import    org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_vm_tag_list {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String tag_List) {
11           boolean check = true;
12           int count = 0;
13           JSONObject json;
14           try {
15               json = (JSONObject) new JSONParser().parse(tag_List);
16               JSONArray tag_obj = (JSONArray) json.get("tags");
17               System.out.println(" ");
18               System.out.println("Tags:");
19               while (check) {
20                   try {
21                       if (tag_obj != null) {
22                            System.out.println(" -" + tag_obj.get(count));
23                       }
24                       count++;
25                   } catch (Exception e) {
26                       check = false;
27                   }
28               }
29           } catch (ParseException e) {
30

31                   e.printStackTrace();
32               }
33

34         }
35

36         public static void main(String[] args) throws MalformedURLException {
37             Client user = new Client();
38             CookieManager cm = new CookieManager();
39             error_Handling errorCheck = new error_Handling();
40             boolean check;
41             String username = "customer";


     150                                                                Chapter 13. tag – Tagging
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



42               String password = "password";
43               String authentication_message = "";
44               String info_Line = "";
45               int count = 0;
46               URL url = new URL(
47                        "https://127.0.0.1/rest/hosting/vm/tag/list/");
48               check = user.initial_Login(cm, username, password);
49               System.out.println(authentication_message);
50               if (check == false) {
51                   System.out.println("Authentication Failed");
52               } else {
53                   do {
54                        // will connect to URL and call display method to output all the
55                        // info
56                        info_Line = (user.connectURI(url, cm, count));
57                        if (info_Line != null) {
58                            errorCheck.api_error(info_Line);
59                            DisplayData(info_Line);
60                            count++;
61                        }
62                   } while (info_Line != null);
63               }
64        }
65

66   }

     Here is an example of how to view all tags for a specific VM.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_vm_uuid_tag_list {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String tag_List, String uuid) {
11           boolean check = true;
12           int count = 0;
13           JSONObject json;
14           try {
15               json = (JSONObject) new JSONParser().parse(tag_List);
16               JSONArray tag_obj = (JSONArray) json.get("tags");
17               System.out.println(" ");
18               System.out.println("Tags for Machine with UUID \"" + uuid + "\":");
19               while (check) {
20                   try {
21                       if (tag_obj != null) {
22                            System.out.println(" -" + tag_obj.get(count));
23                       }
24                       count++;
25                   } catch (Exception e) {
26                       check = false;
27                   }



     13.3. Examples                                                                                    151
     ECP Service Provider Edition API Documentation, Release 3.3.0



28                   }
29               } catch (ParseException e) {
30

31                   e.printStackTrace();
32               }
33

34         }
35

36         public static void main(String[] args) throws MalformedURLException {
37             Client user = new Client();
38             CookieManager cm = new CookieManager();
39             error_Handling errorCheck = new error_Handling();
40             boolean check;
41             String username = "customer";
42             String password = "password";
43             String authentication_message = "";
44             String info_Line = "";
45             String uuid = "1809404a-12cf-11df-8e89-000acd1901c5";
46             int count = 0;
47             URL url = new URL("https://127.0.0.1/rest/hosting/vm/"
48                     + uuid + "/tag/list/");
49             check = user.initial_Login(cm, username, password);
50             System.out.println(authentication_message);
51             if (check == false) {
52                 System.out.println("Authentication Failed");
53             } else {
54                 do {
55                     // will connect to URL and call display method to output all the
56                     // info
57                     info_Line = (user.connectURI(url, cm, count));
58                     if (info_Line != null) {
59                         errorCheck.api_error(info_Line);
60                         DisplayData(info_Line, uuid);
61                         count++;
62                     }
63                 } while (info_Line != null);
64             }
65         }
66

67   }

     Here is an example of how to add a tag or a comma separated list of tags to a virtual machine.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
     Here is an example of how to remove a tag from a virtual machine.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
1    import    java.io.DataInputStream;
2    import    java.io.DataOutputStream;
3    import    java.io.IOException;
4    import    java.net.*;
5

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



     152                                                                                  Chapter 13. tag – Tagging
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



 8   import org.json.simple.parser.ParseException;
 9

10   public class rest_hosting_vm_uuid_tag_put {
11       // Following method will output all information in proper format
12       public static void DisplayData(String vm_tag, String uuid) {
13           JSONObject json;
14           try {
15               json = (JSONObject) new JSONParser().parse(vm_tag);
16               int errObj = ((Number) json.get("errno")).intValue();
17               if (errObj != 0) {
18                   System.out.println(json.get("message"));
19               } else {
20                   System.out
21                            .println("Successfully added tags to machine with UUID \""
22                                    + uuid + "\"");
23               }
24           } catch (ParseException e) {
25

26               e.printStackTrace();
27           }
28       }
29

30       public static void CreateQuota(String uri, String uuid, String query,
31               CookieManager cm) throws IOException {
32           try {
33               error_Handling errorCheck = new error_Handling();
34               URL url = new URL("https://127.0.0.1/" + uri + "/");
35               URLConnection urlConnection = url.openConnection();
36               cm.setCookies(urlConnection);
37               urlConnection.setDoOutput(true);
38               if (urlConnection instanceof HttpURLConnection) {
39                   final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
40                   httpURLConnection.setUseCaches(false);
41                   httpURLConnection.setDoOutput(true);
42                   httpURLConnection.setDoInput(true);
43                   httpURLConnection.setRequestProperty("Content-Type",
44                           "application/x-www-form-urlencoded");
45                   httpURLConnection.setRequestMethod("PUT");
46                   DataOutputStream stream = new DataOutputStream(
47                           httpURLConnection.getOutputStream());
48                   stream.writeBytes(query);
49                   stream.flush();
50                   stream.close();
51                   DataInputStream dis = new DataInputStream(httpURLConnection
52                           .getInputStream());
53                   String nextline;
54                   while ((nextline = dis.readLine()) != null) {
55                       errorCheck.api_error(nextline);
56                       System.out.println(" ");
57                       DisplayData(nextline, uuid);
58                   }
59                   dis.close();
60               }
61           } catch (RuntimeException exception) {
62               System.out.println("FAIL");
63           }
64       }
65




     13.3. Examples                                                                          153
     ECP Service Provider Edition API Documentation, Release 3.3.0



66         public static void main(String[] args) throws IOException {
67             Client user = new Client();
68             CookieManager cm = new CookieManager();
69             boolean check;
70             String username = "customer";
71             String password = "password";
72             String uuid = "1809404a-12cf-11df-8e89-000acd1901c5";
73             String uri = "rest/hosting/vm/" + uuid + "/tag";
74             String query = "tag=ne,tet,nt";
75             check = user.initial_Login(cm, username, password);
76             if (check == false) {
77                 System.out.println("Authentication Failed");
78             } else {
79                 CreateQuota(uri, uuid, query, cm);
80             }
81

82         }
83   }




     154                                                                 Chapter 13. tag – Tagging
                                                                                                 CHAPTER

                                                                                          FOURTEEN



                                           INTERFACE – INTERFACE

Network interface functionality.


14.1 Resources

14.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.


14.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.




                                                                                                         155
ECP Service Provider Edition API Documentation, Release 3.3.0


14.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


14.2 Representations

14.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}



14.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]




156                                                                     Chapter 14. interface – Interface
                                                                                           CHAPTER

                                                                                          FIFTEEN



                                                        ISOFILE – ISO FILES

Viewing the available ISO files.


15.1 Resources

15.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


15.2 Representations

15.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:




                                                                                               157
ECP Service Provider Edition API Documentation, Release 3.3.0



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




158                                                             Chapter 15. isofile – ISO Files
                                                                                                     CHAPTER

                                                                                                  SIXTEEN



                 CDMOUNT – MOUNTING CDS/DVDS

Mounting virtual CDs/DVDs on the virtual machines.


16.1 Resources

16.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


16.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.


                                                                                                            159
ECP Service Provider Edition API Documentation, Release 3.3.0


                  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


16.2 Representations

16.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}}




160                                                            Chapter 16. cdmount – Mounting CDs/DVDs
                                                                                                        CHAPTER

                                                                                              SEVENTEEN



                         DISK – ADDITIONAL STORAGE

Adding storage with additional virtual hard drives.


17.1 Resources

17.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


17.1.2 VMDiskUUID

class disk.VMDiskUUID
      This resource represents a specific disk.
      Resource URI::




                                                                                                               161
ECP Service Provider Edition API Documentation, Release 3.3.0



           /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


17.2 Representations

17.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}}




162                                                                   Chapter 17. disk – Additional Storage
                                                                                                        CHAPTER

                                                                                                      EIGHTEEN



                                  USAGE – VIRTUAL MACHINE
                                         RESOURCE USAGE

Virtual machine resource usage functionality.


18.1 Resources

18.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


18.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




                                                                                                            163
     ECP Service Provider Edition API Documentation, Release 3.3.0



     18.2 Representations

     18.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}}



     18.3 Examples

     18.3.1 PHP

     Here is an example of how to check the usage for the current user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19         //Use use the same cookie file for other API calls
20         $arr_usage = api_request($base_url.’/rest/hosting/usage/’, ’get’,
21             null, $cookies_file);
22

23         //Make sure there was no error returned
24         if(is_array($arr_usage)){
25

26               if($arr_usage){
27

28                   //Display all usage info
29                   echo "
30                   <h1>Usage:</h1><table>
31                   <tr>
32                   <td>Usage</td>


     164                                                   Chapter 18. usage – Virtual Machine Resource Usage
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



33                   <td>Used</td>
34                   <td>Total</td>
35                   </tr>";
36                   foreach ($arr_usage[’usage’] as $usage=>$info){
37                       echo "
38                       <tr>
39                       <td>$usage</td>
40                       <td>$info[used]</td>
41                       <td>$info[available]</td>
42                       </tr>";
43                   }
44                   echo ’</table>’;
45               }
46               else{
47                   echo ’<p>No quotas available.</p>’;
48               }
49        }
50        else{
51                echo ’<p>Error: ’.$arr_usage.’</p>’;
52        }
53

54   }
55   else{
56       echo "<p>Authentication failed.</p>";
57   }
58

59   ?>

     Here is an example of how to check the usage for a specific virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Check usage the this Virtual Machine
17   $uuid = ’d8895fc5-0dd1-11df-ab9f-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $arr_usage = api_request($base_url.’/rest/hosting/usage/’.$uuid.’/’, ’get’,
24            null, $cookies_file);
25




     18.3. Examples                                                                                    165
     ECP Service Provider Edition API Documentation, Release 3.3.0



26         //Make sure there was no error returned
27         if(is_array($arr_usage)){
28

29               if($arr_usage){
30

31                    //Display all usage info
32                    echo "
33                    <h1>Usage:</h1><table>
34                    <tr>
35                    <td>Usage</td>
36                    <td>Used</td>
37                    <td>Total</td>
38                    </tr>";
39                    foreach ($arr_usage[’usage’] as $usage=>$info){
40                        echo "
41                        <tr>
42                        <td>$usage</td>
43                        <td>$info[used]</td>
44                        <td>$info[available]</td>
45                        </tr>";
46                    }
47                    echo ’</table>’;
48               }
49               else{
50                   echo ’<p>No quotas available.</p>’;
51               }
52          }
53          else{
54                  echo ’<p>Error: ’.$arr_usage.’</p>’;
55          }
56

57   }
58   else{
59       echo "<p>Authentication failed.</p>";
60   }
61

62   ?>



     18.3.2 Python

     Here is an example of how to check the usage for the current user.
     See Also:
     Cookies
 1   from   cookielib import CookieJar
 2   from   urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from   urllib2 import build_opener, install_opener, URLError
 4   from   json import loads
 5   from   error import ecp_check_error
 6

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

10   #Domain or ip of primary ECP node (also specify port if not 80)
11   #Include protocol prefix http:// and do not include a trailing slash
12   host = ’http://127.0.0.1’


     166                                                  Chapter 18. usage – Virtual Machine Resource Usage
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



13   username = ’customer’
14   password = ’password’
15

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/usage/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44

45               #Output the usage in a nice format
46               usage = json[’usage’]
47

48               print ’VMs:        %i/%i’ % (usage[’vms’][’used’], usage[’vms’][’available’])
49

50               print ’CPUs:       %i/%i’ % (usage[’cpus’][’used’], usage[’cpus’][’available’])
51

52               print ’Memory: %i/%i MB’ % (usage[’memory’][’used’],
53               usage[’memory’][’available’])
54

55               print ’Storage: %.2f/%.2f GB’ % (float(usage[’storage’][’used’])/1024,
56               float(usage[’storage’][’available’])/1024)
57

58          else:
59              #Output the error
60              print error

     Here is an example of how to check the usage for a specific virtual machine.
     See Also:
     Cookies
1    from    cookielib import CookieJar
2    from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
3    from    urllib2 import build_opener, install_opener, URLError
4    from    json import loads



     18.3. Examples                                                                                    167
     ECP Service Provider Edition API Documentation, Release 3.3.0



 5   from error import ecp_check_error
 6

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

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

16   #UUID of machine to get usage information about
17   uuid = ’04a0a538-129e-11df-a880-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/usage/’+uuid+’/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44             #Format the output nicely
45             #Parse the response into a dictionary
46             json = loads(response_body)
47

48             #Show information about this VM’s usage
49             usage = json[’usage’]
50

51             print ’CPUs:    %i/%i’ % (usage[’cpus’][’used’], usage[’cpus’][’available’])
52

53             print ’Memory: %i/%i MB’ % (usage[’memory’][’used’],
54             usage[’memory’][’available’])
55

56             print ’Storage: %.2f/%.2f GB’ % (float(usage[’storage’][’used’])/1024,
57             float(usage[’storage’][’available’])/1024)
58

59          else:
60              #Output the error
61                      print error




     168                                        Chapter 18. usage – Virtual Machine Resource Usage
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


     18.3.3 Java

     Here is an example of how to check the usage for the current user.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5   import org.json.simple.parser.ParseException;
 6

 7   public class rest_hosting_usage_get {
 8       // Following method will output all information in proper format
 9       public static void DisplayData(String usage_List, String field, String unit) {
10

11               JSONObject json;
12               try {
13                   json = (JSONObject) new JSONParser().parse(usage_List);
14                   try {
15                       JSONObject usage_info = (JSONObject) json.get("usage");
16                       JSONObject info_item = (JSONObject) usage_info.get(field);
17                       System.out.println(" ");
18                       System.out.println(field.toUpperCase());
19                       System.out.println("   Available: "
20                               + info_item.get("available") + " " + unit);
21                       System.out.println("   Used: " + info_item.get("used") + " "
22                               + unit);
23

24                   } catch (Exception e) {
25                       System.out.println("Display Error");
26                   }
27               } catch (ParseException e) {
28

29                   e.printStackTrace();
30               }
31

32        }
33

34        public static void main(String[] args) throws MalformedURLException {
35            Client user = new Client();
36            CookieManager cm = new CookieManager();
37            error_Handling errorCheck = new error_Handling();
38            boolean check;
39            String username = "customer";
40            String password = "password";
41            String authentication_message = "";
42            String info_Line = "";
43            int count = 0;
44            URL url = new URL("https://127.0.0.1/rest/hosting/usage/");
45            check = user.initial_Login(cm, username, password);
46            System.out.println(authentication_message);
47            if (check == false) {
48                System.out.println("Authentication Failed");
49            } else {
50                do {
51                     // will connect to URL and call display method to output all the



     18.3. Examples                                                                                    169
     ECP Service Provider Edition API Documentation, Release 3.3.0



52                       // info
53                       info_Line = (user.connectURI(url, cm, count));
54                       if (info_Line != null) {
55                           errorCheck.api_error(info_Line);
56                           DisplayData(info_Line, "memory", "MB");
57                           DisplayData(info_Line, "storage", "MB");
58                           DisplayData(info_Line, "vms", "");
59                           DisplayData(info_Line, "cpus", "");
60                           count++;
61                       }
62                   } while (info_Line != null);
63               }
64         }
65

66   }

     Here is an example of how to check the usage for a specific virtual machine.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5   import org.json.simple.parser.ParseException;
 6

 7   public class rest_hosting_usage_uuid_get {
 8       // Following method will output all information in proper format
 9       public static void DisplayData(String usage_List, String field, String unit) {
10           boolean exists = true;
11           JSONObject json;
12           try {
13               json = (JSONObject) new JSONParser().parse(usage_List);
14               int errObj = ((Number) json.get("errno")).intValue();
15               if (errObj != 0) {
16                   System.out.println(json.get("message"));
17                   System.out.println(" ");
18                   exists = false;
19               }
20               while (exists) {
21                   try {
22                       JSONObject usage_info = (JSONObject) json.get("usage");
23                       JSONObject info_item = (JSONObject) usage_info.get(field);
24                       System.out.println(" ");
25                       System.out.println(field.toUpperCase());
26                       System.out.println("   Available: "
27                               + info_item.get("available") + " " + unit);
28                       System.out.println("   Used: " + info_item.get("used")
29                               + " " + unit);
30

31                        } catch (Exception e) {
32                            System.out.println("Display Error");
33                        }
34                   }
35               } catch (ParseException e) {
36

37                   e.printStackTrace();



     170                                                 Chapter 18. usage – Virtual Machine Resource Usage
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



38           }
39

40       }
41

42       public static void main(String[] args) throws MalformedURLException {
43           Client user = new Client();
44           CookieManager cm = new CookieManager();
45           error_Handling errorCheck = new error_Handling();
46           boolean check;
47           String username = "customer";
48           String password = "password";
49           String uuid = "e4ed8a9e-11c1-11df-b782-000acd1901c5";
50           String authentication_message = "";
51           String info_Line = "";
52           int count = 0;
53           URL url = new URL("https://127.0.0.1/rest/hosting/usage/"
54                    + uuid + "/");
55           check = user.initial_Login(cm, username, password);
56           System.out.println(authentication_message);
57           if (check == false) {
58               System.out.println("Authentication Failed");
59           } else {
60               do {
61                    // will connect to URL and call display method to output all the
62                    // info
63                    info_Line = (user.connectURI(url, cm, count));
64                    if (info_Line != null) {
65                        errorCheck.api_error(info_Line);
66                        System.out.println(" ");
67                        DisplayData(info_Line, "memory", "MB");
68                        DisplayData(info_Line, "storage", "MB");
69                        DisplayData(info_Line, "cpus", "");
70                        count++;
71                    }
72               } while (info_Line != null);
73           }
74       }
75

76   }




     18.3. Examples                                                                          171
ECP Service Provider Edition API Documentation, Release 3.3.0




172                                        Chapter 18. usage – Virtual Machine Resource Usage
                                                                                                      CHAPTER

                                                                                                 NINETEEN



                                                                            USER – USER

User functionality.


19.1 Resources

19.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


19.1.2 UserUUID

class user.UserUUID
      This resource represens a specific user.
      Resource URI:
         /rest/hosting/user/<UUID>/




                                                                                                          173
ECP Service Provider Edition API Documentation, Release 3.3.0


      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.
                 Return type user.RepUserUUID


19.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


19.2 Representations

19.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.



174                                                                                   Chapter 19. user – User
                                           ECP Service Provider Edition API Documentation, Release 3.3.0


      Representation:
         {"errno":response.errno,
          "message":response.message,
          "user": user_obj}



19.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.
      Representation:
         {"errno": response.errno,
          "message": response.message,
          "user": {"uuid": user.uuid,
                   "user_name": user.user_name,
                   "display_name": user.display_name,
                   "password": user.password,
                   "email": user.email}}



19.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




19.2. Representations                                                                                    175
     ECP Service Provider Edition API Documentation, Release 3.3.0



              {"errno": response.errno,
               "message": response.message,
               "users": [user1, user2]}



     19.3 Examples

     19.3.1 PHP

     Here is an example of how to list all users.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19         //Use use the same cookie file for other API calls
20         $arr_users = api_request($base_url.’/rest/hosting/user/list/’, ’get’, null,
21             $cookies_file);
22

23         //Make sure there was no error returned
24         if(is_array($arr_users)){
25

26               if($arr_users[’users’]){
27

28                   //Display the users in a table
29                   echo ’<h1>Users:</h1><table>’;
30                   echo ’<tr>’;
31                   echo ’<td>UUID</td>’;
32                   echo ’<td>Display name</td>’;
33                   echo ’<td>Username</td>’;
34                   echo ’<td>Groups</td>’;
35                   echo ’</tr>’;
36                   foreach ($arr_users[’users’] as $user)
37                   {
38                       echo ’<tr>’;
39                       echo "<td>$user[uuid]</td>";
40                       echo "<td>$user[display_name]</td>";
41                       echo "<td>$user[user_name]</td>";
42                       echo ’<td>’;



     176                                                                      Chapter 19. user – User
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



43                        //If the user belongs to at least one group, show a comma
44                        //separated list of the groups
45                        if(is_array($user[’groups’]) && $user[’groups’]){
46                            echo implode(’, ’,$user[’groups’]);
47                        }
48                        else{ //otherwise show "None!"
49                            echo ’None!</td>’;
50                        }
51                        echo ’</tr>’;
52                   }
53                   echo ’</table>’;
54               }
55               else{
56                   echo ’<p>No users available.</p>’;
57               }
58        }
59        else{
60                echo ’<p>Error: ’.$arr_users.’</p>’;
61        }
62

63   }
64   else{
65       echo "<p>Authentication failed.</p>";
66   }
67

68   ?>

     Here is an example of how to get information about a specific user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //User to get details of
17   $uuid = ’74f27594-fa86-11de-9e2d-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/user/’.$uuid.’/’, ’get’,
24            null, $cookies_file);
25

26        //Make sure there was no error returned



     19.3. Examples                                                                                    177
     ECP Service Provider Edition API Documentation, Release 3.3.0



27         if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for user with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’user’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }
35               echo ’</ul>’;
36         }
37         else{
38              echo ’<p>Error: ’.$details.’</p>’;
39         }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to create a new user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Information about       the new user
17   $username         =       ’API_user4’;
18   $displayname      =       ’A user of the API’;
19   $password         =       ’password’;
20   $password_confirm =       ’password’;
21   $group            =       ’f9b5fc11-1bf4-11df-9c93-000acd1901c5’;
22   $email            =       ’person4@example.com’;
23

24

25   //Combine the data to create the PUT string
26   $data = "username=$username&displayname=$displayname&password=$password".
27           "&password_confirm=$password_confirm&group=$group&email=$email";
28

29   //Authenticate and check for success
30   if (authenticate($base_url, $username, $password, $cookies_file)){
31

32         //Use use the same cookie file for other API calls



     178                                                                      Chapter 19. user – User
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



33          $response = api_request($base_url.’/rest/hosting/user/’, ’put’,
34              $data, $cookies_file, ’user’);
35

36          //Make sure there was no error returned
37          if(is_array($response)){
38

39               echo "<p>New user created with UUID: ".$response[’user’][’uuid’]."</p>";
40

41          }
42          else{
43               echo ’<p>Error: ’.$response.’</p>’;
44          }
45

46   }
47   else{
48       echo "<p>Authentication failed.</p>";
49   }
50

51   ?>



     19.3.2 Python

     Here is an example of how to list all users.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/user/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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


     19.3. Examples                                                                                      179
     ECP Service Provider Edition API Documentation, Release 3.3.0


31

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the users
45               for user in json[’users’]:
46

47                  #Output and remove the name from the dictionary.
48                  print
49                  print "=========== " + user[’user_name’] + " ==========="
50                  del(user[’user_name’])
51

52                  #Output all information
53                  for key in user.keys():
54                      print key + ’ = ’ + str(user[key])
55          else:
56              #Output the error
57              print error

     Here is an example of how to get information about a specific user.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #User for which to get information
17   uuid = ’ee5d91f0-0055-11df-8ecf-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.



     180                                                                  Chapter 19. user – User
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



26        req = Request(host+’/rest/hosting/user/’+uuid+’/’)
27        #Send the request
28        response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37        #Read the response
38        response_body = response.read()
39

40        #Verify that there was no error
41        error = ecp_check_error(response_body)
42        if not error:
43

44               #Format the output nicely
45               #Parse the response into a dictionary
46               json = loads(response_body)
47

48               #Show information about this user
49               user = json[’user’]
50

51               #Output and remove the name from the dictionary
52               print
53               print ’=========== ’ + user[’user_name’] + ’ ===========’
54               del(user[’user_name’])
55

56               #Output all information
57               for key in user.keys():
58                   print key + ’ = ’ + str(user[key])
59

60        else:
61            #Output the error
62                    print error



     19.3.3 Java

     Here is an example of how to list all existing users.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_user_list {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String user_List) {
11           boolean check = true;
12           int count = 0;


     19.3. Examples                                                                                      181
     ECP Service Provider Edition API Documentation, Release 3.3.0



13             JSONObject json;
14             try {
15                 json = (JSONObject) new JSONParser().parse(user_List);
16                 JSONArray user_obj = (JSONArray) json.get("users");
17                 System.out.println(" ");
18                 System.out.println("Users:");
19                 while (check) {
20                     try {
21                         JSONObject user_items = (JSONObject) user_obj.get(count);
22                         System.out.println(" ");
23                         System.out.println((count + 1) + ")");
24                         System.out.println("Display Name: "
25                                 + user_items.get("display_name"));
26                         System.out.println("User Name: "
27                                 + user_items.get("user_name"));
28                         System.out.println("Date Created: "
29                                 + user_items.get("created"));
30                         System.out.println("Email Address: "
31                                 + user_items.get("email_address"));
32                         System.out.println("uuid: " + user_items.get("uuid"));
33                         System.out.println("Groups: " + user_items.get("groups"));
34                         count++;
35                     } catch (Exception e) {
36                         check = false;
37                     }
38                 }
39             } catch (ParseException e) {
40

41                 e.printStackTrace();
42             }
43

44         }
45

46         public static void main(String[] args) throws MalformedURLException {
47             Client user = new Client();
48             CookieManager cm = new CookieManager();
49             error_Handling errorCheck = new error_Handling();
50             boolean check;
51             String username = "admin";
52             String password = "password";
53             String authentication_message = "";
54             String info_Line = "";
55             int count = 0;
56             URL url = new URL(
57                      "https://127.0.0.1/rest/hosting/user/list/");
58             check = user.initial_Login(cm, username, password);
59             System.out.println(authentication_message);
60             if (check == false) {
61                 System.out.println("Authentication Failed");
62             } else {
63                 do {
64                      // will connect to URL and call display method to output all the
65                      // info
66                      info_Line = (user.connectURI(url, cm, count));
67                      if (info_Line != null) {
68                          errorCheck.api_error(info_Line);
69                          DisplayData(info_Line);
70                          count++;



     182                                                                Chapter 19. user – User
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



71                       }
72                   } while (info_Line != null);
73               }
74        }
75

76   }

     Here is an example of how to get information about a specific user.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import org.json.simple.JSONObject;
 4   import org.json.simple.parser.JSONParser;
 5   import org.json.simple.parser.ParseException;
 6

 7   public class rest_hosting_user_uuid_get {
 8       // Following method will output all information in proper format
 9       public static void DisplayData(String user_List) {
10           JSONObject json;
11           try {
12               json = (JSONObject) new JSONParser().parse(user_List);
13               System.out.println(" ");
14               System.out.println("User:");
15               try {
16                   JSONObject user_info = (JSONObject) json.get("user");
17                   System.out.println(" ");
18                   System.out.println("Display Name: "
19                           + user_info.get("display_name"));
20                   System.out.println("Groups: " + user_info.get("groups"));
21                   System.out.println("Date Created: " + user_info.get("created"));
22                   System.out.println("uuid: " + user_info.get("uuid"));
23                   System.out.println("Email Address: "
24                           + user_info.get("email_address"));
25               } catch (Exception e) {
26

27                        System.out.println("User with specified uuid does not exist");
28                   }
29

30               } catch (ParseException e) {
31

32                   e.printStackTrace();
33               }
34

35        }
36

37        public static void main(String[] args) throws MalformedURLException {
38            Client user = new Client();
39            CookieManager cm = new CookieManager();
40            error_Handling errorCheck = new error_Handling();
41            boolean check;
42            String username = "admin";
43            String password = "password";
44            String authentication_message = "";
45            String info_Line = "";
46            String uuid = "ee5d91f0-0055-11df-8ecf-000acd1901c5";



     19.3. Examples                                                                                    183
     ECP Service Provider Edition API Documentation, Release 3.3.0



47             int count = 0;
48             URL url = new URL("https://127.0.0.1/rest/hosting/user/"
49                      + uuid + "/");
50             check = user.initial_Login(cm, username, password);
51             System.out.println(authentication_message);
52             if (check == false) {
53                 System.out.println("Authentication Failed");
54             } else {
55                 // will connect to URL and call display method to output all the
56                 // info
57                 do {
58                      info_Line = (user.connectURI(url, cm, count));
59                      if (info_Line != null) {
60                          errorCheck.api_error(info_Line);
61                          DisplayData(info_Line);
62                          count++;
63                      }
64                 } while (info_Line != null);
65             }
66         }
67   }




     184                                                                Chapter 19. user – User
                                                                                                         CHAPTER

                                                                                                        TWENTY



                                                                        UTIL – UTILITIES

Utility functionality.


20.1 Resources

20.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


20.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.
                 Parameters
                         • locale – The locale of the translations to return.
                 Return type util.RepI18N




                                                                                                             185
ECP Service Provider Edition API Documentation, Release 3.3.0


20.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


20.2 Representations

20.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}}



20.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.



186                                                                                  Chapter 20. util – Utilities
                                                ECP Service Provider Edition API Documentation, Release 3.3.0


           Representation:
              {"errno": response.errno,
               "message": response.message,
               "i18n": {"current": i18n.current,
                        "supported": [lang1, lang2],
                        i18n_label: i18n.translation}}



     20.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}}}



     20.3 Examples

     20.3.1 PHP

     Here is an example of how to get the current language’s translation of all messages.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){


     20.3. Examples                                                                                      187
     ECP Service Provider Edition API Documentation, Release 3.3.0


18

19         //Use use the same cookie file for other API calls
20         $arr_i18n = api_request($base_url.’/rest/hosting/i18n/’, ’get’,
21             null, $cookies_file);
22

23         //Make sure there was no error returned
24         if(is_array($arr_i18n)){
25

26               //Display the info.
27                       echo ’<p>Current language: ’.$arr_i18n[’i18n’][’current’].’</p>’;
28                       echo ’<p>Supported languages: ’;
29                       $buff = ’’;
30                       foreach($arr_i18n[’i18n’][’supported’] as $lang)
31                       {
32                               $buff .= ’, ’.$lang[1].’(’.$lang[0].’)’;
33                       }
34                       echo substr ($buff,2).’</p>’;
35

36                        //Ignore the unnedded info for the next section
37                        unset($arr_i18n[’i18n’][’supported’]);
38                        unset($arr_i18n[’i18n’][’current’]);
39

40                        //Display the translations in a table
41                        echo "
42                        <h1>Current transaltion:</h1><table>
43                        <tr>
44                        <td><b>Label</b></td>
45                        <td><b>Translation</b></td>
46                        </tr>";
47                        foreach ($arr_i18n[’i18n’] as $label=>$translation)
48                        {
49                                echo "
50                                <tr>
51                                <td>$label</td>
52                                <td>$translation</td>
53                                </tr>";
54                        }
55                        echo ’</table>’;
56         }
57         else{
58                 echo ’<p>Error: ’.$arr_i18n.’</p>’;
59         }
60

61   }
62   else{
63       echo "<p>Authentication failed.</p>";
64   }
65

66   ?>

     Here is an example of how to get the paths of all VM icons.
     See Also:
     Authentication function, Error handling function, API request function
1    <?php
2    require(’authentication.php’);
3    require(’error_handling.php’);
4    require(’api_request.php’);


     188                                                                      Chapter 20. util – Utilities
                                               ECP Service Provider Edition API Documentation, Release 3.3.0


 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19        //Use use the same cookie file for other API calls
20        $arr_icons = api_request($base_url.’/rest/hosting/iconmap/’, ’get’,
21            null, $cookies_file);
22

23        //Make sure there was no error returned
24        if(is_array($arr_icons)){
25

26               echo "<p>Base path: {$arr_icons[’icons’][’base_path’]}</p>";
27               unset($arr_icons[’icons’][’base_path’]);
28               foreach($arr_icons[’icons’] as $key=>$value){
29                   echo "<p><b>$key</b> -- Small:$value[small] Medium:$value[medium]</p>";
30               }
31        }
32        else{
33             echo ’<p>Error: ’.$arr_i18n.’</p>’;
34        }
35

36   }
37   else{
38       echo "<p>Authentication failed.</p>";
39   }
40

41   ?>



     20.3.2 Python

     Here is an example of how to get the current language’s translation of all messages.
     See Also:
     Cookies
 1   from   cookielib import CookieJar
 2   from   urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from   urllib2 import build_opener, install_opener, URLError
 4   from   json import loads
 5   from   error import ecp_check_error
 6

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

10   #Domain or ip of primary ECP node (also specify port if not 80)
11   #Include protocol prefix http:// and do not include a trailing slash
12   host = ’http://127.0.0.1’



     20.3. Examples                                                                                     189
     ECP Service Provider Edition API Documentation, Release 3.3.0



13   username = ’customer’
14   password = ’password’
15

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/i18n/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41               #Parse the response
42               json = loads(response_body)
43               dictionary = json[’i18n’]
44

45               #Display and remove special elements form the list
46               print ’Current language: ’ + dictionary[’current’]
47               del(dictionary[’current’])
48

49               print ’Supported languages: ’
50               for lang in dictionary[’supported’]:
51                   print ’- %s(%s)’ % (lang[1], lang[0])
52               del(dictionary[’supported’])
53

54               print
55               print ’Current dictionary:’
56               for label, translation in dictionary.items():
57                   print label + ’: ’ + translation
58

59          else:
60              #Output the error
61              print error

     Here is an example of how to get the paths of all VM icons.
     See Also:
     Cookies
1    from cookielib import CookieJar
2    from urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
3    from urllib2 import build_opener, install_opener, URLError



     190                                                              Chapter 20. util – Utilities
                                       ECP Service Provider Edition API Documentation, Release 3.3.0



 4   from json import loads
 5   from error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host+’/rest/hosting/iconmap/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:
33

34          #Read the response
35          response_body = response.read()
36

37          #Verify that there was no error
38          error = ecp_check_error(response_body)
39          if not error:
40

41             #Parse the response
42             json = loads(response_body)
43             icons = json[’icons’]
44

45             print ’Base path: ’ + icons[’base_path’]
46             print
47             del(icons[’base_path’])
48

49             for label, info in icons.items():
50                 print ’--- ’ + label + ’ ---’
51                 print ’Small: ’ + info[’small’]
52                 print ’Medium: ’ + info[’medium’]
53                 print
54

55          else:
56              #Output the error
57              print error




     20.3. Examples                                                                             191
     ECP Service Provider Edition API Documentation, Release 3.3.0


     20.3.3 Java

     Here is an example of how to get the current language’s translation of all messages.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.MalformedURLException;
 2   import java.net.URL;
 3

 4   import org.json.simple.JSONObject;
 5   import org.json.simple.parser.JSONParser;
 6   import org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_i18n_get {
 9

10         public static void DisplayData(String i18n_List) {
11             String key_Line = "";
12             String key_Data = "";
13             String[] split_key_line = null;
14             String[] split_key_data = null;
15

16               JSONObject json;
17               try {
18                   json = (JSONObject) new JSONParser().parse(i18n_List);
19                   try {
20                       JSONObject i18n_name = (JSONObject) json.get("i18n");
21                       System.out.println(" ");
22                       System.out.println("Langauges Supported: "
23                                + i18n_name.get("supported"));
24                       System.out.println("Current Language: \""
25                                + i18n_name.get("current") + "\"");
26                       System.out.println(" ");
27                       key_Line = i18n_name.keySet().toString();
28                       // Following will replace unnecessary character and strings with
29                       // empty
30                       // values
31                       key_Line = key_Line.replace("[", "");
32                       key_Line = key_Line.replace("]", "");
33                       key_Line = key_Line.replaceAll(" supported, current,", "");
34                       // Split items in string at commas
35                       split_key_line = key_Line.split(",");
36

37                        key_Data = i18n_name.values().toString();
38                        // Following will replace unnecessary character and strings with
39                        // empty
40                        // values
41                        key_Data = key_Data.replace("[", "");
42                        key_Data = key_Data.replace("]", "");
43                        key_Data = key_Data.replaceAll(
44                                 " \"en\",\"English\",\"sv\",\"svenska\", en,", "");
45                        // Split items in string at commas
46                        split_key_data = key_Data.split(",");
47

48                        for (int i = 0; i < split_key_line.length; i++) {
49                            System.out.println(" ");
50                            System.out.println((i + 1) + ")");
51                            System.out.println("Label: " + split_key_line[i]);



     192                                                                                    Chapter 20. util – Utilities
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



52                             System.out.println("Message: " + split_key_data[i]);
53                        }
54

55                   } catch (Exception e) {
56                       System.out.println("Display Error");
57                   }
58               } catch (ParseException e) {
59

60                   e.printStackTrace();
61               }
62

63        }
64

65        public static void main(String[] args) throws MalformedURLException {
66            Client user = new Client();
67            CookieManager cm = new CookieManager();
68            error_Handling errorCheck = new error_Handling();
69            boolean check;
70            String info_Line = "";
71            String username = "admin";
72            String password = "password";
73            int count = 0;
74            URL url = new URL("https://127.0.0.1/rest/hosting/i18n/");
75            check = user.initial_Login(cm, username, password);
76            System.out.println(" ");
77            if (check == false) {
78                System.out.println("Authentication Failed");
79            } else {
80                do {
81                     info_Line = (user.connectURI(url, cm, count));
82                     if (info_Line != null) {
83                         errorCheck.api_error(info_Line);
84                         DisplayData(info_Line);
85                         count++;
86                     }
87                } while (info_Line != null);
88            }
89        }
90

91   }

     Here is an example of how to get the paths of all VM icons.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.MalformedURLException;
 2   import java.net.URL;
 3

 4   import org.json.simple.JSONObject;
 5   import org.json.simple.parser.JSONParser;
 6   import org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_iconmap_get {
 9

10        public static void DisplayData(String icon_List) {
11            String key_Line = "";
12            String key_Data = "";



     20.3. Examples                                                                                    193
     ECP Service Provider Edition API Documentation, Release 3.3.0



13             String[] split_key_line = null;
14             String[] split_key_data = null;
15

16             JSONObject json;
17             try {
18                 json = (JSONObject) new JSONParser().parse(icon_List);
19                 try {
20                     JSONObject icon_types = (JSONObject) json.get("icons");
21                     System.out.println(" ");
22                     System.out.println("Base Path for Icons: "
23                              + icon_types.get("base_path"));
24                     key_Line = icon_types.keySet().toString();
25                     // Following will replace unnecessary character and strings with
26                     // empty
27                     // values
28                     key_Line = key_Line.replace("[", "");
29                     key_Line = key_Line.replace("]", "");
30                     key_Line = key_Line.replaceAll(" base_path,", "");
31                     split_key_line = key_Line.split(",");
32

33                    key_Data = icon_types.values().toString();
34                    // Following will replace unnecessary character and strings with
35                    // empty
36                    // values
37                    key_Data = key_Data.replace("[", "");
38                    key_Data = key_Data.replace("]", "");
39                    key_Data = key_Data.replace("\"", "");
40                    key_Data = key_Data.replace("{", "");
41                    key_Data = key_Data.replaceAll(
42                             " /modules/hosting/static/img/,", "");
43                    split_key_data = key_Data.split("},");
44                    // following will create a counted loop to display all labels
45                    // with paths
46                    // Max size could also be replaced with data array length as
47                    // they both
48                    // have the same amount of elements
49                    for (int i = 0; i < split_key_line.length; i++) {
50                        System.out.println(" ");
51                        System.out.println((i + 1) + ")");
52                        System.out.println("OS Label: " + split_key_line[i]);
53                        split_key_data[i] = split_key_data[i].replace(",", "   ");
54                        System.out.println("Icon Paths: "
55                                 + split_key_data[i].replace("}", ""));
56                    }
57

58                 } catch (Exception e) {
59                     System.out.println("Display Error");
60                 }
61             } catch (ParseException e) {
62

63                 e.printStackTrace();
64             }
65

66         }
67

68         public static void main(String[] args) throws MalformedURLException {
69             Client user = new Client();
70             CookieManager cm = new CookieManager();



     194                                                             Chapter 20. util – Utilities
                                    ECP Service Provider Edition API Documentation, Release 3.3.0



71           error_Handling errorCheck = new error_Handling();
72           boolean check;
73           String info_Line = "";
74           String username = "admin";
75           String password = "password";
76           int count = 0;
77           URL url = new URL(
78                    "https://127.0.0.1/rest/hosting/iconmap/");
79           check = user.initial_Login(cm, username, password);
80           System.out.println(" ");
81           if (check == false) {
82               System.out.println("Authentication Failed");
83           } else {
84               do {
85                    info_Line = (user.connectURI(url, cm, count));
86                    if (info_Line != null) {
87                        errorCheck.api_error(info_Line);
88                        DisplayData(info_Line);
89                        count++;
90                    }
91               } while (info_Line != null);
92           }
93       }
94

95   }




     20.3. Examples                                                                          195
ECP Service Provider Edition API Documentation, Release 3.3.0




196                                                             Chapter 20. util – Utilities
                                                                                                     CHAPTER

                                                                                           TWENTYONE



                                              VM – VIRTUAL MACHINE

Virtual machine functionality.


21.1 Resources

21.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


21.1.2 VmUUID

class vm.VmUUID
      This resource represens a specific virtual machine.
      Resource URI:




                                                                                                         197
ECP Service Provider Edition API Documentation, Release 3.3.0



         /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 exten-
             sion 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”.
                      • 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


21.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


List by IP

class vm.VmList
      This resource represents a list of virtual machines specified by an ip address.
      Resource URI:


198                                                                            Chapter 21. vm – Virtual Machine
                                          ECP Service Provider Edition API Documentation, Release 3.3.0



         /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


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


21.2 Representations

21.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.


21.2. Representations                                                                                         199
ECP Service Provider Edition API Documentation, Release 3.3.0


      Representation:
         {"errno":response.errno,
          "message":response.message,
          "txid": transaction.uuid,
          "machine_id": machine.uuid}



21.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.
      Representation:
         {"errno": response.errno,
          "message": response.message,
          "vm": {"uuid": vm.uuid,
                 "name": vm.name,
                 "state": vm.state,
                 "os": vm.os,


200                                                                             Chapter 21. vm – Virtual Machine
                                                ECP Service Provider Edition API Documentation, Release 3.3.0



                         "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}}



     21.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


     21.3 Examples

     21.3.1 PHP

     Here is an example of how to list all virtual machines owned by the current user.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;


     21.3. Examples                                                                                                  201
     ECP Service Provider Edition API Documentation, Release 3.3.0



11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Authenticate and check for success
17   if (authenticate($base_url, $username, $password, $cookies_file)){
18

19         //Use use the same cookie file for other API calls
20         $arr_vms = api_request($base_url.’/rest/hosting/vm/list/’, ’get’, null,
21             $cookies_file);
22

23         //Make sure there was no error returned
24         if(is_array($arr_vms)){
25

26             if($arr_vms[’vms’]){
27

28                 //Display VMs in a table
29                 echo "
30                 <h1>Virtual Machines:</h1><table>
31                 <tr>
32                 <td>UUID</td>
33                 <td>Name</td>
34                 <td>State</td>
35                 <td>Operating System</td>
36                 <td>Hardware UUID</td>
37                 <td>VNC IP</td>
38                 <td>VNC port</td>
39                 <td>VNC password</td>
40                 <td>VNC enabled</td>
41                 <td>Interfaces</td>
42                 </tr>";
43                 foreach ($arr_vms[’vms’] as $vms)
44                 {
45                     echo "
46                     <tr>
47                     <td>$vms[uuid]</td>
48                     <td>$vms[name]</td>
49                     <td>$vms[state]</td>
50                     <td>$vms[os]</td>
51                     <td>$vms[hardware_profile_uuid]</td>
52                     <td>$vms[vnc_ip_address]</td>
53                     <td>$vms[vnc_port]</td>
54                     <td>$vms[vnc_password]</td>
55                     <td>".($vms[’vnc_enabled’]?’Yes’:’No’)."</td>
56                     <td>";
57

58                     //The logic for putting together a list of the network
59                     //interfaces:
60                     $list=’’;
61                     foreach($vms[’interfaces’] as $interface)
62                     {
63                         $list .= ’, ’.$interface[’network_name’].’(’.$interface[’ip’].’)’;
64                     }
65                     echo substr($list,2);
66

67                     echo "
68                     </td>



     202                                                             Chapter 21. vm – Virtual Machine
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



69                       </tr>";
70                   }
71                   echo ’</table>’;
72               }
73               else{
74                   echo ’<p>No VMs available.</p>’;
75               }
76        }
77        else{
78             echo ’<p>Error: ’.$arr_vms.’</p>’;
79        }
80

81   }
82   else{
83       echo "<p>Authentication failed.</p>";
84   }
85

86   ?>

     Here is an example of how to get information about a specific virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //VM to get details of
17   $uuid = ’cfd4df9c-0b11-11df-bc8a-000acd1901c5’;
18

19   //Authenticate and check for success
20   if (authenticate($base_url, $username, $password, $cookies_file)){
21

22        //Use use the same cookie file for other API calls
23        $details = api_request($base_url.’/rest/hosting/vm/’.$uuid.’/’, ’get’, null,
24            $cookies_file);
25

26        //Make sure there was no error returned
27        if(is_array($details)){
28

29               //Display the details.
30               echo ’<h1>Details for virtual machine with UUID:’.$uuid.’</h1>’;
31               echo ’<ul>’;
32               foreach ($details[’vm’] as $key=>$value){
33                    echo "<li>$key=$value</li>";
34               }



     21.3. Examples                                                                                    203
     ECP Service Provider Edition API Documentation, Release 3.3.0



35             echo ’</ul>’;
36         }
37         else{
38              echo ’<p>Error: ’.$details.’</p>’;
39         }
40

41   }
42   else{
43       echo "<p>Authentication failed.</p>";
44   }
45

46   ?>

     Here is an example of how to provision a new virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’customer’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Information about the new VM
17   $name           = "Machine Created by API";
18   $package        = ’5d407a68-c76c-11de-86e5-000475cb7577’;
19   $hardware       = ’bcaff710-2914-11de-836c-001a929face2’;
20   $disk           = ’f1648fba-29ce-11de-84a2-001a929face2’;
21   $network_uuid   = ’fc38963c-a9fa-11de-8c4b-001b63a56c51’;
22

23   //Combine the data to create the PUT string
24   $data = "name=$name&package=$package&hardware=$hardware".
25           "&disk=$disk&network_uuid=$network_uuid";
26

27   //Authenticate and check for success
28   if (authenticate($base_url, $username, $password, $cookies_file)){
29

30         //Use use the same cookie file for other API calls
31         $response = api_request($base_url.’/rest/hosting/vm/’, ’put’,
32             $data, $cookies_file);
33

34         //Make sure there was no error returned
35         if(is_array($response)){
36

37               echo "<p>New vm provisioned with UUID: $response[machine_id].".
38                    "Transaction UUID: $response[txid]</p>";
39

40         }



     204                                                                      Chapter 21. vm – Virtual Machine
                                              ECP Service Provider Edition API Documentation, Release 3.3.0



41        else{
42             echo ’<p>Error: ’.$response.’</p>’;
43        }
44

45   }
46   else{
47       echo "<p>Authentication failed.</p>";
48   }
49

50   ?>

     Here is an example of how to control a virtual machine.
     See Also:
     Authentication function, Error handling function, API request function
 1   <?php
 2   require(’authentication.php’);
 3   require(’error_handling.php’);
 4   require(’api_request.php’);
 5

 6   //Basic connection parameters.
 7   //IP address or host name of the primary ECP node (no trailing slash)
 8   $base_url = ’127.0.0.1’;
 9   //login info
10   $username = ’admin’;
11   $password = ’password’;
12

13   //The cookie file used to store the session cookie.
14   $cookies_file = ’cookies.txt’;
15

16   //Virtual Machine UUID
17   $uuid = ’f3178ef5-0f48-11df-9387-000acd1901c5’;
18   //Command to send
19   $action = ’start’;
20   //The action has to be set to ’save’ to rename or change hardware template
21   $rename = ’new name’;
22   //hardware changes will be made only upon restart
23   $hardware = ’bcaff710-2914-11de-836c-001a929face2’;
24

25   //Combine the data to create the POST string
26   $data = "action=$action";
27   //add the additional information if we are using "save"
28   if ($action == ’save’)
29       $data .= "&name=$rename&hardware_profile_uuid=$hardware";
30

31   //Authenticate and check for success
32   if (authenticate($base_url, $username, $password, $cookies_file)){
33

34        //Use use the same cookie file for other API calls
35        $response = api_request($base_url.’/rest/hosting/vm/’.$uuid.’/’,
36            ’post’, $data, $cookies_file);
37

38        //Make sure there was no error returned
39        if(is_array($response)){
40

41               //Display the details.
42               echo ’<h1>Action sucessful on VM with UUID: ’.$uuid.’</h1>’;



     21.3. Examples                                                                                    205
     ECP Service Provider Edition API Documentation, Release 3.3.0



43               echo ’<ul>’;
44               foreach ($response[’vm’] as $key=>$value){
45                    echo "<li>$key=$value</li>";
46               }
47               echo ’</ul>’;
48

49          }
50          else{
51               echo ’<p>Error: ’.$response.’</p>’;
52          }
53

54   }
55   else{
56       echo "<p>Authentication failed.</p>";
57   }
58

59   ?>



     21.3.2 Python

     Here is an example of how to list all virtual machines owned by the current user.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   try:
17

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

22          #Set up the request. It is a GET by default when not providing data.
23          req = Request(host + ’/rest/hosting/vm/list/’)
24          #Send the request
25          response = urlopen(req)
26

27   except (HTTPError, URLError) as exception:
28

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

32   else:


     206                                                                           Chapter 21. vm – Virtual Machine
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


33

34        #Read the response
35        response_body = response.read()
36

37        #Verify that there was no error
38        error = ecp_check_error(response_body)
39        if not error:
40

41               #Format the output nicely
42               #Parse the response into a dictionary
43               json = loads(response_body)
44               #Loop through the virtual machines
45               for vm in json[’vms’]:
46

47                  #Output and remove the name from the dictionary
48                  print
49                  print ’=========== ’ + vm[’name’] + ’ ===========’
50                  del(vm[’name’])
51

52                  #Get the network interfaces out of the dictionary for use later
53                  interfaces = vm[’interfaces’]
54                  del(vm[’interfaces’])
55

56                  #Output all information about the virtual machine that we got
57                  for key in vm.keys():
58                      print key + ’ = ’ + str(vm[key])
59

60                  #Print out a nicely formatted list of the network interfaces
61                  for interface in interfaces:
62                      print ’---network interface---’
63                      for key in interface.keys():
64                          print key + ’: ’ + str(interface[key])
65                  print ’-----------------------’
66        else:
67            #Output the error
68            print error

     Here is an example of how to get information about a specific virtual machine.
     See Also:
     Cookies
 1   from   cookielib import CookieJar
 2   from   urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from   urllib2 import build_opener, install_opener, URLError
 4   from   json import loads
 5   from   error import ecp_check_error
 6

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

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

16   #VM for which to get information



     21.3. Examples                                                                                    207
     ECP Service Provider Edition API Documentation, Release 3.3.0



17   uuid = ’04a0a538-129e-11df-a880-000acd1901c5’
18

19   try:
20

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

25          #Set up the request. It is a GET by default when not providing data.
26          req = Request(host+’/rest/hosting/vm/’+uuid+’/’)
27          #Send the request
28          response = urlopen(req)
29

30   except (HTTPError, URLError) as exception:
31

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

35   else:
36

37          #Read the response
38          response_body = response.read()
39

40          #Verify that there was no error
41          error = ecp_check_error(response_body)
42          if not error:
43

44              #Format the output nicely
45              #Parse the response into a dictionary
46              json = loads(response_body)
47

48              #Show information about this vm
49              vm = json[’vm’]
50

51              #Remove the interface information. It will be used later.
52              interfaces = vm[’interfaces’]
53              del(vm[’interfaces’])
54

55              #Output and remove the name from the dictionary
56              print
57              print ’=========== ’ + vm[’name’] + ’ ===========’
58              del(vm[’name’])
59

60              #Output all information about the virtual machine that we got
61              for key in vm.keys():
62                  print key + ’ = ’ + str(vm[key])
63

64              #Print out a nicely formatted list of the network interfaces
65              for interface in interfaces:
66                  print ’---network interface---’
67                  for key in interface.keys():
68                      print key + ’: ’ + str(interface[key])
69              print ’-----------------------’
70

71          else:
72              #Output the error
73                  print error




     208                                                             Chapter 21. vm – Virtual Machine
                                             ECP Service Provider Edition API Documentation, Release 3.3.0


     Here is an example of how to provision a new virtual machine.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Information about the virtual machine to be created
17   name           = "My Machine"
18   package        = ’5d407a68-c76c-11de-86e5-000475cb7577’
19   hardware       = ’bcaff710-2914-11de-836c-001a929face2’
20   disk           = ’f1648fba-29ce-11de-84a2-001a929face2’
21   network_uuid   = ’fc38963c-a9fa-11de-8c4b-001b63a56c51’
22

23   data = ’name=’ + name + ’&package=’ + package + ’&hardware=’ + hardware + \
24          ’&disk=’ + disk + ’&network_uuid=’ + network_uuid
25

26   try:
27

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

32          #Set up the request. It is a POST by default when providing data.
33          req = Request(host + ’/rest/hosting/vm/’, data = data)
34          req.get_method = lambda: ’PUT’
35          #Send the request
36          response = urlopen(req)
37

38   except (HTTPError, URLError) as exception:
39

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

43   else:
44

45          #Read the response
46          response_body = response.read()
47

48          #Verify that there was no error
49          error = ecp_check_error(response_body)
50          if not error:
51

52               #Format the output nicely
53               #Parse the response into a dictionary
54               json = loads(response_body)


     21.3. Examples                                                                                   209
     ECP Service Provider Edition API Documentation, Release 3.3.0



55               print ’Virtual Machine sucessfuly created!’
56               print
57

58               #Output information
59               print ’Virtual Machine UUID: ’ + json[’machine_id’]
60               print ’Transaction ID: ’ + json[’txid’]
61

62          else:
63              #Output the error
64              print error

     Here is an example of how to control a virtual machine.
     See Also:
     Cookies
 1   from    cookielib import CookieJar
 2   from    urllib2 import Request, urlopen, HTTPError, HTTPCookieProcessor
 3   from    urllib2 import build_opener, install_opener, URLError
 4   from    json import loads
 5   from    error import ecp_check_error
 6

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

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

16   #Virtual Machine to be updated
17   uuid = ’04a0a538-129e-11df-a880-000acd1901c5’
18   action = ’stop’
19   #New name if action is "save"
20   name = ’newName’
21   #New hardware template if action is "save"
22   htemplate = ’bcaff710-2914-11de-836c-001a929face2’
23

24   data = ’action=’ + action
25

26   if action == ’save’:
27       data = data + ’&name=’ + name + ’&hardware_profile_uuid=’ + htemplate
28

29   try:
30

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

35          #Set up the request. It is a POST by default when providing data.
36          req = Request(host + ’/rest/hosting/vm/’+uuid+’/’, data = data)
37          #Send the request
38          response = urlopen(req)
39

40   except (HTTPError, URLError) as exception:
41

42          #Handle http error codes and errors with the connection



     210                                                             Chapter 21. vm – Virtual Machine
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



43        print exception
44

45   else:
46

47        #Read the response
48        response_body = response.read()
49

50        #Verify that there was no error
51        error = ecp_check_error(response_body)
52        if not error:
53

54               #Format the output nicely
55               #Parse the response into a dictionary
56               json = loads(response_body)
57

58               #Show information about this vm
59               vm = json[’vm’]
60

61               #Remove the interface information. It will be used later.
62               interfaces = vm[’interfaces’]
63               del(vm[’interfaces’])
64

65               #Output and remove the name from the dictionary
66               print
67               print ’Action successful.’
68               print
69               print ’=========== ’ + vm[’name’] + ’ ===========’
70               del(vm[’name’])
71

72               #Output all information about the virtual machine that we got
73               for key in vm.keys():
74                   print key + ’ = ’ + str(vm[key])
75

76               #Print out a nicely formatted list of the network interfaces
77               for interface in interfaces:
78                   print ’---network interface---’
79                   for key in interface.keys():
80                       print key + ’: ’ + str(interface[key])
81               print ’-----------------------’
82

83        else:
84            #Output the error
85            print error



     21.3.3 Java

     Here is an example of how to list all existing virtual machines owned by the current user.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;


     21.3. Examples                                                                                     211
     ECP Service Provider Edition API Documentation, Release 3.3.0


7

8    public class rest_hosting_vm_list {
9        // Following method will output all information in proper format
10       public static void DisplayData(String vm_List) {
11           boolean check = true;
12           boolean check2 = true;
13           int count = 0;
14           int count2 = 0;
15           JSONObject json;
16           try {
17               json = (JSONObject) new JSONParser().parse(vm_List);
18               JSONArray vm_obj = (JSONArray) json.get("vms");
19               System.out.println(" ");
20               System.out.println("Virtual Machines:");
21               while (check) {
22                   try {
23                       JSONObject vm_name = (JSONObject) vm_obj.get(count);
24                       System.out.println(" ");
25                       System.out.println((count + 1) + ")");
26                       System.out.println("Name:" + vm_name.get("name"));
27                       System.out.println("Vnc Enabled ?:"
28                               + vm_name.get("vnc_enabled"));
29                       System.out.println("IP Address:"
30                               + vm_name.get("ip_address"));
31                       System.out.println("Virtual Machine State:"
32                               + vm_name.get("state") + " ");
33                       System.out.println("OS:" + vm_name.get("os") + " ");
34                       System.out.println("VNC Port #:" + vm_name.get("vnc_port"));
35                       System.out.println("uuid:" + vm_name.get("uuid"));
36                       JSONArray intFace_obj = (JSONArray) vm_name
37                               .get("interfaces");
38                       System.out.println("Following Info on Interfaces:");
39

40                        while (check2) {
41                            try {
42                                JSONObject intFace_name = (JSONObject) intFace_obj
43                                        .get(count2);
44                                System.out.println(" " + (count2 + 1) + ".");
45                                System.out.println(" -IP Address:"
46                                        + intFace_name.get("ip"));
47                                System.out.println(" -Network Name:"
48                                        + intFace_name.get("network_name"));
49                                count2++;
50                            } catch (Exception e) {
51                                count2 = 0;
52                                check2 = false;
53                            }
54                        }
55                        count++;
56                        check2 = true;
57                    } catch (Exception e) {
58                        check = false;
59                    }
60               }
61           } catch (ParseException e) {
62

63                e.printStackTrace();
64           }



     212                                                             Chapter 21. vm – Virtual Machine
                                              ECP Service Provider Edition API Documentation, Release 3.3.0


65

66        }
67

68        public static void main(String[] args) throws MalformedURLException {
69            Client user = new Client();
70            CookieManager cm = new CookieManager();
71            error_Handling errorCheck = new error_Handling();
72            boolean check;
73            String username = "customer";
74            String password = "password";
75            String authentication_message = "";
76            String info_Line = "";
77            int count = 0;
78            URL url = new URL(
79                     "https://127.0.0.1/rest/hosting/vm/list/");
80            check = user.initial_Login(cm, username, password);
81            System.out.println(authentication_message);
82            if (check == false) {
83                System.out.println("Authentication Failed");
84            } else {
85                do {
86                     // will connect to URL and call display method to output all the
87                     // info
88                     info_Line = (user.connectURI(url, cm, count));
89                     if (info_Line != null) {
90                         errorCheck.api_error(info_Line);
91                         DisplayData(info_Line);
92                         count++;
93                     }
94                } while (info_Line != null);
95            }
96        }
97

98   }

     Here is an example of how to get information about a specific virtual machine.
     See Also:
     Client Class, Cookie Manager Class, Error Handling Class
 1   import java.net.*;
 2

 3   import   org.json.simple.JSONArray;
 4   import   org.json.simple.JSONObject;
 5   import   org.json.simple.parser.JSONParser;
 6   import   org.json.simple.parser.ParseException;
 7

 8   public class rest_hosting_vm_uuid_get {
 9       // Following method will output all information in proper format
10       public static void DisplayData(String vm_Mach, String uuid) {
11           boolean exists = true;
12           boolean check = true;
13           int count = 0;
14           JSONObject json;
15           try {
16               json = (JSONObject) new JSONParser().parse(vm_Mach);
17               System.out.println(" ");
18               int errObj = ((Number) json.get("errno")).intValue();



     21.3. Examples                                                                                    213
     ECP Service Provider Edition API Documentation, Release 3.3.0



19                 if (errObj != 0) {
20                     System.out.println(json.get("message"));
21                     exists = false;
22                 }
23                 while (exists) {
24                     try {
25                         System.out.println("Virtual Machine with UUID \"" + uuid
26                                 + "\":");
27                         JSONObject vm_info = (JSONObject) json.get("vm");
28                         System.out.println(" ");
29                         System.out.println((count + 1) + ")");
30                         System.out.println("Name:" + vm_info.get("name"));
31                         System.out.println("Vnc Enabled ?:"
32                                 + vm_info.get("vnc_enabled"));
33                         System.out.println("IP Address:"
34                                 + vm_info.get("ip_address"));
35                         System.out.println("Virtual Machine State:"
36                                 + vm_info.get("state") + " ");
37                         System.out.println("OS:" + vm_info.get("os") + " ");
38                         System.out.println("VNC Port #:" + vm_info.get("vnc_port"));
39                         System.out.println("VNC IP Address:"
40                                 + vm_info.get("vnc_ip_address"));
41                         System.out.println("VNC Password:"
42                                 + vm_info.get("vnc_password"));
43                         JSONArray intFace_obj = (JSONArray) vm_info
44                                 .get("interfaces");
45                         System.out.println("Following Info on Interfaces:");
46

47                         while (check) {
48                             try {
49                                 JSONObject intFace_name = (JSONObject) intFace_obj
50                                          .get(count);
51                                 System.out.println(" " + (count + 1) + ".");
52                                 System.out.println(" -IP Address:"
53                                          + intFace_name.get("ip"));
54                                 System.out.println(" -Network Name:"
55                                          + intFace_name.get("network_name"));
56                                 count++;
57                             } catch (Exception e) {
58                                 count = 0;
59                                 check = false;
60                             }
61                         }
62                     exists = false;
63                     } catch (Exception e) {
64                         check = false;
65                     }
66                 }
67             } catch (ParseException e) {
68

69                 e.printStackTrace();
70             }
71

72         }
73

74         public static void main(String[] args) throws MalformedURLException {
75             Client user = new Client();
76             CookieManager cm = new CookieManager();



     214                                                             Chapter 21. vm – Virtual Machine
                                               ECP Service Provider Edition API Documentation, Release 3.3.0



 77               error_Handling errorCheck = new error_Handling();
 78               boolean check;
 79               String username = "customer";
 80               String password = "password";
 81               String authentication_message = "";
 82               String info_Line = "";
 83               String uuid = "9a9317b3-174a-11df-969a-000acd1901c5";
 84               int count = 0;
 85               URL url = new URL("https://127.0.0.1/rest/hosting/vm/"
 86                        + uuid + "/");
 87               check = user.initial_Login(cm, username, password);
 88               System.out.println(authentication_message);
 89               if (check == false) {
 90                   System.out.println("Authentication Failed");
 91               } else {
 92                   do {
 93                        // will connect to URL and call display method to output all the
 94                        // info
 95                        info_Line = (user.connectURI(url, cm, count));
 96                        if (info_Line != null) {
 97                            errorCheck.api_error(info_Line);
 98                            DisplayData(info_Line, uuid);
 99                            count++;
100                        }
101                   } while (info_Line != null);
102               }
103        }
104

105   }

      Here is an example of how to control a virtual machine.
      See Also:
      Client Class, Cookie Manager Class, Error Handling Class
 1    import   java.io.DataInputStream;
 2    import   java.io.DataOutputStream;
 3    import   java.io.IOException;
 4    import   java.net.*;
 5

 6    import   org.json.simple.JSONArray;
 7    import   org.json.simple.JSONObject;
 8    import   org.json.simple.parser.JSONParser;
 9    import   org.json.simple.parser.ParseException;
10

11    public class rest_hosting_vm_uuid_post {
12        // Following method will output all information in proper format
13        public static void DisplayData(String vm_Mach, String uuid) {
14

15                boolean check = true;
16                boolean exists = true;
17                int errObj = 0;
18                int count = 0;
19                JSONObject json;
20                try {
21                    json = (JSONObject) new JSONParser().parse(vm_Mach);
22                    System.out.println(" ");
23                    errObj = ((Number) json.get("errno")).intValue();



      21.3. Examples                                                                                    215
     ECP Service Provider Edition API Documentation, Release 3.3.0



24                 if (errObj != 0) {
25                     System.out.println(json.get("message"));
26                     exists = false;
27                 }
28                 while (exists) {
29                     System.out.println(json.get("message"));
30                     try {
31                         System.out.println("Virtual Machine with UUID \"" + uuid
32                                 + "\":");
33                         System.out.println(" ");
34                         JSONObject vm_info = (JSONObject) json.get("vm");
35                         System.out.println("Name:" + vm_info.get("name"));
36                         System.out.println("Vnc Enabled ?:"
37                                 + vm_info.get("vnc_enabled"));
38                         System.out.println("IP Address:"
39                                 + vm_info.get("ip_address"));
40                         System.out.println("Virtual Machine State:"
41                                 + vm_info.get("state") + " ");
42                         System.out.println("OS:" + vm_info.get("os") + " ");
43                         System.out.println("VNC Port #:" + vm_info.get("vnc_port"));
44                         System.out.println("VNC IP Address:"
45                                 + vm_info.get("vnc_ip_address"));
46                         System.out.println("VNC Password:"
47                                 + vm_info.get("vnc_password"));
48                         JSONArray intFace_obj = (JSONArray) vm_info
49                                 .get("interfaces");
50                         System.out.println("Following Info on Interfaces:");
51

52                        while (check) {
53                            try {
54                                JSONObject intFace_name = (JSONObject) intFace_obj
55                                         .get(count);
56                                System.out.println(" " + (count + 1) + ".");
57                                System.out.println(" -IP Address:"
58                                         + intFace_name.get("ip"));
59                                System.out.println(" -Network Name:"
60                                         + intFace_name.get("network_name"));
61                                count++;
62                            } catch (Exception e) {
63                                count = 0;
64                                check = false;
65                            }
66                        }
67                        exists = false;
68                    } catch (Exception e) {
69                        check = false;
70                    }
71                 }
72             } catch (ParseException e) {
73

74                 e.printStackTrace();
75             }
76

77         }
78

79         public static void ControlVM(Client user, String uri, String query,
80                 String uuid, CookieManager cm) throws IOException {
81             String trans_info_Line = "";



     216                                                             Chapter 21. vm – Virtual Machine
                                     ECP Service Provider Edition API Documentation, Release 3.3.0



 82           int count = 0;
 83           error_Handling errorCheck = new error_Handling();
 84           try {
 85               URL url = new URL("https://127.0.0.1/" + uri + "/"
 86                       + uuid + "/");
 87               trans_info_Line = (user.connectURI(url, cm, count));
 88               errorCheck.api_error(trans_info_Line);
 89               URLConnection urlConnection = url.openConnection();
 90               cm.setCookies(urlConnection);
 91               urlConnection.setDoOutput(true);
 92               if (urlConnection instanceof HttpURLConnection) {
 93                   final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
 94                   httpURLConnection.setUseCaches(false);
 95                   httpURLConnection.setDoOutput(true);
 96                   httpURLConnection.setDoInput(true);
 97                   httpURLConnection.setRequestProperty("Content-Type",
 98                           "application/x-www-form-urlencoded");
 99                   httpURLConnection.setRequestMethod("POST");
100                   DataOutputStream stream = new DataOutputStream(
101                           httpURLConnection.getOutputStream());
102                   stream.writeBytes(query);
103                   stream.flush();
104                   stream.close();
105                   DataInputStream dis = new DataInputStream(httpURLConnection
106                           .getInputStream());
107                   String nextline;
108                   while ((nextline = dis.readLine()) != null) {
109                       DisplayData(nextline, uuid);
110                   }
111                   dis.close();
112               }
113           } catch (RuntimeException exception) {
114               System.out.println("FAIL");
115           }
116       }
117

118       public static void main(String[] args) throws IOException {
119           Client user = new Client();
120           CookieManager cm = new CookieManager();
121           boolean check;
122           String username = "customer";
123           String password = "password";
124           String uuid = "9a9317b3-174a-11df-969a-000acd1901c5";
125           String uri = "rest/hosting/vm";
126           String action = "start";
127           String name = "newName";
128           String h_template = "bcaff710-2914-11de-836c-001a929face2";
129           String query = "action=" + action;
130           if (action == "save") {
131               query += "&name=" + name + "&hardware_profile_uuid=" + h_template;
132           }
133           check = user.initial_Login(cm, username, password);
134           if (check == false) {
135               System.out.println("Authentication Failed");
136           } else {
137               ControlVM(user, uri, query, uuid, cm);
138           }
139




      21.3. Examples                                                                          217
      ECP Service Provider Edition API Documentation, Release 3.3.0



140         }
141   }




      218                                                             Chapter 21. vm – Virtual Machine
                            CHAPTER

                        TWENTYTWO



             INDICES AND TABLES

• genindex
• modindex
• search




                                219
ECP Service Provider Edition API Documentation, Release 3.3.0




220                                                             Chapter 22. Indices and tables
                 PYTHON MODULE INDEX


b
billing, 17
c
cdmount, 159
clone, 25
d
disk, 161
dtemplate, 31
g
group, 47
h
htemplate, 59
i
interface, 155
isofile, 157
l
log, 81
n
network, 93
p
ptemplate, 111
q
quota, 121
t
tag, 141
u
usage, 163
user, 173
util, 185
v
vm, 197


                                  221
ECP Service Provider Edition API Documentation, Release 3.3.0




222                                                             Python Module Index
                                                                                           INDEX


B                                                     errno (group.RepGroupList attribute), 49
Billing (class in billing), 17                        errno (group.RepGroupUUID attribute), 49
billing (module), 17                                  errno (isofile.RepISOFile attribute), 157
                                                      errno (log.RepLogList attribute), 82
C                                                     errno (network.RepNetwork attribute), 94
                                                      errno (network.RepNetworkList attribute), 95
CDMount (class in cdmount), 159
                                                      errno (network.RepNetworkUUID attribute), 95
cdmount (module), 159
                                                      errno (tag.RepTag attribute), 142
CDMountUUID (class in cdmount), 159
                                                      errno (tag.RepTagList attribute), 142
cdrom_mount (cdmount.RepCDMount attribute), 160
                                                      errno (user.RepUser attribute), 174
Clone (class in clone), 25
                                                      errno (user.RepUserList attribute), 175
clone (module), 25
                                                      errno (user.RepUserUUID attribute), 175
created (group.RepGroupUUID.group attribute), 49
                                                      errno (util.RepErrCodes attribute), 186
                                                      errno (util.RepI18N attribute), 186
D                                                     errno (util.RepIconMap attribute), 187
date (log.RepLogUUID attribute), 82                   errno (vm.RepVm attribute), 199
DELETE() (cdmount.CDMountUUID method), 160            errno (vm.RepVmList attribute), 201
DELETE() (disk.VMDiskUUID method), 162                errno (vm.RepVmUUID attribute), 200
DELETE() (htemplate.HtemplateUUID method), 60         error (log.RepLogUUID attribute), 82
DELETE() (interface.InterfaceUUID method), 155
DELETE() (log.LogUUID method), 81                     F
DELETE() (network.NetworkUUID method), 94
                                                      file_names (isofile.RepISOFile attribute), 157
DELETE() (quota.QuotaUUID method), 122
                                                      flags (vm.RepVmUUID.vm attribute), 200
DELETE() (tag.TagName method), 141
disk (module), 161
display_name (group.RepGroupUUID.group attribute),
                                                      G
          49                                          GET() (billing.Billing method), 17
display_name (user.RepUserUUID.user attribute), 175   GET() (cdmount.CDMountUUID method), 159
dtemplate (module), 31                                GET() (disk.VMDiskUUID method), 162
DtemplateList (class in dtemplate), 31                GET() (dtemplate.DtemplateList method), 31
DtemplateUUID (class in dtemplate), 31                GET() (dtemplate.DtemplateUUID method), 31
                                                      GET() (group.GroupList method), 48
E                                                     GET() (group.GroupUUID method), 47
                                                      GET() (htemplate.HtemplateList method), 60
email (user.RepUserUUID.user attribute), 175
                                                      GET() (htemplate.HtemplateUUID method), 59
ErrCodes (class in util), 185
                                                      GET() (interface.InterfaceList method), 156
errcodes (util.RepErrCodes attribute), 186
                                                      GET() (interface.InterfaceUUID method), 155
errno (cdmount.RepCDMount attribute), 160
                                                      GET() (isofile.ISOFileList method), 157
errno (clone.RepClone attribute), 25
                                                      GET() (log.LogList method), 81
errno (disk.RepDisk attribute), 162
                                                      GET() (network.NetworkList method), 94
errno (dtemplate.RepDtemplateList attribute), 33
                                                      GET() (network.NetworkUUID method), 93
errno (dtemplate.RepDtemplateUUID attribute), 32
                                                      GET() (ptemplate.PtemplateList method), 111
errno (group.RepGroup attribute), 48


                                                                                                     223
ECP Service Provider Edition API Documentation, Release 3.3.0


GET() (ptemplate.PtemplateUUID method), 111       message (clone.RepClone attribute), 25
GET() (quota.QuotaGroupUUID method), 122          message (disk.RepDisk attribute), 162
GET() (quota.QuotaList method), 123               message (dtemplate.RepDtemplateList attribute), 33
GET() (quota.QuotaUUID method), 121               message (dtemplate.RepDtemplateUUID attribute), 32
GET() (tag.TagList method), 142                   message (group.RepGroup attribute), 48
GET() (usage.Usage method), 163                   message (group.RepGroupList attribute), 49
GET() (usage.UsageUUID method), 163               message (group.RepGroupUUID attribute), 49
GET() (user.UserList method), 174                 message (isofile.RepISOFile attribute), 157
GET() (user.UserUUID method), 173                 message (log.RepLogList attribute), 82
GET() (util.ErrCodes method), 185                 message (log.RepLogUUID attribute), 82
GET() (util.I18N method), 185                     message (network.RepNetwork attribute), 94
GET() (util.IconMap method), 186                  message (network.RepNetworkList attribute), 95
GET() (vm.VmList method), 198, 199                message (network.RepNetworkUUID attribute), 95
GET() (vm.VmUUID method), 198                     message (tag.RepTag attribute), 142
Group (class in group), 47                        message (tag.RepTagList attribute), 142
group (group.RepGroup attribute), 48              message (user.RepUser attribute), 174
group (module), 47                                message (user.RepUserList attribute), 175
group_name (group.RepGroupUUID.group attribute), 49
                                                  message (user.RepUserUUID attribute), 175
GroupList (class in group), 48                    message (util.RepErrCodes attribute), 186
groups (group.RepGroupList attribute), 49         message (util.RepI18N attribute), 186
GroupUUID (class in group), 47                    message (util.RepIconMap attribute), 187
                                                  message (vm.RepVm attribute), 199
H                                                 message (vm.RepVmList attribute), 201
hardware_profile_uuid (vm.RepVmUUID.vm attribute), message (vm.RepVmUUID attribute), 200
           200
Htemplate (class in htemplate), 59                N
htemplate (module), 59                            name (network.RepNetworkUUID.network attribute), 95
HtemplateList (class in htemplate), 60            name (vm.RepVmUUID.vm attribute), 200
HtemplateUUID (class in htemplate), 59            Network (class in network), 93
                                                  network (module), 93
I                                                 network (network.RepNetwork attribute), 94
I18N (class in util), 185                         NetworkList (class in network), 94
i18n (util.RepI18N attribute), 186                networks (network.RepNetworkList attribute), 95
IconMap (class in util), 186                      NetworkUUID (class in network), 93
icons (util.RepIconMap attribute), 187
Interface (class in interface), 155                   O
interface (module), 155                               os (vm.RepVmUUID.vm attribute), 200
InterfaceList (class in interface), 156               owner (vm.RepVmUUID.vm attribute), 200
interfaces (vm.RepVmUUID.vm attribute), 200
InterfaceUUID (class in interface), 155               P
isofile (module), 157                                  password (user.RepUserUUID.user attribute), 175
ISOFileList (class in isofile), 157                    POST() (clone.Clone method), 25
                                                      POST() (group.GroupUUID method), 47
L                                                     POST() (htemplate.HtemplateUUID method), 60
log (module), 81                                      POST() (interface.InterfaceUUID method), 155
LogList (class in log), 81                            POST() (network.NetworkUUID method), 93
logs (log.RepLogList attribute), 82                   POST() (quota.QuotaGroupUUID method), 122
LogUUID (class in log), 81                            POST() (quota.QuotaUUID method), 122
                                                      POST() (user.UserUUID method), 174
M                                                     POST() (vm.VmUUID method), 198
machine_id (clone.RepClone attribute), 25             ptemplate (module), 111
machine_id (vm.RepVm attribute), 199                  PtemplateList (class in ptemplate), 111
message (cdmount.RepCDMount attribute), 160           PtemplateUUID (class in ptemplate), 111
                                                      PUT() (cdmount.CDMount method), 159


224                                                                                                     Index
                                          ECP Service Provider Edition API Documentation, Release 3.3.0


PUT() (disk.VMDisk method), 161                         RepVmList (class in vm), 201
PUT() (group.Group method), 47                          RepVmUUID (class in vm), 200
PUT() (htemplate.Htemplate method), 59
PUT() (interface.Interface method), 155                 S
PUT() (network.Network method), 93                      size (dtemplate.RepDtemplateUUID attribute), 32
PUT() (quota.Quota method), 121                         state (vm.RepVmUUID.vm attribute), 200
PUT() (tag.Tag method), 141
PUT() (user.User method), 173                           T
PUT() (vm.Vm method), 197                               Tag (class in tag), 141
                                                        tag (module), 141
Q                                                       TagList (class in tag), 142
Quota (class in quota), 121                             TagName (class in tag), 141
quota (group.RepGroupUUID.group attribute), 49          tags (tag.RepTag attribute), 142
quota (module), 121                                     tags (tag.RepTagList attribute), 143
QuotaGroupUUID (class in quota), 122                    templates (dtemplate.RepDtemplateList attribute), 33
QuotaList (class in quota), 123                         timestamp (log.RepLogUUID attribute), 82
QuotaUUID (class in quota), 121                         transactions (log.RepLogList attribute), 82
                                                        txid (vm.RepVm attribute), 199
R
RepBilling (class in billing), 17
                                                        U
RepCDMount (class in cdmount), 160                      Usage (class in usage), 163
RepClone (class in clone), 25                           usage (module), 163
RepDisk (class in disk), 162                            UsageUUID (class in usage), 163
RepDtemplateList (class in dtemplate), 33               User (class in user), 173
RepDtemplateUUID (class in dtemplate), 32               user (module), 173
RepErrCodes (class in util), 186                        user (user.RepUser attribute), 174
RepGroup (class in group), 48                           user_name (user.RepUserUUID.user attribute), 175
RepGroupList (class in group), 49                       UserList (class in user), 174
RepGroupUUID (class in group), 49                       users (group.RepGroupUUID.group attribute), 49
RepHtemplate (class in htemplate), 60                   users (user.RepUserList attribute), 175
RepHtemplateList (class in htemplate), 62               UserUUID (class in user), 173
RepHtemplateUUID (class in htemplate), 61               util (module), 185
RepI18N (class in util), 186                            uuid (dtemplate.RepDtemplateUUID attribute), 32
RepIconMap (class in util), 187                         uuid (group.RepGroupUUID.group attribute), 49
RepInterfaceList (class in interface), 156              uuid (log.RepLogUUID attribute), 82
RepInterfaceUUID (class in interface), 156              uuid (network.RepNetworkUUID.network attribute), 95
RepISOFile (class in isofile), 157                       uuid (user.RepUserUUID.user attribute), 175
RepLogList (class in log), 82                           uuid (vm.RepVmUUID.vm attribute), 200
RepLogUUID (class in log), 82
RepNetwork (class in network), 94
                                                        V
RepNetworkList (class in network), 95                   vlan_id (network.RepNetworkUUID.network attribute),
RepNetworkUUID (class in network), 95                             95
RepPtemplateList (class in ptemplate), 112              Vm (class in vm), 197
RepPtemplateUUID (class in ptemplate), 112              vm (module), 197
RepQuota (class in quota), 123                          VMDisk (class in disk), 161
RepQuotaList (class in quota), 124                      vmdisk (disk.RepDisk attribute), 162
RepQuotaUUID (class in quota), 123                      VMDiskUUID (class in disk), 161
RepTag (class in tag), 142                              VmList (class in vm), 198, 199
RepTagList (class in tag), 142                          vms (vm.RepVmList attribute), 201
RepUsage (class in usage), 164                          VmUUID (class in vm), 197
RepUser (class in user), 174                            vnc_enabled (vm.RepVmUUID.vm attribute), 200
RepUserList (class in user), 175                        vnc_ip_address (vm.RepVmUUID.vm attribute), 200
RepUserUUID (class in user), 175                        vnc_password (vm.RepVmUUID.vm attribute), 200
RepVm (class in vm), 199                                vnc_port (vm.RepVmUUID.vm attribute), 200


Index                                                                                                      225