summaryrefslogtreecommitdiff
path: root/sbuild/sbuild-run-parts.cc
blob: b877d757e0a6f1b9531d0b17a9fa30aa57066bbf (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
/* Copyright © 2005-2009  Roger Leigh <rleigh@debian.org>
 *
 * schroot 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.
 *
 * schroot 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, see
 * <http://www.gnu.org/licenses/>.
 *
 *********************************************************************/

#include <config.h>

#include "sbuild-dirstream.h"
#include "sbuild-run-parts.h"
#include "sbuild-util.h"

#include <cerrno>

#include <poll.h>
#include <sys/wait.h>

#include <syslog.h>

#include <boost/format.hpp>

using boost::format;
using namespace sbuild;

namespace
{

  typedef std::pair<sbuild::run_parts::error_code,const char *> emap;

  /**
   * This is a list of the supported error codes.  It's used to
   * construct the real error codes map.
   */
  emap init_errors[] =
    {
      emap(run_parts::CHILD_FORK, N_("Failed to fork child")),
      emap(run_parts::CHILD_WAIT, N_("Wait for child failed")),
      // TRANSLATORS: %1% = command name
      emap(run_parts::EXEC,       N_("Failed to execute '%1%'")),
      emap(run_parts::PIPE,       N_("Failed to create pipe")),
      emap(run_parts::DUP,        N_("Failed to duplicate file descriptor")),
      emap(run_parts::POLL,       N_("Failed to poll file descriptor")),
      emap(run_parts::READ,       N_("Failed to read file descriptor"))
    };

}

template<>
error<run_parts::error_code>::map_type
error<run_parts::error_code>::error_strings
(init_errors,
 init_errors + (sizeof(init_errors) / sizeof(init_errors[0])));

run_parts::run_parts (std::string const& directory,
		      bool               lsb_mode,
		      bool               abort_on_error,
		      mode_t             umask):
  lsb_mode(true),
  abort_on_error(abort_on_error),
  umask(umask),
  verbose(false),
  reverse(false),
  directory(directory),
  programs()
{
  dirstream stream(directory);
  direntry de;
  while (stream >> de)
    {
      // Skip common directories.
      std::string name(de.name());
      if (name == "." || name == "..")
	continue;

      // Skip backup files and dpkg configuration backup files.
      if (is_valid_filename(name, this->lsb_mode))
	this->programs.insert(name);
    }
}

run_parts::~run_parts ()
{
}

bool
run_parts::get_verbose () const
{
  return this->verbose;
}

void
run_parts::set_verbose (bool verbose)
{
  this->verbose = verbose;
}

bool
run_parts::get_reverse () const
{
  return this->reverse;
}

void
run_parts::set_reverse (bool reverse)
{
  this->reverse = reverse;
}

int
run_parts::run (string_list const& command,
		environment const& env)
{
  int exit_status = 0;

  if (!this->reverse)
    {
      for (program_set::const_iterator pos = this->programs.begin();
	   pos != this->programs.end();
	   ++pos)
	{
	  string_list real_command;
	  real_command.push_back(*pos);
	  for (string_list::const_iterator spos = command.begin();
	       spos != command.end();
	       ++spos)
	    real_command.push_back(*spos);

	  exit_status = run_child(*pos, real_command, env);

	  if (exit_status && this->abort_on_error)
	    return exit_status;
	}
    }
  else
    {
      for (program_set::const_reverse_iterator pos = this->programs.rbegin();
	   pos != this->programs.rend();
	   ++pos)
	{
	  string_list real_command;
	  real_command.push_back(*pos);
	  for (string_list::const_iterator spos = command.begin();
	       spos != command.end();
	       ++spos)
	    real_command.push_back(*spos);

	  exit_status = run_child(*pos, real_command, env);

	  if (exit_status && this->abort_on_error)
	    return exit_status;
	}
    }

  return exit_status;
}

int
run_parts::run_child (std::string const& file,
		      string_list const& command,
		      environment const& env)
{
  int stdout_pipe[2];
  int stderr_pipe[2];
  int exit_status = 0;
  pid_t pid;

  try
    {
      if (pipe(stdout_pipe) < 0)
	throw error(PIPE, strerror(errno));
      if (pipe(stderr_pipe) < 0)
	throw error(PIPE, strerror(errno));

      if ((pid = fork()) == -1)
	{
	  throw error(CHILD_FORK, strerror(errno));
	}
      else if (pid == 0)
	{
	  try
	    {
	      log_debug(DEBUG_INFO) << "run_parts: executing "
				    << string_list_to_string(command, ", ")
				    << std::endl;
	      if (this->verbose)
		// TRANSLATORS: %1% = command
		log_info() << format(_("Executing '%1%'"))
		  % string_list_to_string(command, " ")
			   << std::endl;
	      ::umask(this->umask);

	      // Don't leak syslog file descriptor to child processes.
	      closelog();

	      // Set up pipes for stdout and stderr
	      if (dup2(stdout_pipe[1], STDOUT_FILENO) < 0)
		throw error(DUP, strerror(errno));
	      if (dup2(stderr_pipe[1], STDERR_FILENO) < 0)
		throw error(DUP, strerror(errno));

	      close(stdout_pipe[0]);
	      close(stdout_pipe[1]);
	      close(stderr_pipe[0]);
	      close(stderr_pipe[1]);

	      exec(this->directory + '/' + file, command, env);
	      error e(file, EXEC, strerror(errno));
	      log_exception_error(e);
	    }
	  catch (std::exception const& e)
	    {
	      sbuild::log_exception_error(e);
	    }
	  catch (...)
	    {
	      sbuild::log_error()
		<< _("An unknown exception occurred") << std::endl;
	    }
	  _exit(EXIT_FAILURE);
	}

      // Log stdout and stderr.
      close(stdout_pipe[1]);
      close(stderr_pipe[1]);

      struct pollfd pollfds[2];
      pollfds[0].fd = stdout_pipe[0];
      pollfds[0].events = POLLIN;
      pollfds[0].revents = 0;
      pollfds[1].fd = stderr_pipe[0];
      pollfds[1].events = POLLIN;
      pollfds[1].revents = 0;

      char buffer[BUFSIZ];

      std::string stdout_buf;
      std::string stderr_buf;

      while (1)
	{
	  int status;
	  if ((status = poll(pollfds, 2, -1)) < 0)
	    throw error(POLL, strerror(errno));

	  int outdata = 0;
	  int errdata = 0;

	  if (pollfds[1].revents | POLLIN)
	    {
	      int errdata;
	      if ((errdata = read(pollfds[1].fd, buffer, BUFSIZ)) < 0)
		throw error(READ, strerror(errno));

	      if (errdata)
		stderr_buf += std::string(&buffer[0], errdata);
	    }

	  if (pollfds[0].revents | POLLIN)
	    {
	      if ((outdata = read(pollfds[0].fd, buffer, BUFSIZ)) < 0)
		throw error(READ, strerror(errno));

	      if (outdata)
		stdout_buf += std::string(&buffer[0], outdata);
	    }

	  if (!stderr_buf.empty())
	    {
	      string_list lines = split_string_strict(stderr_buf, "\n");
	      // If the buffer ends in a newline before splitting,
	      // it's OK to flush all lines.
	      bool flush = *stderr_buf.rbegin() == '\n';

	      for (string_list::const_iterator pos = lines.begin();
		   pos != lines.end();
		   ++pos)
		{
		  if (pos + 1 != lines.end() || flush)
		    log_error() << file << ": " << *pos << '\n';
		  else // Save possibly incompete line
		    stderr_buf = *pos;
		}

	      if (flush)
		stderr_buf.clear();
	    }

	  if (!stdout_buf.empty())
	    {
	      string_list lines = split_string_strict(stdout_buf, "\n");
	      // If the buffer ends in a newline before splitting,
	      // it's OK to flush all lines.
	      bool flush = *stdout_buf.rbegin() == '\n';

	      for (string_list::const_iterator pos = lines.begin();
		   pos != lines.end();
		   ++pos)
		{
		  if (pos + 1 != lines.end() || flush)
		    log_info() << file << ": " << *pos << '\n';
		  else // Save possibly incompete line
		    stdout_buf = *pos;
		}

	      if (flush)
		stdout_buf.clear();
	    }

	  if (outdata == 0 && errdata == 0) // pipes closed
	    {
	      // Flush any remaining lines
	      if (!stderr_buf.empty())
		log_error() << file << ": " << stderr_buf << '\n';
	      if (!stdout_buf.empty())
		log_info() << file << ": " << stdout_buf << '\n';
	      break;
	    }
	}

      close(stdout_pipe[0]);
      close(stderr_pipe[0]);
      wait_for_child(pid, exit_status);
    }
  catch (error const& e)
    {
      close(stdout_pipe[0]);
      close(stdout_pipe[1]);
      close(stderr_pipe[0]);
      close(stderr_pipe[1]);
      throw;
    }

  if (exit_status)
    log_debug(DEBUG_INFO) << "run_parts: " << file
			  << " failed with status " << exit_status
			  << std::endl;
  else
    log_debug(DEBUG_INFO) << "run_parts: " << file
			  << " succeeded"
			  << std::endl;

  return exit_status;
}

void
run_parts::wait_for_child (pid_t pid,
			   int&  child_status)
{
  child_status = EXIT_FAILURE; // Default exit status

  int status;

  while (1)
    {
      if (waitpid(pid, &status, 0) == -1)
	{
	  if (errno == EINTR)
	    continue; // Wait again.
	  else
	    throw error(CHILD_WAIT, strerror(errno));
	}
      else
	break;
    }

  if (WIFEXITED(status))
    child_status = WEXITSTATUS(status);
}