File: StartProcessThread.cpp

package info (click to toggle)
tango 7.2.6%2Bdfsg-14
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 20,720 kB
  • sloc: cpp: 122,899; sh: 11,304; ansic: 1,079; makefile: 843; java: 215; python: 55
file content (605 lines) | stat: -rwxr-xr-x 16,660 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
static const char *RcsId = "$Header$";
//+=============================================================================
//
// file :         StartProcessThread.cpp
//
// description :  C++ source for the Starter start process thread.
//
// project :      TANGO Device Server
//
// $Author: pascal_verdier $
//
// Copyright (C) :      2004,2005,2006,2007,2008,2009,2010
//						European Synchrotron Radiation Facility
//                      BP 220, Grenoble 38043
//                      FRANCE
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Tango is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Tango.  If not, see <http://www.gnu.org/licenses/>.
//
// $Revision: 15451 $
//
// $Log$
// Revision 3.23  2010/10/18 12:58:52  pascal_verdier
// Pogo-7 compatibility
//
// Revision 3.22  2010/10/15 06:20:33  pascal_verdier
// Copyright added.
//
// Revision 3.21  2010/10/08 08:48:50  pascal_verdier
// Include files order changed.
//
// Revision 3.20  2010/09/21 12:18:58  pascal_verdier
// GPL Licence added to header.
//
// Revision 3.19  2010/02/09 15:09:49  pascal_verdier
// Define  _TG_WINDOWS_  replace WIN32.
// LogFileHome property added.
//
// Revision 3.18  2010/02/09 10:25:38  pascal_verdier
// __MACOS__ compiler flag added.
//
// Revision 3.17  2008/12/12 13:29:56  pascal_verdier
// Log in file start and stop for servers and itself.
//
// Revision 3.16  2008/09/23 14:19:40  pascal_verdier
// Log files history added.
//
// Revision 3.15  2008/04/04 14:30:51  jensmeyer
// Added compile option for FreeBSD and MacOSX.
// They have a different signal handling.
//
// Revision 3.14  2008/02/29 15:15:05  pascal_verdier
// Checking running processes by system call added.
//
// Revision 3.13  2007/09/28 06:12:30  pascal_verdier
// Remove traces
//
// Revision 3.12  2007/09/27 15:11:15  pascal_verdier
// GetLastError() management added on Win 32
//
// Revision 3.11  2007/09/25 13:06:17  pascal_verdier
// In win32 char* replaced by LPWSTR :-)
//
// Revision 3.10  2007/06/20 06:48:21  pascal_verdier
// delete replaced by  delete[].
//
// Revision 3.9  2007/03/23 09:23:44  pascal_verdier
// Bug in windows batch file startup fixed.
//
// Revision 3.8  2007/02/01 09:17:44  pascal_verdier
// Monitor added on some shared data.
// Wait 3 seconds added at startup for first ping timeout.
//
// Revision 3.7  2006/11/20 06:58:37  pascal_verdier
// Mutex on start process data added.
//
// Revision 3.6  2006/11/10 14:53:28  pascal_verdier
// Remove vc8 warnings.
//
// Revision 3.5  2006/06/13 19:38:15  pascal_verdier
// Minor changes.
//
// Revision 3.4  2006/06/06 12:01:26  pascal_verdier
// Bug in log file fixed.
//
// Revision 3.3  2006/06/05 07:20:36  pascal_verdier
// Server startup is now delayed (with timeout) in a startup level.
// New state MOVING added.
// At startup, starter loop until properties have been read.
//
// Revision 3.2  2006/04/24 08:58:10  pascal_verdier
// *** empty log message ***
//
// Revision 3.1  2006/04/24 07:06:27  pascal_verdier
// A thread is started for each level when at servers startup.
//
//+=============================================================================


#include <tango.h>


#ifdef _TG_WINDOWS_
#	include <process.h>
#	include <direct.h>
#	include <io.h>
#else
#	include <sys/wait.h>
#	include <sys/time.h>
#endif

#include <fcntl.h>

#include <Starter.h>

namespace Starter_ns
{
//+------------------------------------------------------------------
/**
 * Thread constructor
 */
//+------------------------------------------------------------------
StartProcessThread::StartProcessThread(vector<NewProcess *> v_np, int level, Starter *st)
{
	for (unsigned int i=0 ; i<v_np.size() ; i++)
		processes.push_back(v_np[i]);
	thread_level = level;
	starter      = st;

}
//+------------------------------------------------------------------
/**
 * Execute the fork of the sub process in a thread.
 */
//+------------------------------------------------------------------
void *StartProcessThread::run_undetached(void *ptr)
{
	unsigned int	i;
	CheckProcessUtil	*process_util = starter->util->proc_util;
	//	Check if a previous level thread is terminated
	if (thread_level>1)
	{
		while (starter->start_proc_data->get_current_level()!=thread_level)
		{
			//cout << "	level " << thread_level <<
			//	"	wait for end for level " << starter->start_proc_data->get_current_level() << endl;
			ms_sleep(500);
		}
	}
	
	//	Start the level process start loop
	for (i=0 ; i<processes.size() ; i++)
	{
		//cout << "Starting " <<
		//	processes[i]->servname << "/" << processes[i]->instancename << endl;

		start_process(processes[i]);

		//	Build server name from admin name
		char	*p = processes[i]->adminname + strlen("dserver/");
		string	servname(p);
		bool	failed = false;

		//	Sleep a bit between startups			 		
		//	to do not overload database
		bool	started = false;
		time_t	t0 = time(NULL);
		time_t	t1 = t0;
		Tango::DeviceProxy	*serv;
		while (failed==false && started==false && (t1-t0)<starter->serverStartupTimeout)
		{
#		ifdef _TG_WINDOWS_
			_sleep(1000);
#		else
			sleep(1);
#		endif


			//	do not test before 4 seconds to be sure
			//	process list has been updated.
			t1 = time(NULL);
			if ((t1-t0)>=4)
			{
				//	Check if server running or failed
				if (process_util->is_server_running(servname)==false)
					failed = true;
				else
				{
					//	if  not failed check if startup is terminated
					serv = NULL;
					try
					{
						serv = new Tango::DeviceProxy(processes[i]->adminname);
						serv->ping();
						started = true;
					}
					catch(Tango::DevFailed &)
					{
						//cout << e.errors[0].desc << endl;
					}
					if (serv!=NULL)
						delete serv;
					t1 = time(NULL);
				}
			}
		}
		if (started)
		{
			TangoSys_OMemStream out_stream;
			out_stream << servname << " started";
			starter->util->log_starter_info(out_stream.str());

			cout << "----- " << servname << " started in " << (t1-t0) << " sec." << endl;
		}
		else
		if (failed)
			cout << "----- " << servname << " failed in " << (t1-t0) << " sec." << endl;
		else
			cout << "----- " << servname << " Timeout = " << (t1-t0) << endl;

		ms_sleep(TIME_BETWEEN_STARTUPS);
	}

	//	Check if a time to wait between two startup levels in seconds as been set
	//	Except for level 0 which is a single startup
	if (thread_level>0 && starter->interStartupLevelWait>0)
	{
		//cout << "Thread level " << thread_level <<
		//	" wait for " << starter->interStartupLevelWait;
		ms_sleep(starter->interStartupLevelWait*1000);
	}

	//	Free the process structure field
	for (i=0 ; i<processes.size() ; i++)
	{
		free(processes[i]->servname);
		free(processes[i]->instancename);
		delete [] processes[i]->adminname;
		delete [] processes[i]->logfile;
	}

//	starter->starting_processes--;
	//	remove in level vector to start another level
	starter->start_proc_data->remove_current_level();
	return NULL;
}
#ifndef	_TG_WINDOWS_
//+------------------------------------------------------------------
/**
 *	Start one process
 */
//+------------------------------------------------------------------
void StartProcessThread::start_process(NewProcess *process)
{
	char	*argv[4];
	int		i = 0;
	argv[i++] = process->servname;
	argv[i++] = process->instancename;
	//argv[i++] = "-v5";
	argv[i++] = NULL;

	//	Fork a child process to start the device server
	int	fork_id = fork();
	switch(fork_id)
	{
	case -1:
		cerr << "Fork Failed !" << endl;
		break;
	case 0:
		switch(fork())
		{
		case -1:
			cerr << "Fork Failed !" << endl;
			break;
		case 0:
			{
				// Change process group and close control tty
#if defined(__darwin__) || defined( __MACOS__)

				setpgrp();

#elif defined (__freebsd__)

				setpgrp(0,setsid());

#else										
				setpgrp();

				//	Call setsid() to do NOT stop children if Starter is killed.
				//--------------------------------------------------------------
				setsid();
#endif

				//	Close the stderr and re-open it on a log file.
				//-------------------------------------------------
				close(2);
				starter->util->manage_log_file_history(
						process->logfile, starter->keepLogFiles);
				//remove(process->logfile);
				open(process->logfile, O_RDWR | O_CREAT, 0664);

				//	Start the execution of the device server
				//---------------------------------------------
				if (execvp(argv[0], argv)<0)
				{
					ofstream	of(process->logfile);
					of << "Exec(" << argv[0] << ") failed " << endl;
					of << strerror(errno) << endl;
					of.close();
				}
				_exit(0);
			}
			break;
		default:
			cout << fork_id << " exit()" << endl;
			_exit(0);
			break;
		}
		break;

	default:
		int		res_wait;
		wait(&res_wait);
		break;
	}
}


#else	//	_TG_WINDOWS_


//+----------------------------------------------------------
//	WIN 32 methods to fork a sub process
//+----------------------------------------------------------
void StartProcessThread::start_process(NewProcess *process)
{
	/*****
	On Win32 problem with permission denied !
	It seems that this not necessary because there is nothing in file.
	
	starter->util->manage_log_file_history(
			process->logfile, starter->keepLogFiles);
	*/
	StartWinThread	*win_thread = new StartWinThread(process, starter);
	win_thread->start();
}

//+------------------------------------------------------------------
/**
 *	Set the path between cotes for windows.
 *
 *      @param  servname	server name
 */
//+------------------------------------------------------------------
string StartWinThread::get_server_name_with_cotes(string servname)
{
	string::size_type	pos = servname.find_last_of("/\\");
	if (pos!=string::npos)
	{
		string	str("\"");
		str += servname.substr(0, pos);
		str += "\"";
		str += servname.substr(pos);
		
		return str;
		
		/*
		string	str("\"");
		str += servname;
		str += "\"";

		string	str("c:\\\"Program Files\"\\Tango\\notify_daemon.bat");
		return str;
		*/
	}
	else
		return servname;
}
//+----------------------------------------------------------
//	WIN 32 Thread to fork a sub process
//		If batch file, the spawnv is blocking !!!
//+----------------------------------------------------------
void *StartWinThread::run_undetached(void *ptr)
{
	//	Check if batch file
	string	str_server(process->servname);
	string	str_with_cotes = get_server_name_with_cotes(process->servname);
	char	*servname = new char[str_with_cotes.length()+1];
	strcpy(servname, str_with_cotes.c_str());
	
	string cmd(servname);
	cmd += "  ";
	cmd += process->instancename;
	cout << "system(" << cmd << ");" << endl;
	system(cmd.c_str());
	return NULL;

	if (str_server.find(".bat") != string::npos)
	{
		char	*argv[3];
		int		i = 0;

		argv[i++] = servname;
		argv[i++] = process->instancename;
		argv[i++] = NULL;

		cout << "Forking "   << servname << endl;
		cout << "log file: " << process->logfile << endl;

		//	Write a starting message in log file
		ofstream	ofs(process->logfile);
		ofs << "Starting " << argv[0] << "....." << endl << endl;
		ofs.close();

		//	Close the stderr and re-open it on a log file.
		//-------------------------------------------------
		int	ret;
		if ((ret=_spawnv(_P_WAIT, argv[0], argv))<0)
		{
			//	Write error in log file
			//-------------------------------
			ofstream	ofs1(process->logfile);
			ofs1 << "Exec(" << argv[0] << ") failed " << endl;
			ofs1 << "_spawnv has returned " << ret << endl;
			DWORD	errcode = GetLastError();
		    LPTSTR	lp_err;
			if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
								FORMAT_MESSAGE_FROM_SYSTEM     |
								FORMAT_MESSAGE_ARGUMENT_ARRAY,
							NULL,
							errcode,
							LANG_NEUTRAL,
							(LPTSTR)&lp_err,
							0,
							NULL))
			{
				char	str[0x80];
				char	*p = str;
				for (int i=0 ; lp_err[i]!=0 ; i++)
					*p++ = lp_err[i];
				*p = '\0';
				ofs1 << str << " errcode = " << errcode << endl;
				cout << "===============================================" << endl
					 << servname << "  " << process->instancename<< endl
					 << str << " errcode = " << errcode                   << endl
					 << "===============================================" << endl;
				::LocalFree(lp_err);
			}
			ofs1.close();
		}
		else
		{
			Sleep(5000);
			cout << "Fork Succeed." << endl;
		}
	}
	else
	{
		PROCESS_INFORMATION pi;
		STARTUPINFO si;

		string	cmd_line(servname);
		cmd_line += " ";
		cmd_line += process->instancename;

		//
		// Get handles for standard output and errors
		//
		SECURITY_ATTRIBUTES sa;
		sa.bInheritHandle = 1;
		sa.nLength = sizeof(sa);
		sa.lpSecurityDescriptor = NULL;

		int buffSize = (int)strlen(process->logfile) + 1;
		LPWSTR lpw_logfile = new wchar_t[buffSize];
		MultiByteToWideChar(CP_ACP, 0, process->logfile, buffSize, lpw_logfile, buffSize);

		HANDLE hStdError  = CreateFile( lpw_logfile, 
			GENERIC_WRITE,
			FILE_SHARE_WRITE | FILE_SHARE_READ, 
			&sa, //lpSecurityAttributes 
			CREATE_ALWAYS, 
			FILE_ATTRIBUTE_NORMAL,
			0);
		if (hStdError == INVALID_HANDLE_VALUE)
			cout << "ERROR INVALID_HANDLE_VALUE " << strerror(GetLastError()) << endl;

		//	Prepare Startup info
		memset( &si, 0, sizeof(si) );
		si.cb = sizeof(si);
		si.dwFlags     = STARTF_USESHOWWINDOW;
		si.wShowWindow = SW_HIDE;

		buffSize = (int)strlen(cmd_line.c_str()) + 1;
		LPWSTR lpw_cmd = new wchar_t[buffSize];
		MultiByteToWideChar(CP_ACP, 0, cmd_line.c_str(), buffSize, lpw_cmd, buffSize);

		ofstream	ofs(process->logfile);
		ofs << "Creating process " << cmd_line << endl;
		if(CreateProcess(
				NULL ,            // pointer to name of executable module
				lpw_cmd,          // pointer to command line string
				&sa,              // process security attributes
				&sa,              // thread security attributes
				TRUE,             // handle inheritance flag
				DETACHED_PROCESS, // creation flags
				NULL,             // pointer to new environment block
				NULL,             // pointer to current directory name
				&si,              // pointer to STARTUPINFO
				&pi               // pointer to PROCESS_INFORMATION
				)==0)
		{
			_sleep(2000);
			cerr << "Error when trying to create process " << cmd_line << endl;

			//	Write a starting message in log file
			ofstream	ofs1(process->logfile);
			ofs << "Error when trying to create process " << cmd_line <<endl;
			DWORD	errcode = GetLastError();
		    LPTSTR lp_err;
			if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
							NULL,
							errcode,
							LANG_NEUTRAL,
							(LPTSTR)&lp_err,
							0,
							NULL))
			{
				char	str[0x80];
				char	*p = str;
				for (int i=0 ; lp_err[i]!=0 ; i++)
					*p++ = lp_err[i];
				*p = '\0';
				ofs << str << " errcode = " << errcode << endl;
				::LocalFree(lp_err);
			}
		}
		else
		{
			ofs << ".......OK (" << cmd_line << ")" << endl;
		}
		delete lpw_cmd;
		delete lpw_logfile;
		ofs.close();
	}
	delete[] servname;
	return NULL;
}

#endif	//	_TG_WINDOWS_

//+------------------------------------------------------------------
//+------------------------------------------------------------------
int StartProcessShared::get_starting_processes()
{
	omni_mutex_lock sync(*this);
	return starting_processes;
}
//+------------------------------------------------------------------
/**
 *	StartProcessShared::push_back_level(int level)
 */
//+------------------------------------------------------------------
void StartProcessShared::push_back_level(int level)
{
	omni_mutex_lock sync(*this);
	start_process_thread_levels.push_back(level);
	starting_processes++;
}
//+------------------------------------------------------------------
/**
 *	StartProcessShared::get_current_level()
 */
//+------------------------------------------------------------------
int StartProcessShared::get_current_level()
{
	omni_mutex_lock sync(*this);
	return start_process_thread_levels[0];
}
//+------------------------------------------------------------------
/**
 *	StartProcessShared::remove_current_level()
 */
//+------------------------------------------------------------------
void StartProcessShared::remove_current_level()
{
	omni_mutex_lock sync(*this);
	vector<int>::iterator it = start_process_thread_levels.begin();
	start_process_thread_levels.erase(it);
	starting_processes--;
}

};	//	namespace