|
| 1 | +// ---------------------------------------------------------------------------------- |
| 2 | +// |
| 3 | +// Copyright Microsoft Corporation |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | +// ---------------------------------------------------------------------------------- |
| 14 | + |
| 15 | +using System; |
| 16 | +using System.Collections.Concurrent; |
| 17 | +using System.Diagnostics; |
| 18 | +using System.Management.Automation; |
| 19 | +using System.Net.Http.Headers; |
| 20 | +using System.Reflection; |
| 21 | +using Microsoft.Azure.Common.Authentication; |
| 22 | +using Microsoft.Azure.Common.Authentication.Models; |
| 23 | +using Microsoft.WindowsAzure.Commands.Common; |
| 24 | + |
| 25 | +namespace Microsoft.WindowsAzure.Commands.Utilities.Common |
| 26 | +{ |
| 27 | + /// <summary> |
| 28 | + /// Represents base class for all Azure cmdlets. |
| 29 | + /// </summary> |
| 30 | + public abstract class AzurePSCmdlet : PSCmdlet, IDisposable |
| 31 | + { |
| 32 | + private readonly ConcurrentQueue<string> _debugMessages; |
| 33 | + |
| 34 | + private RecordingTracingInterceptor _httpTracingInterceptor; |
| 35 | + |
| 36 | + private DebugStreamTraceListener _adalListener; |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Gets the PowerShell module name used for user agent header. |
| 40 | + /// By default uses "Azurepowershell" |
| 41 | + /// </summary> |
| 42 | + protected virtual string ModuleName { get { return "AzurePowershell"; } } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Gets PowerShell module version used for user agent header. |
| 46 | + /// </summary> |
| 47 | + protected string ModuleVersion { get { return Assembly.GetCallingAssembly().GetName().Version.ToString(); } } |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Gets the default Azure context. |
| 51 | + /// </summary> |
| 52 | + protected abstract AzureContext Context { get; } |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Initializes AzurePSCmdlet properties. |
| 56 | + /// </summary> |
| 57 | + public AzurePSCmdlet() |
| 58 | + { |
| 59 | + _debugMessages = new ConcurrentQueue<string>(); |
| 60 | + } |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Cmdlet begin process. Write to logs, setup Http Tracing and initialize profile and adds user agent. |
| 64 | + /// </summary> |
| 65 | + protected override void BeginProcessing() |
| 66 | + { |
| 67 | + if (string.IsNullOrEmpty(ParameterSetName)) |
| 68 | + { |
| 69 | + WriteDebugWithTimestamp(string.Format("{0} begin processing without ParameterSet.", this.GetType().Name)); |
| 70 | + } |
| 71 | + else |
| 72 | + { |
| 73 | + WriteDebugWithTimestamp(string.Format("{0} begin processing with ParameterSet '{1}'.", this.GetType().Name, ParameterSetName)); |
| 74 | + } |
| 75 | + |
| 76 | + if (Context != null && Context.Account != null && Context.Account.Id != null) |
| 77 | + { |
| 78 | + WriteDebugWithTimestamp(string.Format("using account id '{0}'...", Context.Account.Id)); |
| 79 | + } |
| 80 | + |
| 81 | + _httpTracingInterceptor = _httpTracingInterceptor ?? new RecordingTracingInterceptor(_debugMessages); |
| 82 | + _adalListener = _adalListener ?? new DebugStreamTraceListener(_debugMessages); |
| 83 | + RecordingTracingInterceptor.AddToContext(_httpTracingInterceptor); |
| 84 | + DebugStreamTraceListener.AddAdalTracing(_adalListener); |
| 85 | + |
| 86 | + ProductInfoHeaderValue userAgentValue = new ProductInfoHeaderValue( |
| 87 | + ModuleName, string.Format("v{0}", ModuleVersion)); |
| 88 | + AzureSession.ClientFactory.UserAgents.Add(userAgentValue); |
| 89 | + |
| 90 | + base.BeginProcessing(); |
| 91 | + } |
| 92 | + |
| 93 | + /// <summary> |
| 94 | + /// End processing. Flush messages in tracing interceptor and save profile and removes user agent. |
| 95 | + /// </summary> |
| 96 | + protected override void EndProcessing() |
| 97 | + { |
| 98 | + string message = string.Format("{0} end processing.", this.GetType().Name); |
| 99 | + WriteDebugWithTimestamp(message); |
| 100 | + |
| 101 | + RecordingTracingInterceptor.RemoveFromContext(_httpTracingInterceptor); |
| 102 | + DebugStreamTraceListener.RemoveAdalTracing(_adalListener); |
| 103 | + FlushDebugMessages(); |
| 104 | + |
| 105 | + AzureSession.ClientFactory.UserAgents.RemoveAll(u => u.Product.Name == ModuleName); |
| 106 | + |
| 107 | + base.EndProcessing(); |
| 108 | + } |
| 109 | + |
| 110 | + protected string CurrentPath() |
| 111 | + { |
| 112 | + // SessionState is only available within Powershell so default to |
| 113 | + // the CurrentDirectory when being run from tests. |
| 114 | + return (SessionState != null) ? |
| 115 | + SessionState.Path.CurrentLocation.Path : |
| 116 | + Environment.CurrentDirectory; |
| 117 | + } |
| 118 | + |
| 119 | + protected bool IsVerbose() |
| 120 | + { |
| 121 | + bool verbose = MyInvocation.BoundParameters.ContainsKey("Verbose") && ((SwitchParameter)MyInvocation.BoundParameters["Verbose"]).ToBool(); |
| 122 | + return verbose; |
| 123 | + } |
| 124 | + |
| 125 | + protected new void WriteError(ErrorRecord errorRecord) |
| 126 | + { |
| 127 | + FlushDebugMessages(); |
| 128 | + base.WriteError(errorRecord); |
| 129 | + } |
| 130 | + |
| 131 | + protected new void WriteObject(object sendToPipeline) |
| 132 | + { |
| 133 | + FlushDebugMessages(); |
| 134 | + base.WriteObject(sendToPipeline); |
| 135 | + } |
| 136 | + |
| 137 | + protected new void WriteObject(object sendToPipeline, bool enumerateCollection) |
| 138 | + { |
| 139 | + FlushDebugMessages(); |
| 140 | + base.WriteObject(sendToPipeline, enumerateCollection); |
| 141 | + } |
| 142 | + |
| 143 | + protected new void WriteVerbose(string text) |
| 144 | + { |
| 145 | + FlushDebugMessages(); |
| 146 | + base.WriteVerbose(text); |
| 147 | + } |
| 148 | + |
| 149 | + protected new void WriteWarning(string text) |
| 150 | + { |
| 151 | + FlushDebugMessages(); |
| 152 | + base.WriteWarning(text); |
| 153 | + } |
| 154 | + |
| 155 | + protected new void WriteCommandDetail(string text) |
| 156 | + { |
| 157 | + FlushDebugMessages(); |
| 158 | + base.WriteCommandDetail(text); |
| 159 | + } |
| 160 | + |
| 161 | + protected new void WriteProgress(ProgressRecord progressRecord) |
| 162 | + { |
| 163 | + FlushDebugMessages(); |
| 164 | + base.WriteProgress(progressRecord); |
| 165 | + } |
| 166 | + |
| 167 | + protected new void WriteDebug(string text) |
| 168 | + { |
| 169 | + FlushDebugMessages(); |
| 170 | + base.WriteDebug(text); |
| 171 | + } |
| 172 | + |
| 173 | + protected void WriteVerboseWithTimestamp(string message, params object[] args) |
| 174 | + { |
| 175 | + WriteVerbose(string.Format("{0:T} - {1}", DateTime.Now, string.Format(message, args))); |
| 176 | + } |
| 177 | + |
| 178 | + protected void WriteVerboseWithTimestamp(string message) |
| 179 | + { |
| 180 | + WriteVerbose(string.Format("{0:T} - {1}", DateTime.Now, message)); |
| 181 | + } |
| 182 | + |
| 183 | + protected void WriteWarningWithTimestamp(string message) |
| 184 | + { |
| 185 | + WriteWarning(string.Format("{0:T} - {1}", DateTime.Now, message)); |
| 186 | + } |
| 187 | + |
| 188 | + protected void WriteDebugWithTimestamp(string message, params object[] args) |
| 189 | + { |
| 190 | + WriteDebug(string.Format("{0:T} - {1}", DateTime.Now, string.Format(message, args))); |
| 191 | + } |
| 192 | + |
| 193 | + protected void WriteDebugWithTimestamp(string message) |
| 194 | + { |
| 195 | + WriteDebug(string.Format("{0:T} - {1}", DateTime.Now, message)); |
| 196 | + } |
| 197 | + |
| 198 | + protected void WriteErrorWithTimestamp(string message) |
| 199 | + { |
| 200 | + WriteError( |
| 201 | + new ErrorRecord(new Exception(string.Format("{0:T} - {1}", DateTime.Now, message)), |
| 202 | + string.Empty, |
| 203 | + ErrorCategory.NotSpecified, |
| 204 | + null)); |
| 205 | + } |
| 206 | + |
| 207 | + /// <summary> |
| 208 | + /// Write an error message for a given exception. |
| 209 | + /// </summary> |
| 210 | + /// <param name="ex">The exception resulting from the error.</param> |
| 211 | + protected virtual void WriteExceptionError(Exception ex) |
| 212 | + { |
| 213 | + Debug.Assert(ex != null, "ex cannot be null or empty."); |
| 214 | + WriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null)); |
| 215 | + } |
| 216 | + |
| 217 | + protected PSObject ConstructPSObject(string typeName, params object[] args) |
| 218 | + { |
| 219 | + return PowerShellUtilities.ConstructPSObject(typeName, args); |
| 220 | + } |
| 221 | + |
| 222 | + protected void SafeWriteOutputPSObject(string typeName, params object[] args) |
| 223 | + { |
| 224 | + PSObject customObject = this.ConstructPSObject(typeName, args); |
| 225 | + WriteObject(customObject); |
| 226 | + } |
| 227 | + |
| 228 | + private void FlushDebugMessages() |
| 229 | + { |
| 230 | + string message; |
| 231 | + while (_debugMessages.TryDequeue(out message)) |
| 232 | + { |
| 233 | + base.WriteDebug(message); |
| 234 | + } |
| 235 | + } |
| 236 | + |
| 237 | + /// <summary> |
| 238 | + /// Asks for confirmation before executing the action. |
| 239 | + /// </summary> |
| 240 | + /// <param name="force">Do not ask for confirmation</param> |
| 241 | + /// <param name="actionMessage">Message to describe the action</param> |
| 242 | + /// <param name="processMessage">Message to prompt after the active is performed.</param> |
| 243 | + /// <param name="target">The target name.</param> |
| 244 | + /// <param name="action">The action code</param> |
| 245 | + protected void ConfirmAction(bool force, string actionMessage, string processMessage, string target, Action action) |
| 246 | + { |
| 247 | + if (force || ShouldContinue(actionMessage, "")) |
| 248 | + { |
| 249 | + if (ShouldProcess(target, processMessage)) |
| 250 | + { |
| 251 | + action(); |
| 252 | + } |
| 253 | + } |
| 254 | + } |
| 255 | + |
| 256 | + protected virtual void Dispose(bool disposing) |
| 257 | + { |
| 258 | + _adalListener.Dispose(); |
| 259 | + } |
| 260 | + |
| 261 | + public void Dispose() |
| 262 | + { |
| 263 | + Dispose(true); |
| 264 | + GC.SuppressFinalize(this); |
| 265 | + } |
| 266 | + } |
| 267 | +} |
0 commit comments