summaryrefslogtreecommitdiffstats
path: root/rasmgr/rasmgr_localsrv.cc
blob: 211f03e6493488a7f415c0d2907271195c8f6853 (plain)
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
/*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdaman community 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 rasdaman community.  If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003, 2004, 2005, 2006, 2007, 2008, 2009 Peter Baumann /
rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <baumann@rasdaman.com>.
/
/**
 * SOURCE: rasmgr_localsrv.cc
 *
 * MODULE: rasmgr
 * CLASS:  LocalServer, LocalServerManager
 *
 * PURPOSE:
 *   management of rasserver executables
 *    
 * COMMENTS:
 *  		None
 *
*/

using namespace std;

#include "rasmgr_localsrv.hh"
#include "rasmgr_master.hh"
#include "rasmgr_srv.hh"
#include <signal.h>
#include <time.h>

#include <linux/limits.h>	// ARG_MAX
// fix for missing ARG_MAX; workaround for glibc-2.8 and above
#if defined(_SC_ARG_MAX)
# if defined(ARG_MAX)
#    undef ARG_MAX
# endif
# define ARG_MAX sysconf (_SC_ARG_MAX)
#endif

#include "raslib/rminit.hh"

#include "debug.hh"


// aux function for now() to avoid a compiler warning (see 'man strftime')
size_t my_strftime(char *s, size_t max, const char *fmt, const struct tm *tm)
{
        return strftime(s, max, fmt, tm);
}

// now(): aux function returning, as a static string, the current time
// keep in sync with same function in rasserver
const char* now()
{
        size_t strfResult = 0;          // return value of strftime()
        static char timestring[50];     // must hold 20+1 chars

        time_t t = time(NULL);          // get time
        struct tm* tm = localtime(&t);  // break down time
        strfResult = my_strftime( timestring, sizeof(timestring), "[%F %T]", tm );      // format time
        if (strfResult == 0)            // bad luck? then take fallback message
                (void) strncpy( timestring, "[-no time available-]", sizeof(timestring) );
        return( timestring );
}

LocalServer::LocalServer()
  { serverName[0]=0;
    valid=false;
    serverPid=0;
   }
   
void LocalServer::init(const char *name,pid_t p)
  { strcpy(serverName,name);    
    serverPid=p;
    valid=true;
   }	  
const char* LocalServer::getName()
  { return serverName;
   }
      
pid_t LocalServer::getPID()
  { return serverPid;
   }
bool LocalServer::isValid()
  { return valid;
   }

//#######################################
void catch_SIGCHLD(int)
  { localServerManager.childSignalIn();
   }
//#######################################

LocalServerManager::LocalServerManager()
  { wasSignal=false;
    
    signal (SIGCHLD, catch_SIGCHLD);
   }
LocalServerManager::~LocalServerManager()
  {
   }
bool LocalServerManager::startNewServer(const char* commandline)
  {
    ENTER( "LocalServerManager::startNewServer: enter. cmdLine=" << commandline );
    char localcomm[ARG_MAX];

    if (strlen(commandline) >= ARG_MAX)
    {
        VLOG <<"Error: rasserver launch command line too long: " << commandline <<std::endl; 
        LEAVE( "LocalServerManager::startNewServer: leave. cmd line too long, result=false." );
	return false;
    }

    strcpy(localcomm,commandline);
    
    int i;
    const int maxarg=50;
    char* argv[maxarg]; 	// rasserver command line
    char* fileName; 		// name of executable, e.g., "rasserver"
    char* serverName;		// symbolic server name, e.g., "S1"
    
    char *pos=localcomm;
    
    for(i=0;i<maxarg;i++)
      { 
#define WHITESPACE " \t\r\n"
        argv[i]=strtok(pos, WHITESPACE );
	pos=NULL; // for subsequent calls to strtok
	if(argv[i]==NULL) break;
       }   
    argv[maxarg-1]=0; // for security reasons
    
    serverName=argv[0];
    fileName  =argv[1];
    
    LocalServer &lcs=operator[](serverName);
    if(lcs.isValid()) 
      { VLOG <<"Server "<<serverName<<" is already up."<<std::endl; 
        LEAVE( "LocalServerManager::startNewServer: leave. srv already up, result=false." );
	return false;
	}
        
   // return false;
    pid_t pid=fork();
    
    if(pid!=0)
      { //parent
        LocalServer temp;
        temp.init(serverName,pid);
	srvList.push_back(temp);
        TALK( "LocalServerManager::startNewServer: leave. parent process. result=true." );
	VLOG << now() << " starting server "<<serverName<<", executable " << fileName << "; pid "<<pid<< "..." << flush;
	
       }
    else
      { //child
        
        TALK( "LocalServerManager::startNewServer: leave. child process, fileName=" << fileName );

	masterCommunicator.closeForcedAllSockets();
    
        execvp(fileName, argv+2);
        int execErrno = errno;
        std::cout<<"Error: cannot fork server "<<fileName<< ": " << strerror (execErrno) << std::endl;
        TALK( "LocalServerManager::startNewServer: cannot fork server "<<fileName<< ": " << strerror (execErrno) );
        exit(1); // if return from exec...
       }
    
    LEAVE( "LocalServerManager::startNewServer: leave. result=true." );
    return true;   
   }
int  LocalServerManager::countStartedServers()
  { return srvList.size();
   }

// sendTerminateSignal: terminate server process.
// if name is in list of known servers, try to terminate; otherwise, complain & do nothing.
// returns:
//	true	iff server was found and killed successfully 
//	false	on error
bool LocalServerManager::sendTerminateSignal(const char *serverName)
{    
	ENTER( "LocalServerManager::sendTerminateSignal: enter. serverName=" << serverName );

	bool found = false;	// list entry pertaining to serverName found?
	bool result = false;	// function result

	list<LocalServer>::iterator iter=srvList.begin();
	for ( int i=0; i<srvList.size() && ! found; i++) 
	{
		if(strcmp(iter->getName(),serverName)==0)
		{
			found = true;
			VLOG <<  now() << " shutting down rasdaman server " << iter->getName() << ", pid " << iter->getPID() << "..." << flush;
			int killResult = kill(iter->getPID(),SIGTERM);
			if (killResult == -1)
			{
				cout << "Error: " << strerror(errno) << endl;
				result = false;
			}
			else
			{
				iter = srvList.erase(iter);
				VLOG << "ok" << endl;
				result = true;
				break;
			}
		} 
	
		iter++;
	} // for

	if (!found)
	{
		cout << "failed: server unknown." << endl;
		result = false;
	}

	LEAVE( "LocalServerManager::sendTerminateSignal: leave. result=" << result );
	return result;
}
   
// killServer: terminate server process.
// if name is in list of known servers, try to kill; otherwise, complain & do nothing.
// returns:
//	true	iff server was found and killed successfully 
//	false	on error
bool LocalServerManager::killServer(const char *serverName)
{
	ENTER( "LocalServerManager::killServer: enter. serverName=" << serverName );

	bool found = false;	// list entry pertaining to serverName found?
	bool result = false;	// function result

	list<LocalServer>::iterator iter=srvList.begin();
	for(int i=0;i<srvList.size();i++) 
	{
		if(strcmp(iter->getName(),serverName)==0)
		{
			found = true;
			VLOG <<  now() << " killing rasdaman server " << iter->getName() << ", pid " << iter->getPID() << "..." << flush;

			int killResult = kill(iter->getPID(),SIGKILL);
			if (killResult == -1)
			{
				cout << "Error: " << strerror(errno) << endl;
				result = false;
			}
			else
			{
				iter = srvList.erase(iter);
				VLOG << "ok" << endl;
				result = true;
				break;
			}
 	 	} 
		iter++;
	}

	if (!found)
	{
		cout << "failed: server unknown." << endl;
		result = false;
	}

	LEAVE( "LocalServerManager::killServer: leave. result=" << result );
	return result;
}
      
LocalServer& LocalServerManager::operator[](int x)
  { list<LocalServer>::iterator iter=srvList.begin();
    for(int i=0;i<x;i++) iter++;
    return *iter;
 
   }
LocalServer& LocalServerManager::operator[](const char* srvName)
  {
    ENTER( "LocalServerManager::operator[]: enter. srvName=" << srvName );
    list<LocalServer>::iterator iter=srvList.begin();
    for(int i=0;i<srvList.size();i++) 
      {
       if(strcmp(iter->getName(),srvName)==0)
         {
           LEAVE( "LocalServerManager::operator[]: leave. valid=" << (*iter).isValid() );
           return *iter; 
         }
       iter++;
       }
    LEAVE( "LocalServerManager::operator[]: leave. valid=" << protElem.isValid() );
    return protElem; 
   } 
      
void LocalServerManager::childSignalIn() //only signal calls this
  { wasSignal=true;
   }
void LocalServerManager::cleanChild()
  {
    ENTER( "LocalServerManager::cleanChild: enter." );

    if(wasSignal==false)
      {
        LEAVE( "LocalServerManager::cleanChild: leave. !wasSignal." );
        return;
      }
    
#define WAITFORANYCHILD -1
	    
    while(1)
      {	signal (SIGCHLD, catch_SIGCHLD); // some SO requieres this, otherwise they reset to default
        
	int status=0;
        int exitpid=waitpid(WAITFORANYCHILD,&status,WNOHANG);
	
	if(exitpid==0)
		break; // no child died
     
	// I'd love to put this code into a textbook as a negative example and cite you, Walter! -- PB 2003-nov-25
	if(exitpid==-1)
	{
		if(errno == EINTR)
			continue;
		break; // another error;
	}
        VLOG << "rasdaman server process with pid " << exitpid << " has terminated." << std::endl;
    
        list<LocalServer>::iterator iter=srvList.begin();
        for(int i=0;i<srvList.size();i++) 
          {
            TALK( "LocalServerManager::cleanChild: inspecting rasdaman server " << iter->getName() << "." );
            if(iter->getPID()==exitpid)
              {
                TALK( "LocalServerManager::cleanChild: rasdaman server " << iter->getName() << " terminated illegally, status=" << status );

	        cout<<"Error: rasdaman server " << iter->getName() << ", pid " << exitpid << " terminated illegally, reason: ";
		// see 'man waitpid': decoding of status variable
		if (WIFEXITED(status) != 0)
			cout << "exited with return code " << WEXITSTATUS(status);
		else if (WIFSIGNALED(status))
			cout << "uncaught signal " << WTERMSIG(status);	
		else
			cout << "(unknown reason)";
		cout << endl;

	        // choices: restart silently the dead server or
	        // just tell the manager about it
	        // Not restart from here, because of sync problem for capabilities, master has to do that!!!
	        LocalServer temp=*iter;
	        srvList.erase(iter);
	   
	        reportDeadServer(temp);
		break;
	       }  
            iter++;
           } // for
	} //while
	   
    wasSignal=false;	 
    LEAVE( "LocalServerManager::cleanChild: leave." );
   }
    
void LocalServerManager::reportDeadServer(LocalServer &srv)
  {
    ENTER( "LocalServerManager::reportDeadServer: enter." );

    int dummy = -1;
    RasServer &r=rasManager[srv.getName()];
    
    if(r.isValid()) r.changeStatus(SERVER_CRASHED,dummy); 
    LEAVE( "LocalServerManager::reportDeadServer: leave." );
   }