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. 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.'
    }
    DeviceTypeValueNotFound = @{
        Code = 17
        Name = "DeviceTypeValueNotFound"
        Message = "Device type value not found. It is required for extension's functionality."
    }
    InvalidDeviceTypeValue = @{
        Code = 18
        Name = "InvalidDeviceTypeValue"
        Message = "The device type value is invalid. It's not something we've added support for."
    }
    VCRedistInstallFailed= @{
        Code = 19
        Name = 'VCRedistInstallFailed'
        Message = "Failed to install VC Redistributable VC_redist.x64.exe."
    }
    GcsConfigFilesNotFound = @{
        Code = 20
        Name = 'GcsConfigFilesNotFound'
        Message = "GCSConfig files are not found. Please check the logs for further investigation."
    }
}

$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'
    }
    ArcARegKey = @{
        Path = 'HKLM:\Software\Microsoft\ArcA\'
        Name = 'IsArcAEnv'
        PropertyType = 'DWORD'
        Value = 1
    }
    ConfigTypes = @{
        Telemetry = 'Telemetry'
        Diagnostics = 'Diagnostics'
        Health = 'Health'
        Metrics = 'Metrics'
    }
    DeviceTypes = @{
        ArcAutonomous = "ArcAutonomous"
        AzureEdge = "AzureEdge"
        HCI = "HCI"
        EnvValidatorStandAlone = "EnvValidatorStandAlone"
    }
    DeviceTypeRegKey = @{
        Path = "HKLM:\SOFTWARE\Microsoft\AzureStack"
        Name = "DeviceType"
        PropertyType = "String"
        ## Value = "Purposefully not setting value as it will be on demand."
    }
    DiagTrackRegKey = @{
        Path = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack'
        Name = 'AllowExporters'
        PropertyType = 'DWORD'
        Value = 1
    }
    ErrorActionPreference = @{
        Stop = "Stop"
        SilentlyContinue = "SilentlyContinue"
    }
    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'
    }
    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'
    }
    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"
            Microsoft_AzureStack_Diagnostics_Geneva = "1d86eb77-fa1e-57df-af8a-04ec4fdf2580"
            Microsoft_AzureStack_Telemetry_Geneva = "40972d54-4fe3-56ea-6161-29a20d8bc12d"
            FDA = "80072b42-cf7a-51a7-ee38-195a10c39d6e"
        }
        MaxLogFileSizeInMB = 500
        OutputFilePath ="$($env:SystemDrive)\Observability\ObservabilityLogmanTraces\observabilityLogmanTraces.etl"
        TraceName = "observabilityLogmanTraces"
    }
    
    AvailableDiskSpaceLimitInGB = 20
    DefaultManagementClusterName = 'Test_Extension_ClusterName'
    DiagTrackExportersRegKeyPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Diagnostics\DiagTrack\exporters'
    FDAOutputDirectory = "C:\Observability\FleetDiagnosticsAgent\FDAOutput"
    GMAHostProcessNameRegex = "MonAgentHost*"
    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'
    WatchdogTimerFrequencyInSeconds = '90'
    WatchdogStatusFileName = 'WatchdogStatus.json'
}
#endregion Constant vairables

#region Functions
function Get-AssemblyVersion {
    $functionName = $MyInvocation.MyCommand.Name

    $assemblyVersion = [System.String]::Empty

    try {
        Import-Module EceClient
        Write-Log "$functionName : Getting current assembly build version."
        $ececlient = Create-ECEClusterServiceClient
        $assemblyVersion = $ececlient.GetStampVersion().GetAwaiter().GetResult()

        Set-GlobalEnvironmentVariable -EnvVariableName "ASSEMBLY_BUILD_VERSION" -EnvVariableValue $assemblyVersion
    }
    catch {
        $exceptionDetails = Get-ExceptionDetails -ErrorObject $_
        Write-Log "$functionName : AssemblyVersion value will be empty as exception occured, details are as follows: $exceptionDetails" -Level "ERROR"
    }

    Write-Log "$functionName : AssemblyVersion value is $assemblyVersion"
    return $assemblyVersion
}

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-OsBuildVersion {
    [CmdletBinding()]
    [OutputType([System.String])]

    $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])"
    Set-GlobalEnvironmentVariable -EnvVariableName "OS_BUILD_VERSION" -EnvVariableValue $osBuildVersion

    return $osBuildVersion
}

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

    $message = [System.String]::Empty
    $arcAgentInfo = $null
    try
    {
        # Fetch Arc ResourceID for metrics
        $arcAgentInfo = @{}
        $arcAgentExePath = "$($env:ProgramW6432)\AzureConnectedMachineAgent\azcmagent.exe"
        $arcshow = & $arcAgentExePath show -j
        $arcAgentInfo = $arcshow | ConvertFrom-Json

        if ($arcAgentInfo)
        {
            $message = "$functionName : Successfully retrieved arc agent information."
        }
        else {
            throw "No return information recieved when calling arc agent."
        }
    }
    catch {
        $message = "$functionName : Unable to fetch arc resource information $($_)"
    }

    Write-Log `
        -Message $message `
        -LogFile $LogFile
    if (Get-Command Trace-Execution -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
        Trace-Execution $message
    }
    return $arcAgentInfo
}


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
    )

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

    $message = [System.String]::Empty
    $metricsRegionalNamespace = [System.String]::Empty

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

    Write-Log `
        -Message $message `
        -LogFile $LogFile
    if (Get-Command Trace-Execution -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
        Trace-Execution $message
    }
    return $metricsRegionalNamespace
}

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

    $message = [System.String]::Empty
    $arcAgentResourceId = [System.String]::Empty

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

        # Set machine env variable for metric access
        Set-GlobalEnvironmentVariable -EnvVariableName "METRICS_ARC_RESOURCE_URI" -EnvVariableValue $arcAgentResourceId
        $message = "Set METRICS_ARC_RESOURCE_URI env variable to $arcAgentResourceId"
    }

    Write-Log `
        -Message $message `
        -LogFile $LogFile
    if (Get-Command Trace-Execution -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
        Trace-Execution $message
    }
    return $arcAgentResourceId
}

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

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

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

    $message = [System.String]:: Empty

    # Set machine env variable for health agent to access
    setx /m $EnvVariableName $EnvVariableValue | Out-Null
    $message += "\n$functionName : Set $EnvVariableName to $EnvVariableValue "

    Write-Log `
        -Message $message `
        -LogFile $LogFile

    if (Get-Command Trace-Execution -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
        Trace-Execution $message
    }

}

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
    )

    $message = [System.String]:: Empty
    $shoeboxAccountName = [System.String]::Empty

    # Shoebox account name and region mapping

    if ($MetricsNamespace.Region -contains $Region)
    {
        $message = "$functionName : Found supported region $Region"
        $shoeboxAccountName = $ShoeboxAccountPrefix + $Region
    }
    else
    {
        $message = "$functionName : Region $Region not fully supported. Falling back to default region."
        $shoeboxAccountName = $ShoeboxAccountPrefix + $MetricsNamespace.Default
    }

    # Set machine env variable for health agent to access
    Set-GlobalEnvironmentVariable -EnvVariableName "METRICS_SHOEBOX_ACCOUNT" -EnvVariableValue $shoeboxAccountName

    $message += "\n$functionName : Set METRICS_SHOEBOX_ACCOUNT to $shoeboxAccountName "

    Write-Log `
        -Message $message `
        -LogFile $LogFile

    if (Get-Command Trace-Execution -ErrorAction $MiscConstants.ErrorActionPreference.SilentlyContinue) {
        Trace-Execution $message
    }

    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

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

    # Enable scheduled task event log
    $logChannelStatus = Get-WinEvent -ListLog "Microsoft-Windows-TaskScheduler/Operational"
    if (!$logChannelStatus.IsEnabled)
    {
        Write-Log `
            -Message "$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 `
        -Message "$functionName : Setting up scheduled task ($TaskName) at path ($TaskPath)" `
        -LogFile $logFile
    
    $action = New-ScheduledTaskAction -Execute "powershell.exe" `
                                    -Argument "-windowstyle hidden -Command $ScriptPath $ScriptArguments"
    $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount
    $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 1)
    $trigger.Repetition.StopAtDurationEnd = $false
    
    $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $(New-TimeSpan -Seconds 30) `
                                            -RestartCount 3 `
                                            -RestartInterval $(New-TimeSpan -Minutes 10)

    $object = 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 (Get-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction SilentlyContinue))
    {
        Unregister-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Confirm:$false -Verbose:$false -ErrorAction Stop | Out-Null
        Write-Log `
            -Message "$functionName : Unregistered already created scheduled task ($TaskName) at path ($TaskPath)." `
            -LogFile $logFile
    }

    Register-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -InputObject $object -Verbose:$false -ErrorAction Stop | Out-Null
    Write-Log `
        -Message "$functionName : Scheduled task creation ($TaskName) succeeded." `
        -LogFile $logFile

    if ($DisableOnRegistration) {
        Disable-ScheduledTask -TaskPath $TaskPath -TaskName $TaskName -Verbose:$false -ErrorAction Stop | Out-Null

        Write-Log `
            -Message "$functionName : ScheduledTask named ($($MiscConstants.ObsScheduledTaskDetails.TaskName)) is disabled." `
            -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

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

    if ($GetValueIfExists -and $null -ne $regKey) {
        $value = $regKey.$Name

        Write-Log "$functionName : Obtained registry value '$value' from path '$Path' and name '$Name'." `
            -LogFile $LogFile

        return $value
    }

    return $regKey
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        [Parameter(Mandatory=$True)]
        [System.String] $MONITORING_AEO_CLUSTER_NODE_NAME
    )
    Write-Log "Setting Tenant config registry keys for $ConfigType"
    $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Invalid
    switch($ConfigType)
    {
        "Telemetry"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Telemetry
            break
        }
        "Diagnostics"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Diagnostics
            break
        }
        "Health"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Health
            break
        }
        "Metrics"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Metrics
            break
        }
    }

    if ($LogFile)
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $LogFile,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $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)
    }
    else
    {
        [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.TenantConfigRegistrySetter]::Current.SetTenantConfigRegistryKeys(
            $configTypeEnum,
            $Version,
            $GcsAuthIdType,
            $GcsEnvironment,
            $GcsGenevaAccount,
            $GcsNamespace,
            $GcsRegion,
            $GenevaConfigVersion,
            $LocalPath,
            $DisableUpdate,
            $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)
    }
}

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

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

        [Parameter(Mandatory=$False)]
        [System.String] $LogFile
    )
    Write-Log -Message "Setting $ConfigType Tenant Config Json File at $FilePath." -LogFile $LogFile

    $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Invalid
    switch($ConfigType)
    {
        "Telemetry"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Telemetry
            break
        }
        "Diagnostics"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Diagnostics
            break
        }
        "Health"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Health
            break
        }
        "Metrics"
        {
            $configTypeEnum = [Microsoft.AzureStack.Observability.ObservabilityCommon.TenantConfigGenerator.Contract.TenantConfigType]::Metrics
            break
        }
    }

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

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,

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

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

    if ($WriteToConsole) {
        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 -WriteToConsole ## WriteToConsole is used as it will just write to transcript file and not the output or error stream. This function is only used in TaskScheduler's script as of now.
    switch($Level.toUpper()) {
         "INFO" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.InfoEvent($Message)
                    break;
                }
         "ERROR" {
                    [Microsoft.AzureStack.Observability.GenevaMonitoringAgent.ObservabilityGMAEventSource]::Log.ErrorEvent($Message)
                    break;
                }
    }
}
#endregion Functions

#region Exports

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

## Function exports
Export-ModuleMember -Function Get-ArcAgentResourceId
Export-ModuleMember -Function Get-ArcAgentResourceInfo
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 Test-RegKeyExists
Export-ModuleMember -Function Write-Log
Export-ModuleMember -Function Write-ObservabilityGMAEventSource
Export-ModuleMember -Function Get-MetricsShoeboxAccountName
Export-ModuleMember -Function Set-GlobalEnvironmentVariable 
#endregion Exports
# SIG # Begin signature block
# MIInwgYJKoZIhvcNAQcCoIInszCCJ68CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# B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