Général:FAQ NouvelleInstance

De WikiFr_dbSQWare
Aller à : navigation, rechercher

Généralités

Limites de cette section

Cette section n’a pas la prétention de traiter tous les cas possibles de paramétrage de dbSQWare.
Avant de dire « ça ne fonctionne pas », lisez bien le message d’erreur et réfléchissez à ce dont vous avez besoin au niveau du socle pour que les scripts fonctionnent. Par exemple, si vous n’arrivez pas à faire un sqlplus en ligne de commande pour vous connecter à votre instance Oracle, il n’y a pas de raison pour que les scripts arrivent à le faire (il n’y a rien de magique) !

Paramétrage préalable

Afin de pouvoir utiliser l'API "update", vous devez au préalable avoir paramétré un login avec le type d'authentification "internal_api_update".

Exemples d'utilisation

Vous devez adapter les exemples suivants avec vos propres données (URL, user, password, ...)
Ceci représente une base pour du Python, PHP et shell.
Vous pouvez bien évidemment utiliser le langage de votre choix.

Python

import requests
import json

v_bearer_token = ""

"""
f_api_request does API request

:param v_method  : request method
:param v_url     : website url
:param t_headers : JSON object headers 
:param t_data    : JSON object data
:return          : API request return
"""
def f_api_request(v_method, v_url, t_headers={}, t_data={}):
    v_response = requests.request(v_method, v_url, headers=t_headers, data=t_data) # API request
    return v_response  

"""
f_get_bearer_token recovers bearer token

:param v_username : account username
:param v_password : account password
:return           : bearer token
"""
def f_get_bearer_token(v_username, v_password):
    v_method  = "POST"
    v_url     = "http://my_sqwareweb_url/lib/apiUpdate_login.php"
    t_headers = {'Content-Type': 'application/json'}
    t_data    = json.dumps({"username":v_username,"password":v_password}) # Crendentials for connection

    v_response = f_api_request(v_method, v_url, t_headers=t_headers, t_data=t_data) # API request
    v_json_response = json.loads(v_response.text)
    if "error_message" not in v_json_response:
        global v_bearer_token
        v_bearer_token = v_json_response['results'][0]['token'] # Get token response
        print("Bearer token : "+v_bearer_token)
        return 1
    else:
        v_error_message = v_json_response['error_message']
        print("Error message ["+v_error_message+"]")
        return 0

"""
f_get_instance recovers instance object

:param v_dbalias      : dbalias name
:return               : instance object
"""
def f_get_instance(v_dbalias):
    v_method  = "GET"
    v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias="+v_dbalias
    t_headers = {'Authorization':'Bearer '+v_bearer_token, 'Content-Type': 'application/json'}

    v_response = f_api_request(v_method, v_url, t_headers=t_headers) # API request
    v_json_response = json.loads(v_response.text)
    if "error_message" not in v_json_response:
        v_instance = v_json_response['results'][0] # Get instance
        print(v_instance)
        return 1
    else:
        v_error_message = v_json_response['error_message']
        print("Error message ["+v_error_message+"]")
        return 0

"""
f_get_instances recovers instances objects

:return               : instances objects
"""
def f_get_instances():
    v_method  = "GET"
    v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php"
    t_headers = {'Authorization':'Bearer '+v_bearer_token, 'Content-Type': 'application/json'}

    v_response = f_api_request(v_method, v_url, t_headers=t_headers) # API request
    v_json_response = json.loads(v_response.text)
    if "error_message" not in v_json_response:
        v_instances = v_json_response['results'] # Get instances
        print(v_instances)
        return 1
    else:
        v_error_message = v_json_response['error_message']
        print("Error message ["+v_error_message+"]")
        return 0

"""
f_post_instance create new instance object

:param t_data         : JSON object data
:return               : request response
"""
def f_post_instance(t_data):
    v_method  = "POST"
    v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php"
    t_headers = {'Authorization':'Bearer '+v_bearer_token, 'Content-Type': 'application/json'}
    t_data    = json.dumps(t_data)

    v_response = f_api_request(v_method, v_url, t_headers=t_headers, t_data=t_data) # API request
    v_json_response = json.loads(v_response.text)
    if "error_message" not in v_json_response:
        print("Insert with success !")
        return 1
    else:
        v_error_message = v_json_response['error_message']
        print("Error message ["+v_error_message+"]")
        return 0

"""
f_put_instance update instance object

:param v_dbalias      : dbalias name
:param t_data         : JSON object data
:return               : request response
"""
def f_put_instance(v_dbalias, t_data):
    v_method  = "PUT"
    v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias="+v_dbalias
    t_headers = {'Authorization':'Bearer '+v_bearer_token, 'Content-Type': 'application/json'}
    t_data    = json.dumps(t_data)

    v_response = f_api_request(v_method, v_url, t_headers=t_headers, t_data=t_data) # API request
    v_json_response = json.loads(v_response.text)
    if "error_message" not in v_json_response:
        print("Update with success !")
        return 1
    else:
        v_error_message = v_json_response['error_message']
        print("Error message ["+v_error_message+"]")
        return 0

def main():
    # Variables
    v_username = "toto"
    v_password = "toto"
    v_dbalias  = "toto"

    # Get bearer token
    f_get_bearer_token(v_username, v_password)

    # Post new instance
    t_data = {
                "dbalias"       :v_dbalias,
                "rdbmsname"     :"cassandra",
                "virt_host_name":"AA-TEST-API",
                "host_name"     :"NPW",
                "username"      :"system",
                "port"          :"1430",
                "comments"      :"desc IPS_A",
                "contact"       :"OAY .L",
                "status"        :"ON",
                "client"        :"CUST2",
                "env"           :"PRD3",
                "globalhost"    :"A",
                "custom1"       :"B",
                "custom2"       :"C",
                "dbaname"       :v_username,
                "comments_upd"  :"insert new instance by API"
            }

    f_post_instance(t_data)

    # Get new instance
    f_get_instance(v_dbalias)

    # Put new instance
    t_data = {
                "rdbmsname"     :"mysql",
                "virt_host_name":"AA-TEST-API",
                "host_name"     :"NPW",
                "username"      :"system",
                "port"          :"1430",
                "comments"      :"desc IPS_A",
                "contact"       :"OAY .L",
                "status"        :"OFF",
                "client"        :"CUST2",
                "env"           :"PRD3",
                "globalhost"    :"A",
                "custom1"       :"B",
                "custom2"       :"C",
                "comments_upd"  : "update instance status by API"
            }

    f_put_instance(v_dbalias, t_data)

    # Get all instances
    f_get_instances()

if __name__ == '__main__':
    main()

PHP

<?php

$v_bearer_token = "";

/**
 * f_api_request does API request
 * 
 * @param String $v_method : request method
 * @param String $v_url    : website url
 * @param Array $t_headers : JSON object headers 
 * @param Array $t_data    : JSON object data
 * @return $v_response     : API request return
 */
function f_api_request($v_method, $v_url, $t_headers=[], $t_data='{}'){
    $v_curl = curl_init();

    curl_setopt_array($v_curl, array(
        CURLOPT_URL            => $v_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => ,
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => $v_method,
        CURLOPT_POSTFIELDS     => $t_data,
        CURLOPT_HTTPHEADER     => $t_headers,
    ));

    $v_response = curl_exec($v_curl);
    return $v_response;
}

/**
 * f_get_bearer_token recovers bearer token
 * 
 * @param String $v_username : account username
 * @param String $v_password : account password
 * @return $v_bearer_token   : bearer token
 */
function f_get_bearer_token($v_username, $v_password){
    $v_method  = "POST";
    $v_url     = "http://my_sqwareweb_url/lib/apiUpdate_login.php";
    $t_headers = array('Content-Type: application/json');
    $t_data    = json_encode(array("username" => $v_username, "password" => $v_password), JSON_FORCE_OBJECT); // Crendentials for connection

    $v_response = f_api_request($v_method, $v_url, $t_headers=$t_headers, $t_data=$t_data); // API request
    $v_json_response = json_decode($v_response, true);
    if(!array_key_exists("error_message", $v_json_response)){
        global $v_bearer_token;
        $v_bearer_token = $v_json_response['results'][0]['token']; // Get token response
        echo("Bearer token : $v_bearer_token");
        return 0;
    }
    else{
        $v_error_message = $v_json_response['error_message'];
        echo("Error message [$v_error_message]");
        return 1;
    }
}

/**
 * f_get_instance recovers instance object
 * 
 * @param String $v_dbalias      : dbalias name
 * @return $v_instance           : instance object
 */
function f_get_instance($v_dbalias){
    global $v_bearer_token;
    $v_method  = "GET";
    $v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=".$v_dbalias;
    $t_headers = array('Authorization: Bearer '.$v_bearer_token., 'Content-Type: application/json');

    $v_response = f_api_request($v_method, $v_url, $t_headers=$t_headers); // API request
    $v_json_response = json_decode($v_response, true);
    if(!array_key_exists("error_message", $v_json_response)){
        $v_instance = $v_json_response['results'][0]; // Get instance
        var_dump($v_instance);
        return 0;
    }
    else{
        $v_error_message = $v_json_response['error_message'];
        echo("Error message [$v_error_message]");
        return 1;
    }
}

/**
 * f_get_instances recovers instances objects
 * 
 * @return $v_instances          : instances objects
 */
function f_get_instances(){
    global $v_bearer_token;
    $v_method  = "GET";
    $v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php";
    $t_headers = array('Authorization: Bearer '.$v_bearer_token., 'Content-Type: application/json');

    $v_response = f_api_request($v_method, $v_url, $t_headers=$t_headers); # API request
    $v_json_response = json_decode($v_response, true);
    if(!array_key_exists("error_message", $v_json_response)){
        $v_instance = $v_json_response['results']; // Get instances
        var_dump($v_instance);
        return 0;
    }
    else{
        $v_error_message = $v_json_response['error_message'];
        echo("Error message [$v_error_message]");
        return 1;
    }
}

/**
 * f_post_instance create new instance object
 * 
 * @param Array $t_data          : JSON object data
 * @return Array mixed[]         : request response
 */
function f_post_instance($t_data){
    global $v_bearer_token;
    $v_method  = "POST";
    $v_url     = "http://my_sqwareweb_url/lib/apiUpdate.php";
    $t_headers = array('Authorization: Bearer '.$v_bearer_token., 'Content-Type: application/json');
    $t_data    = json_encode($t_data, JSON_FORCE_OBJECT);

    $v_response = f_api_request($v_method, $v_url, $t_headers=$t_headers, $t_data=$t_data); // API request
    $v_json_response = json_decode($v_response, true);
    if(!array_key_exists("error_message", $v_json_response)){
        echo("Insert with success !");
        return 0;
    }
    else{
        $v_error_message = $v_json_response['error_message'];
        echo("Error message [$v_error_message]");
        return 1;
    }
} 

/**
 * f_put_instance update instance object
 * 
 * @param String $v_dbalias      : dbalias name
 * @param Array $t_data          : JSON object data
 * @return Array mixed[]         : request response
 */
function f_put_instance($v_dbalias, $t_data){
    global $v_bearer_token;
    $v_method  = "PUT";
    $v_url      = "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=".$v_dbalias;
    $t_headers = array('Authorization: Bearer '.$v_bearer_token., 'Content-Type: application/json');
    $t_data    = json_encode($t_data, JSON_FORCE_OBJECT);

    $v_response = f_api_request($v_method, $v_url, $t_headers=$t_headers, $t_data=$t_data); // API request
    $v_json_response = json_decode($v_response, true);
    if(!array_key_exists("error_message", $v_json_response)){
        echo("Update with success !");
        return 0;
    }
    else{
        $v_error_message = $v_json_response['error_message'];
        echo("Error message [$v_error_message]");
        return 1;
    }
}

function main(){
    // Variables
    $v_username = "toto";
    $v_password = "toto";
    $v_dbalias  = "toto";

    // Get bearer token
    f_get_bearer_token($v_username, $v_password);

    // Post new instance
    $t_data = array(
                        "dbalias"        => $v_dbalias,
                        "rdbmsname"      => "cassandra",
                        "virt_host_name" => "AA-TEST-API",
                        "host_name"      => "NPW",
                        "username"       => "system",
                        "port"           => "1430",
                        "comments"       => "desc IPS_A",
                        "contact"        => "OAY .L",
                        "status"         => "ON",
                        "client"         => "CUST2",
                        "env"            => "PRD3",
                        "globalhost"     => "A",
                        "custom1"        => "B",
                        "custom2"        => "C",
                        "dbaname"        => $v_username,
                        "comments_upd"   => "insert new instance by API"
                    );

    f_post_instance($t_data);

    // Get new instance
    f_get_instance($v_dbalias);

    // Put new instance
    $t_data = array(
                        "dbalias"        => $v_dbalias,
                        "rdbmsname"      => "mysql",
                        "virt_host_name" => "AA-TEST-API",
                        "host_name"      => "NPW",
                        "username"       => "system",
                        "port"           => "1430",
                        "comments"       => "desc IPS_A",
                        "contact"        => "OAY .L",
                        "status"         => "OFF",
                        "client"         => "CUST2",
                        "env"            => "PRD3",
                        "globalhost"     => "A",
                        "custom1"        => "B",
                        "custom2"        => "C",
                        "comments_upd"   => "update instance status by API"
                    );

    f_put_instance($v_dbalias, $t_data);

    // Get all instances
    f_get_instances();
}

main();

?>

Shell

#!/bin/sh

v_bearer_token=""
v_tempfile=api_dbSQWare.tmp

<<COMMENTS
    f_get_bearer_token recovers bearer token

    :param v_username : account username
    :param v_password : account password
    :param v_tempfile : temporary file
    :return           : bearer token
COMMENTS
f_get_bearer_token(){
    v_username="$1"
    v_password="$2"
    v_tempfile="$3"

    curl --location --request POST "http://my_sqwareweb_url/lib/apiUpdate_login.php" -H "Content-Type:application/json" -d '{"username":"'$v_username'","password":"'$v_password'"}' > $v_tempfile 2>$v_tempfile.err
	if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
	then
        # Get bearer token
		v_bearer_token=`cat $v_tempfile|grep '\"token\":\"' | cut -d'"' -f4`
        echo "Bearer token : $v_bearer_token"
		return 0
	else
		v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
        echo "Error message [$v_error_message]"
		return 1
	fi
}

<<COMMENTS
    f_get_instance recovers instance object

    :param v_dbalias : dbalias name
    :return          : instance object
COMMENTS
f_get_instance(){
    v_dbalias="$1"

    curl --location --request GET "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=$v_dbalias" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" > $v_tempfile 2>$v_tempfile.err
	if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
	then
        # Get instance
        v_instance=`cat $v_tempfile|grep -A 1 '\"results\":'`
        echo "Instance : $v_instance"
		return 0
	else
		v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
        echo "Error message [$v_error_message]"
		return 1
	fi
}

<<COMMENTS
    f_get_instances recovers instances objects

    :return : instances objects
COMMENTS
f_get_instances(){
    curl --location --request GET "http://my_sqwareweb_url/lib/apiUpdate.php" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" > $v_tempfile 2>$v_tempfile.err
	if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
	then
		# Get instances
		v_instances=`cat $v_tempfile|grep -A 1 '\"results\":'`
        echo "Instances : $v_instances"
		return 0
	else
        v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
        echo "Error message [$v_error_message]"
		return 1
	fi
}

<<COMMENTS
    f_post_instance create new instance object

    :param t_data : JSON object data
    :return       : request response
COMMENTS
f_post_instance(){
    t_data="$1"

    curl --location --request POST "http://my_sqwareweb_url/lib/apiUpdate.php" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" -d "$t_data" > $v_tempfile 2>$v_tempfile.err
	if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
	then
		echo "Insert with success !"
		return 0
	else
		v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
        echo "Error message [$v_error_message]"
		return 1
	fi
}

<<COMMENTS
    f_put_instance update instance object

    :param v_dbalias : dbalias name
    :param t_data    : JSON object data
    :return          : request response
COMMENTS
f_put_instance(){
    v_dbalias="$1"
    t_data="$2"

    echo $t_data > test.tmp
    curl --location --request PUT "http://my_sqwareweb_url/lib/apiUpdate.php?dbalias=$v_dbalias" -H "Authorization: Bearer $v_bearer_token" -H "Content-Type:application/json" -d "$t_data" > $v_tempfile 2>$v_tempfile.err
	if [ $(grep -c '"error_message"' $v_tempfile) -eq 0 ]
	then
		echo "Update with success !"
		return 0
	else
		v_error_message=`cat $v_tempfile|grep '\"error_message\": \"' | cut -d'"' -f4`
        echo "Error message [$v_error_message]"
		return 1
	fi
}

main(){
    # Variables
    v_username="toto";
    v_password="toto";
    v_dbalias="toto";

    # Get bearer token
    f_get_bearer_token $v_username $v_password $v_tempfile

    # Post new instance
    t_data='{"dbalias":"'$v_dbalias'","rdbmsname":"cassandra","virt_host_name":"AA-TEST-API","host_name":"NPW","username":"system","port":"1430","comments":"desc IPS_A","contact":"OAY .L","status":"ON","client":"CUST2","env":"PRD3","globalhost":"A","custom1":"B","custom2":"C","dbaname":"'$v_username'","comments_upd":"insert new instance by API"}'
    f_post_instance "$t_data"

    # Get new instance
    f_get_instance $v_dbalias

    # Put new instance
    t_data='{"rdbmsname":"mysql","virt_host_name":"AA-TEST-API","host_name":"NPW","username":"system","port":"1430","comments":"desc IPS_A","contact":"OAY .L","status":"OFF","client":"CUST2","env":"PRD3","globalhost":"A","custom1":"B","custom2":"C","comments_upd":"update instance status by API"}'
    f_put_instance $v_dbalias "$t_data"

    # Get all instances
    f_get_instances
}

main