|
| 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.Generic; |
| 17 | +using System.Linq; |
| 18 | +using System.Management.Automation; |
| 19 | +using Microsoft.Azure.Commands.Insights.OutputClasses; |
| 20 | +using Microsoft.Azure.Insights; |
| 21 | +using Microsoft.Azure.Insights.Models; |
| 22 | + |
| 23 | +namespace Microsoft.Azure.Commands.Insights |
| 24 | +{ |
| 25 | + /// <summary> |
| 26 | + /// Base class for the Azure SDK EventService Cmdlets |
| 27 | + /// </summary> |
| 28 | + public abstract class EventCmdletBase : InsightsCmdletBase |
| 29 | + { |
| 30 | + internal static readonly TimeSpan DefaultQueryTimeRange = TimeSpan.FromHours(-1); |
| 31 | + |
| 32 | + internal static int MaxNumberOfReturnedRecords = 100000; |
| 33 | + |
| 34 | + internal const string SubscriptionLevelName = "Query at subscription level"; |
| 35 | + internal const string ResourceProviderName = "Query on ResourceProvider"; |
| 36 | + internal const string ResourceGroupName = "Query on ResourceGroupProvider"; |
| 37 | + internal const string ResourceUriName = "Query on ResourceUriName"; |
| 38 | + internal const string CorrelationIdName = "Query on CorrelationId"; |
| 39 | + |
| 40 | + #region Optional parameters declarations |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Gets or sets the starttime parameter of the cmdlet |
| 44 | + /// </summary> |
| 45 | + [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "The startTime of the query")] |
| 46 | + [ValidateNotNullOrEmpty] |
| 47 | + public string StartTime { get; set; } |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Gets or sets the endtime parameter of the cmdlet |
| 51 | + /// </summary> |
| 52 | + [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "The endTime of the query")] |
| 53 | + [ValidateNotNullOrEmpty] |
| 54 | + public string EndTime { get; set; } |
| 55 | + |
| 56 | + /// <summary> |
| 57 | + /// Gets or sets the status parameter of the cmdlet |
| 58 | + /// </summary> |
| 59 | + [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "The status of the records to fetch")] |
| 60 | + [ValidateNotNullOrEmpty] |
| 61 | + public string Status { get; set; } |
| 62 | + |
| 63 | + /// <summary> |
| 64 | + /// Gets or sets the caller parameter of the cmdlet |
| 65 | + /// </summary> |
| 66 | + [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "The caller of the records to fetch")] |
| 67 | + [ValidateNotNullOrEmpty] |
| 68 | + public string Caller { get; set; } |
| 69 | + |
| 70 | + /// <summary> |
| 71 | + /// Gets or sets the detailedoutput parameter of the cmdlet |
| 72 | + /// </summary> |
| 73 | + [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "Return object with all the details of the records (the default is to return only some attributes, i.e. no detail)")] |
| 74 | + public SwitchParameter DetailedOutput { get; set; } |
| 75 | + |
| 76 | + #endregion |
| 77 | + |
| 78 | + #region Parameters processing |
| 79 | + |
| 80 | + /// <summary> |
| 81 | + /// Adds a condition to the query filter based on the give name and the value |
| 82 | + /// </summary> |
| 83 | + /// <param name="currentQueryFilter">The current query filter</param> |
| 84 | + /// <param name="name">The name to be used in the new condition</param> |
| 85 | + /// <param name="value">The value to be used in the new condition.<para>If this value is null, the currentQueryFilter is returned unmodified.</para></param> |
| 86 | + /// <returns></returns> |
| 87 | + protected string AddConditionIfPResent(string currentQueryFilter, string name, string value) |
| 88 | + { |
| 89 | + return !string.IsNullOrWhiteSpace(value) ? string.Format("{0} and {1} eq '{2}'", currentQueryFilter, name, value) : currentQueryFilter; |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Process the parameters defined by this class |
| 94 | + /// </summary> |
| 95 | + /// <returns>The query filter with the conditions for general parameters (i.e. defined by this class) added</returns> |
| 96 | + private string ProcessGeneralParameters() |
| 97 | + { |
| 98 | + DateTime startTime; |
| 99 | + if (string.IsNullOrWhiteSpace(this.StartTime)) |
| 100 | + { |
| 101 | + // Default to one hour from Now |
| 102 | + startTime = DateTime.Now.Subtract(DefaultQueryTimeRange); |
| 103 | + } |
| 104 | + else if (!DateTime.TryParse(this.StartTime, out startTime)) |
| 105 | + { |
| 106 | + throw new ArgumentException("Unable to parse startTime argument"); |
| 107 | + } |
| 108 | + |
| 109 | + string queryFilter; |
| 110 | + |
| 111 | + // EndTime is optional |
| 112 | + if (string.IsNullOrWhiteSpace(this.EndTime)) |
| 113 | + { |
| 114 | + queryFilter = string.Format("eventTimestamp ge '{0:o}'", startTime.ToUniversalTime()); |
| 115 | + } |
| 116 | + else |
| 117 | + { |
| 118 | + DateTime endTime; |
| 119 | + if (!DateTime.TryParse(this.EndTime, out endTime)) |
| 120 | + { |
| 121 | + throw new ArgumentException("Unable to parse endTime argument"); |
| 122 | + } |
| 123 | + |
| 124 | + queryFilter = string.Format("eventTimestamp ge '{0:o}' and eventTimestamp le '{1:o}'", startTime.ToUniversalTime(), endTime.ToUniversalTime()); |
| 125 | + } |
| 126 | + |
| 127 | + // Include the status if present |
| 128 | + queryFilter = this.AddConditionIfPResent(queryFilter, "status", this.Status); |
| 129 | + |
| 130 | + // Include the caller if present |
| 131 | + queryFilter = this.AddConditionIfPResent(queryFilter, "caller", this.Caller); |
| 132 | + |
| 133 | + return queryFilter; |
| 134 | + } |
| 135 | + |
| 136 | + /// <summary> |
| 137 | + /// Process the general parameters (i.e. defined in this class) and the particular parameters (i.e. the parameters added by the descendants of this class). |
| 138 | + /// </summary> |
| 139 | + /// <returns>The final query filter to be used by the cmdlet</returns> |
| 140 | + protected string ProcessParameters() |
| 141 | + { |
| 142 | + string queryFilter = this.ProcessGeneralParameters(); |
| 143 | + return this.ProcessParticularParameters(queryFilter); |
| 144 | + } |
| 145 | + |
| 146 | + /// <summary> |
| 147 | + /// Process the parameters defined by the descendants of this class |
| 148 | + /// </summary> |
| 149 | + /// <param name="currentQueryFilter">The current query filter</param> |
| 150 | + /// <returns>The query filter with the conditions for particular parameters added</returns> |
| 151 | + protected abstract string ProcessParticularParameters(string currentQueryFilter); |
| 152 | + |
| 153 | + #endregion |
| 154 | + |
| 155 | + /// <summary> |
| 156 | + /// Execute the cmdlet |
| 157 | + /// </summary> |
| 158 | + public override void ExecuteCmdlet() |
| 159 | + { |
| 160 | + string queryFilter = this.ProcessParameters(); |
| 161 | + |
| 162 | + // Call the proper API methods to return a list of raw records. In the future this pattern can be extended to include DigestRecords |
| 163 | + Func<string, string, EventDataListResponse> initialCall = (f, s) => this.InsightsClient.EventOperations.ListEvents(filterString: f, selectedProperties: s); |
| 164 | + Func<string, EventDataListResponse> nextCall = (n) => this.InsightsClient.EventOperations.ListEventsNext(nextLink: n); |
| 165 | + |
| 166 | + // Retrieve the records |
| 167 | + var fullDetails = this.DetailedOutput.IsPresent; |
| 168 | + |
| 169 | + // If fullDetails is present do not select fields, if not present fetch only the SelectedFieldsForQuery |
| 170 | + EventDataListResponse response = initialCall.Invoke(queryFilter, fullDetails ? null : PSEventDataNoDetails.SelectedFieldsForQuery); |
| 171 | + var records = new List<IPSEventData>(response.EventDataCollection.Value.Select(e => fullDetails ? (IPSEventData)new PSEventData(e) : (IPSEventData)new PSEventDataNoDetails(e))); |
| 172 | + string nextLink = response.EventDataCollection.NextLink; |
| 173 | + |
| 174 | + // Adding a safety check to stop returning records if too many have been read already. |
| 175 | + while (!string.IsNullOrWhiteSpace(nextLink) && records.Count < MaxNumberOfReturnedRecords) |
| 176 | + { |
| 177 | + response = nextCall.Invoke(nextLink); |
| 178 | + records.AddRange(response.EventDataCollection.Value.Select(e => fullDetails ? (IPSEventData)new PSEventData(e) : (IPSEventData)new PSEventDataNoDetails(e))); |
| 179 | + nextLink = response.EventDataCollection.NextLink; |
| 180 | + } |
| 181 | + |
| 182 | + // Returns an object that contains a link to the set of subsequent records or null if not more records are available, called Next, and an array of records, called Value |
| 183 | + WriteObject(sendToPipeline: records, enumerateCollection: true); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments