Skip to content

Commit 9dbc13b

Browse files
authored
Update scheduled-events.md
1 parent 01df3d7 commit 9dbc13b

File tree

1 file changed

+174
-36
lines changed

1 file changed

+174
-36
lines changed

articles/virtual-machines/windows/scheduled-events.md

Lines changed: 174 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ Scheduled Events is disabled for your service if it does not make a request for
9797
### User-initiated maintenance
9898
User-initiated VM maintenance via the Azure portal, API, CLI, or PowerShell results in a scheduled event. You then can test the maintenance preparation logic in your application, and your application can prepare for user-initiated maintenance.
9999

100-
If you restart a VM, an event with the type `Reboot` is scheduled. If you redeploy a VM, an event with the type `Redeploy` is scheduled.
100+
If you restart a VM, an event with the type `Reboot` is scheduled. If you redeploy a VM, an event with the type `Redeploy` is scheduled. Typically events with a user event source can be immediately approved to avoid a delay on user-initiated actions.
101101

102102
## Use the API
103103

@@ -115,6 +115,22 @@ curl -H Metadata:true http://169.254.169.254/metadata/scheduledevents?api-versio
115115
```
116116
Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01" | ConvertTo-Json -Depth 64
117117
```
118+
#### Python sample
119+
````
120+
import json
121+
import requests
122+
123+
metadata_url ="http://169.254.169.254/metadata/scheduledevents"
124+
header = {'Metadata' : 'true'}
125+
query_params = {'api-version':'2020-07-01'}
126+
127+
def get_scheduled_events():
128+
resp = requests.get(metadata_url, headers = header, params = query_params)
129+
data = resp.json()
130+
return data
131+
132+
````
133+
118134

119135
A response contains an array of scheduled events. An empty array means that currently no events are scheduled.
120136
In the case where there are scheduled events, the response contains an array of events.
@@ -164,6 +180,7 @@ Each event is scheduled a minimum amount of time in the future based on the even
164180

165181
> [!NOTE]
166182
> In some cases, Azure is able to predict host failure due to degraded hardware and will attempt to mitigate disruption to your service by scheduling a migration. Affected virtual machines will receive a scheduled event with a `NotBefore` that is typically a few days in the future. The actual time varies depending on the predicted failure risk assessment. Azure tries to give 7 days' advance notice when possible, but the actual time varies and might be smaller if the prediction is that there is a high chance of the hardware failing imminently. To minimize risk to your service in case the hardware fails before the system-initiated migration, we recommend that you self-redeploy your virtual machine as soon as possible.
183+
167184
>[!NOTE]
168185
> In the case the host node experiences a hardware failure Azure will bypass the minimum notice period an immediately begin the recovery process for affected virtual machines. This reduces recovery time in the case that the affected VMs are unable to respond. During the recovery process an event will be created for all impacted VMs with EventType = Reboot and EventStatus = Started
169186
@@ -173,7 +190,7 @@ You can poll the endpoint for updates as frequently or infrequently as you like.
173190

174191
### Start an event
175192

176-
After you learn of an upcoming event and finish your logic for graceful shutdown, you can approve the outstanding event by making a `POST` call to Metadata Service with `EventId`. This call indicates to Azure that it can shorten the minimum notification time (when possible).
193+
After you learn of an upcoming event and finish your logic for graceful shutdown, you can approve the outstanding event by making a `POST` call to Metadata Service with `EventId`. This call indicates to Azure that it can shorten the minimum notification time (when possible). The event may not start immediately upon approval, in some cases Azure will require the approval of all the VMs hosted on the node before proceeding with the event.
177194

178195
The following JSON sample is expected in the `POST` request body. The request should contain a list of `StartRequests`. Each `StartRequest` contains `EventId` for the event you want to expedite:
179196
```
@@ -186,6 +203,9 @@ The following JSON sample is expected in the `POST` request body. The request sh
186203
}
187204
```
188205

206+
The service will always return a 200 success code in the case of a valid event ID, even if it was already approved by a different VM. A 400 error code indicates that the request header or payload was malformed.
207+
208+
189209
#### Bash sample
190210
```
191211
curl -H Metadata:true -X POST -d '{"StartRequests": [{"EventId": "f020ba2e-3bc0-4c40-a10b-86575a9eabd5"}]}' http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01
@@ -194,63 +214,181 @@ curl -H Metadata:true -X POST -d '{"StartRequests": [{"EventId": "f020ba2e-3bc0-
194214
```
195215
Invoke-RestMethod -Headers @{"Metadata" = "true"} -Method POST -body '{"StartRequests": [{"EventId": "5DD55B64-45AD-49D3-BBC9-F57D4EA97BD7"}]}' -Uri http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01 | ConvertTo-Json -Depth 64
196216
```
217+
#### Python sample
218+
````
219+
import json
220+
import requests
221+
222+
def confirm_scheduled_event(event_id):
223+
# This payload confirms a single event with id event_id
224+
payload = json.dumps({"StartRequests": [{"EventId": event_id }]})
225+
response = requests.post(metadata_url, headers= header, params = query_params, data = payload)
226+
return response.status_code
227+
228+
````
197229

198230
> [!NOTE]
199231
> Acknowledging an event allows the event to proceed for all `Resources` in the event, not just the VM that acknowledges the event. Therefore, you can choose to elect a leader to coordinate the acknowledgement, which might be as simple as the first machine in the `Resources` field.
200232
201-
## Python Sample
233+
## Example responses
234+
The following is an example of a series of events that were seen by two VMs that were live migrated to another node.
202235

203-
The following sample queries Metadata Service for scheduled events and approves each outstanding event:
236+
The `DocumentIncarnation` is changing every time there is new information in `Events`. An approval of the event would allow the freeze to proceed for both WestNO_0 and WestNO_1. The `DurationInSeconds` of -1 indicates that the platform does not know how long the operation will take.
204237

205-
```python
206-
#!/usr/bin/python
238+
```JSON
239+
{
240+
"DocumentIncarnation": 1,
241+
"Events": [
242+
]
243+
}
207244

208-
import json
209-
import socket
210-
import urllib2
245+
{
246+
"DocumentIncarnation": 2,
247+
"Events": [
248+
{
249+
"EventId": "C7061BAC-AFDC-4513-B24B-AA5F13A16123",
250+
"EventStatus": "Scheduled",
251+
"EventType": "Freeze",
252+
"ResourceType": "VirtualMachine",
253+
"Resources": [
254+
"WestNO_0",
255+
"WestNO_1"
256+
],
257+
"NotBefore": "Mon, 11 Apr 2022 22:26:58 GMT",
258+
"Description": "Virtual machine is being paused because of a memory-preserving Live Migration operation.",
259+
"EventSource": "Platform",
260+
"DurationInSeconds": -1
261+
}
262+
]
263+
}
211264

212-
metadata_url = "http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01"
213-
this_host = socket.gethostname()
265+
{
266+
"DocumentIncarnation": 3,
267+
"Events": [
268+
{
269+
"EventId": "C7061BAC-AFDC-4513-B24B-AA5F13A16123",
270+
"EventStatus": "Started",
271+
"EventType": "Freeze",
272+
"ResourceType": "VirtualMachine",
273+
"Resources": [
274+
"WestNO_0",
275+
"WestNO_1"
276+
],
277+
"NotBefore": "",
278+
"Description": "Virtual machine is being paused because of a memory-preserving Live Migration operation.",
279+
"EventSource": "Platform",
280+
"DurationInSeconds": -1
281+
}
282+
]
283+
}
214284

285+
{
286+
"DocumentIncarnation": 4,
287+
"Events": [
288+
]
289+
}
215290

216-
def get_scheduled_events():
217-
req = urllib2.Request(metadata_url)
218-
req.add_header('Metadata', 'true')
219-
resp = urllib2.urlopen(req)
220-
data = json.loads(resp.read())
221-
return data
291+
```
222292

293+
## Python Sample
294+
295+
The following sample queries Metadata Service for scheduled events and approves each outstanding event:
223296

224-
def handle_scheduled_events(data):
225-
for evt in data['Events']:
226-
eventid = evt['EventId']
227-
status = evt['EventStatus']
228-
resources = evt['Resources']
229-
eventtype = evt['EventType']
230-
resourcetype = evt['ResourceType']
231-
notbefore = evt['NotBefore'].replace(" ", "_")
232-
description = evt['Description']
233-
eventSource = evt['EventSource']
234-
if this_host in resources:
235-
print("+ Scheduled Event. This host " + this_host +
236-
" is scheduled for " + eventtype +
237-
" by " + eventSource +
238-
" with description " + description +
239-
" not before " + notbefore)
240-
# Add logic for handling events here
297+
```python
298+
#!/usr/bin/python
299+
import json
300+
import requests
301+
from time import sleep
302+
303+
# The URL to access the metadata service
304+
metadata_url ="http://169.254.169.254/metadata/scheduledevents"
305+
# This must be sent otherwise the request will be ignored
306+
header = {'Metadata' : 'true'}
307+
# Current version of the API
308+
query_params = {'api-version':'2020-07-01'}
309+
310+
def get_scheduled_events():
311+
resp = requests.get(metadata_url, headers = header, params = query_params)
312+
data = resp.json()
313+
return data
241314

315+
def confirm_scheduled_event(event_id):
316+
# This payload confirms a single event with id event_id
317+
# You can confirm multiple events in a single request if needed
318+
payload = json.dumps({"StartRequests": [{"EventId": event_id }]})
319+
response = requests.post(metadata_url,
320+
headers= header,
321+
params = query_params,
322+
data = payload)
323+
return response.status_code
324+
325+
def log(event):
326+
# This is an optional placeholder for logging events to your system
327+
print(event["Description"])
328+
return
329+
330+
def advanced_sample(last_document_incarnation):
331+
# Poll every second to see if there are new scheduled events to process
332+
# Since some events may have necessarily short warning periods, it is
333+
# recommended to poll frequently
334+
found_document_incarnation = last_document_incarnation
335+
while (last_document_incarnation == found_document_incarnation):
336+
sleep(1)
337+
payload = get_scheduled_events()
338+
found_document_incarnation = payload["DocumentIncarnation"]
339+
340+
# We recommend processing all events in a document incarnation together,
341+
# even if you won't be actioning on them right away
342+
for event in payload["Events"]:
343+
# Events that have already started, logged for tracking
344+
if (event["EventStatus"] == "Started"):
345+
log(event)
346+
347+
# Approve all user initiated events. These are typically created by an
348+
# administrator and approving them immediately can help to avoid delays
349+
# in admin actions
350+
elif (event["EventSource"] == "User"):
351+
confirm_scheduled_event(event["EventId"])
352+
353+
# For this application, freeze events less that 9 seconds are considered
354+
# no impact. This will immediately approve them
355+
elif (event["EventType"] == "Freeze" and
356+
int(event["DurationInSeconds"]) >= 0 and
357+
int(event["DurationInSeconds"]) < 9):
358+
confirm_scheduled_event(event["EventId"])
359+
360+
# Events that may be impactful (eg. Reboot or redeploy) may need custom
361+
# handling for your application
362+
else:
363+
#TODO Custom handling for impactful events
364+
log(event)
365+
print("Processed events from document: " + str(found_document_incarnation))
366+
return found_document_incarnation
242367

243368
def main():
244-
data = get_scheduled_events()
245-
handle_scheduled_events(data)
369+
# This will track the last set of events seen
370+
last_document_incarnation = "-1"
371+
372+
input_text = "\
373+
Press 1 to poll for new events \n\
374+
Press 2 to exit \n "
375+
program_exit = False
246376

377+
while program_exit == False:
378+
user_input = input(input_text)
379+
if (user_input == "1"):
380+
last_document_incarnation = advanced_sample(last_document_incarnation)
381+
elif (user_input == "2"):
382+
program_exit = True
247383

248384
if __name__ == '__main__':
249385
main()
250386
```
251387

252388
## Next steps
253389
- Review the Scheduled Events code samples in the [Azure Instance Metadata Scheduled Events GitHub repository](https://github.com/Azure-Samples/virtual-machines-scheduled-events-discover-endpoint-for-non-vnet-vm).
390+
- Review the nodejs Scheduled Events code samples in [Azure Samples GitHub repository](https://github.com/Azure/vm-scheduled-events).
254391
- Read more about the APIs that are available in the [Instance Metadata Service](instance-metadata-service.md).
255392
- Learn about [planned maintenance for Windows virtual machines in Azure](../maintenance-and-updates.md?bc=/azure/virtual-machines/windows/breadcrumb/toc.json&toc=/azure/virtual-machines/windows/toc.json).
256393
- Learn how to [monitor scheduled events for your VMs through Log Analytics](./scheduled-event-service.md).
394+
- Learn how to log scheduled events using Azure Event Hub in the [Azure Samples GitHub repository](https://github.com/Azure-Samples/virtual-machines-python-scheduled-events-central-logging).

0 commit comments

Comments
 (0)