1 // Copyright (C) 2004 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // Author : Paul RASCLE (EDF)
24 // Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
38 #include "LocalTraceBufferPool.hxx"
39 #include "BaseTraceCollector.hxx"
40 #include "LocalTraceCollector.hxx"
41 #include "FileTraceCollector.hxx"
42 #include "BasicsGenericDestructor.hxx"
43 #include "utilities.h"
47 // In case of truncated message, end of trace contains "...\n\0"
49 #define TRUNCATED_MESSAGE "...\n"
50 #define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
52 // Class static attributes initialisation
54 LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
56 //pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
58 pthread_mutex_t LocalTraceBufferPool::_singletonMutex =
59 PTHREAD_MUTEX_INITIALIZER;
61 BaseTraceCollector *LocalTraceBufferPool::_myThreadTrace = 0;
63 // ============================================================================
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
77 // ============================================================================
79 LocalTraceBufferPool* LocalTraceBufferPool::instance()
81 if (_singleton == 0) // no need of lock when singleton already exists
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();
90 DESTRUCTOR_OF<LocalTraceBufferPool> *ptrDestroy =
91 new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
92 _singleton = myInstance;
94 // --- start a trace Collector
96 char* traceKind = getenv("SALOME_trace");
98 //cerr<<"SALOME_trace="<<traceKind<<endl;
100 if (strcmp(traceKind,"local")==0)
102 _myThreadTrace = LocalTraceCollector::instance();
104 else if (strncmp(traceKind,"file",strlen("file"))==0)
107 if (strlen(traceKind) > strlen("file"))
108 fileName = &traceKind[strlen("file")+1];
110 fileName = "/tmp/tracetest.log";
112 _myThreadTrace = FileTraceCollector::instance(fileName);
114 else // --- try a dynamic library
118 string impl_name = string ("lib") + traceKind
119 + string("TraceCollector.so");
120 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
123 string impl_name = string ("lib") + traceKind + string(".dll");
124 handle = LoadLibrary( impl_name.c_str() );
128 typedef BaseTraceCollector * (*FACTORY_FUNCTION) (void);
130 FACTORY_FUNCTION TraceCollectorFactory =
131 (FACTORY_FUNCTION) dlsym(handle, "SingletonInstance");
133 FACTORY_FUNCTION TraceCollectorFactory =
134 (FACTORY_FUNCTION)GetProcAddress(handle, "SingletonInstance");
136 if ( !TraceCollectorFactory )
138 cerr << "Can't resolve symbol: SingletonInstance" <<endl;
140 cerr << "dlerror: " << dlerror() << endl;
144 _myThreadTrace = (TraceCollectorFactory) ();
148 cerr << "library: " << impl_name << " not found !" << endl;
149 assert(handle); // to give file and line
150 exit(1); // in case assert is deactivated
153 DEVTRACE("New buffer pool: end");
155 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
160 // ============================================================================
162 * Called by trace producers within their threads. The trace message is copied
163 * in specific buffer from a circular pool of buffers.
164 * Waits until there is a free buffer in the pool, gets the first available
165 * buffer, fills it with the message.
166 * Messages are printed in a separate thread (see retrieve method)
168 // ============================================================================
170 int LocalTraceBufferPool::insert(int traceType, const char* msg)
173 // get immediately a message number to control sequence (mutex protected)
175 unsigned long myMessageNumber = lockedIncrement(_position);
177 // wait until there is a free buffer in the pool
182 ret = sem_wait(&_freeBufferSemaphore);
183 if (ret) perror(" LocalTraceBufferPool::insert, sem_wait");
186 // get the next free buffer available (mutex protected)
188 unsigned long myInsertPos = lockedIncrement(_insertPos);
190 // fill the buffer with message, thread id and type (normal or abort)
192 strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
194 MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
195 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
196 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
197 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
200 // increment the full buffer semaphore
201 // (if previously 0, awake thread in charge of trace)
203 ret = sem_post(&_fullBufferSemaphore);
205 // returns the number of free buffers
207 sem_getvalue(&_freeBufferSemaphore, &ret);
211 // ============================================================================
213 * Called by the thread in charge of printing trace messages.
214 * Waits until there is a buffer with a message to print.
215 * Gets the first buffer to print, copies it int the provided buffer
217 // ============================================================================
219 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
222 // wait until there is a buffer in the pool, with a message to print
227 ret = sem_wait(&_fullBufferSemaphore);
228 if (ret) perror(" LocalTraceBufferPool::retrieve, sem_wait");
231 // get the next buffer to print
233 unsigned long myRetrievePos = lockedIncrement(_retrievePos);
235 // copy the buffer from the pool to the provided buffer
237 memcpy((void*)&aTrace,
238 (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
241 // increment the free buffer semaphore
242 // (if previously 0, awake one of the threads waiting to put a trace, if any)
243 // there is no way to preserve the order of waiting threads if several
244 // threads are waiting to put a trace: the waken up thread is not
245 // necessarily the first thread to wait.
247 ret = sem_post(&_freeBufferSemaphore);
249 // returns the number of full buffers
251 sem_getvalue(&_fullBufferSemaphore, &ret);
255 // ============================================================================
257 * Gives the number of buffers to print.
258 * Usage : when the thread in charge of messages print id to be stopped,
259 * check if there is still something to print, before stop.
260 * There is no need of mutex here, provided there is only one thread to
261 * retrieve and print the buffers.
263 // ============================================================================
265 unsigned long LocalTraceBufferPool::toCollect()
267 return _insertPos - _retrievePos;
270 // ============================================================================
272 * Constructor : initialize pool of buffers, semaphores and mutex.
274 // ============================================================================
276 LocalTraceBufferPool::LocalTraceBufferPool()
278 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
280 _insertPos = ULONG_MAX; // first increment will give 0
281 _retrievePos = ULONG_MAX;
282 _position=0; // first message will have number = 1
284 memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
285 for (int i=0; i<TRACE_BUFFER_SIZE; i++)
286 strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
288 ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
289 if (ret!=0) IMMEDIATE_ABORT(ret);
290 ret=sem_init(&_fullBufferSemaphore, 0, 0); // 0 buffer full
291 if (ret!=0) IMMEDIATE_ABORT(ret);
292 ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
293 if (ret!=0) IMMEDIATE_ABORT(ret);
295 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()-end" << endl;
298 // ============================================================================
300 * Destructor : release memory associated with semaphores and mutex
302 // ============================================================================
304 LocalTraceBufferPool::~LocalTraceBufferPool()
306 int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
309 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()");
310 delete (_myThreadTrace);
313 ret=sem_destroy(&_freeBufferSemaphore);
314 ret=sem_destroy(&_fullBufferSemaphore);
315 ret=pthread_mutex_destroy(&_incrementMutex);
316 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()-end");
319 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
322 // ============================================================================
324 * pool counters are incremented under a mutex protection
326 // ============================================================================
328 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
331 ret = pthread_mutex_lock(&_incrementMutex); // lock access to counters
332 unsigned long mypos = ++pos;
333 ret = pthread_mutex_unlock(&_incrementMutex); // release lock