View Javadoc
1   /*
2    * Copyright (c) 2002-2025, City of Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.portal.service.daemon;
35  
36  import java.lang.management.ManagementFactory;
37  import java.lang.management.ThreadInfo;
38  import java.lang.management.ThreadMXBean;
39  import java.time.Duration;
40  import java.time.Instant;
41  import java.util.concurrent.BrokenBarrierException;
42  import java.util.concurrent.CyclicBarrier;
43  import java.util.concurrent.TimeUnit;
44  import java.util.concurrent.TimeoutException;
45  
46  import fr.paris.lutece.portal.service.plugin.PluginService;
47  import fr.paris.lutece.portal.service.util.AppLogService;
48  import fr.paris.lutece.test.LuteceTestCase;
49  
50  public class ThreadLauncherDaemonTest extends LuteceTestCase
51  {
52      private static final long TIMEOUT_DURATION = 10L;
53      private static final TimeUnit TIMEOUT_TIMEUNIT = TimeUnit.SECONDS;
54      private boolean _runnableTimedOut;
55      private Boolean _bThreadLauncherDaemonInitialState;
56      private DaemonEntry _threadLauncherDaemonEntry;
57  
58      @Override
59      protected void setUp( ) throws Exception
60      {
61          super.setUp( );
62          // we ensure the ThreadLauncherDeamon is started
63          AppLogService.info( "Ensure ThreadLauncherDeamon is started" );
64          for ( DaemonEntry daemonEntry : AppDaemonService.getDaemonEntries( ) )
65          {
66              if ( daemonEntry.getId( ).equals( "threadLauncherDaemon" ) )
67              {
68                  _threadLauncherDaemonEntry = daemonEntry;
69                  _bThreadLauncherDaemonInitialState = daemonEntry.isRunning( );
70                  break;
71              }
72          }
73          assertNotNull( "Did not find threadLauncherDaemon daemon", _bThreadLauncherDaemonInitialState );
74          AppDaemonService.startDaemon( "threadLauncherDaemon" );
75      }
76  
77      @Override
78      protected void tearDown( ) throws Exception
79      {
80          // restore threadLauncherDaemon state
81          AppLogService.info( "restore threadLauncherDaemon state ( {} )", _bThreadLauncherDaemonInitialState );
82          if ( !_bThreadLauncherDaemonInitialState.booleanValue( ) )
83          {
84              AppDaemonService.stopDaemon( "threadLauncherDaemon" );
85          }
86          super.tearDown( );
87      }
88  
89      public void testAddItemToQueue( ) throws InterruptedException, BrokenBarrierException, TimeoutException
90      {
91          CyclicBarrier barrier = new CyclicBarrier( 2 );
92          _runnableTimedOut = false;
93  
94          dumpStateWhileWaiting( 0L ); // for debugging test failure
95  
96          Instant start = Instant.now( );
97          ThreadLauncherDaemon.addItemToQueue( ( ) -> {
98              try
99              {
100                 AppLogService.info( "testAddItemToQueue: Inside the task, going to await" );
101                 barrier.await( TIMEOUT_DURATION, TIMEOUT_TIMEUNIT );
102             }
103             catch( InterruptedException | BrokenBarrierException | TimeoutException e )
104             {
105                 _runnableTimedOut = true;
106             }
107         }, "key", PluginService.getCore( ) );
108 
109         dumpStateWhileWaiting( 500L ); // for debugging test failure
110 
111         barrier.await( TIMEOUT_DURATION, TIMEOUT_TIMEUNIT );
112         AppLogService.info( "ThreadLauncherDaemonTest#testAddItemToQueue : task executed after {} ms",
113                 ( ) -> Duration.between( start, Instant.now( ) ).toMillis( ) );
114         AppLogService.info( "Last Run Logs : {}", _threadLauncherDaemonEntry.getLastRunLogs( ) );
115         assertFalse( _runnableTimedOut );
116     }
117 
118     private void dumpStateWhileWaiting( long lWait ) throws InterruptedException
119     {
120         // wait for the daemon to have a chance to try running
121         Thread.sleep( lWait );
122         final StringBuilder dump = new StringBuilder( );
123         final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean( );
124         final ThreadInfo [ ] threadInfos = threadMXBean.getThreadInfo( threadMXBean.getAllThreadIds( ), 100 );
125         for ( ThreadInfo threadInfo : threadInfos )
126         {
127             dump.append( '"' );
128             dump.append( threadInfo.getThreadName( ) );
129             dump.append( "\" " );
130             final Thread.State state = threadInfo.getThreadState( );
131             dump.append( "\n   java.lang.Thread.State: " );
132             dump.append( state );
133             final StackTraceElement [ ] stackTraceElements = threadInfo.getStackTrace( );
134             for ( final StackTraceElement stackTraceElement : stackTraceElements )
135             {
136                 dump.append( "\n        at " );
137                 dump.append( stackTraceElement );
138             }
139             dump.append( "\n\n" );
140         }
141         AppLogService.info( "Current state : {}", dump );
142     }
143 }