Obs/bin/GMA/GMATenantJsonHelper.psm1

##------------------------------------------------------------------
## <copyright file="GMATenantJsonHelper.psm1" company="Microsoft">
## Copyright (C) Microsoft. All rights reserved.
## </copyright>
##------------------------------------------------------------------

## Import ObservabilityGMAEventSource
Add-Type -Path "$PSScriptRoot\Microsoft.AzureStack.Observability.GenevaMonitoringAgent.dll" -Verbose
Add-Type -Path "$PSScriptRoot\Microsoft.AzureStack.Observability.ObservabilityCommon.dll" -Verbose
Add-Type -Path "$PSScriptRoot\Newtonsoft.Json.dll" -Verbose

#region Constant vairables
$global:ErrorConstants = @{
    DefaultErrorMessage = @{
        Code = 1
        Name = "DefaultErrorMessage"
        Message = "An unhandled exception has occurred."
    }
    ManagementClusterNameNotFound = @{
        Code = 2
        Name = "ManagementClusterNameNotFound"
        Message = "ManagementClusterName not found in Cloud config."
    }
    CannotCopyUtcExporterDll = @{
        Code = 3
        Name = 'CannotCopyUtcExporterDll'
        Message = "Failed to copy UtcExporterDll file."
    }
    CannotStartService = @{
        Code = 4
        Name = 'CannotStartService'
        Message = "Observability related service cannot be started after multiple retries."
    }
    CannotStopService = @{
        Code = 5
        Name = 'CannotStopService'
        Message = "Observability related service cannot be stopped after multiple retries."
    }
    ConfigFolderDoesNotExist = @{
        Code = 6
        Name = 'ConfigFolderDoesNotExists'
        Message = "Config folder doesn't exist."
    }
    HandlerEnvJsonDoesNotExist = @{
        Code = 8
        Name = 'HandlerEnvJsonDoesNotExist'
        Message = "HandlerEnvironment.json file doesn't exist."
    }
    InsufficientDiskSpaceForGMACache = @{
        Code = 9
        Name = 'InsufficientDiskSpaceForGMACache'
        Message = "There is insufficient disk space available on the drive (Current size = {0} GB on {1} drive). To proceed with the extension installation, please delete some files to free up space."
    }
    LogFolderDoesNotExist = @{
        Code = 10
        Name = 'LogFolderDoesNotExist'
        Message = "Log folder doesn't exist."
    }
    StatusFolderDoesNotExist = @{
        Code = 11
        Name = 'StatusFolderDoesNotExist'
        Message = "Status folder doesn't exist."
    }
    GetAzureStackHCICmdletNotAvailable = @{
        Code = 12
        Name = 'GetAzureStackHCICmdletNotAvailable'
        Message = "If either the Get-AzureStackHCI or Get-ClusterNode cmdlet is not available to retrieve the necessary information, the tenant JSON configuration files will not be created."
    }
    InvalidScheduledTaskScriptPath = @{
        Code = 13
        Name = 'InvalidScheduledTaskScriptPath'
        Message = 'Invalid script path provided for scheduled task creation.'
    }
    TelemetryDisabled = @{
        Code = 14
        Name = 'TelemetryDisabled'
        Message = 'Telemetry is disabled.'
    }
    CannotRegisterService = @{
        Code = 15
        Name = 'CannotRegisterService'
        Message = 'Observability related service cannot be registered.'
    }
    MetricsRegionalNamespaceNotFound = @{
        Code = 16
        Name = 'RegionalMetricNamespaceNotFound'
        Message = 'Regional Metric Namespaces not found.'
    }
    VCRedistInstallFailed= @{
        Code = 17
        Name = 'VCRedistInstallFailed'
        Message = "Failed to install VC Redistributable VC_redist.x64.exe. Exit code is {0}"
    }
    GcsConfigFilesNotFound = @{
        Code = 18
        Name = 'GcsConfigFilesNotFound'
        Message = "GCSConfig files are not found. Please check the logs for further investigation."
    }
    SecurityJsonNotToBeCreatedInExt = @{
        Code = 20
        Name = 'SecurityJsonNotToBeCreatedInExt'
        Message = "Tenant json for Security config is not be created through extension. It will be generated on-demand by enabling/disabling of SysLogForwarder setting."
    }
}

$global:RegistryConstants = @{
    TenantJsonCacheLocalPath = @{
        Path = "HKLM:\Software\Microsoft\AzureStack\Observability\TenantJson\{0}"
        Name = "LocalPath"
        PropertyType = "String"
    }
    TelemetryTenantGcsNamespace = @{
        Path = "HKLM:\SOFTWARE\Microsoft\AzureStack\Observability\TenantJson\Telemetry\"
        Name = "GcsNamespace"
    }
    DeviceTypeRegKey = @{
        Path = "HKLM:\SOFTWARE\Microsoft\AzureStack\"
        Name = "DeviceType"
        PropertyType = "String"
        Value = "AzureEdge"
    }
}

$global:MiscConstants = @{
    CloudNames = @{
        <#
            HCI RP Azure Environment (a.k.a Cloud) constants =
            https://msazure.visualstudio.com/One/_git/AzSHCI-Usage?path=/src/common/ServiceCommon/Models/CommonConstants.cs&version=GBdevelopment&line=25&lineEnd=35&lineStartColumn=1&lineEndColumn=2&lineStyle=plain&_a=contents
        #>

        AzurePublicCloud = @("AzurePublicCloud", "AzureCloud")
        AzureUSGovernmentCloud = @("AzureUSGovernmentCloud", "AzureUSGovernment")
        AzureChinaCloud = @("AzureChinaCloud")
        AzureGermanCloud = @("AzureGermanCloud")
        USNat = @("USNat")
        USSec = @("USSec")
        AzureCanary = @("AzureCanary")
        AzurePPE = @("AzurePPE")
    }
    CIRegKey = @{
        Path = 'HKLM:\Software\Microsoft\SQMClient\'
        Name = 'IsCIEnv'
    }
    MetricsValidationRegKey = @{
        Path = 'HKLM:\Software\Microsoft\SQMClient\'
        Name = 'Enable3PMetricsValidation'
    }
    SddcRegKey = @{        
        Path = 'HKLM:\SOFTWARE\Microsoft\SQMClient'
        Name = 'IsTest'
    }
    ArcARegKey = @{
        Path = 'HKLM:\Software\Microsoft\ArcA\'
        Name = 'IsArcAEnv'
        PropertyType = 'DWORD'
        Value = 1
    }
    ConfigTypes = @{
        Telemetry = 'Telemetry'
        Diagnostics = 'Diagnostics'
        Health = 'Health'
        Security = 'Security'
        Metrics = 'Metrics'
    }
    DiagTrackRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack'
        Name = 'AllowExporters'
        PropertyType = 'DWORD'
        Value = 1
    }
    HciDiagnosticLevel = @{
        Off = "off"
        Basic = "basic"
        Enhanced = "enhanced"
    }
    ErrorActionPreference = @{
        Ignore = "Ignore"
        Stop = "Stop"
        SilentlyContinue = "SilentlyContinue"
        Continue = "Continue"
    }
    GCSEnvironment = @{
        Test = "Test"
        Ppe = "Ppe"
        ArcAPpe = "ArcAPpe"
        Prod = "Prod"
        Fairfax = "Fairfax"
        Mooncake = "Mooncake"
    }
    GCSRegionName = @{
        EastUS = 'eastus'
        WestEurope = 'westeurope'
    }
    GenevaExporterRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\exporters\GenevaExporter'
        Name = 'DllPath'
        PropertyType = 'String'
    }
    GenevaNamespaceRegKey = @{
        Name = 'GenevaNamespace'
        PropertyType = 'String'
        Value = 'NAMESPACE_PLACEHOLDER'
    }
    EnvironmentVariableNames =  @{
        ClusterName = "CLUSTER_NAME"
        HciResourceUri = "HCI_RESOURCE_URI"
        AssemblyBuildVersion = "ASSEMBLY_BUILD_VERSION"
        OsBuildVersion = "OS_BUILD_VERSION"
        MetricsArcResourceUri = "METRICS_ARC_RESOURCE_URI"
        MetricsShoeboxAccount = "METRICS_SHOEBOX_ACCOUNT"
    }
    HCITelemetryRegKey = @{
        Path = 'HKLM:\SYSTEM\Software\Microsoft\MAWatchdogService\HCITelemetry'
        Name = 'AllowTelemetry'
        PropertyType = 'String'
        Value = 'True'
    }
    GMAScenarioRegKey = @{ # Registry is not set for ASZ scenario, "Bootstrap" for Bootstrap Scenario, "1P" for 1P scenario
        Path = 'HKLM:\Software\Microsoft\AzureStack\Observability'
        Name = 'GMAScenario'
        PropertyType = 'String'
        Bootstrap = 'Bootstrap'
        OneP = '1P'
    }
    Level = @{
        Debug = "DEBUG"
        Fatal = "FATAL"
        Error = "ERROR"
        Info = "INFO"
        Verbose = "VERBOSE"
        Warning = "WARN"
    }
    LogCollectionConfigs = @{
        DiagLogRoleConfigJson = "DiagnosticLogRoleConfiguration.json"
    }
    ObsScheduledTaskDetails = @{
        TaskName = "Get-TelemetryStatusAndEditConfigsInJsonDropLocation"
        TaskPath = "\Microsoft\AzureStack\Observability\"
        TranscriptsFolderName = "ObsScheduledTaskTranscripts"
        Description = "Runs every hour to determine telemetry status and based on that either adds or removes Telemetry config from JsonDropLocation."
        ScriptFileName = "GetTelemetryStatusAndEditConfigs.ps1"
    }
    Status = @{
        Error = 'error'
        Success = 'success'
        Transitioning = "transitioning"
        Warning = "warning"
    }
    TestHooksRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\TestHooks'
        Name = 'SkipSignatureMitigation'
        PropertyType = 'DWORD'
        Value = 1
    }
    ValidationFunctionNames = @{
        AssertNoObsGMAProcessIsRunning = "Assert-NoObsGMAProcessIsRunning"
        AssertSufficientDiskSpaceAvailableForGMACache = "Assert-SufficientDiskSpaceAvailableForGMACache"
    }
    WorkLoadName = @{
        Install = 'Install-Extension'
        Enable = 'Enable-Extension'
        Disable = 'Disable-Extension'
        Uninstall = 'Uninstall-Extension'
        Update = 'Update-Extension'
    }
    ObsServiceDetails = @{
        DiagTrack = @{
            Name = 'Diagtrack'
        }
        WatchdogAgent = @{
            Name = 'WatchdogAgent'
            DisplayName = 'Arc Extension MA Watchdog'
            BinaryFileName = 'Microsoft.AzureStack.Solution.Diagnostics.MaWatchdog.exe'
        }
        ObsAgent = @{
            Name = "AzureStack Observability Agent"
            DisplayName = "AzureStack Arc Extension Observability Agent"
            BinaryFileName = "Microsoft.AzureStack.Common.Infrastructure.HostModel.WinSvcHost.exe"
        }
    }
    Logman = @{
        ComponentProviderGuids = @{
            Microsoft_AzureStack_SupportBridgeController_LogCollector = "8a460ad6-c898-51da-3b87-5195076be95c" # Obs Agent
            Microsoft_AzureStack_Observability_LogOrchestrator = "c1b24b80-e724-5f0c-da1f-6521a3f002eb"
            Microsoft_AzureStack_LogParsingEngineManager = "e9809dda-e2ab-5961-2368-958f996b4fd8"
            Microsoft_AzureStack_LogParsingEngine_LogParser = "e1950b60-b861-500c-81bf-0d29ac999695"
            Microsoft_AzureStack_LogParsingEngine_GenevaConnector = "9d526935-090c-5c06-2afa-7886238ae238"
            FDA = "80072b42-cf7a-51a7-ee38-195a10c39d6e"
        }
        MaxLogFileSizeInMB = 500
        OutputFilePath ="$($env:SystemDrive)\Observability\ObservabilityLogmanTraces\observabilityLogmanTraces.etl"
        TraceName = "observabilityLogmanTraces"
    }
    VCRedistRegKeys = @{
        Paths = (
            "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\X64",
            "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\X64"
        )
        Name = "Version"
    }
    IdentityParamsToFetchFromPublicSettings = @{
        DeviceArmResourceUri = "DeviceArmResourceUri"
        StampId = "StampId"
        ClusterName = "ClusterName"
        AssemblyVersion = "AssemblyVersion"
        NodeId = "NodeId"
    }
    ProActiveLogCollectionStates = @{
        Enabled = "enabled"
        Disabled = "disabled"
    }
    TenantJsonPropertyNames = @{
        Version = "Version"
        GcsAuthIdType = "GcsAuthIdType"
        GcsEnvironment = "GcsEnvironment"
        GcsGenevaAccount = "GcsGenevaAccount"
        GcsNamespace = "GcsNamespace"
        GcsRegion = "GcsRegion"
        GenevaConfigVersion = "GenevaConfigVersion"
        LocalPath = "LocalPath"
        DisableUpdate = "DisableUpdate"
        DisableCustomImds = "DisableCustomImds"
        MONITORING_AEO_REGION = "MONITORING_AEO_REGION"
        MONITORING_AEO_DEVICE_ARM_RESOURCE_URI = "MONITORING_AEO_DEVICE_ARM_RESOURCE_URI"
        MONITORING_AEO_STAMPID = "MONITORING_AEO_STAMPID"
        MONITORING_AEO_CLUSTER_NAME = "MONITORING_AEO_CLUSTER_NAME"
        MONITORING_AEO_OSBUILD = "MONITORING_AEO_OSBUILD"
        MONITORING_AEO_ASSEMBLYBUILD = "MONITORING_AEO_ASSEMBLYBUILD"
        MONITORING_AEO_NODEID = "MONITORING_AEO_NODEID"
        MONITORING_AEO_NODE_ARC_RESOURCE_URI = "MONITORING_AEO_NODE_ARC_RESOURCE_URI"
        MONITORING_AEO_CLUSTER_NODE_NAME = "MONITORING_AEO_CLUSTER_NODE_NAME" 
        MONITORING_AEO_NODE_ARC_VMID = "MONITORING_AEO_NODE_ARC_VMID"
    }
    TenantJsonPropertyStaticValues = @{
        Version = "1.0"
        GcsAuthIdType = "AuthMSIToken"
        DisableUpdate = "true"
        DisableCustomImds = "true"
        MONITORING_AEO_CLUSTER_NODE_NAME = "%COMPUTERNAME%"
    }
    WinServiceStartupTypes = @{
        Automatic = "Automatic"
        Manual = "Manual"
    }
    
    AvailableDiskSpaceLimitInGB = 20
    DefaultManagementClusterName = 'Test_Extension_ClusterName'
    DiagTrackExportersRegKeyPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\exporters'
    FDAOutputDirectory = "C:\Observability\FleetDiagnosticsAgent\FDAOutput"
    GMAHostProcessNameRegex = "MonAgentHost*"
    GMAHostProcessFullPathRegex = "C:\\Packages\\Plugins\\Microsoft\.AzureStack\.Observability\..*TelemetryAndDiagnostics\\.+\\bin\\GMA\\Monitoring\\Agent\\MonAgentHost\.exe"
    HandlerLogFileName = 'ObservabilityExtension.log'
    MAWatchDogAppAppConfigName = 'Microsoft.AzureStack.Solution.Diagnostics.MaWatchdog.exe.config'
    MonAgentHostExeName = 'MonAgentHost.exe'
    GMAMultiTenantModeCmdParam = '-serviceMode'
    AMAModeCmdParam = '-mcsmode'
    Retries = 3
    SuccessCode = 0
    UtcExporterDestinationDirectory = 'C:\Windows\System32\UtcExporters'
    UtcxporterDllName = 'UtcGenevaExporter.dll'
    VCRuntimeExeName = 'VC_redist.x64.exe'
    VCRedistInstallationLogFileName = "VCRedistInstallation.log"
    WatchdogTimerFrequencyInSeconds = '90'
    WatchdogStatusFileName = 'WatchdogStatus.json'
}
#endregion Constant vairables

#region Functions
function Get-ExceptionDetails {
    [CmdLetBinding()]
    Param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [System.Management.Automation.ErrorRecord] $ErrorObject
    )

    return @{
        Errormsg = $ErrorObject.ToString()
        Exception = $ErrorObject.Exception.ToString()
        Stacktrace = $ErrorObject.ScriptStackTrace
        Failingline = $ErrorObject.InvocationInfo.Line
        Positionmsg = $ErrorObject.InvocationInfo.PositionMessage
        PScommandpath = $ErrorObject.InvocationInfo.PSCommandPath
        Failinglinenumber = $ErrorObject.InvocationInfo.ScriptLineNumber
        Scriptname = $ErrorObject.InvocationInfo.ScriptName
    } | ConvertTo-Json # The ConvetTo-Json will return the entire hashtable as string.
}

function Get-AssemblyVersion {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param (
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    $assemblyVersion = [System.String]::Empty
    try {
        Import-Module EceClient -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue

        if (Get-Command Create-ECEClusterServiceClient -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
            Write-Log "[$functionName] Getting current assembly build version." -LogFile $LogFile
            $ececlient = Create-ECEClusterServiceClient
            $assemblyVersion = $ececlient.GetStampVersion().GetAwaiter().GetResult()

            Set-GlobalEnvironmentVariable `
                -EnvVariableName $MiscConstants.EnvironmentVariableNames.AssemblyBuildVersion `
                -EnvVariableValue $assemblyVersion `
                -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Cannot get Assembly version due to either the EceClient is not available or the module couldn't be loaded." -LogFile $LogFile
        }
    }
    catch {
        $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
        Write-Log "[$functionName] AssemblyVersion value will be empty as exception occured, details are as follows: $exceptionDetails" -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting. Returning: {assemblyVersion = $assemblyVersion}" -LogFile $LogFile
    return $assemblyVersion
}

function Get-OsBuildVersion {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param (
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    $osVersion = (Get-CimInstance -ClassName Win32_OperatingSystem -Property Version).Version
    $ntoskrnl = (Get-Item -Path (Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'ntoskrnl.exe')).VersionInfo.ProductVersion

    $osBuildVersion = "$osVersion.$($ntoskrnl.Split('.')[-1])"

    Write-Log "[$functionName] Exiting. Returning: {osBuildVersion = $osBuildVersion}" -LogFile $LogFile
    return $osBuildVersion
}

function Get-ArcAgentResourceInfo {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    if ($null -eq $global:ArcAgentResourceInfo) {
        try
        {
            # Fetch Arc ResourceID for metrics
            $arcAgentExePath = "$($env:ProgramW6432)\AzureConnectedMachineAgent\azcmagent.exe"
            $arcshow = & $arcAgentExePath show -j
            $global:ArcAgentResourceInfo = $arcshow | ConvertFrom-Json

            if ($global:ArcAgentResourceInfo)
            {
                Write-Log "[$functionName] Successfully retrieved arc agent information and saved it in global:ArcAgentResourceInfo. Value is $($global:ArcAgentResourceInfo)" -LogFile $LogFile
            }
            else {
                throw "No return information recieved when calling arc agent."
            }
        }
        catch {
            $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
            Write-Log "[$functionName] Unhandled exception occured while fetching arc resource information: Exception is as follows: $exceptionDetails" -LogFile $LogFile
        }
    }
    else {
        Write-Log "[$functionName] global:ArcAgentResourceInfo object has value, returning it." -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting." -LogFile $LogFile    
    return $global:ArcAgentResourceInfo
}


function Get-MetricsNamespaceRegionMapping {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
            [Parameter(Mandatory=$false)]
            [System.String] $LogFile,

            [Parameter(Mandatory=$true)]
            [System.Object] $MetricsNamespace,

            [Parameter(Mandatory=$false)]
            [System.String] $region
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {MetricsNamespace = $MetricsNamespace | Region = $region}" -LogFile $LogFile

    if ($null -eq $MetricsNamespace)
    {
        throw $ErrorConstants.MetricsRegionalNamespaceNotFound.Name
    }

    $metricsRegionalNamespace = [System.String]::Empty

    if ([System.String]::IsNullOrEmpty($region))
    {
        Write-Log "[$functionName] As region is empty, defaulting prefix to eastus." -LogFile $LogFile
        $metricsRegionalNamespace = $MetricsNamespace.Prefix + "eastus"
    }
    else
    {
        if ($MetricsNamespace.Region -contains $region)
        {
            $metricsRegionalNamespace = $MetricsNamespace.Prefix + $region
            Write-Log "[$functionName] Found supported region = $metricsRegionalNamespace." -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Region $region not fully supported. Falling back to default region" -LogFile $LogFile
            $metricsRegionalNamespace = $MetricsNamespace.Prefix + $MetricsNamespace.Default
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {MetricsRegionalNamespace = $metricsRegionalNamespace}" -LogFile $LogFile
    return $metricsRegionalNamespace
}

function Get-ArcAgentResourceId {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$true)]
        [System.Object] $ArcAgentInfo,

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {ArcAgentInfo = $ArcAgentInfo}" -LogFile $LogFile

    $arcAgentResourceId = [System.String]::Empty

    if ($null -eq $arcAgentInfo)
    {
        Write-Log "[$functionName] ArcResourceInfo object null" -LogFile $LogFile
    }
    else
    {
        if ($arcAgentInfo.ResourceId)
        {
            $arcAgentResourceId = $arcAgentInfo.ResourceId
        }
        else
        {
            $arcAgentResourceId = "/Subscriptions/$($arcAgentInfo.SubscriptionID)/resourceGroups/$($arcAgentInfo.ResourceGroup)/providers/Microsoft.HybridCompute/Machines/$($arcAgentInfo.ResourceName)"
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {ArcAgentResourceId = $arcAgentResourceId}" -LogFile $LogFile
    return $arcAgentResourceId
}

function Get-ArcAgentVmId {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$true)]
        [System.Object] $ArcAgentInfo,

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {ArcAgentInfo = $ArcAgentInfo}" -LogFile $LogFile

    $arcAgentVmId = [System.String]::Empty

    if ($null -eq $arcAgentInfo)
    {
        Write-Log "[$functionName] ArcResourceInfo object null" -LogFile $LogFile
    }
    else
    {
        if ($arcAgentInfo.vmId)
        {
            $arcAgentVmId = $arcAgentInfo.vmId
        }
    }

    Write-Log "[$functionName] Exiting. Returning: {ArcAgentVmId = $arcAgentVmId}" -LogFile $LogFile
    return $arcAgentVmId
}

function Set-GlobalEnvironmentVariable {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$False)]
        [System.string] $LogFile,

        [Parameter(Mandatory=$False)]
        [System.string] $EnvVariableName,

        [Parameter(Mandatory=$False)]
        [System.string] $EnvVariableValue
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {EnvVariableName = $EnvVariableName | EnvVariableValue = $EnvVariableValue}" -LogFile $LogFile

    if (Confirm-IsStringNotEmpty $EnvVariableName) {
        if (Confirm-IsStringNotEmpty $EnvVariableValue) {
            # Set machine env variable for health agent to access
            setx /m $EnvVariableName $EnvVariableValue | Out-Null
            Write-Log "[$functionName] Set $EnvVariableName to $([Environment]::GetEnvironmentVariable($EnvVariableName, 'Machine'))." -LogFile $LogFile
        }
        else {
            Write-Log "[$functionName] Cannot set environment variable as EnvVariableValue param is either null or empty." -LogFile $LogFile
        }
    }
    else {
        Write-Log "[$functionName] Cannot set environment variable as EnvVariableName param is either null or empty." -LogFile $LogFile
    }

    Write-Log "[$functionName] Exiting." -LogFile $LogFile
}

function Set-EnvironmentVariablesForMetrics {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$false)]
        [System.string] $LogFile,

        [Parameter(Mandatory=$false)]
        [System.string] $EnvInfoFilePath,

        [Parameter(Mandatory=$false)]
        [System.string] $HciResourceUri,

        [Parameter(Mandatory=$false)]
        [System.string] $GcsEnvironment,

        [Parameter(Mandatory=$false)]
        [System.string] $AssemblyBuildVersion,

        [Parameter(Mandatory=$false)]
        [System.String] $ClusterName
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering." -LogFile $LogFile

    # Set METRICS_ARC_RESOURCE_URI
    $ArcAgentInfo = Get-ArcAgentResourceInfo
    if($null -ne $ArcAgentInfo){
        $arcAgentResourceId = Get-ArcAgentResourceId -ArcAgentInfo $ArcAgentInfo   
        Set-GlobalEnvironmentVariable `
            -EnvVariableName $MiscConstants.EnvironmentVariableNames.MetricsArcResourceUri `
            -EnvVariableValue $arcAgentResourceId `
            -LogFile $LogFile
    }

    # Set CLUSTER_NAME
    $clusterNameValue = [System.String]::Empty
    if($null -ne $ClusterName){
        $clusterNameValue = $ClusterName
    }
    elseif (Confirm-GetAzureStackHciIsAvailable) {
        $clusterNameValue = (Get-Cluster).Name
    }
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.ClusterName `
        -EnvVariableValue $clusterNameValue `
        -LogFile $LogFile

    # Set HCI_RESOURCE_URI
    $deviceArmResourceUri = [System.String]::Empty
    if($null -ne $HciResourceUri) {
        $deviceArmResourceUri = $HciResourceUri
    }
    else {
        if(Confirm-GetAzureStackHciIsAvailable) {
            $azureStackHciDetails = Get-AzureStackHCI
            $deviceArmResourceUri = $azureStackHciDetails.AzureResourceUri
        }
    }
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.HciResourceUri `
        -EnvVariableValue $deviceArmResourceUri `
        -LogFile $LogFile
    
    # Set METRICS_SHOEBOX_ACCOUNT
    try {
        $tenantInfoContent = Get-Content $EnvInfoFilePath -Raw | ConvertFrom-Json
        $gcsEnvironmentName = $GcsEnvironment
        
        if (Test-RegKeyExists -Path $MiscConstants.MetricsValidationRegKey.Path -Name $MiscConstants.MetricsValidationRegKey.Name -LogFile $LogFile) {
            $gcsEnvironmentName = $MiscConstants.GCSEnvironment.Prod
        }

        $envInfo = $tenantInfoContent.$GcsEnvironmentName
        $shoeboxAccountName = Get-MetricsShoeboxAccountName `
            -ShoeboxAccountPrefix $envInfo.ShoeboxAccountPrefix `
            -MetricsNamespace $envInfo.Namespaces.Metrics `
            -Region $ArcAgentInfo.Location

        Set-GlobalEnvironmentVariable `
            -EnvVariableName $MiscConstants.EnvironmentVariableNames.MetricsShoeboxAccount `
            -EnvVariableValue $shoeboxAccountName `
            -LogFile $LogFile
    }
    catch
    {
        $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
        Write-Log "[$functionName] METRICS_SHOEBOX_ACCOUNT environment variable is not set due to exception: $exceptionDetails" -LogFile $LogFile
    }

    # Set Assembly Build Version
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.AssemblyBuildVersion `
        -EnvVariableValue $AssemblyBuildVersion `
        -LogFile $LogFile

    # Set OS Build Version
    $osBuildVersion = Get-OsBuildVersion
    Set-GlobalEnvironmentVariable `
        -EnvVariableName $MiscConstants.EnvironmentVariableNames.OsBuildVersion `
        -EnvVariableValue $osBuildVersion `
        -LogFile $LogFile
}

function Get-MetricsShoeboxAccountName {
    [CmdletBinding()]
    [OutputType([System.String])]
    Param(
        [Parameter(Mandatory=$false)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String] $ShoeboxAccountPrefix,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.Object] $MetricsNamespace,

        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [System.String] $Region
    )

    $functionName = $MyInvocation.MyCommand.Name
    $shoeboxAccountName = [System.String]::Empty

    Write-Log "[$functionName] Entering. Params: {ShoeboxAccountPrefix = $ShoeboxAccountPrefix | MetricsNamespace = $MetricsNamespace | Region = $Region}" -LogFile $LogFile

    # Shoebox account name and region mapping
    if ($MetricsNamespace.Region -contains $Region)
    {
        Write-Log "[$functionName] Found supported region $Region." -LogFile $LogFile
        $shoeboxAccountName = $ShoeboxAccountPrefix + $Region
    }
    else
    {
        Write-Log "[$functionName] Region $Region not fully supported. Falling back to default region." -LogFile $LogFile
        $shoeboxAccountName = $ShoeboxAccountPrefix + $MetricsNamespace.Default
    }

    Write-Log "[$functionName] Exiting. Returning: {ShoeboxAccountName: $shoeboxAccountName}" -LogFile $LogFile
    return $shoeboxAccountName
}

function New-ScheduledTaskForObservability {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [System.String] $TaskName,

        [Parameter(Mandatory=$false)]
        [System.String] $Description,

        [Parameter(Mandatory)]
        [System.String] $ScriptPath,

        [Parameter(Mandatory)]
        [System.String] $ScriptArguments,

        [Parameter(Mandatory=$false)]
        [System.String] $TaskPath = "\Microsoft\AzureStack\Observability\",

        [Parameter(Mandatory=$false)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.SwitchParameter] $DisableOnRegistration
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {TaskName = $TaskName | Description = $Description | ScriptPath = $ScriptPath | ScriptArguments = $ScriptArguments | TaskPath = $TaskPath | DisableOnRegistration = $DisableOnRegistration}" -LogFile $LogFile

    if (([System.String]::IsNullOrEmpty($ScriptPath)) -or `
        (-not (Test-Path -Path $ScriptPath -ErrorAction $MiscConstants.ErrorActionPreference.Ignore)))
    {
        throw $ErrorConstants.InvalidScheduledTaskScriptPath.Name
    }

    # Enable scheduled task event log
    $logChannelStatus = Get-WinEvent -ListLog "Microsoft-Windows-TaskScheduler/Operational"
    if (!$logChannelStatus.IsEnabled)
    {
        Write-Log "[$functionName] Enabling TaskScheduler event logs" -LogFile $logFile
        $logName = 'Microsoft-Windows-TaskScheduler/Operational'
        $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $logName
        $log.IsEnabled = $true
        $log.SaveChanges()
    }

    Write-Log "[$functionName] Setting up scheduled task ($TaskName) at path ($TaskPath)" -LogFile $logFile
    
    $action = ScheduledTasks\New-ScheduledTaskAction -Execute "powershell.exe" `
                                    -Argument "-windowstyle hidden -Command $ScriptPath $ScriptArguments"
    $principal = ScheduledTasks\New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
    $trigger = ScheduledTasks\New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)
    $trigger.Repetition.StopAtDurationEnd = $false
    
    $settings = ScheduledTasks\New-ScheduledTaskSettingsSet -ExecutionTimeLimit $(New-TimeSpan -Seconds 300) `
                                            -RestartCount 3 `
                                            -RestartInterval $(New-TimeSpan -Minutes 10)

    $object = ScheduledTasks\New-ScheduledTask -Action $action `
                                    -Principal $principal `
                                    -Trigger $trigger `
                                    -Settings $settings `
                                    -Description $Description

    # If the task is already registered, unregister it first or otherwise it does not get overwritten.
    if ($null -ne (ScheduledTasks\Get-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue))
    {
        ScheduledTasks\Unregister-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Confirm:$false -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null
        Write-Log "[$functionName] Unregistered already created scheduled task ($TaskName) at path ($TaskPath)." -LogFile $logFile
    }

    ScheduledTasks\Register-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -InputObject $object -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null
    Write-Log "[$functionName] Scheduled task creation ($TaskName) succeeded." -LogFile $logFile

    if ($DisableOnRegistration) {
        ScheduledTasks\Disable-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction $MiscConstants.ErrorActionPreference.Stop | Out-Null

        Write-Log "[$functionName] ScheduledTask named ($($MiscConstants.ObsScheduledTaskDetails.TaskName)) is disabled." -LogFile $logFile
    }
    
    Write-Log "[$functionName] Exiting." -LogFile $LogFile
}

function Test-RegKeyExists {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [System.String] $Path,

        [Parameter(Mandatory)]
        [System.String] $Name,

        [Parameter(Mandatory = $False)]
        [System.String] $LogFile,

        [Parameter(Mandatory = $False)]
        [System.Management.Automation.SwitchParameter] $GetValueIfExists
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {Path = $Path | Name = $Name | GetValueIfExists = $GetValueIfExists}" -LogFile $LogFile

    $regKey = $(Get-ItemProperty -Path $Path -Name $Name -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue)

    if ($null -ne $regKey) {

        if ($GetValueIfExists) {
            $value = $regKey.$Name
    
            Write-Log "[$functionName] Obtained registry value '$value' from path '$Path' and name '$Name'. Exiting." -LogFile $LogFile
    
            return $value
        }
    
        Write-Log "[$functionName] Registry key found at path '$Path' with name '$Name'. Exiting." -LogFile $LogFile

        return $regKey
    }
    else {
        Write-Log "[$functionName] Registry key at path '$Path' with name '$Name' does not exist. Exiting." -LogFile $LogFile

        return $null
    }
}

function Get-ConfigTypeEnum {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Getting configTypeEnum for configType ($ConfigType)." -LogFile $LogFile

    $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Invalid
    switch($ConfigType)
    {
        $MiscConstants.ConfigTypes.Telemetry
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Telemetry
            break
        }
        $MiscConstants.ConfigTypes.Diagnostics
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Diagnostics
            break
        }
        $MiscConstants.ConfigTypes.Health
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Health
            break
        }
        $MiscConstants.ConfigTypes.Security
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Security
            break
        }
        $MiscConstants.ConfigTypes.Metrics
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Metrics
            break
        }
    }
    Write-Log "[$functionName] Exiting. Returning: {configTypeEnum = $configTypeEnum}" -LogFile $LogFile

    return $configTypeEnum
}

function Set-TenantConfigRegistryKeys
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $Version,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsAuthIdType,
        
        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsEnvironment,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsGenevaAccount,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsNamespace,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GcsRegion,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $GenevaConfigVersion,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $LocalPath,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $DisableUpdate,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $DisableCustomImds,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_REGION,

        ## Some of the Identity parameters may be empty and so the AllowEmptyString() attribute is added.
        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_STAMPID,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_CLUSTER_NAME,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_OSBUILD,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_ASSEMBLYBUILD,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_NODEID,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_NODE_ARC_RESOURCE_URI,

        [Parameter(Mandatory=$True)]
        [ValidateNotNullOrEmpty()]
        [System.String] $MONITORING_AEO_CLUSTER_NODE_NAME,

        [Parameter(Mandatory=$True)]
        [AllowEmptyString()]
        [System.String] $MONITORING_AEO_NODE_ARC_VMID
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Setting Tenant config registry keys for $ConfigType" -LogFile $LogFile

    $configTypeEnum = Get-ConfigTypeEnum -ConfigType $ConfigType -LogFile $LogFile

    if ($LogFile)
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $LogFile,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $DisableCustomImds,
            $MONITORING_AEO_REGION,
            $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,
            $MONITORING_AEO_STAMPID,
            $MONITORING_AEO_CLUSTER_NAME,
            $MONITORING_AEO_OSBUILD,
            $MONITORING_AEO_ASSEMBLYBUILD,
            $MONITORING_AEO_NODEID,
            $MONITORING_AEO_NODE_ARC_RESOURCE_URI,
            $MONITORING_AEO_CLUSTER_NODE_NAME,
            $MONITORING_AEO_NODE_ARC_VMID)
    }
    else
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $DisableCustomImds,
            $MONITORING_AEO_REGION,
            $MONITORING_AEO_DEVICE_ARM_RESOURCE_URI,
            $MONITORING_AEO_STAMPID,
            $MONITORING_AEO_CLUSTER_NAME,
            $MONITORING_AEO_OSBUILD,
            $MONITORING_AEO_ASSEMBLYBUILD,
            $MONITORING_AEO_NODEID,
            $MONITORING_AEO_NODE_ARC_RESOURCE_URI,
            $MONITORING_AEO_CLUSTER_NODE_NAME,
            $MONITORING_AEO_NODE_ARC_VMID)
    }

    Write-Log "[$functionName] Successfully set tenant config registry keys for $ConfigType. Exiting." -LogFile $LogFile
}

function Set-TenantConfigJsonFile
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$True)]
        [System.String] $FilePath,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Setting $ConfigType tenant config json file at $FilePath." -LogFile $LogFile

    $configTypeEnum = Get-ConfigTypeEnum -ConfigType $ConfigType -LogFile $LogFile

    if($LogFile)
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigGenerator]::Current.GenerateConfig(
            $configTypeEnum,
            $LogFile,
            $FilePath)
    }
    else
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigGenerator]::Current.GenerateConfig(
            $configTypeEnum,
            $FilePath)
    }

    Write-Log "[$functionName] Successfully created tenant config json file for $ConfigType. Exiting." -LogFile $LogFile    
}

function Sync-TenantRegKeysAndConfigFile
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [ValidateSet("Telemetry", "Health", "Diagnostics", "Security", "Metrics")]
        [System.String] $ConfigType,

        [Parameter(Mandatory=$True)]
        [System.String] $FilePath,

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )
    
    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. ConfigType: $ConfigType FilePath: $FilePath" -LogFile $LogFile

    $rewriteJsonFile = $false
    if (Test-Path $FilePath)
    {
        $jsonContents = Get-ContentAsJson -Path $FilePath
        $jsonSections = @("ServiceArguments", "UserArguments", "ConstantVariables", "ExpandVariables")
        $jsonValues = @{}
        $regConstants = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Constants]
        $commonKeys = $regConstants::CommonRegistryKeys
        $tenantKeys = $regConstants::TenantSpecificRegistryKeys
        foreach ($key in $commonKeys + $tenantKeys)
        {
            foreach ($section in $jsonSections)
            {
                if ($jsonContents.$section.$key)
                {
                    $jsonValues[$key] = $jsonContents.$section.$key
                }
            }
        }
        
        $commonRegPath =  $regConstants::CommonConfigRegistryPath -replace "HKEY_LOCAL_MACHINE", "HKLM:"
        $tenantRegPath = ($regConstants::"$($ConfigType)ConfigRegistryPath") -replace "HKEY_LOCAL_MACHINE", "HKLM:"

        :outerLoop foreach($regPath in $commonRegPath, $tenantRegPath)
        {
            foreach ($key in $jsonValues.Keys)
            {
                $regValue = Test-RegKeyExists -Path $regPath -Name $key -GetValueIfExists -LogFile $LogFile
                $fileValue = $jsonValues[$key]

                if ($null -ne $regValue -and $regValue -ne $fileValue)
                {
                    $rewriteJsonFile = $true
                    Write-Log "[$functionName] Found json file value to registry value discrepancy for $key." -LogFile $LogFile
                    Write-Log "[$functionName] $key Value at $regPath : $regValue" -LogFile $LogFile
                    Write-Log "[$functionName] $key Value at $FilePath : $fileValue" -LogFile $LogFile
                    break outerLoop
                }
            }
        }

        if ($rewriteJsonFile)
        {
            Write-Log "[$functionName] Regenerating $FilePath based on registry values." -LogFile $LogFile
            Set-TenantConfigJsonFile -ConfigType $ConfigType -FilePath $FilePath -LogFile $LogFile
        }
        else
        {
            Write-Log "[$functionName] No discrepancies found between $filePath and $commonRegPath registry keys." -LogFile $LogFile
        }
    }
    else
    {
        Write-Log "[$functionName] File $FilePath is not present. Nothing to sync." -LogFile $LogFile
    }
}

function Write-Log {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [System.String] $Message,

        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG","VERBOSE")]
        [System.String] $Level = "INFO",

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile = $global:LogFile,

        [Parameter(Mandatory=$false)]
        [System.Management.Automation.SwitchParameter] $WriteToConsole
    )

    $dateTimeStamp = [System.DateTime]::UtcNow.ToString('u')
    $formattedMessage = "$dateTimeStamp : $Level : $Message"

    if ($WriteToConsole -or (-not $LogFile)) {
        switch($Level.toUpper()) {
            "INFO" {
                Write-Host $formattedMessage
                break;
            }
            "DEBUG" {
                Write-Debug $formattedMessage
                break;
            }
            "VERBOSE" {
                Write-Verbose $formattedMessage
                break;
            }
            "WARN" {
                Write-Warning $formattedMessage
                break;
            }
            "ERROR" {
                Write-Error $formattedMessage
                break;
            }
            "FATAL" {
                Write-Error $formattedMessage
                break;
            }
        }
    }

    if ($LogFile) {     
        Out-File -FilePath $LogFile -InputObject $formattedMessage -Append -Encoding utf8 
    }
}

function Write-ObservabilityGMAEventSource {
    param(
        [Parameter(Mandatory=$true)]
        [System.String] $Message,

        [Parameter(Mandatory=$False)]
        [ValidateSet("INFO","ERROR")]
        [System.String] $Level = "INFO",

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )

    Write-Log -Message $Message -Level $Level -LogFile $LogFile

    switch($Level.toUpper()) {
         "INFO" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.InfoEvent($Message)
                    break;
                }
         "ERROR" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.ErrorEvent($Message)
                    break;
                }
    }
}

function Confirm-IsStringNotEmpty {
    Param (
        [Parameter(Mandatory=$False)]
        [System.String] $s
    )
    return (-not (Confirm-IsStringEmpty $s))
}

function Confirm-IsStringEmpty {
    Param (
        [Parameter(Mandatory=$False)]
        [System.String] $s
    )
    return ([System.String]::IsNullOrEmpty($s) -and [System.String]::IsNullOrWhiteSpace($s))
}

function Confirm-ClusterCmdletsAreAvailable {
    return (
      (Confirm-GetAzureStackHciIsAvailable) -and `
      (Confirm-GetClusterIsAvailable) -and `
      (Confirm-GetClusterNodeIsAvailable)
    )
}

function Confirm-GetAzureStackHciIsAvailable {
    return (
        (Get-Command Get-AzureStackHCI -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        [System.Convert]::ToString((Get-AzureStackHCI).ClusterStatus).ToLower() -ne "notyet" -and `
        [System.Convert]::ToString((Get-AzureStackHCI).RegistrationStatus).ToLower() -ne "notyet"
    )
}

function Confirm-GetClusterIsAvailable {
    return (
        (Get-Command Get-Cluster `
            -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Cluster `
          -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -ErrorVariable clusterError `
          -WarningAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -WarningVariable clusterWarning) -and `
        $null -eq $clusterError[0] -and `
        $null -eq $clusterWarning[0]
    )
}

function Confirm-GetClusterNodeIsAvailable {
    return (
        (Get-Command Get-ClusterNode `
            -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-ClusterNode `
          -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -ErrorVariable clusterNodeError `
          -WarningAction $MiscConstants.ErrorActionPreference.SilentlyContinue `
          -WarningVariable clusterNodeWarning) -and `
        $null -eq $clusterNodeError[0] -and `
        $null -eq $clusterNodeWarning[0]
    )
}

function Set-ProactiveLogCollectionStatus {
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $DiagnosticLevel,
        
        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )
    $functionName = $MyInvocation.MyCommand.Name
    Write-ObservabilityGMAEventSource "[$functionName] Entering. Params : {DiagnosticLevel = $DiagnosticLevel}" -LogFile $LogFile

    if (-not ((Get-Command Get-ProactiveLogCollectionState -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Command Enable-ProactiveLogCollection -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) -and `
        (Get-Command Disable-ProactiveLogCollection -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue))) {
        $diagnosticsInitializerPath = "$PSScriptRoot\..\ObsAgent\lib\DiagnosticsInitializer\DiagnosticsInitializer.psd1"
        Import-Module $diagnosticsInitializerPath | Out-Null
        Write-ObservabilityGMAEventSource "[$functionName] Enable or Disable-ProactiveLogCollection commands not found. Loading DiagnosticsInitializer from $diagnosticsInitializerPath." -LogFile $LogFile
    }
    
    if ($DiagnosticLevel -eq $MiscConstants.HciDiagnosticLevel.Enhanced) {
        if ((Get-ProactiveLogCollectionState -Verbose:$False) -eq $MiscConstants.ProActiveLogCollectionStates.Disabled) {
            Write-ObservabilityGMAEventSource "[$functionName] DiagnosticLevel = $DiagnosticLevel and ProActiveLogCollectionState is $($MiscConstants.ProActiveLogCollectionStates.Disabled). Enabling ProactiveLogCollection." -LogFile $LogFile
            Enable-ProactiveLogCollection | Out-Null
        }
    }
    else {
        if ((Get-ProactiveLogCollectionState -Verbose:$False) -eq $MiscConstants.ProActiveLogCollectionStates.Enabled) {
            Write-ObservabilityGMAEventSource "[$functionName] DiagnosticLevel = $DiagnosticLevel and ProActiveLogCollectionState is $($MiscConstants.ProActiveLogCollectionStates.Enabled). Disabing ProactiveLogCollection." -LogFile $LogFile
            Disable-ProactiveLogCollection | Out-Null
        }
    }

    Write-ObservabilityGMAEventSource "[$functionName] Exiting." -LogFile $LogFile
}

function Get-ContentAsJson {
    Param (
        [Parameter(Mandatory=$True)]
        [System.String] $Path
    )
    
    return Get-Content -Path $Path | ConvertFrom-Json
}

function Get-ClusterRegistrationValuesForIdParams {
    Param (
        [Parameter(Mandatory=$true)]
        [System.Object] $IdParamsToFetch
    )

    $functionName = $MyInvocation.MyCommand.Name
    Write-Log "[$functionName] Entering. Params: {IdParamsToFetch = $($IdParamsToFetch | ConvertTo-Json)}"

    $clusterRegistrationValues = @{}
    $azureStackHciDetails = Get-AzureStackHCI

    $clusterRegistrationValues[$IdParamsToFetch.DeviceArmResourceUri] = $azureStackHciDetails.AzureResourceUri
    $clusterRegistrationValues[$IdParamsToFetch.StampId] = $azureStackHciDetails.AzureResourceName
    $clusterRegistrationValues[$IdParamsToFetch.ClusterName] = (Get-Cluster).Name
    $clusterRegistrationValues[$IdParamsToFetch.NodeId] = $azureStackHciDetails.AzureResourceName + "-" + (Get-ClusterNode(hostname)).Id

    Write-Log "[$functionName] Exiting. Cluster registration values are as follows: $($clusterRegistrationValues | ConvertTo-Json)"

    return $clusterRegistrationValues
}
#endregion Functions

#region Exports

## Variable exports
Export-ModuleMember -Variable ErrorConstants
Export-ModuleMember -Variable MiscConstants
Export-ModuleMember -Variable RegistryConstants

## Function exports
Export-ModuleMember -Function Get-ArcAgentResourceId
Export-ModuleMember -Function Get-ArcAgentResourceInfo
Export-ModuleMember -Function Get-ArcAgentVmId
Export-ModuleMember -Function Get-AssemblyVersion
Export-ModuleMember -Function Get-ExceptionDetails
Export-ModuleMember -Function Get-MetricsNamespaceRegionMapping
Export-ModuleMember -Function Get-OsBuildVersion
Export-ModuleMember -Function New-ScheduledTaskForObservability
Export-ModuleMember -Function Set-TenantConfigRegistryKeys
Export-ModuleMember -Function Set-TenantConfigJsonFile
Export-ModuleMember -Function Sync-TenantRegKeysAndConfigFile
Export-ModuleMember -Function Set-EnvironmentVariablesForMetrics
Export-ModuleMember -Function Test-RegKeyExists
Export-ModuleMember -Function Write-Log
Export-ModuleMember -Function Write-ObservabilityGMAEventSource
Export-ModuleMember -Function Get-MetricsShoeboxAccountName
Export-ModuleMember -Function Set-GlobalEnvironmentVariable
Export-ModuleMember -Function Confirm-IsStringNotEmpty
Export-ModuleMember -Function Confirm-IsStringEmpty
Export-ModuleMember -Function Confirm-ClusterCmdletsAreAvailable
Export-ModuleMember -Function Confirm-GetAzureStackHciIsAvailable
Export-ModuleMember -Function Confirm-GetClusterIsAvailable
Export-ModuleMember -Function Confirm-GetClusterNodeIsAvailable
Export-ModuleMember -Function Set-ProactiveLogCollectionStatus
Export-ModuleMember -Function Get-ContentAsJson
Export-ModuleMember -Function Get-ClusterRegistrationValuesForIdParams
#endregion Exports
# SIG # Begin signature block
# MIIoKgYJKoZIhvcNAQcCoIIoGzCCKBcCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAFFeP8CqbfCQS8
# yM8+/i/ZctW4SY4KRdOXVdcNl3Mvj6CCDXYwggX0MIID3KADAgECAhMzAAADrzBA
# DkyjTQVBAAAAAAOvMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBA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