Example #1
0
        private async Task <string> AcquireLeaseOnBlobAsync()
        {
            _log.LogMessage(MessageImportance.Low, $"Requesting lease for container/blob '{_containerName}/{_blobName}'.");
            string leaseId = string.Empty;

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    Tuple <string, string>         leaseAction       = new Tuple <string, string>("x-ms-lease-action", "acquire");
                    Tuple <string, string>         leaseDuration     = new Tuple <string, string>("x-ms-lease-duration", "60" /* seconds */);
                    List <Tuple <string, string> > additionalHeaders = new List <Tuple <string, string> >()
                    {
                        leaseAction, leaseDuration
                    };
                    var request = Utility.AzureHelper.RequestMessage("PUT", _leaseUrl, _accountName, _accountKey, additionalHeaders);
                    using (HttpResponseMessage response = await Utility.AzureHelper.RequestWithRetry(_log, client, request))
                    {
                        leaseId = response.Headers.GetValues("x-ms-lease-id").FirstOrDefault();
                    }
                }
                catch (Exception e)
                {
                    _log.LogErrorFromException(e, true);
                }
            }

            return(leaseId);
        }
Example #2
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);
        }
        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;
        }
Example #4
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);
        }
        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;
        }
Example #6
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);
        }