1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // Author : Paul RASCLE (EDF)
26 // Cf. C++ Users Journal, June 2004, Tracing Application Execution, Tomer Abramson
41 #include "LocalTraceBufferPool.hxx"
42 #include "BaseTraceCollector.hxx"
43 #include "LocalTraceCollector.hxx"
44 #include "FileTraceCollector.hxx"
45 #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 new DESTRUCTOR_OF<LocalTraceBufferPool> (*myInstance);
91 _singleton = myInstance;
93 // --- start a trace Collector
95 char* traceKind = getenv("SALOME_trace");
97 if ( !traceKind || strcmp(traceKind,"local")==0 ) // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
99 _myThreadTrace = LocalTraceCollector::instance();
101 else if (strncmp(traceKind,"file",strlen("file"))==0)
103 const char *fileName;
104 if (strlen(traceKind) > strlen("file"))
105 fileName = &traceKind[strlen("file")+1];
107 fileName = "/tmp/tracetest.log";
109 _myThreadTrace = FileTraceCollector::instance(fileName);
111 else // --- try a dynamic library
115 std::string impl_name = std::string ("lib") + traceKind
116 + std::string("TraceCollector.so");
117 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
120 std::string impl_name = std::string ("lib") + traceKind + std::string(".dll");
121 handle = LoadLibrary( impl_name.c_str() );
125 typedef BaseTraceCollector * (*FACTORY_FUNCTION) (void);
127 FACTORY_FUNCTION TraceCollectorFactory =
128 (FACTORY_FUNCTION) dlsym(handle, "SingletonInstance");
130 FACTORY_FUNCTION TraceCollectorFactory =
131 (FACTORY_FUNCTION)GetProcAddress(handle, "SingletonInstance");
133 if ( !TraceCollectorFactory )
135 std::cerr << "Can't resolve symbol: SingletonInstance" <<std::endl;
137 std::cerr << "dlerror: " << dlerror() << std::endl;
141 _myThreadTrace = (TraceCollectorFactory) ();
145 std::cerr << "library: " << impl_name << " not found !" << std::endl;
146 assert(handle); // to give file and line
147 exit(1); // in case assert is deactivated
150 DEVTRACE("New buffer pool: end");
152 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
157 // ============================================================================
159 * Called by trace producers within their threads. The trace message is copied
160 * in specific buffer from a circular pool of buffers.
161 * Waits until there is a free buffer in the pool, gets the first available
162 * buffer, fills it with the message.
163 * Messages are printed in a separate thread (see retrieve method)
165 // ============================================================================
167 int LocalTraceBufferPool::insert(int traceType, const char* msg)
170 // get immediately a message number to control sequence (mutex protected)
172 unsigned long myMessageNumber = lockedIncrement(_position);
174 // wait until there is a free buffer in the pool
179 ret = sem_wait(&_freeBufferSemaphore);
180 if (ret) perror(" LocalTraceBufferPool::insert, sem_wait");
183 // get the next free buffer available (mutex protected)
185 unsigned long myInsertPos = lockedIncrement(_insertPos);
187 // fill the buffer with message, thread id and type (normal or abort)
189 strncpy(_myBuffer[myInsertPos%TRACE_BUFFER_SIZE].trace,
191 MAXMESS_LENGTH); // last chars always "...\n\0" if msg too long
192 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].threadId =pthread_self();//thread id
193 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].traceType = traceType;
194 _myBuffer[myInsertPos%TRACE_BUFFER_SIZE].position = myMessageNumber;
197 // increment the full buffer semaphore
198 // (if previously 0, awake thread in charge of trace)
200 ret = sem_post(&_fullBufferSemaphore);
202 // returns the number of free buffers
204 sem_getvalue(&_freeBufferSemaphore, &ret);
208 // ============================================================================
210 * Called by the thread in charge of printing trace messages.
211 * Waits until there is a buffer with a message to print.
212 * Gets the first buffer to print, copies it int the provided buffer
214 // ============================================================================
216 int LocalTraceBufferPool::retrieve(LocalTrace_TraceInfo& aTrace)
219 // wait until there is a buffer in the pool, with a message to print
224 ret = sem_wait(&_fullBufferSemaphore);
225 if (ret) MESSAGE (" LocalTraceBufferPool::retrieve, sem_wait");
228 // get the next buffer to print
230 unsigned long myRetrievePos = lockedIncrement(_retrievePos);
232 // copy the buffer from the pool to the provided buffer
234 memcpy((void*)&aTrace,
235 (void*)&_myBuffer[myRetrievePos%TRACE_BUFFER_SIZE],
238 // increment the free buffer semaphore
239 // (if previously 0, awake one of the threads waiting to put a trace, if any)
240 // there is no way to preserve the order of waiting threads if several
241 // threads are waiting to put a trace: the waken up thread is not
242 // necessarily the first thread to wait.
244 ret = sem_post(&_freeBufferSemaphore);
246 // returns the number of full buffers
248 sem_getvalue(&_fullBufferSemaphore, &ret);
252 // ============================================================================
254 * Gives the number of buffers to print.
255 * Usage : when the thread in charge of messages print id to be stopped,
256 * check if there is still something to print, before stop.
257 * There is no need of mutex here, provided there is only one thread to
258 * retrieve and print the buffers.
260 // ============================================================================
262 unsigned long LocalTraceBufferPool::toCollect()
264 return _insertPos - _retrievePos;
267 // ============================================================================
269 * Constructor : initialize pool of buffers, semaphores and mutex.
271 // ============================================================================
273 LocalTraceBufferPool::LocalTraceBufferPool()
275 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()" << endl;
277 _insertPos = ULONG_MAX; // first increment will give 0
278 _retrievePos = ULONG_MAX;
279 _position=0; // first message will have number = 1
281 memset(_myBuffer, 0, sizeof(_myBuffer)); // to guarantee end of strings = 0
282 for (int i=0; i<TRACE_BUFFER_SIZE; i++)
283 strcpy(&(_myBuffer[i].trace[MAXMESS_LENGTH]),TRUNCATED_MESSAGE);
285 ret=sem_init(&_freeBufferSemaphore, 0, TRACE_BUFFER_SIZE); // all buffer free
286 if (ret!=0) IMMEDIATE_ABORT(ret);
287 ret=sem_init(&_fullBufferSemaphore, 0, 0); // 0 buffer full
288 if (ret!=0) IMMEDIATE_ABORT(ret);
289 ret=pthread_mutex_init(&_incrementMutex,NULL); // default = fast mutex
290 if (ret!=0) IMMEDIATE_ABORT(ret);
292 //cerr << "LocalTraceBufferPool::LocalTraceBufferPool()-end" << endl;
295 // ============================================================================
297 * Destructor : release memory associated with semaphores and mutex
299 // ============================================================================
301 LocalTraceBufferPool::~LocalTraceBufferPool()
303 int ret = pthread_mutex_lock(&_singletonMutex); // acquire lock to be alone
306 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()");
307 delete (_myThreadTrace);
310 ret=sem_destroy(&_freeBufferSemaphore);
311 ret=sem_destroy(&_fullBufferSemaphore);
312 ret=pthread_mutex_destroy(&_incrementMutex);
313 DEVTRACE("LocalTraceBufferPool::~LocalTraceBufferPool()-end");
316 ret = pthread_mutex_unlock(&_singletonMutex); // release lock
319 // ============================================================================
321 * pool counters are incremented under a mutex protection
323 // ============================================================================
325 unsigned long LocalTraceBufferPool::lockedIncrement(unsigned long& pos)
328 ret = pthread_mutex_lock(&_incrementMutex); // lock access to counters
329 unsigned long mypos = ++pos;
330 ret = pthread_mutex_unlock(&_incrementMutex); // release lock