forked from pschlan/cron-job.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.cpp
233 lines (194 loc) · 6.1 KB
/
App.cpp
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
/*
* chronos, the cron-job.org execution daemon
* Copyright (C) 2017 Patrick Schlangen <[email protected]>
*
* This program 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 2
* of the License, or (at your option) any later version.
*
*/
#include "App.h"
#include <stdexcept>
#include <iostream>
#include <functional>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <curl/curl.h>
#include "UpdateThread.h"
#include "WorkerThread.h"
#include "Config.h"
using namespace Chronos;
App *App::instance = nullptr;
App::App(int argc, char *argv[])
{
if(App::instance != nullptr)
throw std::runtime_error("App instance already exists");
if(argc != 2)
throw std::runtime_error(std::string("Usage: ") + std::string(argv[0]) + std::string(" [config-file]"));
this->config = std::make_shared<Config>(argv[1]);
App::instance = this;
}
App::~App()
{
App::instance = nullptr;
}
App *App::getInstance()
{
if(App::instance == nullptr)
throw std::runtime_error("No app instance available");
return(App::instance);
}
void App::processJobs(int hour, int minute, int month, int mday, int wday, int year, time_t timestamp)
{
std::cout << "App::processJobs(): Called for "
<< "hour = " << hour << ", "
<< "minute = " << minute << ", "
<< "month = " << month << ", "
<< "mday = " << mday << ", "
<< "wday = " << wday << ", "
<< "timestamp = " << timestamp
<< std::endl;
auto res = db->query("SELECT TRIM(`url`),`job`.`jobid`,`auth_enable`,`auth_user`,`auth_pass`,`notify_failure`,`notify_success`,`notify_disable`,`fail_counter`,`save_responses`,`userid`,`request_method`,COUNT(`job_header`.`jobheaderid`),`job_body`.`body` FROM `job` "
"INNER JOIN `job_hours` ON `job_hours`.`jobid`=`job`.`jobid` "
"INNER JOIN `job_mdays` ON `job_mdays`.`jobid`=`job`.`jobid` "
"INNER JOIN `job_wdays` ON `job_wdays`.`jobid`=`job`.`jobid` "
"INNER JOIN `job_minutes` ON `job_minutes`.`jobid`=`job`.`jobid` "
"INNER JOIN `job_months` ON `job_months`.`jobid`=`job`.`jobid` "
"LEFT JOIN `job_header` ON `job_header`.`jobid`=`job`.`jobid` "
"LEFT JOIN `job_body` ON `job_body`.`jobid`=`job`.`jobid` "
"WHERE (`hour`=-1 OR `hour`=%d) "
"AND (`minute`=-1 OR `minute`=%d) "
"AND (`mday`=-1 OR `mday`=%d) "
"AND (`wday`=-1 OR `wday`=%d) "
"AND (`month`=-1 OR `month`=%d) "
"AND `enabled`=1 "
"GROUP BY `job`.`jobid` "
"ORDER BY `fail_counter` ASC, `last_duration` ASC",
hour, minute, mday, wday, month);
int jobCount = res->numRows();
std::cout << "App::processJobs(): " << jobCount << " jobs found" << std::endl;
if(jobCount > 0)
{
std::shared_ptr<WorkerThread> wt = std::make_shared<WorkerThread>(mday, month, year, hour, minute);
MYSQL_ROW row;
while((row = res->fetchRow()) != nullptr)
{
HTTPRequest *req = HTTPRequest::fromURL(row[0], atoi(row[10]));
req->result->jobID = atoi(row[1]);
req->result->datePlanned = (uint64_t)timestamp * 1000;
req->result->notifyFailure = strcmp(row[5], "1") == 0;
req->result->notifySuccess = strcmp(row[6], "1") == 0;
req->result->notifyDisable = strcmp(row[7], "1") == 0;
req->result->oldFailCounter = atoi(row[8]);
req->result->saveResponses = strcmp(row[9], "1") == 0;
if(atoi(row[2]) == 1)
{
req->useAuth = true;
req->authUsername = row[3];
req->authPassword = row[4];
}
req->requestMethod = static_cast<RequestMethod>(atoi(row[11]));
if(row[12] != NULL && atoi(row[12]) > 0)
{
auto headerRes = db->query("SELECT `key`,`value` FROM `job_header` WHERE `jobid`=%s",
row[1]);
while(MYSQL_ROW row = headerRes->fetchRow())
{
req->requestHeaders.push_back({ std::string(row[0]), std::string(row[1]) });
}
}
if(row[13] != NULL)
{
req->requestBody = row[13];
}
wt->addJob(req);
}
std::cout << "App::processJobs(): Starting worker thread" << std::endl;
wt->run();
}
res.reset();
std::cout << "App::processJobs(): Finished" << std::endl;
}
void App::signalHandler(int sig)
{
if(sig == SIGINT)
App::getInstance()->stop = true;
}
int App::run()
{
curl_global_init(CURL_GLOBAL_ALL);
MySQL_DB::libInit();
db = createMySQLConnection();
startUpdateThread();
signal(SIGINT, App::signalHandler);
bool firstLoop = true;
struct tm lastTime = { 0 };
int jitterCorrectionOffset = calcJitterCorrectionOffset();
while(!stop)
{
time_t currentTime = time(nullptr) + jitterCorrectionOffset;
struct tm *t = localtime(¤tTime);
if(t->tm_min > lastTime.tm_min
|| t->tm_hour > lastTime.tm_hour
|| t->tm_mday > lastTime.tm_mday
|| t->tm_mon > lastTime.tm_mon
|| t->tm_year > lastTime.tm_year)
{
// update last time
memcpy(&lastTime, t, sizeof(struct tm));
if(!firstLoop || t->tm_sec == 59 - jitterCorrectionOffset)
{
processJobs(t->tm_hour, t->tm_min, t->tm_mon+1, t->tm_mday, t->tm_wday, t->tm_year+1900, currentTime - t->tm_sec);
jitterCorrectionOffset = calcJitterCorrectionOffset();
}
firstLoop = false;
}
else
{
usleep(100*1000);
}
}
this->stopUpdateThread();
MySQL_DB::libCleanup();
curl_global_cleanup();
return(1);
}
int App::calcJitterCorrectionOffset()
{
return 1; //! @todo
}
void App::updateThreadMain()
{
try
{
updateThreadObj = std::make_unique<UpdateThread>();
updateThreadObj->run();
updateThreadObj.reset();
}
catch(const std::runtime_error &ex)
{
std::cout << "Update thread runtime error: " << ex.what() << std::endl;
stop = true;
}
}
void App::startUpdateThread()
{
updateThread = std::thread(std::bind(&App::updateThreadMain, this));
}
void App::stopUpdateThread()
{
updateThreadObj->stopThread();
updateThread.join();
}
std::unique_ptr<MySQL_DB> App::createMySQLConnection()
{
return(std::make_unique<MySQL_DB>(config->get("mysql_host"),
config->get("mysql_user"),
config->get("mysql_pass"),
config->get("mysql_db"),
config->get("mysql_sock")));
}