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
# MIInvwYJKoZIhvcNAQcCoIInsDCCJ6wCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAFFeP8CqbfCQS8
# yM8+/i/ZctW4SY4KRdOXVdcNl3Mvj6CCDXYwggX0MIID3KADAgECAhMzAAADrzBA
# DkyjTQVBAAAAAAOvMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAM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