File: trackalert-lua.cc

package info (click to toggle)
weakforced 3.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,040 kB
  • sloc: cpp: 20,397; python: 2,002; sh: 700; makefile: 432
file content (320 lines) | stat: -rw-r--r-- 10,855 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
/*
 * This file is part of PowerDNS or weakforced.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 3 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "trackalert.hh"
#include "wforce-common-lua.hh"
#include <thread>
#include "dolog.hh"
#include "sodcrypto.hh"
#include "base64.hh"
#include "trackalert-luastate.hh"
#include "perf-stats.hh"
#include "wforce-webserver.hh"
#include "trackalert-web.hh"
#include <fstream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include "common-lua.hh"
#include "prometheus.hh"

using std::thread;

static vector<std::function<void(void)>>* launchWork;

// lua functions are split into three groups:
// 1) Those which are only applicable as "config/setup" (single global lua state) (they are defined as blank/empty functions otherwise) 
// 2) Those which are only applicable inside the "report" and "background" functions (multiple lua states running in different threads), which are defined as blank/empty otherwise
// 3) Those which are applicable to both states
// Functions that are in 2) or 3) MUST be thread-safe. The rest not as they are called at startup.
// We have a single lua config file for historical reasons, hence the somewhat complex structure of this function
// The Lua state and type is passed via "multi_lua" (true means it's one of the multiple states, false means it's the global lua config state) 
vector<std::function<void(void)>> setupLua(bool client, bool multi_lua,
                                           LuaContext& c_lua,
                                           report_t& report_func,
                                           bg_func_map_t* bg_func_map,
                                           CustomFuncMap& custom_func_map,
                                           const std::string& config)
{
  launchWork= new vector<std::function<void(void)>>();

  setupCommonLua(client, multi_lua, c_lua, config);
  setupWforceCommonLua(client, multi_lua, c_lua, launchWork);

  if (!multi_lua) {
    c_lua.writeFunction("webserver", [client](const std::string& address, const std::string& password) {
      if (client)
        return;
      warnlog("Warning - webserver() configuration command is deprecated in favour of addListener() and will be removed in a future version");
      ComboAddress local;
      try {
        local = ComboAddress(address);
      }
      catch (const WforceException& e) {
        errlog("webserver() error parsing address/port [%s]. Make sure to use IP addresses not hostnames", address);
        return;
      }
      g_webserver.setBasicAuthPassword(password);
      g_webserver.addSimpleListener(local.toString(), local.getPort());
      auto launch =[]() {
        thread t(WforceWebserver::start, &g_webserver);
        t.detach();
      };
      if (launchWork)
        launchWork->push_back(launch);
      else
        launch();
    });
  }
  else {
    c_lua.writeFunction("webserver", [](const std::string& address, const std::string& password) { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("setWebserverPassword", [](const std::string& password) {
      g_webserver.setBasicAuthPassword(password);
    });
  }
  else {
    c_lua.writeFunction("setWebserverPassword", [](const std::string& password) { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("stats", []() {
      boost::format fmt("%d reports\n");
      g_outputBuffer = (fmt % g_stats.reports).str();
    });
  }
  else {
    c_lua.writeFunction("stats", []() { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("setNumReportThreads", [](int numThreads) {
      // XXX this function is deprecated - use setNumWorkerThreads instead
      infolog("setNumReportThreads is deprecated - use setNumWorkerThreads() instead");
    });
  }
  else {
    c_lua.writeFunction("setNumReportThreads", [](int numThreads) { });
  }


  if (multi_lua) {
    c_lua.writeFunction("setReport", [&report_func](report_t func) { report_func=func;});
  }
  else {
    c_lua.writeFunction("setReport", [](report_t func) { });
  }

  if (multi_lua) {
    c_lua.writeFunction("setBackground", [bg_func_map](const std::string& func_name, background_t func) {
      bg_func_map->insert(std::make_pair(func_name, func));
    });
  }
  else {
    c_lua.writeFunction("setBackground",  [](const std::string& func_name, background_t func) { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("setNumSchedulerThreads", [](int numThreads) {
      g_bg_schedulerp->setNumThreads(numThreads);
    });
  }
  else {
    c_lua.writeFunction("setNumSchedulerThreads", [](int numThreads) { });
  }

  if (!multi_lua && !client) {
    c_lua.writeFunction("cronScheduleBackgroundFunc", [](const std::string& cron_str, const std::string& func_name) {
      g_bg_schedulerp->cron(cron_str, [func_name] {
        try {
          g_luamultip->background(func_name);
        }
        catch(LuaContext::ExecutionErrorException& e) {
          try {
            std::rethrow_if_nested(e);
            errlog("Lua background function [%s] exception: %s", func_name, e.what());
          }
          catch (const std::exception& ne) {
            errlog("Exception in background function [%s] exception: %s", func_name, ne.what());
          }
          catch (const WforceException& ne) {
            errlog("Exception in background function [%s] exception: %s", func_name, ne.reason);
          }
        }
      });
    });
  }
  else {
    c_lua.writeFunction("cronScheduleBackgroundFunc", [](const std::string& cron_str, const std::string& func_name) { });
  }

  if (!multi_lua && !client) {
    c_lua.writeFunction("intervalScheduleBackgroundFunc", [](const std::string& duration_str, const std::string& func_name) {
      std::stringstream ss(duration_str);
      boost::posix_time::time_duration td;
      if (ss >> td) {
        g_bg_schedulerp->interval(std::chrono::seconds(td.total_seconds()), [func_name] {
          try {
            g_luamultip->background(func_name);
          }
          catch(LuaContext::ExecutionErrorException& e) {
            try {
              std::rethrow_if_nested(e);
              errlog("Lua background function [%s] exception: %s", func_name, e.what());
            }
            catch (const std::exception& ne) {
              errlog("Exception in background function [%s] exception: %s", func_name, ne.what());
            }
            catch (const WforceException& ne) {
              errlog("Exception in background function [%s] exception: %s", func_name, ne.reason);
            }
          }
        });
      }
      else {
        std::string errmsg = "Cannot parse duration string: " + duration_str;
        errlog(errmsg.c_str());
        throw WforceException(errmsg);
      }
    });
  }
  else {
    c_lua.writeFunction("intervalScheduleBackgroundFunc", [](const std::string& cron_str, const std::string& func_name) { });
  }

  c_lua.writeFunction("durationToSeconds", [](const std::string& duration_str) {
    std::stringstream ss(duration_str);
    boost::posix_time::time_duration td;
    if (ss >> td) {
      return (long)td.total_seconds();
    }
    else {
      errlog("Cannot parse duration string: %s",duration_str);
      return (long)0;
    }
  });

  c_lua.registerMember("attrs", &CustomFuncArgs::attrs);
  c_lua.registerMember("attrs_mv", &CustomFuncArgs::attrs_mv);

  c_lua.writeFunction("setCustomEndpoint", [&custom_func_map, multi_lua, client](const std::string& f_name, custom_func_t func) {
    CustomFuncMapObject cobj;
    cobj.c_func = func;
    custom_func_map.insert(std::make_pair(f_name, cobj));
    if (!multi_lua && !client) {
      addCommandStat(f_name);
      addPrometheusCommandMetric(f_name);
      // register a webserver command
      g_webserver.registerFunc(f_name, HTTPVerb::POST, WforceWSFunc(parseCustomCmd));
      noticelog("Registering custom endpoint [%s]", f_name);
    }
  });

  if (!multi_lua) {
    c_lua.writeFunction("showCustomEndpoints", []() {
      boost::format fmt("%-30.30s \n");
      g_outputBuffer = (fmt % "Custom Endpoint").str();
      for (const auto& i : g_custom_func_map) {
        g_outputBuffer += (fmt % i.first).str();
      }
    });
  }
  else {
    c_lua.writeFunction("showCustomEndpoints", []() { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("showVersion", []() {
      g_outputBuffer = "trackalert " + std::string(VERSION) + "\n";
    });
  }
  else {
    c_lua.writeFunction("showVersion", []() { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("setKey", [](const std::string& key) -> bool {
      string newkey;
      if(B64Decode(key, newkey) < 0) {
        g_outputBuffer=string("Unable to decode ")+key+" as Base64";
        errlog("%s", g_outputBuffer);
        return false;
      }
      else {
        g_key = newkey;
        return true;
      }
    });
  }
  else {
    c_lua.writeFunction("setKey", [](const std::string& key) { });
  }

  if (!multi_lua) {
    c_lua.writeFunction("testCrypto", [](string testmsg)
    {
      try {
        SodiumNonce sn, sn2;
        sn.init();
        sn2=sn;
        string encrypted = sodEncryptSym(testmsg, g_key, sn);
        string decrypted = sodDecryptSym(encrypted, g_key, sn2);

        sn.increment();
        sn2.increment();

        encrypted = sodEncryptSym(testmsg, g_key, sn);
        decrypted = sodDecryptSym(encrypted, g_key, sn2);

        if(testmsg == decrypted)
          g_outputBuffer="Everything is ok!\n";
        else
          g_outputBuffer="Crypto failed..\n";

      }
      catch(...) {
        g_outputBuffer="Crypto failed..\n";
      }});
  }
  else {
    c_lua.writeFunction("testCrypto", [](string testmsg) {});
  }

  std::ifstream ifs(config);
  if(!ifs)
    warnlog("Unable to read configuration from '%s'", config);
  else if (!multi_lua)
    infolog("Read configuration from '%s'", config);

  c_lua.executeCode(ifs);
  if (!multi_lua) {
    auto ret=*launchWork;
    delete launchWork;
    launchWork=0;
    return ret;
  }
  else {
    return vector<std::function<void(void)>>();
  }
}