microsoft / navcontainerhelper

Official Microsoft repository for BcContainerHelper, a PowerShell module, which makes it easier to work with Business Central Containers on Docker.
MIT License
381 stars 243 forks source link

"The property 'UserName' cannot be found on this object. Verify that the property exists" when running InContainer #2923

Open kine opened 1 year ago

kine commented 1 year ago

Describe the issue Working on our containerized Azure DevOps agent, I am now running bccontainerhelper inside the container. Now I am getting error, which seems is connected to the fact, that there are some part of the bccontainerhelper which are different in case of running bccontainerhelper inside container. When I run new-bccontainer, it ends with error:

The property 'UserName' cannot be found on this object. Verify that the property exists

Scripts used to create container and cause the issue

$containerName = 'test'
$artifactUrl = Get-BcArtifactUrl -type 'Sandbox' -country 'us' -select 'Latest'
New-BcContainer `
    -accept_eula `
    -containerName $containerName `
    -artifactUrl $artifactUrl `

Full output of scripts

BcContainerHelper is version 4.0.14
BcContainerHelper is running as administrator
HyperV is DisabledWithPayloadRemoved
BcContainerHelper is running inside a Container
UsePsSession is True
Host is Microsoft Windows Server 2022 Datacenter - 10.0.20348.1547
Dockerd process not found. Docker might not be started, not installed or not running Windows Containers.
Docker Client Version is 23.0.1
Docker Server Version is 23.0.1
Removing Desktop shortcuts
Downloading application artifact /sandbox/21.4.52563.53623/us
https://bcartifacts.azureedge.net/sandbox/21.4.52563.53623/us
Downloading C:\Users\ContainerAdministrator\AppData\Local\Temp\a9ddf463-eee9-414e-bc5d-f0cab2eb1da7.zip
Using WebClient
Unpacking application artifact to tmp folder using 7zip
Downloading platform artifact /sandbox/21.4.52563.53623/platform
https://bcartifacts.azureedge.net/sandbox/21.4.52563.53623/platform
Downloading C:\Users\ContainerAdministrator\AppData\Local\Temp\87511eb5-8ee7-4d9b-8a54-f062eb772361.zip
Using WebClient
Unpacking platform artifact to tmp folder using 7zip
Downloading Prerequisite Components
Downloading c:\bcartifacts.cache\sandbox\21.4.52563.53623\platform\Prerequisite Components\IIS URL Rewrite Module\rewrite_2.0_rtw_x64.msi
Using WebClient
Downloading c:\bcartifacts.cache\sandbox\21.4.52563.53623\platform\Prerequisite Components\DotNetCore\DotNetCore.1.0.4_1.1.1-WindowsHosting.exe
Using WebClient
Fetching all docker images
Fetching all docker volumes
Using image mcr.microsoft.com/businesscentral:10.0.20348.1547
Creating Container test
Style: sandbox
Multitenant: Yes
Version: 21.4.52563.53623
Platform: 21.0.52534.53580
Generic Tag: 1.0.2.14
Container OS Version: 10.0.20348.1547 (ltsc2022)
Host OS Version: 10.0.20348.1547 (ltsc2022)
Using process isolation
Using locale en-US
Disabling the standard eventlog dump to container log every 2 seconds (use -dumpEventLog to enable)
New-BcContainer Telemetry Correlation Id: 0cc938b8-c2fd-48d8-ae5e-ca9a1602dc43
The property 'UserName' cannot be found on this object. Verify that the property exists.
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict

Additional context The script must be runned from container, which have this volume mapping: -v "\.\pipe\docker_engine:\.\pipe\docker_engine" -v "c:\programdata\BcContainerHelper:c:\programdata\BcContainerHelper"

**Research I was looking into source code and I think the problem is in this part of the New-NavContainer.ps1:


    if ($IsInsideContainer) {
        ('
if (!$restartingInstance) {
    $cert = New-SelfSignedCertificate -DnsName "dontcare" -CertStoreLocation Cert:\LocalMachine\My
    winrm create winrm/config/Listener?Address=*+Transport=HTTPS (''@{Hostname="dontcare"; CertificateThumbprint="'' + $cert.Thumbprint + ''"}'')
    winrm set winrm/config/service/Auth ''@{Basic="true"}''
    Write-Host "Creating Container user $username"
    New-LocalUser -AccountNeverExpires -PasswordNeverExpires -FullName $username -Name '+$bcContainerHelperConfig.WinRmCredentials.UserName+' -Password (ConvertTo-SecureString -string "'+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($bcContainerHelperConfig.WinRmCredentials.Password)))+'" -AsPlainText -force) | Out-Null
    Add-LocalGroupMember -Group administrators -Member '+$bcContainerHelperConfig.WinRmCredentials.UserName+'
}
') | Add-Content -Path "$myfolder\AdditionalSetup.ps1"

It seems that the $bcContainerHelperConfig.WinRmCredentials is not initialized from some reason.

I have checked the BC.HelperFunctions.ps1 and found this code:

        if ($isInsideContainer) {
            $bcContainerHelperConfig.usePsSession = $true
            try {
                $myinspect = docker inspect $(hostname) | ConvertFrom-Json
                $bcContainerHelperConfig.WinRmCredentials = New-Object PSCredential -ArgumentList 'WinRmUser', (ConvertTo-SecureString -string "P@ss$($myinspect.Id.SubString(48))" -AsPlainText -Force)
            }
            catch {}
        }

But when I run Get-ContainerHelperConfig function, I get this output:

Name                           Value                                                                                                                                                                                                                                                                                
----                           -----                                                                                                                                                                                                                                                                                
TraefikUseDnsNameAsHostName    False                                                                                                                                                                                                                                                                                
SendExtendedTelemetryToMicr... False                                                                                                                                                                                                                                                                                
baseUrl                        https://businesscentral.dynamics.com                                                                                                                                                                                                                                                 
PartnerTelemetryConnectionS...                                                                                                                                                                                                                                                                                      
useSharedEncryptionKeys        True                                                                                                                                                                                                                                                                                 
psSessionTimeout               0                                                                                                                                                                                                                                                                                    
addTryCatchToScriptBlock       True                                                                                                                                                                                                                                                                                 
digestAlgorithm                SHA256                                                                                                                                                                                                                                                                               
defaultNewContainerParameters  {}                                                                                                                                                                                                                                                                                   
mapNetworkSettings                                                                                                                                                                                                                                                                                                  
ObjectIdForInternalUse         88123                                                                                                                                                                                                                                                                                
useVolumes                     True                                                                                                                                                                                                                                                                                 
killPsSessionProcess           False                                                                                                                                                                                                                                                                                
WarningPreference              SilentlyContinue                                                                                                                                                                                                                                                                     
sandboxContainersAreMultite... True                                                                                                                                                                                                                                                                                 
NoOfSecondsToSleepAfterPubl... 1                                                                                                                                                                                                                                                                                    
containerHelperFolder          C:\ProgramData\BcContainerHelper                                                                                                                                                                                                                                                     
AddHostDnsServersToNatConta... False                                                                                                                                                                                                                                                                                
TreatWarningsAsErrors          {}                                                                                                                                                                                                                                                                                   
apiBaseUrl                     https://api.businesscentral.dynamics.com                                                                                                                                                                                                                                             
bcartifactsCacheFolder         c:\bcartifacts.cache                                                                                                                                                                                                                                                                 
TraefikImage                   tobiasfenster/traefik-for-windows:v1.7.34                                                                                                                                                                                                                                            
use7zipIfAvailable             True                                                                                                                                                                                                                                                                                 
DOCKER_SCAN_SUGGEST            False                                                                                                                                                                                                                                                                                
genericImageName               mcr.microsoft.com/businesscentral:{0}                                                                                                                                                                                                                                                
mapCountryCode                 @{ae=w1; ar=w1; bd=w1; dz=w1; cl=w1; pr=w1; eg=w1; fo=dk; gl=dk; id=w1; ke=w1; lb=w1; lk=w1; lu=w1; ma=w1; mm=w1; mt=w1; my=w1; ng=w1; qa=w1; sa=w1; sg=w1; tn=w1; ua=w1; za=w1; ao=w1; bh=w1; ba=w1; bw=w1; cr=br; cy=w1; do=br; ec=br; sv=br; gt=br; hn=br; jm=w1; mv=w1; mu=w1;...
UseNewFormatForGetBcContain... False                                                                                                                                                                                                                                                                                
usePsSession                   True                                                                                                                                                                                                                                                                                 
timeStampServer                http://timestamp.digicert.com                                                                                                                                                                                                                                                        
genericImageNameFilesOnly      mcr.microsoft.com/businesscentral:{0}-filesonly                                                                                                                                                                                                                                      
MicrosoftTelemetryConnectio... xxxxxxx                                                                                                                                                
WinRmCredentials                                                                                                                                                                                                                                                                                                    
hostHelperFolder               C:\ProgramData\BcContainerHelper                                                                                                                                                                                                                                                     
useVolumeForMyFolder           False                                                                                                                                                                                                                                                                                
defaultContainerName           bcserver                                                                                                                                                                                                                                                                             
RenewClientContextBetweenTests False    

Seems like the $isInsideContainer is not set during this function or so... (just expectation)

freddydk commented 1 year ago

The $isInsideContainer was created some time ago and is really intended for ARM templates with docker in docker. If you set it to false to see whether this is the problem.

kine commented 1 year ago

The $isInsideContainer is not configurable, it is set by

$isInsideContainer = ($myUsername -eq "user manager\containeradministrator")

Which is true in my case.

kine commented 1 year ago

When I removed the part

if ($IsInsideContainer) {
        ('
if (!$restartingInstance) {
    $cert = New-SelfSignedCertificate -DnsName "dontcare" -CertStoreLocation Cert:\LocalMachine\My
    winrm create winrm/config/Listener?Address=*+Transport=HTTPS (''@{Hostname="dontcare"; CertificateThumbprint="'' + $cert.Thumbprint + ''"}'')
    winrm set winrm/config/service/Auth ''@{Basic="true"}''
    Write-Host "Creating Container user $username"
    New-LocalUser -AccountNeverExpires -PasswordNeverExpires -FullName $username -Name '+$bcContainerHelperConfig.WinRmCredentials.UserName+' -Password (ConvertTo-SecureString -string "'+([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($bcContainerHelperConfig.WinRmCredentials.Password)))+'" -AsPlainText -force) | Out-Null
    Add-LocalGroupMember -Group administrators -Member '+$bcContainerHelperConfig.WinRmCredentials.UserName+'
}
') | Add-Content -Path "$myfolder\AdditionalSetup.ps1"

from the new-navcontainer.ps1, creation of the container continued, but ended by asking for credentials and ended like this:

[20f0c8f75739...]: PS C:\Users\ContainerAdministrator\Documents> New-BcContainer `
    -accept_eula `
    -containerName $containerName `
    -artifactUrl $artifactUrl `
    -authenticationEMail 'xxxx' `
    -updateHosts -accept_outdated -Credential (Get-Credential -Message 'cred')
BcContainerHelper is version 4.0.14
BcContainerHelper is running as administrator
HyperV is DisabledWithPayloadRemoved
BcContainerHelper is running inside a Container
UsePsSession is True
Host is Microsoft Windows Server 2022 Datacenter - 10.0.20348.1547
Dockerd process not found. Docker might not be started, not installed or not running Windows Containers.
Docker Client Version is 23.0.1
Docker Server Version is 23.0.1
Removing Session test
Removing container test
Removing entries from hosts
Removing test from container hosts file
Removing test-* from container hosts file
Removing Desktop shortcuts
Removing C:\ProgramData\BcContainerHelper\Extensions\test
Fetching all docker images
Fetching all docker volumes
Using image mcr.microsoft.com/businesscentral:10.0.20348.1547
Creating Container test
Style: sandbox
Multitenant: Yes
Version: 21.4.52563.53772
Platform: 21.0.52534.53733
Generic Tag: 1.0.2.14
Container OS Version: 10.0.20348.1547 (ltsc2022)
Host OS Version: 10.0.20348.1547 (ltsc2022)
Using process isolation
Using locale en-US
Disabling the standard eventlog dump to container log every 2 seconds (use -dumpEventLog to enable)
Files in C:\ProgramData\BcContainerHelper\Extensions\test\my:
- AdditionalOutput.ps1
- MainLoop.ps1
- SetupVariables.ps1
- updatehosts.ps1
Creating container test from image mcr.microsoft.com/businesscentral:10.0.20348.1547
225949168df13c2239b0f5220856e43719e2007c0619ee8e7a7c7164e71b8ae9
Waiting for container test to be ready
Using artifactUrl https://bcartifacts.azureedge.net/sandbox/21.4.52563.53772/us
Using installer from C:\Run\210-new
Installing Business Central
Installing from artifacts
Starting Local SQL Server
Starting Internet Information Server
Copying Service Tier Files
c:\dl\sandbox\21.4.52563.53772\platform\ServiceTier\Program Files
c:\dl\sandbox\21.4.52563.53772\platform\ServiceTier\System64Folder
Copying PowerShell Scripts
c:\dl\sandbox\21.4.52563.53772\platform\WindowsPowerShellScripts\Cloud\NAVAdministration
c:\dl\sandbox\21.4.52563.53772\platform\WindowsPowerShellScripts\WebSearch
Copying Web Client Files
c:\dl\sandbox\21.4.52563.53772\platform\WebClient\Microsoft Dynamics NAV
Copying ModernDev Files
c:\dl\sandbox\21.4.52563.53772\platform
c:\dl\sandbox\21.4.52563.53772\platform\ModernDev\program files\Microsoft Dynamics NAV
Copying additional files
Copying ConfigurationPackages
C:\dl\sandbox\21.4.52563.53772\us\ConfigurationPackages
Copying Test Assemblies
C:\dl\sandbox\21.4.52563.53772\platform\Test Assemblies
Copying Extensions
C:\dl\sandbox\21.4.52563.53772\us\Extensions
Copying Applications
C:\dl\sandbox\21.4.52563.53772\platform\Applications
Copying Applications.US
C:\dl\sandbox\21.4.52563.53772\us\Applications.US
Copying dependencies
Copying ReportBuilder
Importing PowerShell Modules
Restoring CRONUS Demo Database
Setting CompatibilityLevel for tenant on localhost\SQLEXPRESS
Exporting Application to CRONUS
Removing Application from tenant
Modifying Business Central Service Tier Config File for Docker
Creating Business Central Service Tier
Installing SIP crypto provider: 'C:\Windows\System32\NavSip.dll'
Starting Business Central Service Tier
Importing license file
Copying Database on localhost\SQLEXPRESS from tenant to default
Taking database tenant offline
Copying database files
Attaching files as new Database default
Putting database tenant back online
Mounting tenant database
Mounting Database for default on server localhost\SQLEXPRESS with AllowAppDatabaseWrite = False
Sync'ing Tenant
Tenant is Operational
Stopping Business Central Service Tier
Installation took 259 seconds
Installation complete
Initializing...
Setting host.containerhelper.internal to 172.18.144.1 in container hosts file
Starting Container
Hostname is test
PublicDnsName is test
Using Windows Authentication
Modifying Service Tier Config File with Instance Specific Settings
Starting Service Tier
Registering event sources
Creating DotNetCore Web Server Instance
Using application pool name: BC
Using default container name: NavWebApplicationContainer
Copy files to WWW root C:\inetpub\wwwroot\BC
Create the application pool BC
Create website: NavWebApplicationContainer without SSL
Update configuration: navsettings.json
Done Configuring Web Client
Enabling Financials User Experience
Dismounting Tenant
Mounting Tenant
Setting AadTenantId to xxxxx
Mounting Database for default on server localhost\SQLEXPRESS with AllowAppDatabaseWrite = False
Sync'ing Tenant
Tenant is Operational
Creating http download site
Creating Windows user admin
Setting SA Password and enabling SA
Creating SUPER user
Container IP Address: 172.18.153.190
Container Hostname  : test
Container Dns Name  : test
Web Client          : http://test/BC/?tenant=default
Dev. Server         : http://test
Dev. ServerInstance : BC
Dev. Server Tenant  : default
Setting test to 172.18.153.190 in host hosts file
Setting test-default to 172.18.153.190 in host hosts file
Setting test-default to 172.18.153.190 in container hosts file

Files:
http://test:8080/ALLanguage.vsix

Container Total Physical Memory is 255.3Gb
Container Free Physical Memory is 109.1Gb

Initialization took 45 seconds
Ready for connections!
Error trying to establish session, retrying in 5 seconds
New-BcContainer Telemetry Correlation Id: ba3aaa3f-29f4-40b1-bc36-c54d8c62c7f8
Connecting to remote server test failed with the following error message : WinRM cannot complete the operation. Verify that the specified computer name is valid, that the computer is accessible over the network, and that a firewall exception for the WinRM service is enabled and allows access from this 
computer. By default, the WinRM firewall exception for public profiles limits access to remote computers within the same local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed

Which looks like some Invoke-scriptinbccontianer fails on authentication.

freddydk commented 1 year ago

Sorry for the delay on this - how do you load BcContainerHelper? Do you use implicit or explicit Import-Module?

kine commented 1 year ago

I think implicit, will check. Sorry for the delay.

If I do import-module for another module, which have bccontainerhelper as dependency, does it count as implicit or explicit?