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