/
AgentService.java
324 lines (236 loc) · 7.29 KB
/
AgentService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
* Copyright (C) 2010-2023 Structr GmbH
*
* This file is part of Structr <http://structr.org>.
*
* Structr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Structr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Structr. If not, see <http://www.gnu.org/licenses/>.
*/
package org.structr.agent;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.structr.api.service.*;
import org.structr.core.Services;
import org.structr.schema.ConfigurationProvider;
import org.structr.schema.SchemaService;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* The agent service main class.
*/
@ServiceDependency(SchemaService.class)
@StopServiceForMaintenanceMode
public class AgentService extends Thread implements RunnableService {
private static final Logger logger = LoggerFactory.getLogger(AgentService.class.getName());
private final int maxAgents = 10; // TODO: make configurable
private final Map<String, List<Agent>> runningAgents = new ConcurrentHashMap<>(10, 0.9f, 8);
private final Map<String, Class> agentClassCache = new ConcurrentHashMap<>(10, 0.9f, 8);
private final Queue<Task> taskQueue = new ConcurrentLinkedQueue<>();
private Set<Class> supportedCommands = null;
private boolean run = false;
public AgentService() {
super("AgentService");
supportedCommands = new LinkedHashSet<>();
supportedCommands.add(ProcessTaskCommand.class);
super.setDaemon(true);
}
public void processTask(Task task) {
synchronized (taskQueue) {
taskQueue.add(task);
logger.debug("Task {} added to task queue", task);
}
}
@Override
public void run() {
logger.info("AgentService started");
while (run) {
Task nextTask = taskQueue.poll();
if (nextTask != null) {
assignNextAgentForTask(nextTask);
}
// let others act
try { Thread.sleep(10); } catch(Throwable ignore) {}
}
}
public void notifyAgentStart(Agent agent) {
List<Agent> agents = getRunningAgentsForTask(agent.getSupportedTaskType());
synchronized (agents) {
agents.add(agent);
}
}
public void notifyAgentStop(Agent agent) {
List<Agent> agents = getRunningAgentsForTask(agent.getSupportedTaskType());
synchronized (agents) {
agents.remove(agent);
}
}
public Map<String, Class<? extends Agent>> getAgents() {
final ConfigurationProvider configuration = Services.getInstance().getConfigurationProvider();
if (configuration != null) {
return configuration.getAgents();
}
return Collections.emptyMap();
}
@Override
public void injectArguments(Command command) {
command.setArgument("agentService", this);
}
@Override
public ServiceResult initialize(final StructrServices services, String serviceName) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return new ServiceResult(true);
}
@Override
public void initialized() {}
@Override
public void shutdown() {}
@Override
public void startService() throws Exception {
run = true;
this.start();
}
@Override
public void stopService() {
run = false;
}
@Override
public boolean runOnStartup() {
return true;
}
private void assignNextAgentForTask(final Task nextTask) {
Class taskClass = nextTask.getClass();
List<Agent> agents = getRunningAgentsForTask(taskClass);
// need to synchronize on agents
synchronized (agents) {
// find next free agent (agents should be sorted by load, so one
// of the first should do..
for (Agent agent : agents) {
if (agent.assignTask(nextTask)) {
// ok, task is assigned
logger.debug("Task assigned to agent {} ({})", agent.getName(), agent.hashCode());
return;
}
}
}
if (agents.size() < maxAgents) {
// if we get here, task was not assigned to any agent, need to create a new one.
Agent agent = createAgent(nextTask);
if ((agent != null) && agent.assignTask(nextTask)) {
agent.start();
} else {
// re-add task..
synchronized (taskQueue) {
taskQueue.add(nextTask);
}
}
} else {
logger.debug("Overall agents limit reached, re-queueing task");
// re-add task..
synchronized (taskQueue) {
taskQueue.add(nextTask);
}
}
}
/**
* Creates a new agent for the given Task. Note that the agent must be
* started manually after creation.
*
* @param forTask
* @return a new agent for the given task
*/
private Agent createAgent(Task forTask) {
logger.debug("Creating new agent for task {}", forTask.getClass().getSimpleName());
Agent agent = null;
try {
agent = lookupAgent(forTask);
if (agent != null) {
// register us in agent..
agent.setAgentService(this);
}
} catch (Throwable t) {
logger.error(ExceptionUtils.getStackTrace(t));
}
return (agent);
}
private Agent lookupAgent(Task task) {
// FIXME: superuser security context
Class taskClass = task.getClass();
Agent agent = null;
Class agentClass = agentClassCache.get(taskClass.getName());
// cache miss
if (agentClass == null) {
Map<String, Class<? extends Agent>> agentClassesMap = getAgents();
if (agentClassesMap != null) {
for (Entry<String, Class<? extends Agent>> classEntry : agentClassesMap.entrySet()) {
Class<? extends Agent> supportedAgentClass = agentClassesMap.get(classEntry.getKey());
try {
Agent supportedAgent = supportedAgentClass.newInstance();
Class supportedTaskClass = supportedAgent.getSupportedTaskType();
if (supportedTaskClass.equals(taskClass)) {
agentClass = supportedAgentClass;
}
agentClassCache.put(supportedTaskClass.getName(), supportedAgentClass);
} catch (Throwable ignore) {}
}
}
}
if (agentClass != null) {
try {
agent = (Agent) agentClass.newInstance();
} catch (Throwable ignore) {}
}
return (agent);
}
/**
* Returns the current queue of remaining tasks.
* @return tasks
*/
public Collection<Task> getTaskQueue() {
return (taskQueue);
}
/**
* Returns the current collection of running agents.
* @return agents
*/
public Map<String, List<Agent>> getRunningAgents() {
return (runningAgents);
}
private List<Agent> getRunningAgentsForTask(Class taskClass) {
List<Agent> agents = runningAgents.get(taskClass.getName());
if (agents == null) {
agents = Collections.synchronizedList(new LinkedList<>());
// Hashtable is synchronized
runningAgents.put(taskClass.getName(), agents);
}
return (agents);
}
@Override
public boolean isRunning() {
return (this.run);
}
@Override
public boolean isVital() {
return false;
}
@Override
public boolean waitAndRetry() {
return false;
}
// ----- interface Feature -----
@Override
public String getModuleName() {
return "agents";
}
}