forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCimDSCParser.cs
More file actions
4089 lines (3594 loc) · 179 KB
/
Copy pathCimDSCParser.cs
File metadata and controls
4089 lines (3594 loc) · 179 KB
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.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Generic;
using Microsoft.Management.Infrastructure.Serialization;
using Microsoft.PowerShell.Commands;
using static Microsoft.PowerShell.SecureStringHelper;
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
/// <summary>
/// </summary>
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
public static class DscRemoteOperationsClass
{
/// <summary>
/// Convert Cim Instance representing Resource desired state to Powershell Class Object.
/// </summary>
public static object ConvertCimInstanceToObject(Type targetType, CimInstance instance, string moduleName)
{
var className = instance.CimClass.CimSystemProperties.ClassName;
object targetObject = null;
string errorMessage;
using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddScript("param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } ");
powerShell.AddArgument(targetType);
powerShell.AddArgument(moduleName);
Collection<PSObject> psExecutionResult = powerShell.Invoke();
if (psExecutionResult.Count == 1)
{
targetObject = psExecutionResult[0].BaseObject;
}
else
{
Exception innerException = null;
if (powerShell.Streams.Error != null && powerShell.Streams.Error.Count > 0)
{
innerException = powerShell.Streams.Error[0].Exception;
}
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InstantiatePSClassObjectFailed, className);
var invalidOperationException = new InvalidOperationException(errorMessage, innerException);
throw invalidOperationException;
}
}
foreach (var property in instance.CimInstanceProperties)
{
if (property.Value != null)
{
MemberInfo[] memberInfo = targetType.GetMember(property.Name, BindingFlags.Public | BindingFlags.Instance);
// verify property exists in corresponding class type
if (memberInfo == null
|| memberInfo.Length > 1
|| (memberInfo[0] is not PropertyInfo && memberInfo[0] is not FieldInfo))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.PropertyNotDeclaredInPSClass, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
var member = memberInfo[0];
var memberType = (member is FieldInfo)
? ((FieldInfo)member).FieldType
: ((PropertyInfo)member).PropertyType;
object targetValue = null;
switch (property.CimType)
{
case CimType.Instance:
{
var cimPropertyInstance = property.Value as CimInstance;
if (cimPropertyInstance != null &&
cimPropertyInstance.CimClass != null &&
cimPropertyInstance.CimClass.CimSystemProperties != null &&
string.Equals(
cimPropertyInstance.CimClass.CimSystemProperties.ClassName,
"MSFT_Credential", StringComparison.OrdinalIgnoreCase))
{
targetValue = ConvertCimInstancePsCredential(moduleName, cimPropertyInstance);
}
else
{
targetValue = ConvertCimInstanceToObject(memberType, cimPropertyInstance, moduleName);
}
if (targetValue == null)
{
return null;
}
}
break;
case CimType.InstanceArray:
{
if (memberType == typeof(Hashtable))
{
targetValue = ConvertCimInstanceHashtable(moduleName, (CimInstance[])property.Value);
}
else
{
var instanceArray = (CimInstance[])property.Value;
if (!memberType.IsArray)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ExpectArrayTypeOfPropertyInPSClass, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
var elementType = memberType.GetElementType();
var targetArray = Array.CreateInstance(elementType, instanceArray.Length);
for (int i = 0; i < instanceArray.Length; i++)
{
var obj = ConvertCimInstanceToObject(elementType, instanceArray[i], moduleName);
if (obj == null)
{
return null;
}
targetArray.SetValue(obj, i);
}
targetValue = targetArray;
}
}
break;
default:
targetValue = LanguagePrimitives.ConvertTo(property.Value, memberType, CultureInfo.InvariantCulture);
break;
}
if (targetValue == null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.ConvertCimPropertyToObjectPropertyFailed, new object[] { property.Name, className });
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
if (member is FieldInfo)
{
((FieldInfo)member).SetValue(targetObject, targetValue);
}
if (member is PropertyInfo)
{
((PropertyInfo)member).SetValue(targetObject, targetValue);
}
}
}
return targetObject;
}
/// <summary>
/// Convert hashtable from Ciminstance to hashtable primitive type.
/// </summary>
/// <param name="providerName"></param>
/// <param name="arrayInstance"></param>
/// <returns></returns>
private static object ConvertCimInstanceHashtable(string providerName, CimInstance[] arrayInstance)
{
var result = new Hashtable();
string errorMessage;
try
{
foreach (var keyValuePair in arrayInstance)
{
var key = keyValuePair.CimInstanceProperties["Key"];
var value = keyValuePair.CimInstanceProperties["Value"];
if (key == null || value == null)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
result.Add(LanguagePrimitives.ConvertTo<string>(key.Value), LanguagePrimitives.ConvertTo<string>(value.Value));
}
}
catch (Exception exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidHashtable, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
return result;
}
/// <summary>
/// Convert CIM instance to PS Credential.
/// </summary>
/// <param name="providerName"></param>
/// <param name="propertyInstance"></param>
/// <returns></returns>
private static object ConvertCimInstancePsCredential(string providerName, CimInstance propertyInstance)
{
string errorMessage;
string userName;
string plainPassWord;
try
{
userName = propertyInstance.CimInstanceProperties["UserName"].Value as string;
if (string.IsNullOrEmpty(userName))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
}
catch (CimException exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidUserName, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
try
{
plainPassWord = propertyInstance.CimInstanceProperties["PassWord"].Value as string;
// In future we might receive password in an encrypted format. Make sure we add
// the decryption login in this method.
if (string.IsNullOrEmpty(plainPassWord))
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage);
throw invalidOperationException;
}
}
catch (CimException exception)
{
errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.InvalidPassword, providerName);
var invalidOperationException = new InvalidOperationException(errorMessage, exception);
throw invalidOperationException;
}
SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord);
password.MakeReadOnly();
return new PSCredential(userName, password);
}
}
}
namespace Microsoft.PowerShell.DesiredStateConfiguration
{
/// <summary>
/// To make it easier to specify -ConfigurationData parameter, we add an ArgumentTransformationAttribute here.
/// When the input data is of type string and is valid path to a file that can be converted to hashtable, we do
/// the conversion and return the converted value. Otherwise, we just return the input data.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ArgumentToConfigurationDataTransformationAttribute : ArgumentTransformationAttribute
{
/// <summary>
/// Convert a file of ConfigurationData into a hashtable.
/// </summary>
/// <param name="engineIntrinsics"></param>
/// <param name="inputData"></param>
/// <returns></returns>
public override object Transform(EngineIntrinsics engineIntrinsics, object inputData)
{
var configDataPath = inputData as string;
if (string.IsNullOrEmpty(configDataPath))
{
return inputData;
}
if (engineIntrinsics == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics));
}
return PsUtils.EvaluatePowerShellDataFileAsModuleManifest(
"ConfigurationData",
configDataPath,
engineIntrinsics.SessionState.Internal.ExecutionContext,
skipPathValidation: false);
}
}
/// <summary>
/// <para>
/// Represents a communication channel to a CIM server.
/// </para>
/// <para>
/// This is the main entry point of the Microsoft.Management.Infrastructure API.
/// All CIM operations are represented as methods of this class.
/// </para>
/// </summary>
internal class CimDSCParser
{
private readonly CimMofDeserializer _deserializer;
private readonly CimMofDeserializer.OnClassNeeded _onClassNeeded;
/// <summary>
/// </summary>
internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded)
{
_deserializer = CimMofDeserializer.Create();
_onClassNeeded = onClassNeeded;
}
/// <summary>
/// </summary>
internal CimDSCParser(CimMofDeserializer.OnClassNeeded onClassNeeded, Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption validationOptions)
{
_deserializer = CimMofDeserializer.Create();
_deserializer.SchemaValidationOption = validationOptions;
_onClassNeeded = onClassNeeded;
}
/// <summary>
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things. Wrapping those 2 things in a class will result in a more, not less complexity")]
internal List<CimInstance> ParseInstanceMof(string filePath)
{
uint offset = 0;
var buffer = GetFileContent(filePath);
try
{
var result = new List<CimInstance>(_deserializer.DeserializeInstances(buffer, ref offset, _onClassNeeded, null));
return result;
}
catch (CimException exception)
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
exception, ParserStrings.CimDeserializationError, filePath);
e.SetErrorId("CimDeserializationError");
throw e;
}
}
/// <summary>
/// Read file content to byte array.
/// </summary>
/// <param name="fullFilePath"></param>
/// <returns></returns>
internal static byte[] GetFileContent(string fullFilePath)
{
if (string.IsNullOrEmpty(fullFilePath))
{
throw PSTraceSource.NewArgumentNullException(nameof(fullFilePath));
}
if (!File.Exists(fullFilePath))
{
var errorMessage = string.Format(CultureInfo.CurrentCulture, ParserStrings.FileNotFound, fullFilePath);
throw PSTraceSource.NewArgumentException(nameof(fullFilePath), errorMessage);
}
using (FileStream fs = File.OpenRead(fullFilePath))
{
var bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
return bytes;
}
}
internal List<CimClass> ParseSchemaMofFileBuffer(string mof)
{
uint offset = 0;
#if UNIX
// OMI only supports UTF-8 without BOM
var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
#else
// This is what we traditionally use with Windows
// DSC asked to keep it UTF-32 for Windows
var encoding = new UnicodeEncoding();
#endif
var buffer = encoding.GetBytes(mof);
var result = new List<CimClass>(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
return result;
}
/// <summary>
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#", Justification = "Have to return 2 things. Wrapping those 2 things in a class will result in a more, not less complexity")]
internal List<CimClass> ParseSchemaMof(string filePath)
{
uint offset = 0;
var buffer = GetFileContent(filePath);
try
{
string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath);
int dotIndex = fileNameDefiningClass.IndexOf('.');
if (dotIndex != -1)
{
fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex);
}
var result = new List<CimClass>(_deserializer.DeserializeClasses(buffer, ref offset, null, null, null, _onClassNeeded, null));
foreach (CimClass c in result)
{
string superClassName = c.CimSuperClassName;
string className = c.CimSystemProperties.ClassName;
if ((superClassName != null) && (superClassName.Equals("OMI_BaseResource", StringComparison.OrdinalIgnoreCase)))
{
// Get the name of the file without schema.mof extension
if (!(className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase)))
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass);
throw e;
}
}
}
return result;
}
catch (CimException exception)
{
PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(
exception, ParserStrings.CimDeserializationError, filePath);
e.SetErrorId("CimDeserializationError");
throw e;
}
}
/// <summary>
/// Make sure that the instance conforms to the schema.
/// </summary>
/// <param name="classText"></param>
internal void ValidateInstanceText(string classText)
{
uint offset = 0;
byte[] bytes = null;
if (Platform.IsLinux || Platform.IsMacOS)
{
bytes = System.Text.Encoding.UTF8.GetBytes(classText);
}
else
{
bytes = System.Text.Encoding.Unicode.GetBytes(classText);
}
_deserializer.DeserializeInstances(bytes, ref offset, _onClassNeeded, null);
}
}
}
namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
/// <summary>
/// </summary>
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
internal class DscClassCacheEntry
{
/// <summary>
/// Store the RunAs Credentials that this DSC resource will use.
/// </summary>
public DSCResourceRunAsCredential DscResRunAsCred;
/// <summary>
/// If we have implicitly imported this resource, we will set this field to true. This will
/// only happen to InBox resources.
/// </summary>
public bool IsImportedImplicitly;
/// <summary>
/// A CimClass instance for this resource.
/// </summary>
public Microsoft.Management.Infrastructure.CimClass CimClassInstance;
/// <summary>
/// Initializes variables with default values.
/// </summary>
public DscClassCacheEntry() : this(DSCResourceRunAsCredential.Default, false, null) { }
/// <summary>
/// Initializes all values.
/// </summary>
/// <param name="aDSCResourceRunAsCredential"></param>
/// <param name="aIsImportedImplicitly"></param>
/// <param name="aCimClassInstance"></param>
public DscClassCacheEntry(DSCResourceRunAsCredential aDSCResourceRunAsCredential, bool aIsImportedImplicitly, Microsoft.Management.Infrastructure.CimClass aCimClassInstance)
{
DscResRunAsCred = aDSCResourceRunAsCredential;
IsImportedImplicitly = aIsImportedImplicitly;
CimClassInstance = aCimClassInstance;
}
}
/// <summary>
/// </summary>
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes",
Justification = "Needed Internal use only")]
public static class DscClassCache
{
private const string InboxDscResourceModulePath = "WindowsPowershell\\v1.0\\Modules\\PsDesiredStateConfiguration";
private const string reservedDynamicKeywords = "^(Synchronization|Certificate|IIS|SQL)$";
private const string reservedProperties = "^(Require|Trigger|Notify|Before|After|Subscribe)$";
private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache");
// Constants for items in the module qualified name (Module\Version\ClassName)
private const int IndexModuleName = 0;
private const int IndexModuleVersion = 1;
private const int IndexClassName = 2;
private const int IndexFriendlyName = 3;
// Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1
private static readonly string[] s_hiddenResourceList =
{
"MSFT_BaseConfigurationProviderRegistration",
"MSFT_CimConfigurationProviderRegistration",
"MSFT_PSConfigurationProviderRegistration",
};
// Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1)
private static readonly HashSet<string> s_hiddenResourceCache =
new(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase);
// a collection to hold current importing script based resource file
// this prevent circular importing case when the script resource existing in the same module with resources it import-dscresource
private static readonly HashSet<string> s_currentImportingScriptFiles = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// DSC class cache for this runspace.
/// Cache stores the DSCRunAsBehavior, cim class and boolean to indicate if an Inbox resource has been implicitly imported.
/// </summary>
private static Dictionary<string, DscClassCacheEntry> ClassCache
{
get
{
if (t_classCache == null)
{
t_classCache = new Dictionary<string, DscClassCacheEntry>(StringComparer.OrdinalIgnoreCase);
}
return t_classCache;
}
}
[ThreadStatic]
private static Dictionary<string, DscClassCacheEntry> t_classCache;
/// <summary>
/// DSC classname to source module mapper.
/// </summary>
private static Dictionary<string, Tuple<string, Version>> ByClassModuleCache
{
get
{
if (t_byClassModuleCache == null)
{
t_byClassModuleCache = new Dictionary<string, Tuple<string, Version>>(StringComparer.OrdinalIgnoreCase);
}
return t_byClassModuleCache;
}
}
[ThreadStatic]
private static Dictionary<string, Tuple<string, Version>> t_byClassModuleCache;
/// <summary>
/// DSC filename to defined class mapper.
/// </summary>
private static Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>> ByFileClassCache
{
get
{
if (t_byFileClassCache == null)
{
t_byFileClassCache = new Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>>(StringComparer.OrdinalIgnoreCase);
}
return t_byFileClassCache;
}
}
[ThreadStatic]
private static Dictionary<string, List<Microsoft.Management.Infrastructure.CimClass>> t_byFileClassCache;
/// <summary>
/// Filenames from which we have imported script dynamic keywords.
/// </summary>
private static HashSet<string> ScriptKeywordFileCache
{
get
{
if (t_scriptKeywordFileCache == null)
{
t_scriptKeywordFileCache = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
return t_scriptKeywordFileCache;
}
}
[ThreadStatic]
private static HashSet<string> t_scriptKeywordFileCache;
/// <summary>
/// Default ModuleName and ModuleVersion to use.
/// </summary>
private static readonly Tuple<string, Version> s_defaultModuleInfoForResource =
new("PSDesiredStateConfiguration", new Version("1.1"));
/// <summary>
/// Default ModuleName and ModuleVersion to use for meta configuration resources.
/// </summary>
internal static readonly Tuple<string, Version> DefaultModuleInfoForMetaConfigResource =
new("PSDesiredStateConfigurationEngine", new Version("2.0"));
/// <summary>
/// A set of dynamic keywords that can be used in both configuration and meta configuration.
/// </summary>
internal static readonly HashSet<string> SystemResourceNames =
new(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" };
/// <summary>
/// When this property is set to true, DSC Cache will cache multiple versions of a resource.
/// That means it will cache duplicate resource classes (class names for a resource in two different module versions are same).
/// NOTE: This property should be set to false for DSC compiler related methods/functionality, such as Import-DscResource,
/// because the Mof serializer does not support deserialization of classes with different versions.
/// </summary>
[ThreadStatic]
private static bool t_cacheResourcesFromMultipleModuleVersions;
private static bool CacheResourcesFromMultipleModuleVersions
{
get
{
return t_cacheResourcesFromMultipleModuleVersions;
}
set
{
t_cacheResourcesFromMultipleModuleVersions = value;
}
}
/// <summary>
/// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
/// </summary>
public static void Initialize()
{
Initialize(null, null);
}
/// <summary>
/// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration.
/// </summary>
/// <param name="errors">Collection of any errors encountered during initialization.</param>
/// <param name="modulePathList">List of module path from where DSC PS modules will be loaded.</param>
public static void Initialize(Collection<Exception> errors, List<string> modulePathList)
{
s_tracer.WriteLine("Initializing DSC class cache force={0}");
if (Platform.IsLinux || Platform.IsMacOS)
{
//
// Load the base schema files.
//
ClearCache();
var dscConfigurationDirectory = Environment.GetEnvironmentVariable("DSC_HOME") ??
"/etc/opt/omi/conf/dsc/configuration";
if (!Directory.Exists(dscConfigurationDirectory))
{
throw new DirectoryNotFoundException("Unable to find DSC schema store at " + dscConfigurationDirectory + ". Please ensure PS DSC for Linux is installed.");
}
var resourceBaseFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/BaseResource.schema.mof");
ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);
var metaConfigFile = Path.Combine(dscConfigurationDirectory, "BaseRegistration/MSFT_DSCMetaConfiguration.mof");
ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);
var allResourceRoots = new string[] { dscConfigurationDirectory };
//
// Load all of the system resource schema files, searching
//
string resources;
foreach (var resourceRoot in allResourceRoots)
{
resources = Path.Combine(resourceRoot, "schema");
if (!Directory.Exists(resources))
{
continue;
}
foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
{
ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
}
}
// Linux DSC Modules are installed to the dscConfigurationDirectory, so no need to load them.
}
else
{
// DSC SxS scenario
var configSystemPath = Utils.DefaultPowerShellAppBase;
var systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
var inboxModulePath = "Modules\\PSDesiredStateConfiguration";
if (!Directory.Exists(systemResourceRoot))
{
configSystemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
systemResourceRoot = Path.Combine(configSystemPath, "Configuration");
inboxModulePath = InboxDscResourceModulePath;
}
var programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!");
var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration");
Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist");
var allResourceRoots = new string[] { systemResourceRoot, customResourceRoot };
//
// Load the base schema files.
//
ClearCache();
var resourceBaseFile = Path.Combine(systemResourceRoot, "BaseRegistration\\BaseResource.schema.mof");
ImportClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors);
var metaConfigFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_DSCMetaConfiguration.mof");
ImportClasses(metaConfigFile, s_defaultModuleInfoForResource, errors);
var metaConfigExtensionFile = Path.Combine(systemResourceRoot, "BaseRegistration\\MSFT_MetaConfigurationExtensionClasses.schema.mof");
ImportClasses(metaConfigExtensionFile, DefaultModuleInfoForMetaConfigResource, errors);
//
// Load all of the system resource schema files, searching
//
string resources;
foreach (var resourceRoot in allResourceRoots)
{
resources = Path.Combine(resourceRoot, "Schema");
if (!Directory.Exists(resources))
{
continue;
}
foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof")))
{
ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors);
}
}
// Load Regular and DSC PS modules
bool importInBoxResourcesImplicitly = false;
List<string> modulePaths = new();
if (modulePathList == null || modulePathList.Count == 0)
{
modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath));
importInBoxResourcesImplicitly = true;
}
else
{
foreach (string moduleFolderPath in modulePathList)
{
if (!Directory.Exists(moduleFolderPath))
{
continue;
}
foreach (string moduleDir in Directory.EnumerateDirectories(moduleFolderPath))
{
modulePaths.Add(moduleDir);
}
}
}
LoadDSCResourceIntoCache(errors, modulePaths, importInBoxResourcesImplicitly);
}
}
/// <summary>
/// Load DSC resources into Cache from moduleFolderPath.
/// </summary>
/// <param name="errors">Collection of any errors encountered during initialization.</param>
/// <param name="modulePathList">Module path from where DSC PS modules will be loaded.</param>
/// <param name="importInBoxResourcesImplicitly">
/// if module is inbox.
/// </param>
private static void LoadDSCResourceIntoCache(Collection<Exception> errors, List<string> modulePathList, bool importInBoxResourcesImplicitly)
{
foreach (string moduleDir in modulePathList)
{
if (!Directory.Exists(moduleDir)) continue;
var dscResourcesPath = Path.Combine(moduleDir, "DscResources");
if (Directory.Exists(dscResourcesPath))
{
foreach (string resourceDir in Directory.EnumerateDirectories(dscResourcesPath))
{
IEnumerable<string> schemaFiles = Directory.EnumerateFiles(resourceDir, "*.schema.mof");
if (!schemaFiles.Any())
{
continue;
}
Tuple<string, Version> moduleInfo = GetModuleInfoHelper(moduleDir, importInBoxResourcesImplicitly, isPsProviderModule: false);
if (moduleInfo == null)
{
continue;
}
foreach (string schemaFile in schemaFiles)
{
ImportClasses(schemaFile, moduleInfo, errors, importInBoxResourcesImplicitly);
}
}
}
}
}
/// <summary>
/// Get the module name and module version.
/// </summary>
/// <param name="moduleFolderPath">
/// Path to the module folder
/// </param>
/// <param name="importInBoxResourcesImplicitly">
/// if module is inbox and we are importing resources implicitly
/// </param>
/// <param name="isPsProviderModule">
/// Indicate a internal DSC module
/// </param>
/// <returns></returns>
private static Tuple<string, Version> GetModuleInfoHelper(string moduleFolderPath, bool importInBoxResourcesImplicitly, bool isPsProviderModule)
{
string moduleName = "PsDesiredStateConfiguration";
if (!importInBoxResourcesImplicitly)
{
moduleName = Path.GetFileName(moduleFolderPath);
}
string manifestPath = Path.Combine(moduleFolderPath, moduleName + ".psd1");
s_tracer.WriteLine("DSC GetModuleVersion: Try retrieving module version information from file: {0}.", manifestPath);
if (!File.Exists(manifestPath))
{
if (isPsProviderModule)
{
// Some internal PSProviders do not come with a .psd1 file, such
// as MSFT_LogResource. We don't report error in this case.
return new Tuple<string, Version>(moduleName, new Version("1.0"));
}
else
{
s_tracer.WriteLine("DSC GetModuleVersion: Manifest file '{0}' not exist.", manifestPath);
return null;
}
}
try
{
Hashtable dataFileSetting =
PsUtils.GetModuleManifestProperties(
manifestPath,
PsUtils.ManifestModuleVersionPropertyName);
object versionValue = dataFileSetting["ModuleVersion"];
if (versionValue != null)
{
Version moduleVersion;
if (LanguagePrimitives.TryConvertTo(versionValue, out moduleVersion))
{
return new Tuple<string, Version>(moduleName, moduleVersion);
}
else
{
s_tracer.WriteLine(
"DSC GetModuleVersion: ModuleVersion value '{0}' cannot be converted to System.Version. Skip the module '{1}'.",
versionValue, moduleName);
}
}
else
{
s_tracer.WriteLine(
"DSC GetModuleVersion: Manifest file '{0}' does not contain ModuleVersion. Skip the module '{1}'.",
manifestPath, moduleName);
}
}
catch (PSInvalidOperationException ex)
{
s_tracer.WriteLine(
"DSC GetModuleVersion: Error evaluating module manifest file '{0}', with error '{1}'. Skip the module '{2}'.",
manifestPath, ex, moduleName);
}
return null;
}
// Callback implementation...
private static CimClass MyClassCallback(string serverName, string namespaceName, string className)
{
foreach (KeyValuePair<string, DscClassCacheEntry> cimClass in ClassCache)
{
string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName];
if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase))
{
return cimClass.Value.CimClassInstance;
}
}
return null;
}
/// <summary>
/// Reads CIM MOF schema file and returns classes defined in it.
/// This is used MOF->PSClass conversion tool.
/// </summary>
/// <param name="mofPath">
/// Path to CIM MOF schema file for reading.
/// </param>
/// <returns>List of classes from MOF schema file.</returns>
public static List<CimClass> ReadCimSchemaMof(string mofPath)
{
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
return parser.ParseSchemaMof(mofPath);
}
/// <summary>
/// Import CIM classes from the given file.
/// </summary>
/// <param name="path"></param>
/// <param name="moduleInfo"></param>
/// <param name="errors"></param>
/// <param name="importInBoxResourcesImplicitly"></param>
/// <returns></returns>
public static List<CimClass> ImportClasses(string path, Tuple<string, Version> moduleInfo, Collection<Exception> errors, bool importInBoxResourcesImplicitly = false)
{
if (string.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentNullException(nameof(path));
}
s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path);
var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback);
List<CimClass> classes = null;
try
{
classes = parser.ParseSchemaMof(path);
}
catch (PSInvalidOperationException e)
{
// Ignore modules with invalid schemas.
s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e);
if (errors != null)
{
errors.Add(e);
}
}
if (classes != null)
{
foreach (var c in classes)
{
// Only add the class once...
var className = c.CimSystemProperties.ClassName;
string alias = GetFriendlyName(c);
var friendlyName = string.IsNullOrEmpty(alias) ? className : alias;
string moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleInfo.Item1, moduleInfo.Item2.ToString(), className, friendlyName);
DscClassCacheEntry cimClassInfo;