-
Notifications
You must be signed in to change notification settings - Fork 42
/
job.cpp
392 lines (324 loc) · 9.39 KB
/
job.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
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
386
387
388
389
390
391
392
//////////////////////////////////////////////////////////////////////////
//
// pgAgent - PostgreSQL Tools
//
// Copyright (C) 2002 - 2014 The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// job.cpp - pgAgent job
//
//////////////////////////////////////////////////////////////////////////
#include "pgAgent.h"
#include <wx/file.h>
#include <wx/filefn.h>
#include <wx/filename.h>
#include <wx/process.h>
#include <sys/types.h>
#ifndef __WIN32__
#include <errno.h>
#include <sys/wait.h>
#endif
Job::Job(DBconn *conn, const wxString &jid)
{
threadConn = conn;
jobid = jid;
status = wxT("");
LogMessage(wxString::Format(_("Starting job: %s"), jobid.c_str()), LOG_DEBUG);
int rc = threadConn->ExecuteVoid(
wxT("UPDATE pgagent.pga_job SET jobagentid=") + backendPid + wxT(", joblastrun=now() ")
wxT(" WHERE jobagentid IS NULL AND jobid=") + jobid);
if (rc == 1)
{
DBresult *id = threadConn->Execute(
wxT("SELECT nextval('pgagent.pga_joblog_jlgid_seq') AS id"));
if (id)
{
logid = id->GetString(wxT("id"));
DBresult *res = threadConn->Execute(
wxT("INSERT INTO pgagent.pga_joblog(jlgid, jlgjobid, jlgstatus) ")
wxT("VALUES (") + logid + wxT(", ") + jobid + wxT(", 'r')"));
if (res)
{
status = wxT("r");
delete res;
}
delete id;
}
}
}
Job::~Job()
{
if (status != wxT(""))
{
threadConn->ExecuteVoid(
wxT("UPDATE pgagent.pga_joblog ")
wxT(" SET jlgstatus='") + status + wxT("', jlgduration=now() - jlgstart ")
wxT(" WHERE jlgid=") + logid + wxT(";\n")
wxT("UPDATE pgagent.pga_job ")
wxT(" SET jobagentid=NULL, jobnextrun=NULL ")
wxT(" WHERE jobid=") + jobid
);
}
threadConn->Return();
LogMessage(wxString::Format(_("Completed job: %s"), jobid.c_str()), LOG_DEBUG);
}
int Job::Execute()
{
int rc = 0;
bool succeeded = false;
DBresult *steps = threadConn->Execute(
wxT("SELECT * ")
wxT(" FROM pgagent.pga_jobstep ")
wxT(" WHERE jstenabled ")
wxT(" AND jstjobid=") + jobid +
wxT(" ORDER BY jstname, jstid"));
if (!steps)
{
status = wxT("i");
return -1;
}
while (steps->HasData())
{
DBconn *stepConn;
wxString jslid, stepid, jpecode, output;
stepid = steps->GetString(wxT("jstid"));
DBresult *id = threadConn->Execute(
wxT("SELECT nextval('pgagent.pga_jobsteplog_jslid_seq') AS id"));
if (id)
{
jslid = id->GetString(wxT("id"));
DBresult *res = threadConn->Execute(
wxT("INSERT INTO pgagent.pga_jobsteplog(jslid, jsljlgid, jsljstid, jslstatus) ")
wxT("SELECT ") + jslid + wxT(", ") + logid + wxT(", ") + stepid + wxT(", 'r'")
wxT(" FROM pgagent.pga_jobstep WHERE jstid=") + stepid);
if (res)
{
rc = res->RowsAffected();
delete res;
}
else
rc = -1;
}
delete id;
if (rc != 1)
{
status = wxT("i");
return -1;
}
switch ((int) steps->GetString(wxT("jstkind"))[0])
{
case 's':
{
wxString jstdbname = steps->GetString(wxT("jstdbname"));
wxString jstconnstr = steps->GetString(wxT("jstconnstr"));
stepConn = DBconn::Get(jstconnstr, jstdbname);
if (stepConn)
{
LogMessage(wxString::Format(_("Executing SQL step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
rc = stepConn->ExecuteVoid(steps->GetString(wxT("jstcode")));
succeeded = stepConn->LastCommandOk();
output = stepConn->GetLastError();
stepConn->Return();
}
else
{
output = _("Couldn't get a connection to the database!");
succeeded = false;
}
break;
}
case 'b':
{
// Batch jobs are more complex thank SQL, for obvious reasons...
LogMessage(wxString::Format(_("Executing batch step %s (part of job %s)"), stepid.c_str(), jobid.c_str()), LOG_DEBUG);
// Get a temporary filename, then reuse it to create an empty directory.
wxString dirname = wxFileName::CreateTempFileName(wxT("pga_"));
if (dirname.Length() == 0)
{
output = _("Couldn't get a temporary filename!");
LogMessage(_("Couldn't get a temporary filename!"), LOG_WARNING);
rc = -1;
break;
}
;
if (!wxRemoveFile(dirname))
{
output.Printf(_("Couldn't remove temporary file: %s"), dirname.c_str());
LogMessage(output, LOG_WARNING);
rc = -1;
break;
}
if (!wxMkdir(dirname, 0700))
{
output.Printf(_("Couldn't create temporary directory: %s"), dirname.c_str());
LogMessage(output, LOG_WARNING);
rc = -1;
break;
}
#ifdef __WIN32__
wxString filename = dirname + wxT("\\") + jobid + wxT("_") + stepid + wxT(".bat");
#else
wxString filename = dirname + wxT("/") + jobid + wxT("_") + stepid + wxT(".scr");
#endif
// Write the script
wxFile *file = new wxFile();
if (!file->Create(filename, true, wxS_IRUSR | wxS_IWUSR | wxS_IXUSR))
{
output.Printf(_("Couldn't create temporary script file: %s"), filename.c_str());
LogMessage(output, LOG_WARNING);
rc = -1;
break;
}
if (!file->Open(filename, wxFile::write))
{
output.Printf(_("Couldn't open temporary script file: %s"), filename.c_str());
LogMessage(output, LOG_WARNING);
wxRemoveFile(filename);
wxRmdir(dirname);
rc = -1;
break;
}
wxString code = steps->GetString(wxT("jstcode"));
// Cleanup the code. If we're on Windows, we need to make all line ends \r\n,
// If we're on Unix, we need \n
code.Replace(wxT("\r\n"), wxT("\n"));
#ifdef __WIN32__
code.Replace(wxT("\n"), wxT("\r\n"));
#endif
if (!file->Write(code))
{
output.Printf(_("Couldn't write to temporary script file: %s"), filename.c_str());
LogMessage(output, LOG_WARNING);
wxRemoveFile(filename);
wxRmdir(dirname);
rc = -1;
break;
}
file->Close();
LogMessage(wxString::Format(_("Executing script file: %s"), filename.c_str()), LOG_DEBUG);
// Execute the file and capture the output
#ifdef __WIN32__
// The Windows way
HANDLE h_script, h_process;
DWORD dwRead;
char chBuf[4098];
h_script = win32_popen_r(filename.wc_str(), h_process);
if (!h_script)
{
output.Printf(_("Couldn't execute script: %s, GetLastError() returned %d, errno = %d"), filename.c_str(), GetLastError(), errno);
LogMessage(output, LOG_WARNING);
CloseHandle(h_process);
rc = -1;
break;
}
// Read output from the child process
if (h_script)
{
for (;;)
{
if(!ReadFile(h_script, chBuf, 4096, &dwRead, NULL) || dwRead == 0)
break;
chBuf[dwRead] = 0;
output += wxString::FromAscii(chBuf);
}
}
GetExitCodeProcess(h_process, (LPDWORD)&rc);
CloseHandle(h_process);
CloseHandle(h_script);
#else
// The *nix way.
FILE *fp_script;
char buf[4098];
fp_script = popen(filename.mb_str(wxConvUTF8), "r");
if (!fp_script)
{
output.Printf(_("Couldn't execute script: %s, errno = %d"), filename.c_str(), errno);
LogMessage(output, LOG_WARNING);
rc = -1;
break;
}
while(!feof(fp_script))
{
if (fgets(buf, 4096, fp_script) != NULL)
output += wxString::FromAscii(buf);
}
rc = pclose(fp_script);
if (WIFEXITED(rc))
rc = WEXITSTATUS(rc);
else
rc = -1;
#endif
// set success status for batch runs, be pessimistic by default
LogMessage(wxString::Format(_("Script return code: %d"), rc), LOG_DEBUG);
if (rc == 0)
succeeded = true;
// Delete the file/directory. If we fail, don't overwrite the script output in the log, just throw warnings.
if (!wxRemoveFile(filename))
{
LogMessage(wxString::Format(_("Couldn't remove temporary script file: %s"), filename.c_str()), LOG_WARNING);
wxRmdir(dirname);
break;
}
if (!wxRmdir(dirname))
{
LogMessage(wxString::Format(_("Couldn't remove temporary directory: "), dirname.c_str()), LOG_WARNING);
break;
}
break;
}
default:
{
output = _("Invalid step type!");
status = wxT("i");
return -1;
}
}
wxString stepstatus;
if (succeeded)
stepstatus = wxT("s");
else
stepstatus = steps->GetString(wxT("jstonerror"));
rc = threadConn->ExecuteVoid(
wxT("UPDATE pgagent.pga_jobsteplog ")
wxT(" SET jslduration = now() - jslstart, ")
wxT(" jslresult = ") + NumToStr(rc) + wxT(", jslstatus = '") + stepstatus + wxT("', ")
wxT(" jsloutput = ") + threadConn->qtDbString(output) + wxT(" ")
wxT(" WHERE jslid=") + jslid);
if (rc != 1 || stepstatus == wxT("f"))
{
status = wxT("f");
return -1;
}
steps->MoveNext();
}
delete steps;
status = wxT("s");
return 0;
}
JobThread::JobThread(const wxString &jid)
: wxThread(wxTHREAD_DETACHED)
{
LogMessage(wxString::Format(_("Creating job thread for job %s"), jid.c_str()), LOG_DEBUG);
runnable = false;
jobid = jid;
DBconn *threadConn = DBconn::Get(DBconn::GetBasicConnectString(), serviceDBname);
if (threadConn)
{
job = new Job(threadConn, jobid);
if (job->Runnable())
runnable = true;
}
}
JobThread::~JobThread()
{
LogMessage(wxString::Format(_("Destroying job thread for job %s"), jobid.c_str()), LOG_DEBUG);
}
void *JobThread::Entry()
{
if (runnable)
{
job->Execute();
delete job;
}
return(NULL);
}