Restart the Service Instance (v2)

Use the Restart the Service Instance (v2) REST API to restart the service instance.

This topic describes the simplified v2 version of this REST API. This version contains all parameters in the payload and does not require URL encoding while calling the REST APIs. This makes the v2 API easier to use. This API is backwards compatible.

You can also use an optional AutoTune parameter to auto-tune the environment before restarting it to ensure that Essbase index caches for Block Storage Option (BSO) cubes are optimized for your application.

This REST API is version v2.

Required Roles

Service Administrator

REST Resource

POST /interop/rest/v2/config/services/reset

Note:

Before using the REST resources, you must understand how to access the REST resources and other important concepts. See Implementation Best Practices for EPM Cloud REST APIs. Using this REST API requires prerequisites. See Prerequisites.

Request

Supported Media Types: application/json

Payload: JSON

Table 9-41 Parameters

Name Description Type Required Default
api_version Specific API version Path Yes None
comment Comment about executing the restart Payload Yes None
autotune If set to true, runs the auto tune algorithm before the restart. This ensures that Essbase index caches for BSO cubes are optimized for your application. Payload No false

Example of Request Body

{
  "comment": "Reset requested by Administrator",
  "parameters": {
     "autotune": "false" 
  }
}

Response

Table 9-42 Parameters

Name Description
Details In case of errors, details are published with the error string
Status See Migration Status Codes
Links Detailed information about the link
Href Links to API call or status API
Action The HTTP call type
Rel

Possible values: self and/or Job Status.

If the value is set to Job Status, you can use the href to get the status of the reset service

Data Parameters as key value pairs passed in the request

Example of Response Body in JSON Format

{
	"details": null,
	"status": 0,
	"links": [{
		"href": "https://<URL>/interop/rest/v2/config/services/reset",
		"rel": "self",
		"data": null,
		"action": "POST"
	},
	{
		"href": "https://<URL>/interop/rest/v2/config/status/service/hardreset/1",
		"rel": "Job Status",
		"data": null,
		"action": "GET"
	}]
}

Sample cURL command

curl -X POST -s -u '<USERNAME>:<PASSWORD>' -o response.txt -D respHeader.txt -H 'Content-Type: application/json' -d ' {"comment":"<COMMENT>","parameters":{"autotune":"false"}}' 'https://<SERVICE_NAME>-<TENANT_NAME>.<SERVICE_TYPE>.<dcX>.oraclecloud.com/interop/rest/v2/config/services/reset'

Sample cURL code

#!/bin/sh

USERNAME="<USERNAME>"
PASSWORD="<PASSWORD>"
SERVER_URL="<SERVICE_URL>"

APP_NAME="Vision"
API_VERSION="v2"

funcRemoveTempFiles() {
    for var in "$@"
    do
        if [ -f $var ]; then
            rm $var
        fi
    done
}

funcPrintErrorDetails() {
    contentType=`echo $(grep 'Content-Type:' respHeader.txt) | tr -d [:space:]`
    if [ ! -z $contentType ] && [[ $contentType = *"application/json"* ]]; then
        output=`cat $1`
        error=`echo $output | jq '.details'`
        echo "Error details: " $error
    fi
}

funcExecuteRequest() {
    if [ ! -z "$4" ]; then
        statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $4" -d "$3" $2`
    else
        statusCode=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "response.txt" -D "respHeader.txt" -H "Content-Type: $3" $2`
    fi

    if [ $statusCode != 200 ]; then
        echo "Error executing request"
        if [ $statusCode != 000 ]; then
            echo "Response error code : " $statusCode
            funcPrintErrorDetails "response.txt"
            funcRemoveTempFiles "respHeader.txt" "response.txt"
        fi
        exit 0
    fi
}

funcGetStatus() {
    output=`cat response.txt`
    count=`echo $output | jq '.links | length'`
    i=0
    pingUrl=""

    while [ $i -lt $count ]; do
        rel=`echo $output | jq '.links['$i'].rel'`
        rel=`echo "$rel" | tr -d "\""`
        if [ "$rel" == "Job Status" ]; then
                pingUrl=`echo $output | jq '.links['$i'].href'`
                pingUrl=`echo "$pingUrl" | tr -d "\""`
        fi
        i=`expr $i + 1`
    done

    echo $pingUrl
    completed="false"

    while [ $completed != "true" ]; do
        statusCode2=`curl -X $1 -s -w "%{http_code}" -u "$USERNAME:$PASSWORD" -o "pingResponse.txt"  -H "Content-Type: application/json" "$pingUrl"`
        if [ $statusCode2 == 200 ]; then
            status2=`jq '.status' pingResponse.txt`
            if [ $status2 != -1 ]; then
                completed="true"
                echo "Job completed"
            else
                echo "Please wait..."
                sleep 20
            fi
        else
            echo "Please wait..."
            sleep 20
        fi
        funcRemoveTempFiles "pingResponse.txt"
    done
}

funcHardReset() {
    echo "Are you sure you want to restart the service instance (yes/no): no? [Press Enter] "
    read toReset
    if [ $toReset != "yes" ]; then
        echo "User cancelled the reset command"
        exit 0
    fi

    url=$SERVER_URL/interop/rest/$API_VERSION/config/services/reset
    comment=$(echo $1)
    param="{\"comment\":\"${comment}\",\"parameters\":{\"autotune\":\"false\"}}"
    funcExecuteRequest "POST" "$url" "$param" "application/json"

    output=`cat response.txt`
    status=`echo $output | jq '.status'`
    
    if [ "${status}" == -1 ]; then
        echo "Started hard reset succesfully"
        funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi

    funcRemoveTempFiles "respHeader.txt" "response.txt"
}

funcRecreateService() {

    removeAll=$1
    essbaseChange=$2
    tempServiceType=$3
    
    echo "Are you sure you want to recreate the EPM environment (yes/no): no? [Press Enter] "
    read toCreate

    if [ $toCreate != "yes" ]; then
        echo "User cancelled the recreate command"
        exit 0
    fi

    url=$SERVER_URL/interop/rest/$API_VERSION/config/services/recreate
    param="{\"parameters\":{\"removeAll\":\"${removeAll}\",\"essbaseChange\":\"${essbaseChange}\", \"tempServiceType\":\"${tempServiceType}\"}}"
    
    funcExecuteRequest "POST" "$url" "$param" "application/json"
    output=`cat response.txt`
    status=`echo $output | jq '.status'`

    if [ $status == -1 ]; then
        echo "Started recreating the environment successfully"
                funcGetStatus "GET"
    else
        error=`echo $output | jq '.details'`
        echo "Error occurred. " $error
    fi

    funcRemoveTempFiles "respHeader.txt" "response.txt"
}

if [[ "$#" != "1" ]]; then
    echo "Mandatory argument missing"
    echo "Usage: EPMRestSamples <option>"
    echo "  where <option> is -recreate or -reset"
    exit 1
fi

if [ "${1}" == "-reset" ]; then
    funcHardReset "POC Exit Criteria Check - cURL"
elif [ "${1}" == "-recreate" ]; then
    funcRecreateService "false" "default" ""
else
    echo "Incorrect usage"
    echo "Usage: EPMRestSamples <option>"
    echo "  where <option> is -recreate or -reset"
    exit 1
fi

Sample Java Code

package com.oracle.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import java.util.Base64;

import org.json.JSONArray;
import org.json.JSONObject;


/*
 * EPM Rest Samples.
 * The userName variable uses the format <domain>.<username>.
 */
public class EPMRestSamples {

    private String userName;            // EPMCloud user name
    private String password;            // EPMCloud user password
    private String serverUrl;           // EPMCloud server URL
    private String apiVersion="v2";     // Version of the EPMCloud Rest API

    private long startTime;
    private long endTime;
    private long maxLoopTime=(60 * 60 * 1000);

    public static void main(String[] args) {
        try {

            if(null == args || args.length != 1) {
                System.err.println("Mandatory argument missing");
                System.err.println("Usage: EPMRestSamples <option>");
                System.err.println("  where <option> is -recreate or -reset");
                System.exit(1);
            }

            // TODO: Use appropriate username, password, and URL
            EPMRestSamples samples = new EPMRestSamples(
                "<USERNAME>", "<PASSWORD>","<SERVICE_URL>");

            String option = args[0];
            if("-reset".equalsIgnoreCase(option)) {
                samples.hardReset("POC Exit Criteria Check - Java");
            }
            else if("-recreate".equalsIgnoreCase(option)) {
                samples.recreateService("false", "default", "");
            }
            else {
                System.err.println("Incorrect usage");
                System.err.println("Usage: EPMRestSamples <option>");
                System.err.println("  where <option> is -recreate or -reset");
                System.exit(1);
            }
        }
        catch (Throwable x) {
            System.err.println("Error: " + x.getMessage());
        }
    }

    public EPMRestSamples(String userName, String password, String serverUrl) throws Exception {
        this.userName = userName;
        this.password = password;
        this.serverUrl = serverUrl;
    }

    private String getStringFromInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;

        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (br != null) {
                try { br.close(); }
                catch (IOException e) { e.printStackTrace(); }
            }
        }
        return sb.toString();
    }

    private String executeRequest(String urlString, String requestMethod, String payload, String contentType) throws Exception {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            Base64.Encoder encoder = Base64.getEncoder();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(requestMethod);
            connection.setInstanceFollowRedirects(false);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setRequestProperty("Authorization", "Basic " + encoder.encodeToString((userName + ":" + password).getBytes()));
            connection.setRequestProperty("Content-Type", contentType);

            if (payload != null) {
                OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
                writer.write(payload);
                writer.flush();
            }

            int status = connection.getResponseCode();
            if (status == 200 || status == 201) {
                return getStringFromInputStream(connection.getInputStream());
            }

            throw new Exception("Http status code: " + status);
        }
        finally {
            if (connection != null) { connection.disconnect(); }
        }
    }

    private void getJobStatus(String pingUrlString, String methodType) throws Exception {
        boolean completed = false;

        while (!completed) {

            String pingResponse = null;
            try {
                pingResponse = executeRequest(pingUrlString, methodType, null, "application/json");
            }
            catch (Exception e) {
                if(e instanceof java.net.ConnectException || e instanceof java.net.SocketException) {
                    if(System.currentTimeMillis()<endTime) {
                        System.out.println("Processing. Please wait...");
                        Thread.sleep(60000);
                        continue;
                    }
                    throw new Exception("Command timeout..");
                }
                throw e;
            }
            
            JSONObject json = new JSONObject(pingResponse);
            int status = json.getInt("status");

            if (status == -1) {
                try {
                    System.out.println("Processing. Please wait...");
                    Thread.sleep(20000);
                }
                catch (InterruptedException ie) {
                    completed = true;
                    throw ie;
                }
            }
            else {
                if (status > 0) {
                    System.out.println("Error occurred: " + json.getString("details"));
                }
                else {
                    System.out.println("Execution completed successfully");
                }
                completed = true;
            }
        }
    }

    public String fetchPingUrlFromResponse(String response, String retValue) throws Exception {
        String pingUrlString = null;
        JSONObject jsonObj = new JSONObject(response);
        int resStatus = jsonObj.getInt("status");

        if (resStatus == -1) {
            JSONArray lArray = jsonObj.getJSONArray("links");
            for (int i = 0; i < lArray.length(); i++) {
                JSONObject arr = lArray.getJSONObject(i);
                if (arr.get("rel").equals(retValue))
                    pingUrlString = (String) arr.get("href");
            }
        }

        return pingUrlString;
    }

    public void hardReset(String comment) throws Exception {
        Scanner in = new Scanner(System.in);
        System.out.print("Are you sure you want to restart the service instance (yes/no): no? [Press Enter] ");
        String s = in.nextLine();

        if (!s.equals("yes")) {
            System.out.println("User cancelled the recreate command");
            System.exit(0);
        }

        JSONObject params = new JSONObject();
        params.put("comment",comment);
        JSONObject innerParams = new JSONObject();
        innerParams.put("autotune","true");
        params.put("parameters",innerParams);

        String urlString = String.format("%s/interop/rest/%s/config/services/reset", serverUrl, apiVersion);
        startTime=System.currentTimeMillis();
        endTime = startTime+maxLoopTime;
        String response = executeRequest(urlString, "POST", params.toString(), "application/json");
        getJobStatus(fetchPingUrlFromResponse(response, "Job Status"),"GET");
    }

    public void recreateService(String removeAll, String essbaseChange, String tempServiceType) throws Exception {
        Scanner in = new Scanner(System.in);
        System.out.print("Are you sure you want to recreate the EPM environment (yes/no): no ?[Press Enter] " );
        String s = in.nextLine();

        if (!s.equals("yes")) {
            System.out.println("User cancelled the recreate command");
            System.exit(0);
        }

        JSONObject params = new JSONObject();
        JSONObject innerParams = new JSONObject();

        innerParams.put("tempServiceType", tempServiceType);
        innerParams.put("essbaseChange", essbaseChange);
        innerParams.put("removeAll", removeAll);
        params.put("parameters", innerParams);

        String urlString = String.format("%s/interop/rest/%s/config/services/recreate", serverUrl, apiVersion);
        startTime=System.currentTimeMillis();
        endTime = startTime+maxLoopTime;
        String response = executeRequest(urlString, "POST", params.toString(), "application/json");
        getJobStatus(fetchPingUrlFromResponse(response, "Job Status"), "GET");
    }
}

Sample Groovy Code

package com.groovy

import org.json.JSONObject
import groovy.json.JsonSlurper

// TODO: Use appropriate username, password, and url
username="<USERNAME>"
password="<PASSWORD>"
serverUrl="<SERVICE_URL>"

endTime=0
maxLoopTime=(60 * 60 * 1000)

apiVersion = "v2"
userCredentials = username + ":" + password
basicAuth = "Basic " + userCredentials.bytes.encodeBase64().toString()

def getResponse(is) {
    BufferedReader br = new BufferedReader(new InputStreamReader(is))
    StringBuilder sb = new StringBuilder()
    String line

    while ((line = br.readLine()) != null) {
        sb.append(line+"\n")
    }

    br.close()
    return sb.toString()
}

def getJobStatus(pingUrlString, methodType) {
    def pingUrl = new URL(pingUrlString)
    def completed = false

    while (!completed) {
        try {
            pingResponse = executeRequest(pingUrl, methodType, null, "application/json")
        }
        catch(exp) {
            if(exp instanceof java.net.ConnectException || exp instanceof java.net.SocketException) {
                if(System.currentTimeMillis()<endTime) {
                    println("Processing. Please wait...")
                    Thread.sleep(60000)
                    continue
                }
                throw new Exception("Command timeout..")
            }
        }

        status = getJobStatusFromResponse(pingResponse)
        if (status == "Processing") {
            try {
                println "Processing. Please wait..."
                Thread.sleep(5000)
            }
            catch (InterruptedException e) {
                completed = true
            }
        }
        else {
            println "Execution completed successfully"
            completed = true
        }
    }
}

def getJobStatusFromResponse(response) {
    def object = new JsonSlurper().parseText(response)
    def status = object.status
    if (status == -1) { return "Processing" }
    else if (status == 0) { return "Completed" }
    else { return object.details }
}

def executeRequest(url, requestType, payload, contentType) throws Exception {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection()
    connection.setDoOutput(true)
    connection.setInstanceFollowRedirects(false)
    connection.setRequestMethod(requestType)
    connection.setRequestProperty("Content-Type", contentType)
    connection.setRequestProperty("Authorization", basicAuth)
    connection.setUseCaches(false)

    if (payload != null) {
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream())
        writer.write(payload)
        writer.flush()
    }

    int statusCode
    try { statusCode = connection.responseCode }
    catch (all) { throw all }

    def response
    if (statusCode == 200 || statusCode == 201) {
        if (connection.getContentType() != null && !connection.getContentType().startsWith("application/json")) {
            println "Error occurred in server"
            System.exit(0)
        }
        InputStream is = connection.getInputStream()
        if (is != null) { response = getResponse(is) }
    }
    else {

        if (statusCode == 503) {
            throw new Exception("Service Unavailable")
        }

        InputStream is = connection.getErrorStream()
        if (is != null && connection.getContentType() != null &&
            connection.getContentType().startsWith("application/json")) {
            println getJobStatusFromResponse(getResponse(is))
        }
    }

    connection.disconnect()
    return response
}

def getUrlFromResponse(scenario, response, relValue) {
    def object = new JsonSlurper().parseText(response)
    def pingUrlStr
    if (object.status == -1) {
        println "Started - " + scenario
        def links = object.links
        links.each{
            if (it.rel.equals(relValue)) {
                pingUrlStr=it.href
            }
        }
    }
    else {
        println "Error details: " + object.details
        System.exit(0)
    }
    return pingUrlStr
}

def hardReset(comment) {

    def scenario = "Hard reset"
    def toReset = System.console().readLine 'Are you sure you want to restart the service instance (yes/no): no? [Press Enter] '

    if (!toReset.equals("yes")) {
        println "User cancelled the resetService command"
        System.exit(0)
    }

    def url
    JSONObject params = new JSONObject()
    JSONObject innerParams = new JSONObject()

    try {
        params.put("comment", comment)
        innerParams.put("autotune","true")
        params.put("parameters",innerParams)
        url = new URL(serverUrl+"/interop/rest/" + apiVersion + "/config/services/reset")
    }
    catch (MalformedURLException e) {
        println "Malformed URL. Please pass valid URL"
        System.exit(0)
    }

    endTime=System.currentTimeMillis() +maxLoopTime
    response = executeRequest(url, "POST", params.toString(), "application/json")

    if (response != null) {
        getJobStatus(getUrlFromResponse(scenario, response, "Job Status"),"GET")
    }
}

def recreateService(removeall,essabaseoption,tempServiceType) {

    def scenario="Recreate"
    def toCreate = System.console().readLine 'Are you sure you want to recreate the EPM environment (yes/no): no? [Press Enter] '
    if (!toCreate.equals("yes")) {
        println "User cancelled the recreate command"
        System.exit(0)
    }

    def url
    JSONObject params = new JSONObject()
    JSONObject innerParams = new JSONObject()

    try {
        innerParams.put("tempServiceType", tempServiceType)
        innerParams.put("essbaseChange", essabaseoption)
        innerParams.put("removeAll", removeall)
        params.put("parameters", innerParams)
        url = new URL(serverUrl + "/interop/rest/" + apiVersion + "/config/services/recreate")
    }
    catch (MalformedURLException e) {
        println "Malformed URL. Please pass valid URL"
        System.exit(0)
    }

    endTime=System.currentTimeMillis() +maxLoopTime
    response = executeRequest(url, "POST", params.toString(), "application/json")

    if (response != null) {
        getJobStatus(getUrlFromResponse(scenario, response, "Job Status"),"GET")
    }
}

if(this.args == null || this.args.length != 1) {
    println "Mandatory argument missing"
    println "Usage: EPMRestSamples <option>"
    println "  where <option> is -recreate or -reset"
    System.exit(1)
}

def option = this.args[0]

if("-reset".equalsIgnoreCase(option)) {
    hardReset("POC Exit Criteria Check - Groovy");
}
else if("-recreate".equalsIgnoreCase(option)) {
    recreateService("false", "default", "");
}
else {
    println "Incorrect usage"
    println "Usage: EPMRestSamples <option>"
    println "  where <option> is -recreate or -reset"
    System.exit(1)
}
Common Functions