-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
JdbcExecutorLoader.java
1585 lines (1406 loc) · 52.6 KB
/
JdbcExecutorLoader.java
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.executor;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.annotation.Inherited;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import azkaban.database.AbstractJdbcLoader;
import azkaban.executor.ExecutorLogEvent.EventType;
import azkaban.utils.FileIOUtils;
import azkaban.utils.FileIOUtils.LogData;
import azkaban.utils.GZIPUtils;
import azkaban.utils.JSONUtils;
import azkaban.utils.Pair;
import azkaban.utils.Props;
import azkaban.utils.PropsUtils;
public class JdbcExecutorLoader extends AbstractJdbcLoader implements
ExecutorLoader {
private static final Logger logger = Logger
.getLogger(JdbcExecutorLoader.class);
private EncodingType defaultEncodingType = EncodingType.GZIP;
public JdbcExecutorLoader(Props props) {
super(props);
}
public EncodingType getDefaultEncodingType() {
return defaultEncodingType;
}
public void setDefaultEncodingType(EncodingType defaultEncodingType) {
this.defaultEncodingType = defaultEncodingType;
}
@Override
public synchronized void uploadExecutableFlow(ExecutableFlow flow)
throws ExecutorManagerException {
Connection connection = getConnection();
try {
uploadExecutableFlow(connection, flow, defaultEncodingType);
} catch (IOException e) {
throw new ExecutorManagerException("Error uploading flow", e);
} finally {
DbUtils.closeQuietly(connection);
}
}
private synchronized void uploadExecutableFlow(Connection connection,
ExecutableFlow flow, EncodingType encType)
throws ExecutorManagerException, IOException {
final String INSERT_EXECUTABLE_FLOW =
"INSERT INTO execution_flows "
+ "(project_id, flow_id, version, status, submit_time, submit_user, update_time) "
+ "values (?,?,?,?,?,?,?)";
QueryRunner runner = new QueryRunner();
long submitTime = System.currentTimeMillis();
long id;
try {
flow.setStatus(Status.PREPARING);
runner.update(connection, INSERT_EXECUTABLE_FLOW, flow.getProjectId(),
flow.getFlowId(), flow.getVersion(), Status.PREPARING.getNumVal(),
submitTime, flow.getSubmitUser(), submitTime);
connection.commit();
id =
runner.query(connection, LastInsertID.LAST_INSERT_ID,
new LastInsertID());
if (id == -1l) {
throw new ExecutorManagerException(
"Execution id is not properly created.");
}
logger.info("Flow given " + flow.getFlowId() + " given id " + id);
flow.setExecutionId((int) id);
updateExecutableFlow(connection, flow, encType);
} catch (SQLException e) {
throw new ExecutorManagerException("Error creating execution.", e);
}
}
@Override
public void updateExecutableFlow(ExecutableFlow flow)
throws ExecutorManagerException {
Connection connection = this.getConnection();
try {
updateExecutableFlow(connection, flow, defaultEncodingType);
} finally {
DbUtils.closeQuietly(connection);
}
}
private void updateExecutableFlow(Connection connection, ExecutableFlow flow,
EncodingType encType) throws ExecutorManagerException {
final String UPDATE_EXECUTABLE_FLOW_DATA =
"UPDATE execution_flows "
+ "SET status=?,update_time=?,start_time=?,end_time=?,enc_type=?,flow_data=? "
+ "WHERE exec_id=?";
QueryRunner runner = new QueryRunner();
String json = JSONUtils.toJSON(flow.toObject());
byte[] data = null;
try {
byte[] stringData = json.getBytes("UTF-8");
data = stringData;
if (encType == EncodingType.GZIP) {
data = GZIPUtils.gzipBytes(stringData);
}
} catch (IOException e) {
throw new ExecutorManagerException("Error encoding the execution flow.");
}
try {
runner.update(connection, UPDATE_EXECUTABLE_FLOW_DATA, flow.getStatus()
.getNumVal(), flow.getUpdateTime(), flow.getStartTime(), flow
.getEndTime(), encType.getNumVal(), data, flow.getExecutionId());
connection.commit();
} catch (SQLException e) {
throw new ExecutorManagerException("Error updating flow.", e);
}
}
@Override
public ExecutableFlow fetchExecutableFlow(int id)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutableFlows flowHandler = new FetchExecutableFlows();
try {
List<ExecutableFlow> properties =
runner.query(FetchExecutableFlows.FETCH_EXECUTABLE_FLOW, flowHandler,
id);
if (properties.isEmpty()) {
return null;
} else {
return properties.get(0);
}
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching flow id " + id, e);
}
}
/**
*
* {@inheritDoc}
* @see azkaban.executor.ExecutorLoader#fetchQueuedFlows()
*/
@Override
public List<Pair<ExecutionReference, ExecutableFlow>> fetchQueuedFlows()
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchQueuedExecutableFlows flowHandler = new FetchQueuedExecutableFlows();
try {
List<Pair<ExecutionReference, ExecutableFlow>> flows =
runner.query(FetchQueuedExecutableFlows.FETCH_QUEUED_EXECUTABLE_FLOW,
flowHandler);
return flows;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public Map<Integer, Pair<ExecutionReference, ExecutableFlow>> fetchActiveFlows()
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchActiveExecutableFlows flowHandler = new FetchActiveExecutableFlows();
try {
Map<Integer, Pair<ExecutionReference, ExecutableFlow>> properties =
runner.query(FetchActiveExecutableFlows.FETCH_ACTIVE_EXECUTABLE_FLOW,
flowHandler);
return properties;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public int fetchNumExecutableFlows() throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
IntHandler intHandler = new IntHandler();
try {
int count = runner.query(IntHandler.NUM_EXECUTIONS, intHandler);
return count;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching num executions", e);
}
}
@Override
public int fetchNumExecutableFlows(int projectId, String flowId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
IntHandler intHandler = new IntHandler();
try {
int count =
runner.query(IntHandler.NUM_FLOW_EXECUTIONS, intHandler, projectId,
flowId);
return count;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching num executions", e);
}
}
@Override
public int fetchNumExecutableNodes(int projectId, String jobId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
IntHandler intHandler = new IntHandler();
try {
int count =
runner.query(IntHandler.NUM_JOB_EXECUTIONS, intHandler, projectId,
jobId);
return count;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching num executions", e);
}
}
@Override
public List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutableFlows flowHandler = new FetchExecutableFlows();
try {
List<ExecutableFlow> properties =
runner.query(FetchExecutableFlows.FETCH_EXECUTABLE_FLOW_HISTORY,
flowHandler, projectId, flowId, skip, num);
return properties;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public List<ExecutableFlow> fetchFlowHistory(int projectId, String flowId,
int skip, int num, Status status) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutableFlows flowHandler = new FetchExecutableFlows();
try {
List<ExecutableFlow> properties =
runner.query(FetchExecutableFlows.FETCH_EXECUTABLE_FLOW_BY_STATUS,
flowHandler, projectId, flowId, status.getNumVal(), skip, num);
return properties;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public List<ExecutableFlow> fetchFlowHistory(int skip, int num)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutableFlows flowHandler = new FetchExecutableFlows();
try {
List<ExecutableFlow> properties =
runner.query(FetchExecutableFlows.FETCH_ALL_EXECUTABLE_FLOW_HISTORY,
flowHandler, skip, num);
return properties;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public List<ExecutableFlow> fetchFlowHistory(String projContain,
String flowContains, String userNameContains, int status, long startTime,
long endTime, int skip, int num) throws ExecutorManagerException {
String query = FetchExecutableFlows.FETCH_BASE_EXECUTABLE_FLOW_QUERY;
ArrayList<Object> params = new ArrayList<Object>();
boolean first = true;
if (projContain != null && !projContain.isEmpty()) {
query += " ef JOIN projects p ON ef.project_id = p.id WHERE name LIKE ?";
params.add('%' + projContain + '%');
first = false;
}
if (flowContains != null && !flowContains.isEmpty()) {
if (first) {
query += " WHERE ";
first = false;
} else {
query += " AND ";
}
query += " flow_id LIKE ?";
params.add('%' + flowContains + '%');
}
if (userNameContains != null && !userNameContains.isEmpty()) {
if (first) {
query += " WHERE ";
first = false;
} else {
query += " AND ";
}
query += " submit_user LIKE ?";
params.add('%' + userNameContains + '%');
}
if (status != 0) {
if (first) {
query += " WHERE ";
first = false;
} else {
query += " AND ";
}
query += " status = ?";
params.add(status);
}
if (startTime > 0) {
if (first) {
query += " WHERE ";
first = false;
} else {
query += " AND ";
}
query += " start_time > ?";
params.add(startTime);
}
if (endTime > 0) {
if (first) {
query += " WHERE ";
first = false;
} else {
query += " AND ";
}
query += " end_time < ?";
params.add(endTime);
}
if (skip > -1 && num > 0) {
query += " ORDER BY exec_id DESC LIMIT ?, ?";
params.add(skip);
params.add(num);
}
QueryRunner runner = createQueryRunner();
FetchExecutableFlows flowHandler = new FetchExecutableFlows();
try {
List<ExecutableFlow> properties =
runner.query(query, flowHandler, params.toArray());
return properties;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching active flows", e);
}
}
@Override
public void addActiveExecutableReference(ExecutionReference reference)
throws ExecutorManagerException {
final String INSERT =
"INSERT INTO active_executing_flows "
+ "(exec_id, update_time) values (?,?)";
QueryRunner runner = createQueryRunner();
try {
runner.update(INSERT, reference.getExecId(), reference.getUpdateTime());
} catch (SQLException e) {
throw new ExecutorManagerException(
"Error updating active flow reference " + reference.getExecId(), e);
}
}
@Override
public void removeActiveExecutableReference(int execid)
throws ExecutorManagerException {
final String DELETE = "DELETE FROM active_executing_flows WHERE exec_id=?";
QueryRunner runner = createQueryRunner();
try {
runner.update(DELETE, execid);
} catch (SQLException e) {
throw new ExecutorManagerException(
"Error deleting active flow reference " + execid, e);
}
}
@Override
public boolean updateExecutableReference(int execId, long updateTime)
throws ExecutorManagerException {
final String DELETE =
"UPDATE active_executing_flows set update_time=? WHERE exec_id=?";
QueryRunner runner = createQueryRunner();
int updateNum = 0;
try {
updateNum = runner.update(DELETE, updateTime, execId);
} catch (SQLException e) {
throw new ExecutorManagerException(
"Error deleting active flow reference " + execId, e);
}
// Should be 1.
return updateNum > 0;
}
@Override
public void uploadExecutableNode(ExecutableNode node, Props inputProps)
throws ExecutorManagerException {
final String INSERT_EXECUTION_NODE =
"INSERT INTO execution_jobs "
+ "(exec_id, project_id, version, flow_id, job_id, start_time, "
+ "end_time, status, input_params, attempt) VALUES (?,?,?,?,?,?,?,?,?,?)";
byte[] inputParam = null;
if (inputProps != null) {
try {
String jsonString =
JSONUtils.toJSON(PropsUtils.toHierarchicalMap(inputProps));
inputParam = GZIPUtils.gzipString(jsonString, "UTF-8");
} catch (IOException e) {
throw new ExecutorManagerException("Error encoding input params");
}
}
ExecutableFlow flow = node.getExecutableFlow();
String flowId = node.getParentFlow().getFlowPath();
System.out.println("Uploading flowId " + flowId);
QueryRunner runner = createQueryRunner();
try {
runner.update(INSERT_EXECUTION_NODE, flow.getExecutionId(),
flow.getProjectId(), flow.getVersion(), flowId, node.getId(),
node.getStartTime(), node.getEndTime(), node.getStatus().getNumVal(),
inputParam, node.getAttempt());
} catch (SQLException e) {
throw new ExecutorManagerException("Error writing job " + node.getId(), e);
}
}
@Override
public void updateExecutableNode(ExecutableNode node)
throws ExecutorManagerException {
final String UPSERT_EXECUTION_NODE =
"UPDATE execution_jobs "
+ "SET start_time=?, end_time=?, status=?, output_params=? "
+ "WHERE exec_id=? AND flow_id=? AND job_id=? AND attempt=?";
byte[] outputParam = null;
Props outputProps = node.getOutputProps();
if (outputProps != null) {
try {
String jsonString =
JSONUtils.toJSON(PropsUtils.toHierarchicalMap(outputProps));
outputParam = GZIPUtils.gzipString(jsonString, "UTF-8");
} catch (IOException e) {
throw new ExecutorManagerException("Error encoding input params");
}
}
QueryRunner runner = createQueryRunner();
try {
runner.update(UPSERT_EXECUTION_NODE, node.getStartTime(), node
.getEndTime(), node.getStatus().getNumVal(), outputParam, node
.getExecutableFlow().getExecutionId(), node.getParentFlow()
.getFlowPath(), node.getId(), node.getAttempt());
} catch (SQLException e) {
throw new ExecutorManagerException("Error updating job " + node.getId(),
e);
}
}
@Override
public List<ExecutableJobInfo> fetchJobInfoAttempts(int execId, String jobId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
List<ExecutableJobInfo> info =
runner.query(
FetchExecutableJobHandler.FETCH_EXECUTABLE_NODE_ATTEMPTS,
new FetchExecutableJobHandler(), execId, jobId);
if (info == null || info.isEmpty()) {
return null;
}
return info;
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job info " + jobId, e);
}
}
@Override
public ExecutableJobInfo fetchJobInfo(int execId, String jobId, int attempts)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
List<ExecutableJobInfo> info =
runner.query(FetchExecutableJobHandler.FETCH_EXECUTABLE_NODE,
new FetchExecutableJobHandler(), execId, jobId, attempts);
if (info == null || info.isEmpty()) {
return null;
}
return info.get(0);
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job info " + jobId, e);
}
}
@Override
public Props fetchExecutionJobInputProps(int execId, String jobId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
Pair<Props, Props> props =
runner.query(
FetchExecutableJobPropsHandler.FETCH_INPUT_PARAM_EXECUTABLE_NODE,
new FetchExecutableJobPropsHandler(), execId, jobId);
return props.getFirst();
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job params " + execId
+ " " + jobId, e);
}
}
@Override
public Props fetchExecutionJobOutputProps(int execId, String jobId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
Pair<Props, Props> props =
runner
.query(
FetchExecutableJobPropsHandler.FETCH_OUTPUT_PARAM_EXECUTABLE_NODE,
new FetchExecutableJobPropsHandler(), execId, jobId);
return props.getFirst();
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job params " + execId
+ " " + jobId, e);
}
}
@Override
public Pair<Props, Props> fetchExecutionJobProps(int execId, String jobId)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
Pair<Props, Props> props =
runner
.query(
FetchExecutableJobPropsHandler.FETCH_INPUT_OUTPUT_PARAM_EXECUTABLE_NODE,
new FetchExecutableJobPropsHandler(), execId, jobId);
return props;
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job params " + execId
+ " " + jobId, e);
}
}
@Override
public List<ExecutableJobInfo> fetchJobHistory(int projectId, String jobId,
int skip, int size) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
List<ExecutableJobInfo> info =
runner.query(FetchExecutableJobHandler.FETCH_PROJECT_EXECUTABLE_NODE,
new FetchExecutableJobHandler(), projectId, jobId, skip, size);
if (info == null || info.isEmpty()) {
return null;
}
return info;
} catch (SQLException e) {
throw new ExecutorManagerException("Error querying job info " + jobId, e);
}
}
@Override
public LogData fetchLogs(int execId, String name, int attempt, int startByte,
int length) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchLogsHandler handler =
new FetchLogsHandler(startByte, length + startByte);
try {
LogData result =
runner.query(FetchLogsHandler.FETCH_LOGS, handler, execId, name,
attempt, startByte, startByte + length);
return result;
} catch (SQLException e) {
throw new ExecutorManagerException("Error fetching logs " + execId
+ " : " + name, e);
}
}
@Override
public List<Object> fetchAttachments(int execId, String jobId, int attempt)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
try {
String attachments =
runner
.query(
FetchExecutableJobAttachmentsHandler.FETCH_ATTACHMENTS_EXECUTABLE_NODE,
new FetchExecutableJobAttachmentsHandler(), execId, jobId);
if (attachments == null) {
return null;
}
@SuppressWarnings("unchecked")
List<Object> attachmentList =
(List<Object>) JSONUtils.parseJSONFromString(attachments);
return attachmentList;
} catch (IOException e) {
throw new ExecutorManagerException(
"Error converting job attachments to JSON " + jobId, e);
} catch (SQLException e) {
throw new ExecutorManagerException(
"Error query job attachments " + jobId, e);
}
}
@Override
public void uploadLogFile(int execId, String name, int attempt, File... files)
throws ExecutorManagerException {
Connection connection = getConnection();
try {
uploadLogFile(connection, execId, name, attempt, files,
defaultEncodingType);
connection.commit();
} catch (SQLException e) {
throw new ExecutorManagerException("Error committing log", e);
} catch (IOException e) {
throw new ExecutorManagerException("Error committing log", e);
} finally {
DbUtils.closeQuietly(connection);
}
}
private void uploadLogFile(Connection connection, int execId, String name,
int attempt, File[] files, EncodingType encType)
throws ExecutorManagerException, IOException {
// 50K buffer... if logs are greater than this, we chunk.
// However, we better prevent large log files from being uploaded somehow
byte[] buffer = new byte[50 * 1024];
int pos = 0;
int length = buffer.length;
int startByte = 0;
try {
for (int i = 0; i < files.length; ++i) {
File file = files[i];
BufferedInputStream bufferedStream =
new BufferedInputStream(new FileInputStream(file));
try {
int size = bufferedStream.read(buffer, pos, length);
while (size >= 0) {
if (pos + size == buffer.length) {
// Flush here.
uploadLogPart(connection, execId, name, attempt, startByte,
startByte + buffer.length, encType, buffer, buffer.length);
pos = 0;
length = buffer.length;
startByte += buffer.length;
} else {
// Usually end of file.
pos += size;
length = buffer.length - pos;
}
size = bufferedStream.read(buffer, pos, length);
}
} finally {
IOUtils.closeQuietly(bufferedStream);
}
}
// Final commit of buffer.
if (pos > 0) {
uploadLogPart(connection, execId, name, attempt, startByte, startByte
+ pos, encType, buffer, pos);
}
} catch (SQLException e) {
throw new ExecutorManagerException("Error writing log part.", e);
} catch (IOException e) {
throw new ExecutorManagerException("Error chunking", e);
}
}
private void uploadLogPart(Connection connection, int execId, String name,
int attempt, int startByte, int endByte, EncodingType encType,
byte[] buffer, int length) throws SQLException, IOException {
final String INSERT_EXECUTION_LOGS =
"INSERT INTO execution_logs "
+ "(exec_id, name, attempt, enc_type, start_byte, end_byte, "
+ "log, upload_time) VALUES (?,?,?,?,?,?,?,?)";
QueryRunner runner = new QueryRunner();
byte[] buf = buffer;
if (encType == EncodingType.GZIP) {
buf = GZIPUtils.gzipBytes(buf, 0, length);
} else if (length < buf.length) {
buf = Arrays.copyOf(buffer, length);
}
runner.update(connection, INSERT_EXECUTION_LOGS, execId, name, attempt,
encType.getNumVal(), startByte, startByte + length, buf, DateTime.now()
.getMillis());
}
@Override
public void uploadAttachmentFile(ExecutableNode node, File file)
throws ExecutorManagerException {
Connection connection = getConnection();
try {
uploadAttachmentFile(connection, node, file, defaultEncodingType);
connection.commit();
} catch (SQLException e) {
throw new ExecutorManagerException("Error committing attachments ", e);
} catch (IOException e) {
throw new ExecutorManagerException("Error uploading attachments ", e);
} finally {
DbUtils.closeQuietly(connection);
}
}
private void uploadAttachmentFile(Connection connection, ExecutableNode node,
File file, EncodingType encType) throws SQLException, IOException {
String jsonString = FileUtils.readFileToString(file);
byte[] attachments = GZIPUtils.gzipString(jsonString, "UTF-8");
final String UPDATE_EXECUTION_NODE_ATTACHMENTS =
"UPDATE execution_jobs " + "SET attachments=? "
+ "WHERE exec_id=? AND flow_id=? AND job_id=? AND attempt=?";
QueryRunner runner = new QueryRunner();
runner.update(connection, UPDATE_EXECUTION_NODE_ATTACHMENTS, attachments,
node.getExecutableFlow().getExecutionId(), node.getParentFlow()
.getNestedId(), node.getId(), node.getAttempt());
}
private Connection getConnection() throws ExecutorManagerException {
Connection connection = null;
try {
connection = super.getDBConnection(false);
} catch (Exception e) {
DbUtils.closeQuietly(connection);
throw new ExecutorManagerException("Error getting DB connection.", e);
}
return connection;
}
/**
*
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#fetchActiveExecutors()
*/
@Override
public List<Executor> fetchAllExecutors() throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutorHandler executorHandler = new FetchExecutorHandler();
try {
List<Executor> executors =
runner.query(FetchExecutorHandler.FETCH_ALL_EXECUTORS, executorHandler);
return executors;
} catch (Exception e) {
throw new ExecutorManagerException("Error fetching executors", e);
}
}
/**
*
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#fetchActiveExecutors()
*/
@Override
public List<Executor> fetchActiveExecutors() throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutorHandler executorHandler = new FetchExecutorHandler();
try {
List<Executor> executors =
runner.query(FetchExecutorHandler.FETCH_ACTIVE_EXECUTORS,
executorHandler);
return executors;
} catch (Exception e) {
throw new ExecutorManagerException("Error fetching active executors", e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#fetchExecutor(java.lang.String, int)
*/
@Override
public Executor fetchExecutor(String host, int port)
throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutorHandler executorHandler = new FetchExecutorHandler();
try {
List<Executor> executors =
runner.query(FetchExecutorHandler.FETCH_EXECUTOR_BY_HOST_PORT,
executorHandler, host, port);
if (executors.isEmpty()) {
return null;
} else {
return executors.get(0);
}
} catch (Exception e) {
throw new ExecutorManagerException(String.format(
"Error fetching executor %s:%d", host, port), e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#fetchExecutor(int)
*/
@Override
public Executor fetchExecutor(int executorId) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
FetchExecutorHandler executorHandler = new FetchExecutorHandler();
try {
List<Executor> executors =
runner.query(FetchExecutorHandler.FETCH_EXECUTOR_BY_ID,
executorHandler, executorId);
if (executors.isEmpty()) {
return null;
} else {
return executors.get(0);
}
} catch (Exception e) {
throw new ExecutorManagerException(String.format(
"Error fetching executor with id: %d", executorId), e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#updateExecutor(int)
*/
@Override
public void updateExecutor(Executor executor) throws ExecutorManagerException {
final String UPDATE =
"UPDATE executors SET host=?, port=?, active=? where id=?";
QueryRunner runner = createQueryRunner();
try {
int rows =
runner.update(UPDATE, executor.getHost(), executor.getPort(),
executor.isActive(), executor.getId());
if (rows == 0) {
throw new ExecutorManagerException("No executor with id :"
+ executor.getId());
}
} catch (SQLException e) {
throw new ExecutorManagerException("Error inactivating executor "
+ executor.getId(), e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#addExecutor(java.lang.String, int)
*/
@Override
public Executor addExecutor(String host, int port)
throws ExecutorManagerException {
// verify, if executor already exists
Executor executor = fetchExecutor(host, port);
if (executor != null) {
throw new ExecutorManagerException(String.format(
"Executor %s:%d already exist", host, port));
}
// add new executor
addExecutorHelper(host, port);
// fetch newly added executor
executor = fetchExecutor(host, port);
return executor;
}
private void addExecutorHelper(String host, int port)
throws ExecutorManagerException {
final String INSERT = "INSERT INTO executors (host, port) values (?,?)";
QueryRunner runner = createQueryRunner();
try {
runner.update(INSERT, host, port);
} catch (SQLException e) {
throw new ExecutorManagerException(String.format("Error adding %s:%d ",
host, port), e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#postExecutorEvent(azkaban.executor.Executor,
* azkaban.executor.ExecutorLogEvent.EventType, java.lang.String,
* java.lang.String)
*/
@Override
public void postExecutorEvent(Executor executor, EventType type, String user,
String message) throws ExecutorManagerException{
QueryRunner runner = createQueryRunner();
final String INSERT_PROJECT_EVENTS =
"INSERT INTO executor_events (executor_id, event_type, event_time, username, message) values (?,?,?,?,?)";
Date updateDate = new Date();
try {
runner.update(INSERT_PROJECT_EVENTS, executor.getId(), type.getNumVal(),
updateDate, user, message);
} catch (SQLException e) {
throw new ExecutorManagerException("Failed to post executor event", e);
}
}
/**
* {@inheritDoc}
*
* @see azkaban.executor.ExecutorLoader#getExecutorEvents(azkaban.executor.Executor,
* int, int)
*/
@Override
public List<ExecutorLogEvent> getExecutorEvents(Executor executor, int num,
int offset) throws ExecutorManagerException {
QueryRunner runner = createQueryRunner();
ExecutorLogsResultHandler logHandler = new ExecutorLogsResultHandler();
List<ExecutorLogEvent> events = null;
try {
events =
runner.query(ExecutorLogsResultHandler.SELECT_EXECUTOR_EVENTS_ORDER,
logHandler, executor.getId(), num, offset);
} catch (SQLException e) {
throw new ExecutorManagerException(
"Failed to fetch events for executor id : " + executor.getId(), e);
}
return events;
}
/**
*