Skip to content

Commit

Permalink
[sre] Spawn more than one agent.
Browse files Browse the repository at this point in the history
see #481
see #76

Signed-off-by: Stéphane Galland <galland@arakhne.org>
  • Loading branch information
gallandarakhneorg committed Dec 16, 2016
1 parent 8a21533 commit d110883
Show file tree
Hide file tree
Showing 9 changed files with 284 additions and 129 deletions.
Expand Up @@ -39,6 +39,7 @@
import com.google.inject.Singleton;

import io.janusproject.JanusConfig;
import io.janusproject.kernel.services.jdk.spawn.CannotSpawnException;
import io.janusproject.services.IServiceManager;
import io.janusproject.services.Services;
import io.janusproject.services.logging.LogService;
Expand Down Expand Up @@ -144,7 +145,7 @@ public boolean isRunning() {
public UUID spawn(Class<? extends Agent> agent, Object... params) {
final List<UUID> ids = this.spawnService.spawn(1, this.janusContext, null, agent, params);
if (ids.isEmpty()) {
return null;
throw new CannotSpawnException(agent, null);
}
return ids.get(0);
}
Expand Down
Expand Up @@ -39,10 +39,20 @@
*/
public final class BuiltinCapacityUtil {

private static Method methodGetSkill;

private BuiltinCapacityUtil() {
//
}

private static Method getMethodGetSkill() throws Exception {
if (methodGetSkill == null) {
methodGetSkill = Agent.class.getDeclaredMethod("getSkill", Class.class); //$NON-NLS-1$
methodGetSkill.setAccessible(true);
}
return methodGetSkill;
}

/**
* Replies the contexts in which the agent is located.
*
Expand All @@ -51,16 +61,9 @@ private BuiltinCapacityUtil() {
* @throws Exception - when it is not possible to retreive the contexts.
*/
public static SynchronizedCollection<AgentContext> getContextsOf(Agent agent) throws Exception {
final Method method = Agent.class.getDeclaredMethod("getSkill", Class.class); //$NON-NLS-1$
final boolean isAccessible = method.isAccessible();
final ExternalContextAccess skill;
try {
method.setAccessible(true);
skill = (ExternalContextAccess) method.invoke(agent, ExternalContextAccess.class);
} finally {
method.setAccessible(isAccessible);
}

final Method method = getMethodGetSkill();
final ExternalContextAccess skill = (ExternalContextAccess) method.invoke(agent, ExternalContextAccess.class);
assert skill != null;
return skill.getAllContexts();
}

Expand All @@ -72,15 +75,8 @@ public static SynchronizedCollection<AgentContext> getContextsOf(Agent agent) th
* @throws Exception - when it is not possible to retreive the inner context.
*/
public static AgentContext getContextIn(Agent agent) throws Exception {
final Method method = Agent.class.getDeclaredMethod("getSkill", Class.class); //$NON-NLS-1$
final boolean isAccessible = method.isAccessible();
final InnerContextAccess skill;
try {
method.setAccessible(true);
skill = (InnerContextAccess) method.invoke(agent, InnerContextAccess.class);
} finally {
method.setAccessible(isAccessible);
}
final Method method = getMethodGetSkill();
final InnerContextAccess skill = (InnerContextAccess) method.invoke(agent, InnerContextAccess.class);

if (skill instanceof InnerContextSkill) {
final InnerContextSkill janusSkill = (InnerContextSkill) skill;
Expand All @@ -89,6 +85,9 @@ public static AgentContext getContextIn(Agent agent) throws Exception {
}
return null;
}
if (skill == null) {
return null;
}
return skill.getInnerContext();
}

Expand Down
@@ -0,0 +1,51 @@
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2016 the original authors or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.janusproject.kernel.services.jdk.spawn;

import java.text.MessageFormat;

import io.sarl.lang.core.Agent;

/**
* This exception is thrown when an agent cannot be spawned.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public class CannotSpawnException extends RuntimeException {

private static final long serialVersionUID = -380402400888610762L;

/**
* @param agentClazz
* - the type of the agent to spawn.
* @param cause
* - the cause of the exception.
*/
public CannotSpawnException(Class<? extends Agent> agentClazz, Throwable cause) {
super(MessageFormat.format(Messages.StandardSpawnService_3, agentClazz,
(cause == null) ? null : cause.getLocalizedMessage()), cause);
}

}
Expand Up @@ -421,7 +421,12 @@ protected void fireAgentDestroyed(Agent agent) {
synchronized (this.agentLifecycleListeners) {
list = this.agentLifecycleListeners.get(agent.getID());
}
final SpawnServiceListener[] ilisteners = list.getListeners(SpawnServiceListener.class);
final SpawnServiceListener[] ilisteners;
if (list != null) {
ilisteners = list.getListeners(SpawnServiceListener.class);
} else {
ilisteners = null;
}
final SpawnServiceListener[] ilisteners2 = this.globalListeners.getListeners(SpawnServiceListener.class);

try {
Expand All @@ -438,8 +443,10 @@ protected void fireAgentDestroyed(Agent agent) {
throw new RuntimeException(e);
}

for (final SpawnServiceListener l : ilisteners) {
l.agentDestroy(agent);
if (ilisteners != null) {
for (final SpawnServiceListener l : ilisteners) {
l.agentDestroy(agent);
}
}
for (final SpawnServiceListener l : ilisteners2) {
l.agentDestroy(agent);
Expand Down Expand Up @@ -529,31 +536,6 @@ public InvalidSarlSpecificationException(Class<? extends Agent> agentType) {

}

/**
* This exception is thrown when an agent cannot be spawned.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
public static class CannotSpawnException extends RuntimeException {

private static final long serialVersionUID = -380402400888610762L;

/**
* @param agentClazz
* - the type of the agent to spawn.
* @param cause
* - the cause of the exception.
*/
public CannotSpawnException(Class<? extends Agent> agentClazz, Throwable cause) {
super(MessageFormat.format(Messages.StandardSpawnService_3, agentClazz,
(cause == null) ? null : cause.getLocalizedMessage()), cause);
}

}

/**
* An injection module that is able to inject the parent ID and agent ID when creating an agent.
*
Expand Down
@@ -0,0 +1,135 @@
/*
* $Id$
*
* Janus platform is an open-source multiagent platform.
* More details on http://www.janusproject.io
*
* Copyright (C) 2014-2015 Sebastian RODRIGUEZ, Nicolas GAUD, Stéphane GALLAND.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.janusproject.tests.bugs;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

import org.junit.Test;

import io.janusproject.tests.testutils.AbstractJanusRunTest;

import io.sarl.core.DefaultContextInteractions;
import io.sarl.core.Lifecycle;
import io.sarl.lang.SARLVersion;
import io.sarl.lang.annotation.PerceptGuardEvaluator;
import io.sarl.lang.annotation.SarlSpecification;
import io.sarl.lang.core.Event;

/**
* Unit test for the issue #481: Spawn more than one agent at the same time.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @see https://github.com/sarl/sarl/issues/481
*/
@SuppressWarnings("all")
public class BugS481 extends AbstractJanusRunTest {

private static final boolean LOG = false;

private static final int NB_AGENTS = 50;

private static final int TIMEOUT = 60;

@Test
public void spawnSubAgents() throws Exception {
runJanus(SpawnerAgent.class, false, true, TIMEOUT);
assertEquals(NB_AGENTS, getNumberOfResults());
}

@SarlSpecification(SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING)
public static class SpawnerAgent extends TestingAgent {

private final Set<UUID> agents = new HashSet<>();

public SpawnerAgent(UUID parentID, UUID agentID) {
super(parentID, agentID);
}

@Override
protected boolean runAgentTest() {
Lifecycle skill = getSkill(Lifecycle.class);
skill.spawn(NB_AGENTS, ChildAgent.class, getAgentInitializationParameters());
return false;
}

@PerceptGuardEvaluator
private void guardEvaluator(ReadyEvent occurrence, Collection<Runnable> ___SARLlocal_runnableCollection) {
assert occurrence != null;
assert ___SARLlocal_runnableCollection != null;
___SARLlocal_runnableCollection.add(() -> onReadyEvent(occurrence));
}

private void onReadyEvent(ReadyEvent occurrence) {
synchronized(this) {
if (LOG) {
System.err.println(getID() + " received event");
}
this.agents.add(occurrence.getSource().getUUID());
if (LOG) {
System.err.println(getID() + " received event, size = " + this.agents.size());
}
if (this.agents.size() >= NB_AGENTS) {
if (LOG) {
System.err.println("results = " + this.agents);
}
for (UUID ag : this.agents) {
addResult(ag);
}
if (LOG) {
System.err.println("Commit suicide");
}
getSkill(Lifecycle.class).killMe();
}
}
}

}

@SarlSpecification(SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING)
public static class ChildAgent extends TestingAgent {

public ChildAgent(UUID parentID, UUID agentID) {
super(parentID, agentID);
}

@Override
protected boolean runAgentTest() {
DefaultContextInteractions skill = getSkill(DefaultContextInteractions.class);
skill.emit(new ReadyEvent());
if (LOG) {
System.err.println(getID() + " is sending event");
}
return true;
}

}

@SarlSpecification(SARLVersion.SPECIFICATION_RELEASE_VERSION_STRING)
public static class ReadyEvent extends Event {
}

}
Expand Up @@ -45,6 +45,7 @@
import io.janusproject.tests.testutils.AbstractJanusTest;
import io.janusproject.util.TwoStepConstruction;
import javassist.Modifier;
import net.bytebuddy.asm.Advice.Argument;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
Expand Down Expand Up @@ -108,7 +109,11 @@ public void setUp() throws Exception {
//
when(this.spawnService.isRunning()).thenReturn(true);
when(this.spawnService.state()).thenReturn(State.RUNNING);
when(this.spawnService.spawn(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
when(this.spawnService.spawn(
ArgumentMatchers.anyInt(),
ArgumentMatchers.any(),
ArgumentMatchers.any(),
ArgumentMatchers.any(),
ArgumentMatchers.any())).thenReturn(Collections.singletonList(this.uuid));
when(this.executorService.isRunning()).thenReturn(true);
when(this.executorService.state()).thenReturn(State.RUNNING);
Expand Down

0 comments on commit d110883

Please sign in to comment.