ZTWHHH commited on
Commit
f54259b
·
verified ·
1 Parent(s): 97f539f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. vllm/lib/python3.10/site-packages/ray/autoscaler/__init__.py +8 -0
  3. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/__init__.py +0 -0
  4. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/__pycache__/node_provider.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/azure-config-template.json +130 -0
  6. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/azure-vm-template.json +285 -0
  7. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/config.py +208 -0
  8. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__init__.py +0 -0
  9. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__pycache__/__init__.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__pycache__/node_provider.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/config.py +116 -0
  12. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/node_provider.py +324 -0
  13. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/cli_logger.py +825 -0
  14. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/cluster_dump.py +652 -0
  15. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/commands.py +1632 -0
  16. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/constants.py +141 -0
  17. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/docker.py +129 -0
  18. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/event_summarizer.py +75 -0
  19. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/gcp/__pycache__/__init__.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/gcp/__pycache__/config.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/legacy_info_string.py +37 -0
  22. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/monitor.py +709 -0
  23. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/node_launcher.py +221 -0
  24. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/prom_metrics.py +292 -0
  25. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/providers.py +313 -0
  26. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__init__.py +0 -0
  27. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/__init__.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/node_provider.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/spark_job_server.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/subprocess_output_util.py +420 -0
  31. vllm/lib/python3.10/site-packages/ray/autoscaler/_private/util.py +963 -0
  32. vllm/lib/python3.10/site-packages/ray/autoscaler/aliyun/__init__.py +0 -0
  33. vllm/lib/python3.10/site-packages/ray/autoscaler/aliyun/__pycache__/__init__.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/ray/autoscaler/batching_node_provider.py +265 -0
  35. vllm/lib/python3.10/site-packages/ray/autoscaler/command_runner.py +92 -0
  36. vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/__init__.py +0 -0
  37. vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/defaults.yaml +171 -0
  39. vllm/lib/python3.10/site-packages/ray/autoscaler/launch_and_verify_cluster.py +439 -0
  40. vllm/lib/python3.10/site-packages/ray/autoscaler/local/__init__.py +0 -0
  41. vllm/lib/python3.10/site-packages/ray/autoscaler/local/__pycache__/__init__.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/ray/autoscaler/local/__pycache__/coordinator_server.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/ray/autoscaler/local/coordinator_server.py +124 -0
  44. vllm/lib/python3.10/site-packages/ray/autoscaler/local/defaults.yaml +33 -0
  45. vllm/lib/python3.10/site-packages/ray/autoscaler/node_launch_exception.py +37 -0
  46. vllm/lib/python3.10/site-packages/ray/autoscaler/node_provider.py +263 -0
  47. vllm/lib/python3.10/site-packages/ray/autoscaler/ray-schema.json +400 -0
  48. vllm/lib/python3.10/site-packages/ray/autoscaler/spark/__init__.py +0 -0
  49. vllm/lib/python3.10/site-packages/ray/autoscaler/spark/__pycache__/__init__.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/ray/autoscaler/spark/defaults.yaml +49 -0
.gitattributes CHANGED
@@ -1464,3 +1464,4 @@ vllm/lib/python3.10/site-packages/ray/core/src/ray/raylet/raylet filter=lfs diff
1464
  vllm/lib/python3.10/site-packages/ray/core/src/ray/gcs/gcs_server filter=lfs diff=lfs merge=lfs -text
1465
  vllm/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so filter=lfs diff=lfs merge=lfs -text
1466
  parrot/lib/python3.10/site-packages/sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
1464
  vllm/lib/python3.10/site-packages/ray/core/src/ray/gcs/gcs_server filter=lfs diff=lfs merge=lfs -text
1465
  vllm/lib/python3.10/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so filter=lfs diff=lfs merge=lfs -text
1466
  parrot/lib/python3.10/site-packages/sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1467
+ vllm/lib/python3.10/site-packages/ray/jars/ray_dist.jar filter=lfs diff=lfs merge=lfs -text
vllm/lib/python3.10/site-packages/ray/autoscaler/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from ray.autoscaler import sdk
5
+
6
+ __all__ = ["sdk"]
7
+
8
+ AUTOSCALER_DIR_PATH = Path(os.path.abspath(os.path.dirname(__file__)))
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/__pycache__/node_provider.cpython-310.pyc ADDED
Binary file (14.3 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/azure-config-template.json ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
3
+ "contentVersion": "1.0.0.0",
4
+ "parameters": {
5
+ "clusterId": {
6
+ "type": "string",
7
+ "metadata": {
8
+ "description": "Unique string appended to resource names to isolate resources from different ray clusters."
9
+ }
10
+ },
11
+ "subnet": {
12
+ "type": "string",
13
+ "metadata": {
14
+ "description": "Subnet parameters."
15
+ }
16
+ },
17
+ "msiName": {
18
+ "type": "string",
19
+ "metadata": {
20
+ "description": "Managed service identity."
21
+ }
22
+ },
23
+ "msiResourceGroup": {
24
+ "type": "string",
25
+ "metadata": {
26
+ "description": "Managed service identity resource group."
27
+ }
28
+ },
29
+ "createMsi": {
30
+ "type": "bool",
31
+ "defaultValue": "true"
32
+ }
33
+ },
34
+ "variables": {
35
+ "contributor": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')]",
36
+ "location": "[resourceGroup().location]",
37
+ "roleAssignmentName": "[concat('ray-', parameters('clusterId'), '-ra')]",
38
+ "nsgName": "[concat('ray-', parameters('clusterId'), '-nsg')]",
39
+ "nsg": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]",
40
+ "vnetName": "[concat('ray-', parameters('clusterId'), '-vnet')]",
41
+ "subnetName": "[concat('ray-', parameters('clusterId'), '-subnet')]"
42
+ },
43
+ "resources": [
44
+ {
45
+ "condition": "[parameters('createMsi')]",
46
+ "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
47
+ "apiVersion": "2018-11-30",
48
+ "location": "[variables('location')]",
49
+ "name": "[parameters('msiName')]"
50
+ },
51
+ {
52
+ "type": "Microsoft.Authorization/roleAssignments",
53
+ "apiVersion": "2020-08-01-preview",
54
+ "name": "[guid(variables('roleAssignmentName'))]",
55
+ "properties": {
56
+ "principalId": "[reference(resourceId(parameters('msiResourceGroup'), 'Microsoft.ManagedIdentity/userAssignedIdentities', parameters('msiName')), '2018-11-30').principalId]",
57
+ "roleDefinitionId": "[variables('contributor')]",
58
+ "scope": "[resourceGroup().id]",
59
+ "principalType": "ServicePrincipal"
60
+ },
61
+ "dependsOn": [
62
+ "[parameters('msiName')]"
63
+ ]
64
+ },
65
+ {
66
+ "type": "Microsoft.Network/networkSecurityGroups",
67
+ "apiVersion": "2019-02-01",
68
+ "name": "[variables('nsgName')]",
69
+ "location": "[variables('location')]",
70
+ "properties": {
71
+ "securityRules": [
72
+ {
73
+ "name": "SSH",
74
+ "properties": {
75
+ "priority": 1000,
76
+ "protocol": "TCP",
77
+ "access": "Allow",
78
+ "direction": "Inbound",
79
+ "sourceAddressPrefix": "*",
80
+ "sourcePortRange": "*",
81
+ "destinationAddressPrefix": "*",
82
+ "destinationPortRange": "22"
83
+ }
84
+ }
85
+ ]
86
+ }
87
+ },
88
+ {
89
+ "type": "Microsoft.Network/virtualNetworks",
90
+ "apiVersion": "2019-11-01",
91
+ "name": "[variables('vnetName')]",
92
+ "location": "[variables('location')]",
93
+ "properties": {
94
+ "addressSpace": {
95
+ "addressPrefixes": [
96
+ "[parameters('subnet')]"
97
+ ]
98
+ },
99
+ "subnets": [
100
+ {
101
+ "name": "[variables('subnetName')]",
102
+ "properties": {
103
+ "addressPrefix": "[parameters('subnet')]",
104
+ "networkSecurityGroup": {
105
+ "id": "[variables('nsg')]"
106
+ }
107
+ }
108
+ }
109
+ ]
110
+ },
111
+ "dependsOn": [
112
+ "[variables('nsg')]"
113
+ ]
114
+ }
115
+ ],
116
+ "outputs": {
117
+ "subnet": {
118
+ "type": "string",
119
+ "value": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vnetName'), variables('subnetName'))]"
120
+ },
121
+ "nsg": {
122
+ "type": "string",
123
+ "value": "[variables('nsg')]"
124
+ },
125
+ "msi": {
126
+ "type": "string",
127
+ "value": "[resourceId(parameters('msiResourceGroup'), 'Microsoft.ManagedIdentity/userAssignedIdentities', parameters('msiName'))]"
128
+ }
129
+ }
130
+ }
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/azure-vm-template.json ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
3
+ "contentVersion": "1.0.0.0",
4
+ "parameters": {
5
+ "vmName": {
6
+ "type": "string",
7
+ "metadata": {
8
+ "description": "The name of you Virtual Machine."
9
+ }
10
+ },
11
+ "adminUsername": {
12
+ "type": "string",
13
+ "metadata": {
14
+ "description": "Username for the Virtual Machine."
15
+ }
16
+ },
17
+ "publicKey": {
18
+ "type": "securestring",
19
+ "metadata": {
20
+ "description": "SSH Key for the Virtual Machine"
21
+ }
22
+ },
23
+ "imagePublisher": {
24
+ "type": "string",
25
+ "metadata": {
26
+ "description": "The publisher of the VM image"
27
+ }
28
+ },
29
+ "imageOffer": {
30
+ "type": "string",
31
+ "metadata": {
32
+ "description": "The offer of the VM image"
33
+ }
34
+ },
35
+ "imageSku": {
36
+ "type": "string",
37
+ "metadata": {
38
+ "description": "The sku of the VM image"
39
+ }
40
+ },
41
+ "imageVersion": {
42
+ "type": "string",
43
+ "metadata": {
44
+ "description": "The version of the VM image"
45
+ }
46
+ },
47
+ "vmSize": {
48
+ "type": "string",
49
+ "metadata": {
50
+ "description": "The size of the VM"
51
+ }
52
+ },
53
+ "vmTags": {
54
+ "type": "object",
55
+ "metadata": {
56
+ "description": "Tags for the VM"
57
+ }
58
+ },
59
+ "vmCount": {
60
+ "type": "int",
61
+ "metadata": {
62
+ "description": "Number of VMs to deploy"
63
+ }
64
+ },
65
+ "provisionPublicIp": {
66
+ "type": "bool",
67
+ "defaultValue": true,
68
+ "metadata": {
69
+ "description": "If true creates a public ip"
70
+ }
71
+ },
72
+ "priority": {
73
+ "type": "string",
74
+ "defaultValue": "Regular",
75
+ "metadata": {
76
+ "description": "Specifies the priority for the virtual machine."
77
+ }
78
+ },
79
+ "evictionPolicy": {
80
+ "type": "string",
81
+ "defaultValue": "Delete",
82
+ "metadata": {
83
+ "description": "Specifies the eviction policy for the virtual machine."
84
+ }
85
+ },
86
+ "billingProfile": {
87
+ "type": "object",
88
+ "defaultValue": {},
89
+ "metadata": {
90
+ "description": "Specifies the maximum price to pay for Azure Spot VM."
91
+ }
92
+ },
93
+ "msi": {
94
+ "type": "string",
95
+ "metadata": {
96
+ "description": "Managed service identity resource id."
97
+ }
98
+ },
99
+ "nsg": {
100
+ "type": "string",
101
+ "metadata": {
102
+ "description": "Network security group resource id."
103
+ }
104
+ },
105
+ "subnet": {
106
+ "type": "string",
107
+ "metadata": {
108
+ "descriptions": "Subnet resource id."
109
+ }
110
+ }
111
+ },
112
+ "variables": {
113
+ "location": "[resourceGroup().location]",
114
+ "networkInterfaceNamePrivate": "[concat(parameters('vmName'), '-nic')]",
115
+ "networkInterfaceNamePublic": "[concat(parameters('vmName'), '-nic-public')]",
116
+ "networkInterfaceName": "[if(parameters('provisionPublicIp'), variables('networkInterfaceNamePublic'), variables('networkInterfaceNamePrivate'))]",
117
+ "networkIpConfig": "[guid(resourceGroup().id, parameters('vmName'))]",
118
+ "osDiskType": "Standard_LRS",
119
+ "publicIpAddressName": "[concat(parameters('vmName'), '-ip')]"
120
+ },
121
+ "resources": [
122
+ {
123
+ "type": "Microsoft.Network/networkInterfaces",
124
+ "apiVersion": "2020-06-01",
125
+ "name": "[concat(variables('networkInterfaceNamePublic'), copyIndex())]",
126
+ "location": "[variables('location')]",
127
+ "dependsOn": [
128
+ "[resourceId('Microsoft.Network/publicIpAddresses/', concat(variables('publicIpAddressName'), copyIndex()))]"
129
+ ],
130
+ "copy": {
131
+ "name": "NICPublicCopy",
132
+ "count": "[parameters('vmCount')]"
133
+ },
134
+ "properties": {
135
+ "ipConfigurations": [
136
+ {
137
+ "name": "[variables('networkIpConfig')]",
138
+ "properties": {
139
+ "subnet": {
140
+ "id": "[parameters('subnet')]"
141
+ },
142
+ "privateIPAllocationMethod": "Dynamic",
143
+ "publicIpAddress": {
144
+ "id": "[resourceId('Microsoft.Network/publicIPAddresses', concat(variables('publicIPAddressName'), copyIndex()))]"
145
+ }
146
+ }
147
+ }
148
+ ],
149
+ "networkSecurityGroup": {
150
+ "id": "[parameters('nsg')]"
151
+ }
152
+ },
153
+ "condition": "[parameters('provisionPublicIp')]"
154
+ },
155
+ {
156
+ "type": "Microsoft.Network/networkInterfaces",
157
+ "apiVersion": "2020-06-01",
158
+ "name": "[concat(variables('networkInterfaceNamePrivate'), copyIndex())]",
159
+ "location": "[variables('location')]",
160
+ "copy": {
161
+ "name": "NICPrivateCopy",
162
+ "count": "[parameters('vmCount')]"
163
+ },
164
+ "properties": {
165
+ "ipConfigurations": [
166
+ {
167
+ "name": "[variables('networkIpConfig')]",
168
+ "properties": {
169
+ "subnet": {
170
+ "id": "[parameters('subnet')]"
171
+ },
172
+ "privateIPAllocationMethod": "Dynamic"
173
+ }
174
+ }
175
+ ],
176
+ "networkSecurityGroup": {
177
+ "id": "[parameters('nsg')]"
178
+ }
179
+ },
180
+ "condition": "[not(parameters('provisionPublicIp'))]"
181
+ },
182
+ {
183
+ "type": "Microsoft.Network/publicIpAddresses",
184
+ "apiVersion": "2019-02-01",
185
+ "name": "[concat(variables('publicIpAddressName'), copyIndex())]",
186
+ "location": "[variables('location')]",
187
+ "properties": {
188
+ "publicIpAllocationMethod": "Static",
189
+ "publicIPAddressVersion": "IPv4"
190
+ },
191
+ "copy": {
192
+ "name": "PublicIpCopy",
193
+ "count": "[parameters('vmCount')]"
194
+ },
195
+ "sku": {
196
+ "name": "Basic",
197
+ "tier": "Regional"
198
+ },
199
+ "condition": "[parameters('provisionPublicIp')]"
200
+ },
201
+ {
202
+ "type": "Microsoft.Compute/virtualMachines",
203
+ "apiVersion": "2019-03-01",
204
+ "name": "[concat(parameters('vmName'), copyIndex())]",
205
+ "location": "[variables('location')]",
206
+ "dependsOn": [
207
+ "[resourceId('Microsoft.Network/networkInterfaces/', concat(variables('networkInterfaceName'), copyIndex()))]"
208
+ ],
209
+ "copy": {
210
+ "name": "VmCopy",
211
+ "count": "[parameters('vmCount')]"
212
+ },
213
+ "tags": "[parameters('vmTags')]",
214
+ "properties": {
215
+ "hardwareProfile": {
216
+ "vmSize": "[parameters('vmSize')]"
217
+ },
218
+ "storageProfile": {
219
+ "osDisk": {
220
+ "createOption": "fromImage",
221
+ "managedDisk": {
222
+ "storageAccountType": "[variables('osDiskType')]"
223
+ }
224
+ },
225
+ "imageReference": {
226
+ "publisher": "[parameters('imagePublisher')]",
227
+ "offer": "[parameters('imageOffer')]",
228
+ "sku": "[parameters('imageSku')]",
229
+ "version": "[parameters('imageVersion')]"
230
+ }
231
+ },
232
+ "networkProfile": {
233
+ "networkInterfaces": [
234
+ {
235
+ "id": "[resourceId('Microsoft.Network/networkInterfaces', concat(variables('networkInterfaceName'), copyIndex()))]"
236
+ }
237
+ ]
238
+ },
239
+ "osProfile": {
240
+ "computerName": "[concat(parameters('vmName'), copyIndex())]",
241
+ "adminUsername": "[parameters('adminUsername')]",
242
+ "adminPassword": "[parameters('publicKey')]",
243
+ "linuxConfiguration": {
244
+ "disablePasswordAuthentication": true,
245
+ "ssh": {
246
+ "publicKeys": [
247
+ {
248
+ "path": "[concat('/home/', parameters('adminUsername'), '/.ssh/authorized_keys')]",
249
+ "keyData": "[parameters('publicKey')]"
250
+ }
251
+ ]
252
+ }
253
+ }
254
+ },
255
+ "priority": "[parameters('priority')]",
256
+ "evictionPolicy": "[if(equals(parameters('priority'), 'Spot'), parameters('evictionPolicy'), '')]",
257
+ "billingProfile": "[parameters('billingProfile')]"
258
+ },
259
+ "identity": {
260
+ "type": "UserAssigned",
261
+ "userAssignedIdentities": {
262
+ "[parameters('msi')]": {
263
+ }
264
+ }
265
+ }
266
+ }
267
+ ],
268
+ "outputs": {
269
+ "publicIp": {
270
+ "type": "array",
271
+ "copy": {
272
+ "count": "[parameters('vmCount')]",
273
+ "input": "[reference(concat(variables('publicIpAddressName'), copyIndex())).ipAddress]"
274
+ },
275
+ "condition": "[parameters('provisionPublicIp')]"
276
+ },
277
+ "privateIp": {
278
+ "type": "array",
279
+ "copy": {
280
+ "count": "[parameters('vmCount')]",
281
+ "input": "[reference(concat(variables('networkInterfaceName'), copyIndex())).ipConfigurations[0].properties.privateIPAddress]"
282
+ }
283
+ }
284
+ }
285
+ }
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/_azure/config.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import random
4
+ from hashlib import sha256
5
+ from pathlib import Path
6
+ from typing import Any, Callable
7
+
8
+ from azure.common.credentials import get_cli_profile
9
+ from azure.identity import AzureCliCredential
10
+ from azure.mgmt.resource import ResourceManagementClient
11
+ from azure.mgmt.resource.resources.models import DeploymentMode
12
+
13
+ UNIQUE_ID_LEN = 4
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def get_azure_sdk_function(client: Any, function_name: str) -> Callable:
19
+ """Retrieve a callable function from Azure SDK client object.
20
+
21
+ Newer versions of the various client SDKs renamed function names to
22
+ have a begin_ prefix. This function supports both the old and new
23
+ versions of the SDK by first trying the old name and falling back to
24
+ the prefixed new name.
25
+ """
26
+ func = getattr(
27
+ client, function_name, getattr(client, f"begin_{function_name}", None)
28
+ )
29
+ if func is None:
30
+ raise AttributeError(
31
+ "'{obj}' object has no {func} or begin_{func} attribute".format(
32
+ obj={client.__name__}, func=function_name
33
+ )
34
+ )
35
+ return func
36
+
37
+
38
+ def bootstrap_azure(config):
39
+ config = _configure_key_pair(config)
40
+ config = _configure_resource_group(config)
41
+ return config
42
+
43
+
44
+ def _configure_resource_group(config):
45
+ # TODO: look at availability sets
46
+ # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/tutorial-availability-sets
47
+ subscription_id = config["provider"].get("subscription_id")
48
+ if subscription_id is None:
49
+ subscription_id = get_cli_profile().get_subscription_id()
50
+ resource_client = ResourceManagementClient(AzureCliCredential(), subscription_id)
51
+ config["provider"]["subscription_id"] = subscription_id
52
+ logger.info("Using subscription id: %s", subscription_id)
53
+
54
+ assert (
55
+ "resource_group" in config["provider"]
56
+ ), "Provider config must include resource_group field"
57
+ resource_group = config["provider"]["resource_group"]
58
+
59
+ assert (
60
+ "location" in config["provider"]
61
+ ), "Provider config must include location field"
62
+ params = {"location": config["provider"]["location"]}
63
+
64
+ if "tags" in config["provider"]:
65
+ params["tags"] = config["provider"]["tags"]
66
+
67
+ logger.info("Creating/Updating resource group: %s", resource_group)
68
+ rg_create_or_update = get_azure_sdk_function(
69
+ client=resource_client.resource_groups, function_name="create_or_update"
70
+ )
71
+ rg_create_or_update(resource_group_name=resource_group, parameters=params)
72
+
73
+ # load the template file
74
+ current_path = Path(__file__).parent
75
+ template_path = current_path.joinpath("azure-config-template.json")
76
+ with open(template_path, "r") as template_fp:
77
+ template = json.load(template_fp)
78
+
79
+ logger.info("Using cluster name: %s", config["cluster_name"])
80
+
81
+ # set unique id for resources in this cluster
82
+ unique_id = config["provider"].get("unique_id")
83
+ if unique_id is None:
84
+ hasher = sha256()
85
+ hasher.update(config["provider"]["resource_group"].encode("utf-8"))
86
+ unique_id = hasher.hexdigest()[:UNIQUE_ID_LEN]
87
+ else:
88
+ unique_id = str(unique_id)
89
+ config["provider"]["unique_id"] = unique_id
90
+ logger.info("Using unique id: %s", unique_id)
91
+ cluster_id = "{}-{}".format(config["cluster_name"], unique_id)
92
+
93
+ subnet_mask = config["provider"].get("subnet_mask")
94
+ if subnet_mask is None:
95
+ # choose a random subnet, skipping most common value of 0
96
+ random.seed(unique_id)
97
+ subnet_mask = "10.{}.0.0/16".format(random.randint(1, 254))
98
+ logger.info("Using subnet mask: %s", subnet_mask)
99
+
100
+ # Copy over properties from existing subnet.
101
+ # Addresses issue (https://github.com/Azure/azure-quickstart-templates/issues/2786)
102
+ # where existing subnet properties will get overwritten unless explicitly specified
103
+ # during multiple deployments even if vnet/subnet do not change.
104
+ # May eventually be fixed by passing empty subnet list if they already exist:
105
+ # https://techcommunity.microsoft.com/t5/azure-networking-blog/azure-virtual-network-now-supports-updates-without-subnet/ba-p/4067952
106
+ list_by_rg = get_azure_sdk_function(
107
+ client=resource_client.resources, function_name="list_by_resource_group"
108
+ )
109
+ existing_vnets = list(
110
+ list_by_rg(
111
+ resource_group,
112
+ f"substringof('{unique_id}', name) and "
113
+ "resourceType eq 'Microsoft.Network/virtualNetworks'",
114
+ )
115
+ )
116
+ if len(existing_vnets) > 0:
117
+ vnid = existing_vnets[0].id
118
+ get_by_id = get_azure_sdk_function(
119
+ client=resource_client.resources, function_name="get_by_id"
120
+ )
121
+ subnet = get_by_id(vnid, resource_client.DEFAULT_API_VERSION).properties[
122
+ "subnets"
123
+ ][0]
124
+ template_vnet = next(
125
+ (
126
+ rs
127
+ for rs in template["resources"]
128
+ if rs["type"] == "Microsoft.Network/virtualNetworks"
129
+ ),
130
+ None,
131
+ )
132
+ if template_vnet is not None:
133
+ template_subnets = template_vnet["properties"].get("subnets")
134
+ if template_subnets is not None:
135
+ template_subnets[0]["properties"].update(subnet["properties"])
136
+
137
+ # Get or create an MSI name and resource group.
138
+ # Defaults to current resource group if not provided.
139
+ use_existing_msi = (
140
+ "msi_name" in config["provider"] and "msi_resource_group" in config["provider"]
141
+ )
142
+ msi_resource_group = config["provider"].get("msi_resource_group", resource_group)
143
+ msi_name = config["provider"].get("msi_name", f"ray-{cluster_id}-msi")
144
+ logger.info(
145
+ "Using msi_name: %s from msi_resource_group: %s", msi_name, msi_resource_group
146
+ )
147
+
148
+ parameters = {
149
+ "properties": {
150
+ "mode": DeploymentMode.incremental,
151
+ "template": template,
152
+ "parameters": {
153
+ "subnet": {"value": subnet_mask},
154
+ "clusterId": {"value": cluster_id},
155
+ "msiName": {"value": msi_name},
156
+ "msiResourceGroup": {"value": msi_resource_group},
157
+ "createMsi": {"value": not use_existing_msi},
158
+ },
159
+ }
160
+ }
161
+
162
+ create_or_update = get_azure_sdk_function(
163
+ client=resource_client.deployments, function_name="create_or_update"
164
+ )
165
+ outputs = (
166
+ create_or_update(
167
+ resource_group_name=resource_group,
168
+ deployment_name="ray-config",
169
+ parameters=parameters,
170
+ )
171
+ .result()
172
+ .properties.outputs
173
+ )
174
+
175
+ # append output resource ids to be used with vm creation
176
+ config["provider"]["msi"] = outputs["msi"]["value"]
177
+ config["provider"]["nsg"] = outputs["nsg"]["value"]
178
+ config["provider"]["subnet"] = outputs["subnet"]["value"]
179
+
180
+ return config
181
+
182
+
183
+ def _configure_key_pair(config):
184
+ ssh_user = config["auth"]["ssh_user"]
185
+ public_key = None
186
+ # search if the keys exist
187
+ for key_type in ["ssh_private_key", "ssh_public_key"]:
188
+ try:
189
+ key_path = Path(config["auth"][key_type]).expanduser()
190
+ except KeyError:
191
+ raise Exception("Config must define {}".format(key_type))
192
+ except TypeError:
193
+ raise Exception("Invalid config value for {}".format(key_type))
194
+
195
+ assert key_path.is_file(), "Could not find ssh key: {}".format(key_path)
196
+
197
+ if key_type == "ssh_public_key":
198
+ with open(key_path, "r") as f:
199
+ public_key = f.read()
200
+
201
+ for node_type in config["available_node_types"].values():
202
+ azure_arm_parameters = node_type["node_config"].setdefault(
203
+ "azure_arm_parameters", {}
204
+ )
205
+ azure_arm_parameters["adminUsername"] = ssh_user
206
+ azure_arm_parameters["publicKey"] = public_key
207
+
208
+ return config
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/__pycache__/node_provider.cpython-310.pyc ADDED
Binary file (8.89 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/config.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import stat
4
+
5
+ from ray.autoscaler._private.aliyun.utils import AcsClient
6
+
7
+ # instance status
8
+ PENDING = "Pending"
9
+ RUNNING = "Running"
10
+ STARTING = "Starting"
11
+ STOPPING = "Stopping"
12
+ STOPPED = "Stopped"
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def bootstrap_aliyun(config):
18
+ # print(config["provider"])
19
+ # create vpc
20
+ _get_or_create_vpc(config)
21
+ # create security group id
22
+ _get_or_create_security_group(config)
23
+ # create vswitch
24
+ _get_or_create_vswitch(config)
25
+ # create key pair
26
+ _get_or_import_key_pair(config)
27
+ # print(config["provider"])
28
+ return config
29
+
30
+
31
+ def _client(config):
32
+ return AcsClient(
33
+ access_key=config["provider"].get("access_key"),
34
+ access_key_secret=config["provider"].get("access_key_secret"),
35
+ region_id=config["provider"]["region"],
36
+ max_retries=1,
37
+ )
38
+
39
+
40
+ def _get_or_create_security_group(config):
41
+ cli = _client(config)
42
+ security_groups = cli.describe_security_groups(vpc_id=config["provider"]["vpc_id"])
43
+ if security_groups is not None and len(security_groups) > 0:
44
+ config["provider"]["security_group_id"] = security_groups[0]["SecurityGroupId"]
45
+ return config
46
+
47
+ security_group_id = cli.create_security_group(vpc_id=config["provider"]["vpc_id"])
48
+
49
+ for rule in config["provider"].get("security_group_rule", {}):
50
+ cli.authorize_security_group(
51
+ security_group_id=security_group_id,
52
+ port_range=rule["port_range"],
53
+ source_cidr_ip=rule["source_cidr_ip"],
54
+ ip_protocol=rule["ip_protocol"],
55
+ )
56
+ config["provider"]["security_group_id"] = security_group_id
57
+ return
58
+
59
+
60
+ def _get_or_create_vpc(config):
61
+ cli = _client(config)
62
+ vpcs = cli.describe_vpcs()
63
+ if vpcs is not None and len(vpcs) > 0:
64
+ config["provider"]["vpc_id"] = vpcs[0].get("VpcId")
65
+ return
66
+
67
+ vpc_id = cli.create_vpc()
68
+ if vpc_id is not None:
69
+ config["provider"]["vpc_id"] = vpc_id
70
+
71
+
72
+ def _get_or_create_vswitch(config):
73
+ cli = _client(config)
74
+ vswitches = cli.describe_v_switches(vpc_id=config["provider"]["vpc_id"])
75
+ if vswitches is not None and len(vswitches) > 0:
76
+ config["provider"]["v_switch_id"] = vswitches[0].get("VSwitchId")
77
+ return
78
+
79
+ v_switch_id = cli.create_v_switch(
80
+ vpc_id=config["provider"]["vpc_id"],
81
+ zone_id=config["provider"]["zone_id"],
82
+ cidr_block=config["provider"]["cidr_block"],
83
+ )
84
+
85
+ if v_switch_id is not None:
86
+ config["provider"]["v_switch_id"] = v_switch_id
87
+
88
+
89
+ def _get_or_import_key_pair(config):
90
+ cli = _client(config)
91
+ key_name = config["provider"].get("key_name", "ray")
92
+ key_path = os.path.expanduser("~/.ssh/{}".format(key_name))
93
+ keypairs = cli.describe_key_pairs(key_pair_name=key_name)
94
+
95
+ if keypairs is not None and len(keypairs) > 0:
96
+ if "ssh_private_key" not in config["auth"]:
97
+ logger.info(
98
+ "{} keypair exists, use {} as local ssh key".format(key_name, key_path)
99
+ )
100
+ config["auth"]["ssh_private_key"] = key_path
101
+ else:
102
+ if "ssh_private_key" not in config["auth"]:
103
+ # create new keypair
104
+ resp = cli.create_key_pair(key_pair_name=key_name)
105
+ if resp is not None:
106
+ with open(key_path, "w+") as f:
107
+ f.write(resp.get("PrivateKeyBody"))
108
+ os.chmod(key_path, stat.S_IRUSR)
109
+ config["auth"]["ssh_private_key"] = key_path
110
+ else:
111
+ public_key_file = config["auth"]["ssh_private_key"] + ".pub"
112
+ # create new keypair, from local file
113
+ with open(public_key_file) as f:
114
+ public_key = f.readline().strip("\n")
115
+ cli.import_key_pair(key_pair_name=key_name, public_key_body=public_key)
116
+ return
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/aliyun/node_provider.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import random
3
+ import threading
4
+ import time
5
+ from collections import defaultdict
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from ray.autoscaler._private.aliyun.config import (
9
+ PENDING,
10
+ RUNNING,
11
+ STOPPED,
12
+ STOPPING,
13
+ bootstrap_aliyun,
14
+ )
15
+ from ray.autoscaler._private.aliyun.utils import AcsClient
16
+ from ray.autoscaler._private.cli_logger import cli_logger
17
+ from ray.autoscaler._private.constants import BOTO_MAX_RETRIES
18
+ from ray.autoscaler._private.log_timer import LogTimer
19
+ from ray.autoscaler.node_provider import NodeProvider
20
+ from ray.autoscaler.tags import (
21
+ TAG_RAY_CLUSTER_NAME,
22
+ TAG_RAY_LAUNCH_CONFIG,
23
+ TAG_RAY_NODE_KIND,
24
+ TAG_RAY_NODE_NAME,
25
+ TAG_RAY_NODE_STATUS,
26
+ TAG_RAY_USER_NODE_TYPE,
27
+ )
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ TAG_BATCH_DELAY = 1
32
+ STOPPING_NODE_DELAY = 1
33
+
34
+
35
+ class AliyunNodeProvider(NodeProvider):
36
+ def __init__(self, provider_config, cluster_name):
37
+ NodeProvider.__init__(self, provider_config, cluster_name)
38
+ self.cache_stopped_nodes = provider_config.get("cache_stopped_nodes", True)
39
+ self.acs = AcsClient(
40
+ access_key=provider_config["access_key"],
41
+ access_key_secret=provider_config["access_key_secret"],
42
+ region_id=provider_config["region"],
43
+ max_retries=BOTO_MAX_RETRIES,
44
+ )
45
+
46
+ # Try availability zones round-robin, starting from random offset
47
+ self.subnet_idx = random.randint(0, 100)
48
+
49
+ # Tags that we believe to actually be on the node.
50
+ self.tag_cache = {}
51
+ # Tags that we will soon upload.
52
+ self.tag_cache_pending = defaultdict(dict)
53
+ # Number of threads waiting for a batched tag update.
54
+ self.batch_thread_count = 0
55
+ self.batch_update_done = threading.Event()
56
+ self.batch_update_done.set()
57
+ self.ready_for_new_batch = threading.Event()
58
+ self.ready_for_new_batch.set()
59
+ self.tag_cache_lock = threading.Lock()
60
+ self.count_lock = threading.Lock()
61
+
62
+ # Cache of node objects from the last nodes() call. This avoids
63
+ # excessive DescribeInstances requests.
64
+ self.cached_nodes = {}
65
+
66
+ def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]:
67
+ tags = [
68
+ {
69
+ "Key": TAG_RAY_CLUSTER_NAME,
70
+ "Value": self.cluster_name,
71
+ },
72
+ ]
73
+ for k, v in tag_filters.items():
74
+ tags.append(
75
+ {
76
+ "Key": k,
77
+ "Value": v,
78
+ }
79
+ )
80
+
81
+ instances = self.acs.describe_instances(tags=tags)
82
+ non_terminated_instance = []
83
+ for instance in instances:
84
+ if instance.get("Status") == RUNNING or instance.get("Status") == PENDING:
85
+ non_terminated_instance.append(instance.get("InstanceId"))
86
+ self.cached_nodes[instance.get("InstanceId")] = instance
87
+ return non_terminated_instance
88
+
89
+ def is_running(self, node_id: str) -> bool:
90
+ instances = self.acs.describe_instances(instance_ids=[node_id])
91
+ if instances is not None:
92
+ instance = instances[0]
93
+ return instance.get("Status") == "Running"
94
+ cli_logger.error("Invalid node id: %s", node_id)
95
+ return False
96
+
97
+ def is_terminated(self, node_id: str) -> bool:
98
+ instances = self.acs.describe_instances(instance_ids=[node_id])
99
+ if instances is not None:
100
+ assert len(instances) == 1
101
+ instance = instances[0]
102
+ return instance.get("Status") == "Stopped"
103
+ cli_logger.error("Invalid node id: %s", node_id)
104
+ return False
105
+
106
+ def node_tags(self, node_id: str) -> Dict[str, str]:
107
+ instances = self.acs.describe_instances(instance_ids=[node_id])
108
+ if instances is not None:
109
+ assert len(instances) == 1
110
+ instance = instances[0]
111
+ if instance.get("Tags") is not None:
112
+ node_tags = dict()
113
+ for tag in instance.get("Tags").get("Tag"):
114
+ node_tags[tag.get("TagKey")] = tag.get("TagValue")
115
+ return node_tags
116
+ return dict()
117
+
118
+ def external_ip(self, node_id: str) -> str:
119
+ while True:
120
+ instances = self.acs.describe_instances(instance_ids=[node_id])
121
+ if instances is not None:
122
+ assert len(instances)
123
+ instance = instances[0]
124
+ if (
125
+ instance.get("PublicIpAddress") is not None
126
+ and instance.get("PublicIpAddress").get("IpAddress") is not None
127
+ ):
128
+ if len(instance.get("PublicIpAddress").get("IpAddress")) > 0:
129
+ return instance.get("PublicIpAddress").get("IpAddress")[0]
130
+ cli_logger.error("PublicIpAddress attribute is not exist. %s" % instance)
131
+ time.sleep(STOPPING_NODE_DELAY)
132
+
133
+ def internal_ip(self, node_id: str) -> str:
134
+ while True:
135
+ instances = self.acs.describe_instances(instance_ids=[node_id])
136
+ if instances is not None:
137
+ assert len(instances) == 1
138
+ instance = instances[0]
139
+ if (
140
+ instance.get("VpcAttributes") is not None
141
+ and instance.get("VpcAttributes").get("PrivateIpAddress")
142
+ is not None
143
+ and len(
144
+ instance.get("VpcAttributes")
145
+ .get("PrivateIpAddress")
146
+ .get("IpAddress")
147
+ )
148
+ > 0
149
+ ):
150
+ return (
151
+ instance.get("VpcAttributes")
152
+ .get("PrivateIpAddress")
153
+ .get("IpAddress")[0]
154
+ )
155
+ cli_logger.error("InnerIpAddress attribute is not exist. %s" % instance)
156
+ time.sleep(STOPPING_NODE_DELAY)
157
+
158
+ def set_node_tags(self, node_id: str, tags: Dict[str, str]) -> None:
159
+ is_batching_thread = False
160
+ with self.tag_cache_lock:
161
+ if not self.tag_cache_pending:
162
+ is_batching_thread = True
163
+ # Wait for threads in the last batch to exit
164
+ self.ready_for_new_batch.wait()
165
+ self.ready_for_new_batch.clear()
166
+ self.batch_update_done.clear()
167
+ self.tag_cache_pending[node_id].update(tags)
168
+
169
+ if is_batching_thread:
170
+ time.sleep(TAG_BATCH_DELAY)
171
+ with self.tag_cache_lock:
172
+ self._update_node_tags()
173
+ self.batch_update_done.set()
174
+
175
+ with self.count_lock:
176
+ self.batch_thread_count += 1
177
+ self.batch_update_done.wait()
178
+
179
+ with self.count_lock:
180
+ self.batch_thread_count -= 1
181
+ if self.batch_thread_count == 0:
182
+ self.ready_for_new_batch.set()
183
+
184
+ def _update_node_tags(self):
185
+ batch_updates = defaultdict(list)
186
+
187
+ for node_id, tags in self.tag_cache_pending.items():
188
+ for x in tags.items():
189
+ batch_updates[x].append(node_id)
190
+ self.tag_cache[node_id] = tags
191
+
192
+ self.tag_cache_pending = defaultdict(dict)
193
+
194
+ self._create_tags(batch_updates)
195
+
196
+ def _create_tags(self, batch_updates):
197
+
198
+ for (k, v), node_ids in batch_updates.items():
199
+ m = "Set tag {}={} on {}".format(k, v, node_ids)
200
+ with LogTimer("AliyunNodeProvider: {}".format(m)):
201
+ if k == TAG_RAY_NODE_NAME:
202
+ k = "Name"
203
+
204
+ self.acs.tag_resource(node_ids, [{"Key": k, "Value": v}])
205
+
206
+ def create_node(
207
+ self, node_config: Dict[str, Any], tags: Dict[str, str], count: int
208
+ ) -> Optional[Dict[str, Any]]:
209
+ filter_tags = [
210
+ {
211
+ "Key": TAG_RAY_CLUSTER_NAME,
212
+ "Value": self.cluster_name,
213
+ },
214
+ {"Key": TAG_RAY_NODE_KIND, "Value": tags[TAG_RAY_NODE_KIND]},
215
+ {"Key": TAG_RAY_USER_NODE_TYPE, "Value": tags[TAG_RAY_USER_NODE_TYPE]},
216
+ {"Key": TAG_RAY_LAUNCH_CONFIG, "Value": tags[TAG_RAY_LAUNCH_CONFIG]},
217
+ {"Key": TAG_RAY_NODE_NAME, "Value": tags[TAG_RAY_NODE_NAME]},
218
+ ]
219
+
220
+ reused_nodes_dict = {}
221
+ if self.cache_stopped_nodes:
222
+ reuse_nodes_candidate = self.acs.describe_instances(tags=filter_tags)
223
+ if reuse_nodes_candidate:
224
+ with cli_logger.group("Stopping instances to reuse"):
225
+ reuse_node_ids = []
226
+ for node in reuse_nodes_candidate:
227
+ node_id = node.get("InstanceId")
228
+ status = node.get("Status")
229
+ if status != STOPPING and status != STOPPED:
230
+ continue
231
+ if status == STOPPING:
232
+ # wait for node stopped
233
+ while (
234
+ self.acs.describe_instances(instance_ids=[node_id])[
235
+ 0
236
+ ].get("Status")
237
+ == STOPPING
238
+ ):
239
+ logging.info("wait for %s stop" % node_id)
240
+ time.sleep(STOPPING_NODE_DELAY)
241
+ # logger.info("reuse %s" % node_id)
242
+ reuse_node_ids.append(node_id)
243
+ reused_nodes_dict[node.get("InstanceId")] = node
244
+ self.acs.start_instance(node_id)
245
+ self.tag_cache[node_id] = node.get("Tags")
246
+ self.set_node_tags(node_id, tags)
247
+ if len(reuse_node_ids) == count:
248
+ break
249
+ count -= len(reuse_node_ids)
250
+
251
+ created_nodes_dict = {}
252
+ if count > 0:
253
+ filter_tags.append(
254
+ {"Key": TAG_RAY_NODE_STATUS, "Value": tags[TAG_RAY_NODE_STATUS]}
255
+ )
256
+ instance_id_sets = self.acs.run_instances(
257
+ instance_type=node_config["InstanceType"],
258
+ image_id=node_config["ImageId"],
259
+ tags=filter_tags,
260
+ amount=count,
261
+ vswitch_id=self.provider_config["v_switch_id"],
262
+ security_group_id=self.provider_config["security_group_id"],
263
+ key_pair_name=self.provider_config["key_name"],
264
+ )
265
+ instances = self.acs.describe_instances(instance_ids=instance_id_sets)
266
+
267
+ if instances is not None:
268
+ for instance in instances:
269
+ created_nodes_dict[instance.get("InstanceId")] = instance
270
+
271
+ all_created_nodes = reused_nodes_dict
272
+ all_created_nodes.update(created_nodes_dict)
273
+ return all_created_nodes
274
+
275
+ def terminate_node(self, node_id: str) -> None:
276
+ logger.info("terminate node: %s" % node_id)
277
+ if self.cache_stopped_nodes:
278
+ logger.info(
279
+ "Stopping instance {} (to terminate instead, "
280
+ "set `cache_stopped_nodes: False` "
281
+ "under `provider` in the cluster configuration)"
282
+ ).format(node_id)
283
+ self.acs.stop_instance(node_id)
284
+ else:
285
+ self.acs.delete_instance(node_id)
286
+
287
+ def terminate_nodes(self, node_ids: List[str]) -> None:
288
+ if not node_ids:
289
+ return
290
+ if self.cache_stopped_nodes:
291
+ logger.info(
292
+ "Stopping instances {} (to terminate instead, "
293
+ "set `cache_stopped_nodes: False` "
294
+ "under `provider` in the cluster configuration)".format(node_ids)
295
+ )
296
+
297
+ self.acs.stop_instances(node_ids)
298
+ else:
299
+ self.acs.delete_instances(node_ids)
300
+
301
+ def _get_node(self, node_id):
302
+ """Refresh and get info for this node, updating the cache."""
303
+ self.non_terminated_nodes({}) # Side effect: updates cache
304
+
305
+ if node_id in self.cached_nodes:
306
+ return self.cached_nodes[node_id]
307
+
308
+ # Node not in {pending, running} -- retry with a point query. This
309
+ # usually means the node was recently preempted or terminated.
310
+ matches = self.acs.describe_instances(instance_ids=[node_id])
311
+
312
+ assert len(matches) == 1, "Invalid instance id {}".format(node_id)
313
+ return matches[0]
314
+
315
+ def _get_cached_node(self, node_id):
316
+ """Return node info from cache if possible, otherwise fetches it."""
317
+ if node_id in self.cached_nodes:
318
+ return self.cached_nodes[node_id]
319
+
320
+ return self._get_node(node_id)
321
+
322
+ @staticmethod
323
+ def bootstrap_config(cluster_config):
324
+ return bootstrap_aliyun(cluster_config)
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/cli_logger.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Logger implementing the Command Line Interface.
2
+
3
+ A replacement for the standard Python `logging` API
4
+ designed for implementing a better CLI UX for the cluster launcher.
5
+
6
+ Supports color, bold text, italics, underlines, etc.
7
+ (depending on TTY features)
8
+ as well as indentation and other structured output.
9
+ """
10
+ import inspect
11
+ import logging
12
+ import os
13
+ import sys
14
+ import time
15
+ from contextlib import contextmanager
16
+ from functools import wraps
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple
18
+
19
+ import click
20
+ import colorama
21
+
22
+ # Import ray first to use the bundled colorama
23
+ import ray # noqa: F401
24
+
25
+ if sys.platform == "win32":
26
+ import msvcrt
27
+ else:
28
+ import select
29
+
30
+
31
+ class _ColorfulMock:
32
+ def __init__(self):
33
+ # do not do any color work
34
+ self.identity = lambda x: x
35
+
36
+ self.colorful = self
37
+ self.colormode = None
38
+
39
+ self.NO_COLORS = None
40
+ self.ANSI_8_COLORS = None
41
+
42
+ def disable(self):
43
+ pass
44
+
45
+ @contextmanager
46
+ def with_style(self, x):
47
+ class IdentityClass:
48
+ def __getattr__(self, name):
49
+ return lambda y: y
50
+
51
+ yield IdentityClass()
52
+
53
+ def __getattr__(self, name):
54
+ if name == "with_style":
55
+ return self.with_style
56
+
57
+ return self.identity
58
+
59
+
60
+ try:
61
+ import colorful as _cf
62
+ from colorful.core import ColorfulString
63
+
64
+ _cf.use_8_ansi_colors()
65
+ except ModuleNotFoundError:
66
+ # We mock Colorful to restrict the colors used for consistency
67
+ # anyway, so we also allow for not having colorful at all.
68
+ # If the Ray Core dependency on colorful is ever removed,
69
+ # the CliLogger code will still work.
70
+ class ColorfulString:
71
+ pass
72
+
73
+ _cf = _ColorfulMock()
74
+
75
+
76
+ # We want to only allow specific formatting
77
+ # to prevent people from accidentally making bad looking color schemes.
78
+ #
79
+ # This is especially important since most will look bad on either light
80
+ # or dark themes.
81
+ class _ColorfulProxy:
82
+ _proxy_allowlist = [
83
+ "disable",
84
+ "reset",
85
+ "bold",
86
+ "italic",
87
+ "underlined",
88
+ # used instead of `gray` as `dimmed` adapts to
89
+ # both light and dark themes
90
+ "dimmed",
91
+ "dodgerBlue", # group
92
+ "limeGreen", # success
93
+ "red", # error
94
+ "orange", # warning
95
+ "skyBlue", # label
96
+ "magenta", # syntax highlighting key words and symbols
97
+ "yellow", # syntax highlighting strings
98
+ ]
99
+
100
+ def __getattr__(self, name):
101
+ res = getattr(_cf, name)
102
+ if callable(res) and name not in _ColorfulProxy._proxy_allowlist:
103
+ raise ValueError(
104
+ "Usage of the colorful method '" + name + "' is forbidden "
105
+ "by the proxy to keep a consistent color scheme. "
106
+ "Check `cli_logger.py` for allowed methods"
107
+ )
108
+ return res
109
+
110
+
111
+ cf = _ColorfulProxy()
112
+
113
+ colorama.init(strip=False)
114
+
115
+
116
+ def _external_caller_info():
117
+ """Get the info from the caller frame.
118
+
119
+ Used to override the logging function and line number with the correct
120
+ ones. See the comment on _patched_makeRecord for more info.
121
+ """
122
+
123
+ frame = inspect.currentframe()
124
+ caller = frame
125
+ levels = 0
126
+ while caller.f_code.co_filename == __file__:
127
+ caller = caller.f_back
128
+ levels += 1
129
+ return {
130
+ "lineno": caller.f_lineno,
131
+ "filename": os.path.basename(caller.f_code.co_filename),
132
+ }
133
+
134
+
135
+ def _format_msg(
136
+ msg: str,
137
+ *args: Any,
138
+ no_format: bool = None,
139
+ _tags: Dict[str, Any] = None,
140
+ _numbered: Tuple[str, int, int] = None,
141
+ **kwargs: Any,
142
+ ):
143
+ """Formats a message for printing.
144
+
145
+ Renders `msg` using the built-in `str.format` and the passed-in
146
+ `*args` and `**kwargs`.
147
+
148
+ Args:
149
+ *args (Any): `.format` arguments for `msg`.
150
+ no_format (bool):
151
+ If `no_format` is `True`,
152
+ `.format` will not be called on the message.
153
+
154
+ Useful if the output is user-provided or may otherwise
155
+ contain an unexpected formatting string (e.g. "{}").
156
+ _tags (Dict[str, Any]):
157
+ key-value pairs to display at the end of
158
+ the message in square brackets.
159
+
160
+ If a tag is set to `True`, it is printed without the value,
161
+ the presence of the tag treated as a "flag".
162
+
163
+ E.g. `_format_msg("hello", _tags=dict(from=mom, signed=True))`
164
+ `hello [from=Mom, signed]`
165
+ _numbered (Tuple[str, int, int]):
166
+ `(brackets, i, n)`
167
+
168
+ The `brackets` string is composed of two "bracket" characters,
169
+ `i` is the index, `n` is the total.
170
+
171
+ The string `{i}/{n}` surrounded by the "brackets" is
172
+ prepended to the message.
173
+
174
+ This is used to number steps in a procedure, with different
175
+ brackets specifying different major tasks.
176
+
177
+ E.g. `_format_msg("hello", _numbered=("[]", 0, 5))`
178
+ `[0/5] hello`
179
+
180
+ Returns:
181
+ The formatted message.
182
+ """
183
+
184
+ if isinstance(msg, str) or isinstance(msg, ColorfulString):
185
+ tags_str = ""
186
+ if _tags is not None:
187
+ tags_list = []
188
+ for k, v in _tags.items():
189
+ if v is True:
190
+ tags_list += [k]
191
+ continue
192
+ if v is False:
193
+ continue
194
+
195
+ tags_list += [k + "=" + v]
196
+ if tags_list:
197
+ tags_str = cf.reset(cf.dimmed(" [{}]".format(", ".join(tags_list))))
198
+
199
+ numbering_str = ""
200
+ if _numbered is not None:
201
+ chars, i, n = _numbered
202
+ numbering_str = cf.dimmed(chars[0] + str(i) + "/" + str(n) + chars[1]) + " "
203
+
204
+ if no_format:
205
+ # todo: throw if given args/kwargs?
206
+ return numbering_str + msg + tags_str
207
+ return numbering_str + msg.format(*args, **kwargs) + tags_str
208
+
209
+ if kwargs:
210
+ raise ValueError("We do not support printing kwargs yet.")
211
+
212
+ res = [msg, *args]
213
+ res = [str(x) for x in res]
214
+ return ", ".join(res)
215
+
216
+
217
+ # TODO: come up with a plan to unify logging.
218
+ # formatter = logging.Formatter(
219
+ # # TODO(maximsmol): figure out the required log level padding
220
+ # # width automatically
221
+ # fmt="[{asctime}] {levelname:6} {message}",
222
+ # datefmt="%x %X",
223
+ # # We want alignment on our level names
224
+ # style="{")
225
+
226
+
227
+ def _isatty():
228
+ """More robust check for interactive terminal/tty."""
229
+ try:
230
+ # https://stackoverflow.com/questions/6108330/
231
+ # checking-for-interactive-shell-in-a-python-script
232
+ return sys.__stdin__.isatty()
233
+ except Exception:
234
+ # sometimes this can fail due to closed output
235
+ # either way, no-tty is generally safe fallback.
236
+ return False
237
+
238
+
239
+ class _CliLogger:
240
+ """Singleton class for CLI logging.
241
+
242
+ Without calling 'cli_logger.configure', the CLILogger will default
243
+ to 'record' style logging.
244
+
245
+ Attributes:
246
+ color_mode (str):
247
+ Can be "true", "false", or "auto".
248
+
249
+ Enables or disables `colorful`.
250
+
251
+ If `color_mode` is "auto", is set to `not stdout.isatty()`
252
+ indent_level (int):
253
+ The current indentation level.
254
+
255
+ All messages will be indented by prepending `" " * indent_level`
256
+ vebosity (int):
257
+ Output verbosity.
258
+
259
+ Low verbosity will disable `verbose` and `very_verbose` messages.
260
+ """
261
+
262
+ color_mode: str
263
+ # color_mode: Union[Literal["auto"], Literal["false"], Literal["true"]]
264
+ indent_level: int
265
+ interactive: bool
266
+ VALID_LOG_STYLES = ("auto", "record", "pretty")
267
+
268
+ _autodetected_cf_colormode: int
269
+
270
+ def __init__(self):
271
+ self.indent_level = 0
272
+
273
+ self._verbosity = 0
274
+ self._verbosity_overriden = False
275
+ self._color_mode = "auto"
276
+ self._log_style = "record"
277
+ self.pretty = False
278
+ self.interactive = False
279
+
280
+ # store whatever colorful has detected for future use if
281
+ # the color ouput is toggled (colorful detects # of supported colors,
282
+ # so it has some non-trivial logic to determine this)
283
+ self._autodetected_cf_colormode = cf.colorful.colormode
284
+ self.set_format()
285
+
286
+ def set_format(self, format_tmpl=None):
287
+ if not format_tmpl:
288
+ from ray.autoscaler._private.constants import LOGGER_FORMAT
289
+
290
+ format_tmpl = LOGGER_FORMAT
291
+ self._formatter = logging.Formatter(format_tmpl)
292
+
293
+ def configure(self, log_style=None, color_mode=None, verbosity=None):
294
+ """Configures the logger according to values."""
295
+ if log_style is not None:
296
+ self._set_log_style(log_style)
297
+
298
+ if color_mode is not None:
299
+ self._set_color_mode(color_mode)
300
+
301
+ if verbosity is not None:
302
+ self._set_verbosity(verbosity)
303
+
304
+ self.detect_colors()
305
+
306
+ @property
307
+ def log_style(self):
308
+ return self._log_style
309
+
310
+ def _set_log_style(self, x):
311
+ """Configures interactivity and formatting."""
312
+ self._log_style = x.lower()
313
+ self.interactive = _isatty()
314
+
315
+ if self._log_style == "auto":
316
+ self.pretty = _isatty()
317
+ elif self._log_style == "record":
318
+ self.pretty = False
319
+ self._set_color_mode("false")
320
+ elif self._log_style == "pretty":
321
+ self.pretty = True
322
+
323
+ @property
324
+ def color_mode(self):
325
+ return self._color_mode
326
+
327
+ def _set_color_mode(self, x):
328
+ self._color_mode = x.lower()
329
+ self.detect_colors()
330
+
331
+ @property
332
+ def verbosity(self):
333
+ if self._verbosity_overriden:
334
+ return self._verbosity
335
+ elif not self.pretty:
336
+ return 999
337
+ return self._verbosity
338
+
339
+ def _set_verbosity(self, x):
340
+ self._verbosity = x
341
+ self._verbosity_overriden = True
342
+
343
+ def detect_colors(self):
344
+ """Update color output settings.
345
+
346
+ Parse the `color_mode` string and optionally disable or force-enable
347
+ color output
348
+ (8-color ANSI if no terminal detected to be safe) in colorful.
349
+ """
350
+ if self.color_mode == "true":
351
+ if self._autodetected_cf_colormode != cf.NO_COLORS:
352
+ cf.colormode = self._autodetected_cf_colormode
353
+ else:
354
+ cf.colormode = cf.ANSI_8_COLORS
355
+ return
356
+ if self.color_mode == "false":
357
+ cf.disable()
358
+ return
359
+ if self.color_mode == "auto":
360
+ # colorful autodetects tty settings
361
+ return
362
+
363
+ raise ValueError("Invalid log color setting: " + self.color_mode)
364
+
365
+ def newline(self):
366
+ """Print a line feed."""
367
+ self.print("")
368
+
369
+ def _print(
370
+ self,
371
+ msg: str,
372
+ _level_str: str = "INFO",
373
+ _linefeed: bool = True,
374
+ end: str = None,
375
+ ):
376
+ """Proxy for printing messages.
377
+
378
+ Args:
379
+ msg: Message to print.
380
+ linefeed (bool):
381
+ If `linefeed` is `False` no linefeed is printed at the
382
+ end of the message.
383
+ """
384
+ if self.pretty:
385
+ rendered_message = " " * self.indent_level + msg
386
+ else:
387
+ if msg.strip() == "":
388
+ return
389
+ caller_info = _external_caller_info()
390
+ record = logging.LogRecord(
391
+ name="cli",
392
+ # We override the level name later
393
+ # TODO(maximsmol): give approximate level #s to our log levels
394
+ level=0,
395
+ # The user-facing logs do not need this information anyway
396
+ # and it would be very tedious to extract since _print
397
+ # can be at varying depths in the call stack
398
+ # TODO(maximsmol): do it anyway to be extra
399
+ pathname=caller_info["filename"],
400
+ lineno=caller_info["lineno"],
401
+ msg=msg,
402
+ args={},
403
+ # No exception
404
+ exc_info=None,
405
+ )
406
+ record.levelname = _level_str
407
+ rendered_message = self._formatter.format(record)
408
+
409
+ # We aren't using standard python logging convention, so we hardcode
410
+ # the log levels for now.
411
+ if _level_str in ["WARNING", "ERROR", "PANIC"]:
412
+ stream = sys.stderr
413
+ else:
414
+ stream = sys.stdout
415
+
416
+ if not _linefeed:
417
+ stream.write(rendered_message)
418
+ stream.flush()
419
+ return
420
+
421
+ kwargs = {"end": end}
422
+ print(rendered_message, file=stream, **kwargs)
423
+
424
+ def indented(self):
425
+ """Context manager that starts an indented block of output."""
426
+ cli_logger = self
427
+
428
+ class IndentedContextManager:
429
+ def __enter__(self):
430
+ cli_logger.indent_level += 1
431
+
432
+ def __exit__(self, type, value, tb):
433
+ cli_logger.indent_level -= 1
434
+
435
+ return IndentedContextManager()
436
+
437
+ def group(self, msg: str, *args: Any, **kwargs: Any):
438
+ """Print a group title in a special color and start an indented block.
439
+
440
+ For arguments, see `_format_msg`.
441
+ """
442
+ self.print(cf.dodgerBlue(msg), *args, **kwargs)
443
+
444
+ return self.indented()
445
+
446
+ def verbatim_error_ctx(self, msg: str, *args: Any, **kwargs: Any):
447
+ """Context manager for printing multi-line error messages.
448
+
449
+ Displays a start sequence "!!! {optional message}"
450
+ and a matching end sequence "!!!".
451
+
452
+ The string "!!!" can be used as a "tombstone" for searching.
453
+
454
+ For arguments, see `_format_msg`.
455
+ """
456
+ cli_logger = self
457
+
458
+ class VerbatimErorContextManager:
459
+ def __enter__(self):
460
+ cli_logger.error(cf.bold("!!! ") + "{}", msg, *args, **kwargs)
461
+
462
+ def __exit__(self, type, value, tb):
463
+ cli_logger.error(cf.bold("!!!"))
464
+
465
+ return VerbatimErorContextManager()
466
+
467
+ def labeled_value(self, key: str, msg: str, *args: Any, **kwargs: Any):
468
+ """Displays a key-value pair with special formatting.
469
+
470
+ Args:
471
+ key: Label that is prepended to the message.
472
+
473
+ For other arguments, see `_format_msg`.
474
+ """
475
+ self._print(cf.skyBlue(key) + ": " + _format_msg(cf.bold(msg), *args, **kwargs))
476
+
477
+ def verbose(self, msg: str, *args: Any, **kwargs: Any):
478
+ """Prints a message if verbosity is not 0.
479
+
480
+ For arguments, see `_format_msg`.
481
+ """
482
+ if self.verbosity > 0:
483
+ self.print(msg, *args, _level_str="VINFO", **kwargs)
484
+
485
+ def verbose_warning(self, msg, *args, **kwargs):
486
+ """Prints a formatted warning if verbosity is not 0.
487
+
488
+ For arguments, see `_format_msg`.
489
+ """
490
+ if self.verbosity > 0:
491
+ self._warning(msg, *args, _level_str="VWARN", **kwargs)
492
+
493
+ def verbose_error(self, msg: str, *args: Any, **kwargs: Any):
494
+ """Logs an error if verbosity is not 0.
495
+
496
+ For arguments, see `_format_msg`.
497
+ """
498
+ if self.verbosity > 0:
499
+ self._error(msg, *args, _level_str="VERR", **kwargs)
500
+
501
+ def very_verbose(self, msg: str, *args: Any, **kwargs: Any):
502
+ """Prints if verbosity is > 1.
503
+
504
+ For arguments, see `_format_msg`.
505
+ """
506
+ if self.verbosity > 1:
507
+ self.print(msg, *args, _level_str="VVINFO", **kwargs)
508
+
509
+ def success(self, msg: str, *args: Any, **kwargs: Any):
510
+ """Prints a formatted success message.
511
+
512
+ For arguments, see `_format_msg`.
513
+ """
514
+ self.print(cf.limeGreen(msg), *args, _level_str="SUCC", **kwargs)
515
+
516
+ def _warning(self, msg: str, *args: Any, _level_str: str = None, **kwargs: Any):
517
+ """Prints a formatted warning message.
518
+
519
+ For arguments, see `_format_msg`.
520
+ """
521
+ if _level_str is None:
522
+ raise ValueError("Log level not set.")
523
+ self.print(cf.orange(msg), *args, _level_str=_level_str, **kwargs)
524
+
525
+ def warning(self, *args, **kwargs):
526
+ self._warning(*args, _level_str="WARN", **kwargs)
527
+
528
+ def _error(self, msg: str, *args: Any, _level_str: str = None, **kwargs: Any):
529
+ """Prints a formatted error message.
530
+
531
+ For arguments, see `_format_msg`.
532
+ """
533
+ if _level_str is None:
534
+ raise ValueError("Log level not set.")
535
+ self.print(cf.red(msg), *args, _level_str=_level_str, **kwargs)
536
+
537
+ def error(self, *args, **kwargs):
538
+ self._error(*args, _level_str="ERR", **kwargs)
539
+
540
+ def panic(self, *args, **kwargs):
541
+ self._error(*args, _level_str="PANIC", **kwargs)
542
+
543
+ # Fine to expose _level_str here, since this is a general log function.
544
+ def print(
545
+ self,
546
+ msg: str,
547
+ *args: Any,
548
+ _level_str: str = "INFO",
549
+ end: str = None,
550
+ **kwargs: Any,
551
+ ):
552
+ """Prints a message.
553
+
554
+ For arguments, see `_format_msg`.
555
+ """
556
+ self._print(_format_msg(msg, *args, **kwargs), _level_str=_level_str, end=end)
557
+
558
+ def info(self, msg: str, no_format=True, *args, **kwargs):
559
+ self.print(msg, no_format=no_format, *args, **kwargs)
560
+
561
+ def abort(
562
+ self, msg: Optional[str] = None, *args: Any, exc: Any = None, **kwargs: Any
563
+ ):
564
+ """Prints an error and aborts execution.
565
+
566
+ Print an error and throw an exception to terminate the program
567
+ (the exception will not print a message).
568
+ """
569
+ if msg is not None:
570
+ self._error(msg, *args, _level_str="PANIC", **kwargs)
571
+
572
+ if exc is not None:
573
+ raise exc
574
+
575
+ exc_cls = click.ClickException
576
+ if self.pretty:
577
+ exc_cls = SilentClickException
578
+
579
+ if msg is None:
580
+ msg = "Exiting due to cli_logger.abort()"
581
+ raise exc_cls(msg)
582
+
583
+ def doassert(self, val: bool, msg: str, *args: Any, **kwargs: Any):
584
+ """Handle assertion without throwing a scary exception.
585
+
586
+ Args:
587
+ val: Value to check.
588
+
589
+ For other arguments, see `_format_msg`.
590
+ """
591
+ if not val:
592
+ exc = None
593
+ if not self.pretty:
594
+ exc = AssertionError()
595
+
596
+ # TODO(maximsmol): rework asserts so that we get the expression
597
+ # that triggered the assert
598
+ # to do this, install a global try-catch
599
+ # for AssertionError and raise them normally
600
+ self.abort(msg, *args, exc=exc, **kwargs)
601
+
602
+ def render_list(self, xs: List[str], separator: str = cf.reset(", ")):
603
+ """Render a list of bolded values using a non-bolded separator."""
604
+ return separator.join([str(cf.bold(x)) for x in xs])
605
+
606
+ def confirm(
607
+ self,
608
+ yes: bool,
609
+ msg: str,
610
+ *args: Any,
611
+ _abort: bool = False,
612
+ _default: bool = False,
613
+ _timeout_s: Optional[float] = None,
614
+ **kwargs: Any,
615
+ ):
616
+ """Display a confirmation dialog.
617
+
618
+ Valid answers are "y/yes/true/1" and "n/no/false/0".
619
+
620
+ Args:
621
+ yes: If `yes` is `True` the dialog will default to "yes"
622
+ and continue without waiting for user input.
623
+ _abort (bool):
624
+ If `_abort` is `True`,
625
+ "no" means aborting the program.
626
+ _default (bool):
627
+ The default action to take if the user just presses enter
628
+ with no input.
629
+ _timeout_s (float):
630
+ If user has no input within _timeout_s seconds, the default
631
+ action is taken. None means no timeout.
632
+ """
633
+ should_abort = _abort
634
+ default = _default
635
+
636
+ if not self.interactive and not yes:
637
+ # no formatting around --yes here since this is non-interactive
638
+ self.error(
639
+ "This command requires user confirmation. "
640
+ "When running non-interactively, supply --yes to skip."
641
+ )
642
+ raise ValueError("Non-interactive confirm without --yes.")
643
+
644
+ if default:
645
+ yn_str = "Y/n"
646
+ else:
647
+ yn_str = "y/N"
648
+
649
+ confirm_str = cf.underlined("Confirm [" + yn_str + "]:") + " "
650
+
651
+ rendered_message = _format_msg(msg, *args, **kwargs)
652
+ # the rendered message ends with ascii coding
653
+ if rendered_message and not msg.endswith("\n"):
654
+ rendered_message += " "
655
+
656
+ msg_len = len(rendered_message.split("\n")[-1])
657
+ complete_str = rendered_message + confirm_str
658
+
659
+ if yes:
660
+ self._print(complete_str + "y " + cf.dimmed("[automatic, due to --yes]"))
661
+ return True
662
+
663
+ self._print(complete_str, _linefeed=False)
664
+
665
+ res = None
666
+ yes_answers = ["y", "yes", "true", "1"]
667
+ no_answers = ["n", "no", "false", "0"]
668
+ try:
669
+ while True:
670
+ if _timeout_s is None:
671
+ ans = sys.stdin.readline()
672
+ elif sys.platform == "win32":
673
+ # Windows doesn't support select
674
+ start_time = time.time()
675
+ ans = ""
676
+ while True:
677
+ if (time.time() - start_time) >= _timeout_s:
678
+ self.newline()
679
+ ans = "\n"
680
+ break
681
+ elif msvcrt.kbhit():
682
+ ch = msvcrt.getwch()
683
+ if ch in ("\n", "\r"):
684
+ self.newline()
685
+ ans = ans + "\n"
686
+ break
687
+ elif ch == "\b":
688
+ if ans:
689
+ ans = ans[:-1]
690
+ # Emulate backspace erasing
691
+ print("\b \b", end="", flush=True)
692
+ else:
693
+ ans = ans + ch
694
+ print(ch, end="", flush=True)
695
+ else:
696
+ time.sleep(0.1)
697
+ else:
698
+ ready, _, _ = select.select([sys.stdin], [], [], _timeout_s)
699
+ if not ready:
700
+ self.newline()
701
+ ans = "\n"
702
+ else:
703
+ ans = sys.stdin.readline()
704
+
705
+ ans = ans.lower()
706
+
707
+ if ans == "\n":
708
+ res = default
709
+ break
710
+
711
+ ans = ans.strip()
712
+ if ans in yes_answers:
713
+ res = True
714
+ break
715
+ if ans in no_answers:
716
+ res = False
717
+ break
718
+
719
+ indent = " " * msg_len
720
+ self.error(
721
+ "{}Invalid answer: {}. Expected {} or {}",
722
+ indent,
723
+ cf.bold(ans.strip()),
724
+ self.render_list(yes_answers, "/"),
725
+ self.render_list(no_answers, "/"),
726
+ )
727
+ self._print(indent + confirm_str, _linefeed=False)
728
+ except KeyboardInterrupt:
729
+ self.newline()
730
+ res = default
731
+
732
+ if not res and should_abort:
733
+ # todo: make sure we tell the user if they
734
+ # need to do cleanup
735
+ self._print("Exiting...")
736
+ raise SilentClickException(
737
+ "Exiting due to the response to confirm(should_abort=True)."
738
+ )
739
+
740
+ return res
741
+
742
+ def prompt(self, msg: str, *args, **kwargs):
743
+ """Prompt the user for some text input.
744
+
745
+ Args:
746
+ msg: The mesage to display to the user before the prompt.
747
+
748
+ Returns:
749
+ The string entered by the user.
750
+ """
751
+ complete_str = cf.underlined(msg)
752
+ rendered_message = _format_msg(complete_str, *args, **kwargs)
753
+ # the rendered message ends with ascii coding
754
+ if rendered_message and not msg.endswith("\n"):
755
+ rendered_message += " "
756
+ self._print(rendered_message, linefeed=False)
757
+
758
+ res = ""
759
+ try:
760
+ ans = sys.stdin.readline()
761
+ ans = ans.lower()
762
+ res = ans.strip()
763
+ except KeyboardInterrupt:
764
+ self.newline()
765
+
766
+ return res
767
+
768
+ def flush(self):
769
+ sys.stdout.flush()
770
+ sys.stderr.flush()
771
+
772
+
773
+ class SilentClickException(click.ClickException):
774
+ """`ClickException` that does not print a message.
775
+
776
+ Some of our tooling relies on catching ClickException in particular.
777
+
778
+ However the default prints a message, which is undesirable since we expect
779
+ our code to log errors manually using `cli_logger.error()` to allow for
780
+ colors and other formatting.
781
+ """
782
+
783
+ def __init__(self, message: str):
784
+ super(SilentClickException, self).__init__(message)
785
+
786
+ def show(self, file=None):
787
+ pass
788
+
789
+
790
+ cli_logger = _CliLogger()
791
+
792
+ CLICK_LOGGING_OPTIONS = [
793
+ click.option(
794
+ "--log-style",
795
+ required=False,
796
+ type=click.Choice(cli_logger.VALID_LOG_STYLES, case_sensitive=False),
797
+ default="auto",
798
+ help=(
799
+ "If 'pretty', outputs with formatting and color. If 'record', "
800
+ "outputs record-style without formatting. "
801
+ "'auto' defaults to 'pretty', and disables pretty logging "
802
+ "if stdin is *not* a TTY."
803
+ ),
804
+ ),
805
+ click.option(
806
+ "--log-color",
807
+ required=False,
808
+ type=click.Choice(["auto", "false", "true"], case_sensitive=False),
809
+ default="auto",
810
+ help=("Use color logging. Auto enables color logging if stdout is a TTY."),
811
+ ),
812
+ click.option("-v", "--verbose", default=None, count=True),
813
+ ]
814
+
815
+
816
+ def add_click_logging_options(f: Callable) -> Callable:
817
+ for option in reversed(CLICK_LOGGING_OPTIONS):
818
+ f = option(f)
819
+
820
+ @wraps(f)
821
+ def wrapper(*args, log_style=None, log_color=None, verbose=None, **kwargs):
822
+ cli_logger.configure(log_style, log_color, verbose)
823
+ return f(*args, **kwargs)
824
+
825
+ return wrapper
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/cluster_dump.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import subprocess
4
+ import sys
5
+ import tarfile
6
+ import tempfile
7
+ import threading
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from contextlib import contextmanager
10
+ from typing import List, Optional, Sequence, Tuple
11
+
12
+ import yaml
13
+
14
+ import ray # noqa: F401
15
+ from ray.autoscaler._private.cli_logger import cli_logger
16
+ from ray.autoscaler._private.providers import _get_node_provider
17
+ from ray.autoscaler.tags import NODE_KIND_HEAD, NODE_KIND_WORKER, TAG_RAY_NODE_KIND
18
+
19
+ # Import psutil after ray so the packaged version is used.
20
+ import psutil
21
+
22
+ MAX_PARALLEL_SSH_WORKERS = 8
23
+ DEFAULT_SSH_USER = "ubuntu"
24
+ DEFAULT_SSH_KEYS = ["~/ray_bootstrap_key.pem", "~/.ssh/ray-autoscaler_2_us-west-2.pem"]
25
+
26
+
27
+ class CommandFailed(RuntimeError):
28
+ pass
29
+
30
+
31
+ class LocalCommandFailed(CommandFailed):
32
+ pass
33
+
34
+
35
+ class RemoteCommandFailed(CommandFailed):
36
+ pass
37
+
38
+
39
+ class GetParameters:
40
+ def __init__(
41
+ self,
42
+ logs: bool = True,
43
+ debug_state: bool = True,
44
+ pip: bool = True,
45
+ processes: bool = True,
46
+ processes_verbose: bool = True,
47
+ processes_list: Optional[List[Tuple[str, bool]]] = None,
48
+ ):
49
+ self.logs = logs
50
+ self.debug_state = debug_state
51
+ self.pip = pip
52
+ self.processes = processes
53
+ self.processes_verbose = processes_verbose
54
+ self.processes_list = processes_list
55
+
56
+
57
+ class Node:
58
+ """Node (as in "machine")"""
59
+
60
+ def __init__(
61
+ self,
62
+ host: str,
63
+ ssh_user: str = "ubuntu",
64
+ ssh_key: str = "~/ray_bootstrap_key.pem",
65
+ docker_container: Optional[str] = None,
66
+ is_head: bool = False,
67
+ ):
68
+ self.host = host
69
+ self.ssh_user = ssh_user
70
+ self.ssh_key = ssh_key
71
+ self.docker_container = docker_container
72
+ self.is_head = is_head
73
+
74
+
75
+ class Archive:
76
+ """Archive object to collect and compress files into a single file.
77
+
78
+ Objects of this class can be passed around to different data collection
79
+ functions. These functions can use the :meth:`subdir` method to add
80
+ files to a sub directory of the archive.
81
+
82
+ """
83
+
84
+ def __init__(self, file: Optional[str] = None):
85
+ self.file = file or tempfile.mkstemp(prefix="ray_logs_", suffix=".tar.gz")[1]
86
+ self.tar = None
87
+ self._lock = threading.Lock()
88
+
89
+ @property
90
+ def is_open(self):
91
+ return bool(self.tar)
92
+
93
+ def open(self):
94
+ self.tar = tarfile.open(self.file, "w:gz")
95
+
96
+ def close(self):
97
+ self.tar.close()
98
+ self.tar = None
99
+
100
+ def __enter__(self):
101
+ self.open()
102
+ return self
103
+
104
+ def __exit__(self, exc_type, exc_val, exc_tb):
105
+ self.close()
106
+
107
+ @contextmanager
108
+ def subdir(self, subdir: str, root: Optional[str] = "/"):
109
+ """Open a context to add files to the archive.
110
+
111
+ Example:
112
+
113
+ .. code-block:: python
114
+
115
+ with Archive("file.tar.gz") as archive:
116
+ with archive.subdir("logfiles", root="/tmp/logs") as sd:
117
+ # Will be added as `logfiles/nested/file.txt`
118
+ sd.add("/tmp/logs/nested/file.txt")
119
+
120
+ Args:
121
+ subdir: Subdir to which to add files to. Calling the
122
+ ``add(path)`` command will place files into the ``subdir``
123
+ directory of the archive.
124
+ root: Root path. Files without an explicit ``arcname``
125
+ will be named relatively to this path.
126
+
127
+ Yields:
128
+ A context object that can be used to add files to the archive.
129
+ """
130
+ root = os.path.abspath(root)
131
+
132
+ class _Context:
133
+ @staticmethod
134
+ def add(path: str, arcname: Optional[str] = None):
135
+ path = os.path.abspath(path)
136
+ arcname = arcname or os.path.join(subdir, os.path.relpath(path, root))
137
+
138
+ self._lock.acquire()
139
+ self.tar.add(path, arcname=arcname)
140
+ self._lock.release()
141
+
142
+ yield _Context()
143
+
144
+
145
+ ###
146
+ # Functions to gather logs and information on the local node
147
+ ###
148
+
149
+
150
+ def get_local_ray_logs(
151
+ archive: Archive,
152
+ exclude: Optional[Sequence[str]] = None,
153
+ session_log_dir: str = "/tmp/ray/session_latest",
154
+ ) -> Archive:
155
+ """Copy local log files into an archive.
156
+
157
+ Args:
158
+ archive: Archive object to add log files to.
159
+ exclude (Sequence[str]): Sequence of regex patterns. Files that match
160
+ any of these patterns will not be included in the archive.
161
+ session_dir: Path to the Ray session files. Defaults to
162
+ ``/tmp/ray/session_latest``
163
+
164
+ Returns:
165
+ Open archive object.
166
+
167
+ """
168
+ if not archive.is_open:
169
+ archive.open()
170
+
171
+ exclude = exclude or []
172
+
173
+ session_log_dir = os.path.join(os.path.expanduser(session_log_dir), "logs")
174
+
175
+ with archive.subdir("logs", root=session_log_dir) as sd:
176
+ for root, dirs, files in os.walk(session_log_dir):
177
+ for file in files:
178
+ file_path = os.path.join(root, file)
179
+ rel_path = os.path.relpath(file_path, start=session_log_dir)
180
+ # Skip file if it matches any pattern in `exclude`
181
+ if any(re.match(pattern, rel_path) for pattern in exclude):
182
+ continue
183
+ sd.add(file_path)
184
+
185
+ return archive
186
+
187
+
188
+ def get_local_debug_state(
189
+ archive: Archive, session_dir: str = "/tmp/ray/session_latest"
190
+ ) -> Archive:
191
+ """Copy local log files into an archive.
192
+
193
+ Args:
194
+ archive: Archive object to add log files to.
195
+ session_dir: Path to the Ray session files. Defaults to
196
+ ``/tmp/ray/session_latest``
197
+
198
+ Returns:
199
+ Open archive object.
200
+
201
+ """
202
+ if not archive.is_open:
203
+ archive.open()
204
+
205
+ session_dir = os.path.expanduser(session_dir)
206
+ debug_state_file = os.path.join(session_dir, "logs/debug_state.txt")
207
+
208
+ if not os.path.exists(debug_state_file):
209
+ raise LocalCommandFailed("No `debug_state.txt` file found.")
210
+
211
+ with archive.subdir("", root=session_dir) as sd:
212
+ sd.add(debug_state_file)
213
+
214
+ return archive
215
+
216
+
217
+ def get_local_pip_packages(archive: Archive):
218
+ """Get currently installed pip packages and write into an archive.
219
+
220
+ Args:
221
+ archive: Archive object to add meta files to.
222
+
223
+ Returns:
224
+ Open archive object.
225
+ """
226
+ if not archive.is_open:
227
+ archive.open()
228
+
229
+ try:
230
+ from pip._internal.operations import freeze
231
+ except ImportError: # pip < 10.0
232
+ from pip.operations import freeze
233
+
234
+ with tempfile.NamedTemporaryFile("wt") as fp:
235
+ for line in freeze.freeze():
236
+ fp.writelines([line, "\n"])
237
+
238
+ fp.flush()
239
+ with archive.subdir("") as sd:
240
+ sd.add(fp.name, "pip_packages.txt")
241
+
242
+ return archive
243
+
244
+
245
+ def get_local_ray_processes(
246
+ archive: Archive,
247
+ processes: Optional[List[Tuple[str, bool]]] = None,
248
+ verbose: bool = False,
249
+ ):
250
+ """Get the status of all the relevant ray processes.
251
+ Args:
252
+ archive: Archive object to add process info files to.
253
+ processes: List of processes to get information on. The first
254
+ element of the tuple is a string to filter by, and the second
255
+ element is a boolean indicating if we should filter by command
256
+ name (True) or command line including parameters (False)
257
+ verbose: If True, show entire executable command line.
258
+ If False, show just the first term.
259
+ Returns:
260
+ Open archive object.
261
+ """
262
+ if not processes:
263
+ # local import to avoid circular dependencies
264
+ from ray.autoscaler._private.constants import RAY_PROCESSES
265
+
266
+ processes = RAY_PROCESSES
267
+
268
+ process_infos = []
269
+ for process in psutil.process_iter(["pid", "name", "cmdline", "status"]):
270
+ try:
271
+ with process.oneshot():
272
+ cmdline = " ".join(process.cmdline())
273
+ process_infos.append(
274
+ (
275
+ {
276
+ "executable": cmdline
277
+ if verbose
278
+ else cmdline.split("--", 1)[0][:-1],
279
+ "name": process.name(),
280
+ "pid": process.pid,
281
+ "status": process.status(),
282
+ },
283
+ process.cmdline(),
284
+ )
285
+ )
286
+ except Exception as exc:
287
+ raise LocalCommandFailed(exc) from exc
288
+
289
+ relevant_processes = {}
290
+ for process_dict, cmdline in process_infos:
291
+ for keyword, filter_by_cmd in processes:
292
+ if filter_by_cmd:
293
+ corpus = process_dict["name"]
294
+ else:
295
+ corpus = subprocess.list2cmdline(cmdline)
296
+ if keyword in corpus and process_dict["pid"] not in relevant_processes:
297
+ relevant_processes[process_dict["pid"]] = process_dict
298
+
299
+ with tempfile.NamedTemporaryFile("wt") as fp:
300
+ for line in relevant_processes.values():
301
+ fp.writelines([yaml.dump(line), "\n"])
302
+
303
+ fp.flush()
304
+ with archive.subdir("meta") as sd:
305
+ sd.add(fp.name, "process_info.txt")
306
+
307
+ return archive
308
+
309
+
310
+ def get_all_local_data(archive: Archive, parameters: GetParameters):
311
+ """Get all local data.
312
+
313
+ Gets:
314
+ - The Ray logs of the latest session
315
+ - The currently installed pip packages
316
+
317
+ Args:
318
+ archive: Archive object to add meta files to.
319
+ parameters: Parameters (settings) for getting data.
320
+
321
+ Returns:
322
+ Open archive object.
323
+ """
324
+ if not archive.is_open:
325
+ archive.open()
326
+
327
+ if parameters.logs:
328
+ try:
329
+ get_local_ray_logs(archive=archive)
330
+ except LocalCommandFailed as exc:
331
+ cli_logger.error(exc)
332
+ if parameters.debug_state:
333
+ try:
334
+ get_local_debug_state(archive=archive)
335
+ except LocalCommandFailed as exc:
336
+ cli_logger.error(exc)
337
+ if parameters.pip:
338
+ try:
339
+ get_local_pip_packages(archive=archive)
340
+ except LocalCommandFailed as exc:
341
+ cli_logger.error(exc)
342
+ if parameters.processes:
343
+ try:
344
+ get_local_ray_processes(
345
+ archive=archive,
346
+ processes=parameters.processes_list,
347
+ verbose=parameters.processes_verbose,
348
+ )
349
+ except LocalCommandFailed as exc:
350
+ cli_logger.error(exc)
351
+
352
+ return archive
353
+
354
+
355
+ ###
356
+ # Functions to invoke remote scripts and gather data from remote nodes
357
+ ###
358
+
359
+
360
+ def _wrap(items: List[str], quotes="'"):
361
+ return f"{quotes}{' '.join(items)}{quotes}"
362
+
363
+
364
+ def create_and_get_archive_from_remote_node(
365
+ remote_node: Node, parameters: GetParameters, script_path: str = "ray"
366
+ ) -> Optional[str]:
367
+ """Create an archive containing logs on a remote node and transfer.
368
+
369
+ This will call ``ray local-dump --stream`` on the remote
370
+ node. The resulting file will be saved locally in a temporary file and
371
+ returned.
372
+
373
+ Args:
374
+ remote_node: Remote node to gather archive from.
375
+ script_path: Path to this script on the remote node.
376
+ parameters: Parameters (settings) for getting data.
377
+
378
+ Returns:
379
+ Path to a temporary file containing the node's collected data.
380
+
381
+ """
382
+ cmd = [
383
+ "ssh",
384
+ "-o StrictHostKeyChecking=no",
385
+ "-o UserKnownHostsFile=/dev/null",
386
+ "-o LogLevel=ERROR",
387
+ "-i",
388
+ remote_node.ssh_key,
389
+ f"{remote_node.ssh_user}@{remote_node.host}",
390
+ ]
391
+
392
+ if remote_node.docker_container:
393
+ cmd += [
394
+ "docker",
395
+ "exec",
396
+ remote_node.docker_container,
397
+ ]
398
+
399
+ collect_cmd = [script_path, "local-dump", "--stream"]
400
+ collect_cmd += ["--logs"] if parameters.logs else ["--no-logs"]
401
+ collect_cmd += ["--debug-state"] if parameters.debug_state else ["--no-debug-state"]
402
+ collect_cmd += ["--pip"] if parameters.pip else ["--no-pip"]
403
+ collect_cmd += ["--processes"] if parameters.processes else ["--no-processes"]
404
+ if parameters.processes:
405
+ collect_cmd += (
406
+ ["--processes-verbose"]
407
+ if parameters.processes_verbose
408
+ else ["--no-proccesses-verbose"]
409
+ )
410
+
411
+ cmd += ["/bin/bash", "-c", _wrap(collect_cmd, quotes='"')]
412
+
413
+ cat = "node" if not remote_node.is_head else "head"
414
+
415
+ cli_logger.print(f"Collecting data from remote node: {remote_node.host}")
416
+ tmp = tempfile.mkstemp(prefix=f"ray_{cat}_{remote_node.host}_", suffix=".tar.gz")[1]
417
+ with open(tmp, "wb") as fp:
418
+ try:
419
+ subprocess.check_call(cmd, stdout=fp, stderr=sys.stderr)
420
+ except subprocess.CalledProcessError as exc:
421
+ raise RemoteCommandFailed(
422
+ f"Gathering logs from remote node failed: {' '.join(cmd)}"
423
+ ) from exc
424
+
425
+ return tmp
426
+
427
+
428
+ def create_and_add_remote_data_to_local_archive(
429
+ archive: Archive, remote_node: Node, parameters: GetParameters
430
+ ):
431
+ """Create and get data from remote node and add to local archive.
432
+
433
+ Args:
434
+ archive: Archive object to add remote data to.
435
+ remote_node: Remote node to gather archive from.
436
+ parameters: Parameters (settings) for getting data.
437
+
438
+ Returns:
439
+ Open archive object.
440
+ """
441
+ tmp = create_and_get_archive_from_remote_node(remote_node, parameters)
442
+
443
+ if not archive.is_open:
444
+ archive.open()
445
+
446
+ cat = "node" if not remote_node.is_head else "head"
447
+
448
+ with archive.subdir("", root=os.path.dirname(tmp)) as sd:
449
+ sd.add(tmp, arcname=f"ray_{cat}_{remote_node.host}.tar.gz")
450
+
451
+ return archive
452
+
453
+
454
+ def create_and_add_local_data_to_local_archive(
455
+ archive: Archive, parameters: GetParameters
456
+ ):
457
+ """Create and get data from this node and add to archive.
458
+
459
+ Args:
460
+ archive: Archive object to add remote data to.
461
+ parameters: Parameters (settings) for getting data.
462
+
463
+ Returns:
464
+ Open archive object.
465
+ """
466
+ with Archive() as local_data_archive:
467
+ get_all_local_data(local_data_archive, parameters)
468
+
469
+ if not archive.is_open:
470
+ archive.open()
471
+
472
+ with archive.subdir("", root=os.path.dirname(local_data_archive.file)) as sd:
473
+ sd.add(local_data_archive.file, arcname="local_node.tar.gz")
474
+
475
+ os.remove(local_data_archive.file)
476
+
477
+ return archive
478
+
479
+
480
+ def create_archive_for_remote_nodes(
481
+ archive: Archive, remote_nodes: Sequence[Node], parameters: GetParameters
482
+ ):
483
+ """Create an archive combining data from the remote nodes.
484
+
485
+ This will parallelize calls to get data from remote nodes.
486
+
487
+ Args:
488
+ archive: Archive object to add remote data to.
489
+ remote_nodes (Sequence[Node]): Sequence of remote nodes.
490
+ parameters: Parameters (settings) for getting data.
491
+
492
+ Returns:
493
+ Open archive object.
494
+
495
+ """
496
+ if not archive.is_open:
497
+ archive.open()
498
+
499
+ with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SSH_WORKERS) as executor:
500
+ for remote_node in remote_nodes:
501
+ executor.submit(
502
+ create_and_add_remote_data_to_local_archive,
503
+ archive=archive,
504
+ remote_node=remote_node,
505
+ parameters=parameters,
506
+ )
507
+
508
+ return archive
509
+
510
+
511
+ def create_archive_for_local_and_remote_nodes(
512
+ archive: Archive, remote_nodes: Sequence[Node], parameters: GetParameters
513
+ ):
514
+ """Create an archive combining data from the local and remote nodes.
515
+
516
+ This will parallelize calls to get data from remote nodes.
517
+
518
+ Args:
519
+ archive: Archive object to add data to.
520
+ remote_nodes (Sequence[Node]): Sequence of remote nodes.
521
+ parameters: Parameters (settings) for getting data.
522
+
523
+ Returns:
524
+ Open archive object.
525
+
526
+ """
527
+ if not archive.is_open:
528
+ archive.open()
529
+
530
+ try:
531
+ create_and_add_local_data_to_local_archive(archive, parameters)
532
+ except CommandFailed as exc:
533
+ cli_logger.error(exc)
534
+
535
+ create_archive_for_remote_nodes(archive, remote_nodes, parameters)
536
+
537
+ cli_logger.print(
538
+ f"Collected data from local node and {len(remote_nodes)} " f"remote nodes."
539
+ )
540
+ return archive
541
+
542
+
543
+ ###
544
+ # Ray cluster info
545
+ ###
546
+ def get_info_from_ray_cluster_config(
547
+ cluster_config: str,
548
+ ) -> Tuple[List[str], str, str, Optional[str], Optional[str]]:
549
+ """Get information from Ray cluster config.
550
+
551
+ Return list of host IPs, ssh user, ssh key file, and optional docker
552
+ container.
553
+
554
+ Args:
555
+ cluster_config: Path to ray cluster config.
556
+
557
+ Returns:
558
+ Tuple of list of host IPs, ssh user name, ssh key file path,
559
+ optional docker container name, optional cluster name.
560
+ """
561
+ from ray.autoscaler._private.commands import _bootstrap_config
562
+
563
+ cli_logger.print(
564
+ f"Retrieving cluster information from ray cluster file: " f"{cluster_config}"
565
+ )
566
+
567
+ cluster_config = os.path.expanduser(cluster_config)
568
+
569
+ config = yaml.safe_load(open(cluster_config).read())
570
+ config = _bootstrap_config(config, no_config_cache=True)
571
+
572
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
573
+ head_nodes = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_HEAD})
574
+ worker_nodes = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_WORKER})
575
+
576
+ hosts = [provider.external_ip(node) for node in head_nodes + worker_nodes]
577
+ ssh_user = config["auth"]["ssh_user"]
578
+ ssh_key = config["auth"]["ssh_private_key"]
579
+
580
+ docker = None
581
+ docker_config = config.get("docker", None)
582
+ if docker_config:
583
+ docker = docker_config.get("container_name", None)
584
+
585
+ cluster_name = config.get("cluster_name", None)
586
+
587
+ return hosts, ssh_user, ssh_key, docker, cluster_name
588
+
589
+
590
+ def _info_from_params(
591
+ cluster: Optional[str] = None,
592
+ host: Optional[str] = None,
593
+ ssh_user: Optional[str] = None,
594
+ ssh_key: Optional[str] = None,
595
+ docker: Optional[str] = None,
596
+ ):
597
+ """Parse command line arguments.
598
+
599
+ Note: This returns a list of hosts, not a comma separated string!
600
+ """
601
+ if not host and not cluster:
602
+ bootstrap_config = os.path.expanduser("~/ray_bootstrap_config.yaml")
603
+ if os.path.exists(bootstrap_config):
604
+ cluster = bootstrap_config
605
+ cli_logger.warning(
606
+ f"Detected cluster config file at {cluster}. "
607
+ f"If this is incorrect, specify with "
608
+ f"`ray cluster-dump <config>`"
609
+ )
610
+ elif cluster:
611
+ cluster = os.path.expanduser(cluster)
612
+
613
+ cluster_name = None
614
+
615
+ if cluster:
616
+ h, u, k, d, cluster_name = get_info_from_ray_cluster_config(cluster)
617
+
618
+ ssh_user = ssh_user or u
619
+ ssh_key = ssh_key or k
620
+ docker = docker or d
621
+ hosts = host.split(",") if host else h
622
+
623
+ if not hosts:
624
+ raise LocalCommandFailed(
625
+ f"Invalid cluster file or cluster has no running nodes: " f"{cluster}"
626
+ )
627
+ elif host:
628
+ hosts = host.split(",")
629
+ else:
630
+ raise LocalCommandFailed(
631
+ "You need to either specify a `<cluster_config>` or `--host`."
632
+ )
633
+
634
+ if not ssh_user:
635
+ ssh_user = DEFAULT_SSH_USER
636
+ cli_logger.warning(
637
+ f"Using default SSH user `{ssh_user}`. "
638
+ f"If this is incorrect, specify with `--ssh-user <user>`"
639
+ )
640
+
641
+ if not ssh_key:
642
+ for cand_key in DEFAULT_SSH_KEYS:
643
+ cand_key_file = os.path.expanduser(cand_key)
644
+ if os.path.exists(cand_key_file):
645
+ ssh_key = cand_key_file
646
+ cli_logger.warning(
647
+ f"Auto detected SSH key file: {ssh_key}. "
648
+ f"If this is incorrect, specify with `--ssh-key <key>`"
649
+ )
650
+ break
651
+
652
+ return cluster, hosts, ssh_user, ssh_key, docker, cluster_name
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/commands.py ADDED
@@ -0,0 +1,1632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import datetime
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ import random
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from concurrent.futures import ThreadPoolExecutor
14
+ from types import ModuleType
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import click
18
+ import yaml
19
+
20
+ import ray
21
+ from ray._private.usage import usage_lib
22
+ from ray.autoscaler._private import subprocess_output_util as cmd_output_util
23
+ from ray.autoscaler._private.autoscaler import AutoscalerSummary
24
+ from ray.autoscaler._private.cli_logger import cf, cli_logger
25
+ from ray.autoscaler._private.cluster_dump import (
26
+ Archive,
27
+ GetParameters,
28
+ Node,
29
+ _info_from_params,
30
+ create_archive_for_local_and_remote_nodes,
31
+ create_archive_for_remote_nodes,
32
+ get_all_local_data,
33
+ )
34
+ from ray.autoscaler._private.command_runner import (
35
+ set_rsync_silent,
36
+ set_using_login_shells,
37
+ )
38
+ from ray.autoscaler._private.constants import (
39
+ AUTOSCALER_RESOURCE_REQUEST_CHANNEL,
40
+ MAX_PARALLEL_SHUTDOWN_WORKERS,
41
+ )
42
+ from ray.autoscaler._private.event_system import CreateClusterEvent, global_event_system
43
+ from ray.autoscaler._private.log_timer import LogTimer
44
+ from ray.autoscaler._private.node_provider_availability_tracker import (
45
+ NodeAvailabilitySummary,
46
+ )
47
+ from ray.autoscaler._private.providers import (
48
+ _NODE_PROVIDERS,
49
+ _PROVIDER_PRETTY_NAMES,
50
+ _get_node_provider,
51
+ )
52
+ from ray.autoscaler._private.updater import NodeUpdaterThread
53
+ from ray.autoscaler._private.util import (
54
+ LoadMetricsSummary,
55
+ format_info_string,
56
+ hash_launch_conf,
57
+ hash_runtime_conf,
58
+ prepare_config,
59
+ validate_config,
60
+ )
61
+ from ray.autoscaler.node_provider import NodeProvider
62
+ from ray.autoscaler.tags import (
63
+ NODE_KIND_HEAD,
64
+ NODE_KIND_WORKER,
65
+ STATUS_UNINITIALIZED,
66
+ STATUS_UP_TO_DATE,
67
+ TAG_RAY_LAUNCH_CONFIG,
68
+ TAG_RAY_NODE_KIND,
69
+ TAG_RAY_NODE_NAME,
70
+ TAG_RAY_NODE_STATUS,
71
+ TAG_RAY_USER_NODE_TYPE,
72
+ )
73
+ from ray.experimental.internal_kv import _internal_kv_put, internal_kv_get_gcs_client
74
+ from ray.util.debug import log_once
75
+
76
+ try: # py3
77
+ from shlex import quote
78
+ except ImportError: # py2
79
+ from pipes import quote
80
+
81
+
82
+ logger = logging.getLogger(__name__)
83
+
84
+ RUN_ENV_TYPES = ["auto", "host", "docker"]
85
+
86
+ POLL_INTERVAL = 5
87
+
88
+ Port_forward = Union[Tuple[int, int], List[Tuple[int, int]]]
89
+
90
+
91
+ def try_logging_config(config: Dict[str, Any]) -> None:
92
+ if config["provider"]["type"] == "aws":
93
+ from ray.autoscaler._private.aws.config import log_to_cli
94
+
95
+ log_to_cli(config)
96
+
97
+
98
+ def try_get_log_state(provider_config: Dict[str, Any]) -> Optional[dict]:
99
+ if provider_config["type"] == "aws":
100
+ from ray.autoscaler._private.aws.config import get_log_state
101
+
102
+ return get_log_state()
103
+ return None
104
+
105
+
106
+ def try_reload_log_state(provider_config: Dict[str, Any], log_state: dict) -> None:
107
+ if not log_state:
108
+ return
109
+ if provider_config["type"] == "aws":
110
+ from ray.autoscaler._private.aws.config import reload_log_state
111
+
112
+ return reload_log_state(log_state)
113
+
114
+
115
+ def debug_status(
116
+ status, error, verbose: bool = False, address: Optional[str] = None
117
+ ) -> str:
118
+ """
119
+ Return a debug string for the autoscaler.
120
+
121
+ Args:
122
+ status: The autoscaler status string for v1
123
+ error: The autoscaler error string for v1
124
+ verbose: Whether to print verbose information.
125
+ address: The address of the cluster (gcs address).
126
+
127
+ Returns:
128
+ str: A debug string for the cluster's status.
129
+ """
130
+ from ray.autoscaler.v2.utils import is_autoscaler_v2
131
+
132
+ if is_autoscaler_v2():
133
+ from ray.autoscaler.v2.sdk import get_cluster_status
134
+ from ray.autoscaler.v2.utils import ClusterStatusFormatter
135
+
136
+ cluster_status = get_cluster_status(address)
137
+ status = ClusterStatusFormatter.format(cluster_status, verbose=verbose)
138
+ elif status:
139
+ status = status.decode("utf-8")
140
+ status_dict = json.loads(status)
141
+ lm_summary_dict = status_dict.get("load_metrics_report")
142
+ autoscaler_summary_dict = status_dict.get("autoscaler_report")
143
+ timestamp = status_dict.get("time")
144
+ gcs_request_time = status_dict.get("gcs_request_time")
145
+ non_terminated_nodes_time = status_dict.get("non_terminated_nodes_time")
146
+ if lm_summary_dict and autoscaler_summary_dict and timestamp:
147
+ lm_summary = LoadMetricsSummary(**lm_summary_dict)
148
+ node_availability_summary_dict = autoscaler_summary_dict.pop(
149
+ "node_availability_summary", {}
150
+ )
151
+ node_availability_summary = NodeAvailabilitySummary.from_fields(
152
+ **node_availability_summary_dict
153
+ )
154
+ autoscaler_summary = AutoscalerSummary(
155
+ node_availability_summary=node_availability_summary,
156
+ **autoscaler_summary_dict,
157
+ )
158
+ report_time = datetime.datetime.fromtimestamp(timestamp)
159
+ status = format_info_string(
160
+ lm_summary,
161
+ autoscaler_summary,
162
+ time=report_time,
163
+ gcs_request_time=gcs_request_time,
164
+ non_terminated_nodes_time=non_terminated_nodes_time,
165
+ verbose=verbose,
166
+ )
167
+ else:
168
+ status = (
169
+ "No cluster status. It may take a few seconds "
170
+ "for the Ray internal services to start up."
171
+ )
172
+ else:
173
+ status = (
174
+ "No cluster status. It may take a few seconds "
175
+ "for the Ray internal services to start up."
176
+ )
177
+
178
+ if error:
179
+ status += "\n"
180
+ status += error.decode("utf-8")
181
+
182
+ return status
183
+
184
+
185
+ def request_resources(
186
+ num_cpus: Optional[int] = None, bundles: Optional[List[dict]] = None
187
+ ) -> None:
188
+ """Remotely request some CPU or GPU resources from the autoscaler.
189
+
190
+ This function is to be called e.g. on a node before submitting a bunch of
191
+ ray.remote calls to ensure that resources rapidly become available.
192
+
193
+ Args:
194
+ num_cpus: Scale the cluster to ensure this number of CPUs are
195
+ available. This request is persistent until another call to
196
+ request_resources() is made.
197
+ bundles (List[ResourceDict]): Scale the cluster to ensure this set of
198
+ resource shapes can fit. This request is persistent until another
199
+ call to request_resources() is made.
200
+ """
201
+ if not ray.is_initialized():
202
+ raise RuntimeError("Ray is not initialized yet")
203
+ to_request = []
204
+ if num_cpus:
205
+ to_request += [{"CPU": 1}] * num_cpus
206
+ if bundles:
207
+ to_request += bundles
208
+ _internal_kv_put(
209
+ AUTOSCALER_RESOURCE_REQUEST_CHANNEL, json.dumps(to_request), overwrite=True
210
+ )
211
+
212
+ from ray.autoscaler.v2.utils import is_autoscaler_v2
213
+
214
+ if is_autoscaler_v2():
215
+ from ray.autoscaler.v2.sdk import request_cluster_resources
216
+
217
+ gcs_address = internal_kv_get_gcs_client().address
218
+ request_cluster_resources(gcs_address, to_request)
219
+
220
+
221
+ def create_or_update_cluster(
222
+ config_file: str,
223
+ override_min_workers: Optional[int],
224
+ override_max_workers: Optional[int],
225
+ no_restart: bool,
226
+ restart_only: bool,
227
+ yes: bool,
228
+ override_cluster_name: Optional[str] = None,
229
+ no_config_cache: bool = False,
230
+ redirect_command_output: Optional[bool] = False,
231
+ use_login_shells: bool = True,
232
+ no_monitor_on_head: bool = False,
233
+ ) -> Dict[str, Any]:
234
+ """Creates or updates an autoscaling Ray cluster from a config json."""
235
+ # no_monitor_on_head is an internal flag used by the Ray K8s operator.
236
+ # If True, prevents autoscaling config sync to the Ray head during cluster
237
+ # creation. See https://github.com/ray-project/ray/pull/13720.
238
+ set_using_login_shells(use_login_shells)
239
+ if not use_login_shells:
240
+ cmd_output_util.set_allow_interactive(False)
241
+ if redirect_command_output is None:
242
+ # Do not redirect by default.
243
+ cmd_output_util.set_output_redirected(False)
244
+ else:
245
+ cmd_output_util.set_output_redirected(redirect_command_output)
246
+
247
+ def handle_yaml_error(e):
248
+ cli_logger.error("Cluster config invalid")
249
+ cli_logger.newline()
250
+ cli_logger.error("Failed to load YAML file " + cf.bold("{}"), config_file)
251
+ cli_logger.newline()
252
+ with cli_logger.verbatim_error_ctx("PyYAML error:"):
253
+ cli_logger.error(e)
254
+ cli_logger.abort()
255
+
256
+ try:
257
+ config = yaml.safe_load(open(config_file).read())
258
+ except FileNotFoundError:
259
+ cli_logger.abort(
260
+ "Provided cluster configuration file ({}) does not exist",
261
+ cf.bold(config_file),
262
+ )
263
+ except yaml.parser.ParserError as e:
264
+ handle_yaml_error(e)
265
+ raise
266
+ except yaml.scanner.ScannerError as e:
267
+ handle_yaml_error(e)
268
+ raise
269
+ global_event_system.execute_callback(
270
+ CreateClusterEvent.up_started, {"cluster_config": config}
271
+ )
272
+
273
+ # todo: validate file_mounts, ssh keys, etc.
274
+
275
+ importer = _NODE_PROVIDERS.get(config["provider"]["type"])
276
+ if not importer:
277
+ cli_logger.abort(
278
+ "Unknown provider type " + cf.bold("{}") + "\n"
279
+ "Available providers are: {}",
280
+ config["provider"]["type"],
281
+ cli_logger.render_list(
282
+ [k for k in _NODE_PROVIDERS.keys() if _NODE_PROVIDERS[k] is not None]
283
+ ),
284
+ )
285
+
286
+ printed_overrides = False
287
+
288
+ def handle_cli_override(key, override):
289
+ if override is not None:
290
+ if key in config:
291
+ nonlocal printed_overrides
292
+ printed_overrides = True
293
+ cli_logger.warning(
294
+ "`{}` override provided on the command line.\n"
295
+ " Using "
296
+ + cf.bold("{}")
297
+ + cf.dimmed(" [configuration file has " + cf.bold("{}") + "]"),
298
+ key,
299
+ override,
300
+ config[key],
301
+ )
302
+ config[key] = override
303
+
304
+ handle_cli_override("min_workers", override_min_workers)
305
+ handle_cli_override("max_workers", override_max_workers)
306
+ handle_cli_override("cluster_name", override_cluster_name)
307
+
308
+ if printed_overrides:
309
+ cli_logger.newline()
310
+
311
+ cli_logger.labeled_value("Cluster", config["cluster_name"])
312
+
313
+ cli_logger.newline()
314
+ config = _bootstrap_config(config, no_config_cache=no_config_cache)
315
+
316
+ try_logging_config(config)
317
+ get_or_create_head_node(
318
+ config,
319
+ config_file,
320
+ no_restart,
321
+ restart_only,
322
+ yes,
323
+ override_cluster_name,
324
+ no_monitor_on_head,
325
+ )
326
+ return config
327
+
328
+
329
+ CONFIG_CACHE_VERSION = 1
330
+
331
+
332
+ def _bootstrap_config(
333
+ config: Dict[str, Any], no_config_cache: bool = False
334
+ ) -> Dict[str, Any]:
335
+ config = prepare_config(config)
336
+ # NOTE: multi-node-type autoscaler is guaranteed to be in use after this.
337
+
338
+ hasher = hashlib.sha1()
339
+ hasher.update(json.dumps([config], sort_keys=True).encode("utf-8"))
340
+ cache_key = os.path.join(
341
+ tempfile.gettempdir(), "ray-config-{}".format(hasher.hexdigest())
342
+ )
343
+
344
+ if os.path.exists(cache_key) and not no_config_cache:
345
+ config_cache = json.loads(open(cache_key).read())
346
+ if config_cache.get("_version", -1) == CONFIG_CACHE_VERSION:
347
+ # todo: is it fine to re-resolve? afaik it should be.
348
+ # we can have migrations otherwise or something
349
+ # but this seems overcomplicated given that resolving is
350
+ # relatively cheap
351
+ try_reload_log_state(
352
+ config_cache["config"]["provider"],
353
+ config_cache.get("provider_log_info"),
354
+ )
355
+
356
+ if log_once("_printed_cached_config_warning"):
357
+ cli_logger.verbose_warning(
358
+ "Loaded cached provider configuration from " + cf.bold("{}"),
359
+ cache_key,
360
+ )
361
+ if cli_logger.verbosity == 0:
362
+ cli_logger.warning("Loaded cached provider configuration")
363
+ cli_logger.warning(
364
+ "If you experience issues with "
365
+ "the cloud provider, try re-running "
366
+ "the command with {}.",
367
+ cf.bold("--no-config-cache"),
368
+ )
369
+
370
+ return config_cache["config"]
371
+ else:
372
+ cli_logger.warning(
373
+ "Found cached cluster config "
374
+ "but the version " + cf.bold("{}") + " "
375
+ "(expected " + cf.bold("{}") + ") does not match.\n"
376
+ "This is normal if cluster launcher was updated.\n"
377
+ "Config will be re-resolved.",
378
+ config_cache.get("_version", "none"),
379
+ CONFIG_CACHE_VERSION,
380
+ )
381
+
382
+ importer = _NODE_PROVIDERS.get(config["provider"]["type"])
383
+ if not importer:
384
+ raise NotImplementedError("Unsupported provider {}".format(config["provider"]))
385
+
386
+ provider_cls = importer(config["provider"])
387
+
388
+ cli_logger.print(
389
+ "Checking {} environment settings",
390
+ _PROVIDER_PRETTY_NAMES.get(config["provider"]["type"]),
391
+ )
392
+ try:
393
+ config = provider_cls.fillout_available_node_types_resources(config)
394
+ except Exception as exc:
395
+ if cli_logger.verbosity > 2:
396
+ logger.exception("Failed to autodetect node resources.")
397
+ else:
398
+ cli_logger.warning(
399
+ f"Failed to autodetect node resources: {str(exc)}. "
400
+ "You can see full stack trace with higher verbosity."
401
+ )
402
+
403
+ try:
404
+ # NOTE: if `resources` field is missing, validate_config for providers
405
+ # other than AWS and Kubernetes will fail (the schema error will ask
406
+ # the user to manually fill the resources) as we currently support
407
+ # autofilling resources for AWS and Kubernetes only.
408
+ validate_config(config)
409
+ except (ModuleNotFoundError, ImportError):
410
+ cli_logger.abort(
411
+ "Not all Ray autoscaler dependencies were found. "
412
+ "In Ray 1.4+, the Ray CLI, autoscaler, and dashboard will "
413
+ 'only be usable via `pip install "ray[default]"`. Please '
414
+ "update your install command."
415
+ )
416
+ resolved_config = provider_cls.bootstrap_config(config)
417
+
418
+ if not no_config_cache:
419
+ with open(cache_key, "w") as f:
420
+ config_cache = {
421
+ "_version": CONFIG_CACHE_VERSION,
422
+ "provider_log_info": try_get_log_state(resolved_config["provider"]),
423
+ "config": resolved_config,
424
+ }
425
+ f.write(json.dumps(config_cache))
426
+ return resolved_config
427
+
428
+
429
+ def teardown_cluster(
430
+ config_file: str,
431
+ yes: bool,
432
+ workers_only: bool,
433
+ override_cluster_name: Optional[str],
434
+ keep_min_workers: bool,
435
+ ) -> None:
436
+ """Destroys all nodes of a Ray cluster described by a config json."""
437
+ config = yaml.safe_load(open(config_file).read())
438
+ if override_cluster_name is not None:
439
+ config["cluster_name"] = override_cluster_name
440
+
441
+ config = _bootstrap_config(config)
442
+
443
+ cli_logger.confirm(yes, "Destroying cluster.", _abort=True)
444
+
445
+ if not workers_only:
446
+ try:
447
+ exec_cluster(
448
+ config_file,
449
+ cmd="ray stop",
450
+ run_env="auto",
451
+ screen=False,
452
+ tmux=False,
453
+ stop=False,
454
+ start=False,
455
+ override_cluster_name=override_cluster_name,
456
+ port_forward=None,
457
+ with_output=False,
458
+ )
459
+ except Exception as e:
460
+ # todo: add better exception info
461
+ cli_logger.verbose_error("{}", str(e))
462
+ cli_logger.warning(
463
+ "Exception occurred when stopping the cluster Ray runtime "
464
+ "(use -v to dump teardown exceptions)."
465
+ )
466
+ cli_logger.warning(
467
+ "Ignoring the exception and "
468
+ "attempting to shut down the cluster nodes anyway."
469
+ )
470
+
471
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
472
+
473
+ def remaining_nodes():
474
+ workers = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_WORKER})
475
+
476
+ if keep_min_workers:
477
+ min_workers = config.get("min_workers", 0)
478
+ cli_logger.print(
479
+ "{} random worker nodes will not be shut down. "
480
+ + cf.dimmed("(due to {})"),
481
+ cf.bold(min_workers),
482
+ cf.bold("--keep-min-workers"),
483
+ )
484
+
485
+ workers = random.sample(workers, len(workers) - min_workers)
486
+
487
+ # todo: it's weird to kill the head node but not all workers
488
+ if workers_only:
489
+ cli_logger.print(
490
+ "The head node will not be shut down. " + cf.dimmed("(due to {})"),
491
+ cf.bold("--workers-only"),
492
+ )
493
+
494
+ return workers
495
+
496
+ head = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_HEAD})
497
+
498
+ return head + workers
499
+
500
+ def run_docker_stop(node, container_name):
501
+ try:
502
+ updater = NodeUpdaterThread(
503
+ node_id=node,
504
+ provider_config=config["provider"],
505
+ provider=provider,
506
+ auth_config=config["auth"],
507
+ cluster_name=config["cluster_name"],
508
+ file_mounts=config["file_mounts"],
509
+ initialization_commands=[],
510
+ setup_commands=[],
511
+ ray_start_commands=[],
512
+ runtime_hash="",
513
+ file_mounts_contents_hash="",
514
+ is_head_node=False,
515
+ docker_config=config.get("docker"),
516
+ )
517
+
518
+ _exec(
519
+ updater,
520
+ f"docker stop {container_name}",
521
+ with_output=False,
522
+ run_env="host",
523
+ )
524
+ except Exception:
525
+ cli_logger.warning(f"Docker stop failed on {node}")
526
+
527
+ # Loop here to check that both the head and worker nodes are actually
528
+ # really gone
529
+ A = remaining_nodes()
530
+
531
+ container_name = config.get("docker", {}).get("container_name")
532
+ if container_name:
533
+ # This is to ensure that the parallel SSH calls below do not mess with
534
+ # the users terminal.
535
+ output_redir = cmd_output_util.is_output_redirected()
536
+ cmd_output_util.set_output_redirected(True)
537
+ allow_interactive = cmd_output_util.does_allow_interactive()
538
+ cmd_output_util.set_allow_interactive(False)
539
+
540
+ with ThreadPoolExecutor(max_workers=MAX_PARALLEL_SHUTDOWN_WORKERS) as executor:
541
+ for node in A:
542
+ executor.submit(
543
+ run_docker_stop, node=node, container_name=container_name
544
+ )
545
+ cmd_output_util.set_output_redirected(output_redir)
546
+ cmd_output_util.set_allow_interactive(allow_interactive)
547
+ with LogTimer("teardown_cluster: done."):
548
+ while A:
549
+ provider.terminate_nodes(A)
550
+
551
+ cli_logger.print(
552
+ "Requested {} nodes to shut down.",
553
+ cf.bold(len(A)),
554
+ _tags=dict(interval="1s"),
555
+ )
556
+
557
+ time.sleep(POLL_INTERVAL) # todo: interval should be a variable
558
+ A = remaining_nodes()
559
+ cli_logger.print(
560
+ "{} nodes remaining after {} second(s).", cf.bold(len(A)), POLL_INTERVAL
561
+ )
562
+ cli_logger.success("No nodes remaining.")
563
+
564
+
565
+ def kill_node(
566
+ config_file: str, yes: bool, hard: bool, override_cluster_name: Optional[str]
567
+ ) -> Optional[str]:
568
+ """Kills a random Raylet worker."""
569
+
570
+ config = yaml.safe_load(open(config_file).read())
571
+ if override_cluster_name is not None:
572
+ config["cluster_name"] = override_cluster_name
573
+ config = _bootstrap_config(config)
574
+
575
+ cli_logger.confirm(yes, "A random node will be killed.")
576
+
577
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
578
+ nodes = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_WORKER})
579
+ if not nodes:
580
+ cli_logger.print("No worker nodes detected.")
581
+ return None
582
+ node = random.choice(nodes)
583
+ cli_logger.print("Shutdown " + cf.bold("{}"), node)
584
+ if hard:
585
+ provider.terminate_node(node)
586
+ else:
587
+ updater = NodeUpdaterThread(
588
+ node_id=node,
589
+ provider_config=config["provider"],
590
+ provider=provider,
591
+ auth_config=config["auth"],
592
+ cluster_name=config["cluster_name"],
593
+ file_mounts=config["file_mounts"],
594
+ initialization_commands=[],
595
+ setup_commands=[],
596
+ ray_start_commands=[],
597
+ runtime_hash="",
598
+ file_mounts_contents_hash="",
599
+ is_head_node=False,
600
+ docker_config=config.get("docker"),
601
+ )
602
+
603
+ _exec(updater, "ray stop", False, False)
604
+
605
+ time.sleep(POLL_INTERVAL)
606
+
607
+ if config.get("provider", {}).get("use_internal_ips", False):
608
+ node_ip = provider.internal_ip(node)
609
+ else:
610
+ node_ip = provider.external_ip(node)
611
+
612
+ return node_ip
613
+
614
+
615
+ def monitor_cluster(
616
+ cluster_config_file: str, num_lines: int, override_cluster_name: Optional[str]
617
+ ) -> None:
618
+ """Tails the autoscaler logs of a Ray cluster."""
619
+ cmd = f"tail -n {num_lines} -f /tmp/ray/session_latest/logs/monitor*"
620
+ exec_cluster(
621
+ cluster_config_file,
622
+ cmd=cmd,
623
+ run_env="auto",
624
+ screen=False,
625
+ tmux=False,
626
+ stop=False,
627
+ start=False,
628
+ override_cluster_name=override_cluster_name,
629
+ port_forward=None,
630
+ )
631
+
632
+
633
+ def warn_about_bad_start_command(
634
+ start_commands: List[str], no_monitor_on_head: bool = False
635
+ ) -> None:
636
+ ray_start_cmd = list(filter(lambda x: "ray start" in x, start_commands))
637
+ if len(ray_start_cmd) == 0:
638
+ cli_logger.warning(
639
+ "Ray runtime will not be started because `{}` is not in `{}`.",
640
+ cf.bold("ray start"),
641
+ cf.bold("head_start_ray_commands"),
642
+ )
643
+
644
+ autoscaling_config_in_ray_start_cmd = any(
645
+ "autoscaling-config" in x for x in ray_start_cmd
646
+ )
647
+ if not (autoscaling_config_in_ray_start_cmd or no_monitor_on_head):
648
+ cli_logger.warning(
649
+ "The head node will not launch any workers because "
650
+ "`{}` does not have `{}` set.\n"
651
+ "Potential fix: add `{}` to the `{}` command under `{}`.",
652
+ cf.bold("ray start"),
653
+ cf.bold("--autoscaling-config"),
654
+ cf.bold("--autoscaling-config=~/ray_bootstrap_config.yaml"),
655
+ cf.bold("ray start"),
656
+ cf.bold("head_start_ray_commands"),
657
+ )
658
+
659
+
660
+ def get_or_create_head_node(
661
+ config: Dict[str, Any],
662
+ printable_config_file: str,
663
+ no_restart: bool,
664
+ restart_only: bool,
665
+ yes: bool,
666
+ override_cluster_name: Optional[str],
667
+ no_monitor_on_head: bool = False,
668
+ _provider: Optional[NodeProvider] = None,
669
+ _runner: ModuleType = subprocess,
670
+ ) -> None:
671
+ """Create the cluster head node, which in turn creates the workers."""
672
+ global_event_system.execute_callback(CreateClusterEvent.cluster_booting_started)
673
+ provider = _provider or _get_node_provider(
674
+ config["provider"], config["cluster_name"]
675
+ )
676
+
677
+ config = copy.deepcopy(config)
678
+ head_node_tags = {
679
+ TAG_RAY_NODE_KIND: NODE_KIND_HEAD,
680
+ }
681
+ nodes = provider.non_terminated_nodes(head_node_tags)
682
+ if len(nodes) > 0:
683
+ head_node = nodes[0]
684
+ else:
685
+ head_node = None
686
+
687
+ if not head_node:
688
+ cli_logger.confirm(
689
+ yes, "No head node found. Launching a new cluster.", _abort=True
690
+ )
691
+ cli_logger.newline()
692
+ usage_lib.show_usage_stats_prompt(cli=True)
693
+
694
+ if head_node:
695
+ if restart_only:
696
+ cli_logger.confirm(
697
+ yes,
698
+ "Updating cluster configuration and "
699
+ "restarting the cluster Ray runtime. "
700
+ "Setup commands will not be run due to `{}`.\n",
701
+ cf.bold("--restart-only"),
702
+ _abort=True,
703
+ )
704
+ cli_logger.newline()
705
+ usage_lib.show_usage_stats_prompt(cli=True)
706
+ elif no_restart:
707
+ cli_logger.print(
708
+ "Cluster Ray runtime will not be restarted due to `{}`.",
709
+ cf.bold("--no-restart"),
710
+ )
711
+ cli_logger.confirm(
712
+ yes,
713
+ "Updating cluster configuration and running setup commands.",
714
+ _abort=True,
715
+ )
716
+ else:
717
+ cli_logger.print("Updating cluster configuration and running full setup.")
718
+ cli_logger.confirm(
719
+ yes, cf.bold("Cluster Ray runtime will be restarted."), _abort=True
720
+ )
721
+ cli_logger.newline()
722
+ usage_lib.show_usage_stats_prompt(cli=True)
723
+
724
+ cli_logger.newline()
725
+ # TODO(ekl) this logic is duplicated in node_launcher.py (keep in sync)
726
+ head_node_config = copy.deepcopy(config.get("head_node", {}))
727
+ # The above `head_node` field is deprecated in favor of per-node-type
728
+ # node_configs. We allow it for backwards-compatibility.
729
+ head_node_resources = None
730
+ head_node_labels = None
731
+ head_node_type = config.get("head_node_type")
732
+ if head_node_type:
733
+ head_node_tags[TAG_RAY_USER_NODE_TYPE] = head_node_type
734
+ head_config = config["available_node_types"][head_node_type]
735
+ head_node_config.update(head_config["node_config"])
736
+
737
+ # Not necessary to keep in sync with node_launcher.py
738
+ # Keep in sync with autoscaler.py _node_resources
739
+ head_node_resources = head_config.get("resources")
740
+ head_node_labels = head_config.get("labels")
741
+
742
+ launch_hash = hash_launch_conf(head_node_config, config["auth"])
743
+ creating_new_head = _should_create_new_head(
744
+ head_node, launch_hash, head_node_type, provider
745
+ )
746
+ if creating_new_head:
747
+ with cli_logger.group("Acquiring an up-to-date head node"):
748
+ global_event_system.execute_callback(
749
+ CreateClusterEvent.acquiring_new_head_node
750
+ )
751
+ if head_node is not None:
752
+ cli_logger.confirm(yes, "Relaunching the head node.", _abort=True)
753
+
754
+ provider.terminate_node(head_node)
755
+ cli_logger.print("Terminated head node {}", head_node)
756
+
757
+ head_node_tags[TAG_RAY_LAUNCH_CONFIG] = launch_hash
758
+ head_node_tags[TAG_RAY_NODE_NAME] = "ray-{}-head".format(
759
+ config["cluster_name"]
760
+ )
761
+ head_node_tags[TAG_RAY_NODE_STATUS] = STATUS_UNINITIALIZED
762
+ provider.create_node(head_node_config, head_node_tags, 1)
763
+ cli_logger.print("Launched a new head node")
764
+
765
+ start = time.time()
766
+ head_node = None
767
+ with cli_logger.group("Fetching the new head node"):
768
+ while True:
769
+ if time.time() - start > 50:
770
+ cli_logger.abort(
771
+ "Head node fetch timed out. Failed to create head node."
772
+ )
773
+ nodes = provider.non_terminated_nodes(head_node_tags)
774
+ if len(nodes) == 1:
775
+ head_node = nodes[0]
776
+ break
777
+ time.sleep(POLL_INTERVAL)
778
+ cli_logger.newline()
779
+
780
+ global_event_system.execute_callback(CreateClusterEvent.head_node_acquired)
781
+
782
+ with cli_logger.group(
783
+ "Setting up head node",
784
+ _numbered=("<>", 1, 1),
785
+ # cf.bold(provider.node_tags(head_node)[TAG_RAY_NODE_NAME]),
786
+ _tags=dict(),
787
+ ): # add id, ARN to tags?
788
+ # TODO(ekl) right now we always update the head node even if the
789
+ # hash matches.
790
+ # We could prompt the user for what they want to do here.
791
+ # No need to pass in cluster_sync_files because we use this
792
+ # hash to set up the head node
793
+ (runtime_hash, file_mounts_contents_hash) = hash_runtime_conf(
794
+ config["file_mounts"], None, config
795
+ )
796
+
797
+ if not no_monitor_on_head:
798
+ # Return remote_config_file to avoid prematurely closing it.
799
+ config, remote_config_file = _set_up_config_for_head_node(
800
+ config, provider, no_restart
801
+ )
802
+ cli_logger.print("Prepared bootstrap config")
803
+
804
+ if restart_only:
805
+ # Docker may re-launch nodes, requiring setup
806
+ # commands to be rerun.
807
+ if config.get("docker", {}).get("container_name"):
808
+ setup_commands = config["head_setup_commands"]
809
+ else:
810
+ setup_commands = []
811
+ ray_start_commands = config["head_start_ray_commands"]
812
+ # If user passed in --no-restart and we're not creating a new head,
813
+ # omit start commands.
814
+ elif no_restart and not creating_new_head:
815
+ setup_commands = config["head_setup_commands"]
816
+ ray_start_commands = []
817
+ else:
818
+ setup_commands = config["head_setup_commands"]
819
+ ray_start_commands = config["head_start_ray_commands"]
820
+
821
+ if not no_restart:
822
+ warn_about_bad_start_command(ray_start_commands, no_monitor_on_head)
823
+
824
+ updater = NodeUpdaterThread(
825
+ node_id=head_node,
826
+ provider_config=config["provider"],
827
+ provider=provider,
828
+ auth_config=config["auth"],
829
+ cluster_name=config["cluster_name"],
830
+ file_mounts=config["file_mounts"],
831
+ initialization_commands=config["initialization_commands"],
832
+ setup_commands=setup_commands,
833
+ ray_start_commands=ray_start_commands,
834
+ process_runner=_runner,
835
+ runtime_hash=runtime_hash,
836
+ file_mounts_contents_hash=file_mounts_contents_hash,
837
+ is_head_node=True,
838
+ node_resources=head_node_resources,
839
+ node_labels=head_node_labels,
840
+ rsync_options={
841
+ "rsync_exclude": config.get("rsync_exclude"),
842
+ "rsync_filter": config.get("rsync_filter"),
843
+ },
844
+ docker_config=config.get("docker"),
845
+ restart_only=restart_only,
846
+ )
847
+ updater.start()
848
+ updater.join()
849
+
850
+ # Refresh the node cache so we see the external ip if available
851
+ provider.non_terminated_nodes(head_node_tags)
852
+
853
+ if updater.exitcode != 0:
854
+ # todo: this does not follow the mockup and is not good enough
855
+ cli_logger.abort("Failed to setup head node.")
856
+ sys.exit(1)
857
+
858
+ global_event_system.execute_callback(
859
+ CreateClusterEvent.cluster_booting_completed,
860
+ {
861
+ "head_node_id": head_node,
862
+ },
863
+ )
864
+
865
+ monitor_str = "tail -n 100 -f /tmp/ray/session_latest/logs/monitor*"
866
+ if override_cluster_name:
867
+ modifiers = " --cluster-name={}".format(quote(override_cluster_name))
868
+ else:
869
+ modifiers = ""
870
+
871
+ cli_logger.newline()
872
+ with cli_logger.group("Useful commands:"):
873
+ printable_config_file = os.path.abspath(printable_config_file)
874
+
875
+ cli_logger.print("To terminate the cluster:")
876
+ cli_logger.print(cf.bold(f" ray down {printable_config_file}{modifiers}"))
877
+ cli_logger.newline()
878
+
879
+ cli_logger.print("To retrieve the IP address of the cluster head:")
880
+ cli_logger.print(
881
+ cf.bold(f" ray get-head-ip {printable_config_file}{modifiers}")
882
+ )
883
+ cli_logger.newline()
884
+
885
+ cli_logger.print(
886
+ "To port-forward the cluster's Ray Dashboard to the local machine:"
887
+ )
888
+ cli_logger.print(cf.bold(f" ray dashboard {printable_config_file}{modifiers}"))
889
+ cli_logger.newline()
890
+
891
+ cli_logger.print(
892
+ "To submit a job to the cluster, port-forward the "
893
+ "Ray Dashboard in another terminal and run:"
894
+ )
895
+ cli_logger.print(
896
+ cf.bold(
897
+ " ray job submit --address http://localhost:<dashboard-port> "
898
+ "--working-dir . -- python my_script.py"
899
+ )
900
+ )
901
+ cli_logger.newline()
902
+
903
+ cli_logger.print("To connect to a terminal on the cluster head for debugging:")
904
+ cli_logger.print(cf.bold(f" ray attach {printable_config_file}{modifiers}"))
905
+ cli_logger.newline()
906
+
907
+ cli_logger.print("To monitor autoscaling:")
908
+ cli_logger.print(
909
+ cf.bold(
910
+ f" ray exec {printable_config_file}{modifiers} {quote(monitor_str)}"
911
+ )
912
+ )
913
+ cli_logger.newline()
914
+
915
+
916
+ def _should_create_new_head(
917
+ head_node_id: Optional[str],
918
+ new_launch_hash: str,
919
+ new_head_node_type: str,
920
+ provider: NodeProvider,
921
+ ) -> bool:
922
+ """Decides whether a new head node needs to be created.
923
+
924
+ We need a new head if at least one of the following holds:
925
+ (a) There isn't an existing head node
926
+ (b) The user-submitted head node_config differs from the existing head
927
+ node's node_config.
928
+ (c) The user-submitted head node_type key differs from the existing head
929
+ node's node_type.
930
+
931
+ Args:
932
+ head_node_id (Optional[str]): head node id if a head exists, else None
933
+ new_launch_hash: hash of current user-submitted head config
934
+ new_head_node_type: current user-submitted head node-type key
935
+
936
+ Returns:
937
+ bool: True if a new Ray head node should be launched, False otherwise
938
+ """
939
+ if not head_node_id:
940
+ # No head node exists, need to create it.
941
+ return True
942
+
943
+ # Pull existing head's data.
944
+ head_tags = provider.node_tags(head_node_id)
945
+ current_launch_hash = head_tags.get(TAG_RAY_LAUNCH_CONFIG)
946
+ current_head_type = head_tags.get(TAG_RAY_USER_NODE_TYPE)
947
+
948
+ # Compare to current head
949
+ hashes_mismatch = new_launch_hash != current_launch_hash
950
+ types_mismatch = new_head_node_type != current_head_type
951
+
952
+ new_head_required = hashes_mismatch or types_mismatch
953
+
954
+ # Warn user
955
+ if new_head_required:
956
+ with cli_logger.group(
957
+ "Currently running head node is out-of-date with cluster configuration"
958
+ ):
959
+ if hashes_mismatch:
960
+ cli_logger.print(
961
+ "Current hash is {}, expected {}",
962
+ cf.bold(current_launch_hash),
963
+ cf.bold(new_launch_hash),
964
+ )
965
+
966
+ if types_mismatch:
967
+ cli_logger.print(
968
+ "Current head node type is {}, expected {}",
969
+ cf.bold(current_head_type),
970
+ cf.bold(new_head_node_type),
971
+ )
972
+
973
+ return new_head_required
974
+
975
+
976
+ def _set_up_config_for_head_node(
977
+ config: Dict[str, Any], provider: NodeProvider, no_restart: bool
978
+ ) -> Tuple[Dict[str, Any], Any]:
979
+ """Prepares autoscaling config and, if needed, ssh key, to be mounted onto
980
+ the Ray head node for use by the autoscaler.
981
+
982
+ Returns the modified config and the temporary config file that will be
983
+ mounted onto the head node.
984
+ """
985
+ # Rewrite the auth config so that the head
986
+ # node can update the workers
987
+ remote_config = copy.deepcopy(config)
988
+
989
+ # drop proxy options if they exist, otherwise
990
+ # head node won't be able to connect to workers
991
+ remote_config["auth"].pop("ssh_proxy_command", None)
992
+
993
+ # Drop the head_node field if it was introduced. It is technically not a
994
+ # valid field in the config, but it may have been introduced after
995
+ # validation (see _bootstrap_config() call to
996
+ # provider_cls.bootstrap_config(config)). The head node will never try to
997
+ # launch a head node so it doesn't need these defaults.
998
+ remote_config.pop("head_node", None)
999
+
1000
+ if "ssh_private_key" in config["auth"]:
1001
+ remote_key_path = "~/ray_bootstrap_key.pem"
1002
+ remote_config["auth"]["ssh_private_key"] = remote_key_path
1003
+
1004
+ # Adjust for new file locations
1005
+ new_mounts = {}
1006
+ for remote_path in config["file_mounts"]:
1007
+ new_mounts[remote_path] = remote_path
1008
+ remote_config["file_mounts"] = new_mounts
1009
+ remote_config["no_restart"] = no_restart
1010
+
1011
+ remote_config = provider.prepare_for_head_node(remote_config)
1012
+
1013
+ # Now inject the rewritten config and SSH key into the head node
1014
+ remote_config_file = tempfile.NamedTemporaryFile("w", prefix="ray-bootstrap-")
1015
+ remote_config_file.write(json.dumps(remote_config))
1016
+ remote_config_file.flush()
1017
+ config["file_mounts"].update(
1018
+ {"~/ray_bootstrap_config.yaml": remote_config_file.name}
1019
+ )
1020
+
1021
+ if "ssh_private_key" in config["auth"]:
1022
+ config["file_mounts"].update(
1023
+ {
1024
+ remote_key_path: config["auth"]["ssh_private_key"],
1025
+ }
1026
+ )
1027
+
1028
+ return config, remote_config_file
1029
+
1030
+
1031
+ def attach_cluster(
1032
+ config_file: str,
1033
+ start: bool,
1034
+ use_screen: bool,
1035
+ use_tmux: bool,
1036
+ override_cluster_name: Optional[str],
1037
+ no_config_cache: bool = False,
1038
+ new: bool = False,
1039
+ port_forward: Optional[Port_forward] = None,
1040
+ ) -> None:
1041
+ """Attaches to a screen for the specified cluster.
1042
+
1043
+ Arguments:
1044
+ config_file: path to the cluster yaml
1045
+ start: whether to start the cluster if it isn't up
1046
+ use_screen: whether to use screen as multiplexer
1047
+ use_tmux: whether to use tmux as multiplexer
1048
+ override_cluster_name: set the name of the cluster
1049
+ new: whether to force a new screen
1050
+ port_forward ( (int,int) or list[(int,int)] ): port(s) to forward
1051
+ """
1052
+
1053
+ if use_tmux:
1054
+ if new:
1055
+ cmd = "tmux new"
1056
+ else:
1057
+ cmd = "tmux attach || tmux new"
1058
+ elif use_screen:
1059
+ if new:
1060
+ cmd = "screen -L"
1061
+ else:
1062
+ cmd = "screen -L -xRR"
1063
+ else:
1064
+ if new:
1065
+ raise ValueError("--new only makes sense if passing --screen or --tmux")
1066
+ cmd = "$SHELL"
1067
+
1068
+ exec_cluster(
1069
+ config_file,
1070
+ cmd=cmd,
1071
+ run_env="auto",
1072
+ screen=False,
1073
+ tmux=False,
1074
+ stop=False,
1075
+ start=start,
1076
+ override_cluster_name=override_cluster_name,
1077
+ no_config_cache=no_config_cache,
1078
+ port_forward=port_forward,
1079
+ _allow_uninitialized_state=True,
1080
+ )
1081
+
1082
+
1083
+ def exec_cluster(
1084
+ config_file: str,
1085
+ *,
1086
+ cmd: Optional[str] = None,
1087
+ run_env: str = "auto",
1088
+ screen: bool = False,
1089
+ tmux: bool = False,
1090
+ stop: bool = False,
1091
+ start: bool = False,
1092
+ override_cluster_name: Optional[str] = None,
1093
+ no_config_cache: bool = False,
1094
+ port_forward: Optional[Port_forward] = None,
1095
+ with_output: bool = False,
1096
+ _allow_uninitialized_state: bool = False,
1097
+ extra_screen_args: Optional[str] = None,
1098
+ ) -> str:
1099
+ """Runs a command on the specified cluster.
1100
+
1101
+ Arguments:
1102
+ config_file: path to the cluster yaml
1103
+ cmd: command to run
1104
+ run_env: whether to run the command on the host or in a container.
1105
+ Select between "auto", "host" and "docker"
1106
+ screen: whether to run in a screen
1107
+ extra_screen_args: optional custom additional args to screen command
1108
+ tmux: whether to run in a tmux session
1109
+ stop: whether to stop the cluster after command run
1110
+ start: whether to start the cluster if it isn't up
1111
+ override_cluster_name: set the name of the cluster
1112
+ port_forward ( (int, int) or list[(int, int)] ): port(s) to forward
1113
+ _allow_uninitialized_state: whether to execute on an uninitialized head
1114
+ node.
1115
+ """
1116
+ assert not (screen and tmux), "Can specify only one of `screen` or `tmux`."
1117
+ assert run_env in RUN_ENV_TYPES, "--run_env must be in {}".format(RUN_ENV_TYPES)
1118
+ # TODO(rliaw): We default this to True to maintain backwards-compat.
1119
+ # In the future we would want to support disabling login-shells
1120
+ # and interactivity.
1121
+ cmd_output_util.set_allow_interactive(True)
1122
+
1123
+ config = yaml.safe_load(open(config_file).read())
1124
+ if override_cluster_name is not None:
1125
+ config["cluster_name"] = override_cluster_name
1126
+ config = _bootstrap_config(config, no_config_cache=no_config_cache)
1127
+
1128
+ head_node = _get_running_head_node(
1129
+ config,
1130
+ config_file,
1131
+ override_cluster_name,
1132
+ create_if_needed=start,
1133
+ _allow_uninitialized_state=_allow_uninitialized_state,
1134
+ )
1135
+
1136
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
1137
+ updater = NodeUpdaterThread(
1138
+ node_id=head_node,
1139
+ provider_config=config["provider"],
1140
+ provider=provider,
1141
+ auth_config=config["auth"],
1142
+ cluster_name=config["cluster_name"],
1143
+ file_mounts=config["file_mounts"],
1144
+ initialization_commands=[],
1145
+ setup_commands=[],
1146
+ ray_start_commands=[],
1147
+ runtime_hash="",
1148
+ file_mounts_contents_hash="",
1149
+ is_head_node=True,
1150
+ rsync_options={
1151
+ "rsync_exclude": config.get("rsync_exclude"),
1152
+ "rsync_filter": config.get("rsync_filter"),
1153
+ },
1154
+ docker_config=config.get("docker"),
1155
+ )
1156
+ shutdown_after_run = False
1157
+ if cmd and stop:
1158
+ cmd = "; ".join(
1159
+ [
1160
+ cmd,
1161
+ "ray stop",
1162
+ "ray teardown ~/ray_bootstrap_config.yaml --yes --workers-only",
1163
+ ]
1164
+ )
1165
+ shutdown_after_run = True
1166
+
1167
+ result = _exec(
1168
+ updater,
1169
+ cmd,
1170
+ screen,
1171
+ tmux,
1172
+ port_forward=port_forward,
1173
+ with_output=with_output,
1174
+ run_env=run_env,
1175
+ shutdown_after_run=shutdown_after_run,
1176
+ extra_screen_args=extra_screen_args,
1177
+ )
1178
+ if tmux or screen:
1179
+ attach_command_parts = ["ray attach", config_file]
1180
+ if override_cluster_name is not None:
1181
+ attach_command_parts.append(
1182
+ "--cluster-name={}".format(override_cluster_name)
1183
+ )
1184
+ if tmux:
1185
+ attach_command_parts.append("--tmux")
1186
+ elif screen:
1187
+ attach_command_parts.append("--screen")
1188
+
1189
+ attach_command = " ".join(attach_command_parts)
1190
+ cli_logger.print("Run `{}` to check command status.", cf.bold(attach_command))
1191
+ return result
1192
+
1193
+
1194
+ def _exec(
1195
+ updater: NodeUpdaterThread,
1196
+ cmd: Optional[str] = None,
1197
+ screen: bool = False,
1198
+ tmux: bool = False,
1199
+ port_forward: Optional[Port_forward] = None,
1200
+ with_output: bool = False,
1201
+ run_env: str = "auto",
1202
+ shutdown_after_run: bool = False,
1203
+ extra_screen_args: Optional[str] = None,
1204
+ ) -> str:
1205
+ if cmd:
1206
+ if screen:
1207
+ wrapped_cmd = [
1208
+ "screen",
1209
+ "-L",
1210
+ "-dm",
1211
+ ]
1212
+
1213
+ if extra_screen_args is not None and len(extra_screen_args) > 0:
1214
+ wrapped_cmd += [extra_screen_args]
1215
+
1216
+ wrapped_cmd += [
1217
+ "bash",
1218
+ "-c",
1219
+ quote(cmd + "; exec bash"),
1220
+ ]
1221
+ cmd = " ".join(wrapped_cmd)
1222
+ elif tmux:
1223
+ # TODO: Consider providing named session functionality
1224
+ wrapped_cmd = [
1225
+ "tmux",
1226
+ "new",
1227
+ "-d",
1228
+ "bash",
1229
+ "-c",
1230
+ quote(cmd + "; exec bash"),
1231
+ ]
1232
+ cmd = " ".join(wrapped_cmd)
1233
+ return updater.cmd_runner.run(
1234
+ cmd,
1235
+ exit_on_fail=True,
1236
+ port_forward=port_forward,
1237
+ with_output=with_output,
1238
+ run_env=run_env,
1239
+ shutdown_after_run=shutdown_after_run,
1240
+ )
1241
+
1242
+
1243
+ def rsync(
1244
+ config_file: str,
1245
+ source: Optional[str],
1246
+ target: Optional[str],
1247
+ override_cluster_name: Optional[str],
1248
+ down: bool,
1249
+ ip_address: Optional[str] = None,
1250
+ use_internal_ip: bool = False,
1251
+ no_config_cache: bool = False,
1252
+ all_nodes: bool = False,
1253
+ should_bootstrap: bool = True,
1254
+ _runner: ModuleType = subprocess,
1255
+ ) -> None:
1256
+ """Rsyncs files.
1257
+
1258
+ Arguments:
1259
+ config_file: path to the cluster yaml
1260
+ source: source dir
1261
+ target: target dir
1262
+ override_cluster_name: set the name of the cluster
1263
+ down: whether we're syncing remote -> local
1264
+ ip_address: Address of node. Raise Exception
1265
+ if both ip_address and 'all_nodes' are provided.
1266
+ use_internal_ip: Whether the provided ip_address is
1267
+ public or private.
1268
+ all_nodes: whether to sync worker nodes in addition to the head node
1269
+ should_bootstrap: whether to bootstrap cluster config before syncing
1270
+ """
1271
+ if bool(source) != bool(target):
1272
+ cli_logger.abort("Expected either both a source and a target, or neither.")
1273
+
1274
+ assert bool(source) == bool(
1275
+ target
1276
+ ), "Must either provide both or neither source and target."
1277
+
1278
+ if ip_address and all_nodes:
1279
+ cli_logger.abort("Cannot provide both ip_address and 'all_nodes'.")
1280
+
1281
+ config = yaml.safe_load(open(config_file).read())
1282
+ if override_cluster_name is not None:
1283
+ config["cluster_name"] = override_cluster_name
1284
+ if should_bootstrap:
1285
+ config = _bootstrap_config(config, no_config_cache=no_config_cache)
1286
+
1287
+ is_file_mount = False
1288
+ if source and target:
1289
+ for remote_mount in config.get("file_mounts", {}).keys():
1290
+ if (source if down else target).startswith(remote_mount):
1291
+ is_file_mount = True
1292
+ break
1293
+
1294
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
1295
+
1296
+ def rsync_to_node(node_id, is_head_node):
1297
+ updater = NodeUpdaterThread(
1298
+ node_id=node_id,
1299
+ provider_config=config["provider"],
1300
+ provider=provider,
1301
+ auth_config=config["auth"],
1302
+ cluster_name=config["cluster_name"],
1303
+ file_mounts=config["file_mounts"],
1304
+ initialization_commands=[],
1305
+ setup_commands=[],
1306
+ ray_start_commands=[],
1307
+ runtime_hash="",
1308
+ use_internal_ip=use_internal_ip,
1309
+ process_runner=_runner,
1310
+ file_mounts_contents_hash="",
1311
+ is_head_node=is_head_node,
1312
+ rsync_options={
1313
+ "rsync_exclude": config.get("rsync_exclude"),
1314
+ "rsync_filter": config.get("rsync_filter"),
1315
+ },
1316
+ docker_config=config.get("docker"),
1317
+ )
1318
+ if down:
1319
+ rsync = updater.rsync_down
1320
+ else:
1321
+ rsync = updater.rsync_up
1322
+
1323
+ if source and target:
1324
+ # print rsync progress for single file rsync
1325
+ if cli_logger.verbosity > 0:
1326
+ cmd_output_util.set_output_redirected(False)
1327
+ set_rsync_silent(False)
1328
+ rsync(source, target, is_file_mount)
1329
+ else:
1330
+ updater.sync_file_mounts(rsync)
1331
+
1332
+ nodes = []
1333
+ head_node = _get_running_head_node(
1334
+ config, config_file, override_cluster_name, create_if_needed=False
1335
+ )
1336
+ if ip_address:
1337
+ nodes = [provider.get_node_id(ip_address, use_internal_ip=use_internal_ip)]
1338
+ else:
1339
+ nodes = [head_node]
1340
+ if all_nodes:
1341
+ nodes.extend(_get_worker_nodes(config, override_cluster_name))
1342
+
1343
+ for node_id in nodes:
1344
+ rsync_to_node(node_id, is_head_node=(node_id == head_node))
1345
+
1346
+
1347
+ def get_head_node_ip(
1348
+ config_file: str, override_cluster_name: Optional[str] = None
1349
+ ) -> str:
1350
+ """Returns head node IP for given configuration file if exists."""
1351
+
1352
+ config = yaml.safe_load(open(config_file).read())
1353
+ if override_cluster_name is not None:
1354
+ config["cluster_name"] = override_cluster_name
1355
+
1356
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
1357
+ head_node = _get_running_head_node(config, config_file, override_cluster_name)
1358
+ provider_cfg = config.get("provider", {})
1359
+ # Get internal IP if using internal IPs and
1360
+ # use_external_head_ip is not specified
1361
+ if provider_cfg.get("use_internal_ips", False) and not provider_cfg.get(
1362
+ "use_external_head_ip", False
1363
+ ):
1364
+ head_node_ip = provider.internal_ip(head_node)
1365
+ else:
1366
+ head_node_ip = provider.external_ip(head_node)
1367
+
1368
+ return head_node_ip
1369
+
1370
+
1371
+ def get_worker_node_ips(
1372
+ config_file: str, override_cluster_name: Optional[str] = None
1373
+ ) -> List[str]:
1374
+ """Returns worker node IPs for given configuration file."""
1375
+
1376
+ config = yaml.safe_load(open(config_file).read())
1377
+ if override_cluster_name is not None:
1378
+ config["cluster_name"] = override_cluster_name
1379
+
1380
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
1381
+ nodes = provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_WORKER})
1382
+
1383
+ if config.get("provider", {}).get("use_internal_ips", False):
1384
+ return [provider.internal_ip(node) for node in nodes]
1385
+ else:
1386
+ return [provider.external_ip(node) for node in nodes]
1387
+
1388
+
1389
+ def _get_worker_nodes(
1390
+ config: Dict[str, Any], override_cluster_name: Optional[str]
1391
+ ) -> List[str]:
1392
+ """Returns worker node ids for given configuration."""
1393
+ # todo: technically could be reused in get_worker_node_ips
1394
+ if override_cluster_name is not None:
1395
+ config["cluster_name"] = override_cluster_name
1396
+
1397
+ provider = _get_node_provider(config["provider"], config["cluster_name"])
1398
+ return provider.non_terminated_nodes({TAG_RAY_NODE_KIND: NODE_KIND_WORKER})
1399
+
1400
+
1401
+ def _get_running_head_node(
1402
+ config: Dict[str, Any],
1403
+ printable_config_file: str,
1404
+ override_cluster_name: Optional[str],
1405
+ create_if_needed: bool = False,
1406
+ _provider: Optional[NodeProvider] = None,
1407
+ _allow_uninitialized_state: bool = False,
1408
+ ) -> str:
1409
+ """Get a valid, running head node.
1410
+ Args:
1411
+ config (Dict[str, Any]): Cluster Config dictionary
1412
+ printable_config_file: Used for printing formatted CLI commands.
1413
+ override_cluster_name: Passed to `get_or_create_head_node` to
1414
+ override the cluster name present in `config`.
1415
+ create_if_needed: Create a head node if one is not present.
1416
+ _provider: [For testing], a Node Provider to use.
1417
+ _allow_uninitialized_state: Whether to return a head node that
1418
+ is not 'UP TO DATE'. This is used to allow `ray attach` and
1419
+ `ray exec` to debug a cluster in a bad state.
1420
+
1421
+ """
1422
+ provider = _provider or _get_node_provider(
1423
+ config["provider"], config["cluster_name"]
1424
+ )
1425
+ head_node_tags = {
1426
+ TAG_RAY_NODE_KIND: NODE_KIND_HEAD,
1427
+ }
1428
+ nodes = provider.non_terminated_nodes(head_node_tags)
1429
+ head_node = None
1430
+ _backup_head_node = None
1431
+ for node in nodes:
1432
+ node_state = provider.node_tags(node).get(TAG_RAY_NODE_STATUS)
1433
+ if node_state == STATUS_UP_TO_DATE:
1434
+ head_node = node
1435
+ else:
1436
+ _backup_head_node = node
1437
+ cli_logger.warning(f"Head node ({node}) is in state {node_state}.")
1438
+
1439
+ if head_node is not None:
1440
+ return head_node
1441
+ elif create_if_needed:
1442
+ get_or_create_head_node(
1443
+ config,
1444
+ printable_config_file=printable_config_file,
1445
+ restart_only=False,
1446
+ no_restart=False,
1447
+ yes=True,
1448
+ override_cluster_name=override_cluster_name,
1449
+ )
1450
+ # NOTE: `_allow_uninitialized_state` is forced to False if
1451
+ # `create_if_needed` is set to True. This is to ensure that the
1452
+ # commands executed after creation occur on an actually running
1453
+ # cluster.
1454
+ return _get_running_head_node(
1455
+ config,
1456
+ printable_config_file,
1457
+ override_cluster_name,
1458
+ create_if_needed=False,
1459
+ _allow_uninitialized_state=False,
1460
+ )
1461
+ else:
1462
+ if _allow_uninitialized_state and _backup_head_node is not None:
1463
+ cli_logger.warning(
1464
+ f"The head node being returned: {_backup_head_node} is not "
1465
+ "`up-to-date`. If you are not debugging a startup issue "
1466
+ "it is recommended to restart this head node with: {}",
1467
+ cf.bold(f" ray down {printable_config_file}"),
1468
+ )
1469
+
1470
+ return _backup_head_node
1471
+ raise RuntimeError(
1472
+ "Head node of cluster ({}) not found!".format(config["cluster_name"])
1473
+ )
1474
+
1475
+
1476
+ def get_local_dump_archive(
1477
+ stream: bool = False,
1478
+ output: Optional[str] = None,
1479
+ logs: bool = True,
1480
+ debug_state: bool = True,
1481
+ pip: bool = True,
1482
+ processes: bool = True,
1483
+ processes_verbose: bool = False,
1484
+ tempfile: Optional[str] = None,
1485
+ ) -> Optional[str]:
1486
+ if stream and output:
1487
+ raise ValueError(
1488
+ "You can only use either `--output` or `--stream`, but not both."
1489
+ )
1490
+
1491
+ parameters = GetParameters(
1492
+ logs=logs,
1493
+ debug_state=debug_state,
1494
+ pip=pip,
1495
+ processes=processes,
1496
+ processes_verbose=processes_verbose,
1497
+ )
1498
+
1499
+ with Archive(file=tempfile) as archive:
1500
+ get_all_local_data(archive, parameters)
1501
+
1502
+ tmp = archive.file
1503
+
1504
+ if stream:
1505
+ with open(tmp, "rb") as fp:
1506
+ os.write(1, fp.read())
1507
+ os.remove(tmp)
1508
+ return None
1509
+
1510
+ target = output or os.path.join(os.getcwd(), os.path.basename(tmp))
1511
+ shutil.move(tmp, target)
1512
+ cli_logger.print(f"Created local data archive at {target}")
1513
+
1514
+ return target
1515
+
1516
+
1517
+ def get_cluster_dump_archive(
1518
+ cluster_config_file: Optional[str] = None,
1519
+ host: Optional[str] = None,
1520
+ ssh_user: Optional[str] = None,
1521
+ ssh_key: Optional[str] = None,
1522
+ docker: Optional[str] = None,
1523
+ local: Optional[bool] = None,
1524
+ output: Optional[str] = None,
1525
+ logs: bool = True,
1526
+ debug_state: bool = True,
1527
+ pip: bool = True,
1528
+ processes: bool = True,
1529
+ processes_verbose: bool = False,
1530
+ tempfile: Optional[str] = None,
1531
+ ) -> Optional[str]:
1532
+ # Inform the user what kind of logs are collected (before actually
1533
+ # collecting, so they can abort)
1534
+ content_str = ""
1535
+ if logs:
1536
+ content_str += (
1537
+ " - The logfiles of your Ray session\n"
1538
+ " This usually includes Python outputs (stdout/stderr)\n"
1539
+ )
1540
+
1541
+ if debug_state:
1542
+ content_str += (
1543
+ " - Debug state information on your Ray cluster \n"
1544
+ " e.g. number of workers, drivers, objects, etc.\n"
1545
+ )
1546
+
1547
+ if pip:
1548
+ content_str += " - Your installed Python packages (`pip freeze`)\n"
1549
+
1550
+ if processes:
1551
+ content_str += (
1552
+ " - Information on your running Ray processes\n"
1553
+ " This includes command line arguments\n"
1554
+ )
1555
+
1556
+ cli_logger.warning(
1557
+ "You are about to create a cluster dump. This will collect data from "
1558
+ "cluster nodes.\n\n"
1559
+ "The dump will contain this information:\n\n"
1560
+ f"{content_str}\n"
1561
+ f"If you are concerned about leaking private information, extract "
1562
+ f"the archive and inspect its contents before sharing it with "
1563
+ f"anyone."
1564
+ )
1565
+
1566
+ # Parse arguments (e.g. fetch info from cluster config)
1567
+ (
1568
+ cluster_config_file,
1569
+ hosts,
1570
+ ssh_user,
1571
+ ssh_key,
1572
+ docker,
1573
+ cluster_name,
1574
+ ) = _info_from_params(cluster_config_file, host, ssh_user, ssh_key, docker)
1575
+
1576
+ nodes = [
1577
+ Node(host=h, ssh_user=ssh_user, ssh_key=ssh_key, docker_container=docker)
1578
+ for h in hosts
1579
+ ]
1580
+
1581
+ if not nodes:
1582
+ cli_logger.error(
1583
+ "No nodes found. Specify with `--host` or by passing a ray "
1584
+ "cluster config to `--cluster`."
1585
+ )
1586
+ return None
1587
+
1588
+ if cluster_config_file:
1589
+ nodes[0].is_head = True
1590
+
1591
+ if local is None:
1592
+ # If called with a cluster config, this was probably started
1593
+ # from a laptop
1594
+ local = not bool(cluster_config_file)
1595
+
1596
+ parameters = GetParameters(
1597
+ logs=logs,
1598
+ debug_state=debug_state,
1599
+ pip=pip,
1600
+ processes=processes,
1601
+ processes_verbose=processes_verbose,
1602
+ )
1603
+
1604
+ with Archive(file=tempfile) as archive:
1605
+ if local:
1606
+ create_archive_for_local_and_remote_nodes(
1607
+ archive, remote_nodes=nodes, parameters=parameters
1608
+ )
1609
+ else:
1610
+ create_archive_for_remote_nodes(
1611
+ archive, remote_nodes=nodes, parameters=parameters
1612
+ )
1613
+
1614
+ if not output:
1615
+ if cluster_name:
1616
+ filename = (
1617
+ f"{cluster_name}_" f"{datetime.datetime.now():%Y-%m-%d_%H-%M-%S}.tar.gz"
1618
+ )
1619
+ else:
1620
+ filename = (
1621
+ f"collected_logs_" f"{datetime.datetime.now():%Y-%m-%d_%H-%M-%S}.tar.gz"
1622
+ )
1623
+ output = os.path.join(os.getcwd(), filename)
1624
+ else:
1625
+ output = os.path.expanduser(output)
1626
+
1627
+ shutil.move(archive.file, output)
1628
+ return output
1629
+
1630
+
1631
+ def confirm(msg: str, yes: bool) -> Optional[bool]:
1632
+ return None if yes else click.confirm(msg, abort=True)
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/constants.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ from ray._private.ray_constants import ( # noqa F401
5
+ AUTOSCALER_RESOURCE_REQUEST_CHANNEL,
6
+ DEFAULT_OBJECT_STORE_MEMORY_PROPORTION,
7
+ LABELS_ENVIRONMENT_VARIABLE,
8
+ LOGGER_FORMAT,
9
+ RESOURCES_ENVIRONMENT_VARIABLE,
10
+ )
11
+
12
+
13
+ def env_integer(key, default):
14
+ if key in os.environ:
15
+ val = os.environ[key]
16
+ if val == "inf":
17
+ return sys.maxsize
18
+ else:
19
+ return int(val)
20
+ return default
21
+
22
+
23
+ # Whether autoscaler cluster status logging is enabled. Set to 0 disable.
24
+ AUTOSCALER_STATUS_LOG = env_integer("RAY_ENABLE_CLUSTER_STATUS_LOG", 1)
25
+
26
+ # The name of the environment variable for plugging in a utilization scorer.
27
+ AUTOSCALER_UTILIZATION_SCORER_KEY = "RAY_AUTOSCALER_UTILIZATION_SCORER"
28
+
29
+ # Whether to avoid launching GPU nodes for CPU only tasks.
30
+ AUTOSCALER_CONSERVE_GPU_NODES = env_integer("AUTOSCALER_CONSERVE_GPU_NODES", 1)
31
+
32
+ # How long to wait for a node to start and terminate, in seconds.
33
+ AUTOSCALER_NODE_START_WAIT_S = env_integer("AUTOSCALER_NODE_START_WAIT_S", 900)
34
+ AUTOSCALER_NODE_TERMINATE_WAIT_S = env_integer("AUTOSCALER_NODE_TERMINATE_WAIT_S", 900)
35
+
36
+ # Interval at which to check if node SSH became available.
37
+ AUTOSCALER_NODE_SSH_INTERVAL_S = env_integer("AUTOSCALER_NODE_SSH_INTERVAL_S", 5)
38
+
39
+ # Abort autoscaling if more than this number of errors are encountered. This
40
+ # is a safety feature to prevent e.g. runaway node launches.
41
+ AUTOSCALER_MAX_NUM_FAILURES = env_integer("AUTOSCALER_MAX_NUM_FAILURES", 5)
42
+
43
+ # The maximum number of nodes to launch in a single request.
44
+ # Multiple requests may be made for this batch size, up to
45
+ # the limit of AUTOSCALER_MAX_CONCURRENT_LAUNCHES.
46
+ AUTOSCALER_MAX_LAUNCH_BATCH = env_integer("AUTOSCALER_MAX_LAUNCH_BATCH", 5)
47
+
48
+ # Max number of nodes to launch at a time.
49
+ AUTOSCALER_MAX_CONCURRENT_LAUNCHES = env_integer(
50
+ "AUTOSCALER_MAX_CONCURRENT_LAUNCHES", 10
51
+ )
52
+
53
+ # Default upscaling speed for the autoscaler. This specifies how many nodes
54
+ # to request at a time, where the desired number to upscale is
55
+ # min(1, upscaling_speed * current_num_nodes)
56
+ # e.g. 1.0 means to request enough nodes to double
57
+ # the cluster size in each round of requests.
58
+ # When the upscaling speed is 0.0, the autoscaler will request 1 node.
59
+ DEFAULT_UPSCALING_SPEED = 0.0
60
+
61
+ # Interval at which to perform autoscaling updates.
62
+ AUTOSCALER_UPDATE_INTERVAL_S = env_integer("AUTOSCALER_UPDATE_INTERVAL_S", 5)
63
+
64
+ # The autoscaler will attempt to restart Ray on nodes it hasn't heard from
65
+ # in more than this interval.
66
+ AUTOSCALER_HEARTBEAT_TIMEOUT_S = env_integer("AUTOSCALER_HEARTBEAT_TIMEOUT_S", 30)
67
+ # The maximum number of nodes (including failed nodes) that the autoscaler will
68
+ # track for logging purposes.
69
+ AUTOSCALER_MAX_NODES_TRACKED = 1500
70
+
71
+ AUTOSCALER_MAX_FAILURES_DISPLAYED = 20
72
+
73
+ AUTOSCALER_NODE_AVAILABILITY_MAX_STALENESS_S = env_integer(
74
+ "AUTOSCALER_NODE_AVAILABILITY_MAX_STALENESS_S", 30 * 60
75
+ )
76
+
77
+ AUTOSCALER_REPORT_PER_NODE_STATUS = (
78
+ env_integer("AUTOSCALER_REPORT_PER_NODE_STATUS", 1) == 1
79
+ )
80
+
81
+ # The maximum allowed resource demand vector size to guarantee the resource
82
+ # demand scheduler bin packing algorithm takes a reasonable amount of time
83
+ # to run.
84
+ AUTOSCALER_MAX_RESOURCE_DEMAND_VECTOR_SIZE = 1000
85
+
86
+ # Port that autoscaler prometheus metrics will be exported to
87
+ AUTOSCALER_METRIC_PORT = env_integer("AUTOSCALER_METRIC_PORT", 44217)
88
+
89
+ # Max number of retries to AWS (default is 5, time increases exponentially)
90
+ BOTO_MAX_RETRIES = env_integer("BOTO_MAX_RETRIES", 12)
91
+ # Max number of retries to create an EC2 node (retry different subnet)
92
+ BOTO_CREATE_MAX_RETRIES = env_integer("BOTO_CREATE_MAX_RETRIES", 5)
93
+
94
+ # ray home path in the container image
95
+ RAY_HOME = "/home/ray"
96
+
97
+ # The order of this list matters! `scripts.py` kills the ray processes in order of this
98
+ # list. Think twice when you add to this list.
99
+ # Invariants:
100
+ # RAYLET must be the first in the list.
101
+ # GCS SERVER must be the last in the list.
102
+ RAY_PROCESSES = [
103
+ # The first element is the substring to filter.
104
+ # The second element, if True, is to filter ps results by command name
105
+ # (only the first 15 charactors of the executable name on Linux);
106
+ # if False, is to filter ps results by command with all its arguments.
107
+ # See STANDARD FORMAT SPECIFIERS section of
108
+ # http://man7.org/linux/man-pages/man1/ps.1.html
109
+ # about comm and args. This can help avoid killing non-ray processes.
110
+ # Format:
111
+ # Keyword to filter, filter by command (True)/filter by args (False)
112
+ ["raylet", True],
113
+ ["plasma_store", True],
114
+ ["monitor.py", False],
115
+ ["ray.util.client.server", False],
116
+ ["default_worker.py", False], # Python worker.
117
+ ["setup_worker.py", False], # Python environment setup worker.
118
+ # For mac osx, setproctitle doesn't change the process name returned
119
+ # by psutil but only cmdline.
120
+ [
121
+ "ray::",
122
+ sys.platform != "darwin",
123
+ ], # Python worker. TODO(mehrdadn): Fix for Windows
124
+ ["io.ray.runtime.runner.worker.DefaultWorker", False], # Java worker.
125
+ ["log_monitor.py", False],
126
+ ["reporter.py", False],
127
+ [os.path.join("dashboard", "agent.py"), False],
128
+ [os.path.join("dashboard", "dashboard.py"), False],
129
+ [os.path.join("runtime_env", "agent", "main.py"), False],
130
+ ["ray_process_reaper.py", False],
131
+ ["gcs_server", True],
132
+ ]
133
+
134
+ # Max Concurrent SSH Calls to stop Docker
135
+ MAX_PARALLEL_SHUTDOWN_WORKERS = env_integer("MAX_PARALLEL_SHUTDOWN_WORKERS", 50)
136
+
137
+ DISABLE_NODE_UPDATERS_KEY = "disable_node_updaters"
138
+ DISABLE_LAUNCH_CONFIG_CHECK_KEY = "disable_launch_config_check"
139
+ FOREGROUND_NODE_LAUNCH_KEY = "foreground_node_launch"
140
+ WORKER_LIVENESS_CHECK_KEY = "worker_liveness_check"
141
+ WORKER_RPC_DRAIN_KEY = "worker_rpc_drain"
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/docker.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from typing import Any, Dict
3
+
4
+ from ray.autoscaler._private.cli_logger import cli_logger
5
+
6
+ try: # py3
7
+ from shlex import quote
8
+ except ImportError: # py2
9
+ from pipes import quote
10
+
11
+
12
+ def _check_docker_file_mounts(file_mounts: Dict[str, str]) -> None:
13
+ """Checks if files are passed as file_mounts. This is a problem for Docker
14
+ based clusters because when a file is bind-mounted in Docker, updates to
15
+ the file on the host do not always propagate to the container. Using
16
+ directories is recommended.
17
+ """
18
+ for remote, local in file_mounts.items():
19
+ if Path(local).is_file():
20
+ cli_logger.warning(
21
+ f"File Mount: ({remote}:{local}) refers to a file.\n To ensure"
22
+ " this mount updates properly, please use a directory."
23
+ )
24
+
25
+
26
+ def validate_docker_config(config: Dict[str, Any]) -> None:
27
+ """Checks whether the Docker configuration is valid."""
28
+ if "docker" not in config:
29
+ return
30
+
31
+ _check_docker_file_mounts(config.get("file_mounts", {}))
32
+
33
+ docker_image = config["docker"].get("image")
34
+ cname = config["docker"].get("container_name")
35
+
36
+ head_docker_image = config["docker"].get("head_image", docker_image)
37
+
38
+ worker_docker_image = config["docker"].get("worker_image", docker_image)
39
+
40
+ image_present = docker_image or (head_docker_image and worker_docker_image)
41
+ if (not cname) and (not image_present):
42
+ return
43
+ else:
44
+ assert cname and image_present, "Must provide a container & image name"
45
+
46
+ return None
47
+
48
+
49
+ def with_docker_exec(
50
+ cmds, container_name, docker_cmd, env_vars=None, with_interactive=False
51
+ ):
52
+ assert docker_cmd, "Must provide docker command"
53
+ env_str = ""
54
+ if env_vars:
55
+ env_str = " ".join(["-e {env}=${env}".format(env=env) for env in env_vars])
56
+ return [
57
+ "docker exec {interactive} {env} {container} /bin/bash -c {cmd} ".format(
58
+ interactive="-it" if with_interactive else "",
59
+ env=env_str,
60
+ container=container_name,
61
+ cmd=quote(cmd),
62
+ )
63
+ for cmd in cmds
64
+ ]
65
+
66
+
67
+ def _check_helper(cname, template, docker_cmd):
68
+ return " ".join(
69
+ [docker_cmd, "inspect", "-f", "'{{" + template + "}}'", cname, "||", "true"]
70
+ )
71
+
72
+
73
+ def check_docker_running_cmd(cname, docker_cmd):
74
+ return _check_helper(cname, ".State.Running", docker_cmd)
75
+
76
+
77
+ def check_bind_mounts_cmd(cname, docker_cmd):
78
+ return _check_helper(cname, "json .Mounts", docker_cmd)
79
+
80
+
81
+ def check_docker_image(cname, docker_cmd):
82
+ return _check_helper(cname, ".Config.Image", docker_cmd)
83
+
84
+
85
+ def docker_start_cmds(
86
+ user,
87
+ image,
88
+ mount_dict,
89
+ container_name,
90
+ user_options,
91
+ cluster_name,
92
+ home_directory,
93
+ docker_cmd,
94
+ ):
95
+ # Imported here due to circular dependency.
96
+ from ray.autoscaler.sdk import get_docker_host_mount_location
97
+
98
+ docker_mount_prefix = get_docker_host_mount_location(cluster_name)
99
+ mount = {f"{docker_mount_prefix}/{dst}": dst for dst in mount_dict}
100
+
101
+ mount_flags = " ".join(
102
+ [
103
+ "-v {src}:{dest}".format(src=k, dest=v.replace("~/", home_directory + "/"))
104
+ for k, v in mount.items()
105
+ ]
106
+ )
107
+
108
+ # for click, used in ray cli
109
+ env_vars = {"LC_ALL": "C.UTF-8", "LANG": "C.UTF-8"}
110
+ env_flags = " ".join(
111
+ ["-e {name}={val}".format(name=k, val=v) for k, v in env_vars.items()]
112
+ )
113
+
114
+ user_options_str = " ".join(user_options)
115
+ docker_run = [
116
+ docker_cmd,
117
+ "run",
118
+ "--rm",
119
+ "--name {}".format(container_name),
120
+ "-d",
121
+ "-it",
122
+ mount_flags,
123
+ env_flags,
124
+ user_options_str,
125
+ "--net=host",
126
+ image,
127
+ "bash",
128
+ ]
129
+ return " ".join(docker_run)
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/event_summarizer.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from threading import RLock
3
+ from typing import Any, Callable, Dict, List
4
+
5
+
6
+ class EventSummarizer:
7
+ """Utility that aggregates related log messages to reduce log spam."""
8
+
9
+ def __init__(self):
10
+ self.events_by_key: Dict[str, int] = {}
11
+ # Messages to send in next summary batch.
12
+ self.messages_to_send: List[str] = []
13
+ # Tracks TTL of messages. A message will not be re-sent once it is
14
+ # added here, until its TTL expires.
15
+ self.throttled_messages: Dict[str, float] = {}
16
+
17
+ # Event summarizer is used by the main thread and
18
+ # by node launcher child threads.
19
+ self.lock = RLock()
20
+
21
+ def add(
22
+ self, template: str, *, quantity: Any, aggregate: Callable[[Any, Any], Any]
23
+ ) -> None:
24
+ """Add a log message, which will be combined by template.
25
+
26
+ Args:
27
+ template: Format string with one placeholder for quantity.
28
+ quantity: Quantity to aggregate.
29
+ aggregate: Aggregation function used to combine the
30
+ quantities. The result is inserted into the template to
31
+ produce the final log message.
32
+ """
33
+ with self.lock:
34
+ # Enforce proper sentence structure.
35
+ if not template.endswith("."):
36
+ template += "."
37
+ if template in self.events_by_key:
38
+ self.events_by_key[template] = aggregate(
39
+ self.events_by_key[template], quantity
40
+ )
41
+ else:
42
+ self.events_by_key[template] = quantity
43
+
44
+ def add_once_per_interval(self, message: str, key: str, interval_s: int):
45
+ """Add a log message, which is throttled once per interval by a key.
46
+
47
+ Args:
48
+ message: The message to log.
49
+ key: The key to use to deduplicate the message.
50
+ interval_s: Throttling interval in seconds.
51
+ """
52
+ with self.lock:
53
+ if key not in self.throttled_messages:
54
+ self.throttled_messages[key] = time.time() + interval_s
55
+ self.messages_to_send.append(message)
56
+
57
+ def summary(self) -> List[str]:
58
+ """Generate the aggregated log summary of all added events."""
59
+ with self.lock:
60
+ out = []
61
+ for template, quantity in self.events_by_key.items():
62
+ out.append(template.format(quantity))
63
+ out.extend(self.messages_to_send)
64
+ return out
65
+
66
+ def clear(self) -> None:
67
+ """Clear the events added."""
68
+ with self.lock:
69
+ self.events_by_key.clear()
70
+ self.messages_to_send.clear()
71
+ # Expire any messages that have reached their TTL. This allows them
72
+ # to be sent again.
73
+ for k, t in list(self.throttled_messages.items()):
74
+ if time.time() > t:
75
+ del self.throttled_messages[k]
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/gcp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/gcp/__pycache__/config.cpython-310.pyc ADDED
Binary file (19.8 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/legacy_info_string.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from ray._private.ray_constants import DEBUG_AUTOSCALING_STATUS_LEGACY
4
+ from ray.experimental.internal_kv import _internal_kv_initialized, _internal_kv_put
5
+
6
+ """This file provides legacy support for the old info string in order to
7
+ ensure the dashboard's `api/cluster_status` does not break backwards
8
+ compatibilty.
9
+ """
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def legacy_log_info_string(autoscaler, nodes):
15
+ tmp = "Cluster status: "
16
+ tmp += info_string(autoscaler, nodes)
17
+ tmp += "\n"
18
+ tmp += autoscaler.load_metrics.info_string()
19
+ tmp += "\n"
20
+ tmp += autoscaler.resource_demand_scheduler.debug_string(
21
+ nodes,
22
+ autoscaler.pending_launches.breakdown(),
23
+ autoscaler.load_metrics.get_resource_utilization(),
24
+ )
25
+ if _internal_kv_initialized():
26
+ _internal_kv_put(DEBUG_AUTOSCALING_STATUS_LEGACY, tmp, overwrite=True)
27
+ logger.debug(tmp)
28
+
29
+
30
+ def info_string(autoscaler, nodes):
31
+ suffix = ""
32
+ if autoscaler.updaters:
33
+ suffix += " ({} updating)".format(len(autoscaler.updaters))
34
+ if autoscaler.num_failed_updates:
35
+ suffix += " ({} failed to update)".format(len(autoscaler.num_failed_updates))
36
+
37
+ return "{} nodes{}".format(len(nodes), suffix)
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/monitor.py ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Autoscaler monitoring loop daemon."""
2
+
3
+ import argparse
4
+ import json
5
+ import logging
6
+ import os
7
+ import signal
8
+ import sys
9
+ import time
10
+ import traceback
11
+ from collections import Counter
12
+ from dataclasses import asdict
13
+ from typing import Any, Callable, Dict, Optional, Union
14
+
15
+ import ray
16
+ import ray._private.ray_constants as ray_constants
17
+ import ray._private.utils
18
+ from ray._private.event.event_logger import get_event_logger
19
+ from ray._private.ray_logging import setup_component_logger
20
+ from ray._raylet import GcsClient
21
+ from ray.autoscaler._private.autoscaler import StandardAutoscaler
22
+ from ray.autoscaler._private.commands import teardown_cluster
23
+ from ray.autoscaler._private.constants import (
24
+ AUTOSCALER_MAX_RESOURCE_DEMAND_VECTOR_SIZE,
25
+ AUTOSCALER_METRIC_PORT,
26
+ AUTOSCALER_UPDATE_INTERVAL_S,
27
+ DISABLE_LAUNCH_CONFIG_CHECK_KEY,
28
+ )
29
+ from ray.autoscaler._private.event_summarizer import EventSummarizer
30
+ from ray.autoscaler._private.load_metrics import LoadMetrics
31
+ from ray.autoscaler._private.prom_metrics import AutoscalerPrometheusMetrics
32
+ from ray.autoscaler._private.util import format_readonly_node_type
33
+ from ray.core.generated import gcs_pb2
34
+ from ray.core.generated.event_pb2 import Event as RayEvent
35
+ from ray.experimental.internal_kv import (
36
+ _initialize_internal_kv,
37
+ _internal_kv_del,
38
+ _internal_kv_get,
39
+ _internal_kv_initialized,
40
+ _internal_kv_put,
41
+ )
42
+
43
+ try:
44
+ import prometheus_client
45
+ except ImportError:
46
+ prometheus_client = None
47
+
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ def parse_resource_demands(resource_load_by_shape):
53
+ """Handle the message.resource_load_by_shape protobuf for the demand
54
+ based autoscaling. Catch and log all exceptions so this doesn't
55
+ interfere with the utilization based autoscaler until we're confident
56
+ this is stable. Worker queue backlogs are added to the appropriate
57
+ resource demand vector.
58
+
59
+ Args:
60
+ resource_load_by_shape (pb2.gcs.ResourceLoad): The resource demands
61
+ in protobuf form or None.
62
+
63
+ Returns:
64
+ List[ResourceDict]: Waiting bundles (ready and feasible).
65
+ List[ResourceDict]: Infeasible bundles.
66
+ """
67
+ waiting_bundles, infeasible_bundles = [], []
68
+ try:
69
+ for resource_demand_pb in list(resource_load_by_shape.resource_demands):
70
+ request_shape = dict(resource_demand_pb.shape)
71
+ for _ in range(resource_demand_pb.num_ready_requests_queued):
72
+ waiting_bundles.append(request_shape)
73
+ for _ in range(resource_demand_pb.num_infeasible_requests_queued):
74
+ infeasible_bundles.append(request_shape)
75
+
76
+ # Infeasible and ready states for tasks are (logically)
77
+ # mutually exclusive.
78
+ if resource_demand_pb.num_infeasible_requests_queued > 0:
79
+ backlog_queue = infeasible_bundles
80
+ else:
81
+ backlog_queue = waiting_bundles
82
+ for _ in range(resource_demand_pb.backlog_size):
83
+ backlog_queue.append(request_shape)
84
+ if (
85
+ len(waiting_bundles + infeasible_bundles)
86
+ > AUTOSCALER_MAX_RESOURCE_DEMAND_VECTOR_SIZE
87
+ ):
88
+ break
89
+ except Exception:
90
+ logger.exception("Failed to parse resource demands.")
91
+
92
+ return waiting_bundles, infeasible_bundles
93
+
94
+
95
+ # Readonly provider config (e.g., for laptop mode, manually setup clusters).
96
+ BASE_READONLY_CONFIG = {
97
+ "cluster_name": "default",
98
+ "max_workers": 0,
99
+ "upscaling_speed": 1.0,
100
+ "docker": {},
101
+ "idle_timeout_minutes": 0,
102
+ "provider": {
103
+ "type": "readonly",
104
+ "use_node_id_as_ip": True, # For emulated multi-node on laptop.
105
+ DISABLE_LAUNCH_CONFIG_CHECK_KEY: True, # No launch check.
106
+ },
107
+ "auth": {},
108
+ "available_node_types": {
109
+ "ray.head.default": {"resources": {}, "node_config": {}, "max_workers": 0}
110
+ },
111
+ "head_node_type": "ray.head.default",
112
+ "file_mounts": {},
113
+ "cluster_synced_files": [],
114
+ "file_mounts_sync_continuously": False,
115
+ "rsync_exclude": [],
116
+ "rsync_filter": [],
117
+ "initialization_commands": [],
118
+ "setup_commands": [],
119
+ "head_setup_commands": [],
120
+ "worker_setup_commands": [],
121
+ "head_start_ray_commands": [],
122
+ "worker_start_ray_commands": [],
123
+ }
124
+
125
+
126
+ class Monitor:
127
+ """Autoscaling monitor.
128
+
129
+ This process periodically collects stats from the GCS and triggers
130
+ autoscaler updates.
131
+ """
132
+
133
+ def __init__(
134
+ self,
135
+ address: str,
136
+ autoscaling_config: Union[str, Callable[[], Dict[str, Any]]],
137
+ log_dir: str = None,
138
+ prefix_cluster_info: bool = False,
139
+ monitor_ip: Optional[str] = None,
140
+ retry_on_failure: bool = True,
141
+ ):
142
+ self.gcs_address = address
143
+ worker = ray._private.worker.global_worker
144
+ # TODO: eventually plumb ClusterID through to here
145
+ self.gcs_client = GcsClient(address=self.gcs_address)
146
+
147
+ if monitor_ip:
148
+ monitor_addr = f"{monitor_ip}:{AUTOSCALER_METRIC_PORT}"
149
+ self.gcs_client.internal_kv_put(
150
+ b"AutoscalerMetricsAddress", monitor_addr.encode(), True, None
151
+ )
152
+ _initialize_internal_kv(self.gcs_client)
153
+ if monitor_ip:
154
+ monitor_addr = f"{monitor_ip}:{AUTOSCALER_METRIC_PORT}"
155
+ self.gcs_client.internal_kv_put(
156
+ b"AutoscalerMetricsAddress", monitor_addr.encode(), True, None
157
+ )
158
+ self._session_name = self.get_session_name(self.gcs_client)
159
+ logger.info(f"session_name: {self._session_name}")
160
+ worker.mode = 0
161
+ head_node_ip = self.gcs_address.split(":")[0]
162
+
163
+ self.load_metrics = LoadMetrics()
164
+ self.last_avail_resources = None
165
+ self.event_summarizer = EventSummarizer()
166
+ self.prefix_cluster_info = prefix_cluster_info
167
+ self.retry_on_failure = retry_on_failure
168
+ self.autoscaling_config = autoscaling_config
169
+ self.autoscaler = None
170
+ # If set, we are in a manually created cluster (non-autoscaling) and
171
+ # simply mirroring what the GCS tells us the cluster node types are.
172
+ self.readonly_config = None
173
+
174
+ if log_dir:
175
+ try:
176
+ self.event_logger = get_event_logger(
177
+ RayEvent.SourceType.AUTOSCALER, log_dir
178
+ )
179
+ except Exception:
180
+ self.event_logger = None
181
+ else:
182
+ self.event_logger = None
183
+
184
+ self.prom_metrics = AutoscalerPrometheusMetrics(session_name=self._session_name)
185
+
186
+ if monitor_ip and prometheus_client:
187
+ # If monitor_ip wasn't passed in, then don't attempt to start the
188
+ # metric server to keep behavior identical to before metrics were
189
+ # introduced
190
+ try:
191
+ logger.info(
192
+ "Starting autoscaler metrics server on port {}".format(
193
+ AUTOSCALER_METRIC_PORT
194
+ )
195
+ )
196
+ kwargs = {"addr": "127.0.0.1"} if head_node_ip == "127.0.0.1" else {}
197
+ prometheus_client.start_http_server(
198
+ port=AUTOSCALER_METRIC_PORT,
199
+ registry=self.prom_metrics.registry,
200
+ **kwargs,
201
+ )
202
+
203
+ # Reset some gauges, since we don't know which labels have
204
+ # leaked if the autoscaler was restarted.
205
+ self.prom_metrics.pending_nodes.clear()
206
+ self.prom_metrics.active_nodes.clear()
207
+ except Exception:
208
+ logger.exception(
209
+ "An exception occurred while starting the metrics server."
210
+ )
211
+ elif not prometheus_client:
212
+ logger.warning(
213
+ "`prometheus_client` not found, so metrics will not be exported."
214
+ )
215
+
216
+ logger.info("Monitor: Started")
217
+
218
+ def _initialize_autoscaler(self):
219
+ if self.autoscaling_config:
220
+ autoscaling_config = self.autoscaling_config
221
+ else:
222
+ # This config mirrors the current setup of the manually created
223
+ # cluster. Each node gets its own unique node type.
224
+ self.readonly_config = BASE_READONLY_CONFIG
225
+
226
+ # Note that the "available_node_types" of the config can change.
227
+ def get_latest_readonly_config():
228
+ return self.readonly_config
229
+
230
+ autoscaling_config = get_latest_readonly_config
231
+ self.autoscaler = StandardAutoscaler(
232
+ autoscaling_config,
233
+ self.load_metrics,
234
+ self.gcs_client,
235
+ self._session_name,
236
+ prefix_cluster_info=self.prefix_cluster_info,
237
+ event_summarizer=self.event_summarizer,
238
+ prom_metrics=self.prom_metrics,
239
+ )
240
+
241
+ def update_load_metrics(self):
242
+ """Fetches resource usage data from GCS and updates load metrics."""
243
+
244
+ response = self.gcs_client.get_all_resource_usage(timeout=60)
245
+ resources_batch_data = response.resource_usage_data
246
+ log_resource_batch_data_if_desired(resources_batch_data)
247
+
248
+ # Tell the readonly node provider what nodes to report.
249
+ if self.readonly_config:
250
+ new_nodes = []
251
+ for msg in list(resources_batch_data.batch):
252
+ node_id = msg.node_id.hex()
253
+ new_nodes.append((node_id, msg.node_manager_address))
254
+ self.autoscaler.provider._set_nodes(new_nodes)
255
+
256
+ mirror_node_types = {}
257
+ cluster_full = False
258
+ if (
259
+ hasattr(response, "cluster_full_of_actors_detected_by_gcs")
260
+ and response.cluster_full_of_actors_detected_by_gcs
261
+ ):
262
+ # GCS has detected the cluster full of actors.
263
+ cluster_full = True
264
+ for resource_message in resources_batch_data.batch:
265
+ node_id = resource_message.node_id
266
+ # Generate node type config based on GCS reported node list.
267
+ if self.readonly_config:
268
+ # Keep prefix in sync with ReadonlyNodeProvider.
269
+ node_type = format_readonly_node_type(node_id.hex())
270
+ resources = {}
271
+ for k, v in resource_message.resources_total.items():
272
+ resources[k] = v
273
+ mirror_node_types[node_type] = {
274
+ "resources": resources,
275
+ "node_config": {},
276
+ "max_workers": 1,
277
+ }
278
+ if (
279
+ hasattr(resource_message, "cluster_full_of_actors_detected")
280
+ and resource_message.cluster_full_of_actors_detected
281
+ ):
282
+ # A worker node has detected the cluster full of actors.
283
+ cluster_full = True
284
+ total_resources = dict(resource_message.resources_total)
285
+ available_resources = dict(resource_message.resources_available)
286
+
287
+ waiting_bundles, infeasible_bundles = parse_resource_demands(
288
+ resources_batch_data.resource_load_by_shape
289
+ )
290
+
291
+ pending_placement_groups = list(
292
+ resources_batch_data.placement_group_load.placement_group_data
293
+ )
294
+
295
+ use_node_id_as_ip = self.autoscaler is not None and self.autoscaler.config[
296
+ "provider"
297
+ ].get("use_node_id_as_ip", False)
298
+
299
+ # "use_node_id_as_ip" is a hack meant to address situations in
300
+ # which there's more than one Ray node residing at a given ip.
301
+ # TODO (Dmitri): Stop using ips as node identifiers.
302
+ # https://github.com/ray-project/ray/issues/19086
303
+ if use_node_id_as_ip:
304
+ peloton_id = total_resources.get("NODE_ID_AS_RESOURCE")
305
+ # Legacy support https://github.com/ray-project/ray/pull/17312
306
+ if peloton_id is not None:
307
+ ip = str(int(peloton_id))
308
+ else:
309
+ ip = node_id.hex()
310
+ else:
311
+ ip = resource_message.node_manager_address
312
+ self.load_metrics.update(
313
+ ip,
314
+ node_id,
315
+ total_resources,
316
+ available_resources,
317
+ waiting_bundles,
318
+ infeasible_bundles,
319
+ pending_placement_groups,
320
+ cluster_full,
321
+ )
322
+ if self.readonly_config:
323
+ self.readonly_config["available_node_types"].update(mirror_node_types)
324
+
325
+ def get_session_name(self, gcs_client: GcsClient) -> Optional[str]:
326
+ """Obtain the session name from the GCS.
327
+
328
+ If the GCS doesn't respond, session name is considered None.
329
+ In this case, the metrics reported from the monitor won't have
330
+ the correct session name.
331
+ """
332
+ if not _internal_kv_initialized():
333
+ return None
334
+
335
+ session_name = gcs_client.internal_kv_get(
336
+ b"session_name",
337
+ ray_constants.KV_NAMESPACE_SESSION,
338
+ timeout=10,
339
+ )
340
+
341
+ if session_name:
342
+ session_name = session_name.decode()
343
+
344
+ return session_name
345
+
346
+ def update_resource_requests(self):
347
+ """Fetches resource requests from the internal KV and updates load."""
348
+ if not _internal_kv_initialized():
349
+ return
350
+ data = _internal_kv_get(
351
+ ray._private.ray_constants.AUTOSCALER_RESOURCE_REQUEST_CHANNEL
352
+ )
353
+ if data:
354
+ try:
355
+ resource_request = json.loads(data)
356
+ self.load_metrics.set_resource_requests(resource_request)
357
+ except Exception:
358
+ logger.exception("Error parsing resource requests")
359
+
360
+ def _run(self):
361
+ """Run the monitor loop."""
362
+
363
+ while True:
364
+ try:
365
+ gcs_request_start_time = time.time()
366
+ self.update_load_metrics()
367
+ gcs_request_time = time.time() - gcs_request_start_time
368
+ self.update_resource_requests()
369
+ self.update_event_summary()
370
+ load_metrics_summary = self.load_metrics.summary()
371
+ status = {
372
+ "gcs_request_time": gcs_request_time,
373
+ "time": time.time(),
374
+ "monitor_pid": os.getpid(),
375
+ }
376
+
377
+ if self.autoscaler and not self.load_metrics:
378
+ # load_metrics is Falsey iff we haven't collected any
379
+ # resource messages from the GCS, which can happen at startup if
380
+ # the GCS hasn't yet received data from the Raylets.
381
+ # In this case, do not do an autoscaler update.
382
+ # Wait to get load metrics.
383
+ logger.info(
384
+ "Autoscaler has not yet received load metrics. Waiting."
385
+ )
386
+ elif self.autoscaler:
387
+ # Process autoscaling actions
388
+ update_start_time = time.time()
389
+ self.autoscaler.update()
390
+ status["autoscaler_update_time"] = time.time() - update_start_time
391
+ autoscaler_summary = self.autoscaler.summary()
392
+ try:
393
+ self.emit_metrics(
394
+ load_metrics_summary,
395
+ autoscaler_summary,
396
+ self.autoscaler.all_node_types,
397
+ )
398
+ except Exception:
399
+ logger.exception("Error emitting metrics")
400
+
401
+ if autoscaler_summary:
402
+ status["autoscaler_report"] = asdict(autoscaler_summary)
403
+ status[
404
+ "non_terminated_nodes_time"
405
+ ] = (
406
+ self.autoscaler.non_terminated_nodes.non_terminated_nodes_time # noqa: E501
407
+ )
408
+
409
+ for msg in self.event_summarizer.summary():
410
+ # Need to prefix each line of the message for the lines to
411
+ # get pushed to the driver logs.
412
+ for line in msg.split("\n"):
413
+ logger.info(
414
+ "{}{}".format(
415
+ ray_constants.LOG_PREFIX_EVENT_SUMMARY, line
416
+ )
417
+ )
418
+ if self.event_logger:
419
+ self.event_logger.info(line)
420
+
421
+ self.event_summarizer.clear()
422
+
423
+ status["load_metrics_report"] = asdict(load_metrics_summary)
424
+ as_json = json.dumps(status)
425
+ if _internal_kv_initialized():
426
+ _internal_kv_put(
427
+ ray_constants.DEBUG_AUTOSCALING_STATUS, as_json, overwrite=True
428
+ )
429
+ except Exception:
430
+ # By default, do not exit the monitor on failure.
431
+ if self.retry_on_failure:
432
+ logger.exception("Monitor: Execution exception. Trying again...")
433
+ else:
434
+ raise
435
+
436
+ # Wait for a autoscaler update interval before processing the next
437
+ # round of messages.
438
+ time.sleep(AUTOSCALER_UPDATE_INTERVAL_S)
439
+
440
+ def emit_metrics(self, load_metrics_summary, autoscaler_summary, node_types):
441
+ if autoscaler_summary is None:
442
+ return None
443
+
444
+ for resource_name in ["CPU", "GPU", "TPU"]:
445
+ _, total = load_metrics_summary.usage.get(resource_name, (0, 0))
446
+ pending = autoscaler_summary.pending_resources.get(resource_name, 0)
447
+ self.prom_metrics.cluster_resources.labels(
448
+ resource=resource_name,
449
+ SessionName=self.prom_metrics.session_name,
450
+ ).set(total)
451
+ self.prom_metrics.pending_resources.labels(
452
+ resource=resource_name,
453
+ SessionName=self.prom_metrics.session_name,
454
+ ).set(pending)
455
+
456
+ pending_node_count = Counter()
457
+ for _, node_type, _ in autoscaler_summary.pending_nodes:
458
+ pending_node_count[node_type] += 1
459
+
460
+ for node_type, count in autoscaler_summary.pending_launches.items():
461
+ pending_node_count[node_type] += count
462
+
463
+ for node_type in node_types:
464
+ count = pending_node_count[node_type]
465
+ self.prom_metrics.pending_nodes.labels(
466
+ SessionName=self.prom_metrics.session_name,
467
+ NodeType=node_type,
468
+ ).set(count)
469
+
470
+ for node_type in node_types:
471
+ count = autoscaler_summary.active_nodes.get(node_type, 0)
472
+ self.prom_metrics.active_nodes.labels(
473
+ SessionName=self.prom_metrics.session_name,
474
+ NodeType=node_type,
475
+ ).set(count)
476
+
477
+ failed_node_counts = Counter()
478
+ for _, node_type in autoscaler_summary.failed_nodes:
479
+ failed_node_counts[node_type] += 1
480
+
481
+ # NOTE: This metric isn't reset with monitor resets. This means it will
482
+ # only be updated when the autoscaler' node tracker remembers failed
483
+ # nodes. If the node type failure is evicted from the autoscaler, the
484
+ # metric may not update for a while.
485
+ for node_type, count in failed_node_counts.items():
486
+ self.prom_metrics.recently_failed_nodes.labels(
487
+ SessionName=self.prom_metrics.session_name,
488
+ NodeType=node_type,
489
+ ).set(count)
490
+
491
+ def update_event_summary(self):
492
+ """Report the current size of the cluster.
493
+
494
+ To avoid log spam, only cluster size changes (CPU, GPU or TPU count change)
495
+ are reported to the event summarizer. The event summarizer will report
496
+ only the latest cluster size per batch.
497
+ """
498
+ avail_resources = self.load_metrics.resources_avail_summary()
499
+ if not self.readonly_config and avail_resources != self.last_avail_resources:
500
+ self.event_summarizer.add(
501
+ "Resized to {}.", # e.g., Resized to 100 CPUs, 4 GPUs, 4 TPUs.
502
+ quantity=avail_resources,
503
+ aggregate=lambda old, new: new,
504
+ )
505
+ self.last_avail_resources = avail_resources
506
+
507
+ def destroy_autoscaler_workers(self):
508
+ """Cleanup the autoscaler, in case of an exception in the run() method.
509
+
510
+ We kill the worker nodes, but retain the head node in order to keep
511
+ logs around, keeping costs minimal. This monitor process runs on the
512
+ head node anyway, so this is more reliable."""
513
+
514
+ if self.autoscaler is None:
515
+ return # Nothing to clean up.
516
+
517
+ if self.autoscaling_config is None:
518
+ # This is a logic error in the program. Can't do anything.
519
+ logger.error("Monitor: Cleanup failed due to lack of autoscaler config.")
520
+ return
521
+
522
+ logger.info("Monitor: Exception caught. Taking down workers...")
523
+ clean = False
524
+ while not clean:
525
+ try:
526
+ teardown_cluster(
527
+ config_file=self.autoscaling_config,
528
+ yes=True, # Non-interactive.
529
+ workers_only=True, # Retain head node for logs.
530
+ override_cluster_name=None,
531
+ keep_min_workers=True, # Retain minimal amount of workers.
532
+ )
533
+ clean = True
534
+ logger.info("Monitor: Workers taken down.")
535
+ except Exception:
536
+ logger.error("Monitor: Cleanup exception. Trying again...")
537
+ time.sleep(2)
538
+
539
+ def _handle_failure(self, error):
540
+ if (
541
+ self.autoscaler is not None
542
+ and os.environ.get("RAY_AUTOSCALER_FATESHARE_WORKERS", "") == "1"
543
+ ):
544
+ self.autoscaler.kill_workers()
545
+ # Take down autoscaler workers if necessary.
546
+ self.destroy_autoscaler_workers()
547
+
548
+ # Something went wrong, so push an error to all current and future
549
+ # drivers.
550
+ message = f"The autoscaler failed with the following error:\n{error}"
551
+ if _internal_kv_initialized():
552
+ _internal_kv_put(
553
+ ray_constants.DEBUG_AUTOSCALING_ERROR, message, overwrite=True
554
+ )
555
+ gcs_publisher = ray._raylet.GcsPublisher(address=self.gcs_address)
556
+ from ray._private.utils import publish_error_to_driver
557
+
558
+ publish_error_to_driver(
559
+ ray_constants.MONITOR_DIED_ERROR,
560
+ message,
561
+ gcs_publisher=gcs_publisher,
562
+ )
563
+
564
+ def _signal_handler(self, sig, frame):
565
+ try:
566
+ self._handle_failure(
567
+ f"Terminated with signal {sig}\n"
568
+ + "".join(traceback.format_stack(frame))
569
+ )
570
+ except Exception:
571
+ logger.exception("Monitor: Failure in signal handler.")
572
+ sys.exit(sig + 128)
573
+
574
+ def run(self):
575
+ # Register signal handlers for autoscaler termination.
576
+ # Signals will not be received on windows
577
+ signal.signal(signal.SIGINT, self._signal_handler)
578
+ signal.signal(signal.SIGTERM, self._signal_handler)
579
+ try:
580
+ if _internal_kv_initialized():
581
+ # Delete any previous autoscaling errors.
582
+ _internal_kv_del(ray_constants.DEBUG_AUTOSCALING_ERROR)
583
+ self._initialize_autoscaler()
584
+ self._run()
585
+ except Exception:
586
+ logger.exception("Error in monitor loop")
587
+ self._handle_failure(traceback.format_exc())
588
+ raise
589
+
590
+
591
+ def log_resource_batch_data_if_desired(
592
+ resources_batch_data: gcs_pb2.ResourceUsageBatchData,
593
+ ) -> None:
594
+ if os.getenv("AUTOSCALER_LOG_RESOURCE_BATCH_DATA") == "1":
595
+ logger.info("Logging raw resource message pulled from GCS.")
596
+ logger.info(resources_batch_data)
597
+ logger.info("Done logging raw resource message.")
598
+
599
+
600
+ if __name__ == "__main__":
601
+ parser = argparse.ArgumentParser(
602
+ description=("Parse GCS server for the monitor to connect to.")
603
+ )
604
+ parser.add_argument(
605
+ "--gcs-address", required=False, type=str, help="The address (ip:port) of GCS."
606
+ )
607
+ parser.add_argument(
608
+ "--redis-address", required=False, type=str, help="This is deprecated"
609
+ )
610
+ parser.add_argument(
611
+ "--redis-password",
612
+ required=False,
613
+ type=str,
614
+ default=None,
615
+ help="This is deprecated",
616
+ )
617
+ parser.add_argument(
618
+ "--autoscaling-config",
619
+ required=False,
620
+ type=str,
621
+ help="the path to the autoscaling config file",
622
+ )
623
+ parser.add_argument(
624
+ "--logging-level",
625
+ required=False,
626
+ type=str,
627
+ default=ray_constants.LOGGER_LEVEL,
628
+ choices=ray_constants.LOGGER_LEVEL_CHOICES,
629
+ help=ray_constants.LOGGER_LEVEL_HELP,
630
+ )
631
+ parser.add_argument(
632
+ "--logging-format",
633
+ required=False,
634
+ type=str,
635
+ default=ray_constants.LOGGER_FORMAT,
636
+ help=ray_constants.LOGGER_FORMAT_HELP,
637
+ )
638
+ parser.add_argument(
639
+ "--logging-filename",
640
+ required=False,
641
+ type=str,
642
+ default=ray_constants.MONITOR_LOG_FILE_NAME,
643
+ help="Specify the name of log file, "
644
+ "log to stdout if set empty, default is "
645
+ f'"{ray_constants.MONITOR_LOG_FILE_NAME}"',
646
+ )
647
+ parser.add_argument(
648
+ "--logs-dir",
649
+ required=True,
650
+ type=str,
651
+ help="Specify the path of the temporary directory used by Ray processes.",
652
+ )
653
+ parser.add_argument(
654
+ "--logging-rotate-bytes",
655
+ required=False,
656
+ type=int,
657
+ default=ray_constants.LOGGING_ROTATE_BYTES,
658
+ help="Specify the max bytes for rotating "
659
+ "log file, default is "
660
+ f"{ray_constants.LOGGING_ROTATE_BYTES} bytes.",
661
+ )
662
+ parser.add_argument(
663
+ "--logging-rotate-backup-count",
664
+ required=False,
665
+ type=int,
666
+ default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT,
667
+ help="Specify the backup count of rotated log file, default is "
668
+ f"{ray_constants.LOGGING_ROTATE_BACKUP_COUNT}.",
669
+ )
670
+ parser.add_argument(
671
+ "--monitor-ip",
672
+ required=False,
673
+ type=str,
674
+ default=None,
675
+ help="The IP address of the machine hosting the monitor process.",
676
+ )
677
+
678
+ args = parser.parse_args()
679
+ setup_component_logger(
680
+ logging_level=args.logging_level,
681
+ logging_format=args.logging_format,
682
+ log_dir=args.logs_dir,
683
+ filename=args.logging_filename,
684
+ max_bytes=args.logging_rotate_bytes,
685
+ backup_count=args.logging_rotate_backup_count,
686
+ )
687
+
688
+ logger.info(f"Starting monitor using ray installation: {ray.__file__}")
689
+ logger.info(f"Ray version: {ray.__version__}")
690
+ logger.info(f"Ray commit: {ray.__commit__}")
691
+ logger.info(f"Monitor started with command: {sys.argv}")
692
+
693
+ if args.autoscaling_config:
694
+ autoscaling_config = os.path.expanduser(args.autoscaling_config)
695
+ else:
696
+ autoscaling_config = None
697
+
698
+ bootstrap_address = args.gcs_address
699
+ if bootstrap_address is None:
700
+ raise ValueError("--gcs-address must be set!")
701
+
702
+ monitor = Monitor(
703
+ bootstrap_address,
704
+ autoscaling_config,
705
+ log_dir=args.logs_dir,
706
+ monitor_ip=args.monitor_ip,
707
+ )
708
+
709
+ monitor.run()
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/node_launcher.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import logging
3
+ import operator
4
+ import threading
5
+ import time
6
+ import traceback
7
+ from typing import Any, Dict, Optional
8
+
9
+ from ray.autoscaler._private.node_provider_availability_tracker import (
10
+ NodeProviderAvailabilityTracker,
11
+ )
12
+ from ray.autoscaler._private.prom_metrics import AutoscalerPrometheusMetrics
13
+ from ray.autoscaler._private.util import hash_launch_conf
14
+ from ray.autoscaler.node_launch_exception import NodeLaunchException
15
+ from ray.autoscaler.tags import (
16
+ NODE_KIND_WORKER,
17
+ STATUS_UNINITIALIZED,
18
+ TAG_RAY_LAUNCH_CONFIG,
19
+ TAG_RAY_NODE_KIND,
20
+ TAG_RAY_NODE_NAME,
21
+ TAG_RAY_NODE_STATUS,
22
+ TAG_RAY_USER_NODE_TYPE,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class BaseNodeLauncher:
29
+ """Launches Ray nodes in the main thread using
30
+ `BaseNodeLauncher.launch_node()`.
31
+
32
+ This is a superclass of NodeLauncher, which launches nodes asynchronously
33
+ in the background.
34
+
35
+ By default, the subclass NodeLauncher is used to launch nodes in subthreads.
36
+ That behavior can be flagged off in the provider config by setting
37
+ `foreground_node_launch: True`; the autoscaler will then makes blocking calls to
38
+ BaseNodeLauncher.launch_node() in the main thread.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ provider,
44
+ pending,
45
+ event_summarizer,
46
+ node_provider_availability_tracker: NodeProviderAvailabilityTracker,
47
+ session_name: Optional[str] = None,
48
+ prom_metrics=None,
49
+ node_types=None,
50
+ index=None,
51
+ *args,
52
+ **kwargs,
53
+ ):
54
+ self.pending = pending
55
+ self.event_summarizer = event_summarizer
56
+ self.node_provider_availability_tracker = node_provider_availability_tracker
57
+ self.prom_metrics = prom_metrics or AutoscalerPrometheusMetrics(
58
+ session_name=session_name
59
+ )
60
+ self.provider = provider
61
+ self.node_types = node_types
62
+ self.index = str(index) if index is not None else ""
63
+
64
+ def launch_node(
65
+ self, config: Dict[str, Any], count: int, node_type: str
66
+ ) -> Optional[Dict]:
67
+ self.log("Got {} nodes to launch.".format(count))
68
+ created_nodes = self._launch_node(config, count, node_type)
69
+ self.pending.dec(node_type, count)
70
+ return created_nodes
71
+
72
+ def _launch_node(
73
+ self, config: Dict[str, Any], count: int, node_type: str
74
+ ) -> Optional[Dict]:
75
+ if self.node_types:
76
+ assert node_type, node_type
77
+
78
+ # The `worker_nodes` field is deprecated in favor of per-node-type
79
+ # node_configs. We allow it for backwards-compatibility.
80
+ launch_config = copy.deepcopy(config.get("worker_nodes", {}))
81
+ if node_type:
82
+ launch_config.update(
83
+ config["available_node_types"][node_type]["node_config"]
84
+ )
85
+ resources = copy.deepcopy(
86
+ config["available_node_types"][node_type]["resources"]
87
+ )
88
+ labels = copy.deepcopy(
89
+ config["available_node_types"][node_type].get("labels", {})
90
+ )
91
+ launch_hash = hash_launch_conf(launch_config, config["auth"])
92
+ node_config = copy.deepcopy(config.get("worker_nodes", {}))
93
+ node_tags = {
94
+ TAG_RAY_NODE_NAME: "ray-{}-worker".format(config["cluster_name"]),
95
+ TAG_RAY_NODE_KIND: NODE_KIND_WORKER,
96
+ TAG_RAY_NODE_STATUS: STATUS_UNINITIALIZED,
97
+ TAG_RAY_LAUNCH_CONFIG: launch_hash,
98
+ }
99
+ # A custom node type is specified; set the tag in this case, and also
100
+ # merge the configs. We merge the configs instead of overriding, so
101
+ # that the bootstrapped per-cloud properties are preserved.
102
+ # TODO(ekl) this logic is duplicated in commands.py (keep in sync)
103
+ if node_type:
104
+ node_tags[TAG_RAY_USER_NODE_TYPE] = node_type
105
+ node_config.update(launch_config)
106
+
107
+ node_launch_start_time = time.time()
108
+
109
+ error_msg = None
110
+ full_exception = None
111
+ created_nodes = {}
112
+ try:
113
+ created_nodes = self.provider.create_node_with_resources_and_labels(
114
+ node_config, node_tags, count, resources, labels
115
+ )
116
+ except NodeLaunchException as node_launch_exception:
117
+ self.node_provider_availability_tracker.update_node_availability(
118
+ node_type, int(node_launch_start_time), node_launch_exception
119
+ )
120
+
121
+ if node_launch_exception.src_exc_info is not None:
122
+ full_exception = "\n".join(
123
+ traceback.format_exception(*node_launch_exception.src_exc_info)
124
+ )
125
+
126
+ error_msg = (
127
+ f"Failed to launch {{}} node(s) of type {node_type}. "
128
+ f"({node_launch_exception.category}): "
129
+ f"{node_launch_exception.description}"
130
+ )
131
+ except Exception:
132
+ error_msg = f"Failed to launch {{}} node(s) of type {node_type}."
133
+ full_exception = traceback.format_exc()
134
+ else:
135
+ # Record some metrics/observability information when a node is launched.
136
+ launch_time = time.time() - node_launch_start_time
137
+ for _ in range(count):
138
+ # Note: when launching multiple nodes we observe the time it
139
+ # took all nodes to launch for each node. For example, if 4
140
+ # nodes were created in 25 seconds, we would observe the 25
141
+ # second create time 4 times.
142
+ self.prom_metrics.worker_create_node_time.observe(launch_time)
143
+ self.prom_metrics.started_nodes.inc(count)
144
+ self.node_provider_availability_tracker.update_node_availability(
145
+ node_type=node_type,
146
+ timestamp=int(node_launch_start_time),
147
+ node_launch_exception=None,
148
+ )
149
+
150
+ if error_msg is not None:
151
+ self.event_summarizer.add(
152
+ error_msg,
153
+ quantity=count,
154
+ aggregate=operator.add,
155
+ )
156
+ self.log(error_msg)
157
+ self.prom_metrics.node_launch_exceptions.inc()
158
+ self.prom_metrics.failed_create_nodes.inc(count)
159
+ else:
160
+ self.log("Launching {} nodes, type {}.".format(count, node_type))
161
+ self.event_summarizer.add(
162
+ "Adding {} node(s) of type " + str(node_type) + ".",
163
+ quantity=count,
164
+ aggregate=operator.add,
165
+ )
166
+
167
+ if full_exception is not None:
168
+ self.log(full_exception)
169
+
170
+ return created_nodes
171
+
172
+ def log(self, statement):
173
+ # launcher_class is "BaseNodeLauncher", or "NodeLauncher" if called
174
+ # from that subclass.
175
+ launcher_class: str = type(self).__name__
176
+ prefix = "{}{}:".format(launcher_class, self.index)
177
+ logger.info(prefix + " {}".format(statement))
178
+
179
+
180
+ class NodeLauncher(BaseNodeLauncher, threading.Thread):
181
+ """Launches nodes asynchronously in the background."""
182
+
183
+ def __init__(
184
+ self,
185
+ provider,
186
+ queue,
187
+ pending,
188
+ event_summarizer,
189
+ node_provider_availability_tracker,
190
+ session_name: Optional[str] = None,
191
+ prom_metrics=None,
192
+ node_types=None,
193
+ index=None,
194
+ *thread_args,
195
+ **thread_kwargs,
196
+ ):
197
+ self.queue = queue
198
+ BaseNodeLauncher.__init__(
199
+ self,
200
+ provider=provider,
201
+ pending=pending,
202
+ event_summarizer=event_summarizer,
203
+ session_name=session_name,
204
+ node_provider_availability_tracker=node_provider_availability_tracker,
205
+ prom_metrics=prom_metrics,
206
+ node_types=node_types,
207
+ index=index,
208
+ )
209
+ threading.Thread.__init__(self, *thread_args, **thread_kwargs)
210
+
211
+ def run(self):
212
+ """Collects launch data from queue populated by StandardAutoscaler.
213
+ Launches nodes in a background thread.
214
+
215
+ Overrides threading.Thread.run().
216
+ NodeLauncher.start() executes this loop in a background thread.
217
+ """
218
+ while True:
219
+ config, count, node_type = self.queue.get()
220
+ # launch_node is implemented in BaseNodeLauncher
221
+ self.launch_node(config, count, node_type)
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/prom_metrics.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+
4
+ class NullMetric:
5
+ """Mock metric class to be used in case of prometheus_client import error."""
6
+
7
+ def set(self, *args, **kwargs):
8
+ pass
9
+
10
+ def observe(self, *args, **kwargs):
11
+ pass
12
+
13
+ def inc(self, *args, **kwargs):
14
+ pass
15
+
16
+ def labels(self, *args, **kwargs):
17
+ return self
18
+
19
+ def clear(self):
20
+ pass
21
+
22
+
23
+ try:
24
+
25
+ from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram
26
+
27
+ # The metrics in this class should be kept in sync with
28
+ # python/ray/tests/test_metrics_agent.py
29
+ class AutoscalerPrometheusMetrics:
30
+ def __init__(
31
+ self, session_name: str = None, registry: Optional[CollectorRegistry] = None
32
+ ):
33
+ self.registry: CollectorRegistry = registry or CollectorRegistry(
34
+ auto_describe=True
35
+ )
36
+ self._session_name = session_name
37
+ # Buckets: 5 seconds, 10 seconds, 20 seconds, 30 seconds,
38
+ # 45 seconds, 1 minute, 1.5 minutes, 2 minutes,
39
+ # 3 minutes, 4 minutes, 5 minutes, 6 minutes,
40
+ # 8 minutes, 10 minutes, 12 minutes, 15 minutes
41
+ # 20 minutes, 25 minutes, 30 minutes
42
+ # used for both worker launch time and worker update time
43
+ histogram_buckets = [
44
+ 5,
45
+ 10,
46
+ 20,
47
+ 30,
48
+ 45,
49
+ 60,
50
+ 90,
51
+ 120,
52
+ 180,
53
+ 240,
54
+ 300,
55
+ 360,
56
+ 480,
57
+ 600,
58
+ 720,
59
+ 900,
60
+ 1200,
61
+ 1500,
62
+ 1800,
63
+ ]
64
+ # Buckets: .01 seconds to 1000 seconds.
65
+ # Used for autoscaler update time.
66
+ update_time_buckets = [0.01, 0.1, 1, 10, 100, 1000]
67
+ self.worker_create_node_time: Histogram = Histogram(
68
+ "worker_create_node_time_seconds",
69
+ "Worker launch time. This is the time it takes for a call to "
70
+ "a node provider's create_node method to return. Note that "
71
+ "when nodes are launched in batches, the launch time for that "
72
+ "batch will be observed once for *each* node in that batch. "
73
+ "For example, if 8 nodes are launched in 3 minutes, a launch "
74
+ "time of 3 minutes will be observed 8 times.",
75
+ labelnames=("SessionName",),
76
+ unit="seconds",
77
+ namespace="autoscaler",
78
+ registry=self.registry,
79
+ buckets=histogram_buckets,
80
+ ).labels(SessionName=session_name)
81
+ self.worker_update_time: Histogram = Histogram(
82
+ "worker_update_time_seconds",
83
+ "Worker update time. This is the time between when an updater "
84
+ "thread begins executing and when it exits successfully. This "
85
+ "metric only observes times for successful updates.",
86
+ labelnames=("SessionName",),
87
+ unit="seconds",
88
+ namespace="autoscaler",
89
+ registry=self.registry,
90
+ buckets=histogram_buckets,
91
+ ).labels(SessionName=session_name)
92
+ self.update_time: Histogram = Histogram(
93
+ "update_time",
94
+ "Autoscaler update time. This is the time for an autoscaler "
95
+ "update iteration to complete.",
96
+ labelnames=("SessionName",),
97
+ unit="seconds",
98
+ namespace="autoscaler",
99
+ registry=self.registry,
100
+ buckets=update_time_buckets,
101
+ ).labels(SessionName=session_name)
102
+ self.pending_nodes: Gauge = Gauge(
103
+ "pending_nodes",
104
+ "Number of nodes pending to be started.",
105
+ labelnames=(
106
+ "NodeType",
107
+ "SessionName",
108
+ ),
109
+ unit="nodes",
110
+ namespace="autoscaler",
111
+ registry=self.registry,
112
+ )
113
+ self.active_nodes: Gauge = Gauge(
114
+ "active_nodes",
115
+ "Number of nodes in the cluster.",
116
+ labelnames=(
117
+ "NodeType",
118
+ "SessionName",
119
+ ),
120
+ unit="nodes",
121
+ namespace="autoscaler",
122
+ registry=self.registry,
123
+ )
124
+ self.recently_failed_nodes = Gauge(
125
+ "recently_failed_nodes",
126
+ "The number of recently failed nodes. This count could reset "
127
+ "at undefined times.",
128
+ labelnames=(
129
+ "NodeType",
130
+ "SessionName",
131
+ ),
132
+ unit="nodes",
133
+ namespace="autoscaler",
134
+ registry=self.registry,
135
+ )
136
+ self.started_nodes: Counter = Counter(
137
+ "started_nodes",
138
+ "Number of nodes started.",
139
+ labelnames=("SessionName",),
140
+ unit="nodes",
141
+ namespace="autoscaler",
142
+ registry=self.registry,
143
+ ).labels(SessionName=session_name)
144
+ self.stopped_nodes: Counter = Counter(
145
+ "stopped_nodes",
146
+ "Number of nodes stopped.",
147
+ labelnames=("SessionName",),
148
+ unit="nodes",
149
+ namespace="autoscaler",
150
+ registry=self.registry,
151
+ ).labels(SessionName=session_name)
152
+ self.updating_nodes: Gauge = Gauge(
153
+ "updating_nodes",
154
+ "Number of nodes in the process of updating.",
155
+ labelnames=("SessionName",),
156
+ unit="nodes",
157
+ namespace="autoscaler",
158
+ registry=self.registry,
159
+ ).labels(SessionName=session_name)
160
+ self.recovering_nodes: Gauge = Gauge(
161
+ "recovering_nodes",
162
+ "Number of nodes in the process of recovering.",
163
+ labelnames=("SessionName",),
164
+ unit="nodes",
165
+ namespace="autoscaler",
166
+ registry=self.registry,
167
+ ).labels(SessionName=session_name)
168
+ self.running_workers: Gauge = Gauge(
169
+ "running_workers",
170
+ "Number of worker nodes running.",
171
+ labelnames=("SessionName",),
172
+ unit="nodes",
173
+ namespace="autoscaler",
174
+ registry=self.registry,
175
+ ).labels(SessionName=session_name)
176
+ self.failed_create_nodes: Counter = Counter(
177
+ "failed_create_nodes",
178
+ "Number of nodes that failed to be created due to an "
179
+ "exception in the node provider's create_node method.",
180
+ labelnames=("SessionName",),
181
+ unit="nodes",
182
+ namespace="autoscaler",
183
+ registry=self.registry,
184
+ ).labels(SessionName=session_name)
185
+ self.failed_updates: Counter = Counter(
186
+ "failed_updates",
187
+ "Number of failed worker node updates.",
188
+ labelnames=("SessionName",),
189
+ unit="updates",
190
+ namespace="autoscaler",
191
+ registry=self.registry,
192
+ ).labels(SessionName=session_name)
193
+ self.successful_updates: Counter = Counter(
194
+ "successful_updates",
195
+ "Number of succesfful worker node updates.",
196
+ labelnames=("SessionName",),
197
+ unit="updates",
198
+ namespace="autoscaler",
199
+ registry=self.registry,
200
+ ).labels(SessionName=session_name)
201
+ self.failed_recoveries: Counter = Counter(
202
+ "failed_recoveries",
203
+ "Number of failed node recoveries.",
204
+ labelnames=("SessionName",),
205
+ unit="recoveries",
206
+ namespace="autoscaler",
207
+ registry=self.registry,
208
+ ).labels(SessionName=session_name)
209
+ self.successful_recoveries: Counter = Counter(
210
+ "successful_recoveries",
211
+ "Number of successful node recoveries.",
212
+ labelnames=("SessionName",),
213
+ unit="recoveries",
214
+ namespace="autoscaler",
215
+ registry=self.registry,
216
+ ).labels(SessionName=session_name)
217
+ self.update_loop_exceptions: Counter = Counter(
218
+ "update_loop_exceptions",
219
+ "Number of exceptions raised in the update loop of the autoscaler.",
220
+ labelnames=("SessionName",),
221
+ unit="exceptions",
222
+ namespace="autoscaler",
223
+ registry=self.registry,
224
+ ).labels(SessionName=session_name)
225
+ self.node_launch_exceptions: Counter = Counter(
226
+ "node_launch_exceptions",
227
+ "Number of exceptions raised while launching nodes.",
228
+ labelnames=("SessionName",),
229
+ unit="exceptions",
230
+ namespace="autoscaler",
231
+ registry=self.registry,
232
+ ).labels(SessionName=session_name)
233
+ self.reset_exceptions: Counter = Counter(
234
+ "reset_exceptions",
235
+ "Number of exceptions raised while resetting the autoscaler.",
236
+ labelnames=("SessionName",),
237
+ unit="exceptions",
238
+ namespace="autoscaler",
239
+ registry=self.registry,
240
+ ).labels(SessionName=session_name)
241
+ self.config_validation_exceptions: Counter = Counter(
242
+ "config_validation_exceptions",
243
+ "Number of exceptions raised while validating the config "
244
+ "during a reset.",
245
+ labelnames=("SessionName",),
246
+ unit="exceptions",
247
+ namespace="autoscaler",
248
+ registry=self.registry,
249
+ ).labels(SessionName=session_name)
250
+ self.drain_node_exceptions: Counter = Counter(
251
+ "drain_node_exceptions",
252
+ "Number of exceptions raised when making a DrainNode rpc"
253
+ "prior to node termination.",
254
+ labelnames=("SessionName",),
255
+ unit="exceptions",
256
+ namespace="autoscaler",
257
+ registry=self.registry,
258
+ ).labels(SessionName=session_name)
259
+ # This represents the autoscaler's view of essentially
260
+ # `ray.cluster_resources()`, it may be slightly different from the
261
+ # core metric from an eventual consistency perspective.
262
+ self.cluster_resources: Gauge = Gauge(
263
+ "cluster_resources",
264
+ "Total logical resources in the cluster.",
265
+ labelnames=("resource", "SessionName"),
266
+ unit="resources",
267
+ namespace="autoscaler",
268
+ registry=self.registry,
269
+ )
270
+ # This represents the pending launches + nodes being set up for the
271
+ # autoscaler.
272
+ self.pending_resources: Gauge = Gauge(
273
+ "pending_resources",
274
+ "Pending logical resources in the cluster.",
275
+ labelnames=("resource", "SessionName"),
276
+ unit="resources",
277
+ namespace="autoscaler",
278
+ registry=self.registry,
279
+ )
280
+
281
+ @property
282
+ def session_name(self):
283
+ return self._session_name
284
+
285
+ except ImportError:
286
+
287
+ class AutoscalerPrometheusMetrics(object):
288
+ def __init__(self, session_name: str = None):
289
+ pass
290
+
291
+ def __getattr__(self, attr):
292
+ return NullMetric()
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/providers.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import logging
4
+ import os
5
+ from typing import Any, Dict
6
+
7
+ import yaml
8
+
9
+ from ray.autoscaler._private.loader import load_function_or_class
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # For caching provider instantiations across API calls of one python session
14
+ _provider_instances = {}
15
+
16
+ # Minimal config for compatibility with legacy-style external configs.
17
+ MINIMAL_EXTERNAL_CONFIG = {
18
+ "available_node_types": {
19
+ "ray.head.default": {},
20
+ "ray.worker.default": {},
21
+ },
22
+ "head_node_type": "ray.head.default",
23
+ "head_node": {},
24
+ "worker_nodes": {},
25
+ }
26
+
27
+
28
+ def _import_aws(provider_config):
29
+ try:
30
+ # boto3 and botocore are imported in multiple places in the codebase,
31
+ # so we just import them here to ensure that they are installed.
32
+ import boto3 # noqa: F401
33
+ except ImportError as e:
34
+ raise ImportError(
35
+ "The Ray AWS VM launcher requires the AWS SDK for Python (Boto3) "
36
+ "to be installed. You can install it with `pip install boto3`."
37
+ ) from e
38
+
39
+ from ray.autoscaler._private.aws.node_provider import AWSNodeProvider
40
+
41
+ return AWSNodeProvider
42
+
43
+
44
+ def _import_gcp(provider_config):
45
+ try:
46
+ import googleapiclient # noqa: F401
47
+ except ImportError as e:
48
+ raise ImportError(
49
+ "The Ray GCP VM launcher requires the Google API Client to be installed. "
50
+ "You can install it with `pip install google-api-python-client`."
51
+ ) from e
52
+
53
+ from ray.autoscaler._private.gcp.node_provider import GCPNodeProvider
54
+
55
+ return GCPNodeProvider
56
+
57
+
58
+ def _import_azure(provider_config):
59
+ from ray.autoscaler._private._azure.node_provider import AzureNodeProvider
60
+
61
+ return AzureNodeProvider
62
+
63
+
64
+ def _import_vsphere(provider_config):
65
+ from ray.autoscaler._private.vsphere.node_provider import VsphereNodeProvider
66
+
67
+ return VsphereNodeProvider
68
+
69
+
70
+ def _import_local(provider_config):
71
+ if "coordinator_address" in provider_config:
72
+ from ray.autoscaler._private.local.coordinator_node_provider import (
73
+ CoordinatorSenderNodeProvider,
74
+ )
75
+
76
+ return CoordinatorSenderNodeProvider
77
+ else:
78
+ from ray.autoscaler._private.local.node_provider import LocalNodeProvider
79
+
80
+ return LocalNodeProvider
81
+
82
+
83
+ def _import_readonly(provider_config):
84
+ from ray.autoscaler._private.readonly.node_provider import ReadOnlyNodeProvider
85
+
86
+ return ReadOnlyNodeProvider
87
+
88
+
89
+ def _import_fake_multinode(provider_config):
90
+ from ray.autoscaler._private.fake_multi_node.node_provider import (
91
+ FakeMultiNodeProvider,
92
+ )
93
+
94
+ return FakeMultiNodeProvider
95
+
96
+
97
+ def _import_fake_multinode_docker(provider_config):
98
+ from ray.autoscaler._private.fake_multi_node.node_provider import (
99
+ FakeMultiNodeDockerProvider,
100
+ )
101
+
102
+ return FakeMultiNodeDockerProvider
103
+
104
+
105
+ def _import_kubernetes(provider_config):
106
+ from ray.autoscaler._private._kubernetes.node_provider import KubernetesNodeProvider
107
+
108
+ return KubernetesNodeProvider
109
+
110
+
111
+ def _import_kuberay(provider_config):
112
+ from ray.autoscaler._private.kuberay.node_provider import KubeRayNodeProvider
113
+
114
+ return KubeRayNodeProvider
115
+
116
+
117
+ def _import_aliyun(provider_config):
118
+ from ray.autoscaler._private.aliyun.node_provider import AliyunNodeProvider
119
+
120
+ return AliyunNodeProvider
121
+
122
+
123
+ def _import_spark(provider_config):
124
+ from ray.autoscaler._private.spark.node_provider import SparkNodeProvider
125
+
126
+ return SparkNodeProvider
127
+
128
+
129
+ def _load_fake_multinode_defaults_config():
130
+ import ray.autoscaler._private.fake_multi_node as ray_fake_multinode
131
+
132
+ return os.path.join(os.path.dirname(ray_fake_multinode.__file__), "example.yaml")
133
+
134
+
135
+ def _load_read_only_defaults_config():
136
+ import ray.autoscaler._private.readonly as ray_readonly
137
+
138
+ return os.path.join(os.path.dirname(ray_readonly.__file__), "example.yaml")
139
+
140
+
141
+ def _load_fake_multinode_docker_defaults_config():
142
+ import ray.autoscaler._private.fake_multi_node as ray_fake_multinode
143
+
144
+ return os.path.join(
145
+ os.path.dirname(ray_fake_multinode.__file__), "example_docker.yaml"
146
+ )
147
+
148
+
149
+ def _load_local_defaults_config():
150
+ import ray.autoscaler.local as ray_local
151
+
152
+ return os.path.join(os.path.dirname(ray_local.__file__), "defaults.yaml")
153
+
154
+
155
+ def _load_kubernetes_defaults_config():
156
+ import ray.autoscaler.kubernetes as ray_kubernetes
157
+
158
+ return os.path.join(os.path.dirname(ray_kubernetes.__file__), "defaults.yaml")
159
+
160
+
161
+ def _load_aws_defaults_config():
162
+ import ray.autoscaler.aws as ray_aws
163
+
164
+ return os.path.join(os.path.dirname(ray_aws.__file__), "defaults.yaml")
165
+
166
+
167
+ def _load_vsphere_defaults_config():
168
+ import ray.autoscaler.vsphere as ray_vsphere
169
+
170
+ return os.path.join(os.path.dirname(ray_vsphere.__file__), "defaults.yaml")
171
+
172
+
173
+ def _load_gcp_defaults_config():
174
+ import ray.autoscaler.gcp as ray_gcp
175
+
176
+ return os.path.join(os.path.dirname(ray_gcp.__file__), "defaults.yaml")
177
+
178
+
179
+ def _load_azure_defaults_config():
180
+ import ray.autoscaler.azure as ray_azure
181
+
182
+ return os.path.join(os.path.dirname(ray_azure.__file__), "defaults.yaml")
183
+
184
+
185
+ def _load_aliyun_defaults_config():
186
+ import ray.autoscaler.aliyun as ray_aliyun
187
+
188
+ return os.path.join(os.path.dirname(ray_aliyun.__file__), "defaults.yaml")
189
+
190
+
191
+ def _import_external(provider_config):
192
+ provider_cls = load_function_or_class(path=provider_config["module"])
193
+ return provider_cls
194
+
195
+
196
+ _NODE_PROVIDERS = {
197
+ "local": _import_local,
198
+ "fake_multinode": _import_fake_multinode,
199
+ "fake_multinode_docker": _import_fake_multinode_docker,
200
+ "readonly": _import_readonly,
201
+ "aws": _import_aws,
202
+ "gcp": _import_gcp,
203
+ "vsphere": _import_vsphere,
204
+ "azure": _import_azure,
205
+ "kubernetes": _import_kubernetes,
206
+ "kuberay": _import_kuberay,
207
+ "aliyun": _import_aliyun,
208
+ "external": _import_external, # Import an external module
209
+ "spark": _import_spark,
210
+ }
211
+
212
+ _PROVIDER_PRETTY_NAMES = {
213
+ "readonly": "Readonly (Manual Cluster Setup)",
214
+ "fake_multinode": "Fake Multinode",
215
+ "fake_multinode_docker": "Fake Multinode Docker",
216
+ "local": "Local",
217
+ "aws": "AWS",
218
+ "gcp": "GCP",
219
+ "azure": "Azure",
220
+ "kubernetes": "Kubernetes",
221
+ "kuberay": "KubeRay",
222
+ "aliyun": "Aliyun",
223
+ "external": "External",
224
+ "vsphere": "vSphere",
225
+ }
226
+
227
+ _DEFAULT_CONFIGS = {
228
+ "fake_multinode": _load_fake_multinode_defaults_config,
229
+ "fake_multinode_docker": _load_fake_multinode_docker_defaults_config,
230
+ "local": _load_local_defaults_config,
231
+ "aws": _load_aws_defaults_config,
232
+ "gcp": _load_gcp_defaults_config,
233
+ "azure": _load_azure_defaults_config,
234
+ "aliyun": _load_aliyun_defaults_config,
235
+ "kubernetes": _load_kubernetes_defaults_config,
236
+ "vsphere": _load_vsphere_defaults_config,
237
+ "readonly": _load_read_only_defaults_config,
238
+ }
239
+
240
+
241
+ def _get_node_provider_cls(provider_config: Dict[str, Any]):
242
+ """Get the node provider class for a given provider config.
243
+
244
+ Note that this may be used by private node providers that proxy methods to
245
+ built-in node providers, so we should maintain backwards compatibility.
246
+
247
+ Args:
248
+ provider_config: provider section of the autoscaler config.
249
+
250
+ Returns:
251
+ NodeProvider class
252
+ """
253
+ importer = _NODE_PROVIDERS.get(provider_config["type"])
254
+ if importer is None:
255
+ raise NotImplementedError(
256
+ "Unsupported node provider: {}".format(provider_config["type"])
257
+ )
258
+ return importer(provider_config)
259
+
260
+
261
+ def _get_node_provider(
262
+ provider_config: Dict[str, Any], cluster_name: str, use_cache: bool = True
263
+ ) -> Any:
264
+ """Get the instantiated node provider for a given provider config.
265
+
266
+ Note that this may be used by private node providers that proxy methods to
267
+ built-in node providers, so we should maintain backwards compatibility.
268
+
269
+ Args:
270
+ provider_config: provider section of the autoscaler config.
271
+ cluster_name: cluster name from the autoscaler config.
272
+ use_cache: whether or not to use a cached definition if available. If
273
+ False, the returned object will also not be stored in the cache.
274
+
275
+ Returns:
276
+ NodeProvider
277
+ """
278
+ provider_key = (json.dumps(provider_config, sort_keys=True), cluster_name)
279
+ if use_cache and provider_key in _provider_instances:
280
+ return _provider_instances[provider_key]
281
+
282
+ provider_cls = _get_node_provider_cls(provider_config)
283
+ new_provider = provider_cls(provider_config, cluster_name)
284
+
285
+ if use_cache:
286
+ _provider_instances[provider_key] = new_provider
287
+
288
+ return new_provider
289
+
290
+
291
+ def _clear_provider_cache():
292
+ global _provider_instances
293
+ _provider_instances = {}
294
+
295
+
296
+ def _get_default_config(provider_config):
297
+ """Retrieve a node provider.
298
+
299
+ This is an INTERNAL API. It is not allowed to call this from any Ray
300
+ package outside the autoscaler.
301
+ """
302
+ if provider_config["type"] == "external":
303
+ return copy.deepcopy(MINIMAL_EXTERNAL_CONFIG)
304
+ load_config = _DEFAULT_CONFIGS.get(provider_config["type"])
305
+ if load_config is None:
306
+ raise NotImplementedError(
307
+ "Unsupported node provider: {}".format(provider_config["type"])
308
+ )
309
+ path_to_default = load_config()
310
+ with open(path_to_default) as f:
311
+ defaults = yaml.safe_load(f)
312
+
313
+ return defaults
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/node_provider.cpython-310.pyc ADDED
Binary file (7.1 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/spark/__pycache__/spark_job_server.cpython-310.pyc ADDED
Binary file (7.37 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/subprocess_output_util.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import subprocess
4
+ import sys
5
+ import tempfile
6
+ import time
7
+
8
+ from ray.autoscaler._private.cli_logger import cf, cli_logger
9
+
10
+ CONN_REFUSED_PATIENCE = 30 # how long to wait for sshd to run
11
+
12
+ _redirect_output = False # Whether to log command output to a temporary file
13
+ _allow_interactive = True # whether to pass on stdin to running commands.
14
+
15
+
16
+ def is_output_redirected():
17
+ return _redirect_output
18
+
19
+
20
+ def set_output_redirected(val: bool):
21
+ """Choose between logging to a temporary file and to `sys.stdout`.
22
+
23
+ The default is to log to a file.
24
+
25
+ Args:
26
+ val: If true, subprocess output will be redirected to
27
+ a temporary file.
28
+ """
29
+ global _redirect_output
30
+ _redirect_output = val
31
+
32
+
33
+ def does_allow_interactive():
34
+ return _allow_interactive
35
+
36
+
37
+ def set_allow_interactive(val: bool):
38
+ """Choose whether to pass on stdin to running commands.
39
+
40
+ The default is to pipe stdin and close it immediately.
41
+
42
+ Args:
43
+ val: If true, stdin will be passed to commands.
44
+ """
45
+ global _allow_interactive
46
+ _allow_interactive = val
47
+
48
+
49
+ class ProcessRunnerError(Exception):
50
+ def __init__(self, msg, msg_type, code=None, command=None, special_case=None):
51
+ super(ProcessRunnerError, self).__init__(
52
+ "{} (discovered={}): type={}, code={}, command={}".format(
53
+ msg, special_case, msg_type, code, command
54
+ )
55
+ )
56
+
57
+ self.msg_type = msg_type
58
+ self.code = code
59
+ self.command = command
60
+
61
+ self.special_case = special_case
62
+
63
+
64
+ _ssh_output_regexes = {
65
+ "known_host_update": re.compile(
66
+ r"\s*Warning: Permanently added '.+' \(.+\) " r"to the list of known hosts.\s*"
67
+ ),
68
+ "connection_closed": re.compile(r"\s*Shared connection to .+ closed.\s*"),
69
+ "timeout": re.compile(
70
+ r"\s*ssh: connect to host .+ port .+: " r"Operation timed out\s*"
71
+ ),
72
+ "conn_refused": re.compile(
73
+ r"\s*ssh: connect to host .+ port .+: Connection refused\s*"
74
+ )
75
+ # todo: check for other connection failures for better error messages?
76
+ }
77
+
78
+
79
+ def _read_subprocess_stream(f, output_file, is_stdout=False):
80
+ """Read and process a subprocess output stream.
81
+
82
+ The goal is to find error messages and respond to them in a clever way.
83
+ Currently just used for SSH messages (CONN_REFUSED, TIMEOUT, etc.), so
84
+ the user does not get confused by these.
85
+
86
+ Ran in a thread each for both `stdout` and `stderr` to
87
+ allow for cross-platform asynchronous IO.
88
+
89
+ Note: `select`-based IO is another option, but Windows has
90
+ no support for `select`ing pipes, and Linux support varies somewhat.
91
+ Spefically, Older *nix systems might also have quirks in how they
92
+ handle `select` on pipes.
93
+
94
+ Args:
95
+ f: File object for the stream.
96
+ output_file: File object to which filtered output is written.
97
+ is_stdout (bool):
98
+ When `is_stdout` is `False`, the stream is assumed to
99
+ be `stderr`. Different error message detectors are used,
100
+ and the output is displayed to the user unless it matches
101
+ a special case (e.g. SSH timeout), in which case this is
102
+ left up to the caller.
103
+ """
104
+
105
+ detected_special_case = None
106
+ while True:
107
+ # ! Readline here is crucial.
108
+ # ! Normal `read()` will block until EOF instead of until
109
+ # something is available.
110
+ line = f.readline()
111
+
112
+ if line is None or line == "":
113
+ # EOF
114
+ break
115
+
116
+ if line[-1] == "\n":
117
+ line = line[:-1]
118
+
119
+ if not is_stdout:
120
+ if _ssh_output_regexes["connection_closed"].fullmatch(line) is not None:
121
+ # Do not log "connection closed" messages which SSH
122
+ # puts in stderr for no reason.
123
+ #
124
+ # They are never errors since the connection will
125
+ # close no matter whether the command succeeds or not.
126
+ continue
127
+
128
+ if _ssh_output_regexes["timeout"].fullmatch(line) is not None:
129
+ # Timeout is not really an error but rather a special
130
+ # condition. It should be handled by the caller, since
131
+ # network conditions/nodes in the early stages of boot
132
+ # are expected to sometimes cause connection timeouts.
133
+ if detected_special_case is not None:
134
+ raise ValueError(
135
+ "Bug: ssh_timeout conflicts with another "
136
+ "special codition: " + detected_special_case
137
+ )
138
+
139
+ detected_special_case = "ssh_timeout"
140
+ continue
141
+
142
+ if _ssh_output_regexes["conn_refused"].fullmatch(line) is not None:
143
+ # Connection refused is not really an error but
144
+ # rather a special condition. It should be handled by
145
+ # the caller, since network conditions/nodes in the
146
+ # early stages of boot are expected to sometimes cause
147
+ # CONN_REFUSED.
148
+ if detected_special_case is not None:
149
+ raise ValueError(
150
+ "Bug: ssh_conn_refused conflicts with another "
151
+ "special codition: " + detected_special_case
152
+ )
153
+
154
+ detected_special_case = "ssh_conn_refused"
155
+ continue
156
+
157
+ if _ssh_output_regexes["known_host_update"].fullmatch(line) is not None:
158
+ # Since we ignore SSH host control anyway
159
+ # (-o UserKnownHostsFile=/dev/null),
160
+ # we should silence the host control warnings.
161
+ continue
162
+
163
+ cli_logger.error(line)
164
+
165
+ if output_file is not None and output_file != subprocess.DEVNULL:
166
+ output_file.write(line + "\n")
167
+
168
+ return detected_special_case
169
+
170
+
171
+ def _run_and_process_output(
172
+ cmd,
173
+ stdout_file,
174
+ process_runner=subprocess,
175
+ stderr_file=None,
176
+ use_login_shells=False,
177
+ ):
178
+ """Run a command and process its output for special cases.
179
+
180
+ Calls a standard 'check_call' if process_runner is not subprocess.
181
+
182
+ Specifically, run all command output through regex to detect
183
+ error conditions and filter out non-error messages that went to stderr
184
+ anyway (SSH writes ALL of its "system" messages to stderr even if they
185
+ are not actually errors).
186
+
187
+ Args:
188
+ cmd (List[str]): Command to run.
189
+ process_runner: Used for command execution. Assumed to have
190
+ 'check_call' and 'check_output' inplemented.
191
+ stdout_file: File to redirect stdout to.
192
+ stderr_file: File to redirect stderr to.
193
+
194
+ Implementation notes:
195
+ 1. `use_login_shells` disables special processing
196
+ If we run interactive apps, output processing will likely get
197
+ overwhelmed with the interactive output elements.
198
+ Thus, we disable output processing for login shells. This makes
199
+ the logging experience considerably worse, but it only degrades
200
+ to old-style logging.
201
+
202
+ For example, `pip install` outputs HUNDREDS of progress-bar lines
203
+ when downloading a package, and we have to
204
+ read + regex + write all of them.
205
+
206
+ After all, even just printing output to console can often slow
207
+ down a fast-printing app, and we do more than just print, and
208
+ all that from Python, which is much slower than C regarding
209
+ stream processing.
210
+
211
+ 2. `stdin=PIPE` for subprocesses
212
+ Do not inherit stdin as it messes with bash signals
213
+ (ctrl-C for SIGINT) and these commands aren't supposed to
214
+ take input anyway.
215
+
216
+ 3. `ThreadPoolExecutor` without the `Pool`
217
+ We use `ThreadPoolExecutor` to create futures from threads.
218
+ Threads are never reused.
219
+
220
+ This approach allows us to have no custom synchronization by
221
+ off-loading the return value and exception passing to the
222
+ standard library (`ThreadPoolExecutor` internals).
223
+
224
+ This instance will be `shutdown()` ASAP so it's fine to
225
+ create one in such a weird place.
226
+
227
+ The code is thus 100% thread-safe as long as the stream readers
228
+ are read-only except for return values and possible exceptions.
229
+ """
230
+ stdin_overwrite = subprocess.PIPE
231
+ # This already should be validated in a higher place of the stack.
232
+ assert not (
233
+ does_allow_interactive() and is_output_redirected()
234
+ ), "Cannot redirect output while in interactive mode."
235
+ if process_runner != subprocess or (
236
+ does_allow_interactive() and not is_output_redirected()
237
+ ):
238
+ stdin_overwrite = None
239
+
240
+ # See implementation note #1
241
+
242
+ if use_login_shells or process_runner != subprocess:
243
+ return process_runner.check_call(
244
+ cmd,
245
+ # See implementation note #2
246
+ stdin=stdin_overwrite,
247
+ stdout=stdout_file,
248
+ stderr=stderr_file,
249
+ )
250
+
251
+ with subprocess.Popen(
252
+ cmd,
253
+ # See implementation note #2
254
+ stdin=stdin_overwrite,
255
+ stdout=subprocess.PIPE,
256
+ stderr=subprocess.PIPE,
257
+ bufsize=1, # line buffering
258
+ universal_newlines=True, # text mode outputs
259
+ ) as p:
260
+ from concurrent.futures import ThreadPoolExecutor
261
+
262
+ # Closing stdin might be necessary to signal EOF to some
263
+ # apps (they might get stuck waiting for input forever otherwise).
264
+ p.stdin.close()
265
+
266
+ # See implementation note #3
267
+ with ThreadPoolExecutor(max_workers=2) as executor:
268
+ stdout_future = executor.submit(
269
+ _read_subprocess_stream, p.stdout, stdout_file, is_stdout=True
270
+ )
271
+ stderr_future = executor.submit(
272
+ _read_subprocess_stream, p.stderr, stderr_file, is_stdout=False
273
+ )
274
+ # Wait for completion.
275
+ executor.shutdown()
276
+
277
+ # Update `p.returncode`
278
+ p.poll()
279
+
280
+ detected_special_case = stdout_future.result()
281
+ if stderr_future.result() is not None:
282
+ if detected_special_case is not None:
283
+ # This might some day need to be changed.
284
+ # We should probably make sure the two special cases
285
+ # are compatible then and that we can handle both by
286
+ # e.g. reporting both to the caller.
287
+ raise ValueError(
288
+ "Bug: found a special case in both stdout and "
289
+ "stderr. This is not valid behavior at the time "
290
+ "of writing this code."
291
+ )
292
+ detected_special_case = stderr_future.result()
293
+
294
+ if p.returncode > 0:
295
+ # Process failed, but not due to a signal, since signals
296
+ # set the exit code to a negative value.
297
+ raise ProcessRunnerError(
298
+ "Command failed",
299
+ "ssh_command_failed",
300
+ code=p.returncode,
301
+ command=cmd,
302
+ special_case=detected_special_case,
303
+ )
304
+ elif p.returncode < 0:
305
+ # Process failed due to a signal, since signals
306
+ # set the exit code to a negative value.
307
+ raise ProcessRunnerError(
308
+ "Command failed",
309
+ "ssh_command_failed",
310
+ code=p.returncode,
311
+ command=cmd,
312
+ special_case="died_to_signal",
313
+ )
314
+
315
+ return p.returncode
316
+
317
+
318
+ def run_cmd_redirected(
319
+ cmd, process_runner=subprocess, silent=False, use_login_shells=False
320
+ ):
321
+ """Run a command and optionally redirect output to a file.
322
+
323
+ Args:
324
+ cmd (List[str]): Command to run.
325
+ process_runner: Process runner used for executing commands.
326
+ silent: If true, the command output will be silenced completely
327
+ (redirected to /dev/null), unless verbose logging
328
+ is enabled. Use this for running utility commands like
329
+ rsync.
330
+ """
331
+ if silent and cli_logger.verbosity < 1:
332
+ return _run_and_process_output(
333
+ cmd,
334
+ process_runner=process_runner,
335
+ stdout_file=process_runner.DEVNULL,
336
+ stderr_file=process_runner.DEVNULL,
337
+ use_login_shells=use_login_shells,
338
+ )
339
+
340
+ if not is_output_redirected():
341
+ return _run_and_process_output(
342
+ cmd,
343
+ process_runner=process_runner,
344
+ stdout_file=sys.stdout,
345
+ stderr_file=sys.stderr,
346
+ use_login_shells=use_login_shells,
347
+ )
348
+ else:
349
+ tmpfile_path = os.path.join(
350
+ tempfile.gettempdir(), "ray-up-{}-{}.txt".format(cmd[0], time.time())
351
+ )
352
+ with open(
353
+ tmpfile_path,
354
+ mode="w",
355
+ # line buffering
356
+ buffering=1,
357
+ ) as tmp:
358
+ cli_logger.verbose("Command stdout is redirected to {}", cf.bold(tmp.name))
359
+
360
+ return _run_and_process_output(
361
+ cmd,
362
+ process_runner=process_runner,
363
+ stdout_file=tmp,
364
+ stderr_file=tmp,
365
+ use_login_shells=use_login_shells,
366
+ )
367
+
368
+
369
+ def handle_ssh_fails(e, first_conn_refused_time, retry_interval):
370
+ """Handle SSH system failures coming from a subprocess.
371
+
372
+ Args:
373
+ e: The `ProcessRunnerException` to handle.
374
+ first_conn_refused_time:
375
+ The time (as reported by this function) or None,
376
+ indicating the last time a CONN_REFUSED error was caught.
377
+
378
+ After exceeding a patience value, the program will be aborted
379
+ since SSH will likely never recover.
380
+ retry_interval: The interval after which the command will be retried,
381
+ used here just to inform the user.
382
+ """
383
+ if e.msg_type != "ssh_command_failed":
384
+ return
385
+
386
+ if e.special_case == "ssh_conn_refused":
387
+ if (
388
+ first_conn_refused_time is not None
389
+ and time.time() - first_conn_refused_time > CONN_REFUSED_PATIENCE
390
+ ):
391
+ cli_logger.error(
392
+ "SSH connection was being refused "
393
+ "for {} seconds. Head node assumed "
394
+ "unreachable.",
395
+ cf.bold(str(CONN_REFUSED_PATIENCE)),
396
+ )
397
+ cli_logger.abort(
398
+ "Check the node's firewall settings "
399
+ "and the cloud network configuration."
400
+ )
401
+
402
+ cli_logger.warning("SSH connection was refused.")
403
+ cli_logger.warning(
404
+ "This might mean that the SSH daemon is "
405
+ "still setting up, or that "
406
+ "the host is inaccessable (e.g. due to "
407
+ "a firewall)."
408
+ )
409
+
410
+ return time.time()
411
+
412
+ if e.special_case in ["ssh_timeout", "ssh_conn_refused"]:
413
+ cli_logger.print(
414
+ "SSH still not available, retrying in {} seconds.",
415
+ cf.bold(str(retry_interval)),
416
+ )
417
+ else:
418
+ raise e
419
+
420
+ return first_conn_refused_time
vllm/lib/python3.10/site-packages/ray/autoscaler/_private/util.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import copy
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import os
7
+ import threading
8
+ from dataclasses import dataclass
9
+ from datetime import datetime
10
+ from io import StringIO
11
+ from numbers import Number, Real
12
+ from typing import Any, Dict, List, Optional, Tuple, Union
13
+
14
+ import ray
15
+ import ray._private.ray_constants as ray_constants
16
+ import ray._private.services as services
17
+ from ray._private.utils import (
18
+ PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN,
19
+ PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN,
20
+ )
21
+ from ray.autoscaler._private import constants
22
+ from ray.autoscaler._private.cli_logger import cli_logger
23
+ from ray.autoscaler._private.docker import validate_docker_config
24
+ from ray.autoscaler._private.local.config import prepare_local
25
+ from ray.autoscaler._private.providers import _get_default_config
26
+ from ray.autoscaler.tags import NODE_TYPE_LEGACY_HEAD, NODE_TYPE_LEGACY_WORKER
27
+
28
+ REQUIRED, OPTIONAL = True, False
29
+
30
+
31
+ HEAD_TYPE_MAX_WORKERS_WARN_TEMPLATE = (
32
+ "Setting `max_workers` for node type"
33
+ " `{node_type}` to the global `max_workers` value of {max_workers}. To"
34
+ " avoid spawning worker nodes of type `{node_type}`, explicitly set"
35
+ " `max_workers: 0` for `{node_type}`.\n"
36
+ "Note that `max_workers: 0` was the default value prior to Ray 1.3.0."
37
+ " Your current version is Ray {version}.\n"
38
+ "See the docs for more information:\n"
39
+ "https://docs.ray.io/en/master/cluster/config.html"
40
+ "#cluster-configuration-node-max-workers\n"
41
+ "https://docs.ray.io/en/master/cluster/config.html#full-configuration"
42
+ )
43
+
44
+ ResourceBundle = Dict[str, Union[int, float]]
45
+
46
+ # A Dict and the count of how many times it occurred.
47
+ # Refer to freq_of_dicts() below.
48
+ DictCount = Tuple[Dict, Number]
49
+
50
+ # e.g., cpu_4_ondemand.
51
+ NodeType = str
52
+
53
+ # e.g., head, worker, unmanaged
54
+ NodeKind = str
55
+
56
+ # e.g., {"resources": ..., "max_workers": ...}.
57
+ NodeTypeConfigDict = Dict[str, Any]
58
+
59
+ # e.g., {"GPU": 1}.
60
+ ResourceDict = Dict[str, Real]
61
+
62
+ # e.g., "node-1".
63
+ NodeID = str
64
+
65
+ # e.g., "127.0.0.1".
66
+ NodeIP = str
67
+
68
+ # Number of nodes to launch
69
+ NodeCount = int
70
+
71
+ # e.g. "up-to-date", "update-failed"
72
+ # See autoscaler/tags.py for other status
73
+ # values used by the autoscaler.
74
+ NodeStatus = str
75
+
76
+ Usage = Dict[str, Tuple[Number, Number]]
77
+
78
+ logger = logging.getLogger(__name__)
79
+
80
+
81
+ def is_placement_group_resource(resource_name: str) -> bool:
82
+ """
83
+ Check if a resource name is structured like a placement group.
84
+ """
85
+ return bool(
86
+ PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN.match(resource_name)
87
+ or PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN.match(resource_name)
88
+ )
89
+
90
+
91
+ @dataclass
92
+ class LoadMetricsSummary:
93
+ # Map of resource name (e.g. "memory") to pair of (Used, Available) numbers
94
+ usage: Usage
95
+ # Counts of demand bundles from task/actor demand.
96
+ # e.g. [({"CPU": 1}, 5), ({"GPU":1}, 2)]
97
+ resource_demand: List[DictCount]
98
+ # Counts of pending placement groups
99
+ pg_demand: List[DictCount]
100
+ # Counts of demand bundles requested by autoscaler.sdk.request_resources
101
+ request_demand: List[DictCount]
102
+ node_types: List[DictCount]
103
+ # Optionally included for backwards compatibility: IP of the head node. See
104
+ # https://github.com/ray-project/ray/pull/20623 for details.
105
+ head_ip: Optional[NodeIP] = None
106
+ # Optionally included for backwards compatibility: Resource breakdown by
107
+ # node. Mapping from node id to resource usage.
108
+ usage_by_node: Optional[Dict[str, Usage]] = None
109
+ # A mapping from node name (the same key as `usage_by_node`) to node type.
110
+ # Optional for deployment modes which have the concept of node types and
111
+ # backwards compatibility.
112
+ node_type_mapping: Optional[Dict[str, str]] = None
113
+ idle_time_map: Optional[Dict[str, int]] = None
114
+
115
+
116
+ class ConcurrentCounter:
117
+ def __init__(self):
118
+ self._lock = threading.RLock()
119
+ self._counter = collections.defaultdict(int)
120
+
121
+ def inc(self, key, count):
122
+ with self._lock:
123
+ self._counter[key] += count
124
+ return self.value
125
+
126
+ def dec(self, key, count):
127
+ with self._lock:
128
+ self._counter[key] -= count
129
+ assert self._counter[key] >= 0, "counter cannot go negative"
130
+ return self.value
131
+
132
+ def breakdown(self):
133
+ with self._lock:
134
+ return dict(self._counter)
135
+
136
+ @property
137
+ def value(self):
138
+ with self._lock:
139
+ return sum(self._counter.values())
140
+
141
+
142
+ def validate_config(config: Dict[str, Any]) -> None:
143
+ """Required Dicts indicate that no extra fields can be introduced."""
144
+ if not isinstance(config, dict):
145
+ raise ValueError("Config {} is not a dictionary".format(config))
146
+
147
+ schema_path = os.path.join(
148
+ os.path.dirname(ray.autoscaler.__file__), "ray-schema.json"
149
+ )
150
+ with open(schema_path) as f:
151
+ schema = json.load(f)
152
+
153
+ try:
154
+ import jsonschema
155
+ except (ModuleNotFoundError, ImportError) as e:
156
+ # Don't log a warning message here. Logging be handled by upstream.
157
+ raise e from None
158
+
159
+ try:
160
+ jsonschema.validate(config, schema)
161
+ except jsonschema.ValidationError as e:
162
+ raise e from None
163
+
164
+ # Detect out of date defaults. This happens when the autoscaler that filled
165
+ # out the default values is older than the version of the autoscaler that
166
+ # is running on the cluster.
167
+ if "cluster_synced_files" not in config:
168
+ raise RuntimeError(
169
+ "Missing 'cluster_synced_files' field in the cluster "
170
+ "configuration. This is likely due to the Ray version running "
171
+ "in the cluster {ray_version} is greater than the Ray version "
172
+ "running on your laptop. Please try updating Ray on your local "
173
+ "machine and make sure the versions match.".format(
174
+ ray_version=ray.__version__
175
+ )
176
+ )
177
+
178
+ if "available_node_types" in config:
179
+ if "head_node_type" not in config:
180
+ raise ValueError(
181
+ "You must specify `head_node_type` if `available_node_types is set."
182
+ )
183
+ if config["head_node_type"] not in config["available_node_types"]:
184
+ raise ValueError("`head_node_type` must be one of `available_node_types`.")
185
+
186
+ sum_min_workers = sum(
187
+ config["available_node_types"][node_type].get("min_workers", 0)
188
+ for node_type in config["available_node_types"]
189
+ )
190
+ if sum_min_workers > config["max_workers"]:
191
+ raise ValueError(
192
+ "The specified global `max_workers` is smaller than the "
193
+ "sum of `min_workers` of all the available node types."
194
+ )
195
+
196
+
197
+ def check_legacy_fields(config: Dict[str, Any]) -> None:
198
+ """For use in providers that have completed the migration to
199
+ available_node_types.
200
+
201
+ Warns user that head_node and worker_nodes fields are being ignored.
202
+ Throws an error if available_node_types and head_node_type aren't
203
+ specified.
204
+ """
205
+ # log warning if non-empty head_node field
206
+ if "head_node" in config and config["head_node"]:
207
+ cli_logger.warning(
208
+ "The `head_node` field is deprecated and will be ignored. "
209
+ "Use `head_node_type` and `available_node_types` instead."
210
+ )
211
+ # log warning if non-empty worker_nodes field
212
+ if "worker_nodes" in config and config["worker_nodes"]:
213
+ cli_logger.warning(
214
+ "The `worker_nodes` field is deprecated and will be ignored. "
215
+ "Use `available_node_types` instead."
216
+ )
217
+ if "available_node_types" not in config:
218
+ cli_logger.error("`available_node_types` not specified in config")
219
+ raise ValueError("`available_node_types` not specified in config")
220
+ if "head_node_type" not in config:
221
+ cli_logger.error("`head_node_type` not specified in config")
222
+ raise ValueError("`head_node_type` not specified in config")
223
+
224
+
225
+ def prepare_config(config: Dict[str, Any]) -> Dict[str, Any]:
226
+ """
227
+ The returned config has the following properties:
228
+ - Uses the multi-node-type autoscaler configuration.
229
+ - Merged with the appropriate defaults.yaml
230
+ - Has a valid Docker configuration if provided.
231
+ - Has max_worker set for each node type.
232
+ """
233
+ is_local = config.get("provider", {}).get("type") == "local"
234
+ is_kuberay = config.get("provider", {}).get("type") == "kuberay"
235
+ if is_local:
236
+ config = prepare_local(config)
237
+ elif is_kuberay:
238
+ # With KubeRay, we don't need to do anything here since KubeRay
239
+ # generate the autoscaler config from the RayCluster CR instead
240
+ # of loading from the files.
241
+ return config
242
+
243
+ with_defaults = fillout_defaults(config)
244
+ merge_setup_commands(with_defaults)
245
+ validate_docker_config(with_defaults)
246
+ fill_node_type_min_max_workers(with_defaults)
247
+ return with_defaults
248
+
249
+
250
+ def translate_trivial_legacy_config(config: Dict[str, Any]):
251
+ """
252
+ Drop empty deprecated fields ("head_node" and "worker_node").
253
+ """
254
+
255
+ REMOVABLE_FIELDS = ["head_node", "worker_nodes"]
256
+
257
+ for field in REMOVABLE_FIELDS:
258
+ if field in config and not config[field]:
259
+ logger.warning(
260
+ f"Dropping the empty legacy field {field}. {field}"
261
+ "is not supported for ray>=2.0.0. It is recommended to remove"
262
+ f"{field} from the cluster config."
263
+ )
264
+ del config[field]
265
+
266
+
267
+ def fillout_defaults(config: Dict[str, Any]) -> Dict[str, Any]:
268
+ defaults = _get_default_config(config["provider"])
269
+ defaults.update(config)
270
+
271
+ # Just for clarity:
272
+ merged_config = copy.deepcopy(defaults)
273
+
274
+ # Fill auth field to avoid key errors.
275
+ # This field is accessed when calling NodeUpdater but is not relevant to
276
+ # certain node providers and is thus left out of some cluster launching
277
+ # configs.
278
+ merged_config["auth"] = merged_config.get("auth", {})
279
+
280
+ # A legacy config is one which doesn't have available_node_types,
281
+ # but has at least one of head_node or worker_nodes.
282
+ is_legacy_config = ("available_node_types" not in config) and (
283
+ "head_node" in config or "worker_nodes" in config
284
+ )
285
+ # Do merging logic for legacy configs.
286
+ if is_legacy_config:
287
+ merged_config = merge_legacy_yaml_with_defaults(merged_config)
288
+ # Take care of this here, in case a config does not specify any of head,
289
+ # workers, node types, but does specify min workers:
290
+ merged_config.pop("min_workers", None)
291
+
292
+ translate_trivial_legacy_config(merged_config)
293
+
294
+ return merged_config
295
+
296
+
297
+ def merge_legacy_yaml_with_defaults(merged_config: Dict[str, Any]) -> Dict[str, Any]:
298
+ """Rewrite legacy config's available node types after it has been merged
299
+ with defaults yaml.
300
+ """
301
+ cli_logger.warning(
302
+ "Converting legacy cluster config to a multi node type cluster "
303
+ "config. Multi-node-type cluster configs are the recommended "
304
+ "format for configuring Ray clusters. "
305
+ "See the docs for more information:\n"
306
+ "https://docs.ray.io/en/master/cluster/config.html#full-configuration"
307
+ )
308
+
309
+ # Get default head and worker types.
310
+ default_head_type = merged_config["head_node_type"]
311
+ # Default configs are assumed to have two node types -- one for the head
312
+ # and one for the workers.
313
+ assert len(merged_config["available_node_types"].keys()) == 2
314
+ default_worker_type = (
315
+ merged_config["available_node_types"].keys() - {default_head_type}
316
+ ).pop()
317
+
318
+ if merged_config["head_node"]:
319
+ # User specified a head node in legacy config.
320
+ # Convert it into data for the head's node type.
321
+ head_node_info = {
322
+ "node_config": merged_config["head_node"],
323
+ "resources": merged_config["head_node"].get("resources") or {},
324
+ "min_workers": 0,
325
+ "max_workers": 0,
326
+ }
327
+ else:
328
+ # Use default data for the head's node type.
329
+ head_node_info = merged_config["available_node_types"][default_head_type]
330
+ if merged_config["worker_nodes"]:
331
+ # User specified a worker node in legacy config.
332
+ # Convert it into data for the workers' node type.
333
+ worker_node_info = {
334
+ "node_config": merged_config["worker_nodes"],
335
+ "resources": merged_config["worker_nodes"].get("resources") or {},
336
+ "min_workers": merged_config.get("min_workers", 0),
337
+ "max_workers": merged_config["max_workers"],
338
+ }
339
+ else:
340
+ # Use default data for the workers' node type.
341
+ worker_node_info = merged_config["available_node_types"][default_worker_type]
342
+
343
+ # Rewrite available_node_types.
344
+ merged_config["available_node_types"] = {
345
+ NODE_TYPE_LEGACY_HEAD: head_node_info,
346
+ NODE_TYPE_LEGACY_WORKER: worker_node_info,
347
+ }
348
+ merged_config["head_node_type"] = NODE_TYPE_LEGACY_HEAD
349
+
350
+ # Resources field in head/worker fields cause node launch to fail.
351
+ merged_config["head_node"].pop("resources", None)
352
+ merged_config["worker_nodes"].pop("resources", None)
353
+
354
+ return merged_config
355
+
356
+
357
+ def merge_setup_commands(config):
358
+ config["head_setup_commands"] = (
359
+ config["setup_commands"] + config["head_setup_commands"]
360
+ )
361
+ config["worker_setup_commands"] = (
362
+ config["setup_commands"] + config["worker_setup_commands"]
363
+ )
364
+ return config
365
+
366
+
367
+ def fill_node_type_min_max_workers(config):
368
+ """Sets default per-node max workers to global max_workers.
369
+ This equivalent to setting the default per-node max workers to infinity,
370
+ with the only upper constraint coming from the global max_workers.
371
+ Sets default per-node min workers to zero.
372
+ Also sets default max_workers for the head node to zero.
373
+ """
374
+ assert "max_workers" in config, "Global max workers should be set."
375
+ node_types = config["available_node_types"]
376
+ for node_type_name in node_types:
377
+ node_type_data = node_types[node_type_name]
378
+
379
+ node_type_data.setdefault("min_workers", 0)
380
+ if "max_workers" not in node_type_data:
381
+ if node_type_name == config["head_node_type"]:
382
+ logger.info("setting max workers for head node type to 0")
383
+ node_type_data.setdefault("max_workers", 0)
384
+ else:
385
+ global_max_workers = config["max_workers"]
386
+ logger.info(
387
+ f"setting max workers for {node_type_name} to "
388
+ f"{global_max_workers}"
389
+ )
390
+ node_type_data.setdefault("max_workers", global_max_workers)
391
+
392
+
393
+ def with_envs(cmds: List[str], kv: Dict[str, str]) -> str:
394
+ """
395
+ Returns a list of commands with the given environment variables set.
396
+
397
+ Args:
398
+ cmds (List[str]): List of commands to set environment variables for.
399
+ kv (Dict[str, str]): Dictionary of environment variables to set.
400
+
401
+ Returns:
402
+ List[str]: List of commands with the given environment variables set.
403
+
404
+ Example:
405
+ with_envs(["echo $FOO"], {"FOO": "BAR"})
406
+ -> ["export FOO=BAR; echo $FOO"]
407
+ """
408
+ out_cmds = []
409
+ for cmd in cmds:
410
+ kv_str = ""
411
+ for k, v in kv.items():
412
+ # We will need to do export here so that it works correctly with
413
+ # shell if the cmd args uses the argument.
414
+ kv_str += f"export {k}={v}; "
415
+
416
+ out_cmds.append(f"{kv_str}{cmd}")
417
+ return out_cmds
418
+
419
+
420
+ def with_head_node_ip(cmds, head_ip=None):
421
+ if head_ip is None:
422
+ head_ip = services.get_node_ip_address()
423
+ return with_envs(cmds, {"RAY_HEAD_IP": head_ip})
424
+
425
+
426
+ def hash_launch_conf(node_conf, auth):
427
+ hasher = hashlib.sha1()
428
+ # For hashing, we replace the path to the key with the
429
+ # key itself. This is to make sure the hashes are the
430
+ # same even if keys live at different locations on different
431
+ # machines.
432
+ full_auth = auth.copy()
433
+ for key_type in ["ssh_private_key", "ssh_public_key"]:
434
+ if key_type in auth:
435
+ with open(os.path.expanduser(auth[key_type])) as key:
436
+ full_auth[key_type] = key.read()
437
+ hasher.update(json.dumps([node_conf, full_auth], sort_keys=True).encode("utf-8"))
438
+ return hasher.hexdigest()
439
+
440
+
441
+ # Cache the file hashes to avoid rescanning it each time. Also, this avoids
442
+ # inadvertently restarting workers if the file mount content is mutated on the
443
+ # head node.
444
+ _hash_cache = {}
445
+
446
+
447
+ def hash_runtime_conf(
448
+ file_mounts,
449
+ cluster_synced_files,
450
+ extra_objs,
451
+ generate_file_mounts_contents_hash=False,
452
+ ):
453
+ """Returns two hashes, a runtime hash and file_mounts_content hash.
454
+
455
+ The runtime hash is used to determine if the configuration or file_mounts
456
+ contents have changed. It is used at launch time (ray up) to determine if
457
+ a restart is needed.
458
+
459
+ The file_mounts_content hash is used to determine if the file_mounts or
460
+ cluster_synced_files contents have changed. It is used at monitor time to
461
+ determine if additional file syncing is needed.
462
+ """
463
+ runtime_hasher = hashlib.sha1()
464
+ contents_hasher = hashlib.sha1()
465
+
466
+ def add_content_hashes(path, allow_non_existing_paths: bool = False):
467
+ def add_hash_of_file(fpath):
468
+ with open(fpath, "rb") as f:
469
+ for chunk in iter(lambda: f.read(2**20), b""):
470
+ contents_hasher.update(chunk)
471
+
472
+ path = os.path.expanduser(path)
473
+ if allow_non_existing_paths and not os.path.exists(path):
474
+ return
475
+ if os.path.isdir(path):
476
+ dirs = []
477
+ for dirpath, _, filenames in os.walk(path):
478
+ dirs.append((dirpath, sorted(filenames)))
479
+ for dirpath, filenames in sorted(dirs):
480
+ contents_hasher.update(dirpath.encode("utf-8"))
481
+ for name in filenames:
482
+ contents_hasher.update(name.encode("utf-8"))
483
+ fpath = os.path.join(dirpath, name)
484
+ add_hash_of_file(fpath)
485
+ else:
486
+ add_hash_of_file(path)
487
+
488
+ conf_str = json.dumps(file_mounts, sort_keys=True).encode("utf-8") + json.dumps(
489
+ extra_objs, sort_keys=True
490
+ ).encode("utf-8")
491
+
492
+ # Only generate a contents hash if generate_contents_hash is true or
493
+ # if we need to generate the runtime_hash
494
+ if conf_str not in _hash_cache or generate_file_mounts_contents_hash:
495
+ for local_path in sorted(file_mounts.values()):
496
+ add_content_hashes(local_path)
497
+ head_node_contents_hash = contents_hasher.hexdigest()
498
+
499
+ # Generate a new runtime_hash if its not cached
500
+ # The runtime hash does not depend on the cluster_synced_files hash
501
+ # because we do not want to restart nodes only if cluster_synced_files
502
+ # contents have changed.
503
+ if conf_str not in _hash_cache:
504
+ runtime_hasher.update(conf_str)
505
+ runtime_hasher.update(head_node_contents_hash.encode("utf-8"))
506
+ _hash_cache[conf_str] = runtime_hasher.hexdigest()
507
+
508
+ # Add cluster_synced_files to the file_mounts_content hash
509
+ if cluster_synced_files is not None:
510
+ for local_path in sorted(cluster_synced_files):
511
+ # For cluster_synced_files, we let the path be non-existant
512
+ # because its possible that the source directory gets set up
513
+ # anytime over the life of the head node.
514
+ add_content_hashes(local_path, allow_non_existing_paths=True)
515
+
516
+ file_mounts_contents_hash = contents_hasher.hexdigest()
517
+
518
+ else:
519
+ file_mounts_contents_hash = None
520
+
521
+ return (_hash_cache[conf_str], file_mounts_contents_hash)
522
+
523
+
524
+ def add_prefix(info_string, prefix):
525
+ """Prefixes each line of info_string, except the first, by prefix."""
526
+ lines = info_string.split("\n")
527
+ prefixed_lines = [lines[0]]
528
+ for line in lines[1:]:
529
+ prefixed_line = ":".join([prefix, line])
530
+ prefixed_lines.append(prefixed_line)
531
+ prefixed_info_string = "\n".join(prefixed_lines)
532
+ return prefixed_info_string
533
+
534
+
535
+ def format_pg(pg):
536
+ strategy = pg["strategy"]
537
+ bundles = pg["bundles"]
538
+ shape_strs = []
539
+ for bundle, count in bundles:
540
+ shape_strs.append(f"{bundle} * {count}")
541
+ bundles_str = ", ".join(shape_strs)
542
+ return f"{bundles_str} ({strategy})"
543
+
544
+
545
+ def parse_placement_group_resource_str(
546
+ placement_group_resource_str: str,
547
+ ) -> Tuple[str, Optional[str], bool]:
548
+ """Parse placement group resource in the form of following 3 cases:
549
+ {resource_name}_group_{bundle_id}_{group_name};
550
+ -> This case is ignored as it is duplicated to the case below.
551
+ {resource_name}_group_{group_name};
552
+ {resource_name}
553
+
554
+ Returns:
555
+ Tuple of (resource_name, placement_group_name, is_countable_resource).
556
+ placement_group_name could be None if its not a placement group
557
+ resource. is_countable_resource is True if the resource
558
+ doesn't contain bundle index. We shouldn't count resources
559
+ with bundle index because it will
560
+ have duplicated resource information as
561
+ wildcard resources (resource name without bundle index).
562
+ """
563
+ result = PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN.match(
564
+ placement_group_resource_str
565
+ )
566
+ if result:
567
+ return (result.group(1), result.group(3), False)
568
+ result = PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN.match(
569
+ placement_group_resource_str
570
+ )
571
+ if result:
572
+ return (result.group(1), result.group(2), True)
573
+ return (placement_group_resource_str, None, True)
574
+
575
+
576
+ MEMORY_SUFFIXES = [
577
+ ("TiB", 2**40),
578
+ ("GiB", 2**30),
579
+ ("MiB", 2**20),
580
+ ("KiB", 2**10),
581
+ ]
582
+
583
+
584
+ def format_memory(mem_bytes: Number) -> str:
585
+ """Formats memory in bytes in friendly unit. E.g. (2**30 + 1) bytes should
586
+ be displayed as 1GiB but 1 byte should be displayed as 1B, (as opposed to
587
+ rounding it to 0GiB).
588
+ """
589
+ for suffix, bytes_per_unit in MEMORY_SUFFIXES:
590
+ if mem_bytes >= bytes_per_unit:
591
+ mem_in_unit = mem_bytes / bytes_per_unit
592
+ return f"{mem_in_unit:.2f}{suffix}"
593
+
594
+ return f"{int(mem_bytes)}B"
595
+
596
+
597
+ def parse_usage(usage: Usage, verbose: bool) -> List[str]:
598
+ # first collect resources used in placement groups
599
+ placement_group_resource_usage = {}
600
+ placement_group_resource_total = collections.defaultdict(float)
601
+ for resource, (used, total) in usage.items():
602
+ (pg_resource_name, pg_name, is_countable) = parse_placement_group_resource_str(
603
+ resource
604
+ )
605
+ if pg_name:
606
+ if pg_resource_name not in placement_group_resource_usage:
607
+ placement_group_resource_usage[pg_resource_name] = 0
608
+ if is_countable:
609
+ placement_group_resource_usage[pg_resource_name] += used
610
+ placement_group_resource_total[pg_resource_name] += total
611
+ continue
612
+ usage_lines = []
613
+ for resource, (used, total) in sorted(usage.items()):
614
+ if "node:" in resource:
615
+ continue # Skip the auto-added per-node "node:<ip>" resource.
616
+
617
+ (_, pg_name, _) = parse_placement_group_resource_str(resource)
618
+ if pg_name:
619
+ continue # Skip resource used by placement groups
620
+
621
+ pg_used = 0
622
+ pg_total = 0
623
+ used_in_pg = resource in placement_group_resource_usage
624
+ if used_in_pg:
625
+ pg_used = placement_group_resource_usage[resource]
626
+ pg_total = placement_group_resource_total[resource]
627
+ # Used includes pg_total because when pgs are created
628
+ # it allocates resources.
629
+ # To get the real resource usage, we should subtract the pg
630
+ # reserved resources from the usage and add pg used instead.
631
+ used = used - pg_total + pg_used
632
+
633
+ if resource in ["memory", "object_store_memory"]:
634
+ formatted_used = format_memory(used)
635
+ formatted_total = format_memory(total)
636
+ line = f"{formatted_used}/{formatted_total} {resource}"
637
+ if used_in_pg:
638
+ formatted_pg_used = format_memory(pg_used)
639
+ formatted_pg_total = format_memory(pg_total)
640
+ line = line + (
641
+ f" ({formatted_pg_used} used of "
642
+ f"{formatted_pg_total} " + "reserved in placement groups)"
643
+ )
644
+ usage_lines.append(line)
645
+ elif resource.startswith("accelerator_type:") and not verbose:
646
+ # We made a judgement call not to show this.
647
+ # https://github.com/ray-project/ray/issues/33272
648
+ pass
649
+ else:
650
+ line = f"{used}/{total} {resource}"
651
+ if used_in_pg:
652
+ line += (
653
+ f" ({pg_used} used of " f"{pg_total} reserved in placement groups)"
654
+ )
655
+ usage_lines.append(line)
656
+ return usage_lines
657
+
658
+
659
+ def get_usage_report(lm_summary: LoadMetricsSummary, verbose: bool) -> str:
660
+ usage_lines = parse_usage(lm_summary.usage, verbose)
661
+
662
+ sio = StringIO()
663
+ for line in usage_lines:
664
+ print(f" {line}", file=sio)
665
+ return sio.getvalue()
666
+
667
+
668
+ def format_resource_demand_summary(
669
+ resource_demand: List[Tuple[ResourceBundle, int]]
670
+ ) -> List[str]:
671
+ def filter_placement_group_from_bundle(bundle: ResourceBundle):
672
+ """filter placement group from bundle resource name. returns
673
+ filtered bundle and a bool indicate if the bundle is using
674
+ placement group.
675
+
676
+ Example: {"CPU_group_groupid": 1} returns {"CPU": 1}, True
677
+ {"memory": 1} return {"memory": 1}, False
678
+ """
679
+ using_placement_group = False
680
+ result_bundle = dict()
681
+ for pg_resource_str, resource_count in bundle.items():
682
+ (resource_name, pg_name, _) = parse_placement_group_resource_str(
683
+ pg_resource_str
684
+ )
685
+ result_bundle[resource_name] = resource_count
686
+ if pg_name:
687
+ using_placement_group = True
688
+ return (result_bundle, using_placement_group)
689
+
690
+ bundle_demand = collections.defaultdict(int)
691
+ pg_bundle_demand = collections.defaultdict(int)
692
+
693
+ for bundle, count in resource_demand:
694
+ (
695
+ pg_filtered_bundle,
696
+ using_placement_group,
697
+ ) = filter_placement_group_from_bundle(bundle)
698
+
699
+ # bundle is a special keyword for placement group scheduling
700
+ # but it doesn't need to be exposed to users. Remove it from
701
+ # the demand report.
702
+ if (
703
+ using_placement_group
704
+ and ray_constants.PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME
705
+ in pg_filtered_bundle.keys()
706
+ ):
707
+ del pg_filtered_bundle[ray_constants.PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME]
708
+
709
+ # No need to report empty request to demand (e.g.,
710
+ # placement group ready task).
711
+ if len(pg_filtered_bundle.keys()) == 0:
712
+ continue
713
+
714
+ bundle_demand[tuple(sorted(pg_filtered_bundle.items()))] += count
715
+ if using_placement_group:
716
+ pg_bundle_demand[tuple(sorted(pg_filtered_bundle.items()))] += count
717
+
718
+ demand_lines = []
719
+ for bundle, count in bundle_demand.items():
720
+ line = f" {dict(bundle)}: {count}+ pending tasks/actors"
721
+ if bundle in pg_bundle_demand:
722
+ line += f" ({pg_bundle_demand[bundle]}+ using placement groups)"
723
+ demand_lines.append(line)
724
+ return demand_lines
725
+
726
+
727
+ def get_demand_report(lm_summary: LoadMetricsSummary):
728
+ demand_lines = []
729
+ if lm_summary.resource_demand:
730
+ demand_lines.extend(format_resource_demand_summary(lm_summary.resource_demand))
731
+ for entry in lm_summary.pg_demand:
732
+ pg, count = entry
733
+ pg_str = format_pg(pg)
734
+ line = f" {pg_str}: {count}+ pending placement groups"
735
+ demand_lines.append(line)
736
+ for bundle, count in lm_summary.request_demand:
737
+ line = f" {bundle}: {count}+ from request_resources()"
738
+ demand_lines.append(line)
739
+ if len(demand_lines) > 0:
740
+ demand_report = "\n".join(demand_lines)
741
+ else:
742
+ demand_report = " (no resource demands)"
743
+ return demand_report
744
+
745
+
746
+ def get_per_node_breakdown_as_dict(
747
+ lm_summary: LoadMetricsSummary,
748
+ ) -> dict:
749
+ per_node_breakdown = {}
750
+
751
+ for node_id, usage in lm_summary.usage_by_node.items():
752
+ usage_string = ""
753
+ for line in parse_usage(usage, verbose=True):
754
+ usage_string += f"{line}\n"
755
+ per_node_breakdown[node_id] = usage_string.strip()
756
+
757
+ return per_node_breakdown
758
+
759
+
760
+ def get_per_node_breakdown(
761
+ lm_summary: LoadMetricsSummary,
762
+ node_type_mapping: Optional[Dict[str, float]],
763
+ node_activities: Optional[Dict[str, List[str]]],
764
+ verbose: bool,
765
+ ) -> str:
766
+ sio = StringIO()
767
+
768
+ if node_type_mapping is None:
769
+ node_type_mapping = {}
770
+
771
+ print(file=sio)
772
+ for node_id, usage in lm_summary.usage_by_node.items():
773
+ print(file=sio) # Print a newline.
774
+ node_string = f"Node: {node_id}"
775
+ if node_id in node_type_mapping:
776
+ node_type = node_type_mapping[node_id]
777
+ node_string += f" ({node_type})"
778
+ print(node_string, file=sio)
779
+ if (
780
+ lm_summary.idle_time_map
781
+ and node_id in lm_summary.idle_time_map
782
+ and lm_summary.idle_time_map[node_id] > 0
783
+ ):
784
+ print(f" Idle: {lm_summary.idle_time_map[node_id]} ms", file=sio)
785
+
786
+ print(" Usage:", file=sio)
787
+ for line in parse_usage(usage, verbose):
788
+ print(f" {line}", file=sio)
789
+ # Don't print anything if not provided.
790
+ if not node_activities:
791
+ continue
792
+ print(" Activity:", file=sio)
793
+ if node_id not in node_activities:
794
+ print(" (no activity)", file=sio)
795
+ else:
796
+ # Note: We have node IP here.
797
+ _, reasons = node_activities[node_id]
798
+ for reason in reasons:
799
+ print(f" {reason}", file=sio)
800
+
801
+ return sio.getvalue()
802
+
803
+
804
+ def format_info_string(
805
+ lm_summary,
806
+ autoscaler_summary,
807
+ time=None,
808
+ gcs_request_time: Optional[float] = None,
809
+ non_terminated_nodes_time: Optional[float] = None,
810
+ autoscaler_update_time: Optional[float] = None,
811
+ verbose: bool = False,
812
+ ):
813
+ if time is None:
814
+ time = datetime.now()
815
+ header = "=" * 8 + f" Autoscaler status: {time} " + "=" * 8
816
+ separator = "-" * len(header)
817
+ if verbose:
818
+ header += "\n"
819
+ if gcs_request_time:
820
+ header += f"GCS request time: {gcs_request_time:3f}s\n"
821
+ if non_terminated_nodes_time:
822
+ header += (
823
+ "Node Provider non_terminated_nodes time: "
824
+ f"{non_terminated_nodes_time:3f}s\n"
825
+ )
826
+ if autoscaler_update_time:
827
+ header += "Autoscaler iteration time: " f"{autoscaler_update_time:3f}s\n"
828
+
829
+ available_node_report_lines = []
830
+ if not autoscaler_summary.active_nodes:
831
+ available_node_report = " (no active nodes)"
832
+ else:
833
+ for node_type, count in autoscaler_summary.active_nodes.items():
834
+ line = f" {count} {node_type}"
835
+ available_node_report_lines.append(line)
836
+ available_node_report = "\n".join(available_node_report_lines)
837
+
838
+ if not autoscaler_summary.idle_nodes:
839
+ idle_node_report = " (no idle nodes)"
840
+ else:
841
+ idle_node_report_lines = []
842
+ for node_type, count in autoscaler_summary.idle_nodes.items():
843
+ line = f" {count} {node_type}"
844
+ idle_node_report_lines.append(line)
845
+ idle_node_report = "\n".join(idle_node_report_lines)
846
+
847
+ pending_lines = []
848
+ for node_type, count in autoscaler_summary.pending_launches.items():
849
+ line = f" {node_type}, {count} launching"
850
+ pending_lines.append(line)
851
+ for ip, node_type, status in autoscaler_summary.pending_nodes:
852
+ line = f" {ip}: {node_type}, {status.lower()}"
853
+ pending_lines.append(line)
854
+ if pending_lines:
855
+ pending_report = "\n".join(pending_lines)
856
+ else:
857
+ pending_report = " (no pending nodes)"
858
+
859
+ failure_lines = []
860
+ for ip, node_type in autoscaler_summary.failed_nodes:
861
+ line = f" {node_type}: NodeTerminated (ip: {ip})"
862
+ failure_lines.append(line)
863
+ if autoscaler_summary.node_availability_summary:
864
+ records = sorted(
865
+ autoscaler_summary.node_availability_summary.node_availabilities.values(),
866
+ key=lambda record: record.last_checked_timestamp,
867
+ )
868
+ for record in records:
869
+ if record.is_available:
870
+ continue
871
+ assert record.unavailable_node_information is not None
872
+ node_type = record.node_type
873
+ category = record.unavailable_node_information.category
874
+ description = record.unavailable_node_information.description
875
+ attempted_time = datetime.fromtimestamp(record.last_checked_timestamp)
876
+ formatted_time = (
877
+ # This `:02d` funny business is python syntax for printing a 2
878
+ # digit number with a leading zero as padding if needed.
879
+ f"{attempted_time.hour:02d}:"
880
+ f"{attempted_time.minute:02d}:"
881
+ f"{attempted_time.second:02d}"
882
+ )
883
+ line = f" {node_type}: {category} (latest_attempt: {formatted_time})"
884
+ if verbose:
885
+ line += f" - {description}"
886
+ failure_lines.append(line)
887
+
888
+ failure_lines = failure_lines[: -constants.AUTOSCALER_MAX_FAILURES_DISPLAYED : -1]
889
+ failure_report = "Recent failures:\n"
890
+ if failure_lines:
891
+ failure_report += "\n".join(failure_lines)
892
+ else:
893
+ failure_report += " (no failures)"
894
+
895
+ usage_report = get_usage_report(lm_summary, verbose)
896
+ demand_report = get_demand_report(lm_summary)
897
+ formatted_output = f"""{header}
898
+ Node status
899
+ {separator}
900
+ Active:
901
+ {available_node_report}"""
902
+
903
+ if not autoscaler_summary.legacy:
904
+ formatted_output += f"""
905
+ Idle:
906
+ {idle_node_report}"""
907
+
908
+ formatted_output += f"""
909
+ Pending:
910
+ {pending_report}
911
+ {failure_report}
912
+
913
+ Resources
914
+ {separator}
915
+ {"Total " if verbose else ""}Usage:
916
+ {usage_report}
917
+ {"Total " if verbose else ""}Demands:
918
+ {demand_report}"""
919
+
920
+ if verbose:
921
+ if lm_summary.usage_by_node:
922
+ formatted_output += get_per_node_breakdown(
923
+ lm_summary,
924
+ autoscaler_summary.node_type_mapping,
925
+ autoscaler_summary.node_activities,
926
+ verbose,
927
+ )
928
+ else:
929
+ formatted_output += "\n"
930
+
931
+ return formatted_output.strip()
932
+
933
+
934
+ def format_readonly_node_type(node_id: str):
935
+ """The anonymous node type for readonly node provider nodes."""
936
+ return "node_{}".format(node_id)
937
+
938
+
939
+ def format_no_node_type_string(node_type: dict):
940
+ placement_group_resource_usage = {}
941
+ regular_resource_usage = collections.defaultdict(float)
942
+ for resource, total in node_type.items():
943
+ (pg_resource_name, pg_name, is_countable) = parse_placement_group_resource_str(
944
+ resource
945
+ )
946
+ if pg_name:
947
+ if not is_countable:
948
+ continue
949
+ if pg_resource_name not in placement_group_resource_usage:
950
+ placement_group_resource_usage[pg_resource_name] = 0
951
+ placement_group_resource_usage[pg_resource_name] += total
952
+ else:
953
+ regular_resource_usage[resource] += total
954
+
955
+ output_lines = [""]
956
+ for resource, total in regular_resource_usage.items():
957
+ output_line = f"{resource}: {total}"
958
+ if resource in placement_group_resource_usage:
959
+ pg_resource = placement_group_resource_usage[resource]
960
+ output_line += f" ({pg_resource} reserved in placement groups)"
961
+ output_lines.append(output_line)
962
+
963
+ return "\n ".join(output_lines)
vllm/lib/python3.10/site-packages/ray/autoscaler/aliyun/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/aliyun/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/batching_node_provider.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from collections import defaultdict
3
+ from dataclasses import dataclass, field
4
+ from typing import Any, Dict, List, Optional, Set
5
+
6
+ from ray.autoscaler._private.constants import (
7
+ DISABLE_LAUNCH_CONFIG_CHECK_KEY,
8
+ DISABLE_NODE_UPDATERS_KEY,
9
+ FOREGROUND_NODE_LAUNCH_KEY,
10
+ )
11
+ from ray.autoscaler._private.util import NodeID, NodeIP, NodeKind, NodeStatus, NodeType
12
+ from ray.autoscaler.node_provider import NodeProvider
13
+ from ray.autoscaler.tags import (
14
+ NODE_KIND_HEAD,
15
+ TAG_RAY_NODE_KIND,
16
+ TAG_RAY_NODE_STATUS,
17
+ TAG_RAY_REPLICA_INDEX,
18
+ TAG_RAY_USER_NODE_TYPE,
19
+ )
20
+
21
+ provider_exists = False
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ @dataclass
27
+ class ScaleRequest:
28
+ """Stores desired scale computed by the autoscaler.
29
+
30
+ Attributes:
31
+ desired_num_workers: Map of worker NodeType to desired number of workers of
32
+ that type.
33
+ workers_to_delete: List of ids of nodes that should be removed.
34
+ """
35
+
36
+ desired_num_workers: Dict[NodeType, int] = field(default_factory=dict)
37
+ workers_to_delete: Set[NodeID] = field(default_factory=set)
38
+
39
+
40
+ @dataclass
41
+ class NodeData:
42
+ """Stores all data about a Ray node needed by the autoscaler.
43
+
44
+ Attributes:
45
+ kind: Whether the node is the head or a worker.
46
+ type: The user-defined type of the node.
47
+ replica_index: An identifier for nodes in a replica of a TPU worker group.
48
+ This value is set as a Pod label by a GKE webhook when TPUs are requested
49
+ ip: Cluster-internal ip of the node. ip can be None if the ip
50
+ has not yet been assigned.
51
+ status: The status of the node. You must adhere to the following semantics
52
+ for status:
53
+ * The status must be "up-to-date" if and only if the node is running.
54
+ * The status must be "update-failed" if and only if the node is in an
55
+ unknown or failed state.
56
+ * If the node is in a pending (starting-up) state, the status should be
57
+ a brief user-facing description of why the node is pending.
58
+ """
59
+
60
+ kind: NodeKind
61
+ type: NodeType
62
+ ip: Optional[NodeIP]
63
+ status: NodeStatus
64
+ replica_index: Optional[str] = None
65
+
66
+
67
+ class BatchingNodeProvider(NodeProvider):
68
+ """Abstract subclass of NodeProvider meant for use with external cluster managers.
69
+
70
+ Batches reads of cluster state into a single method, get_node_data, called at the
71
+ start of an autoscaling update.
72
+
73
+ Batches modifications to cluster state into a single method, submit_scale_request,
74
+ called at the end of an autoscaling update.
75
+
76
+ Implementing a concrete subclass of BatchingNodeProvider only requires overriding
77
+ get_node_data() and submit_scale_request().
78
+
79
+ See the method docstrings for more information.
80
+
81
+ Note that an autoscaling update may be conditionally
82
+ cancelled using the optional method safe_to_scale()
83
+ of the root NodeProvider.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ provider_config: Dict[str, Any],
89
+ cluster_name: str,
90
+ _allow_multiple: bool = False,
91
+ ) -> None:
92
+ NodeProvider.__init__(self, provider_config, cluster_name)
93
+ self.node_data_dict: Dict[NodeID, NodeData] = {}
94
+
95
+ # Disallow multiple node providers, unless explicitly allowed for testing.
96
+ global provider_exists
97
+ if not _allow_multiple:
98
+ assert (
99
+ not provider_exists
100
+ ), "Only one BatchingNodeProvider allowed per process."
101
+
102
+ # These flags enforce correct behavior for single-threaded node providers
103
+ # which interact with external cluster managers:
104
+ assert (
105
+ provider_config.get(DISABLE_NODE_UPDATERS_KEY, False) is True
106
+ ), f"To use BatchingNodeProvider, must set `{DISABLE_NODE_UPDATERS_KEY}:True`."
107
+ assert provider_config.get(DISABLE_LAUNCH_CONFIG_CHECK_KEY, False) is True, (
108
+ "To use BatchingNodeProvider, must set "
109
+ f"`{DISABLE_LAUNCH_CONFIG_CHECK_KEY}:True`."
110
+ )
111
+ assert (
112
+ provider_config.get(FOREGROUND_NODE_LAUNCH_KEY, False) is True
113
+ ), f"To use BatchingNodeProvider, must set `{FOREGROUND_NODE_LAUNCH_KEY}:True`."
114
+
115
+ # self.scale_change_needed tracks whether we need to update scale.
116
+ # set to True in create_node and terminate_nodes calls
117
+ # reset to False in non_terminated_nodes, which occurs at the start of the
118
+ # autoscaling update. For good measure, also set to false in post_process.
119
+ self.scale_change_needed = False
120
+
121
+ self.scale_request = ScaleRequest()
122
+
123
+ # Initialize map of replica indices to nodes in that replica
124
+ self.replica_index_to_nodes = defaultdict(list[str])
125
+
126
+ def get_node_data(self) -> Dict[NodeID, NodeData]:
127
+ """Queries cluster manager for node info. Returns a mapping from node id to
128
+ NodeData.
129
+
130
+ Each NodeData value must adhere to the semantics of the NodeData docstring.
131
+ (Note in particular the requirements for NodeData.status.)
132
+
133
+ Consistency requirement:
134
+ If a node id was present in ScaleRequest.workers_to_delete of a previously
135
+ submitted scale request, it should no longer be present as a key in
136
+ get_node_data.
137
+ (Node termination must be registered immediately when submit_scale_request
138
+ returns.)
139
+ """
140
+ raise NotImplementedError
141
+
142
+ def submit_scale_request(self, scale_request: ScaleRequest) -> None:
143
+ """Tells the cluster manager which nodes to delete and how many nodes of
144
+ each node type to maintain.
145
+
146
+ Consistency requirement:
147
+ If a node id was present in ScaleRequest.workers_to_delete of a previously
148
+ submitted scale request, it should no longer be present as key in get_node_data.
149
+ (Node termination must be registered immediately when submit_scale_request
150
+ returns.)
151
+ """
152
+ raise NotImplementedError
153
+
154
+ def post_process(self) -> None:
155
+ """Submit a scale request if it is necessary to do so."""
156
+ if self.scale_change_needed:
157
+ self.submit_scale_request(self.scale_request)
158
+ self.scale_change_needed = False
159
+
160
+ def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]:
161
+ self.scale_change_needed = False
162
+ self.node_data_dict = self.get_node_data()
163
+
164
+ # Initialize ScaleRequest
165
+ self.scale_request = ScaleRequest(
166
+ desired_num_workers=self.cur_num_workers(), # Current scale
167
+ workers_to_delete=set(), # No workers to delete yet
168
+ )
169
+ all_nodes = list(self.node_data_dict.keys())
170
+ self.replica_index_to_nodes.clear()
171
+ for node_id in all_nodes:
172
+ replica_index = self.node_data_dict[node_id].replica_index
173
+ # Only add node to map if it belongs to a multi-host podslice
174
+ if replica_index is not None:
175
+ self.replica_index_to_nodes[replica_index].append(node_id)
176
+ # Support filtering by TAG_RAY_NODE_KIND, TAG_RAY_NODE_STATUS, and
177
+ # TAG_RAY_USER_NODE_TYPE.
178
+ # The autoscaler only uses tag_filters={},
179
+ # but filtering by the these keys is useful for testing.
180
+ filtered_nodes = [
181
+ node
182
+ for node in all_nodes
183
+ if tag_filters.items() <= self.node_tags(node).items()
184
+ ]
185
+ return filtered_nodes
186
+
187
+ def cur_num_workers(self):
188
+ """Returns dict mapping node type to the number of nodes of that type."""
189
+ # Factor like this for convenient re-use.
190
+ return self._cur_num_workers(self.node_data_dict)
191
+
192
+ def _cur_num_workers(self, node_data_dict: Dict[str, Any]):
193
+ num_workers_dict = defaultdict(int)
194
+ for node_data in node_data_dict.values():
195
+ if node_data.kind == NODE_KIND_HEAD:
196
+ # Only track workers.
197
+ continue
198
+ num_workers_dict[node_data.type] += 1
199
+ return num_workers_dict
200
+
201
+ def node_tags(self, node_id: str) -> Dict[str, str]:
202
+ node_data = self.node_data_dict[node_id]
203
+ tags = {
204
+ TAG_RAY_NODE_KIND: node_data.kind,
205
+ TAG_RAY_NODE_STATUS: node_data.status,
206
+ TAG_RAY_USER_NODE_TYPE: node_data.type,
207
+ }
208
+ if node_data.replica_index is not None:
209
+ tags[TAG_RAY_REPLICA_INDEX] = node_data.replica_index
210
+ return tags
211
+
212
+ def internal_ip(self, node_id: str) -> str:
213
+ return self.node_data_dict[node_id].ip
214
+
215
+ def create_node(
216
+ self, node_config: Dict[str, Any], tags: Dict[str, str], count: int
217
+ ) -> Optional[Dict[str, Any]]:
218
+ node_type = tags[TAG_RAY_USER_NODE_TYPE]
219
+ self.scale_request.desired_num_workers[node_type] += count
220
+ self.scale_change_needed = True
221
+
222
+ def terminate_node(self, node_id: str) -> Optional[Dict[str, Any]]:
223
+ # Sanity check: We should never try to delete the same node twice.
224
+ if node_id in self.scale_request.workers_to_delete:
225
+ logger.warning(
226
+ f"Autoscaler tried to terminate node {node_id} twice in the same update"
227
+ ". Skipping termination request."
228
+ )
229
+ return
230
+
231
+ # Sanity check: We should never try to delete a node we haven't seen.
232
+ if node_id not in self.node_data_dict:
233
+ logger.warning(
234
+ f"Autoscaler tried to terminate unkown node {node_id}"
235
+ ". Skipping termination request."
236
+ )
237
+ return
238
+
239
+ node_type = self.node_data_dict[node_id].type
240
+
241
+ # Sanity check: Don't request less than 0 nodes.
242
+ if self.scale_request.desired_num_workers[node_type] <= 0:
243
+ # This is logically impossible.
244
+ raise AssertionError(
245
+ "NodeProvider attempted to request less than 0 workers of type "
246
+ f"{node_type}. Skipping termination request."
247
+ )
248
+
249
+ # Terminate node
250
+ self.scale_request.desired_num_workers[node_type] -= 1
251
+ self.scale_request.workers_to_delete.add(node_id)
252
+
253
+ # Scale down all nodes in replica if node_id is part of a multi-host podslice
254
+ tags = self.node_tags(node_id)
255
+ if TAG_RAY_REPLICA_INDEX in tags:
256
+ node_replica_index = tags[TAG_RAY_REPLICA_INDEX]
257
+ for worker_id in self.replica_index_to_nodes[node_replica_index]:
258
+ # Check if worker has already been scheduled to delete
259
+ if worker_id not in self.scale_request.workers_to_delete:
260
+ self.scale_request.workers_to_delete.add(worker_id)
261
+ logger.info(
262
+ f"Autoscaler terminating node {worker_id} "
263
+ f"in multi-host replica {node_replica_index}."
264
+ )
265
+ self.scale_change_needed = True
vllm/lib/python3.10/site-packages/ray/autoscaler/command_runner.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Tuple
2
+
3
+ from ray.util.annotations import DeveloperAPI
4
+
5
+
6
+ @DeveloperAPI
7
+ class CommandRunnerInterface:
8
+ """Interface to run commands on a remote cluster node.
9
+
10
+ **Important**: This is an INTERNAL API that is only exposed for the purpose
11
+ of implementing custom node providers. It is not allowed to call into
12
+ CommandRunner methods from any Ray package outside the autoscaler, only to
13
+ define new implementations for use with the "external" node provider
14
+ option.
15
+
16
+ Command runner instances are returned by provider.get_command_runner()."""
17
+
18
+ def run(
19
+ self,
20
+ cmd: Optional[str] = None,
21
+ timeout: int = 120,
22
+ exit_on_fail: bool = False,
23
+ port_forward: List[Tuple[int, int]] = None,
24
+ with_output: bool = False,
25
+ environment_variables: Optional[Dict[str, object]] = None,
26
+ run_env: str = "auto",
27
+ ssh_options_override_ssh_key: str = "",
28
+ shutdown_after_run: bool = False,
29
+ ) -> str:
30
+ """Run the given command on the cluster node and optionally get output.
31
+
32
+ WARNING: the cloudgateway needs arguments of "run" function to be json
33
+ dumpable to send them over HTTP requests.
34
+
35
+ Args:
36
+ cmd: The command to run.
37
+ timeout: The command timeout in seconds.
38
+ exit_on_fail: Whether to sys exit on failure.
39
+ port_forward: List of (local, remote) ports to forward, or
40
+ a single tuple.
41
+ with_output: Whether to return output.
42
+ environment_variables (Dict[str, str | int | Dict[str, str]):
43
+ Environment variables that `cmd` should be run with.
44
+ run_env: Options: docker/host/auto. Used in
45
+ DockerCommandRunner to determine the run environment.
46
+ ssh_options_override_ssh_key: if provided, overwrites
47
+ SSHOptions class with SSHOptions(ssh_options_override_ssh_key).
48
+ shutdown_after_run: if provided, shutdowns down the machine
49
+ after executing the command with `sudo shutdown -h now`.
50
+ """
51
+ raise NotImplementedError
52
+
53
+ def run_rsync_up(
54
+ self, source: str, target: str, options: Optional[Dict[str, Any]] = None
55
+ ) -> None:
56
+ """Rsync files up to the cluster node.
57
+
58
+ Args:
59
+ source: The (local) source directory or file.
60
+ target: The (remote) destination path.
61
+ """
62
+ raise NotImplementedError
63
+
64
+ def run_rsync_down(
65
+ self, source: str, target: str, options: Optional[Dict[str, Any]] = None
66
+ ) -> None:
67
+ """Rsync files down from the cluster node.
68
+
69
+ Args:
70
+ source: The (remote) source directory or file.
71
+ target: The (local) destination path.
72
+ """
73
+ raise NotImplementedError
74
+
75
+ def remote_shell_command_str(self) -> str:
76
+ """Return the command the user can use to open a shell."""
77
+ raise NotImplementedError
78
+
79
+ def run_init(
80
+ self, *, as_head: bool, file_mounts: Dict[str, str], sync_run_yet: bool
81
+ ) -> Optional[bool]:
82
+ """Used to run extra initialization commands.
83
+
84
+ Args:
85
+ as_head: Run as head image or worker.
86
+ file_mounts: Files to copy to the head and worker nodes.
87
+ sync_run_yet: Whether sync has been run yet.
88
+
89
+ Returns:
90
+ optional: Whether initialization is necessary.
91
+ """
92
+ pass
vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (168 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/gcp/defaults.yaml ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # An unique identifier for the head node and workers of this cluster.
2
+ cluster_name: default
3
+
4
+ # The maximum number of workers nodes to launch in addition to the head
5
+ # node.
6
+ max_workers: 2
7
+
8
+ # The autoscaler will scale up the cluster faster with higher upscaling speed.
9
+ # E.g., if the task requires adding more nodes then autoscaler will gradually
10
+ # scale up the cluster in chunks of upscaling_speed*currently_running_nodes.
11
+ # This number should be > 0.
12
+ upscaling_speed: 1.0
13
+
14
+ # This executes all commands on all nodes in the docker container,
15
+ # and opens all the necessary ports to support the Ray cluster.
16
+ # Empty string means disabled.
17
+ docker: {}
18
+
19
+ # If a node is idle for this many minutes, it will be removed.
20
+ idle_timeout_minutes: 5
21
+
22
+ # Cloud-provider specific configuration.
23
+ provider:
24
+ type: gcp
25
+ region: us-west1
26
+ availability_zone: us-west1-a
27
+ project_id: null # Globally unique project id
28
+
29
+ # How Ray will authenticate with newly launched nodes.
30
+ auth:
31
+ ssh_user: ubuntu
32
+ # By default Ray creates a new private keypair, but you can also use your own.
33
+ # If you do so, make sure to also set "KeyName" in the head and worker node
34
+ # configurations below. This requires that you have added the key into the
35
+ # project wide meta-data.
36
+ # ssh_private_key: /path/to/your/key.pem
37
+
38
+ # Tell the autoscaler the allowed node types and the resources they provide.
39
+ # The key is the name of the node type, which is just for debugging purposes.
40
+ # The node config specifies the launch config and physical instance type.
41
+ available_node_types:
42
+ ray_head_default:
43
+ # The resources provided by this node type.
44
+ resources: {"CPU": 2}
45
+ # Provider-specific config for this node type, e.g. instance type. By default
46
+ # Ray will auto-configure unspecified fields such as subnets and ssh-keys.
47
+ # For more documentation on available fields, see:
48
+ # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
49
+ node_config:
50
+ machineType: n1-standard-2
51
+ disks:
52
+ - boot: true
53
+ autoDelete: true
54
+ type: PERSISTENT
55
+ initializeParams:
56
+ diskSizeGb: 50
57
+ # See https://cloud.google.com/compute/docs/images for more images
58
+ sourceImage: projects/deeplearning-platform-release/global/images/family/common-cpu
59
+
60
+ # Additional options can be found in in the compute docs at
61
+ # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
62
+
63
+ # If the network interface is specified as below in both head and worker
64
+ # nodes, the manual network config is used. Otherwise an existing subnet is
65
+ # used. To use a shared subnet, ask the subnet owner to grant permission
66
+ # for 'compute.subnetworks.use' to the ray autoscaler account...
67
+ # networkInterfaces:
68
+ # - kind: compute#networkInterface
69
+ # subnetwork: path/to/subnet
70
+ # aliasIpRanges: []
71
+ ray_worker_small:
72
+ # The minimum number of nodes of this type to launch.
73
+ # This number should be >= 0.
74
+ min_workers: 0
75
+ # The resources provided by this node type.
76
+ resources: {"CPU": 2}
77
+ # Provider-specific config for this node type, e.g. instance type. By default
78
+ # Ray will auto-configure unspecified fields such as subnets and ssh-keys.
79
+ # For more documentation on available fields, see:
80
+ # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
81
+ node_config:
82
+ machineType: n1-standard-2
83
+ disks:
84
+ - boot: true
85
+ autoDelete: true
86
+ type: PERSISTENT
87
+ initializeParams:
88
+ diskSizeGb: 50
89
+ # See https://cloud.google.com/compute/docs/images for more images
90
+ sourceImage: projects/deeplearning-platform-release/global/images/family/common-cpu
91
+ # Run workers on preemtible instance by default.
92
+ # Comment this out to use on-demand.
93
+ scheduling:
94
+ - preemptible: true
95
+
96
+ # Additional options can be found in in the compute docs at
97
+ # https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
98
+
99
+ # Specify the node type of the head node (as configured above).
100
+ head_node_type: ray_head_default
101
+
102
+ # Files or directories to copy to the head and worker nodes. The format is a
103
+ # dictionary from REMOTE_PATH: LOCAL_PATH, e.g.
104
+ file_mounts: {
105
+ # "/path1/on/remote/machine": "/path1/on/local/machine",
106
+ # "/path2/on/remote/machine": "/path2/on/local/machine",
107
+ }
108
+
109
+ # Files or directories to copy from the head node to the worker nodes. The format is a
110
+ # list of paths. The same path on the head node will be copied to the worker node.
111
+ # This behavior is a subset of the file_mounts behavior. In the vast majority of cases
112
+ # you should just use file_mounts. Only use this if you know what you're doing!
113
+ cluster_synced_files: []
114
+
115
+ # Whether changes to directories in file_mounts or cluster_synced_files in the head node
116
+ # should sync to the worker node continuously
117
+ file_mounts_sync_continuously: False
118
+
119
+ # Patterns for files to exclude when running rsync up or rsync down
120
+ rsync_exclude: []
121
+
122
+ # Pattern files to use for filtering out files when running rsync up or rsync down. The file is searched for
123
+ # in the source directory and recursively through all subdirectories. For example, if .gitignore is provided
124
+ # as a value, the behavior will match git's behavior for finding and using .gitignore files.
125
+ rsync_filter: []
126
+
127
+ # List of commands that will be run before `setup_commands`. If docker is
128
+ # enabled, these commands will run outside the container and before docker
129
+ # is setup.
130
+ initialization_commands: []
131
+
132
+ # List of shell commands to run to set up nodes.
133
+ setup_commands:
134
+ # Note: if you're developing Ray, you probably want to create an AMI that
135
+ # has your Ray repo pre-cloned. Then, you can replace the pip installs
136
+ # below with a git checkout <your_sha> (and possibly a recompile).
137
+ # - echo 'export PATH="$HOME/anaconda3/envs/tensorflow_p36/bin:$PATH"' >> ~/.bashrc
138
+ # Install ray if not present
139
+ - >-
140
+ (stat /opt/conda/bin/ &> /dev/null &&
141
+ echo 'export PATH="/opt/conda/bin:$PATH"' >> ~/.bashrc) || true
142
+ - which ray || pip install -U "ray[default] @ https://s3-us-west-2.amazonaws.com/ray-wheels/latest/ray-3.0.0.dev0-cp37-cp37m-manylinux2014_x86_64.whl"
143
+
144
+
145
+ # Custom commands that will be run on the head node after common setup.
146
+ head_setup_commands:
147
+ - pip install google-api-python-client==1.7.8
148
+
149
+ # Custom commands that will be run on worker nodes after common setup.
150
+ worker_setup_commands: []
151
+
152
+ # Command to start ray on the head node. You don't need to change this.
153
+ head_start_ray_commands:
154
+ - ray stop
155
+ - >-
156
+ ulimit -n 65536;
157
+ ray start
158
+ --head
159
+ --port=6379
160
+ --object-manager-port=8076
161
+ --autoscaling-config=~/ray_bootstrap_config.yaml
162
+ --dashboard-host=0.0.0.0
163
+
164
+ # Command to start ray on worker nodes. You don't need to change this.
165
+ worker_start_ray_commands:
166
+ - ray stop
167
+ - >-
168
+ ulimit -n 65536;
169
+ ray start
170
+ --address=$RAY_HEAD_IP:6379
171
+ --object-manager-port=8076
vllm/lib/python3.10/site-packages/ray/autoscaler/launch_and_verify_cluster.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script automates the process of launching and verifying a Ray cluster using a given
3
+ cluster configuration file. It also handles cluster cleanup before and after the
4
+ verification process. The script requires one command-line argument: the path to the
5
+ cluster configuration file.
6
+
7
+ Usage:
8
+ python launch_and_verify_cluster.py [--no-config-cache] [--retries NUM_RETRIES]
9
+ [--num-expected-nodes NUM_NODES] [--docker-override DOCKER_OVERRIDE]
10
+ [--wheel-override WHEEL_OVERRIDE]
11
+ <cluster_configuration_file_path>
12
+ """
13
+ import argparse
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ import traceback
21
+ from pathlib import Path
22
+
23
+ import boto3
24
+ import botocore
25
+ import yaml
26
+ from google.cloud import storage
27
+
28
+ import ray
29
+ from ray.autoscaler._private.aws.config import RAY
30
+
31
+
32
+ def check_arguments():
33
+ """
34
+ Check command line arguments and return the cluster configuration file path, the
35
+ number of retries, the number of expected nodes, and the value of the
36
+ --no-config-cache flag.
37
+ """
38
+ parser = argparse.ArgumentParser(description="Launch and verify a Ray cluster")
39
+ parser.add_argument(
40
+ "--no-config-cache",
41
+ action="store_true",
42
+ help="Pass the --no-config-cache flag to Ray CLI commands",
43
+ )
44
+ parser.add_argument(
45
+ "--retries",
46
+ type=int,
47
+ default=3,
48
+ help="Number of retries for verifying Ray is running (default: 3)",
49
+ )
50
+ parser.add_argument(
51
+ "--num-expected-nodes",
52
+ type=int,
53
+ default=1,
54
+ help="Number of nodes for verifying Ray is running (default: 1)",
55
+ )
56
+ parser.add_argument(
57
+ "--docker-override",
58
+ choices=["disable", "latest", "nightly", "commit"],
59
+ default="disable",
60
+ help="Override the docker image used for the head node and worker nodes",
61
+ )
62
+ parser.add_argument(
63
+ "--wheel-override",
64
+ type=str,
65
+ default="",
66
+ help="Override the wheel used for the head node and worker nodes",
67
+ )
68
+ parser.add_argument(
69
+ "cluster_config", type=str, help="Path to the cluster configuration file"
70
+ )
71
+ args = parser.parse_args()
72
+
73
+ assert not (
74
+ args.docker_override != "disable" and args.wheel_override != ""
75
+ ), "Cannot override both docker and wheel"
76
+
77
+ return (
78
+ args.cluster_config,
79
+ args.retries,
80
+ args.no_config_cache,
81
+ args.num_expected_nodes,
82
+ args.docker_override,
83
+ args.wheel_override,
84
+ )
85
+
86
+
87
+ def get_docker_image(docker_override):
88
+ """
89
+ Get the docker image to use for the head node and worker nodes.
90
+
91
+ Args:
92
+ docker_override: The value of the --docker-override flag.
93
+
94
+ Returns:
95
+ The docker image to use for the head node and worker nodes, or None if not
96
+ applicable.
97
+ """
98
+ if docker_override == "latest":
99
+ return "rayproject/ray:latest-py39"
100
+ elif docker_override == "nightly":
101
+ return "rayproject/ray:nightly-py39"
102
+ elif docker_override == "commit":
103
+ if re.match("^[0-9]+.[0-9]+.[0-9]+$", ray.__version__):
104
+ return f"rayproject/ray:{ray.__version__}.{ray.__commit__[:6]}-py39"
105
+ else:
106
+ print(
107
+ "Error: docker image is only available for "
108
+ f"release version, but we get: {ray.__version__}"
109
+ )
110
+ sys.exit(1)
111
+ return None
112
+
113
+
114
+ def check_file(file_path):
115
+ """
116
+ Check if the provided file path is valid and readable.
117
+
118
+ Args:
119
+ file_path: The path of the file to check.
120
+
121
+ Raises:
122
+ SystemExit: If the file is not readable or does not exist.
123
+ """
124
+ if not file_path.is_file() or not os.access(file_path, os.R_OK):
125
+ print(f"Error: Cannot read cluster configuration file: {file_path}")
126
+ sys.exit(1)
127
+
128
+
129
+ def override_wheels_url(config_yaml, wheel_url):
130
+ setup_commands = config_yaml.get("setup_commands", [])
131
+ setup_commands.append(
132
+ f'pip3 uninstall -y ray && pip3 install -U "ray[default] @ {wheel_url}"'
133
+ )
134
+ config_yaml["setup_commands"] = setup_commands
135
+
136
+
137
+ def override_docker_image(config_yaml, docker_image):
138
+ docker_config = config_yaml.get("docker", {})
139
+ docker_config["image"] = docker_image
140
+ docker_config["container_name"] = "ray_container"
141
+ assert docker_config.get("head_image") is None, "Cannot override head_image"
142
+ assert docker_config.get("worker_image") is None, "Cannot override worker_image"
143
+ config_yaml["docker"] = docker_config
144
+
145
+
146
+ def download_ssh_key_aws():
147
+ """Download the ssh key from the S3 bucket to the local machine."""
148
+ print("======================================")
149
+ print("Downloading ssh key...")
150
+ # Create a Boto3 client to interact with S3
151
+ s3_client = boto3.client("s3", region_name="us-west-2")
152
+
153
+ # Set the name of the S3 bucket and the key to download
154
+ bucket_name = "aws-cluster-launcher-test"
155
+ key_name = "ray-autoscaler_59_us-west-2.pem"
156
+
157
+ # Download the key from the S3 bucket to a local file
158
+ local_key_path = os.path.expanduser(f"~/.ssh/{key_name}")
159
+ if not os.path.exists(os.path.dirname(local_key_path)):
160
+ os.makedirs(os.path.dirname(local_key_path))
161
+ s3_client.download_file(bucket_name, key_name, local_key_path)
162
+
163
+ # Set permissions on the key file
164
+ os.chmod(local_key_path, 0o400)
165
+
166
+
167
+ def download_ssh_key_gcp():
168
+ """Download the ssh key from the google cloud bucket to the local machine."""
169
+ print("======================================")
170
+ print("Downloading ssh key from GCP...")
171
+
172
+ # Initialize the GCP storage client
173
+ client = storage.Client()
174
+
175
+ # Set the name of the GCS bucket and the blob (key) to download
176
+ bucket_name = "gcp-cluster-launcher-release-test-ssh-keys"
177
+ key_name = "ray-autoscaler_gcp_us-west1_anyscale-bridge-cd812d38_ubuntu_0.pem"
178
+
179
+ # Get the bucket and blob
180
+ bucket = client.get_bucket(bucket_name)
181
+ blob = bucket.get_blob(key_name)
182
+
183
+ # Download the blob to a local file
184
+ local_key_path = os.path.expanduser(f"~/.ssh/{key_name}")
185
+ if not os.path.exists(os.path.dirname(local_key_path)):
186
+ os.makedirs(os.path.dirname(local_key_path))
187
+ blob.download_to_filename(local_key_path)
188
+
189
+ # Set permissions on the key file
190
+ os.chmod(local_key_path, 0o400)
191
+
192
+
193
+ def cleanup_cluster(config_yaml, cluster_config):
194
+ """
195
+ Clean up the cluster using the given cluster configuration file.
196
+
197
+ Args:
198
+ cluster_config: The path of the cluster configuration file.
199
+ """
200
+ print("======================================")
201
+ print("Cleaning up cluster...")
202
+
203
+ # We do multiple retries here because sometimes the cluster
204
+ # fails to clean up properly, resulting in a non-zero exit code (e.g.
205
+ # when processes have to be killed forcefully).
206
+
207
+ last_error = None
208
+ num_tries = 3
209
+ for i in range(num_tries):
210
+ try:
211
+ subprocess.run(
212
+ ["ray", "down", "-v", "-y", str(cluster_config)],
213
+ check=True,
214
+ capture_output=True,
215
+ )
216
+ cleanup_security_groups(config_yaml)
217
+ # Final success
218
+ return
219
+ except subprocess.CalledProcessError as e:
220
+ print(f"ray down fails[{i+1}/{num_tries}]: ")
221
+ print(e.output.decode("utf-8"))
222
+
223
+ # Print full traceback
224
+ traceback.print_exc()
225
+
226
+ # Print stdout and stderr from ray down
227
+ print(f"stdout:\n{e.stdout.decode('utf-8')}")
228
+ print(f"stderr:\n{e.stderr.decode('utf-8')}")
229
+
230
+ last_error = e
231
+
232
+ raise last_error
233
+
234
+
235
+ def cleanup_security_group(ec2_client, id):
236
+ retry = 0
237
+ while retry < 10:
238
+ try:
239
+ ec2_client.delete_security_group(GroupId=id)
240
+ return
241
+ except botocore.exceptions.ClientError as e:
242
+ if e.response["Error"]["Code"] == "DependencyViolation":
243
+ sleep_time = 2**retry
244
+ print(
245
+ f"Waiting {sleep_time}s for the instance to be terminated before deleting the security group {id}" # noqa E501
246
+ )
247
+ time.sleep(sleep_time)
248
+ retry += 1
249
+ else:
250
+ print(f"Error deleting security group: {e}")
251
+ return
252
+
253
+
254
+ def cleanup_security_groups(config):
255
+ provider_type = config.get("provider", {}).get("type")
256
+ if provider_type != "aws":
257
+ return
258
+
259
+ try:
260
+ ec2_client = boto3.client("ec2", region_name="us-west-2")
261
+ response = ec2_client.describe_security_groups(
262
+ Filters=[
263
+ {
264
+ "Name": "tag-key",
265
+ "Values": [RAY],
266
+ },
267
+ {
268
+ "Name": "tag:ray-cluster-name",
269
+ "Values": [config["cluster_name"]],
270
+ },
271
+ ]
272
+ )
273
+ for security_group in response["SecurityGroups"]:
274
+ cleanup_security_group(ec2_client, security_group["GroupId"])
275
+ except Exception as e:
276
+ print(f"Error cleaning up security groups: {e}")
277
+
278
+
279
+ def run_ray_commands(
280
+ config_yaml, cluster_config, retries, no_config_cache, num_expected_nodes=1
281
+ ):
282
+ """
283
+ Run the necessary Ray commands to start a cluster, verify Ray is running, and clean
284
+ up the cluster.
285
+
286
+ Args:
287
+ cluster_config: The path of the cluster configuration file.
288
+ retries: The number of retries for the verification step.
289
+ no_config_cache: Whether to pass the --no-config-cache flag to the ray CLI
290
+ commands.
291
+ """
292
+
293
+ print("======================================")
294
+ print("Starting new cluster...")
295
+ cmd = ["ray", "up", "-v", "-y"]
296
+ if no_config_cache:
297
+ cmd.append("--no-config-cache")
298
+ cmd.append(str(cluster_config))
299
+
300
+ print(" ".join(cmd))
301
+
302
+ try:
303
+ subprocess.run(cmd, check=True, capture_output=True)
304
+ except subprocess.CalledProcessError as e:
305
+ print(e.output)
306
+ # print stdout and stderr
307
+ print(f"stdout:\n{e.stdout.decode('utf-8')}")
308
+ print(f"stderr:\n{e.stderr.decode('utf-8')}")
309
+ raise e
310
+
311
+ print("======================================")
312
+ print("Verifying Ray is running...")
313
+
314
+ success = False
315
+ count = 0
316
+ while count < retries:
317
+ try:
318
+ cmd = [
319
+ "ray",
320
+ "exec",
321
+ "-v",
322
+ str(cluster_config),
323
+ (
324
+ 'python -c \'import ray; ray.init("localhost:6379");'
325
+ + f" assert len(ray.nodes()) >= {num_expected_nodes}'"
326
+ ),
327
+ ]
328
+ if no_config_cache:
329
+ cmd.append("--no-config-cache")
330
+ subprocess.run(cmd, check=True)
331
+ success = True
332
+ break
333
+ except subprocess.CalledProcessError:
334
+ count += 1
335
+ print(f"Verification failed. Retry attempt {count} of {retries}...")
336
+ time.sleep(60)
337
+
338
+ if not success:
339
+ print("======================================")
340
+ print(
341
+ f"Error: Verification failed after {retries} attempts. Cleaning up cluster "
342
+ "before exiting..."
343
+ )
344
+ cleanup_cluster(config_yaml, cluster_config)
345
+ print("======================================")
346
+ print("Exiting script.")
347
+ sys.exit(1)
348
+
349
+ print("======================================")
350
+ print("Ray verification successful.")
351
+
352
+ cleanup_cluster(config_yaml, cluster_config)
353
+
354
+ print("======================================")
355
+ print("Finished executing script successfully.")
356
+
357
+
358
+ if __name__ == "__main__":
359
+ (
360
+ cluster_config,
361
+ retries,
362
+ no_config_cache,
363
+ num_expected_nodes,
364
+ docker_override,
365
+ wheel_override,
366
+ ) = check_arguments()
367
+ cluster_config = Path(cluster_config)
368
+ check_file(cluster_config)
369
+
370
+ print(f"Using cluster configuration file: {cluster_config}")
371
+ print(f"Number of retries for 'verify ray is running' step: {retries}")
372
+ print(f"Using --no-config-cache flag: {no_config_cache}")
373
+ print(f"Number of expected nodes for 'verify ray is running': {num_expected_nodes}")
374
+
375
+ config_yaml = yaml.safe_load(cluster_config.read_text())
376
+ # Make the cluster name unique
377
+ config_yaml["cluster_name"] = (
378
+ config_yaml["cluster_name"] + "-" + str(int(time.time()))
379
+ )
380
+
381
+ print("======================================")
382
+ print(f"Overriding ray wheel...: {wheel_override}")
383
+ if wheel_override:
384
+ override_wheels_url(config_yaml, wheel_override)
385
+
386
+ print("======================================")
387
+ print(f"Overriding docker image...: {docker_override}")
388
+ docker_override_image = get_docker_image(docker_override)
389
+ print(f"Using docker image: {docker_override_image}")
390
+ if docker_override_image:
391
+ override_docker_image(config_yaml, docker_override_image)
392
+
393
+ provider_type = config_yaml.get("provider", {}).get("type")
394
+ config_yaml["provider"]["cache_stopped_nodes"] = False
395
+ if provider_type == "aws":
396
+ download_ssh_key_aws()
397
+ elif provider_type == "gcp":
398
+ download_ssh_key_gcp()
399
+ # Get the active account email
400
+ account_email = (
401
+ subprocess.run(
402
+ ["gcloud", "config", "get-value", "account"],
403
+ stdout=subprocess.PIPE,
404
+ check=True,
405
+ )
406
+ .stdout.decode("utf-8")
407
+ .strip()
408
+ )
409
+ print("Active account email:", account_email)
410
+ # Get the current project ID
411
+ project_id = (
412
+ subprocess.run(
413
+ ["gcloud", "config", "get-value", "project"],
414
+ stdout=subprocess.PIPE,
415
+ check=True,
416
+ )
417
+ .stdout.decode("utf-8")
418
+ .strip()
419
+ )
420
+ print(
421
+ f"Injecting GCP project '{project_id}' into cluster configuration file..."
422
+ )
423
+ config_yaml["provider"]["project_id"] = project_id
424
+ elif provider_type == "vsphere":
425
+ print("======================================")
426
+ print("VSPHERE provider detected.")
427
+ else:
428
+ print("======================================")
429
+ print("Provider type not recognized. Exiting script.")
430
+ sys.exit(1)
431
+
432
+ # Create a new temporary file and dump the updated configuration into it
433
+ with tempfile.NamedTemporaryFile(suffix=".yaml") as temp:
434
+ temp.write(yaml.dump(config_yaml).encode("utf-8"))
435
+ temp.flush()
436
+ cluster_config = Path(temp.name)
437
+ run_ray_commands(
438
+ config_yaml, cluster_config, retries, no_config_cache, num_expected_nodes
439
+ )
vllm/lib/python3.10/site-packages/ray/autoscaler/local/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/local/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/local/__pycache__/coordinator_server.cpython-310.pyc ADDED
Binary file (4.66 kB). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/local/coordinator_server.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Web server that runs on local/private clusters to coordinate and manage
2
+ different clusters for multiple users. It receives node provider function calls
3
+ through HTTP requests from remote CoordinatorSenderNodeProvider and runs them
4
+ locally in LocalNodeProvider. To start the webserver the user runs:
5
+ `python coordinator_server.py --ips <comma separated ips> --port <PORT>`."""
6
+ import argparse
7
+ import json
8
+ import logging
9
+ import socket
10
+ import threading
11
+ from http.server import HTTPServer, SimpleHTTPRequestHandler
12
+
13
+ from ray.autoscaler._private.local.node_provider import LocalNodeProvider
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logging.basicConfig(level=logging.INFO)
17
+
18
+
19
+ def runner_handler(node_provider):
20
+ class Handler(SimpleHTTPRequestHandler):
21
+ """A custom handler for OnPremCoordinatorServer.
22
+
23
+ Handles all requests and responses coming into and from the
24
+ remote CoordinatorSenderNodeProvider.
25
+ """
26
+
27
+ def _do_header(self, response_code=200, headers=None):
28
+ """Sends the header portion of the HTTP response.
29
+
30
+ Args:
31
+ response_code: Standard HTTP response code
32
+ headers (list[tuples]): Standard HTTP response headers
33
+ """
34
+ if headers is None:
35
+ headers = [("Content-type", "application/json")]
36
+
37
+ self.send_response(response_code)
38
+ for key, value in headers:
39
+ self.send_header(key, value)
40
+ self.end_headers()
41
+
42
+ def do_HEAD(self):
43
+ """HTTP HEAD handler method."""
44
+ self._do_header()
45
+
46
+ def do_GET(self):
47
+ """Processes requests from remote CoordinatorSenderNodeProvider."""
48
+ if self.headers["content-length"]:
49
+ raw_data = (
50
+ self.rfile.read(int(self.headers["content-length"]))
51
+ ).decode("utf-8")
52
+ logger.info(
53
+ "OnPremCoordinatorServer received request: " + str(raw_data)
54
+ )
55
+ request = json.loads(raw_data)
56
+ response = getattr(node_provider, request["type"])(*request["args"])
57
+ logger.info(
58
+ "OnPremCoordinatorServer response content: " + str(raw_data)
59
+ )
60
+ response_code = 200
61
+ message = json.dumps(response)
62
+ self._do_header(response_code=response_code)
63
+ self.wfile.write(message.encode())
64
+
65
+ return Handler
66
+
67
+
68
+ class OnPremCoordinatorServer(threading.Thread):
69
+ """Initializes HTTPServer and serves CoordinatorSenderNodeProvider forever.
70
+
71
+ It handles requests from the remote CoordinatorSenderNodeProvider. The
72
+ requests are forwarded to LocalNodeProvider function calls.
73
+ """
74
+
75
+ def __init__(self, list_of_node_ips, host, port):
76
+ """Initialize HTTPServer and serve forever by invoking self.run()."""
77
+
78
+ logger.info(
79
+ "Running on prem coordinator server on address " + host + ":" + str(port)
80
+ )
81
+ threading.Thread.__init__(self)
82
+ self._port = port
83
+ self._list_of_node_ips = list_of_node_ips
84
+ address = (host, self._port)
85
+ config = {"list_of_node_ips": list_of_node_ips}
86
+ self._server = HTTPServer(
87
+ address,
88
+ runner_handler(LocalNodeProvider(config, cluster_name=None)),
89
+ )
90
+ self.start()
91
+
92
+ def run(self):
93
+ self._server.serve_forever()
94
+
95
+ def shutdown(self):
96
+ """Shutdown the underlying server."""
97
+ self._server.shutdown()
98
+ self._server.server_close()
99
+
100
+
101
+ def main():
102
+ parser = argparse.ArgumentParser(
103
+ description="Please provide a list of node ips and port."
104
+ )
105
+ parser.add_argument(
106
+ "--ips", required=True, help="Comma separated list of node ips."
107
+ )
108
+ parser.add_argument(
109
+ "--port",
110
+ type=int,
111
+ required=True,
112
+ help="The port on which the coordinator listens.",
113
+ )
114
+ args = parser.parse_args()
115
+ list_of_node_ips = args.ips.split(",")
116
+ OnPremCoordinatorServer(
117
+ list_of_node_ips=list_of_node_ips,
118
+ host=socket.gethostbyname(socket.gethostname()),
119
+ port=args.port,
120
+ )
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
vllm/lib/python3.10/site-packages/ray/autoscaler/local/defaults.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This configuration file is used internally
2
+ # to fill default settings for on-prem Ray clusters
3
+ # bootstrapped by the Ray autoscaler.
4
+ # For annotated examples, see the example yamls in this directory.
5
+
6
+ cluster_name: default
7
+
8
+ auth: {}
9
+
10
+ upscaling_speed: 1.0
11
+ idle_timeout_minutes: 5
12
+
13
+ docker: {}
14
+
15
+ # Defaults are empty to avoid any surprise changes to on-prem cluster's state.
16
+ # Refer to example yamls for examples of ray installation in setup commands.
17
+ initialization_commands: []
18
+ setup_commands: []
19
+ head_setup_commands: []
20
+ worker_setup_commands: []
21
+
22
+ head_start_ray_commands:
23
+ - ray stop
24
+ - ulimit -c unlimited; ray start --head --port=6379 --autoscaling-config=~/ray_bootstrap_config.yaml
25
+ worker_start_ray_commands:
26
+ - ray stop
27
+ - ray start --address=$RAY_HEAD_IP:6379
28
+
29
+ file_mounts: {}
30
+ cluster_synced_files: []
31
+ file_mounts_sync_continuously: false
32
+ rsync_exclude: []
33
+ rsync_filter: []
vllm/lib/python3.10/site-packages/ray/autoscaler/node_launch_exception.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional, Tuple
2
+
3
+ from ray.util.annotations import DeveloperAPI
4
+
5
+
6
+ @DeveloperAPI
7
+ class NodeLaunchException(Exception):
8
+ """A structured exception that can be thrown by a node provider during a
9
+ `create_node` call to pass additional information for observability.
10
+ """
11
+
12
+ def __init__(
13
+ self,
14
+ category: str,
15
+ description: str,
16
+ src_exc_info: Optional[Tuple[Any, Any, Any]], # The
17
+ ):
18
+ """Args:
19
+ category: A short (<20 chars) label for the error.
20
+ description: A longer, human readable description of the error.
21
+ src_exc_info: The source exception info if applicable. This is a
22
+ tuple of (type, exception, traceback) as returned by
23
+ sys.exc_info()
24
+
25
+ """
26
+ super().__init__(f"Node Launch Exception ({category}): {description}")
27
+ self.category = category
28
+ self.description = description
29
+ self.src_exc_info = src_exc_info
30
+
31
+ def __reduce__(self):
32
+ # NOTE: Since tracebacks can't be pickled, we'll drop the optional
33
+ # traceback if we have to serialize this object.
34
+ return (
35
+ self.__class__,
36
+ (self.category, self.description, None),
37
+ )
vllm/lib/python3.10/site-packages/ray/autoscaler/node_provider.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from types import ModuleType
3
+ from typing import Any, Dict, List, Optional
4
+
5
+ from ray.autoscaler._private.command_runner import DockerCommandRunner, SSHCommandRunner
6
+ from ray.autoscaler.command_runner import CommandRunnerInterface
7
+ from ray.util.annotations import DeveloperAPI
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ @DeveloperAPI
13
+ class NodeProvider:
14
+ """Interface for getting and returning nodes from a Cloud.
15
+
16
+ **Important**: This is an INTERNAL API that is only exposed for the purpose
17
+ of implementing custom node providers. It is not allowed to call into
18
+ NodeProvider methods from any Ray package outside the autoscaler, only to
19
+ define new implementations of NodeProvider for use with the "external" node
20
+ provider option.
21
+
22
+ NodeProviders are namespaced by the `cluster_name` parameter; they only
23
+ operate on nodes within that namespace.
24
+
25
+ Nodes may be in one of three states: {pending, running, terminated}. Nodes
26
+ appear immediately once started by `create_node`, and transition
27
+ immediately to terminated when `terminate_node` is called.
28
+ """
29
+
30
+ def __init__(self, provider_config: Dict[str, Any], cluster_name: str) -> None:
31
+ self.provider_config = provider_config
32
+ self.cluster_name = cluster_name
33
+ self._internal_ip_cache: Dict[str, str] = {}
34
+ self._external_ip_cache: Dict[str, str] = {}
35
+
36
+ def is_readonly(self) -> bool:
37
+ """Returns whether this provider is readonly.
38
+
39
+ Readonly node providers do not allow nodes to be created or terminated.
40
+ """
41
+ return False
42
+
43
+ def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]:
44
+ """Return a list of node ids filtered by the specified tags dict.
45
+
46
+ This list must not include terminated nodes. For performance reasons,
47
+ providers are allowed to cache the result of a call to
48
+ non_terminated_nodes() to serve single-node queries
49
+ (e.g. is_running(node_id)). This means that non_terminate_nodes() must
50
+ be called again to refresh results.
51
+
52
+ Examples:
53
+ >>> from ray.autoscaler.node_provider import NodeProvider
54
+ >>> from ray.autoscaler.tags import TAG_RAY_NODE_KIND
55
+ >>> provider = NodeProvider(...) # doctest: +SKIP
56
+ >>> provider.non_terminated_nodes( # doctest: +SKIP
57
+ ... {TAG_RAY_NODE_KIND: "worker"})
58
+ ["node-1", "node-2"]
59
+
60
+ """
61
+ raise NotImplementedError
62
+
63
+ def is_running(self, node_id: str) -> bool:
64
+ """Return whether the specified node is running."""
65
+ raise NotImplementedError
66
+
67
+ def is_terminated(self, node_id: str) -> bool:
68
+ """Return whether the specified node is terminated."""
69
+ raise NotImplementedError
70
+
71
+ def node_tags(self, node_id: str) -> Dict[str, str]:
72
+ """Returns the tags of the given node (string dict)."""
73
+ raise NotImplementedError
74
+
75
+ def external_ip(self, node_id: str) -> str:
76
+ """Returns the external ip of the given node."""
77
+ raise NotImplementedError
78
+
79
+ def internal_ip(self, node_id: str) -> str:
80
+ """Returns the internal ip (Ray ip) of the given node."""
81
+ raise NotImplementedError
82
+
83
+ def get_node_id(self, ip_address: str, use_internal_ip: bool = False) -> str:
84
+ """Returns the node_id given an IP address.
85
+
86
+ Assumes ip-address is unique per node.
87
+
88
+ Args:
89
+ ip_address: Address of node.
90
+ use_internal_ip: Whether the ip address is
91
+ public or private.
92
+
93
+ Raises:
94
+ ValueError if not found.
95
+ """
96
+
97
+ def find_node_id():
98
+ if use_internal_ip:
99
+ return self._internal_ip_cache.get(ip_address)
100
+ else:
101
+ return self._external_ip_cache.get(ip_address)
102
+
103
+ if not find_node_id():
104
+ all_nodes = self.non_terminated_nodes({})
105
+ ip_func = self.internal_ip if use_internal_ip else self.external_ip
106
+ ip_cache = (
107
+ self._internal_ip_cache if use_internal_ip else self._external_ip_cache
108
+ )
109
+ for node_id in all_nodes:
110
+ ip_cache[ip_func(node_id)] = node_id
111
+
112
+ if not find_node_id():
113
+ if use_internal_ip:
114
+ known_msg = f"Worker internal IPs: {list(self._internal_ip_cache)}"
115
+ else:
116
+ known_msg = f"Worker external IP: {list(self._external_ip_cache)}"
117
+ raise ValueError(f"ip {ip_address} not found. " + known_msg)
118
+
119
+ return find_node_id()
120
+
121
+ def create_node(
122
+ self, node_config: Dict[str, Any], tags: Dict[str, str], count: int
123
+ ) -> Optional[Dict[str, Any]]:
124
+ """Creates a number of nodes within the namespace.
125
+
126
+ Optionally returns a mapping from created node ids to node metadata.
127
+
128
+ Optionally may throw a
129
+ ray.autoscaler.node_launch_exception.NodeLaunchException which the
130
+ autoscaler may use to provide additional functionality such as
131
+ observability.
132
+
133
+ """
134
+ raise NotImplementedError
135
+
136
+ def create_node_with_resources_and_labels(
137
+ self,
138
+ node_config: Dict[str, Any],
139
+ tags: Dict[str, str],
140
+ count: int,
141
+ resources: Dict[str, float],
142
+ labels: Dict[str, str],
143
+ ) -> Optional[Dict[str, Any]]:
144
+ """Create nodes with a given resource and label config.
145
+
146
+ This is the method actually called by the autoscaler. Prefer to
147
+ implement this when possible directly, otherwise it delegates to the
148
+ create_node() implementation.
149
+
150
+ Optionally may throw a ray.autoscaler.node_launch_exception.NodeLaunchException.
151
+ """
152
+ return self.create_node(node_config, tags, count)
153
+
154
+ def set_node_tags(self, node_id: str, tags: Dict[str, str]) -> None:
155
+ """Sets the tag values (string dict) for the specified node."""
156
+ raise NotImplementedError
157
+
158
+ def terminate_node(self, node_id: str) -> Optional[Dict[str, Any]]:
159
+ """Terminates the specified node.
160
+
161
+ Optionally return a mapping from deleted node ids to node
162
+ metadata.
163
+ """
164
+ raise NotImplementedError
165
+
166
+ def terminate_nodes(self, node_ids: List[str]) -> Optional[Dict[str, Any]]:
167
+ """Terminates a set of nodes.
168
+
169
+ May be overridden with a batch method, which optionally may return a
170
+ mapping from deleted node ids to node metadata.
171
+ """
172
+ for node_id in node_ids:
173
+ logger.info("NodeProvider: {}: Terminating node".format(node_id))
174
+ self.terminate_node(node_id)
175
+ return None
176
+
177
+ @property
178
+ def max_terminate_nodes(self) -> Optional[int]:
179
+ """The maximum number of nodes which can be terminated in one single
180
+ API request. By default, this is "None", which means that the node
181
+ provider's underlying API allows infinite requests to be terminated
182
+ with one request.
183
+
184
+ For example, AWS only allows 1000 nodes to be terminated
185
+ at once; to terminate more, we must issue multiple separate API
186
+ requests. If the limit is infinity, then simply set this to None.
187
+
188
+ This may be overridden. The value may be useful when overriding the
189
+ "terminate_nodes" method.
190
+ """
191
+ return None
192
+
193
+ @staticmethod
194
+ def bootstrap_config(cluster_config: Dict[str, Any]) -> Dict[str, Any]:
195
+ """Bootstraps the cluster config by adding env defaults if needed."""
196
+ return cluster_config
197
+
198
+ def get_command_runner(
199
+ self,
200
+ log_prefix: str,
201
+ node_id: str,
202
+ auth_config: Dict[str, Any],
203
+ cluster_name: str,
204
+ process_runner: ModuleType,
205
+ use_internal_ip: bool,
206
+ docker_config: Optional[Dict[str, Any]] = None,
207
+ ) -> CommandRunnerInterface:
208
+ """Returns the CommandRunner class used to perform SSH commands.
209
+
210
+ Args:
211
+ log_prefix: stores "NodeUpdater: {}: ".format(<node_id>). Used
212
+ to print progress in the CommandRunner.
213
+ node_id: the node ID.
214
+ auth_config: the authentication configs from the autoscaler
215
+ yaml file.
216
+ cluster_name: the name of the cluster.
217
+ process_runner: the module to use to run the commands
218
+ in the CommandRunner. E.g., subprocess.
219
+ use_internal_ip: whether the node_id belongs to an internal ip
220
+ or external ip.
221
+ docker_config: If set, the docker information of the docker
222
+ container that commands should be run on.
223
+ """
224
+ common_args = {
225
+ "log_prefix": log_prefix,
226
+ "node_id": node_id,
227
+ "provider": self,
228
+ "auth_config": auth_config,
229
+ "cluster_name": cluster_name,
230
+ "process_runner": process_runner,
231
+ "use_internal_ip": use_internal_ip,
232
+ }
233
+ if docker_config and docker_config["container_name"] != "":
234
+ return DockerCommandRunner(docker_config, **common_args)
235
+ else:
236
+ return SSHCommandRunner(**common_args)
237
+
238
+ def prepare_for_head_node(self, cluster_config: Dict[str, Any]) -> Dict[str, Any]:
239
+ """Returns a new cluster config with custom configs for head node."""
240
+ return cluster_config
241
+
242
+ @staticmethod
243
+ def fillout_available_node_types_resources(
244
+ cluster_config: Dict[str, Any]
245
+ ) -> Dict[str, Any]:
246
+ """Fills out missing "resources" field for available_node_types."""
247
+ return cluster_config
248
+
249
+ def safe_to_scale(self) -> bool:
250
+ """Optional condition to determine if it's safe to proceed with an autoscaling
251
+ update. Can be used to wait for convergence of state managed by an external
252
+ cluster manager.
253
+
254
+ Called by the autoscaler immediately after non_terminated_nodes().
255
+ If False is returned, the autoscaler will abort the update.
256
+ """
257
+ return True
258
+
259
+ def post_process(self) -> None:
260
+ """This optional method is executed at the end of
261
+ StandardAutoscaler._update().
262
+ """
263
+ pass
vllm/lib/python3.10/site-packages/ray/autoscaler/ray-schema.json ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "http://github.com/ray-project/ray/python/ray/autoscaler/ray-schema.json",
4
+ "title": "Ray AutoScaler",
5
+ "description": "Ray autoscaler schema",
6
+ "type": "object",
7
+ "definitions": {
8
+ "commands": {
9
+ "type": "array",
10
+ "items": {
11
+ "type": "string",
12
+ "description": "shell command"
13
+ }
14
+ }
15
+ },
16
+ "required": [
17
+ "cluster_name",
18
+ "provider"
19
+ ],
20
+ "additionalProperties": false,
21
+ "properties": {
22
+ "cluster_name": {
23
+ "description": "A unique identifier for the head node and workers of this cluster.",
24
+ "type": "string"
25
+ },
26
+ "max_workers": {
27
+ "description": "The maximum number of workers nodes to launch in addition to the head node. This should be no larger than the sum of min_workers for all available node types.",
28
+ "type": "integer",
29
+ "minimum": 0
30
+ },
31
+ "upscaling_speed": {
32
+ "description": "The autoscaler will scale up the cluster faster with higher upscaling speed. E.g., if the task requires adding more nodes then autoscaler will gradually scale up the cluster in chunks of upscaling_speed*currently_running_nodes. This number should be > 0.",
33
+ "type": "number",
34
+ "minimum": 0
35
+ },
36
+ "idle_timeout_minutes": {
37
+ "description": "If a node is idle for this many minutes, it will be removed.",
38
+ "type": "number",
39
+ "minimum": 0
40
+ },
41
+ "provider": {
42
+ "type": "object",
43
+ "description": "Cloud-provider specific configuration.",
44
+ "required": [ "type" ],
45
+ "additionalProperties": true,
46
+ "properties": {
47
+ "type": {
48
+ "type": "string",
49
+ "description": "e.g. aws, azure, gcp,..."
50
+ },
51
+ "region": {
52
+ "type": "string",
53
+ "description": "e.g. us-east-1"
54
+ },
55
+ "module": {
56
+ "type": "string",
57
+ "description": "module, if using external node provider"
58
+ },
59
+ "head_ip": {
60
+ "type": "string",
61
+ "description": "gcp project id, if using gcp"
62
+ },
63
+ "worker_ips": {
64
+ "type": "array",
65
+ "description": "local cluster head node"
66
+ },
67
+ "use_internal_ips": {
68
+ "type": "boolean",
69
+ "description": "don't require public ips"
70
+ },
71
+ "namespace": {
72
+ "type": "string",
73
+ "description": "k8s namespace, if using k8s"
74
+ },
75
+ "location": {
76
+ "type": "string",
77
+ "description": "Azure location"
78
+ },
79
+ "resource_group": {
80
+ "type": "string",
81
+ "description": "Azure resource group"
82
+ },
83
+ "tags": {
84
+ "type": "object",
85
+ "description": "Azure user-defined tags"
86
+ },
87
+ "subscription_id": {
88
+ "type": "string",
89
+ "description": "Azure subscription id"
90
+ },
91
+ "msi_identity_id": {
92
+ "type": "string",
93
+ "description": "User-defined managed identity (generated by config)"
94
+ },
95
+ "msi_identity_principal_id": {
96
+ "type": "string",
97
+ "description": "User-defined managed identity principal id (generated by config)"
98
+ },
99
+ "subnet_id": {
100
+ "type": "string",
101
+ "description": "Network subnet id"
102
+ },
103
+ "autoscaler_service_account": {
104
+ "type": "object",
105
+ "description": "k8s autoscaler permissions, if using k8s"
106
+ },
107
+ "autoscaler_role": {
108
+ "type": "object",
109
+ "description": "k8s autoscaler permissions, if using k8s"
110
+ },
111
+ "autoscaler_role_binding": {
112
+ "type": "object",
113
+ "description": "k8s autoscaler permissions, if using k8s"
114
+ },
115
+ "cache_stopped_nodes": {
116
+ "type": "boolean",
117
+ "description": " Whether to try to reuse previously stopped nodes instead of launching nodes. This will also cause the autoscaler to stop nodes instead of terminating them. Only implemented for AWS."
118
+ },
119
+ "availability_zone": {
120
+ "type": "string",
121
+ "description": "GCP availability zone"
122
+ },
123
+ "project_id": {
124
+ "type": ["string", "null"],
125
+ "description": "GCP globally unique project id"
126
+ },
127
+ "security_group": {
128
+ "type": "object",
129
+ "description": "AWS security group",
130
+ "additionalProperties": false,
131
+ "properties": {
132
+ "GroupName": {
133
+ "type": "string",
134
+ "description": "Security group name"
135
+ },
136
+ "IpPermissions": {
137
+ "type": "array",
138
+ "description": "Security group in bound rules"
139
+ }
140
+ }
141
+ },
142
+ "disable_node_updaters": {
143
+ "type": "boolean",
144
+ "description": "Disables node updaters if set to True. Default is False. (For Kubernetes operator usage.)"
145
+ },
146
+ "gcp_credentials": {
147
+ "type": "object",
148
+ "description": "Credentials for authenticating with the GCP client",
149
+ "required": [ "type" ],
150
+ "additionalProperties": false,
151
+ "properties": {
152
+ "type": {
153
+ "type": "string",
154
+ "enum": ["credentials_token", "service_account"],
155
+ "description": "Credentials type: either temporary OAuth 2.0 token or permanent service account credentials blob."
156
+ },
157
+ "credentials": {
158
+ "type": "string",
159
+ "description": "Oauth token or JSON string constituting service account credentials"
160
+ }
161
+ }
162
+ },
163
+ "cloudwatch": {
164
+ "agent": {
165
+ "CLOUDWATCH_AGENT_INSTALLED_AMI_TAG": {
166
+ "type": ["string"],
167
+ "description": "Tag to be added to cloudwatch agent pre-installed AMI name."
168
+ },
169
+ "config": {
170
+ "type": ["string", "null"],
171
+ "description": "Path to Unified CloudWatch Agent config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for additional details."
172
+ },
173
+ "retryer": {
174
+ "max_attempts": {
175
+ "type": ["integer", "null"],
176
+ "description": "Max allowed Unified CloudWatch Agent installation attempts on any host."
177
+ },
178
+ "delay_seconds": {
179
+ "type": ["integer", "null"],
180
+ "description": "Seconds to wait between each Unified CloudWatch Agent installation attempt."
181
+ }
182
+ }
183
+ },
184
+ "dashboard": {
185
+ "name": {
186
+ "type": ["string", "null"],
187
+ "description": "User defined CloudWatch Dashboard name."
188
+ },
189
+ "config": {
190
+ "type": ["string", "null"],
191
+ "description": "Path to CloudWatch Dashboard config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html for additional details."
192
+ }
193
+ },
194
+ "alarm": {
195
+ "config": {
196
+ "type": ["string", "null"],
197
+ "description": "Path to CloudWatch Alarm config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricAlarm.html for additional details."
198
+ }
199
+ }
200
+ }
201
+ }
202
+ },
203
+ "auth": {
204
+ "type": "object",
205
+ "description": "How Ray will authenticate with newly launched nodes.",
206
+ "additionalProperties": false,
207
+ "properties": {
208
+ "ssh_user": {
209
+ "type": "string",
210
+ "default": "ubuntu"
211
+ },
212
+ "ssh_public_key": {
213
+ "type": "string"
214
+ },
215
+ "ssh_private_key": {
216
+ "type": "string"
217
+ },
218
+ "ssh_proxy_command": {
219
+ "description": "A value for ProxyCommand ssh option, for connecting through proxies. Example: nc -x proxy.example.com:1234 %h %p",
220
+ "type": "string"
221
+ }
222
+ }
223
+ },
224
+ "docker": {
225
+ "type": "object",
226
+ "description": "Docker configuration. If this is specified, all setup and start commands will be executed in the container.",
227
+ "additionalProperties": false,
228
+ "properties": {
229
+ "image": {
230
+ "type": "string",
231
+ "description": "the docker image name",
232
+ "default": "rayproject/ray:latest"
233
+ },
234
+ "container_name": {
235
+ "type": "string",
236
+ "default": "ray_docker"
237
+ },
238
+ "pull_before_run": {
239
+ "type": "boolean",
240
+ "description": "run `docker pull` first"
241
+ },
242
+ "run_options": {
243
+ "type": "array",
244
+ "description": "shared options for starting head/worker docker"
245
+ },
246
+ "head_image": {
247
+ "type": "string",
248
+ "description": "image for head node, takes precedence over 'image' if specified"
249
+ },
250
+ "head_run_options": {
251
+ "type": "array",
252
+ "description": "head specific run options, appended to run_options"
253
+ },
254
+ "worker_image": {
255
+ "type": "string",
256
+ "description": "analogous to head_image"
257
+ },
258
+ "worker_run_options": {
259
+ "type": "array",
260
+ "description": "analogous to head_run_options"
261
+ },
262
+ "disable_automatic_runtime_detection" : {
263
+ "type": "boolean",
264
+ "description": "disable Ray from automatically using the NVIDIA runtime if available",
265
+ "default": false
266
+ },
267
+ "disable_shm_size_detection" : {
268
+ "type": "boolean",
269
+ "description": "disable Ray from automatically detecting /dev/shm size for the container",
270
+ "default": false
271
+ },
272
+ "use_podman" : {
273
+ "type": "boolean",
274
+ "description": "Use 'podman' command in place of 'docker'",
275
+ "default": false
276
+ }
277
+ }
278
+ },
279
+ "head_node_type": {
280
+ "type": "string",
281
+ "description": "If using multiple node types, specifies the head node type."
282
+ },
283
+ "file_mounts": {
284
+ "type": "object",
285
+ "description": "Map of remote paths to local paths, e.g. {\"/tmp/data\": \"/my/local/data\"}"
286
+ },
287
+ "cluster_synced_files": {
288
+ "type": "array",
289
+ "description": "List of paths on the head node which should sync to the worker nodes, e.g. [\"/some/data/somehwere\"]"
290
+ },
291
+ "file_mounts_sync_continuously": {
292
+ "type": "boolean",
293
+ "description": "If enabled, file mounts will sync continously between the head node and the worker nodes. The nodes will not re-run setup commands if only the contents of the file mounts folders change."
294
+ },
295
+ "rsync_exclude": {
296
+ "type": "array",
297
+ "description": "File pattern to not sync up or down when using the rsync command. Matches the format of rsync's --exclude param."
298
+ },
299
+ "rsync_filter": {
300
+ "type": "array",
301
+ "description": "Pattern files to lookup patterns to exclude when using rsync up or rsync down. This file is checked for recursively in all directories. For example, if .gitignore is provided here, the behavior will match git's .gitignore behavior."
302
+ },
303
+ "metadata": {
304
+ "type": "object",
305
+ "description": "Metadata field that can be used to store user-defined data in the cluster config. Ray does not interpret these fields."
306
+ },
307
+ "initialization_commands": {
308
+ "$ref": "#/definitions/commands",
309
+ "description": "List of commands that will be run before `setup_commands`. If docker is enabled, these commands will run outside the container and before docker is setup."
310
+ },
311
+ "setup_commands": {
312
+ "$ref": "#/definitions/commands",
313
+ "description": "List of common shell commands to run to setup nodes."
314
+ },
315
+ "head_setup_commands": {
316
+ "$ref": "#/definitions/commands",
317
+ "description": "Commands that will be run on the head node after common setup."
318
+ },
319
+ "worker_setup_commands": {
320
+ "$ref": "#/definitions/commands",
321
+ "description": "Commands that will be run on worker nodes after common setup."
322
+ },
323
+ "head_start_ray_commands": {
324
+ "$ref": "#/definitions/commands",
325
+ "description": "Command to start ray on the head node. You shouldn't need to modify this."
326
+ },
327
+ "worker_start_ray_commands": {
328
+ "$ref": "#/definitions/commands",
329
+ "description": "Command to start ray on worker nodes. You shouldn't need to modify this."
330
+ },
331
+ "no_restart": {
332
+ "description": "Whether to avoid restarting the cluster during updates. This field is controlled by the ray --no-restart flag and cannot be set by the user."
333
+ },
334
+ "available_node_types": {
335
+ "type": "object",
336
+ "description": "A list of node types for multi-node-type autoscaling.",
337
+ "patternProperties": {
338
+ ".*": {
339
+ "type": "object",
340
+ "required": [ "resources", "node_config" ],
341
+ "properties": {
342
+ "node_config": {
343
+ "type": "object",
344
+ "description": "Provider-specific config for the node, e.g. instance type."
345
+ },
346
+ "min_workers": {"type": "integer"},
347
+ "max_workers": {"type": "integer"},
348
+ "idle_timeout_s": {"type": "number", "nullable": true},
349
+ "resources": {
350
+ "type": "object",
351
+ "patternProperties": {
352
+ ".*":{
353
+ "type": "integer",
354
+ "minimum": 0
355
+ }
356
+ }
357
+ },
358
+ "labels": {
359
+ "type": "object",
360
+ "patternProperties": {
361
+ ".*":{
362
+ "type": "string"
363
+ }
364
+ }
365
+ },
366
+ "initialization_commands": {
367
+ "$ref": "#/definitions/commands",
368
+ "description": "List of commands that will be run before `setup_commands`. If docker is enabled, these commands will run outside the container and before docker is setup."
369
+ },
370
+ "worker_setup_commands": {
371
+ "$ref": "#/definitions/commands",
372
+ "description": "List of common shell commands to run to setup nodes. This node specfic list will override the global setup_commands and worker_setup_commands."
373
+ },
374
+ "docker": {
375
+ "description": "Configuration of Worker nodes.",
376
+ "type": "object",
377
+ "properties": {
378
+ "pull_before_run": {
379
+ "type": "boolean",
380
+ "description": "run `docker pull` first"
381
+ },
382
+ "worker_image": {
383
+ "type": "string",
384
+ "description": "analogous to head_image"
385
+ },
386
+ "worker_run_options": {
387
+ "type": "array",
388
+ "description": "analogous to head_run_options, merged with the global docker run_options."
389
+ }
390
+ },
391
+ "additionalProperties": false
392
+ }
393
+ },
394
+ "additionalProperties": false
395
+ }
396
+ },
397
+ "additionalProperties": false
398
+ }
399
+ }
400
+ }
vllm/lib/python3.10/site-packages/ray/autoscaler/spark/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/autoscaler/spark/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/autoscaler/spark/defaults.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example command to start a cluster with this config:
2
+ #
3
+ # ray start --autoscaling-config=default.yaml --head --block
4
+ #
5
+ cluster_name: spark
6
+ max_workers: 8
7
+ provider:
8
+ type: spark
9
+ # This must be true since the nodes share the same ip!
10
+ use_node_id_as_ip: True
11
+ disable_node_updaters: True
12
+ disable_launch_config_check: True
13
+ available_node_types:
14
+ ray.head.default:
15
+ # You must set this manually to your "head" node resources!! The head
16
+ # node is launched via `ray start` and hence the autoscaler cannot
17
+ # configure its resources. The resources specified for its node type
18
+ # must line up with what Ray detects/is configured with on start.
19
+ resources:
20
+ CPU: 8 # <-- set this to num CPUs used/detected in `ray start`
21
+ GPU: 0 # <-- set this to num GPUs used/detected in `ray start`
22
+ node_config: {}
23
+ max_workers: 0
24
+ ray.worker:
25
+ resources:
26
+ CPU: 1
27
+ object_store_memory: 1000000000
28
+ node_config: {}
29
+ min_workers: 0
30
+ max_workers: 4
31
+ head_node_type: ray.head.default
32
+ upscaling_speed: 1.0
33
+ idle_timeout_minutes: 1.0
34
+ #
35
+ # !!! Configurations below are not supported in spark cluster mode
36
+ #
37
+ auth: {}
38
+ docker: {}
39
+ initialization_commands: []
40
+ setup_commands: []
41
+ head_setup_commands: []
42
+ worker_setup_commands: []
43
+ head_start_ray_commands: []
44
+ worker_start_ray_commands: []
45
+ file_mounts: {}
46
+ cluster_synced_files: []
47
+ file_mounts_sync_continuously: false
48
+ rsync_exclude: []
49
+ rsync_filter: []