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