File: afprog.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (723 lines) | stat: -rw-r--r-- 22,220 bytes parent folder | download | duplicates (2)
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
/*
 * Copyright (c) 2002-2012 Balabit
 * Copyright (c) 1998-2012 Balázs Scheidler
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 *
 */

#include "afprog.h"
#include "driver.h"
#include "messages.h"
#include "logwriter.h"
#include "children.h"
#include "fdhelpers.h"
#include "stats/stats-registry.h"
#include "stats/stats-cluster-key-builder.h"
#include "transport/transport-pipe.h"
#include "logproto/logproto-text-server.h"
#include "logproto/logproto-text-client.h"
#include "poll-fd-events.h"

#include <sys/resource.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

typedef struct _AFProgramReloadStoreItem
{
  LogWriter *writer;
  pid_t pid;
} AFProgramReloadStoreItem;

static inline void
_terminate_process_group_by_pid(const pid_t pid)
{
  msg_verbose("Sending TERM signal to the process group",
              evt_tag_int("pid", pid));

  pid_t pgid = getpgid(pid);
  if (pgid != -1 && pgid != getpgrp())
    killpg(pgid, SIGTERM);
}

static inline void
afprogram_reload_store_item_deinit(AFProgramReloadStoreItem *reload_info)
{
  child_manager_unregister(reload_info->pid);
  _terminate_process_group_by_pid(reload_info->pid);
}

static inline void
afprogram_reload_store_item_free(AFProgramReloadStoreItem *reload_info)
{
  log_pipe_unref((LogPipe *)reload_info->writer);
  g_free(reload_info);
}

static inline void
afprogram_reload_store_item_destroy_notify(gpointer data)
{
  AFProgramReloadStoreItem *reload_info = (AFProgramReloadStoreItem *)data;

  afprogram_reload_store_item_deinit(reload_info);
  afprogram_reload_store_item_free(reload_info);
}

static inline void
_exec_program_with_clean_environment(const gchar *cmdline)
{
  execle("/bin/sh", "/bin/sh", "-c", cmdline, NULL, NULL);
}

static inline void
_exec_program(const gchar *cmdline)
{
  execl("/bin/sh", "/bin/sh", "-c", cmdline, NULL);
}

static void
_close_all_fd(void)
{
  const rlim_t min_range = 10000;
  struct rlimit rlp;
  if (getrlimit(RLIMIT_NOFILE, &rlp) < 0)
    {
      /*
       * Failing to query max *fd*, still closing an arbitrary range might make sense,
       * trying with some arbitrary big number. The only issue could be that it cannot
       * close all of the needed *fd* and fail to bind to a socket (original issue).
       */
      rlp.rlim_max = min_range;
    }
  else if (rlp.rlim_max == RLIM_INFINITY)
    {
      /*
       * Also could happen that the limits are RLIM_INFINITY.
       * Use the same logic as above, try to close as much as possible.
       */
      rlp.rlim_max = (rlp.rlim_cur != RLIM_INFINITY ? rlp.rlim_cur : min_range);
    }

  for (rlim_t i = rlp.rlim_max; i > 2; --i)
    close(i);
}

static void
_wait_for_child_closing_fds(int pipe[2])
{
  gchar buff[1];
  while (read(pipe[0], buff, 1) != 0);
}

static gboolean
afprogram_popen(AFProgramProcessInfo *process_info, GIOCondition cond, gint *fd)
{
  int msg_pipe[2];
  int sync_pipe[2];

  g_return_val_if_fail(cond == G_IO_IN || cond == G_IO_OUT, FALSE);

  if (pipe(msg_pipe) == -1)
    {
      msg_error("Error creating program pipe",
                evt_tag_str("cmdline", process_info->cmdline->str),
                evt_tag_error(EVT_TAG_OSERROR));
      return FALSE;
    }

  if (pipe(sync_pipe) == -1)
    {
      msg_error("Error creating program pipe",
                evt_tag_str("cmdline", process_info->cmdline->str),
                evt_tag_error(EVT_TAG_OSERROR));
      close(msg_pipe[0]);
      close(msg_pipe[1]);
      return FALSE;
    }

  if ((process_info->pid = fork()) < 0)
    {
      msg_error("Error in fork()",
                evt_tag_error(EVT_TAG_OSERROR));
      close(msg_pipe[0]);
      close(msg_pipe[1]);
      close(sync_pipe[0]);
      close(sync_pipe[1]);
      return FALSE;
    }

  if (process_info->pid == 0)
    {
      /* child */
      int devnull;

      setpgid(0, 0);

      devnull = open("/dev/null", O_WRONLY);

      if (devnull == -1)
        {
          _exit(127);
        }

      if (cond == G_IO_IN)
        {
          dup2(msg_pipe[1], 1);
          dup2(devnull, 0);
          dup2(devnull, 2);
        }
      else
        {
          dup2(msg_pipe[0], 0);
          dup2(devnull, 1);
          dup2(devnull, 2);
        }
      dup2(sync_pipe[1], 3);
      close(devnull);
      close(msg_pipe[0]);
      close(msg_pipe[1]);

      _close_all_fd();

      if (process_info->inherit_environment)
        _exec_program(process_info->cmdline->str);
      else
        _exec_program_with_clean_environment(process_info->cmdline->str);

      _exit(127);
    }

  close(sync_pipe[1]);
  _wait_for_child_closing_fds(sync_pipe);
  close(sync_pipe[0]);

  if (cond == G_IO_IN)
    {
      *fd = msg_pipe[0];
      close(msg_pipe[1]);
    }
  else
    {
      *fd = msg_pipe[1];
      close(msg_pipe[0]);
    }
  msg_verbose(cond == G_IO_IN ? "Program source started" : "Program destination started",
              evt_tag_str("cmdline", process_info->cmdline->str),
              evt_tag_int("fd", *fd));
  return TRUE;
}


/* source driver */

static void
afprogram_sd_kill_child(AFProgramSourceDriver *self)
{
  if (self->process_info.pid != -1)
    {
      msg_verbose("Sending source program a TERM signal",
                  evt_tag_str("cmdline", self->process_info.cmdline->str),
                  evt_tag_int("child_pid", self->process_info.pid));
      _terminate_process_group_by_pid(self->process_info.pid);
      self->process_info.pid = -1;
    }
}

static void
afprogram_sd_exit(pid_t pid, int status, gpointer s)
{
  AFProgramSourceDriver *self = (AFProgramSourceDriver *) s;

  /* Note: self->process_info.pid being -1 means that deinit was called, thus we don't
   * need to restart the command. self->process_info.pid might change due to EPIPE
   * handling restarting the command before this handler is run. */
  if (self->process_info.pid != -1 && self->process_info.pid == pid)
    {
      msg_verbose("Child program exited",
                  evt_tag_str("cmdline", self->process_info.cmdline->str),
                  evt_tag_int("status", status));
      self->process_info.pid = -1;
    }
}

static void
afprogram_sd_queue(LogPipe *s, LogMessage *msg, const LogPathOptions *path_options)
{
  log_msg_set_value_to_string(msg, LM_V_TRANSPORT, "local+program");
  log_src_driver_queue_method(s, msg, path_options);
}

static gboolean
afprogram_sd_init(LogPipe *s)
{
  AFProgramSourceDriver *self = (AFProgramSourceDriver *) s;
  GlobalConfig *cfg = log_pipe_get_config(s);
  gint fd;

  if (!log_src_driver_init_method(s))
    return FALSE;

  log_reader_options_init(&self->reader_options, cfg, self->super.super.group);

  msg_verbose("Starting source program",
              evt_tag_str("cmdline", self->process_info.cmdline->str));

  if (!afprogram_popen(&self->process_info, G_IO_IN, &fd))
    return FALSE;

  /* parent */
  child_manager_register(self->process_info.pid, afprogram_sd_exit, log_pipe_ref(&self->super.super.super),
                         (GDestroyNotify) log_pipe_unref);

  g_fd_set_nonblock(fd, TRUE);
  g_fd_set_cloexec(fd, TRUE);
  if (!self->reader)
    {
      LogTransport *transport;
      LogProtoServer *proto;

      transport = log_transport_pipe_new(fd);
      proto = log_proto_text_server_new(transport, &self->reader_options.proto_options.super);

      self->reader = log_reader_new(s->cfg);
      log_pipe_set_options(&self->reader->super.super, &self->super.super.super.options);
      log_reader_open(self->reader, proto, poll_fd_events_new(fd));

      StatsClusterKeyBuilder *kb = stats_cluster_key_builder_new();
      stats_cluster_key_builder_add_label(kb, stats_cluster_label("driver", "program"));
      stats_cluster_key_builder_add_legacy_label(kb, stats_cluster_label("command", self->process_info.cmdline->str));
      log_reader_set_options(self->reader,
                             s,
                             &self->reader_options,
                             self->super.super.id,
                             kb);
    }
  log_pipe_append((LogPipe *) self->reader, &self->super.super.super);
  if (!log_pipe_init((LogPipe *) self->reader))
    {
      msg_error("Error initializing program source, closing fd",
                evt_tag_int("fd", fd));
      log_pipe_unref((LogPipe *) self->reader);
      self->reader = NULL;
      close(fd);
      return FALSE;
    }
  return TRUE;
}

static gboolean
afprogram_sd_deinit(LogPipe *s)
{
  AFProgramSourceDriver *self = (AFProgramSourceDriver *) s;

  afprogram_sd_kill_child(self);
  if (self->reader)
    {
      log_pipe_deinit((LogPipe *) self->reader);
      log_pipe_unref((LogPipe *) self->reader);
      self->reader = NULL;
    }

  if (!log_src_driver_deinit_method(s))
    return FALSE;

  return TRUE;
}

static void
afprogram_sd_free(LogPipe *s)
{
  AFProgramSourceDriver *self = (AFProgramSourceDriver *) s;

  log_reader_options_destroy(&self->reader_options);
  g_string_free(self->process_info.cmdline, TRUE);
  log_src_driver_free(s);
}

static gint
afprogram_sd_notify(LogPipe *s, gint notify_code, gpointer user_data)
{
  switch (notify_code)
    {
    case NC_CLOSE:
    case NC_READ_ERROR:
      afprogram_sd_deinit(s);
      afprogram_sd_init(s);
      break;
    default:
      break;
    }
  return NR_OK;
}

LogDriver *
afprogram_sd_new(gchar *cmdline, GlobalConfig *cfg)
{
  AFProgramSourceDriver *self = g_new0(AFProgramSourceDriver, 1);
  log_src_driver_init_instance(&self->super, cfg);

  self->super.super.super.init = afprogram_sd_init;
  self->super.super.super.deinit = afprogram_sd_deinit;
  self->super.super.super.free_fn = afprogram_sd_free;
  self->super.super.super.notify = afprogram_sd_notify;
  self->super.super.super.queue = afprogram_sd_queue;
  self->process_info.cmdline = g_string_new(cmdline);
  afprogram_set_inherit_environment(&self->process_info, TRUE);
  log_reader_options_defaults(&self->reader_options);
  self->reader_options.parse_options.flags |= LP_LOCAL;
  self->reader_options.super.stats_level = STATS_LEVEL0;
  self->reader_options.super.stats_source = stats_register_type("program");
  return &self->super.super;
}

/* dest driver */

static void afprogram_dd_exit(pid_t pid, int status, gpointer s);

static gchar *
afprogram_dd_format_queue_persist_name(AFProgramDestDriver *self)
{
  static gchar persist_name[256];

  g_snprintf(persist_name, sizeof(persist_name),
             "afprogram_dd_qname(%s,%s)", self->process_info.cmdline->str, self->super.super.id);

  return persist_name;
}

static const gchar *
afprogram_dd_format_persist_name(const LogPipe *s)
{
  const AFProgramDestDriver *self = (const AFProgramDestDriver *)s;
  static gchar persist_name[256];

  if (s->persist_name)
    g_snprintf(persist_name, sizeof(persist_name), "afprogram_dd_name.%s", s->persist_name);
  else
    g_snprintf(persist_name, sizeof(persist_name), "afprogram_dd_name(%s,%s)",
               self->process_info.cmdline->str, self->super.super.id);

  return persist_name;
}

static void
afprogram_dd_kill_child(AFProgramDestDriver *self)
{
  if (self->process_info.pid != -1)
    {
      msg_verbose("Sending destination program a TERM signal",
                  evt_tag_str("cmdline", self->process_info.cmdline->str),
                  evt_tag_int("child_pid", self->process_info.pid));
      _terminate_process_group_by_pid(self->process_info.pid);
      self->process_info.pid = -1;
    }
}

static inline gboolean
afprogram_dd_open_program(AFProgramDestDriver *self, int *fd)
{
  if (self->process_info.pid == -1)
    {
      msg_verbose("Starting destination program",
                  evt_tag_str("cmdline", self->process_info.cmdline->str));

      if (!afprogram_popen(&self->process_info, G_IO_OUT, fd))
        return FALSE;

      g_fd_set_nonblock(*fd, TRUE);
    }

  child_manager_register(self->process_info.pid, afprogram_dd_exit, log_pipe_ref(&self->super.super.super),
                         (GDestroyNotify)log_pipe_unref);

  return TRUE;
}

static gboolean
afprogram_dd_reopen(AFProgramDestDriver *self)
{
  int fd = -1;

  afprogram_dd_kill_child(self);

  if (!afprogram_dd_open_program(self, &fd) ||
      fd < 0)
    return FALSE;

  log_writer_reopen(self->writer, log_proto_text_client_new(log_transport_pipe_new(fd),
                                                            &self->writer_options.proto_options.super));
  return TRUE;
}

static gboolean
afprogram_dd_is_command_not_found(int status)
{
  /*
   * Status here is a 16-bit int, the real exit status is the 8 least
   * significant bits of it, and an exit status of 127 from the shell is
   * supposed to signal a command-not-found case. The other 8 bits are one bit
   * to signal if the child dumped core, the other 7 the signal - if any - with
   * which it exited.
   *
   * In our case, we want to make sure that the other 8 bits are all empty (no
   * core dump; and normal exit, not one due to a signal), hence the second part
   * of the check.
   *
   * See wait(2) for more information.
   */
  return (status >> 8) == 127 && ((status & 0x00ff) == 0);
}

static void
afprogram_dd_exit(pid_t pid, int status, gpointer s)
{
  AFProgramDestDriver *self = (AFProgramDestDriver *) s;

  /* Note: self->process_info.pid being -1 means that deinit was called, thus we don't
   * need to restart the command. self->process_info.pid might change due to EPIPE
   * handling restarting the command before this handler is run. */
  if (self->process_info.pid != -1 && self->process_info.pid == pid)
    {
      if (afprogram_dd_is_command_not_found(status))
        {
          msg_error("Child program exited with command not found, stopping the destination.",
                    evt_tag_str("cmdline", self->process_info.cmdline->str),
                    evt_tag_int("status", status));

          self->process_info.pid = -1;
        }
      else
        {
          msg_info("Child program exited, restarting",
                   evt_tag_str("cmdline", self->process_info.cmdline->str),
                   evt_tag_int("status", status));

          self->process_info.pid = -1;
          afprogram_dd_reopen(self);
        }
    }
}

static gboolean
afprogram_dd_restore_reload_store_item(AFProgramDestDriver *self, GlobalConfig *cfg)
{
  const gchar *persist_name = afprogram_dd_format_persist_name((const LogPipe *)self);
  AFProgramReloadStoreItem *restored_info =
    (AFProgramReloadStoreItem *)cfg_persist_config_fetch(cfg, persist_name);

  if (restored_info)
    {
      self->process_info.pid = restored_info->pid;
      self->writer = restored_info->writer;

      child_manager_register(self->process_info.pid, afprogram_dd_exit, log_pipe_ref(&self->super.super.super),
                             (GDestroyNotify)log_pipe_unref);
      g_free(restored_info);
    }

  return !!(self->writer);
}

static void
_init_stats_key_builders(AFProgramDestDriver *self, StatsClusterKeyBuilder **writer_sck_builder,
                         StatsClusterKeyBuilder **driver_sck_builder, StatsClusterKeyBuilder **queue_sck_builder)
{
  *writer_sck_builder = stats_cluster_key_builder_new();
  stats_cluster_key_builder_add_label(*writer_sck_builder, stats_cluster_label("driver", "program"));
  stats_cluster_key_builder_add_legacy_label(*writer_sck_builder, stats_cluster_label("command",
                                             self->process_info.cmdline->str));

  *driver_sck_builder = stats_cluster_key_builder_new();
  stats_cluster_key_builder_add_label(*driver_sck_builder, stats_cluster_label("driver", "program"));
  stats_cluster_key_builder_add_label(*driver_sck_builder, stats_cluster_label("id", self->super.super.id));
  stats_cluster_key_builder_add_legacy_label(*driver_sck_builder, stats_cluster_label("command",
                                             self->process_info.cmdline->str));
  stats_cluster_key_builder_set_legacy_alias(*driver_sck_builder,
                                             self->writer_options.stats_source | SCS_DESTINATION,
                                             self->super.super.id, self->process_info.cmdline->str);

  *queue_sck_builder = stats_cluster_key_builder_new();
  stats_cluster_key_builder_add_label(*queue_sck_builder, stats_cluster_label("driver", "program"));
  stats_cluster_key_builder_add_label(*queue_sck_builder, stats_cluster_label("id", self->super.super.id));
  stats_cluster_key_builder_add_legacy_label(*queue_sck_builder, stats_cluster_label("command",
                                             self->process_info.cmdline->str));
}

static gboolean
afprogram_dd_init(LogPipe *s)
{
  AFProgramDestDriver *self = (AFProgramDestDriver *) s;
  GlobalConfig *cfg = log_pipe_get_config(s);

  if (!log_dest_driver_init_method(s))
    return FALSE;

  log_writer_options_init(&self->writer_options, cfg, 0);

  const gboolean restore_successful = afprogram_dd_restore_reload_store_item(self, cfg);

  if (!self->writer)
    self->writer = log_writer_new(LW_FORMAT_FILE, s->cfg);

  StatsClusterKeyBuilder *writer_sck_builder;
  StatsClusterKeyBuilder *driver_sck_builder;
  StatsClusterKeyBuilder *queue_sck_builder;
  _init_stats_key_builders(self, &writer_sck_builder, &driver_sck_builder, &queue_sck_builder);

  log_pipe_set_options((LogPipe *) self->writer, &self->super.super.super.options);
  log_writer_set_options(self->writer,
                         s,
                         &self->writer_options,
                         self->super.super.id,
                         writer_sck_builder);


  gint stats_level = log_pipe_is_internal(&self->super.super.super) ? STATS_LEVEL3 : self->writer_options.stats_level;
  LogQueue *queue = log_dest_driver_acquire_queue(&self->super, afprogram_dd_format_queue_persist_name(self),
                                                  stats_level, driver_sck_builder, queue_sck_builder);
  log_writer_set_queue(self->writer, queue);

  stats_cluster_key_builder_free(queue_sck_builder);
  stats_cluster_key_builder_free(driver_sck_builder);

  if (!log_pipe_init((LogPipe *) self->writer))
    {
      log_pipe_unref((LogPipe *) self->writer);
      return FALSE;
    }
  log_pipe_append(&self->super.super.super, (LogPipe *) self->writer);

  if (restore_successful)
    {
      LogProtoClient *proto = log_writer_steal_proto(self->writer);
      log_writer_reopen(self->writer, proto);
      return TRUE;
    }

  return afprogram_dd_reopen(self);
}

static inline void
afprogram_dd_store_reload_store_item(AFProgramDestDriver *self, GlobalConfig *cfg)
{
  AFProgramReloadStoreItem *reload_info = g_new0(AFProgramReloadStoreItem, 1);

  reload_info->pid = self->process_info.pid;
  reload_info->writer = self->writer;

  cfg_persist_config_add(cfg, afprogram_dd_format_persist_name((const LogPipe *)self), reload_info,
                         afprogram_reload_store_item_destroy_notify);
}

static gboolean
afprogram_dd_deinit(LogPipe *s)
{
  AFProgramDestDriver *self = (AFProgramDestDriver *) s;
  GlobalConfig *cfg = log_pipe_get_config(&self->super.super.super);

  if (self->writer)
    log_pipe_deinit((LogPipe *) self->writer);

  child_manager_unregister(self->process_info.pid);

  if (self->keep_alive)
    {
      afprogram_dd_store_reload_store_item(self, cfg);
    }
  else
    {
      afprogram_dd_kill_child(self);

      if (self->writer)
        log_pipe_unref((LogPipe *) self->writer);
    }

  if (self->writer)
    {
      self->writer = NULL;
    }

  return log_dest_driver_deinit_method(s);
}

static void
afprogram_dd_free(LogPipe *s)
{
  AFProgramDestDriver *self = (AFProgramDestDriver *) s;

  log_pipe_unref((LogPipe *) self->writer);
  g_string_free(self->process_info.cmdline, TRUE);
  log_writer_options_destroy(&self->writer_options);
  log_dest_driver_free(s);
}

static gint
afprogram_dd_notify(LogPipe *s, gint notify_code, gpointer user_data)
{
  AFProgramDestDriver *self = (AFProgramDestDriver *) s;

  switch (notify_code)
    {
    case NC_CLOSE:
      afprogram_dd_reopen(self);
      break;
    case NC_WRITE_ERROR:
      /* We let this fall through, to be handled by the child manager. We do
         this to have access to the exit status, and which we use to decide
         whether to restart immediately, or stop the destination. */
      break;
    default:
      break;
    }
  return NR_OK;
}

LogDriver *
afprogram_dd_new(gchar *cmdline, GlobalConfig *cfg)
{
  AFProgramDestDriver *self = g_new0(AFProgramDestDriver, 1);
  log_dest_driver_init_instance(&self->super, cfg);

  self->super.super.super.init = afprogram_dd_init;
  self->super.super.super.deinit = afprogram_dd_deinit;
  self->super.super.super.free_fn = afprogram_dd_free;
  self->super.super.super.notify = afprogram_dd_notify;
  self->super.super.super.generate_persist_name = afprogram_dd_format_persist_name;
  self->process_info.cmdline = g_string_new(cmdline);
  self->process_info.pid = -1;
  afprogram_set_inherit_environment(&self->process_info, TRUE);
  log_writer_options_defaults(&self->writer_options);
  self->writer_options.stats_level = STATS_LEVEL0;
  self->writer_options.stats_source = stats_register_type("program");
  return &self->super.super;
}

void
afprogram_dd_set_keep_alive(AFProgramDestDriver *self, gboolean keep_alive)
{
  self->keep_alive = keep_alive;
}

void
afprogram_set_inherit_environment(AFProgramProcessInfo *self, gboolean inherit_environment)
{
  self->inherit_environment = inherit_environment;
}