-
Notifications
You must be signed in to change notification settings - Fork 138
/
MLModelManager.java
2007 lines (1892 loc) · 99.1 KB
/
MLModelManager.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 OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.ml.model;
import static org.opensearch.common.xcontent.XContentType.JSON;
import static org.opensearch.core.xcontent.ToXContent.EMPTY_PARAMS;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.ml.common.CommonValue.ML_CONTROLLER_INDEX;
import static org.opensearch.ml.common.CommonValue.ML_MODEL_GROUP_INDEX;
import static org.opensearch.ml.common.CommonValue.ML_MODEL_INDEX;
import static org.opensearch.ml.common.CommonValue.NOT_FOUND;
import static org.opensearch.ml.common.CommonValue.UNDEPLOYED;
import static org.opensearch.ml.common.MLModel.ALGORITHM_FIELD;
import static org.opensearch.ml.common.MLTask.ERROR_FIELD;
import static org.opensearch.ml.common.MLTask.FUNCTION_NAME_FIELD;
import static org.opensearch.ml.common.MLTask.MODEL_ID_FIELD;
import static org.opensearch.ml.common.MLTask.STATE_FIELD;
import static org.opensearch.ml.common.MLTaskState.COMPLETED;
import static org.opensearch.ml.common.MLTaskState.FAILED;
import static org.opensearch.ml.common.utils.StringUtils.getErrorMessage;
import static org.opensearch.ml.engine.ModelHelper.CHUNK_FILES;
import static org.opensearch.ml.engine.ModelHelper.CHUNK_SIZE;
import static org.opensearch.ml.engine.ModelHelper.MODEL_FILE_HASH;
import static org.opensearch.ml.engine.ModelHelper.MODEL_SIZE_IN_BYTES;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.CLIENT;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.CLUSTER_SERVICE;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.CONNECTOR_PRIVATE_IP_ENABLED;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.GUARDRAILS;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.RATE_LIMITER;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.SCRIPT_SERVICE;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.USER_RATE_LIMITER_MAP;
import static org.opensearch.ml.engine.algorithms.remote.RemoteModel.XCONTENT_REGISTRY;
import static org.opensearch.ml.engine.algorithms.text_embedding.TextEmbeddingDenseModel.ML_ENGINE;
import static org.opensearch.ml.engine.algorithms.text_embedding.TextEmbeddingDenseModel.MODEL_HELPER;
import static org.opensearch.ml.engine.algorithms.text_embedding.TextEmbeddingDenseModel.MODEL_ZIP_FILE;
import static org.opensearch.ml.engine.utils.FileUtils.calculateFileHash;
import static org.opensearch.ml.engine.utils.FileUtils.deleteFileQuietly;
import static org.opensearch.ml.plugin.MachineLearningPlugin.DEPLOY_THREAD_POOL;
import static org.opensearch.ml.plugin.MachineLearningPlugin.REGISTER_THREAD_POOL;
import static org.opensearch.ml.settings.MLCommonsSettings.ML_COMMONS_MAX_DEPLOY_MODEL_TASKS_PER_NODE;
import static org.opensearch.ml.settings.MLCommonsSettings.ML_COMMONS_MAX_MODELS_PER_NODE;
import static org.opensearch.ml.settings.MLCommonsSettings.ML_COMMONS_MAX_REGISTER_MODEL_TASKS_PER_NODE;
import static org.opensearch.ml.stats.ActionName.REGISTER;
import static org.opensearch.ml.stats.MLActionLevelStat.ML_ACTION_REQUEST_COUNT;
import static org.opensearch.ml.utils.MLExceptionUtils.logException;
import static org.opensearch.ml.utils.MLNodeUtils.checkOpenCircuitBreaker;
import static org.opensearch.ml.utils.MLNodeUtils.createXContentParserFromRegistry;
import java.io.File;
import java.nio.file.Path;
import java.security.PrivilegedActionException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.logging.log4j.util.Strings;
import org.opensearch.OpenSearchStatusException;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.index.IndexResponse;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.action.support.ThreadedActionListener;
import org.opensearch.action.support.WriteRequest;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.action.update.UpdateResponse;
import org.opensearch.client.Client;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.cluster.service.ClusterService;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.TokenBucket;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.index.query.TermQueryBuilder;
import org.opensearch.index.reindex.DeleteByQueryAction;
import org.opensearch.index.reindex.DeleteByQueryRequest;
import org.opensearch.ml.breaker.MLCircuitBreakerService;
import org.opensearch.ml.cluster.DiscoveryNodeHelper;
import org.opensearch.ml.common.CommonValue;
import org.opensearch.ml.common.FunctionName;
import org.opensearch.ml.common.MLModel;
import org.opensearch.ml.common.MLModelGroup;
import org.opensearch.ml.common.MLTask;
import org.opensearch.ml.common.MLTaskState;
import org.opensearch.ml.common.connector.Connector;
import org.opensearch.ml.common.controller.MLController;
import org.opensearch.ml.common.controller.MLRateLimiter;
import org.opensearch.ml.common.exception.MLException;
import org.opensearch.ml.common.exception.MLLimitExceededException;
import org.opensearch.ml.common.exception.MLResourceNotFoundException;
import org.opensearch.ml.common.exception.MLValidationException;
import org.opensearch.ml.common.model.Guardrails;
import org.opensearch.ml.common.model.MLGuard;
import org.opensearch.ml.common.model.MLModelState;
import org.opensearch.ml.common.transport.deploy.MLDeployModelAction;
import org.opensearch.ml.common.transport.deploy.MLDeployModelRequest;
import org.opensearch.ml.common.transport.deploy.MLDeployModelResponse;
import org.opensearch.ml.common.transport.register.MLRegisterModelInput;
import org.opensearch.ml.common.transport.register.MLRegisterModelResponse;
import org.opensearch.ml.common.transport.upload_chunk.MLRegisterModelMetaInput;
import org.opensearch.ml.engine.MLEngine;
import org.opensearch.ml.engine.MLExecutable;
import org.opensearch.ml.engine.ModelHelper;
import org.opensearch.ml.engine.Predictable;
import org.opensearch.ml.engine.indices.MLIndicesHandler;
import org.opensearch.ml.engine.utils.FileUtils;
import org.opensearch.ml.profile.MLModelProfile;
import org.opensearch.ml.settings.MLFeatureEnabledSetting;
import org.opensearch.ml.stats.ActionName;
import org.opensearch.ml.stats.MLActionLevelStat;
import org.opensearch.ml.stats.MLNodeLevelStat;
import org.opensearch.ml.stats.MLStats;
import org.opensearch.ml.task.MLTaskManager;
import org.opensearch.ml.utils.MLExceptionUtils;
import org.opensearch.ml.utils.MLNodeUtils;
import org.opensearch.script.ScriptService;
import org.opensearch.search.fetch.subphase.FetchSourceContext;
import org.opensearch.threadpool.ThreadPool;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import lombok.extern.log4j.Log4j2;
/**
* Manager class for ML models. It contains ML model related operations like
* register, deploy model etc.
*/
@Log4j2
public class MLModelManager {
public static final int TIMEOUT_IN_MILLIS = 5000;
public static final long MODEL_FILE_SIZE_LIMIT = 4l * 1024 * 1024 * 1024;// 4GB
private final Client client;
private final ClusterService clusterService;
private final ScriptService scriptService;
private ThreadPool threadPool;
private NamedXContentRegistry xContentRegistry;
private ModelHelper modelHelper;
private final MLModelCacheHelper modelCacheHelper;
private final MLStats mlStats;
private final MLCircuitBreakerService mlCircuitBreakerService;
private final MLIndicesHandler mlIndicesHandler;
private final MLTaskManager mlTaskManager;
private final MLEngine mlEngine;
private final DiscoveryNodeHelper nodeHelper;
private final MLFeatureEnabledSetting mlFeatureEnabledSetting;
private volatile Integer maxModelPerNode;
private volatile Integer maxRegisterTasksPerNode;
private volatile Integer maxDeployTasksPerNode;
public static final ImmutableSet MODEL_DONE_STATES = ImmutableSet
.of(
MLModelState.TRAINED,
MLModelState.REGISTERED,
MLModelState.DEPLOYED,
MLModelState.PARTIALLY_DEPLOYED,
MLModelState.DEPLOY_FAILED,
MLModelState.UNDEPLOYED
);
public MLModelManager(
ClusterService clusterService,
ScriptService scriptService,
Client client,
ThreadPool threadPool,
NamedXContentRegistry xContentRegistry,
ModelHelper modelHelper,
Settings settings,
MLStats mlStats,
MLCircuitBreakerService mlCircuitBreakerService,
MLIndicesHandler mlIndicesHandler,
MLTaskManager mlTaskManager,
MLModelCacheHelper modelCacheHelper,
MLEngine mlEngine,
DiscoveryNodeHelper nodeHelper,
MLFeatureEnabledSetting mlFeatureEnabledSetting
) {
this.client = client;
this.threadPool = threadPool;
this.xContentRegistry = xContentRegistry;
this.modelHelper = modelHelper;
this.clusterService = clusterService;
this.scriptService = scriptService;
this.modelCacheHelper = modelCacheHelper;
this.mlStats = mlStats;
this.mlCircuitBreakerService = mlCircuitBreakerService;
this.mlIndicesHandler = mlIndicesHandler;
this.mlTaskManager = mlTaskManager;
this.mlEngine = mlEngine;
this.nodeHelper = nodeHelper;
this.mlFeatureEnabledSetting = mlFeatureEnabledSetting;
this.maxModelPerNode = ML_COMMONS_MAX_MODELS_PER_NODE.get(settings);
clusterService.getClusterSettings().addSettingsUpdateConsumer(ML_COMMONS_MAX_MODELS_PER_NODE, it -> maxModelPerNode = it);
maxRegisterTasksPerNode = ML_COMMONS_MAX_REGISTER_MODEL_TASKS_PER_NODE.get(settings);
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(ML_COMMONS_MAX_REGISTER_MODEL_TASKS_PER_NODE, it -> maxRegisterTasksPerNode = it);
maxDeployTasksPerNode = ML_COMMONS_MAX_DEPLOY_MODEL_TASKS_PER_NODE.get(settings);
clusterService
.getClusterSettings()
.addSettingsUpdateConsumer(ML_COMMONS_MAX_DEPLOY_MODEL_TASKS_PER_NODE, it -> maxDeployTasksPerNode = it);
}
public void registerModelMeta(MLRegisterModelMetaInput mlRegisterModelMetaInput, ActionListener<String> listener) {
try {
FunctionName functionName = mlRegisterModelMetaInput.getFunctionName();
mlStats.getStat(MLNodeLevelStat.ML_REQUEST_COUNT).increment();
mlStats.createCounterStatIfAbsent(functionName, REGISTER, ML_ACTION_REQUEST_COUNT).increment();
String modelGroupId = mlRegisterModelMetaInput.getModelGroupId();
if (Strings.isBlank(modelGroupId)) {
uploadMLModelMeta(mlRegisterModelMetaInput, "1", listener);
} else {
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
ActionListener<String> wrappedListener = ActionListener.runBefore(listener, () -> context.restore());
GetRequest getModelGroupRequest = new GetRequest(ML_MODEL_GROUP_INDEX).id(modelGroupId);
client.get(getModelGroupRequest, ActionListener.wrap(modelGroup -> {
if (modelGroup.isExists()) {
Map<String, Object> modelGroupSource = modelGroup.getSourceAsMap();
int updatedVersion = incrementLatestVersion(modelGroupSource);
UpdateRequest updateModelGroupRequest = createUpdateModelGroupRequest(
modelGroupSource,
modelGroupId,
modelGroup.getSeqNo(),
modelGroup.getPrimaryTerm(),
updatedVersion
);
client.update(updateModelGroupRequest, ActionListener.wrap(r -> {
uploadMLModelMeta(mlRegisterModelMetaInput, updatedVersion + "", wrappedListener);
}, e -> {
log.error("Failed to update model group", e);
wrappedListener.onFailure(e);
}));
} else {
log.error("Model group not found");
wrappedListener.onFailure(new MLResourceNotFoundException("Fail to find model group"));
}
}, e -> {
if (e instanceof IndexNotFoundException) {
wrappedListener.onFailure(new MLResourceNotFoundException("Fail to find model group"));
} else {
log.error("Failed to get model group", e);
wrappedListener.onFailure(new MLValidationException("Failed to get model group"));
}
}));
} catch (Exception e) {
log.error("Failed to register model", e);
listener.onFailure(e);
}
}
} catch (final Exception e) {
log.error("Failed to init model index", e);
listener.onFailure(e);
}
}
private void uploadMLModelMeta(MLRegisterModelMetaInput mlRegisterModelMetaInput, String version, ActionListener<String> listener) {
FunctionName functionName = mlRegisterModelMetaInput.getFunctionName();
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
ActionListener<String> wrappedListener = ActionListener.runBefore(listener, () -> context.restore());
String modelName = mlRegisterModelMetaInput.getName();
mlIndicesHandler.initModelIndexIfAbsent(ActionListener.wrap(res -> {
if (!res) {
wrappedListener.onFailure(new RuntimeException("No response to create ML Model index"));
return;
}
Instant now = Instant.now();
MLModel mlModelMeta = MLModel
.builder()
.name(modelName)
.algorithm(functionName)
.version(version)
.modelGroupId(mlRegisterModelMetaInput.getModelGroupId())
.description(mlRegisterModelMetaInput.getDescription())
.isEnabled(mlRegisterModelMetaInput.getIsEnabled())
.rateLimiter(mlRegisterModelMetaInput.getRateLimiter())
.isEnabled(mlRegisterModelMetaInput.getIsEnabled())
.modelFormat(mlRegisterModelMetaInput.getModelFormat())
.modelState(MLModelState.REGISTERING)
.modelConfig(mlRegisterModelMetaInput.getModelConfig())
.deploySetting(mlRegisterModelMetaInput.getDeploySetting())
.totalChunks(mlRegisterModelMetaInput.getTotalChunks())
.modelContentHash(mlRegisterModelMetaInput.getModelContentHashValue())
.modelContentSizeInBytes(mlRegisterModelMetaInput.getModelContentSizeInBytes())
.isHidden(mlRegisterModelMetaInput.getIsHidden())
.modelInterface(mlRegisterModelMetaInput.getModelInterface())
.createdTime(now)
.lastUpdateTime(now)
.build();
IndexRequest indexRequest = new IndexRequest(ML_MODEL_INDEX);
if (mlRegisterModelMetaInput.getIsHidden() != null && mlRegisterModelMetaInput.getIsHidden()) {
indexRequest.id(modelName);
}
indexRequest.source(mlModelMeta.toXContent(XContentBuilder.builder(JSON.xContent()), EMPTY_PARAMS));
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
client.index(indexRequest, ActionListener.wrap(response -> {
log.debug("Index model meta doc successfully {}", modelName);
wrappedListener.onResponse(response.getId());
}, e -> {
deleteOrUpdateModelGroup(
mlRegisterModelMetaInput.getModelGroupId(),
mlRegisterModelMetaInput.getDoesVersionCreateModelGroup(),
version
);
log.error("Failed to index model meta doc", e);
wrappedListener.onFailure(e);
}));
}, ex -> {
log.error("Failed to init model index", ex);
wrappedListener.onFailure(ex);
}));
} catch (Exception e) {
log.error("Failed to register model", e);
listener.onFailure(e);
}
}
/**
*
* @param mlRegisterModelInput register model input for remote models
* @param mlTask ML task
* @param listener action listener
*/
public void registerMLRemoteModel(
MLRegisterModelInput mlRegisterModelInput,
MLTask mlTask,
ActionListener<MLRegisterModelResponse> listener
) {
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
checkAndAddRunningTask(mlTask, maxRegisterTasksPerNode);
mlStats.getStat(MLNodeLevelStat.ML_REQUEST_COUNT).increment();
mlStats.createCounterStatIfAbsent(mlTask.getFunctionName(), REGISTER, ML_ACTION_REQUEST_COUNT).increment();
mlStats.getStat(MLNodeLevelStat.ML_EXECUTING_TASK_COUNT).increment();
String modelGroupId = mlRegisterModelInput.getModelGroupId();
GetRequest getModelGroupRequest = new GetRequest(ML_MODEL_GROUP_INDEX).id(modelGroupId);
client.get(getModelGroupRequest, ActionListener.wrap(getModelGroupResponse -> {
if (getModelGroupResponse.isExists()) {
Map<String, Object> modelGroupSourceMap = getModelGroupResponse.getSourceAsMap();
int updatedVersion = incrementLatestVersion(modelGroupSourceMap);
UpdateRequest updateModelGroupRequest = createUpdateModelGroupRequest(
modelGroupSourceMap,
modelGroupId,
getModelGroupResponse.getSeqNo(),
getModelGroupResponse.getPrimaryTerm(),
updatedVersion
);
client.update(updateModelGroupRequest, ActionListener.wrap(r -> {
indexRemoteModel(mlRegisterModelInput, mlTask, updatedVersion + "", listener);
}, e -> {
log.error("Failed to update model group " + modelGroupId, e);
handleException(mlRegisterModelInput.getFunctionName(), mlTask.getTaskId(), e);
listener.onFailure(e);
}));
} else {
log.error("Model group response is empty");
handleException(
mlRegisterModelInput.getFunctionName(),
mlTask.getTaskId(),
new MLValidationException("Model group not found")
);
listener.onFailure(new MLResourceNotFoundException("Model Group Response is empty for " + modelGroupId));
}
}, error -> {
if (error instanceof IndexNotFoundException) {
log.error("Model group Index is missing");
handleException(
mlRegisterModelInput.getFunctionName(),
mlTask.getTaskId(),
new MLResourceNotFoundException("Failed to get model group due to index missing")
);
listener.onFailure(error);
} else {
log.error("Failed to get model group", error);
handleException(mlRegisterModelInput.getFunctionName(), mlTask.getTaskId(), error);
listener.onFailure(error);
}
}));
} catch (Exception e) {
log.error("Failed to register remote model", e);
handleException(mlRegisterModelInput.getFunctionName(), mlTask.getTaskId(), e);
listener.onFailure(e);
} finally {
mlStats.getStat(MLNodeLevelStat.ML_EXECUTING_TASK_COUNT).decrement();
}
}
/**
* Register model. Basically download model file, split into chunks and save
* into model index.
*
* @param registerModelInput register model input
* @param mlTask ML task
*/
public void registerMLModel(MLRegisterModelInput registerModelInput, MLTask mlTask) {
checkAndAddRunningTask(mlTask, maxRegisterTasksPerNode);
try {
mlStats.getStat(MLNodeLevelStat.ML_REQUEST_COUNT).increment();
mlStats.createCounterStatIfAbsent(mlTask.getFunctionName(), REGISTER, ML_ACTION_REQUEST_COUNT).increment();
mlStats.getStat(MLNodeLevelStat.ML_EXECUTING_TASK_COUNT).increment();
String modelGroupId = registerModelInput.getModelGroupId();
GetRequest getModelGroupRequest = new GetRequest(ML_MODEL_GROUP_INDEX).id(modelGroupId);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
client.get(getModelGroupRequest, ActionListener.runBefore(ActionListener.wrap(modelGroup -> {
if (modelGroup.isExists()) {
Map<String, Object> modelGroupSourceMap = modelGroup.getSourceAsMap();
int updatedVersion = incrementLatestVersion(modelGroupSourceMap);
UpdateRequest updateModelGroupRequest = createUpdateModelGroupRequest(
modelGroupSourceMap,
modelGroupId,
modelGroup.getSeqNo(),
modelGroup.getPrimaryTerm(),
updatedVersion
);
try (ThreadContext.StoredContext threadContext = client.threadPool().getThreadContext().stashContext()) {
client
.update(
updateModelGroupRequest,
ActionListener.wrap(r -> { uploadModel(registerModelInput, mlTask, updatedVersion + ""); }, e -> {
log.error("Failed to update model group", e);
handleException(registerModelInput.getFunctionName(), mlTask.getTaskId(), e);
})
);
}
} else {
log.error("Model group not found");
handleException(
registerModelInput.getFunctionName(),
mlTask.getTaskId(),
new MLValidationException("Model group not found")
);
}
}, e -> {
if (e instanceof IndexNotFoundException) {
handleException(
registerModelInput.getFunctionName(),
mlTask.getTaskId(),
new MLResourceNotFoundException("Failed to get model group")
);
} else {
log.error("Failed to get model group", e);
handleException(registerModelInput.getFunctionName(), mlTask.getTaskId(), e);
}
}), () -> context.restore()));
} catch (Exception e) {
log.error("Failed to register model", e);
handleException(registerModelInput.getFunctionName(), mlTask.getTaskId(), e);
}
} catch (Exception e) {
handleException(registerModelInput.getFunctionName(), mlTask.getTaskId(), e);
} finally {
mlStats.getStat(MLNodeLevelStat.ML_EXECUTING_TASK_COUNT).decrement();
}
}
private UpdateRequest createUpdateModelGroupRequest(
Map<String, Object> modelGroupSourceMap,
String modelGroupId,
long seqNo,
long primaryTerm,
int updatedVersion
) {
modelGroupSourceMap.put(MLModelGroup.LATEST_VERSION_FIELD, updatedVersion);
modelGroupSourceMap.put(MLModelGroup.LAST_UPDATED_TIME_FIELD, Instant.now().toEpochMilli());
UpdateRequest updateModelGroupRequest = new UpdateRequest();
updateModelGroupRequest
.index(ML_MODEL_GROUP_INDEX)
.id(modelGroupId)
.setIfSeqNo(seqNo)
.setIfPrimaryTerm(primaryTerm)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.doc(modelGroupSourceMap);
return updateModelGroupRequest;
}
private int incrementLatestVersion(Map<String, Object> modelGroupSourceMap) {
return (int) modelGroupSourceMap.get(MLModelGroup.LATEST_VERSION_FIELD) + 1;
}
private void indexRemoteModel(
MLRegisterModelInput registerModelInput,
MLTask mlTask,
String modelVersion,
ActionListener<MLRegisterModelResponse> listener
) {
String taskId = mlTask.getTaskId();
FunctionName functionName = mlTask.getFunctionName();
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
String modelName = registerModelInput.getModelName();
String version = modelVersion == null ? registerModelInput.getVersion() : modelVersion;
Instant now = Instant.now();
if (registerModelInput.getConnector() != null) {
registerModelInput.getConnector().encrypt(mlEngine::encrypt);
}
mlIndicesHandler.initModelIndexIfAbsent(ActionListener.wrap(boolResponse -> {
if (!boolResponse) {
listener.onFailure(new RuntimeException("No response to create ML Model index"));
return;
}
MLModel mlModelMeta = MLModel
.builder()
.name(modelName)
.algorithm(functionName)
.modelGroupId(registerModelInput.getModelGroupId())
.version(version)
.description(registerModelInput.getDescription())
.rateLimiter(registerModelInput.getRateLimiter())
.isEnabled(registerModelInput.getIsEnabled())
.modelFormat(registerModelInput.getModelFormat())
.modelState(MLModelState.REGISTERED)
.connector(registerModelInput.getConnector())
.connectorId(registerModelInput.getConnectorId())
.modelConfig(registerModelInput.getModelConfig())
.deploySetting(registerModelInput.getDeploySetting())
.createdTime(now)
.lastUpdateTime(now)
.isHidden(registerModelInput.getIsHidden())
.guardrails(registerModelInput.getGuardrails())
.modelInterface(registerModelInput.getModelInterface())
.build();
IndexRequest indexModelMetaRequest = new IndexRequest(ML_MODEL_INDEX);
if (registerModelInput.getIsHidden() != null && registerModelInput.getIsHidden()) {
indexModelMetaRequest.id(modelName);
}
indexModelMetaRequest.source(mlModelMeta.toXContent(XContentBuilder.builder(JSON.xContent()), EMPTY_PARAMS));
indexModelMetaRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
// index remote model doc
ActionListener<IndexResponse> indexListener = ActionListener.wrap(modelMetaRes -> {
String modelId = modelMetaRes.getId();
mlTask.setModelId(modelId);
log.info("create new model meta doc {} for upload task {}", modelId, taskId);
mlTaskManager.updateMLTask(taskId, Map.of(MODEL_ID_FIELD, modelId, STATE_FIELD, COMPLETED), 5000, true);
if (registerModelInput.isDeployModel()) {
deployModelAfterRegistering(registerModelInput, modelId);
}
listener.onResponse(new MLRegisterModelResponse(taskId, MLTaskState.CREATED.name(), modelId));
}, e -> {
log.error("Failed to index model meta doc", e);
handleException(functionName, taskId, e);
listener.onFailure(e);
});
client.index(indexModelMetaRequest, threadedActionListener(REGISTER_THREAD_POOL, indexListener));
}, error -> {
// failed to initialize the model index
log.error("Failed to init model index", error);
handleException(functionName, taskId, error);
listener.onFailure(error);
}));
}
}
@VisibleForTesting
void indexRemoteModel(MLRegisterModelInput registerModelInput, MLTask mlTask, String modelVersion) {
String taskId = mlTask.getTaskId();
FunctionName functionName = mlTask.getFunctionName();
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
String modelName = registerModelInput.getModelName();
String version = modelVersion == null ? registerModelInput.getVersion() : modelVersion;
Instant now = Instant.now();
if (registerModelInput.getConnector() != null) {
registerModelInput.getConnector().encrypt(mlEngine::encrypt);
}
mlIndicesHandler.initModelIndexIfAbsent(ActionListener.runBefore(ActionListener.wrap(res -> {
if (!res) {
handleException(functionName, taskId, new RuntimeException("No response to create ML Model index"));
return;
}
MLModel mlModelMeta = MLModel
.builder()
.name(modelName)
.algorithm(functionName)
.modelGroupId(registerModelInput.getModelGroupId())
.version(version)
.description(registerModelInput.getDescription())
.rateLimiter(registerModelInput.getRateLimiter())
.isEnabled(registerModelInput.getIsEnabled())
.modelFormat(registerModelInput.getModelFormat())
.modelState(MLModelState.REGISTERED)
.connector(registerModelInput.getConnector())
.connectorId(registerModelInput.getConnectorId())
.modelConfig(registerModelInput.getModelConfig())
.deploySetting(registerModelInput.getDeploySetting())
.createdTime(now)
.lastUpdateTime(now)
.isHidden(registerModelInput.getIsHidden())
.guardrails(registerModelInput.getGuardrails())
.modelInterface(registerModelInput.getModelInterface())
.build();
IndexRequest indexModelMetaRequest = new IndexRequest(ML_MODEL_INDEX);
if (registerModelInput.getIsHidden() != null && registerModelInput.getIsHidden()) {
indexModelMetaRequest.id(modelName);
}
indexModelMetaRequest.source(mlModelMeta.toXContent(XContentBuilder.builder(JSON.xContent()), EMPTY_PARAMS));
indexModelMetaRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
// create model meta doc
ActionListener<IndexResponse> indexListener = ActionListener.wrap(modelMetaRes -> {
String modelId = modelMetaRes.getId();
mlTask.setModelId(modelId);
log.info("create new model meta doc {} for upload task {}", modelId, taskId);
mlTaskManager.updateMLTask(taskId, Map.of(MODEL_ID_FIELD, modelId, STATE_FIELD, COMPLETED), 5000, true);
if (registerModelInput.isDeployModel()) {
deployModelAfterRegistering(registerModelInput, modelId);
}
}, e -> {
log.error("Failed to index model meta doc", e);
handleException(functionName, taskId, e);
});
client.index(indexModelMetaRequest, threadedActionListener(REGISTER_THREAD_POOL, indexListener));
}, e -> {
log.error("Failed to init model index", e);
handleException(functionName, taskId, e);
}), () -> context.restore()));
} catch (Exception e) {
logException("Failed to upload model", e, log);
handleException(functionName, taskId, e);
}
}
private void uploadModel(MLRegisterModelInput registerModelInput, MLTask mlTask, String modelVersion) throws PrivilegedActionException {
if (registerModelInput.getUrl() != null) {
registerModelFromUrl(registerModelInput, mlTask, modelVersion);
} else if (registerModelInput.getFunctionName() == FunctionName.REMOTE || registerModelInput.getConnectorId() != null) {
indexRemoteModel(registerModelInput, mlTask, modelVersion);
} else {
registerPrebuiltModel(registerModelInput, mlTask, modelVersion);
}
}
private void registerModelFromUrl(MLRegisterModelInput registerModelInput, MLTask mlTask, String modelVersion) {
String taskId = mlTask.getTaskId();
FunctionName functionName = mlTask.getFunctionName();
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
String modelName = registerModelInput.getModelName();
String version = modelVersion == null ? registerModelInput.getVersion() : modelVersion;
String modelGroupId = registerModelInput.getModelGroupId();
Instant now = Instant.now();
mlIndicesHandler.initModelIndexIfAbsent(ActionListener.runBefore(ActionListener.wrap(res -> {
if (!res) {
handleException(functionName, taskId, new RuntimeException("No response to create ML Model index"));
return;
}
MLModel mlModelMeta = MLModel
.builder()
.name(modelName)
.modelGroupId(modelGroupId)
.algorithm(functionName)
.version(version)
.description(registerModelInput.getDescription())
.rateLimiter(registerModelInput.getRateLimiter())
.isEnabled(registerModelInput.getIsEnabled())
.modelFormat(registerModelInput.getModelFormat())
.modelState(MLModelState.REGISTERING)
.modelConfig(registerModelInput.getModelConfig())
.deploySetting(registerModelInput.getDeploySetting())
.createdTime(now)
.lastUpdateTime(now)
.isHidden(registerModelInput.getIsHidden())
.guardrails(registerModelInput.getGuardrails())
.modelInterface(registerModelInput.getModelInterface())
.build();
IndexRequest indexModelMetaRequest = new IndexRequest(ML_MODEL_INDEX);
if (functionName == FunctionName.METRICS_CORRELATION) {
indexModelMetaRequest.id(functionName.name());
}
if (registerModelInput.getIsHidden() != null && registerModelInput.getIsHidden()) {
indexModelMetaRequest.id(modelName);
}
indexModelMetaRequest.source(mlModelMeta.toXContent(XContentBuilder.builder(JSON.xContent()), EMPTY_PARAMS));
indexModelMetaRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
// create model meta doc
ActionListener<IndexResponse> listener = ActionListener.wrap(modelMetaRes -> {
String modelId = modelMetaRes.getId();
mlTask.setModelId(modelId);
log.info("create new model meta doc {} for register model task {}", modelId, taskId);
// model group id is not present in request body.
registerModel(registerModelInput, taskId, functionName, modelName, version, modelId);
}, e -> {
log.error("Failed to index model meta doc", e);
handleException(functionName, taskId, e);
});
client.index(indexModelMetaRequest, threadedActionListener(REGISTER_THREAD_POOL, listener));
}, e -> {
log.error("Failed to init model index", e);
handleException(functionName, taskId, e);
}), () -> context.restore()));
} catch (Exception e) {
logException("Failed to register model", e, log);
handleException(functionName, taskId, e);
}
}
private void registerModel(
MLRegisterModelInput registerModelInput,
String taskId,
FunctionName functionName,
String modelName,
String version,
String modelId
) {
modelHelper
.downloadAndSplit(
registerModelInput.getModelFormat(),
modelId,
modelName,
version,
registerModelInput.getUrl(),
registerModelInput.getHashValue(),
functionName,
ActionListener.wrap(result -> {
Long modelSizeInBytes = (Long) result.get(MODEL_SIZE_IN_BYTES);
if (modelSizeInBytes >= MODEL_FILE_SIZE_LIMIT) {
throw new MLException("Model file size exceeds the limit of 4GB: " + modelSizeInBytes);
}
List<String> chunkFiles = (List<String>) result.get(CHUNK_FILES);
String hashValue = (String) result.get(MODEL_FILE_HASH);
Semaphore semaphore = new Semaphore(1);
AtomicInteger uploaded = new AtomicInteger(0);
AtomicBoolean failedToUploadChunk = new AtomicBoolean(false);
// upload chunks
for (String name : chunkFiles) {
semaphore.tryAcquire(10, TimeUnit.SECONDS);
if (failedToUploadChunk.get()) {
throw new MLException("Failed to save model chunk");
}
File file = new File(name);
byte[] bytes = Files.toByteArray(file);
int chunkNum = Integer.parseInt(file.getName());
Instant now = Instant.now();
MLModel mlModel = MLModel
.builder()
.modelId(modelId)
.name(modelName)
.algorithm(functionName)
.version(version)
.modelFormat(registerModelInput.getModelFormat())
.rateLimiter(registerModelInput.getRateLimiter())
.isEnabled(registerModelInput.getIsEnabled())
.chunkNumber(chunkNum)
.totalChunks(chunkFiles.size())
.content(Base64.getEncoder().encodeToString(bytes))
.createdTime(now)
.lastUpdateTime(now)
.isHidden(registerModelInput.getIsHidden())
.guardrails(registerModelInput.getGuardrails())
.modelInterface(registerModelInput.getModelInterface())
.build();
IndexRequest indexRequest = new IndexRequest(ML_MODEL_INDEX);
if (registerModelInput.getIsHidden() != null && registerModelInput.getIsHidden()) {
indexRequest.id(modelName);
}
String chunkId = getModelChunkId(modelId, chunkNum);
indexRequest.id(chunkId);
indexRequest.source(mlModel.toXContent(XContentBuilder.builder(JSON.xContent()), EMPTY_PARAMS));
indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
client.index(indexRequest, ActionListener.wrap(r -> {
uploaded.getAndIncrement();
if (uploaded.get() == chunkFiles.size()) {
updateModelRegisterStateAsDone(
registerModelInput,
taskId,
modelId,
modelSizeInBytes,
chunkFiles,
hashValue,
version
);
} else {
deleteFileQuietly(file);
}
semaphore.release();
}, e -> {
log.error("Failed to index model chunk " + chunkId, e);
failedToUploadChunk.set(true);
handleException(functionName, taskId, e);
deleteFileQuietly(file);
// remove model doc as failed to upload model
deleteModel(modelId, registerModelInput, version);
semaphore.release();
deleteFileQuietly(mlEngine.getRegisterModelPath(modelId));
}));
}
}, e -> {
log.error("Failed to index chunk file", e);
deleteFileQuietly(mlEngine.getRegisterModelPath(modelId));
deleteModel(modelId, registerModelInput, version);
handleException(functionName, taskId, e);
})
);
}
private void registerPrebuiltModel(MLRegisterModelInput registerModelInput, MLTask mlTask, String modelVersion)
throws PrivilegedActionException {
String taskId = mlTask.getTaskId();
List modelMetaList = modelHelper.downloadPrebuiltModelMetaList(taskId, registerModelInput);
if (!modelHelper.isModelAllowed(registerModelInput, modelMetaList)) {
throw new IllegalArgumentException("This model is not in the pre-trained model list, please check your parameters.");
}
modelHelper.downloadPrebuiltModelConfig(taskId, registerModelInput, ActionListener.wrap(mlRegisterModelInput -> {
mlTask.setFunctionName(mlRegisterModelInput.getFunctionName());
mlTaskManager
.updateMLTask(taskId, Map.of(FUNCTION_NAME_FIELD, mlRegisterModelInput.getFunctionName()), TIMEOUT_IN_MILLIS, false);
registerModelFromUrl(mlRegisterModelInput, mlTask, modelVersion);
}, e -> {
log.error("Failed to register prebuilt model", e);
handleException(registerModelInput.getFunctionName(), taskId, e);
}));
}
private <T> ThreadedActionListener<T> threadedActionListener(String threadPoolName, ActionListener<T> listener) {
return new ThreadedActionListener<>(log, threadPool, threadPoolName, listener, false);
}
/**
* Check if exceed running task limit and if circuit breaker is open.
*
* @param mlTask ML task
* @param runningTaskLimit limit
*/
public void checkAndAddRunningTask(MLTask mlTask, Integer runningTaskLimit) {
if (Objects.nonNull(mlTask) && mlTask.getFunctionName() != FunctionName.REMOTE) {
checkOpenCircuitBreaker(mlCircuitBreakerService, mlStats);
}
mlTaskManager.checkLimitAndAddRunningTask(mlTask, runningTaskLimit);
}
private void updateModelRegisterStateAsDone(
MLRegisterModelInput registerModelInput,
String taskId,
String modelId,
Long modelSizeInBytes,
List<String> chunkFiles,
String hashValue,
String version
) {
FunctionName functionName = registerModelInput.getFunctionName();
deleteFileQuietly(mlEngine.getRegisterModelPath(modelId));
Map<String, Object> updatedFields = Map
.of(
MLModel.MODEL_STATE_FIELD,
MLModelState.REGISTERED,
MLModel.LAST_REGISTERED_TIME_FIELD,
Instant.now().toEpochMilli(),
MLModel.TOTAL_CHUNKS_FIELD,
chunkFiles.size(),
MLModel.MODEL_CONTENT_HASH_VALUE_FIELD,
hashValue,
MLModel.MODEL_CONTENT_SIZE_IN_BYTES_FIELD,
modelSizeInBytes
);
log.info("Model registered successfully, model id: {}, task id: {}", modelId, taskId);
updateModel(modelId, updatedFields, ActionListener.wrap(updateResponse -> {
mlTaskManager.updateMLTask(taskId, Map.of(STATE_FIELD, COMPLETED, MODEL_ID_FIELD, modelId), TIMEOUT_IN_MILLIS, true);
if (registerModelInput.isDeployModel()) {
deployModelAfterRegistering(registerModelInput, modelId);
}
}, e -> {
log.error("Failed to update model", e);
handleException(functionName, taskId, e);
deleteModel(modelId, registerModelInput, version);
}));
}
@VisibleForTesting
void deployModelAfterRegistering(MLRegisterModelInput registerModelInput, String modelId) {
String[] modelNodeIds = registerModelInput.getModelNodeIds();
log.debug("start deploying model after registering, modelId: {} on nodes: {}", modelId, Arrays.toString(modelNodeIds));
MLDeployModelRequest request = new MLDeployModelRequest(modelId, modelNodeIds, false, true, true);
ActionListener<MLDeployModelResponse> listener = ActionListener
.wrap(r -> log.debug("model deployed, response {}", r), e -> log.error("Failed to deploy model", e));
client.execute(MLDeployModelAction.INSTANCE, request, listener);
}
private void deleteModel(String modelId, MLRegisterModelInput registerModelInput, String modelVersion) {
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.index(ML_MODEL_INDEX).id(modelId).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
client.delete(deleteRequest);
DeleteByQueryRequest deleteChunksRequest = new DeleteByQueryRequest(ML_MODEL_INDEX)
.setQuery(new TermQueryBuilder(MLModel.MODEL_ID_FIELD, modelId))
.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN)
.setAbortOnVersionConflict(false);
client.execute(DeleteByQueryAction.INSTANCE, deleteChunksRequest);
deleteOrUpdateModelGroup(registerModelInput.getModelGroupId(), registerModelInput.getDoesVersionCreateModelGroup(), modelVersion);
}
private void deleteOrUpdateModelGroup(String modelGroupID, Boolean doesVersionCreateModelGroup, String modelVersion) {
// This checks if model group is created when registering the version. If yes,
// model group is deleted since the version registration
// had failed. Else model group latest version is decremented by 1
if (Boolean.TRUE.equals(doesVersionCreateModelGroup)) {
DeleteRequest deleteModelGroupRequest = new DeleteRequest();
deleteModelGroupRequest.index(ML_MODEL_GROUP_INDEX).id(modelGroupID).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
client.delete(deleteModelGroupRequest);
} else {
updateLatestVersionInModelGroup(
modelGroupID,
Integer.parseInt(modelVersion) - 1,
ActionListener
.wrap(r -> log.debug("model group updated, response {}", r), e -> log.error("Failed to update model group", e))
);
}
}
private void updateLatestVersionInModelGroup(String modelGroupID, Integer latestVersion, ActionListener<UpdateResponse> listener) {
Map<String, Object> updatedFields = new HashMap<>();
updatedFields.put(MLModelGroup.LATEST_VERSION_FIELD, latestVersion);
updatedFields.put(MLModelGroup.LAST_UPDATED_TIME_FIELD, Instant.now().toEpochMilli());
UpdateRequest updateRequest = new UpdateRequest(ML_MODEL_GROUP_INDEX, modelGroupID);
updateRequest.doc(updatedFields);
updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
try (ThreadContext.StoredContext context = client.threadPool().getThreadContext().stashContext()) {
client.update(updateRequest, ActionListener.runBefore(listener, () -> context.restore()));
} catch (Exception e) {
listener.onFailure(e);
}
}
private void handleException(FunctionName functionName, String taskId, Exception e) {
if (!(e instanceof MLLimitExceededException)
&& !(e instanceof MLResourceNotFoundException)
&& !(e instanceof IllegalArgumentException)) {
mlStats.createCounterStatIfAbsent(functionName, REGISTER, MLActionLevelStat.ML_ACTION_FAILURE_COUNT).increment();
mlStats.getStat(MLNodeLevelStat.ML_FAILURE_COUNT).increment();
}
Map<String, Object> updated = Map.of(ERROR_FIELD, MLExceptionUtils.getRootCauseMessage(e), STATE_FIELD, FAILED);
mlTaskManager.updateMLTask(taskId, updated, TIMEOUT_IN_MILLIS, true);
}
/**
* Read model chunks from model index. Concat chunks into a whole model file,
* then load
* into memory.
*
* @param modelId model id
* @param modelContentHash model content hash value
* @param functionName function name
* @param mlTask ML task
* @param listener action listener
*/
public void deployModel(
String modelId,
String modelContentHash,
FunctionName functionName,
boolean deployToAllNodes,
boolean autoDeployModel,
MLTask mlTask,
ActionListener<String> listener
) {
mlStats.createCounterStatIfAbsent(functionName, ActionName.DEPLOY, ML_ACTION_REQUEST_COUNT).increment();
mlStats.getStat(MLNodeLevelStat.ML_EXECUTING_TASK_COUNT).increment();
mlStats.getStat(MLNodeLevelStat.ML_REQUEST_COUNT).increment();
mlStats.createModelCounterStatIfAbsent(modelId, ActionName.DEPLOY, ML_ACTION_REQUEST_COUNT).increment();
List<String> workerNodes = mlTask.getWorkerNodes();
if (modelCacheHelper.isModelDeployed(modelId)) {
if (!autoDeployModel && workerNodes != null && !workerNodes.isEmpty()) {
log.info("Set new target node ids {} for model {}", Arrays.toString(workerNodes.toArray(new String[0])), modelId);
modelCacheHelper.setDeployToAllNodes(modelId, deployToAllNodes);
modelCacheHelper.setTargetWorkerNodes(modelId, workerNodes);