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