Salome HOME
Fix compilation pb.
[modules/kernel.git] / src / SALOMELocalTrace / LocalTraceBufferPool.cxx
1 //  copyright (C) 2004  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
3 // 
4 //  This library is free software; you can redistribute it and/or 
5 //  modify it under the terms of the GNU Lesser General Public 
6 //  License as published by the Free Software Foundation; either 
7 //  version 2.1 of the License. 
8 // 
9 //  This library is distributed in the hope that it will be useful, 
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 //  Lesser General Public License for more details. 
13 // 
14 //  You should have received a copy of the GNU Lesser General Public 
15 //  License along with this library; if not, write to the Free Software 
16 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
17 // 
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 //  Author : Paul RASCLE (EDF)
21 //  Module : KERNEL
22 //  $Header$
23 //
24 // Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
25 //
26
27 #include <iostream>
28 #include <limits.h>
29 #include <cassert>
30
31 #ifndef WNT
32 #include <dlfcn.h>
33 #else
34 #include <windows.h>
35 #endif
36
37 //#define _DEVDEBUG_
38 #include "LocalTraceBufferPool.hxx"
39 #include "BaseTraceCollector.hxx"
40 #include "LocalTraceCollector.hxx"
41 #include "FileTraceCollector.hxx"
42 #include "BasicsGenericDestructor.hxx"
43 #include "utilities.h"
44
45 using namespace std;
46
47 // In case of truncated message, end of trace contains "...\n\0"
48
49 #define TRUNCATED_MESSAGE "...\n"
50 #define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
51
52 // Class static attributes initialisation
53
54 LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
55 //#ifndef WNT
56 //pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
57 //#else
58 pthread_mutex_t LocalTraceBufferPool::_singletonMutex =
59   PTHREAD_MUTEX_INITIALIZER;
60 //#endif
61 BaseTraceCollector *LocalTraceBufferPool::_myThreadTrace = 0;
62
63 // ============================================================================
64 /*!
65  *  Guarantees a unique object instance of the class (singleton thread safe).
66  *  When the LocalTraceBufferPool instance is created, the trace collector is
67  *  also created (singleton). Type of trace collector to create depends on 
68  *  environment variable "SALOME_trace":
69  *  - "local" implies standard err trace, LocalTraceCollector is launched.
70  *  - "file" implies trace in /tmp/tracetest.log
71  *  - "file:pathname" implies trace in file pathname
72  *  - anything else like "other" : try to load dynamically a library named
73  *    otherTraceCollector, and invoque C method instance() to start a singleton
74  *    instance of the trace collector. Example: with_loggerTraceCollector, for
75  *    CORBA Log.
76  */
77 // ============================================================================
78
79 LocalTraceBufferPool* LocalTraceBufferPool::instance()
80 {
81   if (_singleton == 0) // no need of lock when singleton already exists
82     {
83       int ret;
84       ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
85       if (_singleton == 0)                     // another thread may have got
86         {                                      // the lock after the first test
87           DEVTRACE("New buffer pool");
88           LocalTraceBufferPool* myInstance = new LocalTraceBufferPool(); 
89
90           DESTRUCTOR_OF<LocalTraceBufferPool> *ptrDestroy =
91             new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
92           _singleton = myInstance;
93
94           // --- start a trace Collector
95
96           char* traceKind = getenv("SALOME_trace");
97
98           if ( !traceKind || strcmp(traceKind,"local")==0 ) // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
99             {
100               _myThreadTrace = LocalTraceCollector::instance();
101             }
102           else if (strncmp(traceKind,"file",strlen("file"))==0)
103             {
104               char *fileName;
105               if (strlen(traceKind) > strlen("file"))
106                 fileName = &traceKind[strlen("file")+1];
107               else
108                 fileName = "/tmp/tracetest.log";
109               
110               _myThreadTrace = FileTraceCollector::instance(fileName);
111             }
112           else // --- try a dynamic library
113             {
114 #ifndef WNT
115               void* handle;
116               string impl_name = string ("lib") + traceKind 
117                 + string("TraceCollector.so");
118               handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
119 #else
120               HINSTANCE handle;
121               string impl_name = string ("lib") + traceKind + string(".dll");
122               handle = LoadLibrary( impl_name.c_str() );
123 #endif
124               if ( handle )
125                 {
126                   typedef BaseTraceCollector * (*FACTORY_FUNCTION) (void);
127 #ifndef WNT
128                   FACTORY_FUNCTION TraceCollectorFactory =
129                     (FACTORY_FUNCTION) dlsym(handle, "SingletonInstance");
130 #else
131                   FACTORY_FUNCTION TraceCollectorFactory =
132                     (FACTORY_FUNCTION)GetProcAddress(handle, "SingletonInstance");
133 #endif
134                   if ( !TraceCollectorFactory )
135                   {
136                       cerr << "Can't resolve symbol: SingletonInstance" <<endl;
137 #ifndef WNT
138                       cerr << "dlerror: " << dlerror() << endl;
139 #endif
140                       exit( 1 );
141                     }
142                   _myThreadTrace = (TraceCollectorFactory) ();
143                 }
144               else
145                 {
146                   cerr << "library: " << impl_name << " not found !" << endl;
147                   assert(handle); // to give file and line
148                   exit(1);        // in case assert is deactivated
149                 }             
150             }
151           DEVTRACE("New buffer pool: end");
152         }
153       ret = pthread_mutex_unlock(&_singletonMutex); // release lock
154     }
155   return _singleton;
156 }
157
158 // ============================================================================
159 /*!
160  *  Called by trace producers within their threads. The trace message is copied
161  *  in specific buffer from a circular pool of buffers.
162  *  Waits until there is a free buffer in the pool, gets the first available
163  *  buffer, fills it with the message.
164  *  Messages are printed in a separate thread (see retrieve method)
165  */
166 // ============================================================================
167
168 int LocalTraceBufferPool::insert(int traceType, const char* msg)
169 {
170
171   // get immediately a message number to control sequence (mutex protected)
172
173   unsigned long myMessageNumber = lockedIncrement(_position);
174
175   // wait until there is a free buffer in the pool
176
177   int ret = -1;
178   while (ret)
179     {
180       ret = sem_wait(&_freeBufferSemaphore);
181       if (ret) perror(" LocalTraceBufferPool::insert, sem_wait");
182     }
183
184   // get the next free buffer available (mutex protected) 
185
186   unsigned long myInsertPos = lockedIncrement(_insertPos);
187
188   // fill the buffer with message, thread id and type (normal or abort)
189
190   strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
191           msg,
192           MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
193   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
194   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
195   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
196
197
198   // increment the full buffer semaphore
199   // (if previously 0, awake thread in charge of trace)
200
201   ret = sem_post(&_fullBufferSemaphore);
202
203   // returns the number of free buffers
204
205   sem_getvalue(&_freeBufferSemaphore, &ret);
206   return ret;  
207 }
208
209 // ============================================================================
210 /*!
211  *  Called by the thread in charge of printing trace messages.
212  *  Waits until there is a buffer with a message to print.
213  *  Gets the first buffer to print, copies it int the provided buffer
214  */
215 // ============================================================================
216
217 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
218 {
219
220   // wait until there is a buffer in the pool, with a message to print
221
222   int ret = -1;
223   while (ret)
224     {
225       ret = sem_wait(&_fullBufferSemaphore);
226       if (ret) perror(" LocalTraceBufferPool::retrieve, sem_wait");
227     }
228
229   // get the next buffer to print
230
231   unsigned long myRetrievePos = lockedIncrement(_retrievePos);
232
233   // copy the buffer from the pool to the provided buffer
234
235   memcpy((void*)&aTrace,
236          (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
237          sizeof(aTrace));
238
239   // increment the free buffer semaphore
240   // (if previously 0, awake one of the threads waiting to put a trace, if any)
241   // there is no way to preserve the order of waiting threads if several
242   // threads are waiting to put a trace: the waken up thread is not
243   // necessarily the first thread to wait.
244
245   ret = sem_post(&_freeBufferSemaphore);
246
247   // returns the number of full buffers
248
249   sem_getvalue(&_fullBufferSemaphore, &ret);
250   return ret;
251 }
252
253 // ============================================================================
254 /*!
255  *  Gives the number of buffers to print.
256  *  Usage : when the thread in charge of messages print id to be stopped,
257  *  check if there is still something to print, before stop.
258  *  There is no need of mutex here, provided there is only one thread to
259  *  retrieve and print the buffers.
260  */
261 // ============================================================================
262
263 unsigned long LocalTraceBufferPool::toCollect()
264 {
265   return _insertPos - _retrievePos;
266 }
267
268 // ============================================================================
269 /*!
270  * Constructor : initialize pool of buffers, semaphores and mutex.
271  */
272 // ============================================================================
273
274 LocalTraceBufferPool::LocalTraceBufferPool()
275 {
276   //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
277
278   _insertPos   = ULONG_MAX;  // first increment will give 0
279   _retrievePos = ULONG_MAX;
280   _position=0;               // first message will have number = 1
281
282   memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
283   for (int i=0; i<TRACE_BUFFER_SIZE; i++)
284     strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
285   int ret;
286   ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
287   if (ret!=0) IMMEDIATE_ABORT(ret);
288   ret=sem_init(&_fullBufferSemaphore, 0, 0);                 // 0 buffer full
289   if (ret!=0) IMMEDIATE_ABORT(ret);
290   ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
291   if (ret!=0) IMMEDIATE_ABORT(ret);
292
293   //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()-end" << endl;
294 }
295
296 // ============================================================================
297 /*!
298  * Destructor : release memory associated with semaphores and mutex
299  */
300 // ============================================================================
301
302 LocalTraceBufferPool::~LocalTraceBufferPool()
303 {
304   int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
305   if (_singleton)
306     {
307       DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()");
308       delete (_myThreadTrace);
309       _myThreadTrace = 0;
310       int ret;
311       ret=sem_destroy(&_freeBufferSemaphore);
312       ret=sem_destroy(&_fullBufferSemaphore);
313       ret=pthread_mutex_destroy(&_incrementMutex);
314       DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()-end");
315       _singleton = 0;
316     }
317   ret = pthread_mutex_unlock(&_singletonMutex); // release lock
318 }
319
320 // ============================================================================
321 /*!
322  * pool counters are incremented under a mutex protection
323  */
324 // ============================================================================
325
326 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
327 {
328   int ret;
329   ret = pthread_mutex_lock(&_incrementMutex);   // lock access to counters
330   unsigned long mypos = ++pos;
331   ret = pthread_mutex_unlock(&_incrementMutex); // release lock
332   return mypos;
333 }
334