File: process.vala

package info (click to toggle)
libfsobasics 0.9.0%2Bgit20100509-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,676 kB
  • ctags: 103
  • sloc: sh: 10,183; makefile: 233; ansic: 12
file content (355 lines) | stat: -rw-r--r-- 8,954 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
/*
 * Copyright (C) 2009-2010 Michael 'Mickey' Lauer <mlauer@vanille-media.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.

 * This library 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
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 */

/**
 * @interface FsoFramework.IProcessGuard
 **/
public interface FsoFramework.IProcessGuard : GLib.Object
{
    public abstract bool launch( string[] command );
    public abstract void stop( int sig = Posix.SIGTERM );
    public abstract void setAutoRelaunch( bool on );

    public abstract bool sendSignal( int sig );
    public abstract bool isRunning();

    public signal void running();
    public signal void stopped();
}

/**
 * @class FsoFramework.GProcessGuard
 **/
public class FsoFramework.GProcessGuard : FsoFramework.IProcessGuard, GLib.Object
{
    private Pid pid;
    private uint watch;
    private string[] command;
    private bool relaunch;

    public Posix.pid_t _pid()
    {
        return (Posix.pid_t)pid;
    }

    ~GProcessGuard()
    {
        if ( pid != (Pid)0 )
        {
#if DEBUG
            warning( "Guard being freed, while child %d still running. This is most likely a bug in your problem. Trying to kill the child in a synchronous way...", (int)pid );
#endif
            relaunch = false;
            syncStop();
        }
    }

    public bool launch( string[] command )
    {
        this.command = command; // save for possible relaunching

        if ( pid != (Pid)0 )
        {
            warning( @"Can't launch $(command[0]); already running as pid %d".printf( (int)pid ) );
            return false;
        }

        try
        {
            GLib.Process.spawn_async( GLib.Environment.get_variable( "PWD" ),
                                      command,
                                      null,
                                      GLib.SpawnFlags.DO_NOT_REAP_CHILD | GLib.SpawnFlags.SEARCH_PATH,
                                      null,
                                      out pid );
        }
        catch ( SpawnError e )
        {
            warning( @"Can't spawn $(command[0]): $(strerror(errno))" );
            return false;
        }

        watch = GLib.ChildWatch.add( pid, onChildWatchEvent );
        this.running(); // SIGNAL
        return true;
    }

    public bool launchWithPipes( string[] command, out int fdin, out int fdout )
    {
        this.command = command; // save for possible relaunching

        if ( pid != (Pid)0 )
        {
            warning( @"Can't launch $(command[0]); already running as pid %d".printf( (int)pid ) );
            return false;
        }

        try
        {
            GLib.Process.spawn_async_with_pipes(
                GLib.Environment.get_variable( "PWD" ),
                command,
                null,
                GLib.SpawnFlags.DO_NOT_REAP_CHILD | GLib.SpawnFlags.SEARCH_PATH,
                null,
                out pid,
                out fdin,
                out fdout,
                null );
        }
        catch ( SpawnError e )
        {
            warning( @"Can't spawn w/ pipes $(command[0]): $(e.message))" );
            return false;
        }

        watch = GLib.ChildWatch.add( pid, onChildWatchEvent );
        this.running(); // SIGNAL
        return true;
    }

    // FIXME: consider making this async?
    public void stop( int sig = Posix.SIGTERM )
    {
        stopSendStopped( true );
    }

    public void setAutoRelaunch( bool on )
    {
        relaunch = on;
    }

    public bool sendSignal( int sig )
    {
        if ( pid == (Pid)0 )
        {
            return false;
        }

        var res = Posix.kill( (Posix.pid_t)pid, sig );
        return res == 0;
    }

    public bool isRunning()
    {
        return ( pid != (Pid)0 );
    }

    //
    // private API
    //
    private void stopSendStopped( bool send )
    {
        _stop( send );
    }

    private void cleanupResources()
    {
        if ( watch > 0 )
        {
            GLib.Source.remove( watch );
        }
        GLib.Process.close_pid( pid );
        pid = 0;
        this.stopped();
    }

    private void onChildWatchEvent( Pid pid, int status )
    {
        if ( this.pid != pid )
        {
            critical( "D'OH!" );
            return;
        }
#if DEBUG
        debug( "CHILD WATCH EVENT FOR %d: %d", (int)pid, status );
#endif
        pid = 0;
        cleanupResources();

        if ( relaunch )
        {
#if DEBUG
            debug( "Relanching requested..." );
#endif
            if ( ! launch( command ) )
            {
                warning( @"Could not relaunch $(command[0]); disabling." );
                relaunch = false;
            }
        }
    }

    internal const int KILL_SLEEP_TIMEOUT  = 1000 * 1000 * 5; // 5 seconds
    internal const int KILL_SLEEP_INTERVAL = 1000 * 1000 * 1; // 1 second

    private async void _stop( bool send )
    {
        if ( (Posix.pid_t)pid == 0 )
        {
            return;
        }
#if DEBUG
        debug( "Attempting to stop pid %d - sending SIGTERM first...", pid );
#endif
        Posix.kill( (Posix.pid_t)pid, Posix.SIGTERM );
        var done = false;
        var timer = new GLib.Timer();
        timer.start();

        while ( !done && pid != 0 )
        {
            var pid_result = Posix.waitpid( (Posix.pid_t)pid, null, Posix.WNOHANG );
#if DEBUG
            debug( "Waitpid result %d", pid_result );
#endif
			if ( pid_result < 0 )
			{
				done = true;
#if DEBUG
				debug( "Failed to wait for process to exit: waitpid returned %d", pid_result );
#endif
			}
			else if ( pid_result == 0 )
			{
				if ( timer.elapsed() >= KILL_SLEEP_TIMEOUT )
				{
#if DEBUG
					debug( "Timeout for pid %d elapsed, exiting wait loop", pid );
#endif
					done = true;
				}
				else
				{
#if DEBUG
					debug( "Process %d is still running, waiting...", pid );
#endif
                    Timeout.add_seconds( 1, _stop.callback );
                    yield;
				}
			}
			else /* pid_result > 0 */
			{
				done = true;
#if DEBUG
				debug( "Process %d terminated normally", pid );
#endif
				GLib.Process.close_pid( pid );
				pid = 0;
			}
        }

        if ( pid != 0 )
        {
            warning( "Process %d ignored SIGTERM, sending SIGKILL", pid );

            if ( watch > 0 )
            {
                GLib.Source.remove( watch );
                watch = 0;
            }

            Posix.kill( (Posix.pid_t)pid, Posix.SIGKILL );
            Thread.usleep( 1000 );
            pid = 0;
#if DEBUG
            debug( "Process %d stop complete", pid );
#endif
        }

        if ( send )
        {
            this.stopped();
        }
    }

    private void syncStop()
    {
        if ( watch > 0 )
        {
            GLib.Source.remove( watch );
            watch = 0;
        }
#if DEBUG
        debug( "Attempting to syncstop pid %d - sending SIGTERM first...", pid );
#endif
        Posix.kill( (Posix.pid_t)pid, Posix.SIGTERM );
        var done = false;
        var timer = new GLib.Timer();
        timer.start();

        while ( !done && pid != 0 )
        {
            var pid_result = Posix.waitpid( (Posix.pid_t)pid, null, Posix.WNOHANG );
#if DEBUG
            debug( "Waitpid result %d", pid_result );
#endif
			if ( pid_result < 0 )
			{
				done = true;
#if DEBUG
				debug( "Failed to syncwait for process to exit: waitpid returned %d", pid_result );
#endif
			}
			else if ( pid_result == 0 )
			{
				if ( timer.elapsed() >= KILL_SLEEP_TIMEOUT )
				{
#if DEBUG
					debug( "Timeout for pid %d elapsed, exiting syncwait loop", pid );
#endif
					done = true;
				}
				else
				{
#if DEBUG
					debug( "Process %d is still running, sync waiting...", pid );
#endif
                    Thread.usleep( KILL_SLEEP_INTERVAL );
				}
			}
			else /* pid_result > 0 */
			{
				done = true;
#if DEBUG
				debug( "Process %d terminated normally", pid );
#endif
				GLib.Process.close_pid( pid );
				pid = 0;
			}
        }

        if ( pid != 0 )
        {
            warning( "Process %d ignored SIGTERM, sending SIGKILL", pid );

            if ( watch > 0 )
            {
                GLib.Source.remove( watch );
            }

            Posix.kill( (Posix.pid_t)pid, Posix.SIGKILL );
            Thread.usleep( 1000 );
            pid = 0;
#if DEBUG
            debug( "Process %d stop complete", pid );
#endif
        }
    }
}