-
Notifications
You must be signed in to change notification settings - Fork 54
/
DockerMsftProvider.psm1
1874 lines (1587 loc) · 54.4 KB
/
DockerMsftProvider.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#########################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# DockerMsftProvider
#
#########################################################################################
Microsoft.PowerShell.Core\Set-StrictMode -Version Latest
#region variables
$script:Providername = "DockerMsftProvider"
$script:DockerSources = $null
$script:location_modules = Microsoft.PowerShell.Management\Join-Path -Path $env:TEMP -ChildPath $script:ProviderName
$script:location_sources= Microsoft.PowerShell.Management\Join-Path -Path $env:LOCALAPPDATA -ChildPath $script:ProviderName
$script:file_modules = Microsoft.PowerShell.Management\Join-Path -Path $script:location_sources -ChildPath "sources.txt"
$script:DockerSearchIndex = "DockerSearchIndex.json"
$script:Installer_Extension = "zip"
$script:dockerURL = "https://go.microsoft.com/fwlink/?LinkID=825636&clcid=0x409"
$separator = "|#|"
$script:restartRequired = $false
$script:isNanoServerInitialized = $false
$script:isNanoServer = $false
$script:SystemEnvironmentKey = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment'
$script:pathDockerRoot = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath "Docker"
$script:pathDockerD = Microsoft.PowerShell.Management\Join-Path -Path $script:pathDockerRoot -ChildPath "dockerd.exe"
$script:pathDockerClient = Microsoft.PowerShell.Management\Join-Path -Path $script:pathDockerRoot -ChildPath "docker.exe"
$script:wildcardOptions = [System.Management.Automation.WildcardOptions]::CultureInvariant -bor `
[System.Management.Automation.WildcardOptions]::IgnoreCase
$script:NuGetProviderName = "NuGet"
$script:NuGetBinaryProgramDataPath="$env:ProgramFiles\PackageManagement\ProviderAssemblies"
$script:NuGetBinaryLocalAppDataPath="$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies"
$script:NuGetProvider = $null
$script:nanoserverPackageProvider = "NanoServerPackage"
$script:hotFixID = 'KB3176936'
$script:minOsMajorBuild = 14393
$script:minOSRevision= 206
$script:MetadataFileName = 'metadata.json'
$script:serviceName = "docker"
$script:SemVerTypeName = 'Microsoft.PackageManagement.Provider.Utility.SemanticVersion'
if('Microsoft.PackageManagement.NuGetProvider.SemanticVersion' -as [Type])
{
$script:SemVerTypeName = 'Microsoft.PackageManagement.NuGetProvider.SemanticVersion'
}
#endregion variables
#region One-Get Functions
function Find-Package
{
[CmdletBinding()]
param
(
[string[]]
$names,
[string]
$RequiredVersion,
[string]
$MinimumVersion,
[string]
$MaximumVersion
)
Set-ModuleSourcesVariable
$null = Install-NuGetClientBinary -CallerPSCmdlet $PSCmdlet
$options = $request.Options
foreach( $o in $options.Keys )
{
Write-Debug ( "OPTION: {0} => {1}" -f ($o, $options[$o]) )
}
$AllVersions = $null
if($options.ContainsKey("AllVersions"))
{
$AllVersions = $options['AllVersions']
}
$sources = @()
if($options.ContainsKey('Source'))
{
$sources = $options['Source']
}
if ((-not $names) -or ($names.Count -eq 0))
{
$names = @('')
}
$allResults = @()
$allSources = Get-SourceList -Sources $sources
foreach($currSource in $allSources)
{
$Location = $currSource.SourceLocation
$sourceName = $currSource.Name
if($location.StartsWith("https://"))
{
$tempResults = @()
$tempResults += Find-FromUrl -Source $Location `
-SourceName $sourceName `
-Name $names `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion `
-AllVersions:$AllVersions
if($tempResults)
{
$allResults += $tempResults
}
}
else
{
Write-Error "Currently only https sources are supported. Please register with https source."
}
}
if((-not $allResults) -or ($allResults.Count -eq 0))
{
return
}
foreach($result in $allResults)
{
$swid = New-SoftwareIdentityFromDockerInfo -DockerInfo $result
Write-Output $swid
}
}
function Download-Package
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$FastPackageReference,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Location
)
DownloadPackageHelper -FastPackageReference $FastPackageReference `
-Request $Request `
-Location $Location
}
function Install-Package
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$fastPackageReference
)
if(-not (Test-AdminPrivilege))
{
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName "InvalidOperationException" `
-ExceptionMessage "Administrator rights are required to install docker." `
-ErrorId "AdminPrivilegesAreRequiredForInstall" `
-ErrorCategory InvalidOperation
}
if(-not (IsNanoServer))
{
$osVersion = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\').CurrentBuildNumber
$osRevision = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\').UBR
# Ensure that the host is either running a build newer than Windows Server 2016 GA or
# if running Windows Server 2016 GA that it has a revision greater than 206 (KB3176936)
if (($osVersion -lt $script:minOsMajorBuild) -or
(($osVersion -eq $script:minOsMajorBuild) -and ($osRevision -lt $script:minOsRevision)))
{
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName "InvalidOperationException" `
-ExceptionMessage "$script:hotFixID or later is required for docker to work" `
-ErrorId "RequiredWindowsUpdateNotInstalled" `
-ErrorCategory InvalidOperation
return
}
# This block should not be removed. It enforces Docker's support policy towards which
# SKU of Windows that Docker Engine - Enterprise is supported on. Windows 10 users should
# use Docker Desktop for Windows instead.
if ((Get-CimInstance Win32_Operatingsystem | Select-Object -expand Caption) -like "*Windows 10*")
{
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName "InvalidOperationException" `
-ExceptionMessage "Docker Engine - Enterprise is not supported on Windows 10 client. See https://aka.ms/docker-for-windows instead." `
-ErrorId "RequiresWindowsServer" `
-ErrorCategory InvalidOperation
return
}
}
else
{
Write-Warning "$script:hotFixID or later is required for docker to work. Please ensure this is installed."
}
$options = $request.Options
$update = $false
$force = $false
if($options)
{
foreach( $o in $options.Keys )
{
Write-Debug ("OPTION: {0} => {1}" -f ($o, $request.Options[$o]) )
}
if($options.ContainsKey('Update'))
{
Write-Verbose "Updating the docker installation."
$update = $true
}
if($options.ContainsKey("Force"))
{
$force = $true
}
}
if(Test-Path $script:pathDockerD)
{
if($update -or $force)
{
# Uninstall if another installation exists
UninstallHelper
}
elseif(-not $force)
{
$dockerVersion = & "$script:pathDockerClient" --version
$resultArr = $dockerVersion -split ","
$version = ($resultArr[0].Trim() -split " ")[2]
Write-Verbose "Docker $version already exists. Skipping install. Use -force to install anyway."
return
}
}
else
{
# Install WindowsFeature containers
try
{
InstallContainer
}
catch
{
$ErrorMessage = $_.Exception.Message
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName $_.Exception.GetType().FullName `
-ExceptionMessage $ErrorMessage `
-ErrorId FailedToDownload `
-ErrorCategory InvalidOperation
return
}
}
$splitterArray = @("$separator")
$resultArray = $fastPackageReference.Split($splitterArray, [System.StringSplitOptions]::None)
if((-not $resultArray) -or ($resultArray.count -ne 8)){Write-Debug "Fast package reference doesn't have required parts."}
$source = $resultArray[0]
$name = $resultArray[1]
$version = $resultArray[2]
$description = $resultArray[3]
$originPath = $resultArray[5]
$size = $resultArray[6]
$sha = $resultArray[7]
$date = $resultArray[4]
$Location = $script:location_modules
$destination = GenerateFullPath -Location $Location `
-Name $name `
-Version $Version
$downloadOutput = DownloadPackageHelper -FastPackageReference $FastPackageReference `
-Request $Request `
-Location $Location
if(-not (Test-Path $destination))
{
Write-Error "$destination does not exist"
return
}
else
{
Write-verbose "Found $destination to install."
}
# Install
try
{
Write-Verbose "Trying to unzip : $destination"
$null = Expand-Archive -Path $destination -DestinationPath $env:ProgramFiles -Force
# Rename the docker folder to become Docker
$dummyName = 'dummyName'
$null = Rename-Item -Path $script:pathDockerRoot -NewName $env:ProgramFiles\$dummyName
$null = Rename-Item -Path $env:ProgramFiles\$dummyName -NewName $script:pathDockerRoot
if(Test-Path $script:pathDockerD)
{
Write-Verbose "Trying to enable the docker service..."
$service = get-service -Name Docker -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
if(-not $service)
{
& "$script:pathDockerD" --register-service
}
}
else
{
Write-Error "Unable to expand docker to Program Files."
}
}
catch
{
$ErrorMessage = $_.Exception.Message
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName $_.Exception.GetType().FullName `
-ExceptionMessage $ErrorMessage `
-ErrorId FailedToDownload `
-ErrorCategory InvalidOperation
}
finally
{
# Clean up
Write-Verbose "Removing the archive: $destination"
$null = remove-item $destination -Force
}
# Save the install information
$null = SaveInfo -Source $source
# Update the path variable
$null = Update-PathVar
if($script:restartRequired)
{
Write-Warning "A restart is required to enable the containers feature. Please restart your machine."
}
Write-Warning "This provider is being deprecated and should no longer be used. Users should refer to the instructions on aka.ms/containers/install instead."
Write-Output $downloadOutput
}
function Uninstall-Package
{
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$fastPackageReference
)
UninstallHelper
Write-Verbose "Uninstalling container feature from windows"
UninstallContainer
[string[]] $splitterArray = @("$separator")
[string[]] $resultArray = $fastPackageReference.Split($splitterArray, [System.StringSplitOptions]::None)
if((-not $resultArray) -or ($resultArray.count -ne 3)){Write-Debug "Fast package reference doesn't have required parts."}
$name = $resultArray[0]
$version = $resultArray[1]
$source = $resultArray[2]
$dockerSWID = @{
Name = $name
version = $version
Source = $source
versionScheme = "MultiPartNumeric"
fastPackageReference = $fastPackageReference
}
New-SoftwareIdentity @dockerSWID
}
#endregion One-Get Functions
#region One-Get Required Functions
function Initialize-Provider
{
write-debug "In $($script:Providername) - Initialize-Provider"
}
function Get-PackageProviderName
{
return $script:Providername
}
function Get-InstalledPackage
{
param
(
[string]$name,
[string]$requiredVersion,
[string]$minimumVersion,
[string]$maximumVersion
)
$name = 'docker'
$version = ''
$source = ''
if(Test-Path $script:pathDockerRoot\$script:MetadataFileName)
{
$metaContent = (Get-Content -Path $script:pathDockerRoot\$script:MetadataFileName)
if(IsNanoServer)
{
$jsonDll = [Microsoft.PowerShell.CoreCLR.AssemblyExtensions]::LoadFrom($PSScriptRoot + "\Json.coreclr.dll")
$jsonParser = $jsonDll.GetTypes() | Where-Object name -match jsonparser
$metaContentParsed = $jsonParser::FromJson($metaContent)
$source = if($metaContentParsed.ContainsKey('SourceName')) {$metaContentParsed.SourceName} else {'Unable To Retrieve Source from metadata.json'}
$version = if($metaContentParsed.ContainsKey('Version')) {$metaContentParsed.Version} else {'Unable To Retrieve Version from metadata.json'}
}
else
{
$metaContentParsed = (Get-Content -Path $script:pathDockerRoot\$script:MetadataFileName) | ConvertFrom-Json
if($metaContentParsed)
{
$source = if($metaContentParsed.PSObject.properties.name -contains 'SourceName') {$metaContentParsed.SourceName} else {'Unable To Retrieve Source from metadata.json'}
$version = if($metaContentParsed.PSObject.properties.name -contains 'Version') {$metaContentParsed.Version} else {'Unable To Retrieve Version from metadata.json'}
}
}
}
elseif(Test-Path $script:pathDockerD)
{
$dockerVersion = & "$script:pathDockerClient" --version
$resultArr = $dockerVersion -split ","
$version = ($resultArr[0].Trim() -split " ")[2]
$source = ' '
}
else
{
return $null
}
$fastPackageReference = $name +
$separator + $version +
$separator + $source
$dockerSWID = @{
Name = $name
version = $version
Source = $source
versionScheme = "MultiPartNumeric"
fastPackageReference = $fastPackageReference
}
return New-SoftwareIdentity @dockerSWID
}
#endregion One-Get Required Functions
#region Helper-Functions
function SaveInfo
{
param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$Source
)
# Create a file
$metaFileInfo = New-Item -ItemType File -Path $script:pathDockerRoot -Name $script:MetadataFileName -Force
if(-not $metaFileInfo)
{
# TODO: Handle File not created scenario
}
if(Test-Path $script:pathDockerD)
{
$dockerVersion = & "$script:pathDockerD" --version
$resultArr = $dockerVersion -split ","
$version = ($resultArr[0].Trim() -split " ")[2]
$metaInfo = Microsoft.PowerShell.Utility\New-Object PSCustomObject -Property ([ordered]@{
SourceName = $source
Version = $version
})
$metaInfo | ConvertTo-Json > $metaFileInfo
}
}
function UninstallHelper
{
if(-not (Test-AdminPrivilege))
{
ThrowError -CallerPSCmdlet $PSCmdlet `
-ExceptionName "InvalidOperationException" `
-ExceptionMessage "Administrator rights are required to install docker." `
-ErrorId "AdminPrivilegesAreRequiredForInstall" `
-ErrorCategory InvalidOperation
}
# Stop docker service
$dockerService = get-service -Name Docker -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
if(-not $dockerService)
{
# Docker service is not available
Write-Warning "Docker Service is not available."
}
if(($dockerService.Status -eq "Started") -or ($dockerService.Status -eq "Running"))
{
Write-Verbose "Trying to stop docker service"
$null = stop-service docker
}
if(Test-Path $script:pathDockerD)
{
Write-Verbose "Unregistering the docker service"
$null = & "$script:pathDockerD" --unregister-service
Write-Verbose "Removing the docker files"
$null = Get-ChildItem -Path $script:pathDockerRoot -Recurse | Remove-Item -force -Recurse
if(Test-Path $script:pathDockerRoot ) {$null = Remove-Item $script:pathDockerRoot -Force}
}
else
{
Write-Warning "Docker is not present under the Program Files. Please check the installation."
}
Write-Verbose "Removing the path variable"
$null = Remove-PathVar
}
function InstallContainer
{
if(IsNanoServer)
{
if(HandleProvider)
{
$containerExists = get-package -providername NanoServerPackage -Name *container* -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if($containerExists)
{
Write-Verbose "Containers package is already installed. Skipping the install."
return
}
# Find Container Package
$containerPackage = Find-NanoServerPackage -Name *Container* -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if(-not $containerPackage)
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage "Unable to find the Containers Package from NanoServerPackage Module." `
-ErrorId "PackageNotFound" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
Write-Verbose "Installing Containers..."
$null = $containerPackage | Install-NanoServerPackage -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
$script:restartRequired = $true
}
else
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage "Unable to load the NanoServerPackage Module." `
-ErrorId "ModuleNotFound" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
}
else
{
$containerExists = Get-WindowsFeature -Name Containers
if($containerExists -and $containerExists.Installed)
{
Write-Verbose "Containers feature is already installed. Skipping the install."
return
}
else
{
Write-Verbose "Installing Containers feature..."
Install-WindowsFeature containers
$script:restartRequired = $true
}
}
Write-Verbose "Installed Containers feature"
}
function UninstallContainer
{
if(IsNanoServer)
{
return
}
else
{
Uninstall-WindowsFeature containers
}
}
function HandleProvider
{
# Get the nanoServerpackage provider is present
$getnanoServerPackage = Get-PackageProvider -Name $script:nanoserverPackageProvider -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
# if not download and install
if(-not $getnanoServerPackage)
{
$repositories = Get-PSRepository -Name PSGallery -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if(-not $repositories){$null = Register-PSRepository -Default}
$nanoserverPackage = Find-Module -Name $script:nanoserverPackageProvider -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Repository PSGallery
if(-not $nanoserverPackage)
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage "Unable to find the Containers Package from NanoServerPackage Module." `
-ErrorId "PackageNotFound" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
# Install the provider
$null = $nanoserverPackage | Install-Module -Force -SkipPublisherCheck
}
# Import the provider
$importProvider = Import-PackageProvider -Name $script:nanoserverPackageProvider -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
$importModule = Import-module -Name $script:nanoserverPackageProvider -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -PassThru
return ($importModule -and $importProvider)
}
function Update-PathVar
{
$NameOfPath = "Path"
# Set the environment variable in the Local Process
$envVars = [Environment]::GetEnvironmentVariable($NameOfPath)
$envArr = @()
$envArr = $envVars -split ';'
$envFlag = $true
foreach($envItem in $envArr)
{
if($envItem.Trim() -match [regex]::Escape($script:pathDockerRoot))
{
$envFlag = $false
break
}
}
if($envFlag)
{
$null = [Environment]::SetEnvironmentVariable($NameOfPath, $envVars + ";" + $script:pathDockerRoot)
}
# Set the environment variable in the Machine
$currPath = (Microsoft.PowerShell.Management\Get-ItemProperty -Path $script:SystemEnvironmentKey -Name $NameOfPath -ErrorAction SilentlyContinue).Path
$currArr = @()
$currArr = $currPath -split ';'
$currFlag = $true
foreach($currItem in $currArr)
{
if($currItem.Trim() -match [regex]::Escape($script:pathDockerRoot))
{
$currFlag = $false
break
}
}
if($currFlag)
{
$null = Microsoft.PowerShell.Management\Set-ItemProperty $script:SystemEnvironmentKey -Name $NameOfPath -Value ($currPath + ";" + $script:pathDockerRoot)
# Nanoserver needs a reboot to persist the registry change
if(IsNanoServer)
{
$script:restartRequired = $true
}
}
}
function Remove-PathVar
{
$NameOfPath = "Path"
# Set the environment variable in the Local Process
$envVars = [Environment]::GetEnvironmentVariable($NameOfPath)
$envArr = @()
$envArr = $envVars -split ';'
$envFlag = $false
foreach($envItem in $envArr)
{
if($envItem.Trim() -match [regex]::Escape($script:pathDockerRoot))
{
$envFlag = $true
break
}
}
if($envFlag)
{
$newPath = $envVars -replace [regex]::Escape($script:pathDockerRoot),$null
$newPath = $newPath -replace (";;"), ";"
$null = [Environment]::SetEnvironmentVariable($NameOfPath, $newPath)
}
# Set the environment variable in the Machine
$currPath = (Microsoft.PowerShell.Management\Get-ItemProperty -Path $script:SystemEnvironmentKey -Name $NameOfPath -ErrorAction SilentlyContinue).Path
$currArr = @()
$currArr = $currPath -split ';'
$currFlag = $false
foreach($currItem in $currArr)
{
if($currItem.Trim() -match [regex]::Escape($script:pathDockerRoot))
{
$currFlag = $true
break
}
}
if($currFlag)
{
$newPath = $currPath -replace [regex]::Escape($script:pathDockerRoot),$null
$newPath = $newPath -replace (";;"), ";"
$null = Microsoft.PowerShell.Management\Set-ItemProperty $script:SystemEnvironmentKey -Name $NameOfPath -Value $newPath
}
}
function Set-ModuleSourcesVariable
{
if(Microsoft.PowerShell.Management\Test-Path $script:file_modules)
{
$script:DockerSources = DeSerialize-PSObject -Path $script:file_modules
}
else
{
$script:DockerSources = [ordered]@{}
$defaultModuleSource = Microsoft.PowerShell.Utility\New-Object PSCustomObject -Property ([ordered]@{
Name = "DockerDefault"
SourceLocation = $script:dockerURL
Trusted=$false
Registered= $true
InstallationPolicy = "Untrusted"
})
$script:DockerSources.Add("DockerDefault", $defaultModuleSource)
Save-ModuleSources
}
}
function DeSerialize-PSObject
{
[CmdletBinding(PositionalBinding=$false)]
Param
(
[Parameter(Mandatory=$true)]
$Path
)
$filecontent = Microsoft.PowerShell.Management\Get-Content -Path $Path
[System.Management.Automation.PSSerializer]::Deserialize($filecontent)
}
function Save-ModuleSources
{
# check if exists
if(-not (Test-Path $script:location_sources))
{
$null = mkdir $script:location_sources
}
# seralize module
Microsoft.PowerShell.Utility\Out-File -FilePath $script:file_modules `
-Force `
-InputObject ([System.Management.Automation.PSSerializer]::Serialize($script:DockerSources))
}
function Get-SourceList
{
param
(
[Parameter(Mandatory=$true)]
$sources
)
Set-ModuleSourcesVariable
$listOfSources = @()
foreach($mySource in $script:DockerSources.Values)
{
if((-not $sources) -or
(($mySource.Name -eq $sources) -or
($mySource.SourceLocation -eq $sources)))
{
$tempHolder = @{}
$location = $mySource."SourceLocation"
$tempHolder.Add("SourceLocation", $location)
$packageSourceName = $mySource.Name
$tempHolder.Add("Name", $packageSourceName)
$listOfSources += $tempHolder
}
}
return $listOfSources
}
function Resolve-ChannelAlias
{
param
(
[Parameter(Mandatory=$true)]
[psobject]
$Channels,
[Parameter(Mandatory=$true)]
[String]
$Channel
)
while ($Channels.$Channel.PSObject.Properties.Name -contains 'alias')
{
$Channel = $Channels.$Channel.alias
}
return $Channel
}
function Find-FromUrl
{
param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Uri]
$Source,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$SourceName,
[Parameter(Mandatory=$false)]
[string[]]
$Name,
[Parameter(Mandatory=$false)]
[String]
$MinimumVersion,
[Parameter(Mandatory=$false)]
[String]
$MaximumVersion,
[Parameter(Mandatory=$false)]
[String]
$RequiredVersion,
[Parameter(Mandatory=$false)]
[switch]
$AllVersions
)
if ([string]::IsNullOrWhiteSpace($Name))
{
$Name = "*"
}
if ([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Name))
{
if('docker' -notlike $Name) {return $null}
}
elseif('docker' -ne $Name) {return $Null}
$searchFile = Get-SearchIndex -fwdLink $Location `
-SourceName $SourceName
[String] $searchFileContent = Get-Content -Path $searchFile
if(-not $searchFileContent)
{
return $null
}
$updatedContent = $searchFileContent.Trim(" .-`t`n`r")
$contents = $updatedContent | ConvertFrom-Json
$channels = $contents.channels
$versions = $contents.versions
$channelValues = $channels | Get-Member -MemberType NoteProperty
$searchResults = @()
# If name is null or whitespace, interpret as *
if ([string]::IsNullOrWhiteSpace($Name))
{
$Name = "*"
}
# Set the default channel, allowing $RequiredVersion to override when set to a channel name.
$defaultChannel = 'cs'
if ($RequiredVersion)
{
foreach ($channel in $channelValues)
{
if ($RequiredVersion -eq $channel.Name)
{
$defaultChannel = $channel.Name
$RequiredVersion = $null
break
}
}
}
# if no versions are mentioned, just provide the default version, i.e.: CS
if((-not ($MinimumVersion -or $MaximumVersion -or $RequiredVersion -or $AllVersions)))
{
$resolvedChannel = Resolve-ChannelAlias -Channels $channels -Channel $defaultChannel
$RequiredVersion = $channels.$resolvedChannel.version
}
# if a particular version is requested, provide that version only
if($RequiredVersion)
{
if($versions.PSObject.properties.name -contains $RequiredVersion)
{
$obj = Get-ResultObject -JSON $versions -Version $RequiredVersion
$searchResults += $obj
return $searchResults
}
else {
return $null
}
}
$savedVersion = New-Object $script:SemVerTypeName -ArgumentList '0.0.0'
# version requirement
# compare different versions
foreach($channel in $channelValues)
{
if ($channel.Name -eq $defaultChannel)
{
continue
}
else
{
$dockerName = "Docker"
$versionName = Resolve-ChannelAlias -Channels $channels -Channel $channel.Name
$versionValue = $channels.$versionName.version
$toggle = $false
# Check if the search string has * in it
if ([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($Name))
{
if($dockerName -like $Name)
{
$toggle = $true
}
else
{
continue
}
}
else
{
if($dockerName -eq $Name)
{
$toggle = $true
}
else
{