public void UnitTestDoWork_With_No_Explicit_Roles_Configured_For_White_List_Service()
        {
            MockRepository mockRepository = new MockRepository();
            WhiteListService whiteListService = new WhiteListService { Name = "wls1" };
            WhiteListService[] whiteListServices = new[] { whiteListService };

            // Arrange
            ISubscription mockSubscription = mockRepository.StrictMock<ISubscription>();
            mockSubscription
                .Expect(s => s.ListHostedServices())
                .Repeat.Once()
                .Return(new[] { "wls1" });
            mockSubscription
                .Expect(s => s.SubscriptionId)
                .Repeat.Any()
                .Return(SubscriptionId);
            mockSubscription
                .Expect(s => s.CertificateThumbprint)
                .Repeat.Any()
                .Return(CertificateThumbprint);
            ISubscription[] subscriptions = new[] { mockSubscription };
            IDeployment mockDeployment = mockRepository.StrictMock<IDeployment>();
            IOperation mockOperation = mockRepository.StrictMock<IOperation>();

            // Act
            // There are no roles configured for the white list service, therefore there should be no checks made against
            // the service, we just accept however it is deployed for instance count or instance size.
            mockRepository.ReplayAll();
            WhiteListForecastWorker whiteListForecastWorker = new WhiteListForecastWorker(subscriptions, mockDeployment, mockOperation, whiteListServices, 1);
            whiteListForecastWorker.DoWork();
            whiteListForecastWorker.DoWork(); // Call twice to test the polling interval (nothing should be invoked the second time).

            // Assert
            mockRepository.VerifyAll();
        }
        public void UnitTestDoWork_With_One_Role_Having_Instance_Count_Too_High_And_Second_Role_Having_Instance_Size_Too_Large()
        {
            MockRepository mockRepository = new MockRepository();
            WhiteListService whiteListService = new WhiteListService { Name = "wls1" };
            WhiteListRole whiteListRole = new WhiteListRole { Name = "wlr1", MaxInstanceSize = InstanceSize.ExtraSmall, MaxInstanceCount = 1 };
            whiteListService.Roles.Add(whiteListRole);
            WhiteListService[] whiteListServices = new[] { whiteListService };

            // Arrange
            ISubscription mockSubscription = mockRepository.StrictMock<ISubscription>();
            mockSubscription
                .Expect(s => s.ListHostedServices())
                .Repeat.Once()
                .Return(new[] { "bls1", "wls1" });
            mockSubscription
                .Expect(s => s.SubscriptionId)
                .Repeat.Any()
                .Return(SubscriptionId);
            mockSubscription
                .Expect(s => s.CertificateThumbprint)
                .Repeat.Any()
                .Return(CertificateThumbprint);
            ISubscription[] subscriptions = new[] { mockSubscription };
            IDeployment mockDeployment = mockRepository.StrictMock<IDeployment>();
            IOperation mockOperation = mockRepository.StrictMock<IOperation>();

            // Delete the black listed service from Staging and Production
            SetupDeleteRequestWithStatusCheck(mockDeployment, mockOperation, "bls1", DeploymentSlot.Staging, "deleteRequest1");
            SetupDeleteRequestWithStatusCheck(mockDeployment, mockOperation, "bls1", DeploymentSlot.Production, "deleteRequest2");

            // Get the instance size of White List Role 1 from Staging, all okay.
            mockDeployment
                .Expect(d => d.GetInstanceSize(SubscriptionId, CertificateThumbprint, "wls1", DeploymentSlot.Staging, "wlr1"))
                .Repeat.Once()
                .Return(InstanceSize.ExtraSmall.ToString());

            // Get the instance count of White List Role 1 from Staging, horizontally scale as a result.
            mockDeployment
                .Expect(d => d.GetInstanceCount(SubscriptionId, CertificateThumbprint, "wls1", DeploymentSlot.Staging, "wlr1"))
                .Repeat.Once()
                .Return(2);
            SetupHorizontallyScaleWithStatusCheck(mockDeployment, mockOperation, "wls1", DeploymentSlot.Staging, new[] { new HorizontalScale { RoleName = "wlr1", InstanceCount = 1 } }, "scaleRequest1");

            // Get the instance size of the White List Role 1 from Production, delete as a result.
            mockDeployment
                .Expect(d => d.GetInstanceSize(SubscriptionId, CertificateThumbprint, "wls1", DeploymentSlot.Production, "wlr1"))
                .Repeat.Once()
                .Return(InstanceSize.ExtraLarge.ToString());
            SetupDeleteRequestWithStatusCheck(mockDeployment, mockOperation, "wls1", DeploymentSlot.Production, "deleteRequest3");

            // Act
            mockRepository.ReplayAll();
            WhiteListForecastWorker whiteListForecastWorker = new WhiteListForecastWorker(subscriptions, mockDeployment, mockOperation, whiteListServices, 1);
            whiteListForecastWorker.DoWork();
            whiteListForecastWorker.DoWork(); // Call twice to test the polling interval (nothing should be invoked the second time).

            // Assert
            mockRepository.VerifyAll();
        }
 public WhiteListForecastWorker(
     ISubscription[] subscriptions,
     IDeployment deployment,
     IOperation operation,
     WhiteListService[] allowedServices,
     int pollingIntervalInMinutes)
     : base(GetWorkerId(typeof(WhiteListForecastWorker).FullName))
 {
     this.subscriptions = subscriptions;
     this.deployment = deployment;
     this.operation = operation;
     this.allowedServices = allowedServices;
     this.pollingIntervalInMinutes = pollingIntervalInMinutes;
 }
        public WhiteListConfiguration GetWindowsAzureHostedServiceWhiteListConfiguration()
        {
            // The "StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList" property is
            // never null because it's a "Configuration Element Collection". So the best way to test if the White
            // List has been explicitly configured is if the "PollingIntervalInMinutes" is set (i.e. not "0").
            if (StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList.PollingIntervalInMinutes > 0)
            {
                WhiteListConfiguration whiteListConfiguration = new WhiteListConfiguration();
                whiteListConfiguration.IncludeDeploymentCreateServices = StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList.IncludeDeploymentCreateServices;
                whiteListConfiguration.IncludeDeploymentDeleteServices = StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList.IncludeDeploymentDeleteServices;
                whiteListConfiguration.IncludeHorizontalScaleServices = StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList.IncludeHorizontalScaleServices;
                whiteListConfiguration.PollingIntervalInMinutes = StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList.PollingIntervalInMinutes;
                foreach (ServiceConfigurationElement serviceConfigurationElement in StealFocusForecastConfiguration.Instance.WindowsAzure.HostedService.WhiteList)
                {
                    WhiteListService whiteListService = new WhiteListService { Name = serviceConfigurationElement.Name };
                    foreach (RoleConfigurationElement roleConfigurationElement in serviceConfigurationElement.Roles)
                    {
                        WhiteListRole whiteListRole = new WhiteListRole { Name = roleConfigurationElement.Name };
                        if (!string.IsNullOrEmpty(roleConfigurationElement.MaxInstanceSize))
                        {
                            InstanceSize instanceSize;
                            bool parsed = System.Enum.TryParse(roleConfigurationElement.MaxInstanceSize, true, out instanceSize);
                            if (!parsed)
                            {
                                string exceptionMessage = string.Format(CultureInfo.CurrentCulture, "The configured instance size of '{0}' could not be parsed as a valid Azure instance size. Valid values are '{1}', '{2}', '{3}', '{4}' or '{5}'.", roleConfigurationElement.MaxInstanceSize, InstanceSize.ExtraSmall, InstanceSize.Small, InstanceSize.Medium, InstanceSize.Large, InstanceSize.ExtraLarge);
                                throw new ForecastException(exceptionMessage);
                            }

                            whiteListRole.MaxInstanceSize = instanceSize;
                        }

                        if (roleConfigurationElement.MaxInstanceCount > 0)
                        {
                            whiteListRole.MaxInstanceCount = roleConfigurationElement.MaxInstanceCount;
                        }

                        whiteListService.Roles.Add(whiteListRole);
                    }

                    whiteListConfiguration.Services.Add(whiteListService);
                }

                return whiteListConfiguration;
            }

            return null;
        }
        private bool FindIfDeployedInstanceSizesExceedWhiteListConfiguration(ISubscription subscription, string hostedServiceName, WhiteListService whiteListService, string deploymentSlot)
        {
            if (whiteListService.Roles.Count == 0)
            {
                // No explicit roles configured, so just allow whatever is there.
                return false;
            }

            foreach (WhiteListRole whiteListRole in whiteListService.Roles)
            {
                if (whiteListRole.MaxInstanceSize.HasValue)
                {
                    string actualInstanceSizeValue = this.deployment.GetInstanceSize(subscription.SubscriptionId, subscription.CertificateThumbprint, hostedServiceName, deploymentSlot, whiteListRole.Name);
                    InstanceSize actualInstanceSize = (InstanceSize)Enum.Parse(typeof(InstanceSize), actualInstanceSizeValue);
                    if (actualInstanceSize > whiteListRole.MaxInstanceSize.Value)
                    {
                        return true;
                    }
                }
            }

            return false;
        }
        private HorizontalScale[] FindHorizontalScaleChangesComparedToWhitelist(ISubscription subscription, string hostedServiceName, WhiteListService whiteListService, string deploymentSlot)
        {
            List<HorizontalScale> horizontalScales = new List<HorizontalScale>();
            foreach (WhiteListRole whiteListRole in whiteListService.Roles)
            {
                if (whiteListRole.MaxInstanceCount.HasValue)
                {
                    int instanceCount = this.deployment.GetInstanceCount(subscription.SubscriptionId, subscription.CertificateThumbprint, hostedServiceName, deploymentSlot, whiteListRole.Name);
                    if (instanceCount > whiteListRole.MaxInstanceCount)
                    {
                        HorizontalScale horizontalScale = new HorizontalScale { InstanceCount = whiteListRole.MaxInstanceCount.Value, RoleName = whiteListRole.Name };
                        horizontalScales.Add(horizontalScale);
                    }
                }
            }

            return horizontalScales.ToArray();
        }
        private void CheckDeploymentAgainstItsWhiteListEntry(ISubscription subscription, string hostedServiceName, WhiteListService whiteListService, string deploymentSlot)
        {
            bool deployedInstanceSizesExceedWhiteListConfiguration = this.FindIfDeployedInstanceSizesExceedWhiteListConfiguration(subscription, hostedServiceName, whiteListService, deploymentSlot);
            if (deployedInstanceSizesExceedWhiteListConfiguration)
            {
                this.DeleteDeployedService(subscription, hostedServiceName, deploymentSlot);
                return;
            }

            HorizontalScale[] horizontalScales = this.FindHorizontalScaleChangesComparedToWhitelist(subscription, hostedServiceName, whiteListService, deploymentSlot);
            if (horizontalScales.Length > 0)
            {
                this.HorizontallyScaleDeployedServiceRole(subscription, hostedServiceName, deploymentSlot, horizontalScales);
            }
        }
        internal static WhiteListForecastWorker GetWhiteListForecastWorker()
        {
            IConfigurationSource configurationSource = GetConfigurationSource();
            WhiteListConfiguration whiteListConfiguration = configurationSource.GetWindowsAzureHostedServiceWhiteListConfiguration();
            if (whiteListConfiguration != null)
            {
                SubscriptionConfiguration[] subscriptionConfigurations = configurationSource.GetAllWindowsAzureSubscriptionConfigurations();
                ISubscription[] subscriptions = new ISubscription[subscriptionConfigurations.Length];
                for (int i = 0; i < subscriptionConfigurations.Length; i++)
                {
                    subscriptions[i] = subscriptionConfigurations[i].Convert();
                }

                if (whiteListConfiguration.IncludeDeploymentCreateServices)
                {
                    foreach (DeploymentCreateConfiguration deploymentCreateConfiguration in configurationSource.GetWindowsAzureDeploymentCreateConfigurations())
                    {
                        bool alreadyIncluded = false;
                        foreach (WhiteListService configuredWhiteListService in whiteListConfiguration.Services)
                        {
                            if (configuredWhiteListService.Name == deploymentCreateConfiguration.ServiceName)
                            {
                                alreadyIncluded = true;
                            }
                        }

                        if (!alreadyIncluded)
                        {
                            WhiteListService whiteListService = new WhiteListService { Name = deploymentCreateConfiguration.ServiceName };
                            whiteListConfiguration.Services.Add(whiteListService);
                        }
                    }
                }

                if (whiteListConfiguration.IncludeDeploymentDeleteServices)
                {
                    foreach (DeploymentDeleteConfiguration deploymentDeleteConfiguration in configurationSource.GetWindowsAzureDeploymentDeleteConfigurations())
                    {
                        bool alreadyIncluded = false;
                        foreach (WhiteListService configuredWhiteListService in whiteListConfiguration.Services)
                        {
                            if (configuredWhiteListService.Name == deploymentDeleteConfiguration.ServiceName)
                            {
                                alreadyIncluded = true;
                            }
                        }

                        if (!alreadyIncluded)
                        {
                            WhiteListService whiteListService = new WhiteListService { Name = deploymentDeleteConfiguration.ServiceName };
                            whiteListConfiguration.Services.Add(whiteListService);
                        }
                    }
                }

                if (whiteListConfiguration.IncludeHorizontalScaleServices)
                {
                    foreach (ScheduledHorizontalScaleConfiguration windowsAzureScheduledHorizontalScaleConfiguration in configurationSource.GetWindowsAzureScheduledHorizontalScaleConfigurations())
                    {
                        bool alreadyIncluded = false;
                        foreach (WhiteListService configuredWhiteListService in whiteListConfiguration.Services)
                        {
                            if (configuredWhiteListService.Name == windowsAzureScheduledHorizontalScaleConfiguration.ServiceName)
                            {
                                alreadyIncluded = true;
                            }
                        }

                        if (!alreadyIncluded)
                        {
                            WhiteListService whiteListService = new WhiteListService { Name = windowsAzureScheduledHorizontalScaleConfiguration.ServiceName };
                            whiteListConfiguration.Services.Add(whiteListService);
                        }
                    }
                }

                WhiteListForecastWorker whiteListForecastWorker = new WhiteListForecastWorker(
                    subscriptions,
                    new Deployment(),
                    new Operation(),
                    whiteListConfiguration.Services.ToArray(),
                    whiteListConfiguration.PollingIntervalInMinutes);
                return whiteListForecastWorker;
            }

            return null;
        }