use of co.paralleluniverse.actors.ActorRef in project eat by nhnent.
the class ManagerActor method doRun.
/**
* doRun of Actor. It performs requests on Actor Mailbox.
*/
@Override
protected Void doRun() throws SuspendExecution {
try {
NettyClient.initEventLoopGroup();
MDC.put("playerId", "Manager");
MDC.put("strand", Strand.currentStrand().getName());
// Read config, and Spawn TestActor according to config.
int cntOfTest = Config.obj().getScenario().getPlayerCount();
spawnActor();
// Request test preparation to TestActors
for (int idx = 0; idx < cntOfTest; idx++) {
ActorRef tester = actorList.get(idx);
tester.send(makeRequestTestPreparationMessage(idx));
logger.debug("Request preparation to tester actor (" + tester.toString() + ")");
}
// Wait for preparation from all of TestActors
int receivedPreparedCnt = 0;
while (true) {
Object o = receive();
if (o instanceof Messages) {
Messages m = (Messages) o;
if (m.type == MessageType.TestPrepared) {
receivedPreparedCnt++;
logger.info("Receive message(Test Preparation is Finish), " + receivedPreparedCnt + "/" + cntOfTest);
if (receivedPreparedCnt >= cntOfTest) {
break;
}
}
}
}
Date testStartDateTime = new Date();
// Request test to TestActors
for (int idx = 0; idx < cntOfTest; idx++) {
ActorRef tester = actorList.get(idx);
tester.send(new Messages(this.ref, MessageType.TestStart));
logger.info("Request preparation to tester actor (" + tester.toString() + ")");
if (Config.obj().getScenario().getTestActorStartGap() != 0) {
Strand.sleep(Config.obj().getScenario().getTestActorStartGap());
}
}
// Wait for test finishing from all of TestActors
int receivedTestFinishCnt = 0;
ScenarioExecutionResult[] results = new ScenarioExecutionResult[cntOfTest];
for (; ; ) {
Object o = receive();
if (o instanceof Messages) {
Messages m = (Messages) o;
if (m.type == MessageType.TestFinished) {
results[receivedTestFinishCnt] = m.scenarioExecutionResult;
receivedTestFinishCnt++;
logger.info("[userId:{}] Receive message(Test is Finished), {}/{}", m.userId, receivedTestFinishCnt, cntOfTest);
if (receivedTestFinishCnt >= cntOfTest) {
break;
}
}
}
}
JMXClient.obj().disconnect();
Date testEndDateTime = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info(String.format("Testing period : %s ~ %s", dateFormat.format(testStartDateTime), dateFormat.format(testEndDateTime)));
long diff = testEndDateTime.getTime() - testStartDateTime.getTime();
logger.info("Elapsed time(sec) : " + (diff / 1000));
logger.info("Total transferred packet : " + transmitDataTotalCount);
double avgTransPacketCount = (double) transmitDataTotalCount / (diff / 1000.0);
logger.info("Average Transferred packet for 1 sec: " + String.format("%.2f", avgTransPacketCount));
ReportHandler reportHandler = new ReportHandler();
reportHandler.writeFinalStatisticsResult(results);
NettyClient.shutdownEventLoopGroup();
} catch (final Exception e) {
logger.error("Exception is raised", e);
}
MDC.remove("playerId");
MDC.remove("strand");
MDC.remove("logfileName");
return null;
}
use of co.paralleluniverse.actors.ActorRef in project quasar by puniverse.
the class PeerTKB method run.
public void run() throws ExecutionException, InterruptedException {
switch(SCENARIO.testGenEvent) {
case test:
final Store store = Grid.getInstance().store();
if (i == 1) {
StoreTransaction tx = store.beginTransaction();
try {
long root = store.getRoot("root", tx);
// "hello".getBytes();
byte[] buf = null;
store.set(root, buf, tx);
store.commit(tx);
} catch (TimeoutException ex) {
throw new RuntimeException("set failed");
}
Thread.sleep(20000);
} else {
StoreTransaction tx = store.beginTransaction();
byte[] get;
try {
long root = store.getRoot("root", tx);
get = store.get(root);
store.commit(tx);
} catch (TimeoutException ex) {
throw new RuntimeException("get failed");
}
System.out.println(get);
}
break;
case testGenServer:
if (i == 1) {
spawnGenServer(new AbstractServerHandler<Message, Integer, Message>() {
@Override
public void init() throws SuspendExecution {
super.init();
ServerActor.currentServerActor().register("myServer");
}
@Override
public Integer handleCall(ActorRef<?> from, Object id, Message m) {
return m.a + m.b;
}
}).join();
} else {
Integer get = spawnActor(new BasicActor<Message, Integer>(new MailboxConfig(10, Channels.OverflowPolicy.THROW)) {
protected Integer doRun() throws SuspendExecution, InterruptedException {
final Server<Message, Integer, Message> gs = (Server) ActorRegistry.getActor("myServer");
return gs.call(new Message(3, 4));
}
}).get();
System.out.println("value is " + get);
assert get == 7;
}
break;
case testGenEvent:
if (i == 1) {
final Val<String> dv = new Val<>();
spawnGenEvent(new Initializer() {
@Override
public void init() throws SuspendExecution {
EventSourceActor.currentEventSourceActor().register("myEventServer");
try {
final EventSource<String> ge = LocalActor.self();
ge.addHandler(new EventHandler<String>() {
@Override
public void handleEvent(String event) {
dv.set(event);
System.out.println("sout " + event);
ge.shutdown();
}
});
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
@Override
public void terminate(Throwable cause) throws SuspendExecution {
System.out.println("terminated");
}
});
String get = dv.get();
System.out.println("got msg " + get);
assert get.equals("hello world");
} else {
spawnActor(new BasicActor<Message, Void>() {
protected Void doRun() throws SuspendExecution, InterruptedException {
final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
ge.notify("hello world");
return null;
}
}).join();
}
break;
case testMultiGetActor:
if (i == 1) {
spawnGenEvent(new Initializer() {
AtomicInteger ai = new AtomicInteger();
@Override
public void init() throws SuspendExecution {
Actor.currentActor().register("myEventServer");
try {
final EventSource<String> ge = LocalActor.self();
ge.addHandler(new EventHandler<String>() {
@Override
public void handleEvent(String event) {
System.out.println("msg no " + ai.incrementAndGet() + ": " + event);
}
});
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
@Override
public void terminate(Throwable cause) throws SuspendExecution {
System.out.println("terminated");
}
}).join();
} else {
Queue<Actor> queue = new LinkedList<>();
for (int j = 0; j < 1000; j++) {
final BasicActor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>("actor-" + j) {
protected Void doRun() throws SuspendExecution, InterruptedException {
try {
final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
ge.notify("hwf " + getName());
} catch (Exception e) {
System.out.println("error in " + getName());
throw e;
}
return null;
}
});
queue.add(actor);
// actor.join();
}
for (Actor localActor : queue) localActor.join();
Thread.sleep(500);
}
break;
case testOrdering:
if (i == 1) {
spawnGenEvent(new Initializer() {
AtomicInteger ai = new AtomicInteger();
@Override
public void init() throws SuspendExecution {
EventSourceActor.currentEventSourceActor().register("myEventServer");
try {
EventSourceActor<String> ge = EventSourceActor.currentEventSourceActor();
ge.ref().addHandler(new EventHandler<String>() {
@Override
public void handleEvent(String event) {
System.out.println("msg no " + ai.incrementAndGet() + ": " + event);
}
});
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
@Override
public void terminate(Throwable cause) throws SuspendExecution {
System.out.println("terminated");
}
}).join();
} else {
Queue<Actor> queue = new LinkedList<>();
for (int j = 0; j < 1; j++) {
final BasicActor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>("actor-" + j) {
protected Void doRun() throws SuspendExecution, InterruptedException {
try {
final EventSource<String> ge = (EventSource) ActorRegistry.getActor("myEventServer");
for (int k = 0; k < 3000; k++) ge.notify("hw " + k + " f" + getName());
} catch (Exception e) {
System.out.println("error in " + getName());
throw e;
}
return null;
}
});
queue.add(actor);
// actor.join();
}
for (Actor localActor : queue) localActor.join();
Thread.sleep(5000);
}
break;
default:
}
System.out.println("finished");
System.exit(0);
while (true) {
System.out.println("==================");
ThreadUtil.dumpThreads();
Thread.sleep(5000);
}
}
use of co.paralleluniverse.actors.ActorRef in project quasar by puniverse.
the class SupervisorActor method tryRestart.
private boolean tryRestart(ChildEntry child, Throwable cause, long now, Iterator<ChildEntry> it, boolean isDead) throws SuspendExecution, InterruptedException {
verifyInActor();
switch(child.spec.mode) {
case TRANSIENT:
if (isDead && cause == null) {
removeChild(child, it);
return true;
}
// fall through
case PERMANENT:
log().info("Supervisor trying to restart child {}. (cause: {})", child, cause);
final ActorRef actor = child.actor;
shutdownChild(child, true);
child.restartHistory.addRestart(now);
final int numRestarts = child.restartHistory.numRestarts(now - child.spec.unit.toMillis(child.spec.duration));
if (log().isDebugEnabled())
log().debug("Child {} has been restarted {} times in the last {} {}s", child, numRestarts, child.spec.duration, child.spec.unit);
if (numRestarts > child.spec.maxRestarts) {
log().info(this + ": too many restarts for child {}. Giving up.", actor);
return false;
}
start(child);
return true;
case TEMPORARY:
if (!isDead)
shutdownChild(child, false);
removeChild(child, it);
return true;
default:
throw new AssertionError();
}
}
use of co.paralleluniverse.actors.ActorRef in project quasar by puniverse.
the class SupervisorActor method start.
private ActorRef<?> start(ChildEntry child) throws SuspendExecution {
final ActorRef old = child.actor;
if (old != null && !LocalActor.isDone(old))
throw new IllegalStateException("Actor " + child.actor + " cannot be restarted because it is not dead");
final Actor actor = child.spec.builder.build();
if (actor.getName() == null && child.spec.id != null)
actor.setName(child.spec.id);
log().info("{} starting child {}", this, actor);
if (old != null && actor.getMonitor() == null && isLocal(old) && LocalActor.getMonitor(old) != null)
actor.setMonitor(LocalActor.getMonitor(old));
if (actor.getMonitor() != null)
actor.getMonitor().addRestart();
final Strand strand;
if (actor.getStrand() != null)
strand = actor.getStrand();
else
strand = createStrandForActor(child.actor != null && isLocal(child.actor) ? LocalActor.getStrand(child.actor) : null, actor);
try {
strand.start();
} catch (IllegalThreadStateException e) {
log().info("Child {} has already been started.", actor);
}
return start(child, actor.ref());
}
use of co.paralleluniverse.actors.ActorRef in project quasar by puniverse.
the class SupervisorActor method joinChild.
private boolean joinChild(ChildEntry child) throws SuspendExecution, InterruptedException {
final ActorRef actor = child.actor;
log().debug("Joining child {}", child);
if (child.actor != null) {
try {
LocalActor.join(actor, child.spec.shutdownDeadline, TimeUnit.MILLISECONDS);
log().debug("Child {} terminated normally", child.actor);
return true;
} catch (ExecutionException ex) {
log().info("Child {} terminated with exception {}", child.actor, ex.getCause());
return true;
} catch (TimeoutException ex) {
log().warn("Child {} shutdown timeout. Interrupting...", child.actor);
// is this the best we can do?
LocalActor.getStrand(actor).interrupt();
try {
LocalActor.join(actor, child.spec.shutdownDeadline, TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException e) {
log().info("Child {} terminated with exception {}", child.actor, ex.getCause());
return true;
} catch (TimeoutException e) {
log().warn("Child {} could not shut down...", child.actor);
LocalActor.stopMonitor(child.actor);
LocalActor.unregister(child.actor);
child.actor = null;
return false;
}
}
} else
return true;
}
Aggregations