-
Notifications
You must be signed in to change notification settings - Fork 210
/
CoreAction.java
2397 lines (2189 loc) · 87.6 KB
/
CoreAction.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* <p>
* http:https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 com.qlangtech.tis.coredefine.module.action;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.koubei.web.tag.pager.Pager;
import com.qlangtech.tis.TIS;
import com.qlangtech.tis.assemble.ExecResult;
import com.qlangtech.tis.async.message.client.consumer.impl.MQListenerFactory;
import com.qlangtech.tis.cloud.ITISCoordinator;
import com.qlangtech.tis.compiler.streamcode.GenerateDAOAndIncrScript;
import com.qlangtech.tis.compiler.streamcode.IndexStreamCodeGenerator;
import com.qlangtech.tis.coredefine.biz.FCoreRequest;
import com.qlangtech.tis.coredefine.module.action.IDeploymentDetail.IDeploymentDetailVisitor;
import com.qlangtech.tis.coredefine.module.action.impl.FlinkJobDeploymentDetails;
import com.qlangtech.tis.coredefine.module.action.impl.RcDeployment;
import com.qlangtech.tis.coredefine.module.control.SelectableServer;
import com.qlangtech.tis.coredefine.module.control.SelectableServer.CoreNode;
import com.qlangtech.tis.datax.DataXJobSubmit;
import com.qlangtech.tis.datax.IDataxProcessor;
import com.qlangtech.tis.datax.impl.DataxProcessor;
import com.qlangtech.tis.datax.impl.DataxReader;
import com.qlangtech.tis.datax.impl.DataxWriter;
import com.qlangtech.tis.datax.job.DefaultSSERunnable;
import com.qlangtech.tis.datax.job.ILaunchingOrchestrate;
import com.qlangtech.tis.datax.job.ILaunchingOrchestrate.ExecuteStep;
import com.qlangtech.tis.datax.job.ILaunchingOrchestrate.ExecuteSteps;
import com.qlangtech.tis.datax.job.JobResName;
import com.qlangtech.tis.datax.job.ServerLaunchToken;
import com.qlangtech.tis.datax.job.ServerLaunchToken.FlinkClusterTokenManager;
import com.qlangtech.tis.datax.job.SubJobResName;
import com.qlangtech.tis.extension.Descriptor;
import com.qlangtech.tis.fullbuild.IFullBuildContext;
import com.qlangtech.tis.job.common.JobCommon;
import com.qlangtech.tis.lang.TisException;
import com.qlangtech.tis.manage.IAppSource;
import com.qlangtech.tis.manage.IBasicAppSource;
import com.qlangtech.tis.manage.IDataFlowAppSource;
import com.qlangtech.tis.manage.ISingleTableAppSource;
import com.qlangtech.tis.manage.ISolrAppSource;
import com.qlangtech.tis.manage.PermissionConstant;
import com.qlangtech.tis.manage.biz.dal.pojo.Application;
import com.qlangtech.tis.manage.biz.dal.pojo.Server;
import com.qlangtech.tis.manage.biz.dal.pojo.ServerGroup;
import com.qlangtech.tis.manage.biz.dal.pojo.ServerGroupCriteria;
import com.qlangtech.tis.manage.biz.dal.pojo.SnapshotCriteria;
import com.qlangtech.tis.manage.common.AppDomainInfo;
import com.qlangtech.tis.manage.common.Config;
import com.qlangtech.tis.manage.common.HttpUtils;
import com.qlangtech.tis.manage.common.HttpUtils.PostParam;
import com.qlangtech.tis.manage.common.ManageUtils;
import com.qlangtech.tis.manage.common.RunContext;
import com.qlangtech.tis.manage.servlet.DownloadResource;
import com.qlangtech.tis.manage.servlet.DownloadServlet;
import com.qlangtech.tis.manage.spring.aop.Func;
import com.qlangtech.tis.order.center.IParamContext;
import com.qlangtech.tis.plugin.IPluginStore;
import com.qlangtech.tis.plugin.incr.IncrStreamFactory;
import com.qlangtech.tis.plugin.incr.TISSinkFactory;
import com.qlangtech.tis.pubhook.common.RunEnvironment;
import com.qlangtech.tis.runtime.module.action.BasicModule;
import com.qlangtech.tis.runtime.module.screen.BasicScreen;
import com.qlangtech.tis.runtime.module.screen.ViewPojo;
import com.qlangtech.tis.runtime.pojo.ServerGroupAdapter;
import com.qlangtech.tis.solrj.util.ZkUtils;
import com.qlangtech.tis.sql.parser.DBNode;
import com.qlangtech.tis.sql.parser.stream.generate.StreamCodeContext;
import com.qlangtech.tis.sql.parser.tuple.creator.IStreamIncrGenerateStrategy;
import com.qlangtech.tis.util.DescriptorsJSON;
import com.qlangtech.tis.util.HeteroEnum;
import com.qlangtech.tis.util.ItemsSaveResult;
import com.qlangtech.tis.web.start.TisAppLaunch;
import com.qlangtech.tis.workflow.dao.IWorkFlowBuildHistoryDAO;
import com.qlangtech.tis.workflow.pojo.DatasourceDb;
import com.qlangtech.tis.workflow.pojo.DatasourceDbCriteria;
import com.qlangtech.tis.workflow.pojo.WorkFlow;
import com.qlangtech.tis.workflow.pojo.WorkFlowBuildHistory;
import com.qlangtech.tis.workflow.pojo.WorkFlowBuildHistoryCriteria;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* core 应用定义
*
* @author 百岁([email protected])
* @date 2016年8月4日
*/
public class CoreAction extends BasicModule {
private static final Logger logger = LoggerFactory.getLogger(CoreAction.class);
public static final String ADMIN_COLLECTION_PATH = "/solr/admin/collections";
public static final String CREATE_COLLECTION_PATH = ADMIN_COLLECTION_PATH + "?action=CREATE&name=";
public static final String DEFAULT_SOLR_CONFIG = "tis_mock_config";
private static final long serialVersionUID = -6753169329484480543L;
private static final Pattern PATTERN_IP = Pattern.compile("^((\\d+?).(\\d+?).(\\d+?).(\\d+?)):(\\d+)_solr$");
// private final String CLIENT_ZK_PATH = "/terminator/dump-controller/";
// public static final XMLResponseParser RESPONSE_PARSER = new XMLResponseParser();
private static final int MAX_SHARDS_PER_NODE = 16;
private static final Logger log = LoggerFactory.getLogger(CoreAction.class);
private static final Pattern placehold_pattern = Pattern.compile("\\$\\{(.+)\\}");
public static final String CREATE_CORE_SELECT_COREINFO = "selectCoreinfo";
public static String getAssembleNodeAddress(ITISCoordinator coordinator) {
// 增量状态收集节点
// final String incrStateCollectAddress =
// ZkUtils.getFirstChildValue(
// coordinator,
// ZkUtils.ZK_ASSEMBLE_LOG_COLLECT_PATH,
// true);
return Config.getAssembleHttpHost();
// "http:https://" + StringUtils.substringBefore(incrStateCollectAddress, ":")
// + ":8080" + Config.CONTEXT_ASSEMBLE;
}
/**
* @param context
* @throws Exception
*/
public void doGetTaskInfo(Context context) throws Exception {
Integer taskid = this.getInt("taskid", null, true);
WorkFlowBuildHistory buildHistory =
this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO().selectByPrimaryKey(taskid);
this.setBizResult(context, Collections.singletonMap("task", buildHistory));
}
/**
* 创建新新的Savepoint
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_MANAGE)
public void doCreateNewSavepoint(Context context) throws Exception {
IRCController incrSync = getRCController();
TargetResName resName = new TargetResName(this.getCollectionName());
IRCController.SupportTriggerSavePointResult supportResult = null;
if (!(supportResult = incrSync.supportTriggerSavePoint(resName)).support) {
this.addErrorMessage(context, supportResult.unSupportReason);
return;
}
incrSync.triggerSavePoint(resName);
IndexIncrStatus incrStatus = getIndexIncrStatus(this, false);
this.setBizResult(context, incrStatus);
}
private IRCController getRCController() {
IPluginStore<IncrStreamFactory> incrStreamStore = getIncrStreamFactoryStore(this, true);
IncrStreamFactory incrStream = incrStreamStore.getPlugin();
return incrStream;
}
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_MANAGE)
public void doGetFlinkClusterList(Context context) throws Exception {
FlinkClusterTokenManager clusters = ServerLaunchToken.createFlinkClusterToken();
this.setBizResult(context, clusters.getAllFlinkSessionClusters());
}
/**
* 删除已有的 Savepoint
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_MANAGE)
public void doDiscardSavepoint(Context context) throws Exception {
String savepointPath = this.getString("savepointPath");
if (StringUtils.isEmpty(savepointPath)) {
throw new IllegalArgumentException("param savepointPath can not be null");
}
IRCController incrSync = getRCController();
incrSync.discardSavepoint(new TargetResName(this.getCollectionName()), savepointPath);
IndexIncrStatus incrStatus = getIndexIncrStatus(this, false);
this.setBizResult(context, incrStatus);
}
/**
* 重新启动增量执行进程
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.APP_REBUILD)
public void doRelaunchIncrProcess(Context context) throws Exception {
String savepointPath = this.getString("savepointPath");
if (StringUtils.isEmpty(savepointPath)) {
throw new IllegalArgumentException("param savepointPath can not be null");
}
IRCController incrSync = getRCController();
incrSync.relaunch(new TargetResName(this.getCollectionName()), savepointPath);
waittingiIntendedStatus(context, IFlinkIncrJobStatus.State.RUNNING);
}
@Func(value = PermissionConstant.APP_REBUILD)
public void doRestoreFromCheckpoint(Context context) throws Exception {
Integer checkpointId = this.getInt("checkpointId");
IRCController incrSync = getRCController();
incrSync.restoreFromCheckpoint(new TargetResName(this.getCollectionName()), checkpointId);
waittingiIntendedStatus(context, IFlinkIncrJobStatus.State.RUNNING);
}
/**
* 终止正在执行的任务
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.APP_UPDATE)
public void doCancelTask(Context context) throws Exception {
Integer taskId = this.getInt(JobCommon.KEY_TASK_ID);
IWorkFlowBuildHistoryDAO workFlowBuildDAO
= this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO();
WorkFlowBuildHistory buildHistory = workFlowBuildDAO.loadFromWriteDB(taskId);
ExecResult processState = ExecResult.parse(buildHistory.getState());
if (!processState.isProcessing()) {
this.addErrorMessage(context, "当前任务状态为已终止,不能执行终止操作");
return;
}
DataXJobSubmit dataXJobSubmit = DataXJobSubmit.getDataXJobSubmit();
dataXJobSubmit.cancelTask(this, context, buildHistory);
// List<ConfigFileContext.Header> headers = Lists.newArrayList();
// headers.add(new ConfigFileContext.Header(JobCommon.KEY_TASK_ID, String.valueOf(taskId)));
// headers.add(new ConfigFileContext.Header(IParamContext.KEY_ASYN_JOB_NAME, String.valueOf(processState == ExecResult.ASYN_DOING)));
// headers.add(new ConfigFileContext.Header(IFullBuildContext.KEY_APP_NAME, IAppSourcePipelineController.DATAX_FULL_PIPELINE + buildHistory.getAppName()));
//
// TriggerBuildResult triggerResult = TriggerBuildResult.triggerBuild(this, context, ConfigFileContext.HTTPMethod.DELETE, Collections.emptyList(), headers);
// if (!triggerResult.success) {
// return;
// }
WorkFlowBuildHistory record = new WorkFlowBuildHistory();
record.setState((byte) ExecResult.CANCEL.getValue());
WorkFlowBuildHistoryCriteria criteria = new WorkFlowBuildHistoryCriteria();
criteria.createCriteria().andIdEqualTo(buildHistory.getId());
workFlowBuildDAO.updateByExampleSelective(record, criteria);
this.addActionMessage(context, "已经成功终止当前任务");
this.setBizResult(context, new ExtendWorkFlowBuildHistory(
this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO().loadFromWriteDB(buildHistory.getId())));
}
private void waittingiIntendedStatus(Context context, IFlinkIncrJobStatus.State targetStatus) throws Exception {
int tryCount = 0;
while (tryCount++ < 3) {
IDeploymentDetail detail = TISK8sDelegate.getK8SDelegate(
this.getCollectionName()).getRcConfig(false);
AtomicBoolean getTargetStatus = new AtomicBoolean(false);
detail.accept(new IDeploymentDetail.IDeploymentDetailVisitor() {
@Override
public void visit(RcDeployment rcDeployment) {
throw new UnsupportedOperationException();
}
@Override
public void visit(FlinkJobDeploymentDetails details) {
// getTargetStatus.set( (targetStatus == IFlinkIncrJobStatus.State.RUNNING ) ? details.getIncrJobStatus().getState() == targetStatus);
getTargetStatus.set(!((targetStatus == IFlinkIncrJobStatus.State.RUNNING) ^ details.isRunning()));
}
});
if (getTargetStatus.get()) {
IndexIncrStatus incrStatus = getIndexIncrStatus(this, detail);
this.setBizResult(context, incrStatus);
return;
} else {
// 执行终止操作之后从服务端应该要能取到已经终止的状态,不然重新尝试等待,尝试3次
Thread.sleep(3000);
}
}
}
/**
* 取得当前增量的配置状态
*
* @param context
*/
public void doGetIncrStatus(Context context) throws Exception {
final boolean cache = this.getBoolean("cache");
IndexIncrStatus incrStatus = getIndexIncrStatus(this, cache);
this.setBizResult(context, incrStatus);
}
public static IndexIncrStatus getIndexIncrStatus(BasicModule module, IDeploymentDetail rcConfig) throws Exception {
IndexIncrStatus incrStatus = doGetDataXReaderWriterDesc(module.getCollectionName());
// 是否可以取缓存中的deployment信息,在刚删除pod重启之后需要取全新的deployment信息不能缓存
IPluginStore<IncrStreamFactory> store = getIncrStreamFactoryStore(module);
IncrStreamFactory incrStreamFactory = null;
// IncrStreamFactory incrStream = null;
if ((incrStreamFactory = store.getPlugin()) == null) {
incrStatus.setK8sPluginInitialized(false);
return incrStatus;
}
// 可以基于checkpoint恢复任务的前提是,需要开启checkpoint,并且使用了持久化statebackend
incrStatus.setRestorableByCheckpoint(incrStreamFactory.restorable().isPresent());
incrStatus.setK8sPluginInitialized(true);
IndexStreamCodeGenerator indexStreamCodeGenerator = getIndexStreamCodeGenerator(module);
StreamCodeContext streamCodeContext
= new StreamCodeContext(module.getCollectionName(), indexStreamCodeGenerator.incrScriptTimestamp);
incrStatus.setIncrScriptCreated(streamCodeContext.isIncrScriptDirCreated());
// TISK8sDelegate k8s = TISK8sDelegate.getK8SDelegate(module.getCollectionName());
// IDeploymentDetail rcConfig = k8s.getRcConfig(getRcConfigInCache);
incrStatus.setState(rcConfig != null ? IFlinkIncrJobStatus.State.RUNNING : IFlinkIncrJobStatus.State.NONE);
if (rcConfig != null) {
rcConfig.accept(new IDeploymentDetail.IDeploymentDetailVisitor() {
@Override
public void visit(RcDeployment rcDeployment) {
incrStatus.setRcDeployments(Collections.singletonList(rcDeployment));
}
@Override
public void visit(FlinkJobDeploymentDetails details) {
incrStatus.setFlinkJobDetail(details);
// 这里有三种状态
IFlinkIncrJobStatus status = details.getIncrJobStatus();
if (status.getState() != null) {
incrStatus.setState(status.getState());
}
}
});
incrStatus.setIncrProcess(null);
}
return incrStatus;
}
/**
* @param module
* @param getRcConfigInCache
* @return
* @throws Exception
*/
public static IndexIncrStatus getIndexIncrStatus(BasicModule module, boolean getRcConfigInCache) throws Exception {
IndexIncrStatus incrStatus = doGetDataXReaderWriterDesc(module.getCollectionName());
// 是否可以取缓存中的deployment信息,在刚删除pod重启之后需要取全新的deployment信息不能缓存
IPluginStore<IncrStreamFactory> store = getIncrStreamFactoryStore(module);
if ((store.getPlugin()) == null) {
incrStatus.setK8sPluginInitialized(false);
return incrStatus;
}
TISK8sDelegate k8s = TISK8sDelegate.getK8SDelegate(module.getCollectionName());
if (!k8s.hasCreated()) {
incrStatus.setK8sPluginInitialized(false);
return incrStatus;
}
k8s.checkUseable();
IDeploymentDetail rcConfig = k8s.getRcConfig(getRcConfigInCache);
return getIndexIncrStatus(module, rcConfig);
}
public static IPluginStore<IncrStreamFactory> getIncrStreamFactoryStore(BasicModule module) {
return getIncrStreamFactoryStore(module, false);
}
private static IPluginStore<IncrStreamFactory> getIncrStreamFactoryStore(BasicModule module, boolean validateNull) {
IPluginStore<IncrStreamFactory> store = TIS.getPluginStore(module.getCollectionName(), IncrStreamFactory.class);
if (validateNull && store.getPlugin() == null) {
throw new IllegalStateException("collection:" + module.getCollectionName() + " relevant IncrStreamFactory store can not be null");
}
return store;
}
/**
* create_incr_sync_channal
* 创建增量通道 <br>
* 1. 生成dao层代码,存在本地 <br>
* 2. 对生成的代码进行打包 <br>
* 3. 将代码包发布到仓库中备用,并对本次代码包进行标记 <br>
* 4. 将标记记录到数据库中 <br>
* 5. 自动生成增量代码(scala版本的) <br>
* 6. 对生成的代码包进行编译,打包 <br>
* 7. 将生成的代码包发布到仓库中备用,并对本次代码包进行标记 <br>
* 8. 将标记记录到数据库中 <br>
* 9. 结合dao层代码包和scala层代码包,再结合之前已经构建完成的docker镜像包,将增量代码发布到k8s集群中去<br>
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_CONFIG_EDIT, sideEffect = false)
public void doCreateIncrSyncChannal(Context context) throws Exception {
// 该方法是从PluginAction:doSavePluginConfig中forward过来的
List<ItemsSaveResult> itemsSaveResult = PluginAction.getItemsSaveResultInRequest(this.getRequest());
Optional<ItemsSaveResult> hasCfgChanged
= itemsSaveResult.stream().filter((r) -> r.cfgSaveResult.cfgChanged).findFirst();
IndexIncrStatus incrStatus = generateDAOAndIncrScript(this, context, hasCfgChanged.isPresent());
MQListenerFactory incrFactory = HeteroEnum.getIncrSourceListenerFactory(this.getCollectionName());
TISSinkFactory sinkFactory = TISSinkFactory.getIncrSinKFactory(this.getCollectionName());
incrStatus.setIncrSourceDesc(createDescVals(incrFactory.getDescriptor()));
incrStatus.setIncrSinkDesc(createDescVals(sinkFactory.getDescriptor()));
this.setBizResult(context, incrStatus);
}
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_CONFIG_EDIT, sideEffect = false)
public void doStartIncrSyncChannal(Context context) throws Exception {
// IndexIncrStatus incrStatus = generateDAOAndIncrScript(this, context);
this.setBizResult(context, doGetDataXReaderWriterDesc(this.getCollectionName()));
}
public static IndexIncrStatus generateDAOAndIncrScript(BasicModule module, Context context, boolean hasCfgChanged) throws Exception {
return generateDAOAndIncrScript(module, context, false, false, hasCfgChanged);
}
public static IndexIncrStatus generateDAOAndIncrScript(
BasicModule module, Context context, boolean validateGlobalIncrStreamFactory, boolean compilerAndPackage, boolean hasCfgChanged) throws Exception {
IStreamIncrGenerateStrategy appSource = IAppSource.load(null, module.getCollectionName());
return generateDAOAndIncrScript(module, context
, validateGlobalIncrStreamFactory, compilerAndPackage, appSource.isExcludeFacadeDAOSupport(), hasCfgChanged);
}
/**
* @param module
* @param context
* @param
* @param validateGlobalIncrStreamFactory
* @param compilerAndPackage
* @param excludeFacadeDAOSupport 由于单表同步不需要dao支持,可以选择false即可
* @return
* @throws Exception
*/
public static IndexIncrStatus generateDAOAndIncrScript(
BasicModule module, Context context
, boolean validateGlobalIncrStreamFactory, boolean compilerAndPackage, boolean excludeFacadeDAOSupport, boolean hasCfgChanged) throws Exception {
IndexStreamCodeGenerator indexStreamCodeGenerator = getIndexStreamCodeGenerator(module);
// List<FacadeContext> facadeList = indexStreamCodeGenerator.getFacadeList();
//PluginStore<IncrStreamFactory> store = TIS.getPluginStore(IncrStreamFactory.class);
IndexIncrStatus incrStatus = doGetDataXReaderWriterDesc(module.getCollectionName());
// if (validateGlobalIncrStreamFactory && store.getPlugin() == null) {
// throw new IllegalStateException("global IncrStreamFactory config can not be null");
// }
//if (store.getPlugin() != null) {
// 已经定义了全局插件
IPluginStore<IncrStreamFactory> collectionBindIncrStreamFactoryStore = getIncrStreamFactoryStore(module);
if (collectionBindIncrStreamFactoryStore.getPlugin() == null) {
// 需要将全局插件属性拷贝到collection绑定的插件属性上来
// Descriptor flinkStreamDesc = TIS.get().getDescriptor(IncrStreamFactory.FLINK_STREM);
// if (flinkStreamDesc == null) {
// throw new IllegalStateException(
// "can not find findStream Factory in plugin repository, Descriptor ID:" + IncrStreamFactory.FLINK_STREM);
// }
//
// collectionBindIncrStreamFactoryStore.setPlugins(module, Optional.of(context)
// , Collections.singletonList(flinkStreamDesc.newInstance(module, Collections.emptyMap(), Optional.empty())));
// throw new IllegalStateException("collectionName:" + module.getCollectionName() + " relevant plugin can not be null " + IncrStreamFactory.class.getName());
}
//}
// 这里永远是false应该
incrStatus.setK8sPluginInitialized(false);
// 判断是否已经成功创建,如果已经创建了,就退出
if (indexStreamCodeGenerator.isIncrScriptDirCreated()) {
incrStatus.setIncrScriptCreated(true);
incrStatus.setIncrScriptMainFileContent(indexStreamCodeGenerator.readIncrScriptMainFileContent());
log.info("incr script has create ignore it file path:{}", indexStreamCodeGenerator.getIncrScriptDirPath());
// this.setBizResult(context, incrStatus);
}
GenerateDAOAndIncrScript generateDAOAndIncrScript = new GenerateDAOAndIncrScript(module, indexStreamCodeGenerator);
if (excludeFacadeDAOSupport) {
generateDAOAndIncrScript.generateIncrScript(context, incrStatus, compilerAndPackage, Collections.emptyMap(), hasCfgChanged);
} else {
// 需要facadeDAO支持
generateDAOAndIncrScript.generate(context, incrStatus
, compilerAndPackage, getDependencyDbsMap(module, indexStreamCodeGenerator));
}
incrStatus.setIncrScriptTimestamp(indexStreamCodeGenerator.getIncrScriptTimestamp());
return incrStatus;
}
private static IndexIncrStatus doGetDataXReaderWriterDesc(String appName) throws Exception {
IndexIncrStatus incrStatus = new IndexIncrStatus();
incrStatus.setState(IFlinkIncrJobStatus.State.NONE);
IDataxProcessor dataxProcessor = DataxProcessor.load(null, appName);
DataxWriter writer = (DataxWriter) dataxProcessor.getWriter(null, true);
incrStatus.setWriterDesc(createDescVals(writer.getDescriptor()));
DataxReader reader = (DataxReader) dataxProcessor.getReader(null);
incrStatus.setReaderDesc(createDescVals(reader.getDescriptor()));
return incrStatus;
}
private static HashMap<String, Object> createDescVals(Descriptor desc) {
HashMap<String, Object> newExtraProps = Maps.newHashMap(desc.getExtractProps());
newExtraProps.put(DescriptorsJSON.KEY_IMPL, desc.getId());
newExtraProps.put(DescriptorsJSON.KEY_DISPLAY_NAME, desc.getDisplayName());
newExtraProps.put(DescriptorsJSON.KEY_EXTEND_POINT, desc.getT().getName());
return newExtraProps;
}
/**
* 编译打包
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_CONFIG_EDIT)
public void doCompileAndPackage(Context context) throws Exception {
// IBasicAppSource appSource = IAppSource.load(null, this.getCollectionName());
IndexStreamCodeGenerator indexStreamCodeGenerator = getIndexStreamCodeGenerator(this);
IndexIncrStatus incrStatus = new IndexIncrStatus();
GenerateDAOAndIncrScript daoAndIncrScript = new GenerateDAOAndIncrScript(this, indexStreamCodeGenerator);
// if (appSource.isExcludeFacadeDAOSupport()) {
if (true) {
daoAndIncrScript.generateIncrScript(context, incrStatus, true, Collections.emptyMap(), false);
} else {
Map<Integer, Long> dependencyDbs = getDependencyDbsMap(this, indexStreamCodeGenerator);
// 需要facadeDAO支持
daoAndIncrScript.generate(context, incrStatus, true, dependencyDbs);
}
}
/**
* @param context
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_MANAGE)
public void doReDeployIncrSyncChannal(Context context) throws Exception {
IncrStreamFactory streamFactory = IncrStreamFactory.getFactory(this.getCollectionName());
streamFactory.removeInstance(new TargetResName(this.getCollectionName()));
Thread.sleep(4000);
final ServerLaunchToken incrLaunchToken = streamFactory.getLaunchToken(new TargetResName(this.getCollectionName()));
incrLaunchToken.deleteLaunchToken();
this.launchIncrSyncChannel(context, incrLaunchToken);
}
/**
* 部署实例
* https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/deployment/resource-providers/standalone/kubernetes/
*
* @param context
* @throws Exception
*/
@Func(value = PermissionConstant.PERMISSION_INCR_PROCESS_MANAGE)
public void doDeployIncrSyncChannal(Context context) throws Exception {
IncrStreamFactory streamFactory = IncrStreamFactory.getFactory(this.getCollectionName());
final ServerLaunchToken incrLaunchToken = streamFactory.getLaunchToken(new TargetResName(this.getCollectionName()));
this.launchIncrSyncChannel(context, incrLaunchToken);
IndexIncrStatus incrStatus = new IndexIncrStatus();
this.setBizResult(context, incrStatus);
}
public void launchIncrSyncChannel(Context context, final ServerLaunchToken incrLaunchToken) {
TISK8sDelegate k8sClient = TISK8sDelegate.getK8SDelegate(this.getCollectionName());
ILaunchingOrchestrate<FlinkJobDeployDTO> orchestrate = getFlinkJobWorkingOrchestrate(k8sClient);
final ExecuteSteps executeSteps = orchestrate.createExecuteSteps(this);
DefaultSSERunnable launchProcess = new DefaultSSERunnable(this, executeSteps, () -> {
try {
Thread.sleep(4000l);
} catch (InterruptedException e) {
}
}) {
@Override
public void afterLaunched() {
addActionMessage(context, "已经成功启动Flink增量实例");
}
};
DefaultSSERunnable.execute(launchProcess, false
, incrLaunchToken, () -> {
incrLaunchToken.writeLaunchToken(() -> {
// return this.launchService(launchProcess);
for (ExecuteStep execStep : executeSteps.getExecuteSteps()) {
execStep.getSubJob().execSubJob(new FlinkJobDeployDTO(context, k8sClient));
}
return Optional.empty();
});
// this.writeLaunchToken();
launchProcess.afterLaunched();
});
}
private ILaunchingOrchestrate<FlinkJobDeployDTO> getFlinkJobWorkingOrchestrate(TISK8sDelegate k8sClient) {
final SubJobResName<FlinkJobDeployDTO> checkEnvironment =
JobResName.createSubJob(getCollectionName() + " check environment", (dto) -> {
k8sClient.checkUseable();
});
// =
// new SubJobResName<FlinkJobDeployDTO, SubJobExec<FlinkJobDeployDTO>>("check-environment", new SubJobExec<FlinkJobDeployDTO>() {
// @Override
// public void accept(FlinkJobDeployDTO flinkJobDeployDTO) throws Exception {
// k8sClient.checkUseable();
// }
// }) {
// @Override
// protected String getResourceType() {
// return getCollectionName() + " check environment";
// }
// };
final SubJobResName<FlinkJobDeployDTO> compileAndPackage =
JobResName.createSubJob("Incr " + getCollectionName() + " Compile And Package", (dto) -> {
long start = System.currentTimeMillis();
/**
* ==========================================================
* compile&deploy
* ==========================================================
*/
this.doCompileAndPackage(dto.context);
if (dto.hasErrors()) {
return;
}
dto.appendLog("\n compile and package consume:" + (System.currentTimeMillis() - start) + "ms ");
});
final SubJobResName<FlinkJobDeployDTO> deploy
= SubJobResName.createSubJob("Incr " + getCollectionName() + " Deploy", (dto) -> {
IndexStreamCodeGenerator indexStreamCodeGenerator = getIndexStreamCodeGenerator(this);
// 将打包好的构建,发布到k8s集群中去
// https://github.com/kubernetes-client/java
long start = System.currentTimeMillis();
/**
* ==========================================================
* 通过k8s发布
* ==========================================================
*/
dto.k8sClient.deploy(null, indexStreamCodeGenerator.getIncrScriptTimestamp());
dto.appendLog("\n deploy to flink cluster consume:" + (System.currentTimeMillis() - start) + "ms ");
});
final SubJobResName<FlinkJobDeployDTO> confirm
= SubJobResName.createSubJob("Confirm", (dto) -> {
AtomicBoolean loop = new AtomicBoolean(true);
AtomicInteger tryCount = new AtomicInteger();
while (loop.get() && tryCount.getAndIncrement() < 10) {
IDeploymentDetail rcConfig = dto.k8sClient.getRcConfig(false);
rcConfig.accept(new IDeploymentDetailVisitor() {
@Override
public void visit(RcDeployment rcDeployment) {
throw new UnsupportedOperationException(rcDeployment.getName());
}
@Override
public void visit(FlinkJobDeploymentDetails details) {
switch (details.getIncrJobStatus().getState()) {
case FAILED:
throw TisException.create(getCollectionName() + " faild");
case RUNNING:
loop.set(false);
break;
default:
}
}
});
if (loop.get()) {
log.info("check " + getCollectionName() + " deploy status,tryCount:" + tryCount.get());
Thread.sleep(3000);
}
}
});
final SubJobResName[] flinkDeployRes //
= new SubJobResName[]{
checkEnvironment, compileAndPackage, deploy, confirm
};
return new ILaunchingOrchestrate() {
@Override
public List<ExecuteStep<FlinkJobDeployDTO>> getExecuteSteps() {
List<ExecuteStep<FlinkJobDeployDTO>> launchSteps = Lists.newArrayList();
for (SubJobResName rcRes : flinkDeployRes) {
launchSteps.add(new ExecuteStep(rcRes, null));
}
return launchSteps;
}
};
}
private class FlinkJobDeployDTO {
private final Context context;
private final TISK8sDelegate k8sClient;
private final StringBuffer logger = new StringBuffer("flink sync app:" + getCollectionName());
public FlinkJobDeployDTO(Context context, TISK8sDelegate k8sClient) {
this.context = context;
this.k8sClient = k8sClient;
}
public boolean hasErrors() {
return context.hasErrors();
}
public void appendLog(String loggerMsg) {
logger.append(loggerMsg);
}
}
private static Map<Integer, Long> getDependencyDbsMap(BasicModule module, IndexStreamCodeGenerator indexStreamCodeGenerator) {
final Map<DBNode, List<String>> dbNameMap = indexStreamCodeGenerator.getDbTables();
if (dbNameMap.size() < 1) {
throw new IllegalStateException("dbNameMap size can not small than 1");
}
// Map<Integer /**DBID*/, Long /**timestamp ver*/> dependencyDbs = null;
DatasourceDbCriteria dbCriteria = new DatasourceDbCriteria();
dbCriteria.createCriteria().andIdIn(dbNameMap.keySet().stream().map((dbNode -> dbNode.getDbId())).collect(Collectors.toList()));
return module.getWorkflowDAOFacade().getDatasourceDbDAO()
.selectByExample(dbCriteria).stream()
.collect(Collectors.toMap(DatasourceDb::getId, (r) -> ManageUtils.formatNowYyyyMMddHHmmss(r.getOpTime())));
}
private static IndexStreamCodeGenerator getIndexStreamCodeGenerator(BasicModule module) throws Exception {
IBasicAppSource appSource = IAppSource.load(null, module.getCollectionName());
Date scriptLastOpTime = appSource.accept(new IBasicAppSource.IAppSourceVisitor<Date>() {
@Override
public Date visit(DataxProcessor app) {
Application application = module.getApplicationDAO().selectByName(app.identityValue());
return application.getUpdateTime();
}
@Override
public Date visit(ISingleTableAppSource single) {
// DatasourceTable table = module.getWorkflowDAOFacade().getDatasourceTableDAO().loadFromWriteDB(single.getTabId());
// return table.getOpTime();
throw new UnsupportedOperationException();
}
@Override
public Date visit(IDataFlowAppSource dataflow) {
Integer dfId = dataflow.getDfId();
WorkFlow workFlow = module.getWorkflowDAOFacade().getWorkFlowDAO().loadFromWriteDB(dfId);
return workFlow.getOpTime();
}
});
return new IndexStreamCodeGenerator(module.getCollectionName(), appSource
, ManageUtils.formatNowYyyyMMddHHmmss(scriptLastOpTime), (dbId, rewriteableTables) -> {
// 通过dbid返回db中的所有表名称
// DatasourceTableCriteria tableCriteria = new DatasourceTableCriteria();
// tableCriteria.createCriteria().andDbIdEqualTo(dbId);
// List<DatasourceTable> tableList = module.getWorkflowDAOFacade().getDatasourceTableDAO().selectByExample(tableCriteria);
// return tableList.stream().map((t) -> t.getName()).collect(Collectors.toList());
return Collections.emptyList();
});
}
public static void main(String[] args) {
}
// /**
// * 触发生成一个新的Task do_trigger_fullbuild_task
// *
// * @param context
// * @throws Exception
// */
// @Func(value = PermissionConstant.DATAFLOW_MANAGE)
// public void doTriggerFullbuildTask(Context context) throws Exception {
// Application app = this.getAppDomain().getApp();
// triggerFullIndexSwape(this, context, app, getIndex().getSlices().size());
// }
/**
* 触发全量索引构建
*
* @param module
* @param context
* @param app
* @param sharedCount
* @return
* @throws Exception
*/
public static TriggerBuildResult triggerFullIndexSwape(BasicModule module, Context context, Application app, int sharedCount) throws Exception {
Objects.requireNonNull(app, "app can not be null");
// Objects.requireNonNull(wfId, "wfId can not be null");
// if (sharedCount < 1) {
// throw new IllegalArgumentException("param sharedCount can not be null");
// }
// if (StringUtils.isEmpty(wfName)) {
// throw new IllegalArgumentException("param wfName can not be null");
// }
ISolrAppSource appSource = IAppSource.load(null, app.getProjectName());
if (!appSource.triggerFullIndexSwapeValidate(module, context)) {
return new TriggerBuildResult(false);
}
// SqlTaskNodeMeta.SqlDataFlowTopology topology = SqlTaskNodeMeta.getSqlDataFlowTopology(wfName);
// Objects.requireNonNull(topology, "topology:" + wfName + " relevant topology can not be be null");
//
// Optional<ERRules> erRule = module.getErRules(wfName);
// if (!topology.isSingleTableModel()) {
// if (!erRule.isPresent()) {
// module.addErrorMessage(context, "请为数据流:[" + wfName + "]定义ER Rule");
// return new TriggerBuildResult(false);
// } else {
// ERRules erRules = erRule.get();
// List<PrimaryTableMeta> pTabs = erRules.getPrimaryTabs();
// Optional<PrimaryTableMeta> prTableMeta = pTabs.stream().findFirst();
// if (!TableMeta.hasValidPrimayTableSharedKey(prTableMeta.isPresent() ? Optional.of(prTableMeta.get()) : Optional.empty())) {
// module.addErrorMessage(context, "请为数据流:[" + wfName + "]定义ERRule 选择主表并且设置分区键");
// return new TriggerBuildResult(false);
// }
// }
// }
return sendRequest2FullIndexSwapeNode(module, context, new AppendParams() {
@Override
List<PostParam> getParam() {
return Lists.newArrayList(
// new PostParam(IFullBuildContext.KEY_WORKFLOW_NAME, wfName)
// , new PostParam(IFullBuildContext.KEY_WORKFLOW_ID, String.valueOf(wfId))
// new PostParam(IFullBuildContext.KEY_APP_NAME, app.getProjectName())
//,
new PostParam(IFullBuildContext.KEY_APP_SHARD_COUNT, String.valueOf(sharedCount)));
}
});
}
/**
* 通过taskid查询
*
* @param context
* @throws Exception
*/
public void doGetWorkflowBuildHistory(final Context context) throws Exception {
Integer taskid = this.getInt(JobCommon.KEY_TASK_ID, null, false);
WorkFlowBuildHistory buildHistory = this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO().selectByPrimaryKey(taskid);
if (buildHistory == null) {
throw new IllegalStateException(JobCommon.KEY_TASK_ID + ":" + taskid + "relevant buildHistory can not be null");
}
this.setBizResult(context, new ExtendWorkFlowBuildHistory(buildHistory));
}
/**
* 主动触发全量dump
*
* @param context
* @throws Exception
*/
@Func(PermissionConstant.APP_TRIGGER_FULL_DUMP)
public void doTriggerDump(final Context context) throws Exception {
// 'http:https://localhost:14844/trigger?component.start=indexBackflow&ps=20151215155124'
// ApplicationCriteria criteria = new ApplicationCriteria();
// criteria.createCriteria().andProjectNameEqualTo(this.getServiceName());
// List<Application> appList =
// this.getApplicationDAO().selectByExample(criteria);
// Assert.assertEquals(1, appList.size());
boolean success = sendRequest2FullIndexSwapeNode(this, context, new AppendParams() {
@Override
List<PostParam> getParam() {
return Collections.emptyList();
}
}).success;
if (success) {
this.addActionMessage(context, "已经触发了全量DUMP(triggerServiceFullDump)");
}
}
/**
* @param context
* @param appendParams
* @return
* @throws MalformedURLException
*/
private static TriggerBuildResult sendRequest2FullIndexSwapeNode(
BasicModule module, final Context context, AppendParams appendParams) throws Exception {
List<HttpUtils.PostParam> params = appendParams.getParam();
params.add(new PostParam(TriggerBuildResult.KEY_APPNAME, module.getCollectionName()));
return TriggerBuildResult.triggerBuild(module, context, params);
}
// #################################################################################
public void doGetWorkflow(Context context) throws Exception {
Integer wfid = this.getInt("wfid");
Integer taskid = this.getInt(JobCommon.KEY_TASK_ID);
WorkFlowBuildHistory buildHistory = this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO().selectByPrimaryKey(taskid);
Map<String, Object> result = Maps.newHashMap();
result.put("task", buildHistory);
WorkFlow workFlow = this.getWorkflowDAOFacade().getWorkFlowDAO().selectByPrimaryKey(wfid);
result.put("workflow", workFlow);
this.setBizResult(context, result);
}
/**
* 构建全量索引歷史記錄
*
* @param context
* @throws Exception
*/
public void doGetFullBuildHistory(Context context) throws Exception {
Integer wfid = this.getInt("wfid", -1);
boolean getwf = this.getBoolean("getwf");
WorkFlow workFlow = new WorkFlow();
WorkFlowBuildHistoryCriteria query = new WorkFlowBuildHistoryCriteria();
WorkFlowBuildHistoryCriteria.Criteria criteria = query.createCriteria();
if (isCollectionAware()) {
criteria.andAppIdEqualTo(this.getAppDomain().getAppid());
} else {
if (wfid < 0) {
throw new IllegalArgumentException("param wfid can not small than 0");
}
criteria.andWorkFlowIdEqualTo(wfid);
workFlow = new WorkFlow();
if (getwf) {
workFlow = this.getWorkflowDAOFacade().getWorkFlowDAO().selectByPrimaryKey(wfid);
if (workFlow == null) {
throw new IllegalStateException("can not find workflow in db ,wfid:" + wfid);
}
}
}
query.setOrderByClause("id desc");
IWorkFlowBuildHistoryDAO historyDAO = this.getWorkflowDAOFacade().getWorkFlowBuildHistoryDAO();
Pager pager = this.createPager();
pager.setTotalCount(historyDAO.countByExample(query));