public AutoBundleConfigProcessor(string projectPath, string packagePath, string entryPointOverride, List <string> filePaths, Encoding encoding, Microsoft.Build.Utilities.TaskLoggingHelper log = null, MessageImportance logLevel = MessageImportance.Low)
        {
            ProjectPath   = projectPath;
            FilePaths     = filePaths;
            OutputPath    = projectPath;
            EntryOverride = entryPointOverride;
            this.encoding = encoding;
            this.Log      = log;
            this.LogLevel = logLevel;

            if (!string.IsNullOrWhiteSpace(packagePath))
            {
                OutputPath = packagePath;
            }

            EntryPoint = this.GetEntryPointPath();

            Log?.LogMessage(LogLevel, "Autobundler initialized");
            Log?.LogMessage(LogLevel, $" - Project path: {projectPath}");
            Log?.LogMessage(LogLevel, $" - Package path: {packagePath}");
            Log?.LogMessage(LogLevel, $" - EP Override : {entryPointOverride}");
            Log?.LogMessage(LogLevel, $" - Encoding    : {encoding.EncodingName}");
            Log?.LogMessage(LogLevel, $" - Entrypoint  : {EntryPoint}");
            Log?.LogMessage(LogLevel, $" - Output path : {OutputPath}");
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Deleting route {0}", CFRoute);

            string domain = string.Empty;
            string host = string.Empty;
            Utils.ExtractDomainAndHost(CFRoute, out domain, out host);

            if (domain.Length == 0 || host.Length == 0)
            {
                logger.LogError("Error extracting domain and host information from route {0}", CFRoute);
                return false;
            }

            PagedResponseCollection<ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;
            ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

            var routeList = client.Routes.ListAllRoutes(new RequestOptions() { Query = string.Format(CultureInfo.InvariantCulture,"host:{0}&domain_guid:{1}", host, domainInfo.EntityMetadata.Guid) }).Result;

            if (routeList.Count() > 1)
            {
                logger.LogError("There is more than one route that matches for deletion of route {0}", CFRoute);
                return false;
            }

            client.Routes.DeleteRoute(new Guid(routeList.FirstOrDefault().EntityMetadata.Guid)).Wait();

            return true;
        }
Пример #3
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                if (!Directory.Exists(CFAppPath))
                {
                    logger.LogError("Directory {0} not found", CFAppPath);
                    return(false);
                }

                client.Apps.PushProgress += Apps_PushProgress;

                client.Apps.Push(new Guid(CFAppGuid), CFAppPath, CFStart).Wait();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }
            return(true);
        }
Пример #4
0
        public async Task CompareLocalPackageToFeedPackageShouldCorrectlyInterpretFeedResponse(
            string feedResponseContentName,
            HttpStatusCode feedResponseStatusCode,
            PackageFeedStatus expectedResult)
        {
            var localPackagePath  = TestInputs.GetFullPath(Path.Combine("Nupkgs", "test-package-a.zip"));
            var packageContentUrl = $"https://fakefeed.azure.com/nuget/v3/{feedResponseContentName}.nupkg";
            var taskLoggingHelper = new Microsoft.Build.Utilities.TaskLoggingHelper(new StubTask());
            var retryHandler      = new MockRetryHandler();

            var response = new HttpResponseMessage(feedResponseStatusCode);

            if (!string.IsNullOrEmpty(feedResponseContentName))
            {
                var content = TestInputs.ReadAllBytes(Path.Combine("Nupkgs", $"{feedResponseContentName}.zip"));
                response.Content = new ByteArrayContent(content);
            }
            ;

            var httpClient = FakeHttpClient.WithResponses(response);

            var result = await GeneralUtils.CompareLocalPackageToFeedPackage(
                localPackagePath,
                packageContentUrl,
                httpClient,
                taskLoggingHelper,
                retryHandler);

            result.Should().Be(expectedResult);
        }
Пример #5
0
        [InlineData(HttpStatusCode.InternalServerError, 2)] // retry on 5xx
        public async Task CompareLocalPackageToFeedPackageShouldRetryFailedRequests(
            HttpStatusCode initialResponseStatusCode,
            int expectedAttemptCount)
        {
            var testPackageName   = Path.Combine("Nupkgs", "test-package-a.zip");
            var localPackagePath  = TestInputs.GetFullPath(testPackageName);
            var packageContentUrl = "https://fakefeed.azure.com/nuget/v3/test-package-a.zip";
            var taskLoggingHelper = new Microsoft.Build.Utilities.TaskLoggingHelper(new StubTask());

            var retryHandler = new MockRetryHandler(maxAttempts: 2);

            var responseContent = TestInputs.ReadAllBytes(testPackageName);
            var responses       = new[]
            {
                new HttpResponseMessage(initialResponseStatusCode)
                {
                    Content = new ByteArrayContent(responseContent)
                },
                new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(responseContent)
                }
            };

            var httpClient = FakeHttpClient.WithResponses(responses);

            await GeneralUtils.CompareLocalPackageToFeedPackage(
                localPackagePath,
                packageContentUrl,
                httpClient,
                taskLoggingHelper,
                retryHandler);

            retryHandler.ActualAttempts.Should().Be(expectedAttemptCount);
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Deleting service {0} from space {1}", CFServiceName, CFSpace);

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }

            var servicesList = client.Spaces.ListAllServiceInstancesForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFServiceName }).Result;

            if (servicesList.Count() > 1)
            {
                logger.LogError("There are more services named {0} in space {1}", CFServiceName, CFSpace);
                return false;
            }

            client.ServiceInstances.DeleteServiceInstance(new Guid(servicesList.First().EntityMetadata.Guid)).Wait();
            return true;
        }
Пример #7
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                if (CFAppGuid.Length == 0)
                {
                    logger.LogError("Application Guid must be specified");
                    return(false);
                }

                CloudFoundryClient client = InitClient();

                logger.LogMessage("Binding routes to application {0}", CFAppGuid);
                foreach (string routeGuid in CFRouteGuids)
                {
                    client.Apps.AssociateRouteWithApp(new Guid(CFAppGuid), new Guid(routeGuid)).Wait();
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }
            return(true);
        }
Пример #8
0
 internal BatchSignUtil(IBuildEngine buildEngine, TaskLoggingHelper log, SignTool signTool,
                        BatchSignInput batchData, string[] itemsToSkipStrongNameCheck)
 {
     _signTool    = signTool;
     _batchData   = batchData;
     _log         = log;
     _buildEngine = buildEngine;
     _itemsToSkipStrongNameCheck = itemsToSkipStrongNameCheck ?? Array.Empty <string>();
 }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Unbinding route {0} from app {1}", CFRoute, CFAppName);

            string domain=string.Empty;
            string host = string.Empty;
            Utils.ExtractDomainAndHost(CFRoute, out domain, out host);

            if (domain.Length == 0 || host.Length == 0)
            {
                logger.LogError("Error extracting domain and host information from route {0}", CFRoute);
                return false;
            }

            PagedResponseCollection<ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;
            ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }

            PagedResponseCollection<ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFAppName }).Result;
            if (appList.Count() > 1)
            {
                logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                return false;
            }

            Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);

            PagedResponseCollection<ListAllRoutesForAppResponse> routeList = client.Apps.ListAllRoutesForApp(appGuid).Result;

            ListAllRoutesForAppResponse routeInfo =  routeList.Where(o => o.Host == host && o.DomainGuid == new Guid(domainInfo.EntityMetadata.Guid)).FirstOrDefault();

            if (routeInfo == null)
            {
                logger.LogError("Route {0} not found in {1}'s routes", CFRoute, CFAppName);
                return false;
            }

            client.Routes.RemoveAppFromRoute(new Guid(routeInfo.EntityMetadata.Guid), appGuid).Wait();

            return true;
        }
Пример #10
0
 public AzureBlobLease(string accountName, string accountKey, string connectionString, string containerName, string blobName, Microsoft.Build.Utilities.TaskLoggingHelper log, string maxWait = null, string delay = null)
 {
     _accountName      = accountName;
     _accountKey       = accountKey;
     _connectionString = connectionString;
     _containerName    = containerName;
     _blobName         = blobName;
     _maxWait          = !string.IsNullOrWhiteSpace(maxWait) ? TimeSpan.Parse(maxWait) : TimeSpan.FromSeconds(s_MaxWaitDefault);
     _delay            = !string.IsNullOrWhiteSpace(delay) ? TimeSpan.Parse(delay) : TimeSpan.FromMilliseconds(s_DelayDefault);
     _log      = log;
     _leaseUrl = $"{Utility.AzureHelper.GetBlobRestUrl(_accountName, _containerName, _blobName)}?comp=lease";
 }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Unbinding service {0} from app {1}", CFServiceName, CFAppName);

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }

            var servicesList = client.Spaces.ListAllServiceInstancesForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFServiceName }).Result;

            if (servicesList.Count() > 1)
            {
                logger.LogError("There are more services named {0} in space {1}", CFServiceName, CFSpace);
                return false;
            }

            Guid serviceGuid=new Guid(servicesList.FirstOrDefault().EntityMetadata.Guid);

            PagedResponseCollection<ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFAppName }).Result;
            if (appList.Count() > 1)
            {
                logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                return false;
            }

            Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);

            var bindingsList = client.Apps.ListAllServiceBindingsForApp(appGuid).Result;

            foreach (var bind in bindingsList)
            {
                if (bind.ServiceInstanceGuid.Value == serviceGuid)
                {
                    client.Apps.RemoveServiceBindingFromApp(appGuid, new Guid(bind.EntityMetadata.Guid)).Wait();
                }
            }

            return true;
        }
Пример #12
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Binding services to app {0}", CFAppGuid);

                List <string> bindingGuids = new List <string>();

                foreach (string serviceGuid in CFServicesGuids)
                {
                    CreateServiceBindingRequest request = new CreateServiceBindingRequest();
                    request.AppGuid             = new Guid(CFAppGuid);
                    request.ServiceInstanceGuid = new Guid(serviceGuid);

                    try
                    {
                        var result = client.ServiceBindings.CreateServiceBinding(request).Result;
                        bindingGuids.Add(result.EntityMetadata.Guid);
                    }
                    catch (AggregateException ex)
                    {
                        foreach (Exception e in ex.Flatten().InnerExceptions)
                        {
                            if (e is CloudFoundryException)
                            {
                                logger.LogWarning(e.Message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }

                CFBindingGuids = bindingGuids.ToArray();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }
            return(true);
        }
Пример #13
0
 internal BatchSignUtil(IBuildEngine buildEngine,
                        TaskLoggingHelper log,
                        SignTool signTool,
                        BatchSignInput batchData,
                        string[] itemsToSkipStrongNameCheck,
                        Dictionary <SignedFileContentKey, string> hashToCollisionIdMap,
                        Telemetry telemetry = null)
 {
     _signTool    = signTool;
     _batchData   = batchData;
     _log         = log;
     _buildEngine = buildEngine;
     _itemsToSkipStrongNameCheck = itemsToSkipStrongNameCheck ?? Array.Empty <string>();
     _telemetry            = telemetry;
     _hashToCollisionIdMap = hashToCollisionIdMap;
 }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);

                if (spaceGuid == null)
                {
                    return false;
                }
            }

            Guid? planGuid = null;
            PagedResponseCollection<ListAllServicesResponse> servicesList = client.Services.ListAllServices(new RequestOptions() { Query = "label:" + CFServiceType }).Result;

            foreach (var service in servicesList)
            {
               var planList = client.Services.ListAllServicePlansForService(new Guid(service.EntityMetadata.Guid)).Result;

               var plan = planList.Where(o => o.Name == CFServicePlan).FirstOrDefault();

               if (plan != null)
               {
                   planGuid = new Guid(plan.EntityMetadata.Guid);
                   break;
               }
            }

            CreateServiceInstanceRequest request = new CreateServiceInstanceRequest();

            request.Name = CFServiceName;
            request.ServicePlanGuid = planGuid;
            request.SpaceGuid = spaceGuid;

            CreateServiceInstanceResponse result = client.ServiceInstances.CreateServiceInstance(request).Result;

            CFServiceGuid = result.EntityMetadata.Guid;

            logger.LogMessage("Created {0} service {1}", CFServiceType, result.Name);
            return true;
        }
Пример #15
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            if (!Directory.Exists(CFAppPath))
            {
                logger.LogError("Directory {0} not found", CFAppPath);
                return false;
            }

            client.Apps.PushProgress += Apps_PushProgress;

            client.Apps.Push(new Guid(CFAppGuid), CFAppPath, CFStart).Wait();
            return true;
        }
Пример #16
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Deleting route {0}", CFRoute);

                string domain = string.Empty;
                string host   = string.Empty;
                Utils.ExtractDomainAndHost(CFRoute, out domain, out host);

                if (domain.Length == 0 || host.Length == 0)
                {
                    logger.LogError("Error extracting domain and host information from route {0}", CFRoute);
                    return(false);
                }

                PagedResponseCollection <ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;
                ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                var routeList = client.Routes.ListAllRoutes(new RequestOptions()
                {
                    Query = string.Format(CultureInfo.InvariantCulture, "host:{0}&domain_guid:{1}", host, domainInfo.EntityMetadata.Guid)
                }).Result;

                if (routeList.Count() > 1)
                {
                    logger.LogError("There is more than one route that matches for deletion of route {0}", CFRoute);
                    return(false);
                }

                client.Routes.DeleteRoute(new Guid(routeList.FirstOrDefault().EntityMetadata.Guid)).Wait();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #17
0
        internal static Guid?GetSpaceGuid(CloudFoundryClient client, Microsoft.Build.Utilities.TaskLoggingHelper logger, string CFOrganization, string CFSpace)
        {
            Guid?spaceGuid = null;
            PagedResponseCollection <ListAllOrganizationsResponse> orgList = client.Organizations.ListAllOrganizations(new RequestOptions()
            {
                Query = "name:" + CFOrganization
            }).Result;

            if (orgList.Count() > 1)
            {
                logger.LogError("There are more than one organization with name {0}, organization names need to be unique", CFOrganization);
                return(null);
            }

            ListAllOrganizationsResponse orgInfo = orgList.FirstOrDefault();

            if (orgInfo != null)
            {
                PagedResponseCollection <ListAllSpacesForOrganizationResponse> spaceList = client.Organizations.ListAllSpacesForOrganization(orgInfo.EntityMetadata.Guid.ToNullableGuid(), new RequestOptions()
                {
                    Query = "name:" + CFSpace
                }).Result;

                if (spaceList.Count() > 1)
                {
                    logger.LogError("There are more than one space with name {0} in organization {1}", CFSpace, CFOrganization);
                    return(null);
                }
                if (spaceList.FirstOrDefault() != null)
                {
                    spaceGuid = new Guid(spaceList.FirstOrDefault().EntityMetadata.Guid);
                }
                else
                {
                    logger.LogError("Space {0} not found", CFSpace);
                    return(null);
                }
            }
            else
            {
                logger.LogError("Organization {0} not found", CFOrganization);
                return(null);
            }
            return(spaceGuid);
        }
Пример #18
0
        public bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Saving configuration to {0}", CFConfigurationFile);

            PushProperties Configuration = new PushProperties();

            Configuration.AppDir       = CFAppPath;
            Configuration.Applications = new Dictionary <string, AppDetails>();
            Configuration.Applications.Add(CFAppPath, new AppDetails()
            {
                Name = CFAppName, Url = CFRoute
            });
            Configuration.AutoscaleInfo = new Autoscale()
            {
                Cpu = new Cpu()
                {
                    MaxCpu = CFMaxCpu, MinCpu = CFMinCpu
                }, Enabled = CFEnabled != null ? CFEnabled: "no", InstancesInfo = new Instances()
                {
                    MaxInstances = CFMaxInstances != 0 ? CFMaxInstances : 1, MinInstances = CFMinInstances != 0 ? CFMinInstances : 1
                }
            };
            Configuration.Disk          = CFDisk != 0 ? CFDisk : 1024;
            Configuration.Instances     = CFInstancesNumber;
            Configuration.Memory        = CFAppMemory;
            Configuration.Name          = CFAppName;
            Configuration.PlacementZone = CFPlacementZone != null ? CFPlacementZone : "default";
            if (CFServiceName != null)
            {
                Configuration.Services = new Dictionary <string, ServiceDetails>();
                Configuration.Services.Add(CFServiceName, new ServiceDetails()
                {
                    Plan = CFServicePlan, Type = CFServiceType
                });
            }

            Configuration.SsoEnabled = CFSsoEnabled != null ? CFSsoEnabled : "no";
            Configuration.Stack      = CFStack;

            Utils.SerializeToFile(Configuration, CFConfigurationFile);

            return(true);
        }
Пример #19
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Deleting service {0} from space {1}", CFServiceName, CFSpace);

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                var servicesList = client.Spaces.ListAllServiceInstancesForSpace(spaceGuid, new RequestOptions()
                {
                    Query = "name:" + CFServiceName
                }).Result;

                if (servicesList.Count() > 1)
                {
                    logger.LogError("There are more services named {0} in space {1}", CFServiceName, CFSpace);
                    return(false);
                }

                client.ServiceInstances.DeleteServiceInstance(new Guid(servicesList.First().EntityMetadata.Guid)).Wait();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #20
0
        private static void AutoRenewLeaseOnBlob(AzureBlobLease instance, Microsoft.Build.Utilities.TaskLoggingHelper log)
        {
            TimeSpan          maxWait = TimeSpan.FromSeconds(s_MaxWaitDefault);
            TimeSpan          delay   = TimeSpan.FromMilliseconds(s_DelayDefault);
            TimeSpan          waitFor = maxWait;
            CancellationToken token   = instance._cancellationTokenSource.Token;

            while (true)
            {
                token.ThrowIfCancellationRequested();

                try
                {
                    log.LogMessage(MessageImportance.Low, $"Requesting lease for container/blob '{instance._containerName}/{instance._blobName}'.");
                    using (HttpClient client = new HttpClient())
                    {
                        Tuple <string, string>         leaseAction       = new Tuple <string, string>("x-ms-lease-action", "renew");
                        Tuple <string, string>         headerLeaseId     = new Tuple <string, string>("x-ms-lease-id", instance._leaseId);
                        List <Tuple <string, string> > additionalHeaders = new List <Tuple <string, string> >()
                        {
                            leaseAction, headerLeaseId
                        };
                        var request = AzureHelper.RequestMessage("PUT", instance._leaseUrl, instance._accountName, instance._accountKey, additionalHeaders);
                        using (HttpResponseMessage response = AzureHelper.RequestWithRetry(log, client, request).GetAwaiter().GetResult())
                        {
                            if (!response.IsSuccessStatusCode)
                            {
                                throw new Exception("Unable to acquire lease.");
                            }
                        }
                    }
                    waitFor = maxWait;
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Rerying lease renewal on {instance._containerName}, {e.Message}");
                    waitFor = delay;
                }
                token.ThrowIfCancellationRequested();

                Task.Delay(waitFor, token).Wait();
            }
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            if (CFAppGuid.Length == 0)
            {
                logger.LogError("Application Guid must be specified");
                return false;
            }

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Binding routes to application {0}", CFAppGuid);
            foreach (string routeGuid in CFRouteGuids)
            {
                client.Apps.AssociateRouteWithApp(new Guid(CFAppGuid), new Guid(routeGuid)).Wait();
            }

            return true;
        }
Пример #22
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            if (CFAppGuid.Length == 0)
            {
                logger.LogError("Application guid must be specified");
                return(false);
            }

            try
            {
                CloudFoundryClient client = InitClient();

                UpdateAppRequest request = new UpdateAppRequest();

                request.Name      = CFAppName;
                request.Memory    = CFAppMemory;
                request.Instances = CFAppInstances;
                request.Buildpack = CFAppBuildpack;
                request.State     = CFAppState;

                if (CFEnvironmentJson != null)
                {
                    request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                }

                UpdateAppResponse response = client.Apps.UpdateApp(new Guid(CFAppGuid), request).Result;

                logger.LogMessage("Updated app {0} with guid {1}", response.Name, CFAppGuid);
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Binding services to app {0}", CFAppGuid);

            List<string> bindingGuids = new List<string>();

            foreach (string serviceGuid in CFServicesGuids)
            {
                CreateServiceBindingRequest request = new CreateServiceBindingRequest();
                request.AppGuid = new Guid(CFAppGuid);
                request.ServiceInstanceGuid = new Guid(serviceGuid);

                try
                {
                    var result = client.ServiceBindings.CreateServiceBinding(request).Result;
                    bindingGuids.Add(result.EntityMetadata.Guid);
                }
                catch (AggregateException ex)
                {
                    foreach (Exception e in ex.Flatten().InnerExceptions)
                    {
                        if (e is CloudFoundryException)
                        {
                            logger.LogWarning(e.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }

            CFBindingGuids = bindingGuids.ToArray();

            return true;
        }
Пример #24
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }
                List <ProvisionedService> servicesList = new List <ProvisionedService>();
                try
                {
                    string[] provServs = CFServices.Split(';');

                    foreach (string service in provServs)
                    {
                        if (string.IsNullOrWhiteSpace(service) == false)
                        {
                            string[] serviceInfo = service.Split(',');

                            if (serviceInfo.Length != 3)
                            {
                                logger.LogError("Invalid service information in {0}", service);
                                continue;
                            }

                            ProvisionedService serviceDetails = new ProvisionedService();

                            serviceDetails.Name = serviceInfo[0].Trim();
                            serviceDetails.Type = serviceInfo[1].Trim();
                            serviceDetails.Plan = serviceInfo[2].Trim();

                            servicesList.Add(serviceDetails);
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.LogErrorFromException(ex);
                    logger.LogWarning("Error trying to obtain service information, trying to deserialize as xml");
                    servicesList = Utils.Deserialize <List <ProvisionedService> >(CFServices);
                }

                List <string> serviceGuids = new List <string>();

                foreach (ProvisionedService service in servicesList)
                {
                    logger.LogMessage("Creating {0} service {1}", service.Type, service.Name);
                    Guid?planGuid = null;
                    PagedResponseCollection <ListAllServicesResponse> allServicesList = client.Services.ListAllServices(new RequestOptions()
                    {
                        Query = "label:" + service.Type
                    }).Result;

                    foreach (var serviceInfo in allServicesList)
                    {
                        var planList = client.Services.ListAllServicePlansForService(new Guid(serviceInfo.EntityMetadata.Guid)).Result;

                        var plan = planList.Where(o => o.Name == service.Plan).FirstOrDefault();

                        if (plan != null)
                        {
                            planGuid = new Guid(plan.EntityMetadata.Guid);
                            break;
                        }
                    }
                    Guid?serviceInstanceGuid = null;
                    if ((serviceInstanceGuid = Utils.CheckForExistingService(service.Name, planGuid, client)) != null)
                    {
                        logger.LogMessage("Service {0} - {1} already exists -> skipping", service.Name, service.Type);
                        serviceGuids.Add(serviceInstanceGuid.Value.ToString());
                        continue;
                    }

                    CreateServiceInstanceRequest request = new CreateServiceInstanceRequest();

                    request.Name            = service.Name;
                    request.ServicePlanGuid = planGuid;
                    request.SpaceGuid       = spaceGuid;

                    CreateServiceInstanceResponse result = client.ServiceInstances.CreateServiceInstance(request).Result;

                    serviceGuids.Add(result.EntityMetadata.Guid);
                }

                CFServicesGuids = serviceGuids.ToArray();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #25
0
        public bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Loading configuration from {0}", CFConfigurationFile);
            try
            {
                Configuration = Utils.DeserializeFromFile(CFConfigurationFile);
                CFStack = Configuration.Stack;
                CFAppName = Configuration.Name;
                CFAppPath = Configuration.AppDir;

                List<string> urlList = new List<string>();
                foreach (var app in Configuration.Applications)
                {
                    if (app.Value.Url.Contains(";"))
                    {
                        string[] appurls = app.Value.Url.Split(';');
                        urlList.AddRange(appurls);
                    }
                    else
                    {
                        urlList.Add(app.Value.Url);
                    }
                }
                foreach (string s in urlList)
                {
                    logger.LogMessage("Loaded url {0}", s);
                }

                CFRoutes = string.Join(";",urlList);

                CFAppMemory = Configuration.Memory;
                CFAppInstances = Configuration.Instances;
                CFAutoscale = Utils.Serialize<Autoscale>(Configuration.AutoscaleInfo);
                CFDisk = Configuration.Disk;

                if (Configuration.Services != null)
                {
                    List<ProvisionedService> servicesList = new List<ProvisionedService>();
                    foreach (var service in Configuration.Services)
                    {
                        servicesList.Add(new ProvisionedService() { Name = service.Key, Plan = service.Value.Plan, Type = service.Value.Type });
                    }

                    CFServices = Utils.Serialize<List<ProvisionedService>>(servicesList);
                }
                CFPlacementZone = Configuration.PlacementZone;
                CFSsoEnabled = Configuration.SsoEnabled;

                logger.LogMessage("Configuration loaded");
            }
            catch (Exception ex)
            {
                logger.LogErrorFromException(ex);
                throw;
            }

            return true;
        }
Пример #26
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Unbinding service {0} from app {1}", CFServiceName, CFAppName);

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }


                var servicesList = client.Spaces.ListAllServiceInstancesForSpace(spaceGuid, new RequestOptions()
                {
                    Query = "name:" + CFServiceName
                }).Result;

                if (servicesList.Count() > 1)
                {
                    logger.LogError("There are more services named {0} in space {1}", CFServiceName, CFSpace);
                    return(false);
                }

                Guid serviceGuid = new Guid(servicesList.FirstOrDefault().EntityMetadata.Guid);

                PagedResponseCollection <ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                {
                    Query = "name:" + CFAppName
                }).Result;
                if (appList.Count() > 1)
                {
                    logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                    return(false);
                }

                Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);


                var bindingsList = client.Apps.ListAllServiceBindingsForApp(appGuid).Result;

                foreach (var bind in bindingsList)
                {
                    if (bind.ServiceInstanceGuid.Value == serviceGuid)
                    {
                        client.Apps.RemoveServiceBindingFromApp(appGuid, new Guid(bind.EntityMetadata.Guid)).Wait();
                    }
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #27
0
        public static ConfigProcessor Create(bool autoBundles, string projectPath, string packagePath, string entryPointOverride, List <string> filePaths, Encoding encoding, Microsoft.Build.Utilities.TaskLoggingHelper Log, Microsoft.Build.Framework.MessageImportance importance)
        {
            if (autoBundles)
            {
                return(new AutoBundleConfigProcessor(projectPath, packagePath, entryPointOverride, filePaths, encoding, Log, importance));
            }

            return(new SimpleBundleConfigProcessor(projectPath, packagePath, entryPointOverride, filePaths));
        }
Пример #28
0
        public bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Loading configuration from {0}", CFConfigurationFile);
            try
            {
                Configuration = Utils.DeserializeFromFile(CFConfigurationFile);
                CFStack       = Configuration.Stack;
                CFAppName     = Configuration.Name;
                CFAppPath     = Configuration.AppDir;

                List <string> urlList = new List <string>();
                foreach (var app in Configuration.Applications)
                {
                    if (app.Value.Url.Contains(";"))
                    {
                        string[] appurls = app.Value.Url.Split(';');
                        urlList.AddRange(appurls);
                    }
                    else
                    {
                        urlList.Add(app.Value.Url);
                    }
                }
                foreach (string s in urlList)
                {
                    logger.LogMessage("Loaded url {0}", s);
                }

                CFRoutes = string.Join(";", urlList);

                CFAppMemory    = Configuration.Memory;
                CFAppInstances = Configuration.Instances;
                CFAutoscale    = Utils.Serialize <Autoscale>(Configuration.AutoscaleInfo);
                CFDisk         = Configuration.Disk;

                if (Configuration.Services != null)
                {
                    List <ProvisionedService> servicesList = new List <ProvisionedService>();
                    foreach (var service in Configuration.Services)
                    {
                        servicesList.Add(new ProvisionedService()
                        {
                            Name = service.Key, Plan = service.Value.Plan, Type = service.Value.Type
                        });
                    }

                    CFServices = Utils.Serialize <List <ProvisionedService> >(servicesList);
                }
                CFPlacementZone = Configuration.PlacementZone;
                CFSsoEnabled    = Configuration.SsoEnabled;

                logger.LogMessage("Configuration loaded");
            }
            catch (Exception ex)
            {
                logger.LogErrorFromException(ex);
                throw;
            }

            return(true);
        }
Пример #29
0
        internal static bool RunWixTool(string toolName, string arguments, string workingDirectory, string wixToolsPath, TaskLoggingHelper log)
        {
            if (wixToolsPath == null)
            {
                log.LogError("WixToolsPath must be defined to run WiX tooling. Wixpacks are used to produce signed msi's during post-build signing. If this repository is using in-build signing, remove '*.wixpack.zip' from ItemsToSign.");
                return(false);
            }

            if (!Directory.Exists(wixToolsPath))
            {
                log.LogError($"WixToolsPath '{wixToolsPath}' not found.");
                return(false);
            }

            if (!Directory.Exists(workingDirectory))
            {
                Directory.CreateDirectory(workingDirectory);
            }

            var processStartInfo = new ProcessStartInfo()
            {
                FileName               = "cmd.exe",
                UseShellExecute        = false,
                Arguments              = $"/c {toolName} {arguments}",
                WorkingDirectory       = workingDirectory,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            string path = processStartInfo.EnvironmentVariables["PATH"];

            path = $"{path};{wixToolsPath}";
            processStartInfo.EnvironmentVariables.Remove("PATH");
            processStartInfo.EnvironmentVariables.Add("PATH", path);

            var process = Process.Start(processStartInfo);

            process.WaitForExit();
            return(process.ExitCode == 0);
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            logger.LogMessage("Deleting application {0} from space {1}", CFAppName, CFSpace);

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }

            PagedResponseCollection<ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFAppName }).Result;
            if (appList.Count() > 1)
            {
                logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                return false;
            }

            Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);

            if (CFDeleteRoutes == true)
            {
                logger.LogMessage("Deleting routes associated with {0}", CFAppName);
                var routeList = client.Apps.ListAllRoutesForApp(appGuid).Result;
                foreach (var route in routeList)
                {
                    client.Routes.DeleteRoute(new Guid(route.EntityMetadata.Guid)).Wait();
                }
            }

            if (CFDeleteServices == true)
            {
                logger.LogMessage("Deleting services bound to {0}", CFAppName);

                var serviceBindingList = client.Apps.ListAllServiceBindingsForApp(appGuid).Result;

                foreach (var serviceBind in serviceBindingList)
                {
                    client.ServiceBindings.DeleteServiceBinding(new Guid(serviceBind.EntityMetadata.Guid)).Wait();
                    try
                    {
                        client.ServiceInstances.DeleteServiceInstance(serviceBind.ServiceInstanceGuid).Wait();
                    }
                    catch (AggregateException ex)
                    {
                        foreach (Exception e in ex.Flatten().InnerExceptions)
                        {
                            if (e is CloudFoundryException)
                            {
                                logger.LogWarning(e.Message);
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                }
            }

            client.Apps.DeleteApp(appGuid).Wait();

            return true;
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {

                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);

                if (spaceGuid == null)
                {
                    return false;
                }
            }

            List<string> createdGuid = new List<string>();
            PagedResponseCollection<ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;

            if (spaceGuid.HasValue)
            {
                foreach (String Route in CFRoutes)
                {
                    if (Route.Contains(';'))
                    {
                        foreach (var url in Route.Split(';'))
                        {
                            logger.LogMessage("Creating route {0}", url);
                            string domain = string.Empty;
                            string host = string.Empty;
                            Utils.ExtractDomainAndHost(url, out domain, out host);

                            if (domain.Length == 0 || host.Length == 0)
                            {
                                logger.LogError("Error extracting domain and host information from route {0}", url);
                                continue;
                            }

                            ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                            if (domainInfo == null)
                            {
                                logger.LogError("Domain {0} not found", domain);
                                continue;
                            }

                            CreateRoute(client, spaceGuid, createdGuid, host, domainInfo);
                        }
                    }
                    else
                    {
                        string domain = string.Empty;
                        string host = string.Empty;
                        Utils.ExtractDomainAndHost(Route, out domain, out host);

                        if (domain.Length == 0 || host.Length == 0)
                        {
                            logger.LogError("Error extracting domain and host information from route {0}", Route);
                            continue;
                        }
                        ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                        if (domainInfo == null)
                        {
                            logger.LogError("Domain {0} not found", domain);
                            continue;
                        }
                        CreateRoute(client, spaceGuid, createdGuid, host, domainInfo);
                    }
                }
                CFRouteGuids = createdGuid.ToArray();
            }
            else
            {
                logger.LogError("Space {0} not found", CFSpace);
                return false;
            }

            return true;
        }
Пример #32
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Deleting application {0} from space {1}", CFAppName, CFSpace);

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                PagedResponseCollection <ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                {
                    Query = "name:" + CFAppName
                }).Result;
                if (appList.Count() > 1)
                {
                    logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                    return(false);
                }

                Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);

                if (CFDeleteRoutes == true)
                {
                    logger.LogMessage("Deleting routes associated with {0}", CFAppName);
                    var routeList = client.Apps.ListAllRoutesForApp(appGuid).Result;
                    foreach (var route in routeList)
                    {
                        client.Routes.DeleteRoute(new Guid(route.EntityMetadata.Guid)).Wait();
                    }
                }

                if (CFDeleteServices == true)
                {
                    logger.LogMessage("Deleting services bound to {0}", CFAppName);

                    var serviceBindingList = client.Apps.ListAllServiceBindingsForApp(appGuid).Result;

                    foreach (var serviceBind in serviceBindingList)
                    {
                        client.ServiceBindings.DeleteServiceBinding(new Guid(serviceBind.EntityMetadata.Guid)).Wait();
                        try
                        {
                            client.ServiceInstances.DeleteServiceInstance(serviceBind.ServiceInstanceGuid).Wait();
                        }
                        catch (AggregateException ex)
                        {
                            foreach (Exception e in ex.Flatten().InnerExceptions)
                            {
                                if (e is CloudFoundryException)
                                {
                                    logger.LogWarning(e.Message);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }

                client.Apps.DeleteApp(appGuid).Wait();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #33
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                logger.LogMessage("Unbinding route {0} from app {1}", CFRoute, CFAppName);

                string domain = string.Empty;
                string host   = string.Empty;
                Utils.ExtractDomainAndHost(CFRoute, out domain, out host);

                if (domain.Length == 0 || host.Length == 0)
                {
                    logger.LogError("Error extracting domain and host information from route {0}", CFRoute);
                    return(false);
                }

                PagedResponseCollection <ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;
                ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                PagedResponseCollection <ListAllAppsForSpaceResponse> appList = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                {
                    Query = "name:" + CFAppName
                }).Result;
                if (appList.Count() > 1)
                {
                    logger.LogError("There are more applications named {0} in space {1}", CFAppName, CFSpace);
                    return(false);
                }

                Guid appGuid = new Guid(appList.FirstOrDefault().EntityMetadata.Guid);

                PagedResponseCollection <ListAllRoutesForAppResponse> routeList = client.Apps.ListAllRoutesForApp(appGuid).Result;

                ListAllRoutesForAppResponse routeInfo = routeList.Where(o => o.Host == host && o.DomainGuid == new Guid(domainInfo.EntityMetadata.Guid)).FirstOrDefault();

                if (routeInfo == null)
                {
                    logger.LogError("Route {0} not found in {1}'s routes", CFRoute, CFAppName);
                    return(false);
                }

                client.Routes.RemoveAppFromRoute(new Guid(routeInfo.EntityMetadata.Guid), appGuid).Wait();
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            CloudFoundryClient client = InitClient();

            Guid? spaceGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }
            List<ProvisionedService> servicesList = new List<ProvisionedService>();
            try
            {
               string[] provServs = CFServices.Split(';');

               foreach (string service in provServs)
               {
                   if (string.IsNullOrWhiteSpace(service) == false)
                   {
                       string[] serviceInfo = service.Split(',');

                       if (serviceInfo.Length != 3)
                       {
                           logger.LogError("Invalid service information in {0}", service);
                           continue;
                       }

                       ProvisionedService serviceDetails = new ProvisionedService();

                       serviceDetails.Name = serviceInfo[0].Trim();
                       serviceDetails.Type = serviceInfo[1].Trim();
                       serviceDetails.Plan = serviceInfo[2].Trim();

                       servicesList.Add(serviceDetails);
                   }
               }
            }
            catch(Exception ex)
            {
                logger.LogErrorFromException(ex);
                logger.LogWarning("Error trying to obtain service information, trying to deserialize as xml");
                servicesList = Utils.Deserialize<List<ProvisionedService>>(CFServices);
            }

            List<string> serviceGuids = new List<string>();

            foreach (ProvisionedService service in servicesList)
            {
                logger.LogMessage("Creating {0} service {1}", service.Type, service.Name);
                Guid? planGuid = null;
                PagedResponseCollection<ListAllServicesResponse> allServicesList = client.Services.ListAllServices(new RequestOptions() { Query = "label:" + service.Type }).Result;

                foreach (var serviceInfo in allServicesList)
                {
                    var planList = client.Services.ListAllServicePlansForService(new Guid(serviceInfo.EntityMetadata.Guid)).Result;

                    var plan = planList.Where(o => o.Name == service.Plan).FirstOrDefault();

                    if (plan != null)
                    {
                        planGuid = new Guid(plan.EntityMetadata.Guid);
                        break;
                    }
                }
                Guid? serviceInstanceGuid=null;
                if ((serviceInstanceGuid=Utils.CheckForExistingService(service.Name, planGuid, client)) != null)
                {
                    logger.LogMessage("Service {0} - {1} already exists -> skipping", service.Name, service.Type);
                    serviceGuids.Add(serviceInstanceGuid.Value.ToString());
                    continue;
                }

                CreateServiceInstanceRequest request = new CreateServiceInstanceRequest();

                request.Name = service.Name;
                request.ServicePlanGuid = planGuid;
                request.SpaceGuid = spaceGuid;

                CreateServiceInstanceResponse result = client.ServiceInstances.CreateServiceInstance(request).Result;

                serviceGuids.Add(result.EntityMetadata.Guid);
            }

            CFServicesGuids = serviceGuids.ToArray();

            return true;
        }
Пример #35
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);

                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                List <string> createdGuid = new List <string>();
                PagedResponseCollection <ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;

                if (spaceGuid.HasValue)
                {
                    foreach (String Route in CFRoutes)
                    {
                        if (Route.Contains(';'))
                        {
                            foreach (var url in Route.Split(';'))
                            {
                                logger.LogMessage("Creating route {0}", url);
                                string domain = string.Empty;
                                string host   = string.Empty;
                                Utils.ExtractDomainAndHost(url, out domain, out host);

                                if (domain.Length == 0 || host.Length == 0)
                                {
                                    logger.LogError("Error extracting domain and host information from route {0}", url);
                                    continue;
                                }

                                ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                                if (domainInfo == null)
                                {
                                    logger.LogError("Domain {0} not found", domain);
                                    continue;
                                }

                                CreateRoute(client, spaceGuid, createdGuid, host, domainInfo);
                            }
                        }
                        else
                        {
                            string domain = string.Empty;
                            string host   = string.Empty;
                            Utils.ExtractDomainAndHost(Route, out domain, out host);

                            if (domain.Length == 0 || host.Length == 0)
                            {
                                logger.LogError("Error extracting domain and host information from route {0}", Route);
                                continue;
                            }
                            ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name == domain).FirstOrDefault();

                            if (domainInfo == null)
                            {
                                logger.LogError("Domain {0} not found", domain);
                                continue;
                            }
                            CreateRoute(client, spaceGuid, createdGuid, host, domainInfo);
                        }
                    }
                    CFRouteGuids = createdGuid.ToArray();
                }
                else
                {
                    logger.LogError("Space {0} not found", CFSpace);
                    return(false);
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #36
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            CloudFoundryClient client = InitClient();

            PagedResponseCollection<ListAllStacksResponse> stackList = client.Stacks.ListAllStacks().Result;

            var stackInfo = stackList.Where(o => o.Name == CFStack).FirstOrDefault();

            if (stackInfo == null)
            {
                logger.LogError("Stack {0} not found", CFStack);
                return false;
            }

            Guid? spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);

            if (spaceGuid.HasValue == false)
            {
                logger.LogError("Invalid space and organization");
                return false;
            }

            PagedResponseCollection<ListAllDomainsDeprecatedResponse> domainInfoList = client.DomainsDeprecated.ListAllDomainsDeprecated().Result;

            foreach (String Route in CFRoutes)
            {
                foreach (var url in Route.Split(';'))
                {
                    logger.LogMessage("Validating route {0}", url);
                    string domain = string.Empty;
                    string host = string.Empty;
                    Utils.ExtractDomainAndHost(url, out domain, out host);

                    if (domain.Length == 0 || host.Length == 0)
                    {
                        logger.LogError("Error extracting domain and host information from route {0}", url);
                        continue;
                    }

                    ListAllDomainsDeprecatedResponse domainInfo = domainInfoList.Where(o => o.Name.ToUpperInvariant() == domain.ToUpperInvariant()).FirstOrDefault();

                    if (domainInfo == null)
                    {
                        logger.LogError("Domain {0} not found", domain);
                        return false;
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(CFServices) == false)
            {
                if (ValidateServices(client, CFServices) == false)
                {
                    logger.LogError("Error validating services");
                    return false;
                }
            }

            return true;
        }
Пример #37
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                Guid?spaceGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);

                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                Guid?planGuid = null;
                PagedResponseCollection <ListAllServicesResponse> servicesList = client.Services.ListAllServices(new RequestOptions()
                {
                    Query = "label:" + CFServiceType
                }).Result;

                foreach (var service in servicesList)
                {
                    var planList = client.Services.ListAllServicePlansForService(new Guid(service.EntityMetadata.Guid)).Result;

                    var plan = planList.Where(o => o.Name == CFServicePlan).FirstOrDefault();

                    if (plan != null)
                    {
                        planGuid = new Guid(plan.EntityMetadata.Guid);
                        break;
                    }
                }

                CreateServiceInstanceRequest request = new CreateServiceInstanceRequest();

                request.Name            = CFServiceName;
                request.ServicePlanGuid = planGuid;
                request.SpaceGuid       = spaceGuid;

                CreateServiceInstanceResponse result = client.ServiceInstances.CreateServiceInstance(request).Result;

                CFServiceGuid = result.EntityMetadata.Guid;

                logger.LogMessage("Created {0} service {1}", CFServiceType, result.Name);
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            CloudFoundryClient client = InitClient();

            Guid? spaceGuid = null;
            Guid? stackGuid = null;

            if (CFSpace.Length > 0 && CFOrganization.Length > 0)
            {
                spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                if (spaceGuid == null)
                {
                    return false;
                }
            }

            if (CFStack.Length > 0)
            {
                PagedResponseCollection<ListAllStacksResponse> stackList = client.Stacks.ListAllStacks().Result;

                var stackInfo = stackList.Where(o => o.Name == CFStack).FirstOrDefault();

                if (stackInfo == null)
                {
                    logger.LogError("Stack {0} not found", CFStack);
                    return false;
                }
                stackGuid = new Guid(stackInfo.EntityMetadata.Guid);
            }

            if (stackGuid.HasValue && spaceGuid.HasValue)
            {
                PagedResponseCollection<ListAllAppsForSpaceResponse> apps = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions() { Query = "name:" + CFAppName }).Result;

                if (apps.Count() > 0)
                {
                    CFAppGuid = apps.FirstOrDefault().EntityMetadata.Guid;

                    UpdateAppRequest request = new UpdateAppRequest();
                    request.SpaceGuid = spaceGuid;
                    request.StackGuid = stackGuid;

                    if (CFEnvironmentJson != null)
                    {
                        request.EnvironmentJson = JsonConvert.DeserializeObject<Dictionary<string,string>>(CFEnvironmentJson);
                    }

                    if (CFAppMemory > 0)
                    {
                        request.Memory = CFAppMemory;
                    }
                    if (CFAppInstances > 0)
                    {
                        request.Instances = CFAppInstances;
                    }
                    if (CFAppBuildpack != null)
                    {
                        request.Buildpack = CFAppBuildpack;
                    }

                    UpdateAppResponse response = client.Apps.UpdateApp(new Guid(CFAppGuid), request).Result;
                    logger.LogMessage("Updated app {0} with guid {1}", response.Name, response.EntityMetadata.Guid);
                }
                else
                {

                    CreateAppRequest request = new CreateAppRequest();
                    request.Name = CFAppName;
                    request.SpaceGuid = spaceGuid;
                    request.StackGuid = stackGuid;

                    if(CFEnvironmentJson !=null){
                        request.EnvironmentJson = JsonConvert.DeserializeObject<Dictionary<string,string>>(CFEnvironmentJson);
                    }

                    if (CFAppMemory > 0)
                    {
                        request.Memory = CFAppMemory;
                    }
                    if (CFAppInstances > 0)
                    {
                        request.Instances = CFAppInstances;
                    }
                    if (CFAppBuildpack != null)
                    {
                        request.Buildpack = CFAppBuildpack;
                    }

                    CreateAppResponse response = client.Apps.CreateApp(request).Result;
                    CFAppGuid = response.EntityMetadata.Guid;
                    logger.LogMessage("Created app {0} with guid {1}", CFAppName, CFAppGuid);
                }
            }

            return true;
        }
Пример #39
0
        /// <summary>
        /// Sanity check the certificates that are attached to the various items. Ensure we aren't using, say, a VSIX
        /// certificate on a DLL for example.
        /// </summary>
        private void VerifyCertificates(TaskLoggingHelper log)
        {
            foreach (var fileName in _batchData.FilesToSign.OrderBy(x => x.FullPath))
            {
                bool isVsixCert = (!string.IsNullOrEmpty(fileName.SignInfo.Certificate) && IsVsixCertificate(fileName.SignInfo.Certificate)) ||
                                  fileName.SignInfo.IsAlreadySigned && fileName.HasSignableParts;

                bool isInvalidEmptyCertificate = fileName.SignInfo.Certificate == null && !fileName.HasSignableParts && !fileName.SignInfo.IsAlreadySigned;

                if (fileName.IsPEFile())
                {
                    if (isVsixCert)
                    {
                        log.LogError($"Assembly {fileName} cannot be signed with a VSIX certificate");
                    }
                }
                else if (fileName.IsVsix())
                {
                    if (!isVsixCert)
                    {
                        log.LogError($"VSIX {fileName} must be signed with a VSIX certificate");
                    }

                    if (fileName.SignInfo.StrongName != null)
                    {
                        log.LogError($"VSIX {fileName} cannot be strong name signed.");
                    }
                }
                else if (fileName.IsNupkg())
                {
                    if (isInvalidEmptyCertificate)
                    {
                        log.LogError($"Nupkg {fileName} should have a certificate name.");
                    }

                    if (fileName.SignInfo.StrongName != null)
                    {
                        log.LogError($"Nupkg {fileName} cannot be strong name signed.");
                    }
                }
                else if (fileName.IsZip())
                {
                    if (fileName.SignInfo.Certificate != null)
                    {
                        log.LogError($"Zip {fileName} should not be signed with this certificate: {fileName.SignInfo.Certificate}");
                    }

                    if (fileName.SignInfo.StrongName != null)
                    {
                        log.LogError($"Zip {fileName} cannot be strong name signed.");
                    }
                }
                if (fileName.IsExecutableWixContainer())
                {
                    if (isInvalidEmptyCertificate)
                    {
                        log.LogError($"Wix file {fileName} should have a certificate name.");
                    }

                    if (fileName.SignInfo.StrongName != null)
                    {
                        log.LogError($"Wix file {fileName} cannot be strong name signed.");
                    }
                }
            }
        }
Пример #40
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Restarting application {0}", CFAppGuid);

            try
            {
                if (CFAppGuid.Length == 0)
                {
                    logger.LogError("Application Guid must be specified");
                    return(false);
                }

                CloudFoundryClient client = InitClient();


                // ======= HOOKUP LOGGING =======
                // TODO: detect logyard vs loggregator

                GetV1InfoResponse v1Info = client.Info.GetV1Info().Result;

                using (LogyardLog logyard = new LogyardLog(new Uri(v1Info.AppLogEndpoint), string.Format(CultureInfo.InvariantCulture, "bearer {0}", client.AuthorizationToken), null, CFSkipSslValidation))
                {
                    logyard.ErrorReceived += (sender, error) =>
                    {
                        logger.LogErrorFromException(error.Error, true);
                    };

                    logyard.StreamOpened += (sender, args) =>
                    {
                        logger.LogMessage("Log stream opened.");
                    };

                    logyard.StreamClosed += (sender, args) =>
                    {
                        logger.LogMessage("Log stream closed.");
                    };

                    logyard.MessageReceived += (sender, message) =>
                    {
                        logger.LogMessage("[{0}] - {1}: {2}", message.Message.Value.Source, message.Message.Value.HumanTime, message.Message.Value.Text);
                    };

                    logyard.StartLogStream(CFAppGuid, 0, true);


                    GetAppSummaryResponse response = client.Apps.GetAppSummary(new Guid(CFAppGuid)).Result;

                    if (response.State != "STOPPED")
                    {
                        UpdateAppRequest stopReq = new UpdateAppRequest();
                        stopReq.State = "STOPPED";
                        client.Apps.UpdateApp(new Guid(CFAppGuid), stopReq).Wait();
                    }

                    UpdateAppRequest startReq = new UpdateAppRequest();
                    startReq.State = "STARTED";
                    client.Apps.UpdateApp(new Guid(CFAppGuid), startReq).Wait();

                    // ======= WAIT FOR APP TO COME ONLINE =======
                    while (true)
                    {
                        GetAppSummaryResponse appSummary = client.Apps.GetAppSummary(new Guid(CFAppGuid)).Result;

                        if (appSummary.RunningInstances > 0)
                        {
                            break;
                        }

                        if (appSummary.PackageState == "FAILED")
                        {
                            logger.LogError("App staging failed.");
                            return(false);
                        }
                        else if (appSummary.PackageState == "PENDING")
                        {
                            logger.LogMessage("App is staging ...");
                        }
                        else if (appSummary.PackageState == "STAGED")
                        {
                            logger.LogMessage("App staged, waiting for it to come online ...");
                        }

                        Thread.Sleep(3000);
                    }

                    logyard.StopLogStream();
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #41
0
        public override bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);

            try
            {
                CloudFoundryClient client = InitClient();

                Guid?spaceGuid = null;
                Guid?stackGuid = null;

                if (CFSpace.Length > 0 && CFOrganization.Length > 0)
                {
                    spaceGuid = Utils.GetSpaceGuid(client, logger, CFOrganization, CFSpace);
                    if (spaceGuid == null)
                    {
                        return(false);
                    }
                }

                if (CFStack.Length > 0)
                {
                    PagedResponseCollection <ListAllStacksResponse> stackList = client.Stacks.ListAllStacks().Result;

                    var stackInfo = stackList.Where(o => o.Name == CFStack).FirstOrDefault();

                    if (stackInfo == null)
                    {
                        logger.LogError("Stack {0} not found", CFStack);
                        return(false);
                    }
                    stackGuid = new Guid(stackInfo.EntityMetadata.Guid);
                }

                if (stackGuid.HasValue && spaceGuid.HasValue)
                {
                    PagedResponseCollection <ListAllAppsForSpaceResponse> apps = client.Spaces.ListAllAppsForSpace(spaceGuid, new RequestOptions()
                    {
                        Query = "name:" + CFAppName
                    }).Result;

                    if (apps.Count() > 0)
                    {
                        CFAppGuid = apps.FirstOrDefault().EntityMetadata.Guid;

                        UpdateAppRequest request = new UpdateAppRequest();
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        if (CFEnvironmentJson != null)
                        {
                            request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                        }

                        if (CFAppMemory > 0)
                        {
                            request.Memory = CFAppMemory;
                        }
                        if (CFAppInstances > 0)
                        {
                            request.Instances = CFAppInstances;
                        }
                        if (CFAppBuildpack != null)
                        {
                            request.Buildpack = CFAppBuildpack;
                        }

                        UpdateAppResponse response = client.Apps.UpdateApp(new Guid(CFAppGuid), request).Result;
                        logger.LogMessage("Updated app {0} with guid {1}", response.Name, response.EntityMetadata.Guid);
                    }
                    else
                    {
                        CreateAppRequest request = new CreateAppRequest();
                        request.Name      = CFAppName;
                        request.SpaceGuid = spaceGuid;
                        request.StackGuid = stackGuid;

                        if (CFEnvironmentJson != null)
                        {
                            request.EnvironmentJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(CFEnvironmentJson);
                        }

                        if (CFAppMemory > 0)
                        {
                            request.Memory = CFAppMemory;
                        }
                        if (CFAppInstances > 0)
                        {
                            request.Instances = CFAppInstances;
                        }
                        if (CFAppBuildpack != null)
                        {
                            request.Buildpack = CFAppBuildpack;
                        }

                        CreateAppResponse response = client.Apps.CreateApp(request).Result;
                        CFAppGuid = response.EntityMetadata.Guid;
                        logger.LogMessage("Created app {0} with guid {1}", CFAppName, CFAppGuid);
                    }
                }
            }
            catch (AggregateException exception)
            {
                List <string> messages = new List <string>();
                ErrorFormatter.FormatExceptionMessage(exception, messages);
                this.logger.LogError(string.Join(Environment.NewLine, messages));
                return(false);
            }

            return(true);
        }
Пример #42
0
        public bool Execute()
        {
            logger = new Microsoft.Build.Utilities.TaskLoggingHelper(this);
            logger.LogMessage("Saving configuration to {0}", CFConfigurationFile);

            PushProperties Configuration = new PushProperties();
            Configuration.AppDir = CFAppPath;
            Configuration.Applications = new Dictionary<string, AppDetails>();
            Configuration.Applications.Add(CFAppPath, new AppDetails() { Name = CFAppName, Url = CFRoute });
            Configuration.AutoscaleInfo = new Autoscale() { Cpu = new Cpu() { MaxCpu = CFMaxCpu, MinCpu = CFMinCpu }, Enabled = CFEnabled !=null ? CFEnabled: "no", InstancesInfo = new Instances() { MaxInstances = CFMaxInstances !=0 ? CFMaxInstances : 1, MinInstances = CFMinInstances != 0 ? CFMinInstances : 1 } };
            Configuration.Disk = CFDisk!=0 ? CFDisk : 1024;
            Configuration.Instances = CFInstancesNumber;
            Configuration.Memory = CFAppMemory;
            Configuration.Name = CFAppName;
            Configuration.PlacementZone = CFPlacementZone !=null ? CFPlacementZone : "default";
            if (CFServiceName != null)
            {
                Configuration.Services = new Dictionary<string, ServiceDetails>();
                Configuration.Services.Add(CFServiceName, new ServiceDetails() { Plan = CFServicePlan, Type = CFServiceType });
            }

            Configuration.SsoEnabled = CFSsoEnabled!=null ? CFSsoEnabled : "no";
            Configuration.Stack = CFStack;

            Utils.SerializeToFile(Configuration, CFConfigurationFile);

            return true;
        }