Junos Space Developer
Reply
Contributor
Ar2r
Posts: 42
Registered: ‎11-29-2011
0

REST API: communication with device issue

[ Edited ]

Hello,

 

During Junos Space REST API investigation I encountered some issues. Could you help me, please,  to solve them? 

 

I'm using Hello Space project sample from Junos Space SDK documentation. After getting the response with devices list from Junos Space, I'm trying to check PoE capability or get system information of each device like this:

 

// Get response from the service
ClientResponse response = get(url, JSON_DEVICES);
if (response != null) {

	int status = response.getClientResponseStatus().getStatusCode();

	if (status == Response.Status.BAD_REQUEST.getStatusCode()
			|| status == Response.Status.NOT_FOUND.getStatusCode()
			|| status == Response.Status.NO_CONTENT.getStatusCode()) {

		return null;
	} else {
		/* Check PoE */
		String responseJson = response.getEntity(String.class);
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(responseJson);
			JSONObject jsonDevices = (JSONObject) jsonObject.get(DEVICES);
			JSONArray array = jsonDevices.getJSONArray(DEVICE);
			for (int i = 0; i < array.length(); i++) {
				JSONObject jsonDevice = array.getJSONObject(i);
				int id = getInt(jsonDevice, "@key");
				String smth = checkPoE(iac.getBaseUrl(), id);
				logger.info("!!!!!!!!!!!!!!!! PoE CHECK: /n");
				logger.info(smth);
			}
		} catch (JSONException e) {
			logger.error(e);
		}

 

checkPoE method:

 

public String checkPoE(String baseUrl, int deviceId) {

	String postUrl = baseUrl + "/api/space/device-management/devices/"+Integer.toString(deviceId)+"/exec-rpc";
	//String mediaType = "application/vnd.net.juniper.space.device-management.rpc+json;version=3;charset=UTF-8";
	String mediaType = "application/vnd.net.juniper.space.device-management.rpc+xml;version=3;charset=UTF-8";
	//final String requestBody = "{\"netconf\":{\"rpcCommands\":{\"rpcCommand\": [\"<get-poe-controller-information/>\"]}}}";
	final String requestBody = "<netconf><rpcCommands><rpcCommand><![CDATA[<get-system-information/>]]></rpcCommand></rpcCommands></netconf>";
	ClientResponse response = postRequest(jerseyClient, postUrl, mediaType, requestBody);
	/** Error handling to check if the status code is 200 or no **/
	if (response.getClientResponseStatus() == ClientResponse.Status.OK)
	{
	      /** Get a String representation of the response body using response.getEntity() **/
	      String smth = response.getEntity(String.class);
	      return smth;
	}
	else
	{
	      return null;
	}
}

 

postRequest method:

 

private ClientResponse postRequest(Client jerseyClient, String url, String mediaType, final String requestBody){
	
 ClientResponse response = null;
  try {

  /** HTTP POST request request **/
  response = jerseyClient.resource(url).accept(mediaType).
  post(ClientResponse.class, requestBody);

  } catch (Exception e) {
     logger.error(NO_RESPONSE);
     logger.error(e);
  }
 return response;			
}

 

The result is that the response from the Space platform comes with HTTP Error 415. 

 

Could you explain, please, what I'm doing wrong and give me an example of how to configure devices through the Junos Space REST API.

 

Thank you

Recognized Expert
Yesh
Posts: 456
Registered: ‎09-29-2009
0

Re: REST API: communication with device issue

Hello,

 

You are trying to use version 3 of the API which is aysnchronous (using hornet-q). But seeing your code you seem to want sync request. Change the media type to "application/vnd.net.juniper.space.device-management.rpc+xml;version=1;charset=UTF-8" and check.

 

For an example to configure device using REST API see ...https://developer.juniper.net/content/dam/jdn/tutorials/Tutorials_MonitorPOEDevices_JunosSpaceAPIs.p...  and https://developer.juniper.net/content/jdn/en/develop-overview/junos-space-sdk/getting-started.html 

 

Thanks

Yesh

Contributor
Ar2r
Posts: 42
Registered: ‎11-29-2011
0

Re: REST API: communication with device issue

Thank you for your response,

 

In accordance with Junos Space REST API docs, as I understood, the Junos Space platform sends positive response in both cases. If request is asynchronous (version 3), the platform sends response with the task id, but not an error. Http error 415 means that client sends unsupported content type, but as you can see in the code - content type corresponds with the request body data.

 

I tried to change API version in the media type, but result stays the same (error 415).

 

In doc samples I found only GET requests to the platform. I didn’t found the working samples with POST requests.

Recognized Expert
Yesh
Posts: 456
Registered: ‎09-29-2009
0

Re: REST API: communication with device issue

Hi,

Sorry I did not notice the error.  This means the Content type is not being considered or something is wrong with the request body. Can you please try the following?

 

1. Try sending a POST request from REST client and check if you get a successful response.

2. If your step 1 is successful, I think the problem is in request body (may be the escape sequences ,quotes). Try using single quotes. I will try your code when I am free and let you know. In the meanwhile, you can try the above steps.

 

Please note:For Aync requests, you need to pass the queue name to user otherwise Platform will throw an error(400). In the first link I sent you there is a exec-rpc request with POST example. Please check again.

 

regards

Yesh

 

 

Contributor
Ar2r
Posts: 42
Registered: ‎11-29-2011
0

Re: REST API: communication with device issue

Hi, 

 

I've solved this issue. In Junos documentation code samples was a mistake I didn't noticed. It locates in "Consuming REST Services Using the Jersey Client" paragraph.

In "HTTP POST" code snippet the mediaType variable is passed to the postRequest method with consumed content type data:

 

String mediaType = "application/vnd.net.juniper.space.user-management.user+xml;version=1;charset=UTF-8";
/** Get the Client Response Object **/
final String requestBody = "testfname";
ClientResponse response = postRequest(client, url, mediaType,requestBody);

In "Create object using HTTP POST" code sample the postRequest method is presented:

 

/* This is a utility method to post the message **/

private ClientResponse postRequest(Client jerseyClient, String url, String mediaType, final String requestBody){
	
 ClientResponse response = null;
  try {

  /** HTTP POST request request **/
  response = jerseyClient.resource(url).accept(mediaType).
  post(ClientResponse.class, requestBody);

  } catch (Exception e) {
     logger.error(NO_RESPONSE);
     logger.error(e);
  }
 return response;			
}

As you can see, mediaType variable with consumed content type data is handled like produced one.

After I fixed this, post requests were processed correctly by the platform.

 

Fixed code:

 

response = jerseyClient.resource(url).type(consumedType).accept(producedType).post(ClientResponse.class, requestBody);

 

Unfortunately, I found another issue:

When I connect real SRX (JuniperSRX 210H, JUNOS Release 10.4R8.5) to the Junos Space SDK, pre-installed Space Platform Network Manager Application can discover it, but deployed new applications don't see the device through REST API. HelloSpace documentation sample app that shows all devices connected to the platform doesn't get real SRX too.

Recognized Expert
Yesh
Posts: 456
Registered: ‎09-29-2009
0

Re: REST API: communication with device issue

Hi,

 

Great! Yes you are right the media type should be passed as Content-type header.

 

For the issue now, are you able to see the SRX when you call the REST API directly ?

 

Thanks

Yesh

Contributor
Ar2r
Posts: 42
Registered: ‎11-29-2011
0

Re: REST API: communication with device issue

Hi,

 

Junos Space SDK is running in VirtualBox. The SRX (JuniperSRX 210H, JUNOS Release 10.4R8.5) is connected to the local network where the VirtualBox host machine is connected too. SRX has the following IP: 192.168.1.1

 

I can ping and connect (ssh) to the SRX through the VirtualBox Junos terminal. When I'm trying to discover it in Junos Space Platform UI, device adding fails with status report "Device is not running Junos or is not a supported Junos device".

 

When I'm using REST Client, I get the following:

 

1. After creating a Hornet Queue, the devices discovery request is sent:

 

HTTP POST http://localhost:8080/api/space/device-management/discover-devices?queue=http://localhost:8080/api/hornet-q/queues/jms.queue.testq
Authorization:  Basic c3VwZXI6cmFrZXNocmFqa2U=
Content-Type:  application/vnd.net.juniper.space.device-management.discover-devices+xml;version=1;charset=UTF-8
	
<systemDiscoveryRule>
<ruleName>TestRuleName12331</ruleName>
<ipAddressDiscoveryTarget>
<ipAddress>192.168.1.1</ipAddress>
</ipAddressDiscoveryTarget>
<usePing>true</usePing> // true or false doesn't matter
<useSnmp>false</useSnmp>

<snmpV1Setting>
<communityName>testCommunityName</communityName>
</snmpV1Setting>
<manageDiscoveredSystemsFlag>true</manageDiscoveredSystemsFlag>

<sshCredential>
<userName>sdk</userName>
<password>abc123</password>
</sshCredential>
<sshCredential>
<userName>sdk</userName>
<password>abc123</password>
</sshCredential>

<tagNewlyManagedDiscoveredSystemsFlag>true</tagNewlyManagedDiscoveredSystemsFlag>
<tagForNewlyManagedDiscoveredSystems>true</tagForNewlyManagedDiscoveredSystems>
</systemDiscoveryRule>  

 2. The platform sends the following response:

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<task href="/api/space/job-management/jobs/294912">
<id>294912</id>
</task>

 3.1.1 Client sends GET request by URL "/api/space/job-management/jobs/294912", the server replies 

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<job uri="/api/space/job-management/jobs/294912">
	<id>294912</id>
	<name>Discover Network Elements-294912</name>
	<percent>100.0</percent>
	<status>FAILURE</status>
	<jobType>Discover Network Elements</jobType>
	<summary>Number of scanned IP: 1&lt;br&gt;Number of Discovery succeeded: 1&lt;br&gt;Number of Add Device failed: 1&lt;br&gt;Number of Already Managed: 0&lt;br&gt;Number of Device Managed: 0&lt;br&gt;Number of Skipped: 0&lt;br&gt;</summary>
	<scheduledStartTime>Mon, 05 Mar 2012 14:51:36 GMT</scheduledStartTime>
	<progress-update href="/api/space/job-management/jobs/294912/progress-update"/>
</job>

  3.1.2 Client sends GET request by URL "/api/space/job-management/jobs/294912/progress-update", the server replies 

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><progress-update xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="parallel-progress">
<job href="/api/space/job-management/jobs/294912"/>
	<taskId>294912</taskId>
	<jobName>Discover Network Elements-94912</jobName>
	<state>DONE</state>
	<status>FAILURE</status>
	<percentage>100.0</percentage>
	<data>&lt;![CDATA[Number of scanned IP: 1&lt;br&gt;Number of Discovery succeeded: 1&lt;br&gt;Number of Add Device failed: 1&lt;br&gt;Number of Already Managed: 0&lt;br&gt;Number of Device Managed: 0&lt;br&gt;Number of Skipped: 0&lt;br&gt;]]&gt;</data>
	<subTask xsi:type="percentage-omplete">
		<state>DONE</state>
		<status>SUCCESS</status>
		<percentage>100.0</percentage>
	</subTask>
</progress-update>

 3.2.1 The client sends HEAD "/api/hornet-q/queues/jms.queue.testq", recieves pull consumers URL from server and sends it back. Then client get task progress update URL "http://localhost:8080/api/hornet-q/queues/jms.queue.testq/pull-consumers/attributes-0/1-queue-jms.queue.testq-1330959096130/consume-next-1" and post it on the server. It replys the following:

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<progress-update xsi:type="parallel-progress" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <job href="/api/space/job-management/jobs/294912"/>
    <taskId>294912</taskId>
    <jobName>Discover Network Elements-294912</jobName>
    <state>INPROGRESS</state>
    <status>UNDETERMINED</status>
    <percentage>0.0</percentage>
    <subTask xsi:type="percentage-complete">
        <state>INPROGRESS</state>
        <status>UNDETERMINED</status>
        <percentage>0.0</percentage>
    </subTask>
</progress-update>

 3.2.2 The client sends progress update URL again "http://localhost:8080/api/hornet-q/queues/jms.queue.testq/pull-consumers/attributes-0/1-queue-jms.queue.testq-1330959096130/consume-next-1661" and gets an error:

 

You are using an old consume-next link and are out of sync with the JMS session on the server

 

Recognized Expert
Yesh
Posts: 456
Registered: ‎09-29-2009
0

Re: REST API: communication with device issue

Hi,

 

Since discovery is failing lets try and get over the issue using UI and then solve the REST API discovery issue.

Please try discovering from UI again. Please uncheck SNMP option as this may be causing the issue.

Also, go to the Junos Space CLI and look for errors/issues in /var/log/jboss/server.log and send it to us.

 

Thanks,

Yesh

Contributor
Ar2r
Posts: 42
Registered: ‎11-29-2011
0

Re: REST API: communication with device issue

Hi, this is my jboss server log:

 

2012-03-06 09:59:22,707 WARN  [net.juniper.jmp.cmp.deviceManager.ejb.DeviceSvcAPI] (EJB-Timer-1331027181590[target=jboss.j2ee:service=EJB3,ear=cems.ear,jar=inventoryManager.jar,name=SystemDiscoveryManagerEJB]:) Device Discovery Progress: ssh to device 192.168.1.1
2012-03-06 10:01:27,645 ERROR [net.juniper.jmp.cmp.deviceIOMgr.DeviceInboundConnectionFactory] (Thread-16 (group:HornetQ-client-global-threads-1413706068):) Device inbound cmd 192.168.1.1 failed to request netconf subsystem
2012-03-06 10:01:27,647 ERROR [net.juniper.jmp.cmp.deviceIOMgr.DeviceInboundCmd] (Thread-16 (group:HornetQ-client-global-threads-1413706068):) Send failure message for add reachable device with ip 192.168.1.1 failed --- Device is not running Junos or is not a supported Junos device
2012-03-06 10:01:27,920 WARN  [SystemDiscoveryProgressUpdaterBean] (Thread-18 (group:HornetQ-client-global-threads-1413706068):) Device discovery job 425984 progress: saving the job result
2012-03-06 10:01:33,867 WARN  [com.arjuna.ats.arjuna.logging.arjLoggerI18N] (EJB-Timer-1331027181603[target=jboss.j2ee:service=EJB3,ear=cems.ear,jar=inventoryManager.jar,name=SystemDiscoveryManagerEJB]:) [com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator_4] TwoPhaseCoordinator.afterCompletion - returned failure for com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple@700bde4e

When I changed permissions class of user I used to log in my SRX from "read-only" to "operator", the platform could discover this SRX device.

 

Could you elaborate, please, how user group permissions should be configured on SRX device to allow Junos Space discover the SRX. Default "operator" permissions class has too many privileges for our security policy.

 

Do you have documentation about "edit-config" RPC command? "Supported RPCs" paragraph from official docs doesn't have any notes about it.

Recognized Expert
Yesh
Posts: 456
Registered: ‎09-29-2009
0

Re: REST API: communication with device issue

Hi,

 

The user should have permissions to read and write the configuration. That is because it adds SSH (netconf) and syslog configuration required for it to work with Space.  It is recommended to use a administrative user for adding the device into Space. See http://www.juniper.net/techpubs/en_US/junos-space11.3/topics/task/configuration/junos-space-devices-... for details.

 

For edit-config RPC you can refer to NETCONF XML Guide for the required Junos OS release. For example JUnos 11.3 link is http://www.juniper.net/techpubs/en_US/junos11.4/information-products/topic-collections/netconf-guide... 

 

Thanks

Yesh

Copyright© 1999-2013 Juniper Networks, Inc. All rights reserved.