Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hard Limit scripts #4738

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions samples/scripts/PowerShell/HardLimit/Events/EnableEvents.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Define parameters
$subscriptionId = Read-Host "Subscription Id"
$resourceGroupName = Read-Host "Resource group name"
$tenantId = Read-Host "Tenant Id"
$workspaceName = Read-Host "Workspace name"
$eventSubscriptionName = Read-Host "Event subscription name"
$eventHubNamespace = Read-Host "Event hub namespace"
$eventHubName = Read-Host "Event hub name"
$eventHubResourceGroup = Read-Host "Event hub resource group name"

# Authenticate with Azure (if not already authenticated)
Connect-AzAccount -UseDeviceAuthentication

# Set the Azure subscription
Set-AzContext -SubscriptionId $subscriptionId -TenantId $tenantId

# Get the Health Data Workspace resource
$workspace = Get-AzResource -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.HealthcareApis/workspaces" -Name $workspaceName

# Get the Event Hub resource ID
$eventHub = Get-AzEventHub -ResourceGroupName $eventHubResourceGroup -NamespaceName $eventHubNamespace -EventHubName $eventHubName
$eventHubResourceId = $eventHub.Id

# Log and display the eventHubResourceId ID
Write-Output "eventHubResourceId : $eventHubResourceId"

# Create Event Hub Destination
$eventHubDestination = New-AzEventGridEventHubEventSubscriptionDestinationObject -ResourceId $eventHubResourceId


# Get the Azure Health Data Workspace ID
$workspaceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.HealthcareApis/workspaces/$workspaceName"

# Log and display the workspace ID
Write-Output "Workspace ID: $workspaceId"

# Start Timer and Create Event Grid Subscription
$startTime = [datetime]::Now

# Define Event Types to Filter
$eventTypes = @(
'Microsoft.HealthcareApis.FhirResourceCreated',
'Microsoft.HealthcareApis.FhirResourceUpdated',
'Microsoft.HealthcareApis.FhirResourceDeleted'
)

# Create the Event Grid subscription
New-AzEventGridSubscription -Name $eventSubscriptionName `
-Scope $workspaceId `
-Destination $eventHubDestination `
-FilterIncludedEventType $eventTypes

# Check Provisioning States for Event Grid Subscription and Health Data Workspace
$eventGridProvisioningState = ""
$workspaceProvisioningState = ""

while ($eventGridProvisioningState -ne "Succeeded" -or $workspaceProvisioningState -ne "Succeeded") {
Start-Sleep -Seconds 5

# Check Event Grid Subscription Provisioning State
$eventGridSubscription = Get-AzEventGridSubscription -Name $eventSubscriptionName -Scope $workspaceId
$eventGridProvisioningState = $eventGridSubscription.ProvisioningState
#Write-Output "Event Grid Provisioning State: $eventGridProvisioningState"

# Check Health Data Workspace Provisioning State
$workspace = Get-AzResource -ResourceId $workspaceId
$workspaceProvisioningState = $workspace.Properties.provisioningState
Write-Output "Workspace Provisioning State: $workspaceProvisioningState"
}

# End Timer and Display Total Time
$endTime = [datetime]::Now
$totalTime = $endTime - $startTime
$totalMinutes = $totalTime.TotalSeconds / 60 # Convert seconds to minutes

Write-Output "Event Grid subscription for Health Data workspace enabled successfully. Time taken: $($totalTime.TotalSeconds) seconds."
Write-Output "Event Grid subscription for Health Data workspace enabled successfully. Time taken: $([math]::Round($totalMinutes, 2)) minutes."


# verify the event state of the all the FHIR services under given workspace
Write-Output "Verify the event state of the all the FHIR services under given workspace"


# Get all FHIR services under the specified Health Data workspace
$fhirServices = Get-AzResource -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.HealthcareApis/workspaces/fhirservices" |
Where-Object { $_.ResourceId -like "$workspaceId*" }

# Display the count of FHIR services
Write-Output "Total FHIR services under the specified workspace: $($fhirServices.Count)"

# Flag to track the event state
$allServicesEnabled = $true
$enabledCounter = 0

# Loop through each FHIR service to check the event state
foreach ($fhirService in $fhirServices) {
# Get the FHIR service details
$fhirServiceDetails = Get-AzResource -ResourceId $fhirService.ResourceId -ExpandProperties

# Access the event state property (adjusting for any naming conventions)
$eventState = $fhirServiceDetails.Properties.eventState

# Check the event state
if ($eventState -eq "Enabled") {
$enabledCounter++
Write-Host "$enabledCounter. FHIR Service '$($fhirService.Name)': Event state is Enabled."
} else {
Write-Host "FHIR Service '$($fhirService.Name)': Event state is Disabled or Unavailable."
$allServicesEnabled = $false
break
}
}

# Final status message
if ($allServicesEnabled) {
Write-Host "All FHIR services event states are enabled."
} else {
Write-Host "Failure: At least one FHIR service event state is disabled or unavailable."
}
56 changes: 56 additions & 0 deletions samples/scripts/PowerShell/HardLimit/Events/Resource.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"resourceType": "Patient",
"id": "glossy",
"meta": {
"lastUpdated": "2014-11-13T11:41:00+11:00"
},
"text": {
"status": "generated",
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <p>Henry Levin the 7th</p>\n <p>MRN: 123456. Male, 24-Sept 1932</p>\n </div>"
},
"extension": [
{
"url": "http://example.org/StructureDefinition/trials",
"valueCode": "renal"
}
],
"identifier": [
{
"use": "usual",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MR"
}
]
},
"system": "http://www.goodhealth.org/identifiers/mrn",
"value": "123456"
}
],
"active": true,
"name": [
{
"family": "Levin",
"given": [
"Henry"
],
"suffix": [
"The 7th"
]
}
],
"gender": "male",
"birthDate": "1932-09-24",
"generalPractitioner": [
{
"reference": "Practitioner/example",
"display": "Dr Adam Careful"
}
],
"managingOrganization": {
"reference": "Organization/2",
"display": "Good Health Clinic"
}
}
73 changes: 73 additions & 0 deletions samples/scripts/PowerShell/HardLimit/Events/ValidateEvents.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Variables
$subscriptionId = Read-Host "Subscription Id"
$resourceGroupName = Read-Host "Resource group name"
$tenantId = Read-Host "Tenant Id"
$workspaceName = Read-Host "Workspace name"
$clientId = Read-Host "Client Id of App registration"
$clientSecret = Read-Host "Client secret" -AsSecureString # Secure this appropriately
$jsonFilePath = Join-Path -Path $PSScriptRoot -ChildPath 'Resource.json' # Local file path to the FHIR resource JSON
$resourceType = "Patient" # Type of FHIR resource

# Authenticate with Azure (if not already authenticated)
Connect-AzAccount -UseDeviceAuthentication

# Set the Azure subscription
Set-AzContext -SubscriptionId $subscriptionId -TenantId $tenantId

# Construct the resource ID for the workspace
$workspaceResourceId = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.HealthcareApis/workspaces/$workspaceName"

# Read Resource JSON from the local file
$fhirResourceJson = Get-Content -Path $jsonFilePath -Raw

# Get all FHIR services under the specified Health Data workspace
$fhirServices = Get-AzResource -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.HealthcareApis/workspaces/fhirservices" |
Where-Object { $_.ResourceId -like "$workspaceResourceId*" }

# Initialize the loop counter
$count = 0

# Loop through each FHIR instance to generate an access token and make the HTTP request
foreach ($fhirService in $fhirServices) {

# Replace '/' with '-' in the FHIR service name
$fhirServiceName = $fhirService.Name -replace '/', '-'
Write-Output "FHIR Service Name: '$($fhirServiceName)'"

# Generate Bearer Token for each FHIR instance
$authBody = @{
"grant_type" = "client_credentials"
"client_id" = $clientId
"client_secret" = $clientSecret
"scope" = "https://$($fhirServiceName).fhir.azurehealthcareapis.com/.default" # Scope for the FHIR service
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -Body $authBody -ContentType "application/x-www-form-urlencoded"
$bearerToken = $tokenResponse.access_token

# Define the FHIR service URL
$fhirServiceUrl = "https://$($fhirServiceName).fhir.azurehealthcareapis.com"
Write-Output "FHIR Service URL: '$($fhirServiceUrl)'"

# Make the HTTP POST request with the bearer token as authorization
try {
# Use Invoke-WebRequest to access the StatusCode directly
$response = Invoke-WebRequest -Uri "$fhirServiceUrl/$resourceType" -Method Post -Body $fhirResourceJson -ContentType "application/fhir+json" -Headers @{ Authorization = "Bearer $bearerToken" }

# Check if the request was successful
if ($response.StatusCode -eq 201) {
Write-Output "FHIR resource created successfully in instance '$($fhirServiceName)'. Status Code: 201"
} else {
Write-Output "FHIR resource creation response in instance '$($fhirServiceName)'. Status Code: $($response.StatusCode)"
}

# Increment the counter on success
$count++
Write-Output "Processed FHIR instance count: $count"
}
catch {
Write-Output "Error posting FHIR resource to instance '$($fhirServiceName)': $_"
}
}

# Final completion message
Write-Output "Resource POST request complete for all FHIR services. Total processed: $count"
126 changes: 126 additions & 0 deletions samples/scripts/PowerShell/HardLimit/Events/main.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"defaultValue": "[resourceGroup().location]",
"type": "String",
"metadata": {
"description": "Location for all resources."
}
},
"fhirServiceCount": {
"defaultValue": 80,
"type": "Int",
"metadata": {
"description": "Number of FHIR services to deploy in the workspace."
}
},
"existingWorkspaceName": {
"type": "String",
"metadata": {
"description": "Name of the existing FHIR workspace."
}
},
"eventHubNamespaceName": {
"type": "string",
"metadata": {
"description": "Name for the Event Hub namespace."
}
},
"eventHubName": {
"type": "string",
"metadata": {
"description": "Name for the Event Hub instance."
}
}
},
"variables": {
"tenantId": "[subscription().tenantId]"
},
"resources": [
{
"type": "Microsoft.HealthcareApis/workspaces/fhirservices",
"apiVersion": "2024-03-31",
"name": "[format('{0}/fhirserver{1}', parameters('existingWorkspaceName'), copyIndex(1))]",
"location": "[parameters('location')]",
"kind": "fhir-R4",
"identity": {
"type": "None"
},
"properties": {
"acrConfiguration": {
"loginServers": []
},
"authenticationConfiguration": {
"authority": "[concat('https://login.microsoftonline.com/', variables('tenantId'))]",
"audience": "[concat('https://', parameters('existingWorkspaceName'), '-fhirserver', copyIndex(1), '.fhir.azurehealthcareapis.com')]",
"smartProxyEnabled": false,
"smartIdentityProviders": []
},
"corsConfiguration": {
"origins": [],
"headers": [],
"methods": [],
"allowCredentials": false
},
"exportConfiguration": {},
"importConfiguration": {
"enabled": false,
"initialImportMode": false
},
"resourceVersionPolicyConfiguration": {
"default": "versioned",
"resourceTypeOverrides": {}
},
"implementationGuidesConfiguration": {
"usCoreMissingData": false
},
"encryption": {
"customerManagedKeyEncryption": {}
},
"publicNetworkAccess": "Enabled"
},
"copy": {
"name": "fhirServiceCopy",
"count": "[parameters('fhirServiceCount')]"
}
},
{
"type": "Microsoft.EventHub/namespaces",
"apiVersion": "2024-01-01",
"name": "[parameters('eventHubNamespaceName')]",
"location": "[parameters('location')]",
"sku": {
"name": "Standard",
"tier": "Standard"
},
"properties": {
"isAutoInflateEnabled": false
}
},
{
"type": "Microsoft.EventHub/namespaces/eventhubs",
"apiVersion": "2024-01-01",
"name": "[format('{0}/{1}', parameters('eventHubNamespaceName'), parameters('eventHubName'))]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.EventHub/namespaces', parameters('eventHubNamespaceName'))]"
],
"properties": {
"messageRetentionInDays": 1,
"partitionCount": 2
}
}
],
"outputs": {
"eventHubNamespaceId": {
"type": "string",
"value": "[resourceId('Microsoft.EventHub/namespaces', parameters('eventHubNamespaceName'))]"
},
"eventHubId": {
"type": "string",
"value": "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('eventHubNamespaceName'), parameters('eventHubName'))]"
}
}
}
Loading
Loading