MRatWork Forum by Mustafa Ramadhan

Sawo Project - Kloxo-MR Discussions => Kloxo-MR Development => Topic started by: MRatWork on 2017-06-11, 16:59:05

Title: Kloxo API
Post by: MRatWork on 2017-06-11, 16:59:05
Kloxo-API (taken from LxCenter Wiki)

Kloxo/HyperVM API

JSON

Our JSON based API provides the most comprehensive and robust interface for external programs to interact with Kloxo/HyperVM, and all our future integration efforts will be centered around the theme of JSON. Please check JSON for a better idea of what exactly is JSON, and how the LxCenter API uses it for communication.

What is JSON

JSON, is an object string notation. For people who are familiar with the serialize function available in the scripting languages, JSON wouldn't be anything new. The reason for using JSON instead of the native php serialization is that JSON will work across languages. The advantage JSON provides over traditional XML or mere url notation output is that, with JSON all interactions happens via objects, and you don't need to do any output parsing. Kloxo & HyperVM will be outputing direct objects, and these objects will be directly accessible in your code, whatever language it is written in.

Initialization Prerequisites

There is one minor drawback, and it is that the language that you use has to support JSON serialize/unserialize befor you can utilize our new API. PHP natively supports JSON via the json_serialize and json_unserialize functions from version 5.2.1 onwards, . For pre-5.2.1, you can install the JSON serialize, unserialize functions that are implemented in PHP itself. You can get it from here http://mike.teczno.com/JSON.tar.gz (http://"http://mike.teczno.com/JSON.tar.gz" rel="nofollow")


The basic interaction between Kloxo/HyperVM happens like this: Let us say you want to get a list of domains from Kloxo. The API command is simplelist. To get the list, you send the simplelist command to Kloxo, and get the output.

Code: [Select]
$string = url_get("webcommand.php?login-class=client&login-name=admin&login-password=pass&output-type=json&action=simplelist&resource=domain");
Please note the output-type variable. You will have to specify this if you want to use the JSON interface. This is necessary to provide backward compatibility. If you don't specify the output-type=json, Kloxo will use the old style url notation to print the output, and so the older programs that used to interface with Kloxo via this method will work fine.

The output of the above command would be json encoded string. To get the actual object, unserialize it via the json_unserialize.

Code: [Select]
require_once('JSON.php');
$json = new Services_JSON();
$result = $json->decode($string);

As I had explained, $result is a pure PHP object, and contains three values. $return, $result, and $message. The $return is a string and is either "error" or "success". $message is also a string which would be the error/success messages: For instance: "Error_login_error". If you send anything to Kloxo/HyperVM, you will have to do proper error checking and warn the customer of the problem.

Code: [Select]
if (lxlabs_if_error($result)) {
    print("Server gave error and we cannot continue, The message was $result->message\n");
    exit;
}

If the return is success, then the data you seek will be present in the result variable, and in this particular case -that is the simplelist command- the data will be available as an associative array.

Code: [Select]
// Else clause for the above if.
print("Success: The server returned these values:");
print_r($result->result);
Title: Re: Kloxo API
Post by: MRatWork on 2017-06-11, 18:45:40
JSON Code Examples

Here are some Code Examples for common uses of JSON.

Function lxlabs_get_via_json

Since you are interacting with a specific server, there is no need to provide all the variables all the time in the higher level functions. So we will write a function called lxlabs_get_via_json. This function takes 4 parameters, and uses the JSON library to return a PHP object back.

Code: [Select]
function lxlabs_get_via_json($protocol, $server, $port, $param)
{
    $param = "login-class=client&login-name=admin&login-password=pass&output-type=json&$param";
    $url = "$protocol://$server:$port/webcommand.php";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    $totalout = curl_exec($ch);
    $totalout = trim($totalout);
    require_once('JSON.php');
    $json = new Services_JSON();
    $object = $json->decode($totalout);

    if (!is_object($object)) {
        print("Fatal Error. Got a non-object from the server: $totalout\n");
        exit;
    }

    return $object;
}

Function lxlabs_if_error

This is a function to check if the return value from lxadmin/hyperVM is error or not.

Code: [Select]
function lxlabs_if_error($json)
{
    return $json->return === 'error';
}

Function lxlabs_get_and_print_select_variable

This is a high level function that will print a select block containing the resource values.

Code: [Select]
function lxlabs_get_and_print_select_variable($description, $remotevar, $localvar)
{
    // Send the remote variable to hypervm and get the result.

    $json = lxlabs_get_via_json("http", $server, $port, "action=simplelist&resource=$remotevar");

    if (lxlabs_if_error($json)) {
        print("The server said, error. The message is: $json->message\n");
        exit;
    }
    lxlabs_print_select($localvar, $description, $json->result);
    print("<br> ");
}

Function lxlabs_print_select

This function prints a select box so that when a customer chooses a display name, the corresponding unique name is sent via the form.

Code: [Select]
function lxlabs_print_select($var, $displayvar, $list)
{
    print("Select a $displayvar");
    print("<option value="$uniquename"]$displayname</option>"); }

Listing Resources Example

Now that we have seen all the code examples we can see how we can list resources and perform more complex tasks. All resource objects in Kloxo/HyperVM will depend on other resources. For instance, to add a domain, you need to provide a Resource Plan as an input. To provide the correct resource plan, you will have to first get a list of resource plans from Kloxo/HyperVM and then ask the client to select one. So understanding the lxadmin's listing policy becomes pivotal to writing a good interaction system. Kloxo/HyperVM now has a universal listing method, and it can be used on any resource object, whether it be domain, client, vps, vpspserver_openvz.

Listing a resource

The action for listing is simplelist and the resource name is sent via the resource variable. So let us say you need a list of Resource Plans in Kloxo. The command would be like this:

Code: [Select]
$json = lxlabs_get_via_json("http", $server, "7778", "action=simplelist&amp;resource=resourceplan");
The $json is a JSON object. And the actual list is contained in the result property.

Code: [Select]
$list = $json->result
For simplelist, the $json->result is an associative array. Why are we using an associative array, and not a simple array? The reason is that many resources have two distinct key values: The display name, and the unique name. For instance, let us take resource plans. Each customer can have his own resource plans, and the display can overlap. One customer using a plan called silver doesn't preclude another from using the same name. So to distinguish between the two resource having the same display names, Kloxo/HyperVM will use an internal unique name by concatenating the display name with the client's name. So when you use the simple list, you are getting an associative array containing both the display name and the unique name. The format of the array is this:

Code: [Select]
$list[['unique_name'] = 'display_name';
The key idea is that you need not show the customer the unique name. In the select option, you only show the display name, and create the select box in such a way that when a customer chooses a display name, the form will automatically send the unique name. This can be accomplished quite easily. The function API#Function lxlabs_print_select (http://"#Function_lxlabs_print_select" title="API") from above will create a select box in such a way that it will transparently maintain the relationship between display name and the unique-name

Code: [Select]
$json = lxlabs_get_via_json("http", $server, "7778", "action=simplelist&amp;resource=resourceplan");
if (lxlabs_if_error($json)) {
    print("Server gave error: Message: $json->message.\n");
    exit;
}
lxlabs_print_select("v-plan_name", "Resource Plan", $json->result);

You can use JSON API#Function lxlabs_get_via_json (http://"#Function_lxlabs_get_via_json" title="API") function from above to get any listing.

Code: [Select]
$domain_list = lxlabs_get_via_json("http", $server, "7778", "action=simplelist&amp;resource=domain");
$server_list = lxlabs_get_via_json("http", $server, "7778", "action=simplelist&amp;resource=vpspserver_openvz");

Title: Re: Kloxo API
Post by: MRatWork on 2017-06-11, 18:50:36
Using JSON for webapplications (PHP)

All interactions happens via the file /webcommand.php. This is the file that handles the API for both Kloxo and HyperVM. You can access them as: http://server:7778/webcommand.php?login-class=client (http://"http://server:7778/webcommand.php?login-class=client" rel="nofollow")

The next step is the listing. This is essential because, to add one resource, you will need to provide another as the input, and to do this, you will need to first get the list of the existing resources in Kloxo. You can see API#Listing Resources Example (http://"#Listing_Resources_Example" title="API") for more information on that.

Once you have understood the Kloxo JSON object model and how to list any resource, we can move to the next step:
Adding a resource with JSON

Kloxo &amp; HyperVM has a universal method to add any resource object: it is via the action add. Two parameters are always universally needed: class and name. The class can be anything: client, domain, vps, subdomain etc. Rest of the parameters like 'v-plan_name', 'v-type' will depend on the class of the object you are trying to add.
We will be focussing here on how to add a client on Kloxo and a VM on HyperVM. For HyperVM, you shouldn't add a client, unless the client has more than 1 VM.

Add a Client to Kloxo

Adding happens via the action add. To add a client to Kloxo, the parameters you provide are:

To provide the v-plan_name, you need to first get the list of resource plans in the account. We have written above a high level function called lxlabs_get_and_print_select_variable see API#Function lxlabs_get_and_print_select_variable (http://"#Function_lxlabs_get_and_print_select_variable" title="API") that will get the list of resources, and print a select box.

You can also provide a domain name, in which case a domain will be added to the client's account. To add a domain when adding a client, you have to provide two variables: v-domain_name and v-dns_template. You get the dns template by using the "function Listing Resources Example" we explained above API#Listing Resources Example (http://"#Listing_Resources_Example" title="API") to list the dns templates.

Code: [Select]
<form method=post action=$server:7778/bin/webcommand.php>
<input type=hidden name=login-class value=client>
<input type=hidden name=login-name value=admin>
<input type=hidden name=login-password value=lxlabs>
<input type=hidden name=action value=add>
<input type=hidden name=class value=client>
<input type=hidden name=v-type value=customer>
Client name: <br>
<input type=text name=name value=> <br>
Contact Email <br>
<input type=text name=v-contactemail value=> <br>
<input type=hidden name=v-send_welcome_f value=on> <br>
Password<br>
<input type=text name=v-password value=> <br>
<input type=submit name=submit value=submit> <br>

Add a VM to HyperVM

The variables needed are:
Of the above parameters, v-ostemplate, v-syncserver and v-plan_name has to be selected from a list of values. To get the list of values, please see API#Listing Resources Example (http://"#Listing_Resources_Example" title="API"). For instance, to let the customer select from a list of available OStemplates, you have to first query the HyperVM server and get a list of availalbe OStemplates for OpenVZ.

v-send_welcome_f is a flag variable that tells HyperVM whether to send welcome message to the client or not. The values are either 'on' or off'.

Code: [Select]
$ostemplate_list_json = lxlabs_get_via_json("http", $server", "8888", "action=simplelist&amp;resource=ostemplate_openvz");
$syncserver_list_json = lxlabs_get_via_json("http", $server", "8888", "action=simplelist&amp;resource=vpspserver_openvz");

Below is a webform that can directly add a VM to HyperVM. We are directly using the high level function API#Function lxlabs_get_and_print_select_variable (http://"#Function_lxlabs_get_and_print_select_variable" title="API") to automatically query the HyperVM server to get a list of available resources and automatically generate a select box.

Code: [Select]
<input type=hidden name=login-class value=client>
<input type=hidden name=login-name value=admin>
<input type=hidden name=login-password value=hell>
<input type=hidden name=action value=add>
<input type=hidden name=class value=vps>
 
<input type=hidden name=v-type value=openvz>
VM Type: openvz <br>
VM name: <br>
<input type=text name=name value=> <br>
 
Number of IP addresses <br>
<input type=text name=v-num_ipaddress_f value=> <br>
 
Contact Email <br>
<input type=text name=v-contactemail value=> <br>
 
<input type=hidden name=v-send_welcome_f value=on> <br>
 
Password<br>
<input type=text name=v-password value=> <br>
<?php
lxlabs_get_and_print_select_variable
("Ostemplate""ostemplate_openvz""v-ostemplate");
lxlabs_get_and_print_select_variable("Server""vpspserver_openvz""v-syncserver");
lxlabs_get_and_print_select_variable("Plan""resourceplan""v-plan_name");
?>

<input type=submit name=submit value=submit> <br>
Title: Re: Kloxo API
Post by: MRatWork on 2017-06-11, 18:53:31
Updating resources with JSON

Kloxo/HyperVM also provides API for suspend/unsuspending the VPS/Client, via the universal update action.

Updating a Resource

Kloxo and HyperVM also provides a generic update action, which can be used to make any changes to any resource. The update action allows you to make any change to a resource via the ability to specify the 'subaction', which will let you specify the type of update you are trying to perform.

Code: [Select]
class = vps/client
name = name
action = update
subaction = ...

For examples of update, see bellow API#Enable or disable a resource (http://"#Enable_or_disable_a_resource" title="API")

Enable or Disable a Resource

Kloxo &amp; HyperVM also provides a generic see above [[[API#Updating a resource]] action, which can be used to make any changes to any resource. Suspend/Unsuspend a VM or a Client is a subset of the generic update action, and achieved via the subaction disable/enable.
The parameters are:
You can use the API#Function lxlabs_get_via_json (http://"#Function_lxlabs_get_via_json" title="API") for making updates to resources

Function to suspend a VM at HyperVM.

Code: [Select]
$result = lxlabs_get_via_json("http", $server, "8888", "class=vps&amp;name=name.vm&amp;action=update&amp;subaction=disable);
if (lxlabs_if_error($result)) {
    print("Disable failed.. Server said: $result->message);
}

In the same way for Kloxo:

Code: [Select]
$result = lxlabs_get_via_json("http", $server, "7778", "class=client&amp;name=clientname&amp;action=update&amp;subaction=enable);
if (lxlabs_if_error($result)) {
    print("Enable failed.. Server said: $result->message);
}

See for reference:

Reboot a VM

Rebooting a VM is done via the the generic API#Updating a resource (http://"#Updating_a_resource" title="API") action. The parameters are:
The code:

Code: [Select]
$json = lxlabs_get_via_json("action=update&amp;subaction=reboot&amp;class=vps&amp;name=vps.vm");
if (lxlabs_if_error($json)) {
    print("Reboot failed. Server said $json->message\n");
} else {
    print("Reboot success.\n");
}

See for reference:

Deleting a resource

There is a universal command for deleting a resource and is done via the action 'delete'. All you need to provide are the class and the name.
The parameters are

To delete a client

Code: [Select]
$json = lxlabs_get_via_json("action=delete&amp;class=client&amp;name=name");
if (lxlabs_if_error($json)) {
    print("Delete failed... Server said: $json->message\n");
    exit;
} else {
    print("Delete Succeeded\n");
}

See for reference:

Getting properties from an object

You can edit properties from an object, but first you neet to get properties, and is implemented via the action getproperty.

Code: [Select]
action = getproperty
v-variable1 = null
v-variable2 = null
v-priv-variable3 = null
v-used-variable3 = null

Note1: the above will get you the property of the login object, that is the resource you have logged into. For instance, the admin. To get the property of any object, please see below.

Note2: priv and used are the objects in which the limits and usages are kept respectively. So v-priv-traffic_usage gets translated by lxadmin into $object->priv->traffic_usage, which represents the traffic usage limit, and v-used-traffic_usage gets translated as $object->used->traffic_usage, which represents the current usage for the same variable.

Code: [Select]
$json = lxlabs_get_via_json("action=getproperty&amp;v-used-traffic_usage=&amp;v-used-totaldisk_usage=");
if (lxlabs_if_error($json)) {
    print("Got error: server said: $json->message");
} else {
    print("The value of traffic usage is {$json->result[['v-used-traffic_usage']}");
    print("The value of total disk usage is {$json->result[['v-used-totaldisk_usage']}");
}

The result will be available in the $result variable of the JSON PHP object, and will be an associative array, with a $list[[property-name] = variable-valueformat.

Code: [Select]
action = getproperty
class = domain/client/vps
name = domain.com
v-variable1 = null
v-variable2 = null
v-priv-variable3 = null
v-used-variable3 = null
Code: [Select]
$json = lxlabs_get_via_json("action=getproperty&amp;class=domain&amp;name=domain.com&amp;v-used-traffic_usage=&amp;
v-used-maildisk_usage=&amp;v-used-mysqldb_usage=");
if (lxlabs_if_error($json)) {
    print("Got error: server said: $json->message");
} else {
    print("The value of mysql disk usage is {$json->result[['v-used-mysqldb_usage']}");
}


Code: [Select]
action = getproperty
class = domain/client/vps
name = domain.com
v-priv = null
v-used = null
Code: [Select]
$json = lxlabs_get_via_json("action=getproperty&amp;class=domain&amp;name=domain.com&amp;v-used=");
if (lxlabs_if_error($json)) {
    print("Got error: server said: $json->message");
} else {
    foreach($json->result as $k => $v) {
        print("The value of $k is $v");
    }
}


Code: [Select]
action = getproperty
class = vps
name = vps.vm
v-coma_vmipaddress_a = null
Code: [Select]
$json = lxlabs_get_via_json("action=getproperty&amp;class=vps&amp;name=vps.vm&amp;v-coma_vmipaddress_a=");
if (lxlabs_if_error($json)) {
    print("Got error: server said: $json->message");
} else {
    $iplist = explode(",", $json->result[['v-coma_vmipaddress_a']];
    print("The ips are:");
    foreach($iplist as $ip) {
        print("$ip\n");
    }
}

See for reference:

Usage Examples from commandline (Shell)
Editing In Progess!