Search in sources :

Example 6 with ActiveMessage

use of edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage in project GNS by MobilityFirst.

the class ActiveNonBlockingQuerier method readValueFromField.

/**
	 * 
	 * @param querierGuid
	 * @param queriedGuid
	 * @param fields a JS Array is stringified to this string
	 * @param ttl
	 * @return
	 * @throws ActiveException
	 */
private String readValueFromField(String querierGuid, String queriedGuid, String fields, int ttl) throws ActiveException {
    monitor = new Monitor();
    String value = null;
    try {
        ActiveMessage am = new ActiveMessage(ttl, querierGuid, fields, queriedGuid, currentID);
        channel.sendMessage(am);
        synchronized (monitor) {
            while (!monitor.getDone()) {
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }
        ActiveMessage response = monitor.getResult();
        if (response == null) {
            throw new ActiveException();
        }
        if (response.getError() != null) {
            throw new ActiveException();
        }
        value = response.getValue();
    } catch (IOException e) {
        throw new ActiveException();
    }
    return value;
}
Also used : ActiveException(edu.umass.cs.gnsserver.activecode.prototype.ActiveException) IOException(java.io.IOException) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage)

Example 7 with ActiveMessage

use of edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage in project GNS by MobilityFirst.

the class ActiveWorkerSubmittedTask method run.

@Override
public void run() {
    ActiveMessage response = null;
    long timeout = request.getBudget();
    Future<ActiveMessage> future = executor.submit(new ActiveWorkerTask(runner, request));
    try {
        response = future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        // return an error
        response = new ActiveMessage(request.getId(), null, e.getMessage());
        ActiveNonBlockingWorker.getLogger().log(Level.FINE, "get an exception {0} when executing request {1} with code {2}", new Object[] { e, request, request.getCode() });
    }
    try {
        channel.sendMessage(response);
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
Also used : IOException(java.io.IOException) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with ActiveMessage

use of edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage in project GNS by MobilityFirst.

the class ActiveNamedPipe method receiveMessage.

@Override
public Message receiveMessage() throws IOException {
    Message am = null;
    int len = -1;
    if (reader != null)
        len = reader.read(readerLengthBuffer, 0, readerLengthBuffer.length);
    if (len > 0) {
        int length = ByteBuffer.wrap(readerLengthBuffer).getInt();
        byte[] buffer = new byte[length];
        reader.read(buffer, 0, length);
        try {
            am = new ActiveMessage(buffer);
        } catch (JSONException e) {
        //e.printStackTrace();
        }
    }
    return am;
}
Also used : Message(edu.umass.cs.gnsserver.activecode.prototype.interfaces.Message) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage) JSONException(org.json.JSONException) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage)

Example 9 with ActiveMessage

use of edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage in project GNS by MobilityFirst.

the class ActiveNonBlockingClient method runCode.

/**
	 * This runCode method sends the request to worker, and
	 * wait for worker to finish the request. If the worker
	 * crashed during the request execution, this method
	 * will resend the request to a new created worker, and
	 * the new worker will execute this request again. 
	 * <p>If the worker fails to execute the request, it will 
	 * send back an error to inform this method that the execution
	 * gets accomplished with an error. This method will raise
	 * an ActiveException, and the method which calls this method
	 * needs to handle this exception.
	 * 
	 * @param guid
	 * @param accessor
	 * @param code
	 * @param valuesMap
	 * @param ttl
	 * @return executed result sent back from worker
   * @throws edu.umass.cs.gnsserver.activecode.prototype.ActiveException
	 */
@Override
public JSONObject runCode(InternalRequestHeader header, String guid, String accessor, String code, JSONObject valuesMap, int ttl, long budget) throws ActiveException {
    ActiveMessage msg = new ActiveMessage(guid, accessor, code, valuesMap.toString(), ttl, budget);
    Monitor monitor = new Monitor();
    tasks.put(msg.getId(), monitor);
    ActiveMessage response = null;
    synchronized (monitor) {
        while (!monitor.getDone()) {
            try {
                if (!monitor.getWait()) {
                    sendMessage(msg);
                    monitor.setWait();
                }
                monitor.wait();
            } catch (InterruptedException e) {
                // this thread is interrupted, do nothing
                e.printStackTrace();
            }
            response = monitor.getResult();
            /**
				 * If it's a query, queryHandler needs to handle it.
				 * Otherwise, exit the while loop to process the response.
				 */
            if (response != null && response.type != Type.RESPONSE) {
                // submit the task to the worker and wait for the response
                queryHandler.handleQueryAsync(response, header, monitor);
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!monitor.getDone()) {
                    // If it's not because of the timeout event, then send back the response  
                    ActiveMessage result = monitor.getResult();
                    sendMessage(result);
                } else {
                    // If it's because of timeout, then clean up the state and exit the loop
                    break;
                }
            }
        }
    }
    response = monitor.getResult();
    ActiveCodeHandler.getLogger().log(ActiveCodeHandler.DEBUG_LEVEL, "receive a response from the worker:{0}", new Object[] { response });
    if (response == null) {
        /**
			 * No need to resend the request, as it is much likely
			 * a malicious request. 
			 */
        throw new ActiveException("Worker crashes!");
    }
    if (response.getError() != null) {
        throw new ActiveException("Message: " + msg.toString() + " Response: " + response.toString());
    }
    counter.getAndIncrement();
    tasks.remove(response.getId());
    try {
        // FIXED: it is possible that the returned value is null which causes a NullPointerException when initializing a JSONObject
        if (response.getValue() == null) {
            // the methods will use the original value. See NSFieldAccess, NSUpdateSupport
            return null;
        }
        return new JSONObject(response.getValue());
    } catch (JSONException e) {
        throw new ActiveException("Bad JSON value returned from active code!");
    }
}
Also used : JSONObject(org.json.JSONObject) ActiveException(edu.umass.cs.gnsserver.activecode.prototype.ActiveException) JSONException(org.json.JSONException) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage)

Example 10 with ActiveMessage

use of edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage in project GNS by MobilityFirst.

the class ActiveNonBlockingClient method run.

@Override
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        ActiveMessage response;
        try {
            if ((response = (ActiveMessage) channel.receiveMessage()) != null) {
                long id = response.getId();
                Monitor monitor = tasks.get(id);
                assert (monitor != null) : "the corresponding monitor is null!";
                ActiveCodeHandler.getLogger().log(ActiveCodeHandler.DEBUG_LEVEL, "receive a result or query from the worker:{0}", new Object[] { response });
                monitor.setResult(response, response.type == Type.RESPONSE);
            } else {
                if (!isRestarting.getAndSet(true)) {
                    lastWorkerStartedTime = System.currentTimeMillis();
                    // restart the worker
                    this.shutdown();
                    this.initializeChannelAndStartWorker();
                    // release all the requests that waited on its monitor
                    for (Monitor monitor : this.tasks.values()) {
                        monitor.setResult(null, true);
                    }
                    isRestarting.set(false);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : IOException(java.io.IOException) ActiveMessage(edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage)

Aggregations

ActiveMessage (edu.umass.cs.gnsserver.activecode.prototype.ActiveMessage)13 IOException (java.io.IOException)9 ActiveException (edu.umass.cs.gnsserver.activecode.prototype.ActiveException)6 JSONException (org.json.JSONException)6 ExecutionException (java.util.concurrent.ExecutionException)4 JSONObject (org.json.JSONObject)3 ArrayList (java.util.ArrayList)2 Future (java.util.concurrent.Future)2 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)2 TimeoutException (java.util.concurrent.TimeoutException)2 ScriptException (javax.script.ScriptException)2 Message (edu.umass.cs.gnsserver.activecode.prototype.interfaces.Message)1 ValuesMap (edu.umass.cs.gnsserver.utils.ValuesMap)1 DatagramPacket (java.net.DatagramPacket)1 ScriptObjectMirror (jdk.nashorn.api.scripting.ScriptObjectMirror)1