/
SreMain.sarl
407 lines (364 loc) · 11.9 KB
/
SreMain.sarl
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
* $Id$
*
* SARL is an general-purpose agent programming language.
* More details on http://www.sarl.io
*
* Copyright (C) 2014-2020 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.sarl.sre.boot
import com.google.common.base.Throwables
import com.google.common.util.concurrent.Service
import com.google.inject.Injector
import com.google.inject.Module
import com.google.inject.ProvisionException
import io.bootique.BQRuntime
import io.bootique.Bootique
import io.bootique.help.HelpOption
import io.bootique.help.HelpOptions
import io.bootique.meta.application.ApplicationMetadata
import io.sarl.bootstrap.SRE
import io.sarl.bootstrap.SREBootstrap
import io.sarl.bootstrap.SREListener
import io.sarl.lang.core.Agent
import io.sarl.lang.core.AgentContext
import io.sarl.sre.Kernel
import io.sarl.sre.boot.configs.SreConfig
import io.sarl.sre.boot.configs.subconfigs.BootConfig
import io.sarl.sre.boot.configs.subconfigs.RootContextType
import io.sarl.sre.services.lifecycle.KernelAgentLifecycleListener
import io.sarl.sre.services.lifecycle.LifecycleService
import io.sarl.sre.services.logging.LoggingService
import java.util.List
import java.util.UUID
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicReference
import java.util.logging.Level
import org.apache.log4j.Logger
import org.arakhne.afc.bootique.log4j.configs.Log4jIntegrationConfig
import org.arakhne.afc.bootique.variables.VariableNames
import org.arakhne.afc.util.ListenerCollection
import org.eclipse.xtend.lib.annotations.Accessors
import static io.sarl.bootstrap.SRE.*
/** Class that implements the standard main function for running a SARL run-time environment
* with bootique modules.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @since 0.9
*/
class SreMain implements SREBootstrap {
static val BACKGROUND_SHUTDOWN_TIMEOUT = 20000
val kernel = new AtomicReference<Kernel>
@Accessors(PUBLIC_GETTER)
var runtime : BQRuntime
var bootType : RootContextType
var userDefinedContextId : UUID
var userDefinedSpaceId : UUID
val listeners = new ListenerCollection<SREListener>
/** Replies the reference to the kernel.
*
* @return the reference to the kernel.
*/
def getKernel : Kernel {
return this.kernel.get
}
/** Set the Bootique runtime instance.
*
* @param runtime the new Bootique runtime.
* @return {@code true} if the runtime has been changed.
*/
def setRuntime(runtime : BQRuntime) : boolean {
if (this.runtime !== runtime) {
this.runtime = runtime
return true
}
return false
}
override isRunning : boolean {
val k = getKernel
return k !== null && k.isRunning
}
override setRandomContextUUID {
this.bootType = RootContextType::RANDOM
this.userDefinedContextId = null
}
override setBootAgentTypeContextUUID {
this.bootType = RootContextType::BOOT_AGENT_NAME
this.userDefinedContextId = null
}
override setSpecificContextUUID {
this.bootType = RootContextType::DEFAULT
this.userDefinedContextId = null
}
override setUniverseContextUUID(id : UUID) {
this.userDefinedContextId = id
}
override getUniverseContextUUID : UUID {
this.userDefinedContextId
}
override setUniverseSpaceUUID(id : UUID) {
this.userDefinedSpaceId = id
}
override getUniverseSpaceUUID : UUID {
this.userDefinedSpaceId
}
override setVerboseLevel(level : int) {
var config = ensureBootiqueRuntimeInstance(null, null).getInstance(typeof(Log4jIntegrationConfig))
var levels = org.arakhne.afc.bootique.log4j.configs.Level::values
var lvl = if (level < 0) 0 else (if (level >= levels.length) levels.length - 1 else level)
var levelObject = levels.get(lvl)
config.level = levelObject
var logger = getKernelLogger
if (logger !== null) {
logger.level = levelObject.toJul
}
}
override getKernelLogger : java.util.logging.Logger {
if (isActive) {
var service = this.runtime.getInstance(typeof(LoggingService))
return service.platformLogger
}
return null
}
/** Create the SRE runtime.
*
* @param bootique the instance of the bootique accessor, or {@code null} if none is provided.
* @param module specify the type of the injection module to be used by the bootique accessor.
* @param args the command line arguments to put into the bootique accessor. This argument is used only if {@code bootique}
* is evaluated to {@code null}.
* @return the runtime.
*/
protected def createRuntime(bootique : Bootique, module : Class<? extends Module>, args : String*) : BQRuntime {
var bt = bootique ?: Bootique::app(args)
if (module !== null) {
bt = bt.module(module)
}
return bt.autoLoadModules.createRuntime
}
private def ensureBootiqueRuntimeInstance(bootique : Bootique, module : Class<? extends Module>, args : String*) : BQRuntime {
var r = this.runtime
if (r === null) {
this.runtime = createRuntime(bootique, module, args)
r = this.runtime
}
return this.runtime
}
/** Run the SRE.
*
* <p>This function runs the SRE and exits with the return code.
*
* @param args the command line arguments.
* @return the exit code.
*/
def runSRE(args : String*) : int {
var runtime = ensureBootiqueRuntimeInstance(null, null, args)
try {
// Force the bootstrap to be this object
SRE::bootstrap = this
val outcome = runtime.run
if (outcome !== null) {
if (!outcome.success && outcome.exception !== null) {
Logger::rootLogger.error(outcome.message, outcome.exception)
}
return outcome.exitCode
}
} catch (exception : ProvisionException) {
val ex = Throwables::getRootCause(exception)
if (ex !== null) {
Logger::rootLogger.error(ex.localizedMessage)
} else {
Logger.rootLogger.error(exception.localizedMessage)
}
} catch (exception : Throwable) {
Logger::rootLogger.error(exception.localizedMessage)
}
return 255
}
/** Replies the options of the program.
*
* @return the options of the program.
*/
def getOptions : List<HelpOption> {
val runtime = ensureBootiqueRuntimeInstance(null, null)
val application = runtime.getInstance(typeof(ApplicationMetadata))
val helpOptions = new HelpOptions
application.commands.forEach [ c |
helpOptions.add(c.asOption)
c.options.forEach [o | helpOptions.add(o)]
]
application.options.forEach [o | helpOptions.add(o)]
return helpOptions.options
}
private def ensureKernelInstance(bootique : Bootique, module : Class<? extends Module>, args : String*) : Kernel {
var k = getKernel
if (k === null) {
var runtime = ensureBootiqueRuntimeInstance(bootique, module, args)
val injector = runtime.getInstance(typeof(Injector))
// Update the method for selecting the root context identifier
if (this.bootType !== null
|| this.userDefinedContextId !== null
|| this.userDefinedSpaceId !== null) {
val sreConfig = injector.getInstance(typeof(SreConfig))
if (this.bootType !== null) {
sreConfig.boot.rootContextBootType = this.bootType
}
if (this.userDefinedContextId !== null) {
sreConfig.boot.rootContextID = this.userDefinedContextId
}
if (this.userDefinedSpaceId !== null) {
sreConfig.boot.rootSpaceID = this.userDefinedSpaceId
}
}
k = injector.getInstance(typeof(Kernel))
val listener : KernelAgentLifecycleListener = [
this.kernel.set(null)
this.runtime = null
fireSREStopped
]
k.getService(typeof(LifecycleService)).addKernelAgentLifecycleListener(listener)
this.kernel.set(k)
fireSREStarted
}
// Force the bootstrap to be this object
SRE::bootstrap = this
return getKernel
}
/** Start the agent framework without agent.
*
* @param bootique the Bootique instance to set up the framework. If it is {@code null},
* the default Bootique instance is created.
* @param module the injection module to use. If it is {@code null}, the default module is used.
*/
def startWithoutAgent(bootique : Bootique = null, module : Class<? extends Module> = null) : AgentContext {
ensureKernelInstance(bootique, module).rootContext
}
def startAgent(nbAgents : int, agentCls : Class<? extends Agent>,
params : Object*) {
val propName = VariableNames::toPropertyName(BootConfig::BOOT_AGENT_NAME)
val old = System::setProperty(propName, agentCls.name)
var kernel : Kernel
try {
kernel = ensureKernelInstance(null, null)
} finally {
if (old === null) {
System::clearProperty(propName)
} else {
System::setProperty(propName, old)
}
}
kernel.spawn(nbAgents, agentCls, params)
}
/** Start the boot agent if it is specified in the boot configuration.
*/
def startBootAgent {
var config = this.runtime.getInstance(typeof(SreConfig)).boot
var bootAgent = config.getBootAgent(this.class.classLoader)
assert bootAgent !== null
var args = config.agentStartArgs
startAgent(bootAgent, args)
}
def startAgent(agentCls : Class<? extends Agent>, params : Object*) {
val propName = VariableNames::toPropertyName(BootConfig::BOOT_AGENT_NAME)
assert propName !== null
var alreadyLaunched = System::getProperty(propName)
if (alreadyLaunched.nullOrEmpty) {
// Force the property that indicates the booted agent
System::setProperty(propName, agentCls.name)
}
val kernel = ensureKernelInstance(null, null)
kernel.spawn(agentCls, params)
}
def startAgentWithID(agentCls : Class<? extends Agent>, agentID : UUID, params : Object*) {
val propName = VariableNames::toPropertyName(BootConfig::BOOT_AGENT_NAME)
assert propName !== null
var alreadyLaunched = System::getProperty(propName)
if (alreadyLaunched.nullOrEmpty) {
// Force the property that indicates the booted agent
System::setProperty(propName, agentCls.name)
}
val kernel = ensureKernelInstance(null, null)
kernel.spawn(agentID, agentCls, params)
}
@SuppressWarnings("discouraged_reference")
def shutdown(timeout : int) {
val kern = this.kernel.getAndSet(null)
if (kern !== null) {
if (timeout !== 0) {
kern.shutdown(timeout)
} else {
val th = Executors::defaultThreadFactory.newThread [
kern.shutdown(BACKGROUND_SHUTDOWN_TIMEOUT)
]
th => [
daemon = true
name = "SRE Forced Async Shutdown"
start
]
}
}
}
override getService(serviceType : Class<T>) : T with T {
if (typeof(Service).isAssignableFrom(serviceType)) {
var kern = getKernel
if (kern !== null) {
var castedServiceType = serviceType.asSubclass(typeof(Service))
var serv = kern.getService(castedServiceType)
return serviceType.cast(serv)
}
}
return null
}
override addSREListener(listener : SREListener) {
if (listener !== null) {
this.listeners.add(typeof(SREListener), listener)
}
}
override removeSREListener(listener : SREListener) {
if (listener !== null) {
this.listeners.remove(typeof(SREListener), listener)
}
}
/** Notifies the observers that the SRE has been started.
*
* @since 0.11
*/
protected def fireSREStarted {
val observers = this.listeners.getListeners(typeof(SREListener))
for (observer : observers) {
try {
observer.sreStarted(this)
} catch (exception : Throwable) {
getKernelLogger.log(Level::SEVERE, exception.localizedMessage, exception)
}
}
}
/** Notifies the observers that the SRE has been stopped.
*
* @since 0.11
*/
protected def fireSREStopped {
val observers = this.listeners.getListeners(typeof(SREListener))
for (observer : observers) {
try {
observer.sreStopped(this)
} catch (exception : Throwable) {
getKernelLogger.log(Level::SEVERE, exception.localizedMessage, exception)
}
}
}
}