-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathAzurePSCmdlet.cs
1203 lines (1071 loc) · 44.8 KB
/
AzurePSCmdlet.cs
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 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.Azure.PowerShell.Common.Share.Survey;
using Microsoft.Azure.PowerShell.Common.UpgradeNotification;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using Microsoft.WindowsAzure.Commands.Common.Properties;
using Microsoft.WindowsAzure.Commands.Common.Sanitizer;
using Microsoft.WindowsAzure.Commands.Common.Utilities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.WindowsAzure.Commands.Utilities.Common
{
/// <summary>
/// Represents base class for all Azure cmdlets.
/// </summary>
public abstract class AzurePSCmdlet : PSCmdlet, IDisposable
{
private const string PSVERSION = "PSVersion";
private const string DEFAULT_PSVERSION = "3.0.0.0";
public ConcurrentQueue<string> DebugMessages { get; private set; }
IAzureEventListener _azureEventListener;
protected static ConcurrentQueue<string> InitializationWarnings { get; set; } = new ConcurrentQueue<string>();
public static ConcurrentQueue<string> PromptedPreviewMessageCmdlets { get; set; } = new ConcurrentQueue<string>();
private RecordingTracingInterceptor _httpTracingInterceptor;
private object lockObject = new object();
private AzurePSDataCollectionProfile _cachedProfile = null;
protected IList<Regex> _matchers { get; private set; } = new List<Regex>();
private static readonly Regex _defaultMatcher = new Regex("(\\s*\"access_token\"\\s*:\\s*)\"[^\"]+\"");
protected AzurePSDataCollectionProfile _dataCollectionProfile
{
get
{
lock (lockObject)
{
DataCollectionController controller;
if (_cachedProfile == null && AzureSession.Instance.TryGetComponent(DataCollectionController.RegistryKey, out controller))
{
_cachedProfile = controller.GetProfile(() => WriteWarning(DataCollectionWarning));
}
else if (_cachedProfile == null)
{
_cachedProfile = new AzurePSDataCollectionProfile();
WriteWarning(DataCollectionWarning);
}
return _cachedProfile;
}
}
set
{
lock (lockObject)
{
_cachedProfile = value;
}
}
}
protected static string _errorRecordFolderPath = null;
protected static string _sessionId = Guid.NewGuid().ToString();
protected const string _fileTimeStampSuffixFormat = "yyyy-MM-dd-THH-mm-ss-fff";
protected string _clientRequestId = Guid.NewGuid().ToString();
protected static DateTimeOffset? _previousEndTime = null;
protected MetricHelper _metricHelper;
protected AzurePSQoSEvent _qosEvent;
protected DebugStreamTraceListener _adalListener;
protected virtual bool IsUsageMetricEnabled
{
get { return true; }
}
protected virtual bool IsErrorMetricEnabled
{
get { return true; }
}
[Obsolete("Should use AzurePSCmdlet.PowerShellVersion")]
protected string PSVersion
{
get
{
return LoadPowerShellVersion();
}
}
/// <summary>
/// Gets the PowerShell module name used for user agent header and telemetry.
/// </summary>
protected virtual string ModuleName { get; set; }
/// <summary>
/// Gets PowerShell module version used for user agent header and telemetry.
/// </summary>
protected string ModuleVersion { get; set; }
/// <summary>
/// The context for management cmdlet requests - includes account, tenant, subscription,
/// and credential information for targeting and authorizing management calls.
/// </summary>
protected abstract IAzureContext DefaultContext { get; }
protected abstract string DataCollectionWarning { get; }
private SessionState _sessionState;
public new SessionState SessionState
{
get
{
return _sessionState;
}
set
{
_sessionState = value;
}
}
private RuntimeDefinedParameterDictionary _asJobDynamicParameters;
public RuntimeDefinedParameterDictionary AsJobDynamicParameters
{
get
{
if (_asJobDynamicParameters == null)
{
_asJobDynamicParameters = new RuntimeDefinedParameterDictionary();
}
return _asJobDynamicParameters;
}
set
{
_asJobDynamicParameters = value;
}
}
private IOutputSanitizer OutputSanitizer
{
get
{
if (AzureSession.Instance.TryGetComponent<IOutputSanitizer>(nameof(IOutputSanitizer), out var outputSanitizer))
return outputSanitizer;
return null;
}
}
/// <summary>
/// Resolve user submitted paths correctly on all platforms
/// </summary>
/// <param name="path">Absolute or relative path</param>
/// <returns>Absolute path</returns>
public string ResolveUserPath(string path)
{
if (path == null)
{
return null;
}
if (SessionState == null)
{
return path;
}
try
{
return GetUnresolvedProviderPathFromPSPath(path);
}
catch
{
return path;
}
}
/// <summary>
/// Correctly join sections of a path and resolve final path correctly on all platforms
/// </summary>
/// <param name="paths">Sections of an absolute or relative path</param>
/// <returns>Combined absolute path</returns>
public string ResolveUserPath(string[] paths)
{
if (paths == null || paths.Count() == 0)
{
return "";
}
string path = paths[0];
if (paths.Count() > 1)
{
for (int i = 1; i < paths.Count(); i++)
{
path = Path.Combine(path, paths[i]);
}
}
return ResolveUserPath(path);
}
/// <summary>
/// Initializes AzurePSCmdlet properties.
/// </summary>
public AzurePSCmdlet()
{
DebugMessages = new ConcurrentQueue<string>();
}
// Register Dynamic Parameters for use in long running jobs
public void RegisterDynamicParameters(RuntimeDefinedParameterDictionary parameters)
{
this.AsJobDynamicParameters = parameters;
}
/// <summary>
/// Check whether the data collection is opted in from user
/// </summary>
/// <returns>true if allowed</returns>
public bool IsDataCollectionAllowed()
{
if (_dataCollectionProfile != null &&
_dataCollectionProfile.EnableAzureDataCollection.HasValue &&
_dataCollectionProfile.EnableAzureDataCollection.Value)
{
return true;
}
return false;
}
protected virtual void LogCmdletStartInvocationInfo()
{
if (string.IsNullOrEmpty(ParameterSetName))
{
WriteDebugWithTimestamp(string.Format("{0} begin processing " +
"without ParameterSet.", this.GetType().Name));
}
else
{
WriteDebugWithTimestamp(string.Format("{0} begin processing " +
"with ParameterSet '{1}'.", this.GetType().Name, ParameterSetName));
}
}
protected virtual void LogCmdletEndInvocationInfo()
{
string message = string.Format("{0} end processing.", this.GetType().Name);
WriteDebugWithTimestamp(message);
}
protected void AddDebuggingFilter(Regex matcher)
{
_matchers.Add(matcher);
}
//Override this method in cmdlet if customized regedx filters needed for debugging message
protected virtual void InitDebuggingFilter()
{
AddDebuggingFilter(_defaultMatcher);
}
protected virtual void SetupDebuggingTraces()
{
_httpTracingInterceptor = _httpTracingInterceptor ?? new
RecordingTracingInterceptor(DebugMessages, _matchers);
_adalListener = _adalListener ?? new DebugStreamTraceListener(DebugMessages);
RecordingTracingInterceptor.AddToContext(_httpTracingInterceptor);
DebugStreamTraceListener.AddAdalTracing(_adalListener);
if (AzureSession.Instance.TryGetComponent(nameof(IAzureEventListenerFactory), out IAzureEventListenerFactory factory))
{
_azureEventListener = factory.GetAzureEventListener(
(message) =>
{
DebugMessages.Enqueue(message);
});
}
}
protected virtual void TearDownDebuggingTraces()
{
RecordingTracingInterceptor.RemoveFromContext(_httpTracingInterceptor);
DebugStreamTraceListener.RemoveAdalTracing(_adalListener);
_azureEventListener?.Dispose();
_azureEventListener = null;
FlushDebugMessages();
}
protected virtual void SetupHttpClientPipeline()
{
AzureSession.Instance.ClientFactory.AddUserAgent("AzurePowershell", string.Format("v{0}", AzVersion));
AzureSession.Instance.ClientFactory.AddUserAgent(PSVERSION, string.Format("v{0}", PowerShellVersion));
AzureSession.Instance.ClientFactory.AddUserAgent(ModuleName, this.ModuleVersion);
try {
string hostEnv = AzurePSCmdlet.getEnvUserAgent();
if (!String.IsNullOrWhiteSpace(hostEnv))
{
AzureSession.Instance.ClientFactory.AddUserAgent(hostEnv);
}
}
catch (Exception)
{
// ignore if it failed.
}
AzureSession.Instance.ClientFactory.AddHandler(
new CmdletInfoHandler(this.CommandRuntime.ToString(),
this.ParameterSetName, this._clientRequestId));
}
protected virtual void TearDownHttpClientPipeline()
{
try
{
string hostEnv = AzurePSCmdlet.getEnvUserAgent();
if (!String.IsNullOrWhiteSpace(hostEnv))
{
AzureSession.Instance.ClientFactory.RemoveUserAgent(hostEnv);
}
}
catch (Exception)
{
// ignore if it failed.
}
AzureSession.Instance.ClientFactory.RemoveUserAgent(ModuleName);
AzureSession.Instance.ClientFactory.RemoveHandler(typeof(CmdletInfoHandler));
}
/// <summary>
/// Cmdlet begin process. Write to logs, setup Http Tracing and initialize profile
/// </summary>
protected override void BeginProcessing()
{
FlushInitializationWarnings();
SessionState = base.SessionState;
var profile = _dataCollectionProfile;
//TODO: Inject from CI server
if (_metricHelper == null)
{
lock (lockObject)
{
if (_metricHelper == null)
{
_metricHelper = new MetricHelper(profile);
_metricHelper.AddDefaultTelemetryClient();
}
}
}
// Fetch module name and version which will be used by telemetry and useragent
if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
{
this.ModuleName = this.MyInvocation.MyCommand.ModuleName;
if (this.MyInvocation.MyCommand.Version != null)
{
this.ModuleVersion = this.MyInvocation.MyCommand.Version.ToString();
}
}
else
{
this.ModuleName = this.GetType().Assembly.GetName().Name;
this.ModuleVersion = this.GetType().Assembly.GetName().Version.ToString();
}
InitializeQosEvent();
LogCmdletStartInvocationInfo();
InitDebuggingFilter();
SetupDebuggingTraces();
SetupHttpClientPipeline();
base.BeginProcessing();
//Now see if the cmdlet has any Breaking change attributes on it and process them if it does
//This will print any breaking change attribute messages that are applied to the cmdlet
WriteBreakingChangeOrPreviewMessage();
}
private void WriteBreakingChangeOrPreviewMessage()
{
if (AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager)
&& configManager.GetConfigValue<bool>(ConfigKeysForCommon.DisplayBreakingChangeWarning, MyInvocation))
{
BreakingChangeAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteWarning);
// Write preview message once for each cmdlet in one session
// Preview message may be outputed more than once if a cmdlet is concurrently called
// Considering lock affects performance but warning message is no harm
if (this.MyInvocation?.MyCommand != null
&& !PromptedPreviewMessageCmdlets.Contains(this.MyInvocation?.MyCommand?.Name)
&& PreviewAttributeHelper.ContainsPreviewAttribute(this.GetType(), this.MyInvocation))
{
PreviewAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteWarning);
PromptedPreviewMessageCmdlets.Enqueue(this.MyInvocation.MyCommand.Name);
}
}
}
private void WriteSecretsWarningMessage()
{
if (_qosEvent?.SanitizerInfo != null)
{
var sanitizerInfo = _qosEvent.SanitizerInfo;
if (sanitizerInfo.ShowSecretsWarning && sanitizerInfo.SecretsDetected)
{
if (sanitizerInfo.DetectedProperties.IsEmpty)
{
WriteWarning(string.Format(Resources.DisplaySecretsWarningMessageWithoutProperty, MyInvocation.InvocationName));
}
else
{
WriteWarning(string.Format(Resources.DisplaySecretsWarningMessageWithProperty, MyInvocation.InvocationName, string.Join(", ", sanitizerInfo.DetectedProperties.PropertyNames)));
}
}
}
}
/// <summary>
/// Perform end of pipeline processing.
/// </summary>
protected override void EndProcessing()
{
WriteEndProcessingRecommendation();
WriteWarningMessageForVersionUpgrade();
WriteSecretsWarningMessage();
if (MetricHelper.IsCalledByUser()
&& SurveyHelper.GetInstance().ShouldPromptAzSurvey()
&& (AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager)
&& !configManager.GetConfigValue<bool>(ConfigKeysForCommon.EnableInterceptSurvey, MyInvocation).Equals(false)))
{
WriteSurvey();
if (_qosEvent != null)
{
_qosEvent.SurveyPrompted = true;
}
}
if (MetricHelper.IsCalledByUser())
{
// Send telemetry when cmdlet is directly called by user
LogQosEvent();
}
else
{
// When cmdlet is called within another cmdlet, we will not add a new telemetry, but add the cmdlet name to InternalCalledCmdlets
MetricHelper.AppendInternalCalledCmdlet(this.MyInvocation?.MyCommand?.Name);
}
LogCmdletEndInvocationInfo();
TearDownDebuggingTraces();
TearDownHttpClientPipeline();
_previousEndTime = DateTimeOffset.Now;
base.EndProcessing();
}
private void WriteEndProcessingRecommendation()
{
if (AzureSession.Instance.TryGetComponent<IEndProcessingRecommendationService>(nameof(IEndProcessingRecommendationService), out var service))
{
service.Process(this, MyInvocation, _qosEvent);
}
}
private void WriteWarningMessageForVersionUpgrade()
{
AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager);
AzureSession.Instance.TryGetComponent<IFrequencyService>(nameof(IFrequencyService), out var frequencyService);
UpgradeNotificationHelper.GetInstance().WriteWarningMessageForVersionUpgrade(this, _qosEvent, configManager, frequencyService);
}
protected string CurrentPath()
{
// SessionState is only available within PowerShell so default to
// the TestMockSupport.TestExecutionFolder when being run from tests.
return (SessionState != null) ?
SessionState.Path.CurrentLocation.Path :
TestMockSupport.TestExecutionFolder;
}
protected bool IsVerbose()
{
bool verbose = MyInvocation.BoundParameters.ContainsKey("Verbose")
&& ((SwitchParameter)MyInvocation.BoundParameters["Verbose"]).ToBool();
return verbose;
}
protected void WriteSurvey()
{
// Using color same with Azure brand event.
// Using Ansi Code to control font color(97(Bold White)) and background color(0;120;212(RGB))
string ansiCodePrefix = "\u001b[97;48;2;0;120;212m";
// using '[k' for erase in line. '[0m' to ending ansi code
string ansiCodeSuffix = "\u001b[K\u001b[0m";
var website = "https://go.microsoft.com/fwlink/?linkid=2202892";
WriteInformation(Environment.NewLine);
WriteInformation(ansiCodePrefix + string.Format(Resources.SurveyPreface, website) + ansiCodeSuffix, false);
}
protected new void WriteError(ErrorRecord errorRecord)
{
FlushDebugMessages();
if (ShouldRecordDebugMessages())
{
RecordDebugMessages();
}
if (_qosEvent != null && errorRecord != null)
{
_qosEvent.Exception = errorRecord.Exception;
_qosEvent.IsSuccess = false;
}
base.WriteError(errorRecord);
if (AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager)
&& configManager.GetConfigValue<bool>(ConfigKeysForCommon.DisplayBreakingChangeWarning, MyInvocation))
{
PreviewAttributeHelper.ProcessCustomAttributesAtRuntime(this.GetType(), this.MyInvocation, WriteWarning);
}
}
protected new void ThrowTerminatingError(ErrorRecord errorRecord)
{
FlushDebugMessages();
if (ShouldRecordDebugMessages())
{
RecordDebugMessages();
}
base.ThrowTerminatingError(errorRecord);
}
protected new void WriteObject(object sendToPipeline)
{
FlushDebugMessages();
SanitizeOutput(sendToPipeline);
base.WriteObject(sendToPipeline);
}
protected new void WriteObject(object sendToPipeline, bool enumerateCollection)
{
FlushDebugMessages();
SanitizeOutput(sendToPipeline);
base.WriteObject(sendToPipeline, enumerateCollection);
}
private void SanitizeOutput(object sendToPipeline)
{
if (OutputSanitizer != null && OutputSanitizer.RequireSecretsDetection
&& !OutputSanitizer.IgnoredModules.Contains(MyInvocation?.MyCommand?.ModuleName)
&& !OutputSanitizer.IgnoredCmdlets.Contains(MyInvocation?.MyCommand?.Name))
{
OutputSanitizer.Sanitize(sendToPipeline, out var telemetry);
_qosEvent?.SanitizerInfo.Combine(telemetry);
}
}
protected new void WriteVerbose(string text)
{
FlushDebugMessages();
base.WriteVerbose(text);
}
protected new void WriteWarning(string text)
{
FlushDebugMessages();
base.WriteWarning(text);
}
protected new void WriteInformation(object messageData, string[] tags)
{
FlushDebugMessages();
base.WriteInformation(messageData, tags);
}
protected void WriteInformation(string text, bool? noNewLine = null)
{
HostInformationMessage message = new HostInformationMessage { Message = text, NoNewLine = noNewLine };
WriteInformation(message, new string[1] { "PSHOST" });
}
protected new void WriteCommandDetail(string text)
{
FlushDebugMessages();
base.WriteCommandDetail(text);
}
protected new void WriteProgress(ProgressRecord progressRecord)
{
FlushDebugMessages();
base.WriteProgress(progressRecord);
}
protected new void WriteDebug(string text)
{
FlushDebugMessages();
base.WriteDebug(text);
}
protected void WriteVerboseWithTimestamp(string message, params object[] args)
{
if (CommandRuntime != null)
{
WriteVerbose(string.Format("{0:T} - {1}", DateTime.Now, string.Format(message, args)));
}
}
protected void WriteVerboseWithTimestamp(string message)
{
if (CommandRuntime != null)
{
WriteVerbose(string.Format("{0:T} - {1}", DateTime.Now, message));
}
}
protected void WriteWarningWithTimestamp(string message)
{
if (CommandRuntime != null)
{
WriteWarning(string.Format("{0:T} - {1}", DateTime.Now, message));
}
}
protected void WriteInformationWithTimestamp(string message)
{
if (CommandRuntime != null)
{
WriteInformation(
new HostInformationMessage { Message = string.Format("{0:T} - {1}", DateTime.Now, message), NoNewLine = false },
new string[1] { "PSHOST" });
}
}
protected void WriteDebugWithTimestamp(string message, params object[] args)
{
if (CommandRuntime != null)
{
WriteDebug(string.Format("{0:T} - {1}", DateTime.Now, string.Format(message, args)));
}
}
protected void WriteDebugWithTimestamp(string message)
{
if (CommandRuntime != null)
{
WriteDebug(string.Format("{0:T} - {1}", DateTime.Now, message));
}
}
protected void WriteErrorWithTimestamp(string message)
{
if (CommandRuntime != null)
{
WriteError(
new ErrorRecord(new Exception(string.Format("{0:T} - {1}", DateTime.Now, message)),
string.Empty,
ErrorCategory.NotSpecified,
null));
}
}
/// <summary>
/// Write an error message for a given exception.
/// </summary>
/// <param name="ex">The exception resulting from the error.</param>
protected virtual void WriteExceptionError(Exception ex)
{
Debug.Assert(ex != null, "ex cannot be null or empty.");
WriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
}
protected PSObject ConstructPSObject(string typeName, params object[] args)
{
return PowerShellUtilities.ConstructPSObject(typeName, args);
}
protected void SafeWriteOutputPSObject(string typeName, params object[] args)
{
PSObject customObject = this.ConstructPSObject(typeName, args);
WriteObject(customObject);
}
private void FlushDebugMessages()
{
string message;
while (DebugMessages.TryDequeue(out message))
{
base.WriteDebug(message);
}
}
public void WriteInitializationWarnings(string message)
{
InitializationWarnings.Enqueue(message);
}
protected void FlushInitializationWarnings()
{
string message;
while (InitializationWarnings.TryDequeue(out message))
{
base.WriteWarning(message);
}
}
protected virtual void InitializeQosEvent()
{
_qosEvent = new AzurePSQoSEvent()
{
ClientRequestId = this._clientRequestId,
// Use SessionId from MetricHelper so that generated cmdlet and handcrafted cmdlet could share the same Id
SessionId = MetricHelper.SessionId,
IsSuccess = true,
ParameterSetName = this.ParameterSetName,
PreviousEndTime = _previousEndTime
};
if (AzVersion == null)
{
AzVersion = this.LoadModuleVersion("Az", true);
PowerShellVersion = this.LoadPowerShellVersion();
PSHostName = this.Host?.Name;
PSHostVersion = this.Host?.Version?.ToString();
}
UserAgent = new ProductInfoHeaderValue("AzurePowershell", string.Format("Az{0}", AzVersion)).ToString();
string hostEnv = AzurePSCmdlet.getEnvUserAgent();
if (!String.IsNullOrWhiteSpace(hostEnv))
UserAgent += string.Format(" {0}", hostEnv);
if (AzAccountsVersion == null)
{
AzAccountsVersion = this.LoadModuleVersion("Az.Accounts", false);
}
_qosEvent.AzVersion = AzVersion;
_qosEvent.AzAccountsVersion = AzAccountsVersion;
_qosEvent.UserAgent = UserAgent;
_qosEvent.PSVersion = PowerShellVersion;
_qosEvent.HostVersion = PSHostVersion;
_qosEvent.PSHostName = PSHostName;
_qosEvent.ModuleName = this.ModuleName;
_qosEvent.ModuleVersion = this.ModuleVersion;
_qosEvent.SourceScript = MyInvocation.ScriptName;
_qosEvent.ScriptLineNumber = MyInvocation.ScriptLineNumber;
if (this.MyInvocation != null && this.MyInvocation.MyCommand != null)
{
_qosEvent.CommandName = this.MyInvocation.MyCommand.Name;
}
else
{
_qosEvent.CommandName = this.GetType().Name;
}
if (this.MyInvocation != null && !string.IsNullOrWhiteSpace(this.MyInvocation.InvocationName))
{
_qosEvent.InvocationName = this.MyInvocation.InvocationName;
}
if (this.MyInvocation != null && this.MyInvocation.BoundParameters != null
&& this.MyInvocation.BoundParameters.Keys != null)
{
if (AzureSession.Instance.TryGetComponent<IParameterTelemetryFormatter>(nameof(IParameterTelemetryFormatter), out var formatter))
{
_qosEvent.Parameters = formatter.FormatParameters(MyInvocation);
}
else
{
_qosEvent.Parameters = string.Join(" ",
this.MyInvocation.BoundParameters.Keys.Select(
s => string.Format(CultureInfo.InvariantCulture, "-{0} ***", s)));
}
}
_qosEvent.SanitizerInfo = new SanitizerTelemetry(OutputSanitizer?.RequireSecretsDetection == true);
}
private static string getEnvUserAgent()
{
string hostEnv = Environment.GetEnvironmentVariable("AZUREPS_HOST_ENVIRONMENT");
if (String.IsNullOrWhiteSpace(hostEnv))
{
return null;
}
else
{
return hostEnv.Trim().Replace("@", "_").Replace("/", "_");
}
}
private void RecordDebugMessages()
{
try
{
// Create 'ErrorRecords' folder under profile directory, if not exists
if (string.IsNullOrEmpty(_errorRecordFolderPath)
|| !Directory.Exists(_errorRecordFolderPath))
{
_errorRecordFolderPath = Path.Combine(AzurePowerShell.ProfileDirectory,
"ErrorRecords");
Directory.CreateDirectory(_errorRecordFolderPath);
}
CommandInfo cmd = this.MyInvocation.MyCommand;
string filePrefix = cmd.Name;
string timeSampSuffix = DateTime.Now.ToString(_fileTimeStampSuffixFormat);
string fileName = filePrefix + "_" + timeSampSuffix + ".log";
string filePath = Path.Combine(_errorRecordFolderPath, fileName);
StringBuilder sb = new StringBuilder();
sb.Append("Module : ").AppendLine(cmd.ModuleName);
sb.Append("Cmdlet : ").AppendLine(cmd.Name);
sb.AppendLine("Parameters");
foreach (var item in this.MyInvocation.BoundParameters)
{
sb.Append(" -").Append(item.Key).Append(" : ");
sb.AppendLine(item.Value == null ? "null" : item.Value.ToString());
}
sb.AppendLine();
foreach (var content in DebugMessages)
{
sb.AppendLine(content);
}
AzureSession.Instance.DataStore.WriteFile(filePath, sb.ToString());
}
catch
{
// do not throw an error if recording debug messages fails
}
}
//Use DisableErrorRecordsPersistence as opt-out for now, will replace it with EnableErrorRecordsPersistence as opt-in at next major release (November 2023)
private bool ShouldRecordDebugMessages()
{
return AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager)
&& configManager.GetConfigValue<bool>(ConfigKeysForCommon.EnableErrorRecordsPersistence, MyInvocation)
&& IsDataCollectionAllowed();
}
/// <summary>
/// Invoke this method when the cmdlet is completed or terminated.
/// </summary>
protected void LogQosEvent()
{
if (_qosEvent == null)
{
return;
}
_qosEvent.ParameterSetName = this.ParameterSetName;
_qosEvent.FinishQosEvent();
if (!IsUsageMetricEnabled && (!IsErrorMetricEnabled || _qosEvent.IsSuccess))
{
return;
}
WriteDebug(_qosEvent.ToString());
try
{
_metricHelper.LogQoSEvent(_qosEvent, IsUsageMetricEnabled, IsErrorMetricEnabled);
_metricHelper.FlushMetric();
}
catch (Exception e)
{
//Swallow error from Application Insights event collection.
WriteWarning(e.ToString());
}
}
/// <summary>
/// Guards execution of the given action using ShouldProcess and ShouldContinue. This is a legacy
/// version forcompatibility with older RDFE cmdlets.
/// </summary>
/// <param name="force">Do not ask for confirmation</param>
/// <param name="continueMessage">Message to describe the action</param>
/// <param name="processMessage">Message to prompt after the active is performed.</param>
/// <param name="target">The target name.</param>
/// <param name="action">The action code</param>
protected virtual void ConfirmAction(bool force, string continueMessage, string processMessage, string target,
Action action)
{
if (_qosEvent != null)
{
_qosEvent.PauseQoSTimer();
}
if (force || ShouldContinue(continueMessage, ""))
{
if (ShouldProcess(target, processMessage))
{
if (_qosEvent != null)
{
_qosEvent.ResumeQosTimer();
}
action();
}
}
}
/// <summary>
/// Guards execution of the given action using ShouldProcess and ShouldContinue. The optional
/// useSHouldContinue predicate determines whether SHouldContinue should be called for this
/// particular action (e.g. a resource is being overwritten). By default, both
/// ShouldProcess and ShouldContinue will be executed. Cmdlets that use this method overload
/// must have a force parameter.
/// </summary>
/// <param name="force">Do not ask for confirmation</param>
/// <param name="continueMessage">Message to describe the action</param>
/// <param name="processMessage">Message to prompt after the active is performed.</param>
/// <param name="target">The target name.</param>
/// <param name="action">The action code</param>
/// <param name="useShouldContinue">A predicate indicating whether ShouldContinue should be invoked for thsi action</param>
protected virtual void ConfirmAction(bool force, string continueMessage, string processMessage, string target, Action action, Func<bool> useShouldContinue)
{
if (null == useShouldContinue)
{
useShouldContinue = () => true;
}
if (_qosEvent != null)
{
_qosEvent.PauseQoSTimer();
}
if (ShouldProcess(target, processMessage))
{
if (force || !useShouldContinue() || ShouldContinue(continueMessage, ""))
{
if (_qosEvent != null)
{
_qosEvent.ResumeQosTimer();
}
action();
}
}
}
/// <summary>
/// Prompt for confirmation depending on the ConfirmLevel. By default No confirmation prompt
/// occurs unless ConfirmLevel >= $ConfirmPreference. Guarding the actions of a cmdlet with this
/// method will enable the cmdlet to support -WhatIf and -Confirm parameters.
/// </summary>
/// <param name="processMessage">The change being made to the resource</param>
/// <param name="target">The resource that is being changed</param>
/// <param name="action">The action to perform if confirmed</param>
protected virtual void ConfirmAction(string processMessage, string target, Action action)
{
if (_qosEvent != null)
{
_qosEvent.PauseQoSTimer();
}
if (ShouldProcess(target, processMessage))
{
if (_qosEvent != null)
{
_qosEvent.ResumeQosTimer();
}
action();
}
}
public virtual void ExecuteCmdlet()
{
// Do nothing.
}
protected override void ProcessRecord()
{