Salome HOME
PR: merge from branch BR_3_1_0deb tag mergeto_trunk_22dec05
[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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
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 #endif
35
36 //#define _DEVDEBUG_
37 #include "LocalTraceBufferPool.hxx"
38 #include "BaseTraceCollector.hxx"
39 #include "LocalTraceCollector.hxx"
40 #include "FileTraceCollector.hxx"
41 #include "BasicsGenericDestructor.hxx"
42 #include "utilities.h"
43
44 using namespace std;
45
46 // In case of truncated message, end of trace contains "...\n\0"
47
48 #define TRUNCATED_MESSAGE "...\n"
49 #define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
50
51 // Class static attributes initialisation
52
53 LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
54 #ifndef WNT
55 pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
56 #else
57 pthread_mutex_t LocalTraceBufferPool::_singletonMutex =
58   PTHREAD_MUTEX_INITIALIZER;
59 #endif
60 BaseTraceCollector *LocalTraceBufferPool::_myThreadTrace = 0;
61
62 // ============================================================================
63 /*!
64  *  Guarantees a unique object instance of the class (singleton thread safe).
65  *  When the LocalTraceBufferPool instance is created, the trace collector is
66  *  also created (singleton). Type of trace collector to create depends on 
67  *  environment variable "SALOME_trace":
68  *  - "local" implies standard err trace, LocalTraceCollector is launched.
69  *  - "file" implies trace in /tmp/tracetest.log
70  *  - "file:pathname" implies trace in file pathname
71  *  - anything else like "other" : try to load dynamically a library named
72  *    otherTraceCollector, and invoque C method instance() to start a singleton
73  *    instance of the trace collector. Example: with_loggerTraceCollector, for
74  *    CORBA Log.
75  */
76 // ============================================================================
77
78 LocalTraceBufferPool* LocalTraceBufferPool::instance()
79 {
80   if (_singleton == 0) // no need of lock when singleton already exists
81     {
82       int ret;
83       ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
84       if (_singleton == 0)                     // another thread may have got
85         {                                      // the lock after the first test
86           DEVTRACE("New buffer pool");
87           LocalTraceBufferPool* myInstance = new LocalTraceBufferPool(); 
88
89           DESTRUCTOR_OF<LocalTraceBufferPool> *ptrDestroy =
90             new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
91           _singleton = myInstance;
92
93           // --- start a trace Collector
94
95           char* traceKind = getenv("SALOME_trace");
96           assert(traceKind);
97           //cerr<<"SALOME_trace="<<traceKind<<endl;
98
99           if (strcmp(traceKind,"local")==0)
100             {
101               _myThreadTrace = LocalTraceCollector::instance();
102             }
103           else if (strncmp(traceKind,"file",strlen("file"))==0)
104             {
105               char *fileName;
106               if (strlen(traceKind) > strlen("file"))
107                 fileName = &traceKind[strlen("file")+1];
108               else
109                 fileName = "/tmp/tracetest.log";
110               
111               _myThreadTrace = FileTraceCollector::instance(fileName);
112             }
113           else // --- try a dynamic library
114             {
115               void* handle;
116 #ifndef WNT
117               string impl_name = string ("lib") + traceKind 
118                 + string("TraceCollector.so");
119               handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
120 #else
121               string impl_name = string ("lib") + traceKind + string(".dll");
122               handle = dlopen( impl_name.c_str() , 0 ) ;
123 #endif
124               if ( handle )
125                 {
126                   typedef BaseTraceCollector * (*FACTORY_FUNCTION) (void);
127                   FACTORY_FUNCTION TraceCollectorFactory =
128                     (FACTORY_FUNCTION) dlsym(handle, "SingletonInstance");
129                   char *error ;
130                   if ( (error = dlerror() ) != NULL)
131                     {
132                       cerr << "Can't resolve symbol: SingletonInstance" <<endl;
133                       cerr << "dlerror: " << error << endl;
134                       assert(error == NULL); // to give file and line
135                       exit(1);               // in case assert is deactivated
136                     }
137                   _myThreadTrace = (TraceCollectorFactory) ();
138                 }
139               else
140                 {
141                   cerr << "library: " << impl_name << " not found !" << endl;
142                   assert(handle); // to give file and line
143                   exit(1);        // in case assert is deactivated
144                 }             
145             }
146           DEVTRACE("New buffer pool: end");
147         }
148       ret = pthread_mutex_unlock(&_singletonMutex); // release lock
149     }
150   return _singleton;
151 }
152
153 // ============================================================================
154 /*!
155  *  Called by trace producers within their threads. The trace message is copied
156  *  in specific buffer from a circular pool of buffers.
157  *  Waits until there is a free buffer in the pool, gets the first available
158  *  buffer, fills it with the message.
159  *  Messages are printed in a separate thread (see retrieve method)
160  */
161 // ============================================================================
162
163 int LocalTraceBufferPool::insert(int traceType, const char* msg)
164 {
165
166   // get immediately a message number to control sequence (mutex protected)
167
168   unsigned long myMessageNumber = lockedIncrement(_position);
169
170   // wait until there is a free buffer in the pool
171
172   int ret = -1;
173   while (ret)
174     {
175       ret = sem_wait(&_freeBufferSemaphore);
176       if (ret) perror(" LocalTraceBufferPool::insert, sem_wait");
177     }
178
179   // get the next free buffer available (mutex protected) 
180
181   unsigned long myInsertPos = lockedIncrement(_insertPos);
182
183   // fill the buffer with message, thread id and type (normal or abort)
184
185   strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
186           msg,
187           MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
188   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
189   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
190   _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
191
192
193   // increment the full buffer semaphore
194   // (if previously 0, awake thread in charge of trace)
195
196   ret = sem_post(&_fullBufferSemaphore);
197
198   // returns the number of free buffers
199
200   sem_getvalue(&_freeBufferSemaphore, &ret);
201   return ret;  
202 }
203
204 // ============================================================================
205 /*!
206  *  Called by the thread in charge of printing trace messages.
207  *  Waits until there is a buffer with a message to print.
208  *  Gets the first buffer to print, copies it int the provided buffer
209  */
210 // ============================================================================
211
212 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
213 {
214
215   // wait until there is a buffer in the pool, with a message to print
216
217   int ret = -1;
218   while (ret)
219     {
220       ret = sem_wait(&_fullBufferSemaphore);
221       if (ret) perror(" LocalTraceBufferPool::retrieve, sem_wait");
222     }
223
224   // get the next buffer to print
225
226   unsigned long myRetrievePos = lockedIncrement(_retrievePos);
227
228   // copy the buffer from the pool to the provided buffer
229
230   memcpy((void*)&aTrace,
231          (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
232          sizeof(aTrace));
233
234   // increment the free buffer semaphore
235   // (if previously 0, awake one of the threads waiting to put a trace, if any)
236   // there is no way to preserve the order of waiting threads if several
237   // threads are waiting to put a trace: the waken up thread is not
238   // necessarily the first thread to wait.
239
240   ret = sem_post(&_freeBufferSemaphore);
241
242   // returns the number of full buffers
243
244   sem_getvalue(&_fullBufferSemaphore, &ret);
245   return ret;
246 }
247
248 // ============================================================================
249 /*!
250  *  Gives the number of buffers to print.
251  *  Usage : when the thread in charge of messages print id to be stopped,
252  *  check if there is still something to print, before stop.
253  *  There is no need of mutex here, provided there is only one thread to
254  *  retrieve and print the buffers.
255  */
256 // ============================================================================
257
258 unsigned long LocalTraceBufferPool::toCollect()
259 {
260   return _insertPos - _retrievePos;
261 }
262
263 // ============================================================================
264 /*!
265  * Constructor : initialize pool of buffers, semaphores and mutex.
266  */
267 // ============================================================================
268
269 LocalTraceBufferPool::LocalTraceBufferPool()
270 {
271   //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
272
273   _insertPos   = ULONG_MAX;  // first increment will give 0
274   _retrievePos = ULONG_MAX;
275   _position=0;               // first message will have number = 1
276
277   memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
278   for (int i=0; i<TRACE_BUFFER_SIZE; i++)
279     strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
280   int ret;
281   ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
282   if (ret!=0) IMMEDIATE_ABORT(ret);
283   ret=sem_init(&_fullBufferSemaphore, 0, 0);                 // 0 buffer full
284   if (ret!=0) IMMEDIATE_ABORT(ret);
285   ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
286   if (ret!=0) IMMEDIATE_ABORT(ret);
287
288   //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()-end" << endl;
289 }
290
291 // ============================================================================
292 /*!
293  * Destructor : release memory associated with semaphores and mutex
294  */
295 // ============================================================================
296
297 LocalTraceBufferPool::~LocalTraceBufferPool()
298 {
299   int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
300   if (_singleton)
301     {
302       DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()");
303       delete (_myThreadTrace);
304       _myThreadTrace = 0;
305       int ret;
306       ret=sem_destroy(&_freeBufferSemaphore);
307       ret=sem_destroy(&_fullBufferSemaphore);
308       ret=pthread_mutex_destroy(&_incrementMutex);
309       DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()-end");
310       _singleton = 0;
311     }
312   ret = pthread_mutex_unlock(&_singletonMutex); // release lock
313 }
314
315 // ============================================================================
316 /*!
317  * pool counters are incremented under a mutex protection
318  */
319 // ============================================================================
320
321 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
322 {
323   int ret;
324   ret = pthread_mutex_lock(&_incrementMutex);   // lock access to counters
325   unsigned long mypos = ++pos;
326   ret = pthread_mutex_unlock(&_incrementMutex); // release lock
327   return mypos;
328 }
329