/// <summary>
        /// Execute the cmdlet
        /// </summary>
        public override void ExecuteCmdlet()
        {
            try
            {
                string queryFilter = this.ProcessParameters();

                // Retrieve the records
                var fullDetails = this.DetailedOutput.IsPresent;

                // Call the proper API methods to return a list of raw records. In the future this pattern can be extended to include DigestRecords
                // If fullDetails is present do not select fields, if not present fetch only the SelectedFieldsForQuery
                EventDataListResponse response = this.InsightsClient.EventOperations.ListEventsAsync(filterString: queryFilter, selectedProperties: fullDetails ? null : PSEventDataNoDetails.SelectedFieldsForQuery, cancellationToken: CancellationToken.None).Result;
                var    records  = new List <IPSEventData>(response.EventDataCollection.Value.Where(this.KeepTheRecord).Select(e => fullDetails ? (IPSEventData) new PSEventData(e) : (IPSEventData) new PSEventDataNoDetails(e)));
                string nextLink = response.EventDataCollection.NextLink;

                // Adding a safety check to stop returning records if too many have been read already.
                while (!string.IsNullOrWhiteSpace(nextLink) && records.Count < MaxNumberOfReturnedRecords)
                {
                    response = this.InsightsClient.EventOperations.ListEventsNextAsync(nextLink: nextLink, cancellationToken: CancellationToken.None).Result;
                    records.AddRange(response.EventDataCollection.Value.Select(e => fullDetails ? (IPSEventData) new PSEventData(e) : (IPSEventData) new PSEventDataNoDetails(e)));
                    nextLink = response.EventDataCollection.NextLink;
                }

                // 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
                WriteObject(sendToPipeline: records, enumerateCollection: true);
            }
            catch (AggregateException ex)
            {
                throw ex.Flatten().InnerException;
            }
        }
示例#2
0
        public static void VerifyContinuationToken(EventDataListResponse response, Mock <IEventOperations> insinsightsEventOperationsMockightsClientMock, EventCmdletBase cmdlet)
        {
            // Make sure calls to Next work also
            response.EventDataCollection.NextLink = Utilities.ContinuationToken;
            var responseNext = new EventDataListResponse()
            {
                EventDataCollection = new EventDataCollection()
                {
                    Value = new List <EventData>()
                    {
                        Utilities.CreateFakeEvent(),
                    },
                    NextLink = null,
                },
                RequestId  = Guid.NewGuid().ToString(),
                StatusCode = HttpStatusCode.OK
            };

            string nextToken = null;

            insinsightsEventOperationsMockightsClientMock.Setup(f => f.ListEventsNextAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <EventDataListResponse>(responseNext))
            .Callback((string n, CancellationToken t) => nextToken = n);

            // Calling without optional parameters
            cmdlet.ExecuteCmdlet();
            Assert.True(string.Equals(Utilities.ContinuationToken, nextToken, StringComparison.OrdinalIgnoreCase), "Incorrect continuation token");
        }
        private const double days = -10; //max = -90  (90 days of logs is stored by audit logs)

        static void Main(string[] args)
        {
            Console.WriteLine("Starting operations log export.");

            string token = GetAuthorizationHeader();

            TokenCloudCredentials credentials = new TokenCloudCredentials(SubscriptionID, token);
            InsightsClient        client      = new InsightsClient(credentials);

            DateTime endDateTime   = DateTime.Now;
            DateTime startDateTime = endDateTime.AddDays(days);

            string filterString = FilterString.Generate <ListEventsForResourceProviderParameters>(eventData => (eventData.EventTimestamp >= startDateTime) && (eventData.EventTimestamp <= endDateTime));

            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);
            List <EventData>      logList  = new List <EventData>(response.EventDataCollection.Value);

            while (!string.IsNullOrEmpty(response.EventDataCollection.NextLink))
            {
                Console.WriteLine($"Retrieving page {response.EventDataCollection.NextLink}");

                response = client.EventOperations.ListEventsNext(response.EventDataCollection.NextLink);
                logList.AddRange(response.EventDataCollection.Value);
            }

            ResourceManagementClient resClient = new ResourceManagementClient(credentials);

            Console.WriteLine($"Page retrieval completed, preparing to write to a file {CSVExportNamePath}.");

            ExportOpsLogToCSV(logList, resClient);

            Console.WriteLine("Export completed.");
            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
        /// <summary>
        /// Gets event logs by tracking Id.
        /// </summary>
        /// <param name="correlationId">CorrelationId Id of the deployment</param>
        /// <returns>Logs.</returns>
        public virtual IEnumerable <PSDeploymentEventData> GetDeploymentLogs(string correlationId)
        {
            EventDataListResponse listOfEvents = EventsClient.EventData.ListEventsForCorrelationId(new ListEventsForCorrelationIdParameters
            {
                CorrelationId = correlationId,
                StartTime     = DateTime.UtcNow - TimeSpan.FromDays(EventRetentionPeriod),
                EndTime       = DateTime.UtcNow
            });

            return(listOfEvents.EventDataCollection.Value.Select(e => e.ToPSDeploymentEventData()));
        }
示例#5
0
        static void Main(string[] args)
        {
            // Define the base URI for management operations
            Uri baseUri = new Uri("https://management.azure.com");

            string token           = GetAuthorizationHeader();
            var    startTime       = DateTime.Now;
            var    endTime         = startTime.ToUniversalTime().AddHours(1.0).ToLocalTime();
            var    redisConnection = "";

            ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(redisConnection);
            IDatabase             cachedb    = connection.GetDatabase();

            for (int i = 0; i < 10; i++)
            {
                cachedb.StringIncrement(i.ToString());
                Console.WriteLine("value=" + cachedb.StringGet(i.ToString()));
            }


            // Get the credentials
            // You can find instructions on how to get the token here:
            // http://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
            SubscriptionCloudCredentials credentials = new TokenCloudCredentials(subscriptionId, token);

            // Create an instance of the InsightsClient from Microsoft.Azure.Insights
            InsightsClient client = new InsightsClient(credentials, baseUri);

            // Get the events for an Azure Resource (e.g. Website) (as described by the Azure Resource Manager APIs here:http://msdn.microsoft.com/en-us/library/azure/dn790569.aspx)
            // A resource URI looks like the following string:
            //"/subscriptions/########-####-####-####-############/resourceGroups/resourcegroupname1/providers/resourceprovider1/resourcename1"
            string resourceUri = string.Format("subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Cache/redis/{2}", subscriptionId, resourceGroupName, cacheName);

            //Define a FilterString
            string filterString = FilterString.Generate <ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceUri == resourceUri));

            //Get the events logs
            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);


            //Check the status code of the response
            Console.WriteLine("HTTP Status Code returned for the call:" + response.StatusCode);

            var response2 = client.MetricDefinitionOperations.GetMetricDefinitions(resourceUri, "");
            var metrics   = client.MetricOperations.GetMetrics(resourceUri, "startTime eq 2015-01-14T02:19:03.0712821Z and endTime eq 2015-01-14T03:19:03.0712821Z and timeGrain eq duration'PT5M'", response2.MetricDefinitionCollection.Value);

            Console.WriteLine("Print out the metrics logs");
            foreach (var item in metrics.MetricCollection.Value)
            {
                Console.WriteLine(item.Name.Value + "--" + item.MetricValues.Count);
            }
        }
        /// <summary>
        /// Gets event logs.
        /// </summary>
        /// <param name="parameters">Input parameters</param>
        /// <returns>Logs.</returns>
        public virtual IEnumerable <PSDeploymentEventData> GetResourceGroupLogs(GetPSResourceGroupLogParameters parameters)
        {
            if (parameters.All)
            {
                EventDataListResponse listOfEvents =
                    EventsClient.EventData.ListEventsForResourceGroup(new ListEventsForResourceGroupParameters
                {
                    ResourceGroupName = parameters.Name,
                    StartTime         = DateTime.UtcNow - TimeSpan.FromDays(EventRetentionPeriod),
                    EndTime           = DateTime.UtcNow
                });
                return(listOfEvents.EventDataCollection.Value.Select(e => e.ToPSDeploymentEventData()));
            }
            else if (!string.IsNullOrEmpty(parameters.DeploymentName))
            {
                DeploymentGetResult deploymentGetResult;
                try
                {
                    deploymentGetResult = ResourceManagementClient.Deployments.Get(parameters.Name,
                                                                                   parameters.DeploymentName);
                }
                catch
                {
                    throw new ArgumentException(string.Format(ProjectResources.DeploymentWithNameNotFound, parameters.DeploymentName));
                }

                return(GetDeploymentLogs(deploymentGetResult.Deployment.Properties.CorrelationId));
            }
            else
            {
                DeploymentListResult deploymentListResult;
                try
                {
                    deploymentListResult = ResourceManagementClient.Deployments.List(parameters.Name,
                                                                                     new DeploymentListParameters
                    {
                        Top = 1
                    });
                    if (deploymentListResult.Deployments.Count == 0)
                    {
                        throw new ArgumentException(string.Format(ProjectResources.NoDeploymentWereFound, parameters.Name));
                    }
                }
                catch
                {
                    throw new ArgumentException(string.Format(ProjectResources.NoDeploymentWereFound, parameters.Name));
                }

                return(GetDeploymentLogs(deploymentListResult.Deployments[0].Properties.CorrelationId));
            }
        }
示例#7
0
        public static List <AzureResourceEventData> GetEventData(string token, string subscriptionId, string resourceUri, DateTime startTime, DateTime endTime)
        {
            var result = new List <AzureResourceEventData>();

            string filterString = FilterString.Generate <ListEventsForResourceParameters>(eventData => (eventData.EventTimestamp >= startTime) && (eventData.EventTimestamp <= endTime) && (eventData.ResourceUri == resourceUri));

            var            credentials = CredentialManager.GetCredentials(token, subscriptionId);
            InsightsClient client      = new InsightsClient(credentials);

            EventDataListResponse response = client.EventOperations.ListEvents(filterString, selectedProperties: null);

            foreach (var eventEntry in response.EventDataCollection.Value)
            {
                result.Add(new AzureResourceEventData(eventEntry));
            }

            return(result);
        }
示例#8
0
        public GetAzureCorrelationIdLogCommandTests()
        {
            insightsEventOperationsMock = new Mock <IEventOperations>();
            insightsClientMock          = new Mock <InsightsClient>();
            commandRuntimeMock          = new Mock <ICommandRuntime>();
            cmdlet = new GetAzureCorrelationIdLogCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Utilities.InitializeResponse();

            insightsEventOperationsMock.Setup(f => f.ListEventsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <EventDataListResponse>(response))
            .Callback((string f, string s, CancellationToken t) =>
            {
                filter   = f;
                selected = s;
            });

            insightsClientMock.SetupGet(f => f.EventOperations).Returns(this.insightsEventOperationsMock.Object);
        }
示例#9
0
        public GetAzureRmLogTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagemenet.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagemenet.Common.Models.XunitTracingInterceptor(output));
            insightsEventOperationsMock = new Mock <IEventOperations>();
            insightsClientMock          = new Mock <InsightsClient>();
            commandRuntimeMock          = new Mock <ICommandRuntime>();
            cmdlet = new GetAzureRmLogCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                InsightsClient = insightsClientMock.Object
            };

            response = Utilities.InitializeResponse();

            insightsEventOperationsMock.Setup(f => f.ListEventsAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <EventDataListResponse>(response))
            .Callback((string f, string s, CancellationToken t) =>
            {
                filter   = f;
                selected = s;
            });

            insightsClientMock.SetupGet(f => f.EventOperations).Returns(this.insightsEventOperationsMock.Object);
        }
示例#10
0
        public static void ExecuteVerifications(EventCmdletBase cmdlet, Mock <IEventOperations> insinsightsEventOperationsMockightsClientMock, string requiredFieldName, string requiredFieldValue, ref string filter, ref string selected, DateTime startDate, EventDataListResponse response)
        {
            // Calling without optional parameters
            cmdlet.ExecuteCmdlet();

            VerifyFilterIsUsable(filter: filter);
            VerifyStartDateInFilter(filter: filter, startDate: null);
            VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue);
            Assert.True(string.Equals(PSEventDataNoDetails.SelectedFieldsForQuery, selected, StringComparison.OrdinalIgnoreCase), "Incorrect nameOrTargetUri clause without optional parameters");

            // Calling with only start date
            cmdlet.StartTime = startDate;
            cmdlet.ExecuteCmdlet();

            VerifyFilterIsUsable(filter: filter);
            VerifyStartDateInFilter(filter: filter, startDate: startDate);
            VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue);

            // Calling with only start and end date
            cmdlet.EndTime = startDate.AddSeconds(2);
            cmdlet.ExecuteCmdlet();

            VerifyFilterIsUsable(filter: filter);
            VerifyStartDateInFilter(filter: filter, startDate: startDate);
            VerifyEndDateInFilter(filter: filter, endDate: startDate.AddSeconds(2));
            VerifyConditionInFilter(filter: filter, field: requiredFieldName, value: requiredFieldValue);

            // Calling with only caller
            cmdlet.EndTime = null;
            cmdlet.Caller  = Utilities.Caller;
            cmdlet.ExecuteCmdlet();

            VerifyCallerInCall(filter: filter, startDate: startDate, filedName: requiredFieldName, fieldValue: requiredFieldValue);

            // Calling with caller and status
            cmdlet.Status = Utilities.Status;
            cmdlet.ExecuteCmdlet();

            VerifyStatusAndCallerInCall(filter: filter, startDate: startDate, filedName: requiredFieldName, fieldValue: requiredFieldValue);

            VerifyDetailedOutput(cmdlet: cmdlet, selected: ref selected);
            VerifyContinuationToken(response: response, insinsightsEventOperationsMockightsClientMock: insinsightsEventOperationsMockightsClientMock, cmdlet: cmdlet);

            // Execute negative tests
            cmdlet.StartTime = DateTime.Now.AddSeconds(1);
            Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.StartTime = DateTime.Now.Subtract(TimeSpan.FromSeconds(20));
            cmdlet.EndTime   = DateTime.Now.Subtract(TimeSpan.FromSeconds(21));
            Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet());

            cmdlet.StartTime = DateTime.Now.Subtract(TimeSpan.FromDays(30));
            cmdlet.EndTime   = DateTime.Now.Subtract(TimeSpan.FromDays(14));
            Assert.Throws <ArgumentException>(() => cmdlet.ExecuteCmdlet());
        }