aboutsummaryrefslogtreecommitdiff
path: root/brep/module.cxx
blob: 68177b1f8b87bd8a2b6be0ac2c4578ecaa491821 (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
// file      : brep/module.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2015 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <brep/module>

#include <httpd.h>
#include <http_log.h>

#include <ostream>
#include <sstream>
#include <cstring>    // strchr()
#include <stdexcept>
#include <functional> // bind()

#include <web/module>
#include <web/apache/log>

#include <brep/types>
#include <brep/utility>
#include <brep/options>

using namespace std;
using namespace placeholders; // For std::bind's _1, etc.

namespace brep
{
  using namespace cli;

  // module
  //
  void module::
  handle (request& rq, response& rs, log& l)
  {
    assert (loaded_);

    log_ = &l;

    try
    {
      handle (rq, rs);
    }
    catch (const server_error& e)
    {
      log_write (e.data);

      try
      {
        static const char* sev_str[] = {"error", "warning", "info", "trace"};
        ostream& o (rs.content (500, "text/plain;charset=utf-8"));

        for (const auto& d: e.data)
        {
          string name;

          try
          {
            name = func_name (d.name);
          }
          catch (const invalid_argument&)
          {
            // Log "pretty" function description, see in log file & fix.
            name = d.name;
          }

          o << name << ": " << sev_str[static_cast<size_t> (d.sev)] << ": "
            << d.msg << endl;
        }
      }
      catch (const sequence_error&)
      {
        // We tried to return the error status/description but some
        // content has already been written. Nothing we can do about
        // it.
      }
    }
  }

  // Parse options with a cli-generated scanner. Options verb and conf are
  // recognized by brep::module::init while others to be interpreted by the
  // derived class init method. If there is an option which can not be
  // interpreted not by brep::module::init nor by derived class init method
  // then web server is terminated with a corresponding error message being
  // logged.
  //
  void module::
  init (const name_values& options, log& log)
  {
    assert (!loaded_);

    log_ = &log;
    vector<const char*> argv;

    for (const auto& nv: options)
    {
      argv.push_back (nv.name.c_str ());

      if (nv.value)
        argv.push_back (nv.value->c_str ());
    }

    int argc (argv.size ());

    try
    {
      {
        // Read module implementation configuration.
        //
        argv_file_scanner s (0,
                             argc,
                             const_cast<char**> (argv.data ()),
                             "conf");

        init (s);
      }

      // Read brep::module configuration.
      //
      argv_file_scanner s (0,
                           argc,
                           const_cast<char**> (argv.data ()),
                           "conf");

      options::module o (s, unknown_mode::skip, unknown_mode::skip);
      verb_ = o.verb ();
      loaded_ = true;
    }
    catch (const server_error& e)
    {
      log_write (e.data);
      throw runtime_error ("initialization failed");
    }
    catch (const cli::exception& e)
    {
      ostringstream o;
      e.print (o);
      throw runtime_error (o.str ());
    }
  }

  module::
  module (): log_writer_ (bind (&module::log_write, this, _1)) {}

  // Custom copy constructor is required to initialize log_writer_ properly.
  //
  module::
  module (const module& m): module () {verb_ = m.verb_; loaded_ = m.loaded_;}

// For function func declared like this:
// using B = std::string (*)(int);
// using A = B (*)(int,int);
// A func(B (*)(char),B (*)(wchar_t));
// __PRETTY_FUNCTION__ looks like this:
// virtual std::string (* (* brep::search::func(std::string (* (*)(char))(int)
// ,std::string (* (*)(wchar_t))(int)) const)(int, int))(int)
//
  string module::
  func_name (const char* pretty_name)
  {
    const char* e (strchr (pretty_name, ')'));

    if (e && e > pretty_name)
    {
      // Position e at last matching '(' which is the beginning of the
      // argument list..
      //
      size_t d (1);

      do
      {
        switch (*--e)
        {
        case ')': ++d; break;
        case '(': --d; break;
        }
      }
      while (d && e > pretty_name);

      if (!d && e > pretty_name)
      {
        // Position e at the character following the function name.
        //
        while (e > pretty_name &&
               (*e != '(' || *(e - 1) == ' ' || *(e - 1) == ')'))
          --e;

        if (e > pretty_name)
        {
          // Position b at the beginning of the qualified function name.
          //
          const char* b (e);
          while (--b > pretty_name && *b != ' ');
          if (*b == ' ') ++b;

          return string (b, e - b);
        }
      }
    }

    throw invalid_argument ("::brep::module::func_name");
  }

  void module::
  log_write (const diag_data& d) const
  {
    if (log_ == nullptr)
      return; // No backend yet.

    //@@ Cast log_ to apache::log and write the records.
    //
    auto al (dynamic_cast<::web::apache::log*> (log_));

    if (al)
    {
      // Considered using lambda for mapping but looks too verbose while can
      // be a bit safer in runtime.
      //
      static int s[] = {APLOG_ERR, APLOG_WARNING, APLOG_INFO, APLOG_TRACE1};

      for (const auto& e: d)
      {
        string name;

        try
        {
          name = func_name (e.name);
        }
        catch (const invalid_argument&)
        {
          // Log "pretty" function description, see in log file & fix.
          name = e.name;
        }

        al->write (e.loc.file.c_str (),
                   e.loc.line,
                   name.c_str (),
                   s[static_cast<size_t> (e.sev)],
                   e.msg.c_str ());
      }
    }
  }

  // module::param_scanner
  //
  module::param_scanner::
  param_scanner (const name_values& nv) noexcept
      : name_values_ (nv),
        i_ (nv.begin ()),
        name_ (true)
  {
  }

  bool module::param_scanner::
  more ()
  {
    return i_ != name_values_.end ();
  }

  const char* module::param_scanner::
  peek ()
  {
    if (i_ != name_values_.end ())
      return name_ ? i_->name.c_str () : i_->value->c_str ();
    else
      throw eos_reached ();
  }

  const char* module::param_scanner::
  next ()
  {
    if (i_ != name_values_.end ())
    {
      const char* r (name_ ? i_->name.c_str () : i_->value->c_str ());
      skip ();
      return r;
    }
    else
      throw eos_reached ();
  }

  void module::param_scanner::
  skip ()
  {
    if (i_ != name_values_.end ())
    {
      if (name_)
      {
        if (i_->value)
          name_ = false;
        else
          ++i_;
      }
      else
      {
        ++i_;
        name_ = true;
      }
    }
    else
      throw eos_reached ();
  }
}