aboutsummaryrefslogtreecommitdiff
path: root/mod/mod-build-result.cxx
blob: d8b647ad434ec755fc49dacecf5562cebf0f219f (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
// file      : mod/mod-build-result.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <mod/mod-build-result.hxx>

#include <algorithm> // find_if()

#include <libbutl/sendmail.hxx>
#include <libbutl/process-io.hxx>
#include <libbutl/manifest-parser.hxx>
#include <libbutl/manifest-serializer.hxx>

#include <libbbot/manifest.hxx>

#include <odb/database.hxx>
#include <odb/transaction.hxx>

#include <web/module.hxx>
#include <web/mime-url-encoding.hxx>

#include <libbrep/build.hxx>
#include <libbrep/build-odb.hxx>
#include <libbrep/package.hxx>
#include <libbrep/package-odb.hxx>

#include <mod/options.hxx>

using namespace std;
using namespace butl;
using namespace bbot;
using namespace web;
using namespace brep::cli;
using namespace odb::core;

// While currently the user-defined copy constructor is not required (we don't
// need to deep copy nullptr's), it is a good idea to keep the placeholder
// ready for less trivial cases.
//
brep::build_result::
build_result (const build_result& r)
    : database_module (r),
      options_ (r.initialized_ ? r.options_ : nullptr)
{
}

void brep::build_result::
init (scanner& s)
{
  MODULE_DIAG;

  options_ = make_shared<options::build_result> (
    s, unknown_mode::fail, unknown_mode::fail);

  database_module::init (static_cast<options::package_db> (*options_),
                         options_->package_db_retry ());

  if (options_->build_config_specified ())
    database_module::init (static_cast<options::build>    (*options_),
                           static_cast<options::build_db> (*options_),
                           options_->build_db_retry ());

  if (options_->root ().empty ())
    options_->root (dir_path ("/"));
}

bool brep::build_result::
handle (request& rq, response&)
{
  using brep::version; // Not to confuse with module::version.

  MODULE_DIAG;

  if (build_db_ == nullptr)
    throw invalid_request (501, "not implemented");

  // Make sure no parameters passed.
  //
  try
  {
    name_value_scanner s (rq.parameters ());
    params::build_result (s, unknown_mode::fail, unknown_mode::fail);
  }
  catch (const cli::exception& e)
  {
    throw invalid_request (400, e.what ());
  }

  result_request_manifest rqm;

  try
  {
    size_t limit (options_->build_result_request_max_size ());
    manifest_parser p (rq.content (limit, limit), "result_request_manifest");
    rqm = result_request_manifest (p);
  }
  catch (const manifest_parsing& e)
  {
    throw invalid_request (400, e.what ());
  }

  // Parse the task response session to obtain the build configuration name and
  // the timestamp, and to make sure the session matches the result manifest's
  // package name and version.
  //
  build_id id;
  timestamp session_timestamp;

  try
  {
    const string& s (rqm.session);

    size_t p (s.find ('/')); // End of package name.

    if (p == 0)
      throw invalid_argument ("empty package name");

    if (p == string::npos)
      throw invalid_argument ("no package version");

    string& name (rqm.result.name);
    if (name.compare (0, name.size (), s, 0, p) != 0)
      throw invalid_argument ("package name mismatch");

    size_t b (p + 1);    // Start of version.
    p = s.find ('/', b); // End of version.

    if (p == string::npos)
      throw invalid_argument ("no configuration name");

    auto parse_version = [&s, &b, &p] (const char* what) -> version
    {
      // Intercept exception handling to add the parsing error attribution.
      //
      try
      {
        return brep::version (string (s, b, p - b));
      }
      catch (const invalid_argument& e)
      {
        throw invalid_argument (string ("invalid ") + what + ": " + e.what ());
      }
    };

    version package_version (parse_version ("package version"));

    if (package_version != rqm.result.version)
      throw invalid_argument ("package version mismatch");

    b = p + 1;           // Start of configuration name.
    p = s.find ('/', b); // End of configuration name.

    if (p == string::npos)
      throw invalid_argument ("no toolchain version");

    string config (s, b, p - b);

    b = p + 1;           // Start of toolchain version.
    p = s.find ('/', b); // End of toolchain version.

    if (p == string::npos)
      throw invalid_argument ("no timestamp");

    version toolchain_version (parse_version ("toolchain version"));

    id = build_id (package_id (move (name), package_version),
                   move (config),
                   toolchain_version);

    if (id.configuration.empty ())
      throw invalid_argument ("empty configuration name");

    try
    {
      size_t tsn;
      string ts (s, p + 1);

      session_timestamp = timestamp (
        chrono::duration_cast<timestamp::duration> (
          chrono::nanoseconds (stoull (ts, &tsn))));

      if (tsn != ts.size ())
        throw invalid_argument ("trailing junk");
    }
    // Handle invalid_argument or out_of_range (both derive from logic_error),
    // that can be thrown by stoull().
    //
    catch (const logic_error& e)
    {
      throw invalid_argument (string ("invalid timestamp: ") + e.what ());
    }
  }
  catch (const invalid_argument& e)
  {
    throw invalid_request (400, string ("invalid session: ") + e.what ());
  }

  // If the session expired (no such configuration, package, etc), then we log
  // this case with the warning severity and respond with the 200 HTTP code as
  // if the session is valid. The thinking is that this is a problem with the
  // controller's setup (expires too fast), not with the agent's.
  //
  auto warn_expired = [&rqm, &warn] (const string& d)
  {
    warn << "session '" << rqm.session << "' expired: " << d;
  };

  // Make sure the build configuration still exists.
  //
  auto i (
    find_if (
      build_conf_->begin (), build_conf_->end (),
      [&id] (const build_config& c) {return c.name == id.configuration;}));

  if (i == build_conf_->end ())
  {
    warn_expired ("no build configuration");
    return true;
  }

  // Load the built package (if present).
  //
  shared_ptr<package> p;
  {
    transaction t (package_db_->begin ());
    p = package_db_->find<package> (id.package);
    t.commit ();
  }

  if (p == nullptr)
  {
    warn_expired ("no package");
    return true;
  }

  // Load and update the package build configuration (if present).
  //
  shared_ptr<build> b;
  optional<result_status> prev_status;
  bool notify (false);

  {
    transaction t (build_db_->begin ());
    b = build_db_->find<build> (id);

    if (b == nullptr)
      warn_expired ("no package configuration");
    else if (b->state != build_state::testing)
      warn_expired ("package configuration state is " + to_string (b->state));
    else if (b->timestamp != session_timestamp)
      warn_expired ("non-matching timestamp");
    else
    {
      // Don's send email for the success-to-success status change, unless the
      // build was forced.
      //
      notify = !(rqm.result.status == result_status::success &&
                 b->status && *b->status == rqm.result.status && !b->forced);

      prev_status = move (b->status);

      b->state = build_state::tested;
      b->status = rqm.result.status;
      b->forced = false;

      // Mark the section as loaded, so results are updated.
      //
      b->results_section.load ();
      b->results = move (rqm.result.results);

      b->timestamp = timestamp::clock::now ();

      build_db_->update (b);
    }

    t.commit ();
  }

  // Don't send the notification email if the empty package build email is
  // specified.
  //
  const optional<email>& build_email (p->build_email);
  if (!notify || (build_email && build_email->empty ()))
    return true;

  assert (b != nullptr);

  // Send email to the package owner.
  //
  try
  {
    string subj (to_string (*b->status) + ": " + b->package_name + '/' +
                 b->package_version.string () + '/' + b->configuration + '/' +
                 b->toolchain_name + '-' + b->toolchain_version.string ());

    // If the package build address is not specified, then it is assumed to be
    // the same as the package email address, if specified, otherwise as the
    // project email address.
    //
    const string& to (build_email ? *build_email
                      : p->package_email
                        ? *p->package_email
                        : p->email);

    auto print_args = [&trace, this] (const char* args[], size_t n)
    {
      l2 ([&]{trace << process_args {args, n};});
    };

    // Redirect the diagnostics to webserver error log.
    //
    // Note: if using this somewhere else, then need to factor out all this
    // exit status handling code.
    //
    sendmail sm (print_args,
                 2,
                 options_->email (),
                 subj,
                 {to});

    if (b->results.empty ())
      sm.out << "No operations results available." << endl;
    else
    {
      string url (options_->host () + options_->root ().representation ());
      string pkg (mime_url_encode (b->package_name));
      string cfg (mime_url_encode (b->configuration));

      // Note that '+' is the only package version character that potentially
      // needs to be url-encoded, and only in the query part of the URL.
      // However, we print the package version either as part of URL path or
      // as the build-force URL query part (where it is not encoded by
      // design).
      //
      const version& pvr (b->package_version);
      const version& tvr (b->toolchain_version);
      ostream& os (sm.out);

      assert (b->status);
      os << "combined: " << *b->status << endl << endl
         << "  " << url << pkg << '/' << pvr << "/log/" << cfg << '/' << tvr
         << endl << endl;

      for (const auto& r: b->results)
        os << r.operation << ": " << r.status << endl << endl
           << "  " << url << pkg << '/' << pvr << "/log/" << cfg << '/'
           << tvr << '/' << r.operation << endl << endl;

      os << "Force rebuild (enter the reason, use '+' instead of spaces):"
         << endl << endl
         << "  " << options_->host () << options_->root () << "?build-force&p="
         << pkg << "&v=" << pvr << "&c=" << cfg << "&t=" << tvr << "&reason="
         << endl;
    }

    sm.out.close ();

    if (!sm.wait ())
    {
      diag_record dr (error);
      dr << "sendmail ";

      assert (sm.exit);
      const process_exit& e (*sm.exit);

      if (e.normal ())
        dr << "exited with code " << static_cast<uint16_t> (e.code ());
      else
      {
        dr << "terminated abnormally: " << e.description ();

        if (e.core ())
          dr << " (core dumped)";
      }
    }
  }
  // Handle process_error and io_error (both derive from system_error).
  //
  catch (const system_error& e)
  {
    error << "sendmail error: " << e;
  }

  return true;
}