1 package org
.argeo
.cms
.internal
.kernel
;
3 import java
.io
.IOException
;
5 import java
.nio
.file
.FileSystems
;
6 import java
.nio
.file
.Path
;
7 import java
.nio
.file
.Paths
;
8 import java
.nio
.file
.StandardWatchEventKinds
;
9 import java
.nio
.file
.WatchEvent
;
10 import java
.nio
.file
.WatchKey
;
11 import java
.nio
.file
.WatchService
;
12 import java
.security
.SignatureException
;
13 import java
.util
.ArrayList
;
14 import java
.util
.Collections
;
15 import java
.util
.Enumeration
;
16 import java
.util
.HashMap
;
17 import java
.util
.Iterator
;
18 import java
.util
.LinkedList
;
19 import java
.util
.List
;
20 import java
.util
.ListIterator
;
22 import java
.util
.Properties
;
23 import java
.util
.concurrent
.BlockingQueue
;
24 import java
.util
.concurrent
.LinkedBlockingQueue
;
26 import org
.apache
.commons
.logging
.Log
;
27 import org
.apache
.commons
.logging
.LogFactory
;
28 import org
.apache
.log4j
.AppenderSkeleton
;
29 import org
.apache
.log4j
.Level
;
30 import org
.apache
.log4j
.LogManager
;
31 import org
.apache
.log4j
.Logger
;
32 import org
.apache
.log4j
.PropertyConfigurator
;
33 import org
.apache
.log4j
.spi
.LoggingEvent
;
34 import org
.argeo
.api
.ArgeoLogListener
;
35 import org
.argeo
.api
.ArgeoLogger
;
36 import org
.argeo
.api
.NodeConstants
;
37 import org
.argeo
.cms
.CmsException
;
38 import org
.argeo
.cms
.auth
.CurrentUser
;
39 import org
.argeo
.osgi
.useradmin
.UserAdminConf
;
40 import org
.osgi
.framework
.Bundle
;
41 import org
.osgi
.framework
.Constants
;
42 import org
.osgi
.framework
.ServiceReference
;
43 import org
.osgi
.service
.cm
.ConfigurationAdmin
;
44 import org
.osgi
.service
.log
.LogEntry
;
45 import org
.osgi
.service
.log
.LogLevel
;
46 import org
.osgi
.service
.log
.LogListener
;
47 import org
.osgi
.service
.log
.LogReaderService
;
49 /** Not meant to be used directly in standard log4j config */
50 class NodeLogger
implements ArgeoLogger
, LogListener
{
51 /** Internal debug for development purposes. */
52 private static Boolean debug
= false;
54 // private final static Log log = LogFactory.getLog(NodeLogger.class);
56 private Boolean disabled
= false;
58 private String level
= null;
60 private Level log4jLevel
= null;
61 // private Layout layout;
63 private Properties configuration
;
65 private AppenderImpl appender
;
67 private final List
<ArgeoLogListener
> everythingListeners
= Collections
68 .synchronizedList(new ArrayList
<ArgeoLogListener
>());
69 private final List
<ArgeoLogListener
> allUsersListeners
= Collections
70 .synchronizedList(new ArrayList
<ArgeoLogListener
>());
71 private final Map
<String
, List
<ArgeoLogListener
>> userListeners
= Collections
72 .synchronizedMap(new HashMap
<String
, List
<ArgeoLogListener
>>());
74 private BlockingQueue
<LogEvent
> events
;
75 private LogDispatcherThread logDispatcherThread
= new LogDispatcherThread();
77 private Integer maxLastEventsCount
= 10 * 1000;
79 /** Marker to prevent stack overflow */
80 private ThreadLocal
<Boolean
> dispatching
= new ThreadLocal
<Boolean
>() {
83 protected Boolean
initialValue() {
88 public NodeLogger(LogReaderService lrs
) {
90 Enumeration
<LogEntry
> logEntries
= lrs
.getLog();
91 while (logEntries
.hasMoreElements())
92 logged(logEntries
.nextElement());
93 lrs
.addLogListener(this);
95 // configure log4j watcher
96 String log4jConfiguration
= KernelUtils
.getFrameworkProp("log4j.configuration");
97 if (log4jConfiguration
!= null && log4jConfiguration
.startsWith("file:")) {
98 if (log4jConfiguration
.contains("..")) {
99 if (log4jConfiguration
.startsWith("file://"))
100 log4jConfiguration
= log4jConfiguration
.substring("file://".length());
101 else if (log4jConfiguration
.startsWith("file:"))
102 log4jConfiguration
= log4jConfiguration
.substring("file:".length());
105 Path log4jconfigPath
;
106 if (log4jConfiguration
.startsWith("file:"))
107 log4jconfigPath
= Paths
.get(new URI(log4jConfiguration
));
109 log4jconfigPath
= Paths
.get(log4jConfiguration
);
110 Thread log4jConfWatcher
= new Log4jConfWatcherThread(log4jconfigPath
);
111 log4jConfWatcher
.start();
112 } catch (Exception e
) {
113 stdErr("Badly formatted log4j configuration URI " + log4jConfiguration
+ ": " + e
.getMessage());
121 events
= new LinkedBlockingQueue
<LogEvent
>();
123 // if (layout != null)
124 // setLayout(layout);
126 // setLayout(new PatternLayout(pattern));
127 appender
= new AppenderImpl();
128 reloadConfiguration();
129 Logger
.getRootLogger().addAppender(appender
);
131 logDispatcherThread
= new LogDispatcherThread();
132 logDispatcherThread
.start();
133 } catch (Exception e
) {
134 throw new CmsException("Cannot initialize log4j");
138 public void destroy() throws Exception
{
139 Logger
.getRootLogger().removeAppender(appender
);
140 allUsersListeners
.clear();
141 for (List
<ArgeoLogListener
> lst
: userListeners
.values())
143 userListeners
.clear();
147 logDispatcherThread
.interrupt();
150 // public void setLayout(Layout layout) {
151 // this.layout = layout;
154 public String
toString() {
155 return "Node Logger";
162 public void logged(LogEntry status
) {
163 Log pluginLog
= LogFactory
.getLog(status
.getBundle().getSymbolicName());
164 LogLevel severity
= status
.getLogLevel();
165 if (severity
.equals(LogLevel
.ERROR
) && pluginLog
.isErrorEnabled()) {
166 // FIXME Fix Argeo TP
167 if (status
.getException() instanceof SignatureException
)
169 pluginLog
.error(msg(status
), status
.getException());
170 } else if (severity
.equals(LogLevel
.WARN
) && pluginLog
.isWarnEnabled()) {
171 if (pluginLog
.isTraceEnabled())
172 pluginLog
.warn(msg(status
), status
.getException());
174 pluginLog
.warn(msg(status
));
175 } else if (severity
.equals(LogLevel
.INFO
) && pluginLog
.isDebugEnabled())
176 pluginLog
.debug(msg(status
), status
.getException());
177 else if (severity
.equals(LogLevel
.DEBUG
) && pluginLog
.isTraceEnabled())
178 pluginLog
.trace(msg(status
), status
.getException());
179 else if (severity
.equals(LogLevel
.TRACE
) && pluginLog
.isTraceEnabled())
180 pluginLog
.trace(msg(status
), status
.getException());
183 private String
msg(LogEntry status
) {
184 StringBuilder sb
= new StringBuilder();
185 sb
.append(status
.getMessage());
186 Bundle bundle
= status
.getBundle();
187 if (bundle
!= null) {
188 sb
.append(" '" + bundle
.getSymbolicName() + "'");
190 ServiceReference
<?
> sr
= status
.getServiceReference();
193 String
[] objectClasses
= (String
[]) sr
.getProperty(Constants
.OBJECTCLASS
);
194 if (isSpringApplicationContext(objectClasses
)) {
195 sb
.append("{org.springframework.context.ApplicationContext}");
196 Object symbolicName
= sr
.getProperty(Constants
.BUNDLE_SYMBOLICNAME
);
197 if (symbolicName
!= null)
198 sb
.append(" " + Constants
.BUNDLE_SYMBOLICNAME
+ ": " + symbolicName
);
200 sb
.append(arrayToString(objectClasses
));
202 Object cn
= sr
.getProperty(NodeConstants
.CN
);
204 sb
.append(" " + NodeConstants
.CN
+ ": " + cn
);
205 Object factoryPid
= sr
.getProperty(ConfigurationAdmin
.SERVICE_FACTORYPID
);
206 if (factoryPid
!= null)
207 sb
.append(" " + ConfigurationAdmin
.SERVICE_FACTORYPID
+ ": " + factoryPid
);
209 // Object servicePid = sr.getProperty(Constants.SERVICE_PID);
210 // if (servicePid != null)
211 // sb.append(" " + Constants.SERVICE_PID + ": " + servicePid);
214 Object whiteBoardPattern
= sr
.getProperty(KernelConstants
.WHITEBOARD_PATTERN_PROP
);
215 if (whiteBoardPattern
!= null) {
216 if (whiteBoardPattern
instanceof String
) {
217 sb
.append(" " + KernelConstants
.WHITEBOARD_PATTERN_PROP
+ ": " + whiteBoardPattern
);
219 sb
.append(" " + KernelConstants
.WHITEBOARD_PATTERN_PROP
+ ": "
220 + arrayToString((String
[]) whiteBoardPattern
));
224 Object contextName
= sr
.getProperty(KernelConstants
.CONTEXT_NAME_PROP
);
225 if (contextName
!= null)
226 sb
.append(" " + KernelConstants
.CONTEXT_NAME_PROP
+ ": " + contextName
);
229 Object baseDn
= sr
.getProperty(UserAdminConf
.baseDn
.name());
231 sb
.append(" " + UserAdminConf
.baseDn
.name() + ": " + baseDn
);
234 return sb
.toString();
237 private String
arrayToString(Object
[] arr
) {
238 StringBuilder sb
= new StringBuilder();
240 for (int i
= 0; i
< arr
.length
; i
++) {
246 return sb
.toString();
249 private boolean isSpringApplicationContext(String
[] objectClasses
) {
250 for (String clss
: objectClasses
) {
251 if (clss
.equals("org.eclipse.gemini.blueprint.context.DelegatedExecutionOsgiBundleApplicationContext")) {
262 public synchronized void register(ArgeoLogListener listener
, Integer numberOfPreviousEvents
) {
263 String username
= CurrentUser
.getUsername();
264 if (username
== null)
265 throw new CmsException("Only authenticated users can register a log listener");
267 if (!userListeners
.containsKey(username
)) {
268 List
<ArgeoLogListener
> lst
= Collections
.synchronizedList(new ArrayList
<ArgeoLogListener
>());
269 userListeners
.put(username
, lst
);
271 userListeners
.get(username
).add(listener
);
272 List
<LogEvent
> lastEvents
= logDispatcherThread
.getLastEvents(username
, numberOfPreviousEvents
);
273 for (LogEvent evt
: lastEvents
)
274 dispatchEvent(listener
, evt
);
277 public synchronized void registerForAll(ArgeoLogListener listener
, Integer numberOfPreviousEvents
,
278 boolean everything
) {
280 everythingListeners
.add(listener
);
282 allUsersListeners
.add(listener
);
283 List
<LogEvent
> lastEvents
= logDispatcherThread
.getLastEvents(null, numberOfPreviousEvents
);
284 for (LogEvent evt
: lastEvents
)
285 if (everything
|| evt
.getUsername() != null)
286 dispatchEvent(listener
, evt
);
289 public synchronized void unregister(ArgeoLogListener listener
) {
290 String username
= CurrentUser
.getUsername();
291 if (username
== null)// FIXME
293 if (!userListeners
.containsKey(username
))
294 throw new CmsException("No user listeners " + listener
+ " registered for user " + username
);
295 if (!userListeners
.get(username
).contains(listener
))
296 throw new CmsException("No user listeners " + listener
+ " registered for user " + username
);
297 userListeners
.get(username
).remove(listener
);
298 if (userListeners
.get(username
).isEmpty())
299 userListeners
.remove(username
);
303 public synchronized void unregisterForAll(ArgeoLogListener listener
) {
304 everythingListeners
.remove(listener
);
305 allUsersListeners
.remove(listener
);
308 /** For development purpose, since using regular logging is not easy here */
309 private static void stdOut(Object obj
) {
310 System
.out
.println(obj
);
313 private static void stdErr(Object obj
) {
314 System
.err
.println(obj
);
317 private static void debug(Object obj
) {
319 System
.out
.println(obj
);
322 private static boolean isInternalDebugEnabled() {
326 // public void setPattern(String pattern) {
327 // this.pattern = pattern;
330 public void setDisabled(Boolean disabled
) {
331 this.disabled
= disabled
;
334 public void setLevel(String level
) {
338 public void setConfiguration(Properties configuration
) {
339 this.configuration
= configuration
;
342 public void updateConfiguration(Properties configuration
) {
343 setConfiguration(configuration
);
344 reloadConfiguration();
347 public Properties
getConfiguration() {
348 return configuration
;
352 * Reloads configuration (if the configuration {@link Properties} is set)
354 protected void reloadConfiguration() {
355 if (configuration
!= null) {
356 LogManager
.resetConfiguration();
357 PropertyConfigurator
.configure(configuration
);
361 protected synchronized void processLoggingEvent(LogEvent event
) {
365 if (dispatching
.get())
368 if (level
!= null && !level
.trim().equals("")) {
369 if (log4jLevel
== null || !log4jLevel
.toString().equals(level
))
371 log4jLevel
= Level
.toLevel(level
);
372 } catch (Exception e
) {
373 System
.err
.println("Log4j level could not be set for level '" + level
+ "', resetting it to null.");
378 if (log4jLevel
!= null && !event
.getLoggingEvent().getLevel().isGreaterOrEqual(log4jLevel
)) {
385 Iterator
<ArgeoLogListener
> everythingIt
= everythingListeners
.iterator();
386 while (everythingIt
.hasNext())
387 dispatchEvent(everythingIt
.next(), event
);
389 if (event
.getUsername() != null) {
390 Iterator
<ArgeoLogListener
> allUsersIt
= allUsersListeners
.iterator();
391 while (allUsersIt
.hasNext())
392 dispatchEvent(allUsersIt
.next(), event
);
394 if (userListeners
.containsKey(event
.getUsername())) {
395 Iterator
<ArgeoLogListener
> userIt
= userListeners
.get(event
.getUsername()).iterator();
396 while (userIt
.hasNext())
397 dispatchEvent(userIt
.next(), event
);
400 } catch (Exception e
) {
401 stdOut("Cannot process logging event");
406 protected void dispatchEvent(ArgeoLogListener logListener
, LogEvent evt
) {
407 LoggingEvent event
= evt
.getLoggingEvent();
408 logListener
.appendLog(evt
.getUsername(), event
.getTimeStamp(), event
.getLevel().toString(),
409 event
.getLoggerName(), event
.getThreadName(), event
.getMessage(), event
.getThrowableStrRep());
412 private class AppenderImpl
extends AppenderSkeleton
{
413 public boolean requiresLayout() {
417 public void close() {
421 protected void append(LoggingEvent event
) {
422 if (events
!= null) {
424 String username
= CurrentUser
.getUsername();
425 events
.put(new LogEvent(username
, event
));
426 } catch (InterruptedException e
) {
434 private class LogDispatcherThread
extends Thread
{
435 /** encapsulated in order to simplify concurrency management */
436 private LinkedList
<LogEvent
> lastEvents
= new LinkedList
<LogEvent
>();
438 public LogDispatcherThread() {
439 super("Argeo Logging Dispatcher Thread");
443 while (events
!= null) {
445 LogEvent loggingEvent
= events
.take();
446 processLoggingEvent(loggingEvent
);
447 addLastEvent(loggingEvent
);
448 } catch (InterruptedException e
) {
455 protected synchronized void addLastEvent(LogEvent loggingEvent
) {
456 if (lastEvents
.size() >= maxLastEventsCount
)
458 lastEvents
.add(loggingEvent
);
461 public synchronized List
<LogEvent
> getLastEvents(String username
, Integer maxCount
) {
462 LinkedList
<LogEvent
> evts
= new LinkedList
<LogEvent
>();
463 ListIterator
<LogEvent
> it
= lastEvents
.listIterator(lastEvents
.size());
465 while (it
.hasPrevious() && (count
< maxCount
)) {
466 LogEvent evt
= it
.previous();
467 if (username
== null || username
.equals(evt
.getUsername())) {
476 private class LogEvent
{
477 private final String username
;
478 private final LoggingEvent loggingEvent
;
480 public LogEvent(String username
, LoggingEvent loggingEvent
) {
482 this.username
= username
;
483 this.loggingEvent
= loggingEvent
;
487 public int hashCode() {
488 return loggingEvent
.hashCode();
492 public boolean equals(Object obj
) {
493 return loggingEvent
.equals(obj
);
497 public String
toString() {
498 return username
+ "@ " + loggingEvent
.toString();
501 public String
getUsername() {
505 public LoggingEvent
getLoggingEvent() {
511 private class Log4jConfWatcherThread
extends Thread
{
512 private Path log4jConfigurationPath
;
514 public Log4jConfWatcherThread(Path log4jConfigurationPath
) {
515 super("Log4j Configuration Watcher");
517 this.log4jConfigurationPath
= log4jConfigurationPath
.toRealPath();
518 } catch (IOException e
) {
519 this.log4jConfigurationPath
= log4jConfigurationPath
.toAbsolutePath();
520 stdOut("Cannot determine real path for " + log4jConfigurationPath
+ ": " + e
.getMessage());
525 Path parentDir
= log4jConfigurationPath
.getParent();
526 try (final WatchService watchService
= FileSystems
.getDefault().newWatchService()) {
527 parentDir
.register(watchService
, StandardWatchEventKinds
.ENTRY_MODIFY
);
529 watching
: while ((wk
= watchService
.take()) != null) {
530 for (WatchEvent
<?
> event
: wk
.pollEvents()) {
531 final Path changed
= (Path
) event
.context();
532 if (log4jConfigurationPath
.equals(parentDir
.resolve(changed
))) {
533 if (isInternalDebugEnabled())
534 debug(log4jConfigurationPath
+ " has changed, reloading.");
535 PropertyConfigurator
.configure(log4jConfigurationPath
.toUri().toURL());
539 boolean valid
= wk
.reset();
544 } catch (IOException
| InterruptedException e
) {
545 stdErr("Log4j configuration watcher failed: " + e
.getMessage());