-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
deployment_state.py
2744 lines (2357 loc) · 108 KB
/
deployment_state.py
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
import json
import logging
import math
import os
import random
import time
import traceback
from collections import defaultdict
from copy import copy
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import ray
from ray import ObjectRef, cloudpickle
from ray.actor import ActorHandle
from ray.exceptions import RayActorError, RayError, RayTaskError, RuntimeEnvSetupError
from ray.serve import metrics
from ray.serve._private import default_impl
from ray.serve._private.autoscaling_policy import AutoscalingPolicyManager
from ray.serve._private.cluster_node_info_cache import ClusterNodeInfoCache
from ray.serve._private.common import (
DeploymentID,
DeploymentStatus,
DeploymentStatusInfo,
DeploymentStatusInternalTrigger,
DeploymentStatusTrigger,
Duration,
MultiplexedReplicaInfo,
ReplicaName,
ReplicaState,
ReplicaTag,
RunningReplicaInfo,
)
from ray.serve._private.config import DeploymentConfig
from ray.serve._private.constants import (
MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT,
RAY_SERVE_COLLECT_AUTOSCALING_METRICS_ON_HANDLE,
RAY_SERVE_FORCE_STOP_UNHEALTHY_REPLICAS,
REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD,
SERVE_LOGGER_NAME,
SERVE_NAMESPACE,
)
from ray.serve._private.deployment_info import DeploymentInfo
from ray.serve._private.deployment_scheduler import (
DeploymentDownscaleRequest,
DeploymentScheduler,
ReplicaSchedulingRequest,
SpreadDeploymentSchedulingPolicy,
)
from ray.serve._private.long_poll import LongPollHost, LongPollNamespace
from ray.serve._private.storage.kv_store import KVStoreBase
from ray.serve._private.usage import ServeUsageTag
from ray.serve._private.utils import (
JavaActorHandleProxy,
check_obj_ref_ready_nowait,
format_actor_name,
get_capacity_adjusted_num_replicas,
get_random_string,
msgpack_deserialize,
msgpack_serialize,
)
from ray.serve._private.version import DeploymentVersion, VersionedReplica
from ray.serve.generated.serve_pb2 import DeploymentLanguage
from ray.serve.schema import (
DeploymentDetails,
ReplicaDetails,
_deployment_info_to_schema,
)
from ray.util.placement_group import PlacementGroup
logger = logging.getLogger(SERVE_LOGGER_NAME)
class ReplicaStartupStatus(Enum):
PENDING_ALLOCATION = 1
PENDING_INITIALIZATION = 2
SUCCEEDED = 3
FAILED = 4
class ReplicaHealthCheckResponse(Enum):
NONE = 1
SUCCEEDED = 2
APP_FAILURE = 3
ACTOR_CRASHED = 4
@dataclass
class DeploymentTargetState:
"""The current goal state for a deployment.
info: contains the information needed to initialize a replica.
target_num_replicas: the number of replicas to run. This should already
be adjusted by the target_capacity.
version: the goal version of the deployment.
deleting: whether the deployment is being deleted.
"""
info: Optional[DeploymentInfo]
target_num_replicas: int
version: Optional[DeploymentVersion]
deleting: bool
@classmethod
def default(cls) -> "DeploymentTargetState":
return cls(None, -1, None, False)
@classmethod
def create(
cls,
info: DeploymentInfo,
target_num_replicas: int,
*,
deleting: bool = False,
) -> "DeploymentTargetState":
if deleting:
if target_num_replicas != 0:
raise ValueError(
"target_num_replicas must be 0 when setting target state "
f"to deleting. Got {target_num_replicas} instead."
)
version = DeploymentVersion(
info.version,
deployment_config=info.deployment_config,
ray_actor_options=info.replica_config.ray_actor_options,
placement_group_bundles=info.replica_config.placement_group_bundles,
placement_group_strategy=info.replica_config.placement_group_strategy,
max_replicas_per_node=info.replica_config.max_replicas_per_node,
)
return cls(info, target_num_replicas, version, deleting)
def is_scaled_copy_of(self, other_target_state: "DeploymentTargetState") -> bool:
"""Checks if this target state is a scaled copy of another target state.
A target state is a scaled copy of another target state if all
configurable info is identical, other than target_num_replicas.
Returns: True if this target state contains a non-None DeploymentInfo
and is a scaled copy of the other target state.
"""
if other_target_state.info is None:
return False
return all(
[
self.info.replica_config.ray_actor_options
== other_target_state.info.replica_config.ray_actor_options,
self.info.replica_config.placement_group_bundles
== other_target_state.info.replica_config.placement_group_bundles,
self.info.replica_config.placement_group_strategy
== other_target_state.info.replica_config.placement_group_strategy,
self.info.replica_config.max_replicas_per_node
== other_target_state.info.replica_config.max_replicas_per_node,
self.info.deployment_config.dict(exclude={"num_replicas"})
== other_target_state.info.deployment_config.dict(
exclude={"num_replicas"}
),
# TODO(zcin): version can be None, this is from an outdated codepath.
# We should remove outdated code, so version can never be None.
self.version,
self.version == other_target_state.version,
]
)
@dataclass
class DeploymentStateUpdateResult:
deleted: bool
any_replicas_recovering: bool
upscale: List[ReplicaSchedulingRequest]
downscale: Optional[DeploymentDownscaleRequest]
CHECKPOINT_KEY = "serve-deployment-state-checkpoint"
SLOW_STARTUP_WARNING_S = int(os.environ.get("SERVE_SLOW_STARTUP_WARNING_S", 30))
SLOW_STARTUP_WARNING_PERIOD_S = int(
os.environ.get("SERVE_SLOW_STARTUP_WARNING_PERIOD_S", 30)
)
EXPONENTIAL_BACKOFF_FACTOR = float(os.environ.get("EXPONENTIAL_BACKOFF_FACTOR", 2.0))
MAX_BACKOFF_TIME_S = int(os.environ.get("SERVE_MAX_BACKOFF_TIME_S", 64))
ALL_REPLICA_STATES = list(ReplicaState)
_SCALING_LOG_ENABLED = os.environ.get("SERVE_ENABLE_SCALING_LOG", "0") != "0"
def print_verbose_scaling_log():
assert _SCALING_LOG_ENABLED
log_path = "/tmp/ray/session_latest/logs/monitor.log"
last_n_lines = 50
autoscaler_log_last_n_lines = []
if os.path.exists(log_path):
with open(log_path) as f:
autoscaler_log_last_n_lines = f.readlines()[-last_n_lines:]
debug_info = {
"nodes": ray.nodes(),
"available_resources": ray.available_resources(),
"total_resources": ray.cluster_resources(),
"autoscaler_logs": autoscaler_log_last_n_lines,
}
logger.error(f"Scaling information\n{json.dumps(debug_info, indent=2)}")
class ActorReplicaWrapper:
"""Wraps a Ray actor for a deployment replica.
This is primarily defined so that we can mock out actual Ray operations
for unit testing.
*All Ray API calls should be made here, not in DeploymentState.*
"""
def __init__(
self,
actor_name: str,
replica_tag: ReplicaTag,
deployment_id: DeploymentID,
version: DeploymentVersion,
):
self._actor_name = actor_name
self._replica_tag = replica_tag
self._deployment_id = deployment_id
# Populated in either self.start() or self.recover()
self._allocated_obj_ref: ObjectRef = None
self._ready_obj_ref: ObjectRef = None
self._actor_resources: Dict[str, float] = None
# If the replica is being started, this will be the true version
# If the replica is being recovered, this will be the target
# version, which may be inconsistent with the actual replica
# version. If so, the actual version will be updated later after
# recover() and check_ready()
self._version: DeploymentVersion = version
self._healthy: bool = True
self._health_check_ref: Optional[ObjectRef] = None
self._last_health_check_time: float = 0.0
self._consecutive_health_check_failures = 0
# Populated in `on_scheduled` or `recover`.
self._actor_handle: ActorHandle = None
self._placement_group: PlacementGroup = None
# Populated after replica is allocated.
self._pid: int = None
self._actor_id: str = None
self._worker_id: str = None
self._node_id: str = None
self._node_ip: str = None
self._log_file_path: str = None
# Populated in self.stop().
self._graceful_shutdown_ref: ObjectRef = None
# todo: will be confused with deployment_config.is_cross_language
self._is_cross_language = False
self._deployment_is_cross_language = False
@property
def replica_tag(self) -> str:
return self._replica_tag
@property
def deployment_name(self) -> str:
return self._deployment_id.name
@property
def app_name(self) -> str:
return self._deployment_id.app
@property
def is_cross_language(self) -> bool:
return self._is_cross_language
@property
def actor_handle(self) -> Optional[ActorHandle]:
if not self._actor_handle:
try:
self._actor_handle = ray.get_actor(
self._actor_name, namespace=SERVE_NAMESPACE
)
except ValueError:
self._actor_handle = None
if self._is_cross_language:
assert isinstance(self._actor_handle, JavaActorHandleProxy)
return self._actor_handle.handle
return self._actor_handle
@property
def placement_group_bundles(self) -> Optional[List[Dict[str, float]]]:
if not self._placement_group:
return None
return self._placement_group.bundle_specs
@property
def version(self) -> DeploymentVersion:
"""Replica version. This can be incorrect during state recovery.
If the controller crashes and the deployment state is being
recovered, this will temporarily be the deployment-wide target
version, which may be inconsistent with the actual version
running on the replica actor. If so, the actual version will be
updated when the replica transitions from RECOVERING -> RUNNING
"""
return self._version
@property
def deployment_config(self) -> DeploymentConfig:
"""Deployment config. This can return an incorrect config during state recovery.
If the controller hasn't yet recovered the up-to-date version
from the running replica actor, this property will return the
current target config for the deployment.
"""
return self._version.deployment_config
@property
def max_concurrent_queries(self) -> int:
return self.deployment_config.max_concurrent_queries
@property
def graceful_shutdown_timeout_s(self) -> float:
return self.deployment_config.graceful_shutdown_timeout_s
@property
def health_check_period_s(self) -> float:
return self.deployment_config.health_check_period_s
@property
def health_check_timeout_s(self) -> float:
return self.deployment_config.health_check_timeout_s
@property
def pid(self) -> Optional[int]:
"""Returns the pid of the actor, None if not started."""
return self._pid
@property
def actor_id(self) -> Optional[str]:
"""Returns the actor id, None if not started."""
return self._actor_id
@property
def worker_id(self) -> Optional[str]:
"""Returns the worker id, None if not started."""
return self._worker_id
@property
def node_id(self) -> Optional[str]:
"""Returns the node id of the actor, None if not placed."""
return self._node_id
@property
def node_ip(self) -> Optional[str]:
"""Returns the node ip of the actor, None if not placed."""
return self._node_ip
@property
def log_file_path(self) -> Optional[str]:
"""Returns the relative log file path of the actor, None if not placed."""
return self._log_file_path
def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest:
"""Start the current DeploymentReplica instance.
The replica will be in the STARTING and PENDING_ALLOCATION states
until the deployment scheduler schedules the underlying actor.
"""
self._actor_resources = deployment_info.replica_config.resource_dict
# it is currently not possible to create a placement group
# with no resources (https://github.com/ray-project/ray/issues/20401)
self._deployment_is_cross_language = (
deployment_info.deployment_config.is_cross_language
)
logger.info(
f"Starting replica {self.replica_tag} for deployment "
f"{self.deployment_name} in application '{self.app_name}'.",
extra={"log_to_stderr": False},
)
actor_def = deployment_info.actor_def
if (
deployment_info.deployment_config.deployment_language
== DeploymentLanguage.PYTHON
):
if deployment_info.replica_config.serialized_init_args is None:
serialized_init_args = cloudpickle.dumps(())
else:
serialized_init_args = (
cloudpickle.dumps(
msgpack_deserialize(
deployment_info.replica_config.serialized_init_args
)
)
if self._deployment_is_cross_language
else deployment_info.replica_config.serialized_init_args
)
init_args = (
self._deployment_id,
self.replica_tag,
cloudpickle.dumps(deployment_info.replica_config.deployment_def)
if self._deployment_is_cross_language
else deployment_info.replica_config.serialized_deployment_def,
serialized_init_args,
deployment_info.replica_config.serialized_init_kwargs
if deployment_info.replica_config.serialized_init_kwargs
else cloudpickle.dumps({}),
deployment_info.deployment_config.to_proto_bytes(),
self._version,
)
# TODO(simon): unify the constructor arguments across language
elif (
deployment_info.deployment_config.deployment_language
== DeploymentLanguage.JAVA
):
self._is_cross_language = True
actor_def = ray.cross_language.java_actor_class(
"io.ray.serve.replica.RayServeWrappedReplica"
)
init_args = (
# String deploymentName,
self.deployment_name,
# String replicaTag,
self.replica_tag,
# String deploymentDef
deployment_info.replica_config.deployment_def_name,
# byte[] initArgsbytes
msgpack_serialize(
cloudpickle.loads(
deployment_info.replica_config.serialized_init_args
)
)
if self._deployment_is_cross_language
else deployment_info.replica_config.serialized_init_args,
# byte[] deploymentConfigBytes,
deployment_info.deployment_config.to_proto_bytes(),
# byte[] deploymentVersionBytes,
self._version.to_proto().SerializeToString(),
# String controllerName
# String appName
self.app_name,
)
actor_options = {
"name": self._actor_name,
"namespace": SERVE_NAMESPACE,
"lifetime": "detached",
}
actor_options.update(deployment_info.replica_config.ray_actor_options)
return ReplicaSchedulingRequest(
deployment_id=self._deployment_id,
replica_name=self.replica_tag,
actor_def=actor_def,
actor_resources=self._actor_resources,
actor_options=actor_options,
actor_init_args=init_args,
placement_group_bundles=(
deployment_info.replica_config.placement_group_bundles
),
placement_group_strategy=(
deployment_info.replica_config.placement_group_strategy
),
max_replicas_per_node=(
deployment_info.replica_config.max_replicas_per_node
),
on_scheduled=self.on_scheduled,
)
def on_scheduled(
self,
actor_handle: ActorHandle,
placement_group: Optional[PlacementGroup] = None,
):
self._actor_handle = actor_handle
self._placement_group = placement_group
# Perform auto method name translation for java handles.
# See https://github.com/ray-project/ray/issues/21474
deployment_config = copy(self._version.deployment_config)
deployment_config.user_config = self._format_user_config(
deployment_config.user_config
)
if self._is_cross_language:
self._actor_handle = JavaActorHandleProxy(self._actor_handle)
self._allocated_obj_ref = self._actor_handle.is_allocated.remote()
self._ready_obj_ref = self._actor_handle.is_initialized.remote(
deployment_config.to_proto_bytes()
)
else:
self._allocated_obj_ref = self._actor_handle.is_allocated.remote()
replica_ready_check_func = self._actor_handle.initialize_and_get_metadata
self._ready_obj_ref = replica_ready_check_func.remote(
deployment_config,
# Ensure that `is_allocated` will execute
# before `initialize_and_get_metadata`,
# because `initialize_and_get_metadata` runs
# user code that could block the replica
# asyncio loop. If that happens before `is_allocated` is executed,
# the `is_allocated` call won't be able to run.
self._allocated_obj_ref,
)
def _format_user_config(self, user_config: Any):
temp = copy(user_config)
if user_config is not None and self._deployment_is_cross_language:
if self._is_cross_language:
temp = msgpack_serialize(temp)
else:
temp = msgpack_deserialize(temp)
return temp
def reconfigure(self, version: DeploymentVersion) -> bool:
"""
Update replica version. Also, updates the deployment config on the actor
behind this DeploymentReplica instance if necessary.
Returns: whether the actor is being updated.
"""
updating = False
if self._version.requires_actor_reconfigure(version):
# Call into replica actor reconfigure() with updated user config and
# graceful_shutdown_wait_loop_s
updating = True
deployment_config = copy(version.deployment_config)
deployment_config.user_config = self._format_user_config(
deployment_config.user_config
)
self._ready_obj_ref = self._actor_handle.reconfigure.remote(
deployment_config
)
self._version = version
return updating
def recover(self) -> bool:
"""Recover replica version from a live replica actor.
When controller dies, the deployment state loses the info on the version that's
running on each individual replica actor, so as part of the recovery process, we
need to recover the version that is running on the replica actor.
Also confirm that actor is allocated and initialized before marking as running.
Returns: False if the replica actor is no longer alive; the
actor could have been killed in the time between when the
controller fetching all Serve actors in the cluster and when
the controller tries to recover it. Otherwise, return True.
"""
logger.info(
f"Recovering replica {self.replica_tag} for deployment "
f"{self.deployment_name} in application '{self.app_name}'."
)
try:
self._actor_handle = ray.get_actor(
self._actor_name, namespace=SERVE_NAMESPACE
)
except ValueError:
logger.warning(
f"Failed to get handle to replica {self._actor_name} "
"during controller recovery. Marking as dead."
)
return False
try:
self._placement_group = ray.util.get_placement_group(
self._actor_name,
)
except ValueError:
# ValueError is raised if the placement group does not exist.
self._placement_group = None
# Re-fetch initialization proof
self._allocated_obj_ref = self._actor_handle.is_allocated.remote()
# Running actor handle already has all info needed, thus successful
# starting simply means retrieving replica version hash from actor
if self._is_cross_language:
self._ready_obj_ref = self._actor_handle.check_health.remote()
else:
self._ready_obj_ref = (
self._actor_handle.initialize_and_get_metadata.remote()
)
return True
def check_ready(self) -> Tuple[ReplicaStartupStatus, Optional[str]]:
"""
Check if current replica has started by making ray API calls on
relevant actor / object ref.
Replica initialization calls __init__(), reconfigure(), and check_health().
Returns:
state (ReplicaStartupStatus):
PENDING_ALLOCATION: replica is waiting for a worker to start
PENDING_INITIALIZATION: replica initialization hasn't finished.
FAILED: replica initialization failed.
SUCCEEDED: replica initialization succeeded.
error_msg:
None: for PENDING_ALLOCATION, PENDING_INITIALIZATION or SUCCEEDED states
str: for FAILED state
"""
# Check whether the replica has been allocated.
if self._allocated_obj_ref is None or not check_obj_ref_ready_nowait(
self._allocated_obj_ref
):
return ReplicaStartupStatus.PENDING_ALLOCATION, None
if not self._is_cross_language:
try:
(
self._pid,
self._actor_id,
self._worker_id,
self._node_id,
self._node_ip,
self._log_file_path,
) = ray.get(self._allocated_obj_ref)
except RayTaskError as e:
logger.exception(
f"Exception in replica '{self._replica_tag}', "
"the replica will be stopped."
)
return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause())
except RuntimeEnvSetupError as e:
msg = (
f"Exception when allocating replica '{self._replica_tag}': {str(e)}"
)
logger.exception(msg)
return ReplicaStartupStatus.FAILED, msg
except Exception:
msg = (
f"Exception when allocating replica '{self._replica_tag}':\n"
+ traceback.format_exc()
)
logger.exception(msg)
return ReplicaStartupStatus.FAILED, msg
# Check whether relica initialization has completed.
replica_ready = check_obj_ref_ready_nowait(self._ready_obj_ref)
# In case of deployment constructor failure, ray.get will help to
# surface exception to each update() cycle.
if not replica_ready:
return ReplicaStartupStatus.PENDING_INITIALIZATION, None
else:
try:
# TODO(simon): fully implement reconfigure for Java replicas.
if self._is_cross_language:
return ReplicaStartupStatus.SUCCEEDED, None
# todo: The replica's userconfig whitch java client created
# is different from the controller's userconfig
if not self._deployment_is_cross_language:
# This should only update version if the replica is being recovered.
# If this is checking on a replica that is newly started, this
# should return a version that is identical to what's already stored
_, self._version = ray.get(self._ready_obj_ref)
except RayTaskError as e:
logger.exception(
f"Exception in replica '{self._replica_tag}', "
"the replica will be stopped."
)
# NOTE(zcin): we should use str(e) instead of traceback.format_exc()
# here because the full details of the error is not displayed properly
# with traceback.format_exc().
return ReplicaStartupStatus.FAILED, str(e.as_instanceof_cause())
except Exception as e:
logger.exception(
f"Exception in replica '{self._replica_tag}', "
"the replica will be stopped."
)
return ReplicaStartupStatus.FAILED, repr(e)
return ReplicaStartupStatus.SUCCEEDED, None
@property
def actor_resources(self) -> Optional[Dict[str, float]]:
return self._actor_resources
@property
def available_resources(self) -> Dict[str, float]:
return ray.available_resources()
def graceful_stop(self) -> Duration:
"""Request the actor to exit gracefully.
Returns the timeout after which to kill the actor.
"""
try:
handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE)
if self._is_cross_language:
handle = JavaActorHandleProxy(handle)
self._graceful_shutdown_ref = handle.perform_graceful_shutdown.remote()
except ValueError:
# ValueError thrown from ray.get_actor means actor has already been deleted.
pass
return self.graceful_shutdown_timeout_s
def check_stopped(self) -> bool:
"""Check if the actor has exited."""
try:
handle = ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE)
stopped = check_obj_ref_ready_nowait(self._graceful_shutdown_ref)
if stopped:
try:
ray.get(self._graceful_shutdown_ref)
except Exception:
logger.exception(
"Exception when trying to gracefully shutdown replica:\n"
+ traceback.format_exc()
)
ray.kill(handle, no_restart=True)
except ValueError:
# ValueError thrown from ray.get_actor means actor has already been deleted.
stopped = True
finally:
# Remove the placement group both if the actor has already been deleted or
# it was just killed above.
if stopped and self._placement_group is not None:
ray.util.remove_placement_group(self._placement_group)
return stopped
def _check_active_health_check(self) -> ReplicaHealthCheckResponse:
"""Check the active health check (if any).
self._health_check_ref will be reset to `None` when the active health
check is deemed to have succeeded or failed. This method *does not*
start a new health check, that's up to the caller.
Returns:
- NONE if there's no active health check, or it hasn't returned
yet and the timeout is not up.
- SUCCEEDED if the active health check succeeded.
- APP_FAILURE if the active health check failed (or didn't return
before the timeout).
- ACTOR_CRASHED if the underlying actor crashed.
"""
if self._health_check_ref is None:
# There is no outstanding health check.
response = ReplicaHealthCheckResponse.NONE
elif check_obj_ref_ready_nowait(self._health_check_ref):
# Object ref is ready, ray.get it to check for exceptions.
try:
ray.get(self._health_check_ref)
# Health check succeeded without exception.
response = ReplicaHealthCheckResponse.SUCCEEDED
except RayActorError:
# Health check failed due to actor crashing.
response = ReplicaHealthCheckResponse.ACTOR_CRASHED
except RayError as e:
# Health check failed due to application-level exception.
logger.warning(
f"Health check for replica {self._replica_tag} failed: {e}"
)
response = ReplicaHealthCheckResponse.APP_FAILURE
elif time.time() - self._last_health_check_time > self.health_check_timeout_s:
# Health check hasn't returned and the timeout is up, consider it failed.
logger.warning(
"Didn't receive health check response for replica "
f"{self._replica_tag} after "
f"{self.health_check_timeout_s}s, marking it unhealthy."
)
response = ReplicaHealthCheckResponse.APP_FAILURE
else:
# Health check hasn't returned and the timeout isn't up yet.
response = ReplicaHealthCheckResponse.NONE
if response is not ReplicaHealthCheckResponse.NONE:
self._health_check_ref = None
return response
def _should_start_new_health_check(self) -> bool:
"""Determines if a new health check should be kicked off.
A health check will be started if:
1) There is not already an active health check.
2) It has been more than health_check_period_s since the
previous health check was *started*.
This assumes that self._health_check_ref is reset to `None` when an
active health check succeeds or fails (due to returning or timeout).
"""
if self._health_check_ref is not None:
# There's already an active health check.
return False
# If there's no active health check, kick off another and reset
# the timer if it's been long enough since the last health
# check. Add some randomness to avoid synchronizing across all
# replicas.
time_since_last = time.time() - self._last_health_check_time
randomized_period = self.health_check_period_s * random.uniform(0.9, 1.1)
return time_since_last > randomized_period
def check_health(self) -> bool:
"""Check if the actor is healthy.
self._healthy should *only* be modified in this method.
This is responsible for:
1) Checking the outstanding health check (if any).
2) Determining the replica health based on the health check results.
3) Kicking off a new health check if needed.
"""
response: ReplicaHealthCheckResponse = self._check_active_health_check()
if response is ReplicaHealthCheckResponse.NONE:
# No info; don't update replica health.
pass
elif response is ReplicaHealthCheckResponse.SUCCEEDED:
# Health check succeeded. Reset the consecutive failure counter
# and mark the replica healthy.
self._consecutive_health_check_failures = 0
self._healthy = True
elif response is ReplicaHealthCheckResponse.APP_FAILURE:
# Health check failed. If it has failed more than N times in a row,
# mark the replica unhealthy.
self._consecutive_health_check_failures += 1
if (
self._consecutive_health_check_failures
>= REPLICA_HEALTH_CHECK_UNHEALTHY_THRESHOLD
):
logger.warning(
f"Replica {self._replica_tag} failed the health "
f"check {self._consecutive_health_check_failures} "
"times in a row, marking it unhealthy."
)
self._healthy = False
elif response is ReplicaHealthCheckResponse.ACTOR_CRASHED:
# Actor crashed, mark the replica unhealthy immediately.
logger.warning(
f"Actor for replica {self._replica_tag} crashed, marking "
"it unhealthy immediately."
)
self._healthy = False
else:
assert False, f"Unknown response type: {response}."
if self._should_start_new_health_check():
self._last_health_check_time = time.time()
self._health_check_ref = self._actor_handle.check_health.remote()
return self._healthy
def force_stop(self):
"""Force the actor to exit without shutting down gracefully."""
try:
ray.kill(ray.get_actor(self._actor_name, namespace=SERVE_NAMESPACE))
except ValueError:
pass
class DeploymentReplica(VersionedReplica):
"""Manages state transitions for deployment replicas.
This is basically a checkpointable lightweight state machine.
"""
def __init__(
self,
replica_tag: ReplicaTag,
deployment_id: DeploymentID,
version: DeploymentVersion,
):
self._actor = ActorReplicaWrapper(
f"{ReplicaName.prefix}{format_actor_name(replica_tag)}",
replica_tag,
deployment_id,
version,
)
self._deployment_id = deployment_id
self._replica_tag = replica_tag
self._start_time = None
self._actor_details = ReplicaDetails(
actor_name=self._actor._actor_name,
replica_id=self._replica_tag,
state=ReplicaState.STARTING,
start_time_s=0,
)
self._multiplexed_model_ids: List = []
def get_running_replica_info(
self, cluster_node_info_cache: ClusterNodeInfoCache
) -> RunningReplicaInfo:
return RunningReplicaInfo(
deployment_name=self.deployment_name,
replica_tag=self._replica_tag,
node_id=self.actor_node_id,
availability_zone=cluster_node_info_cache.get_node_az(self.actor_node_id),
actor_handle=self._actor.actor_handle,
max_concurrent_queries=self._actor.max_concurrent_queries,
is_cross_language=self._actor.is_cross_language,
multiplexed_model_ids=self.multiplexed_model_ids,
)
def record_multiplexed_model_ids(self, multiplexed_model_ids: List[str]):
"""Record the multiplexed model ids for this replica."""
self._multiplexed_model_ids = multiplexed_model_ids
@property
def multiplexed_model_ids(self) -> List[str]:
return self._multiplexed_model_ids
@property
def actor_details(self) -> ReplicaDetails:
return self._actor_details
@property
def replica_tag(self) -> ReplicaTag:
return self._replica_tag
@property
def deployment_name(self) -> str:
return self._deployment_id.name
@property
def app_name(self) -> str:
return self._deployment_id.app
@property
def version(self):
return self._actor.version
@property
def actor_handle(self) -> ActorHandle:
return self._actor.actor_handle
@property
def actor_node_id(self) -> Optional[str]:
"""Returns the node id of the actor, None if not placed."""
return self._actor.node_id
def start(self, deployment_info: DeploymentInfo) -> ReplicaSchedulingRequest:
"""
Start a new actor for current DeploymentReplica instance.
"""
replica_scheduling_request = self._actor.start(deployment_info)
self._start_time = time.time()
self.update_actor_details(start_time_s=self._start_time)
return replica_scheduling_request
def reconfigure(self, version: DeploymentVersion) -> bool:
"""
Update replica version. Also, updates the deployment config on the actor
behind this DeploymentReplica instance if necessary.
Returns: whether the actor is being updated.
"""
return self._actor.reconfigure(version)
def recover(self) -> bool:
"""
Recover states in DeploymentReplica instance by fetching running actor
status
Returns: False if the replica is no longer alive at the time
when this method is called.
"""
# If replica is no longer alive
if not self._actor.recover():
return False
self._start_time = time.time()
self.update_actor_details(start_time_s=self._start_time)
return True
def check_started(self) -> Tuple[ReplicaStartupStatus, Optional[str]]:
"""Check if the replica has started. If so, transition to RUNNING.
Should handle the case where the replica has already stopped.
Returns:
status: Most recent state of replica by
querying actor obj ref
"""
is_ready = self._actor.check_ready()
self.update_actor_details(
pid=self._actor.pid,
node_id=self._actor.node_id,
node_ip=self._actor.node_ip,
actor_id=self._actor.actor_id,
worker_id=self._actor.worker_id,
log_file_path=self._actor.log_file_path,
)