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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
20 // Author : Paul RASCLE (EDF)
24 // Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
37 #include "LocalTraceBufferPool.hxx"
38 #include "BaseTraceCollector.hxx"
39 #include "LocalTraceCollector.hxx"
40 #include "FileTraceCollector.hxx"
41 #include "BasicsGenericDestructor.hxx"
42 #include "utilities.h"
46 // In case of truncated message, end of trace contains "...\n\0"
48 #define TRUNCATED_MESSAGE "...\n"
49 #define MAXMESS_LENGTH MAX_TRACE_LENGTH-5
51 // Class static attributes initialisation
53 LocalTraceBufferPool* LocalTraceBufferPool::_singleton = 0;
55 //pthread_mutex_t LocalTraceBufferPool::_singletonMutex;
57 pthread_mutex_t LocalTraceBufferPool::_singletonMutex =
58 PTHREAD_MUTEX_INITIALIZER;
60 BaseTraceCollector *LocalTraceBufferPool::_myThreadTrace = 0;
62 // ============================================================================
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
76 // ============================================================================
78 LocalTraceBufferPool* LocalTraceBufferPool::instance()
80 if (_singleton == 0) // no need of lock when singleton already exists
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();
89 DESTRUCTOR_OF<LocalTraceBufferPool> *ptrDestroy =
90 new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
91 _singleton = myInstance;
93 // --- start a trace Collector
95 char* traceKind = getenv("SALOME_trace");
97 //cerr<<"SALOME_trace="<<traceKind<<endl;
99 if (strcmp(traceKind,"local")==0)
101 _myThreadTrace = LocalTraceCollector::instance();
103 else if (strncmp(traceKind,"file",strlen("file"))==0)
106 if (strlen(traceKind) > strlen("file"))
107 fileName = &traceKind[strlen("file")+1];
109 fileName = "/tmp/tracetest.log";
111 _myThreadTrace = FileTraceCollector::instance(fileName);
113 else // --- try a dynamic library
117 string impl_name = string ("lib") + traceKind
118 + string("TraceCollector.so");
119 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
121 string impl_name = string ("lib") + traceKind + string(".dll");
122 handle = dlopen( impl_name.c_str() , 0 ) ;
126 typedef BaseTraceCollector * (*FACTORY_FUNCTION) (void);
127 FACTORY_FUNCTION TraceCollectorFactory =
128 (FACTORY_FUNCTION) dlsym(handle, "SingletonInstance");
130 if ( (error = dlerror() ) != NULL)
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
137 _myThreadTrace = (TraceCollectorFactory) ();
141 cerr << "library: " << impl_name << " not found !" << endl;
142 assert(handle); // to give file and line
143 exit(1); // in case assert is deactivated
146 DEVTRACE("New buffer pool: end");
148 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
153 // ============================================================================
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)
161 // ============================================================================
163 int LocalTraceBufferPool::insert(int traceType, const char* msg)
166 // get immediately a message number to control sequence (mutex protected)
168 unsigned long myMessageNumber = lockedIncrement(_position);
170 // wait until there is a free buffer in the pool
175 ret = sem_wait(&_freeBufferSemaphore);
176 if (ret) perror(" LocalTraceBufferPool::insert, sem_wait");
179 // get the next free buffer available (mutex protected)
181 unsigned long myInsertPos = lockedIncrement(_insertPos);
183 // fill the buffer with message, thread id and type (normal or abort)
185 strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
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;
193 // increment the full buffer semaphore
194 // (if previously 0, awake thread in charge of trace)
196 ret = sem_post(&_fullBufferSemaphore);
198 // returns the number of free buffers
200 sem_getvalue(&_freeBufferSemaphore, &ret);
204 // ============================================================================
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
210 // ============================================================================
212 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
215 // wait until there is a buffer in the pool, with a message to print
220 ret = sem_wait(&_fullBufferSemaphore);
221 if (ret) perror(" LocalTraceBufferPool::retrieve, sem_wait");
224 // get the next buffer to print
226 unsigned long myRetrievePos = lockedIncrement(_retrievePos);
228 // copy the buffer from the pool to the provided buffer
230 memcpy((void*)&aTrace,
231 (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
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.
240 ret = sem_post(&_freeBufferSemaphore);
242 // returns the number of full buffers
244 sem_getvalue(&_fullBufferSemaphore, &ret);
248 // ============================================================================
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.
256 // ============================================================================
258 unsigned long LocalTraceBufferPool::toCollect()
260 return _insertPos - _retrievePos;
263 // ============================================================================
265 * Constructor : initialize pool of buffers, semaphores and mutex.
267 // ============================================================================
269 LocalTraceBufferPool::LocalTraceBufferPool()
271 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
273 _insertPos = ULONG_MAX; // first increment will give 0
274 _retrievePos = ULONG_MAX;
275 _position=0; // first message will have number = 1
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);
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);
288 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()-end" << endl;
291 // ============================================================================
293 * Destructor : release memory associated with semaphores and mutex
295 // ============================================================================
297 LocalTraceBufferPool::~LocalTraceBufferPool()
299 int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
302 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()");
303 delete (_myThreadTrace);
306 ret=sem_destroy(&_freeBufferSemaphore);
307 ret=sem_destroy(&_fullBufferSemaphore);
308 ret=pthread_mutex_destroy(&_incrementMutex);
309 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()-end");
312 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
315 // ============================================================================
317 * pool counters are incremented under a mutex protection
319 // ============================================================================
321 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
324 ret = pthread_mutex_lock(&_incrementMutex); // lock access to counters
325 unsigned long mypos = ++pos;
326 ret = pthread_mutex_unlock(&_incrementMutex); // release lock